File tree 2 files changed +34
-2
lines changed
2 files changed +34
-2
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {string } s First string.
3
+ * @param {string } t Second string
4
+ * @return {boolean } Are strings anagrams of each other.
5
+ * @summary Valid Anagram {@link https://leetcode.com/problems/valid-anagram/solution/}
6
+ * @description Given two input strings return true if they are anagrams.
7
+ * Space O(1) - Always two arrays of 26 items.
8
+ * Time O(n) - Only loop two arrays if both strings are euqal length, hence 2 loops of n.
9
+ */
10
+ const isAnagram = ( s , t ) => {
11
+ if ( s . length !== t . length ) return false ;
12
+
13
+ const OFFSET = 'a' . charCodeAt ( ) ;
14
+ const ENGLISH_LETTERS_COUNT = 26 ;
15
+
16
+ const countsS = Array ( ENGLISH_LETTERS_COUNT ) ;
17
+ const countsT = Array ( ENGLISH_LETTERS_COUNT ) ;
18
+
19
+ for ( let i = 0 ; i < s . length ; i ++ ) {
20
+ const index = s [ i ] . charCodeAt ( ) - OFFSET ;
21
+
22
+ countsS [ index ] = countsS [ index ] ? countsS [ index ] + 1 : 1 ;
23
+ }
24
+
25
+ for ( let i = 0 ; i < t . length ; i ++ ) {
26
+ const index = t [ i ] . charCodeAt ( ) - OFFSET ;
27
+
28
+ countsT [ index ] = countsT [ index ] ? countsT [ index ] + 1 : 1 ;
29
+ }
30
+
31
+ return countsS . every ( ( count , index ) => count === countsT [ index ] ) ;
32
+ } ;
Original file line number Diff line number Diff line change 4
4
* @return {number[] } Array with indexes of all substrings that are anagrams of word.
5
5
* @summary Find All Anagrams in a String {@link https://leetcode.com/problems/find-all-anagrams-in-a-string/}
6
6
* @description Given two input strings return indexes of substrings that are anagrams of second input.
7
- * Space O(A+B ) - A length of string 'word', B length of string 'stream' .
8
- * Time O(1 ) - Two new arrays, each of 26 elements .
7
+ * Space O(1 ) - Two new arrays, each of 26 elements .
8
+ * Time O(A+B ) - A length of string 'word', B length of string 'stream' .
9
9
*/
10
10
const findAnagrams = ( stream , word ) => {
11
11
const counts = Array ( 26 ) ;
You can’t perform that action at this time.
0 commit comments