-
Notifications
You must be signed in to change notification settings - Fork 0
/
freqCounterAnagram.js
67 lines (57 loc) · 2.05 KB
/
freqCounterAnagram.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
Given two strings, write a function to determine if the second string is an anagram of the first. An anagram is a word, phrase, or name formed by rearranging the letters of another, such as cinema, formed from iceman.
Note: You may assume the string contains only lowercase alphabets. Assume all inputs have no spaces, periods, or numbers; Not case sensitive
Examples
validAnagram('', '') // true
validAnagram('aaz', 'zza') // false
validAnagram('anagram', 'nagaram') // true
validAnagram("rat", "car") // false)
validAnagram('awesome', 'awesom') // false
validAnagram('qwerty', 'qeywrt') // true
validAnagram('texttwisttime', 'timetwisttext') // true
*/
//brute force
function validAnagram(first, second) {
if (first.length !== second.length){
return false
}
const obj = {}
for (let i = 0; i < first.length; i++) {
let letter = first[i] //stores currently looping letter in string 'first'
obj[letter] ? obj[letter] += 1 : obj[letter] = 1
}
//console.log(lookup)
for (let i = 0; i < second.length; i++) {
let letter = second[i];
if (!obj[letter]) {//can't find letter OR letter is 0, then not an anagram
return false
} else { // {z: 1, m: 0}
obj[letter] -= 1
}
}
return true
}
//refactored
function validAnagram(first, second){
if (first.length !== second.length) {
return false
}
const lookup = {} //frequency counter; constructing an object for comparison
for (let i = 0; i < second.length; i++){ //loop through the first string
let letter = first[i] //stores currently looping letter value in string 'first'
lookup[letter] ? lookup[letter] += 1 : lookup[letter] = 1;
//if letter exists, increment (else, set to 1)
//If letter exists in the lookup object? Plus 1 to the value (a: 1 -> a: 2)
//Or if letter does NOT exist? Initialize with 1 (a: 0 -> a: 1)
}
for (let i = 0; i < second.length; i++) {
let letter = second[i];
//can't find letter OR letter is zero..then its not an anagram
if (!lookup[letter]) { //checks if second[i] exists inside 'lookup' object
return false;
}else{
lookup[letter] -= 1
}
}
return true;
}