Skip to content

Commit

Permalink
Update 0242-valid-anagram.js
Browse files Browse the repository at this point in the history
changing space complexity to O(1).
It's constant since we keep hashmap of the letters and their frequency, so the size of the hashmao will be the size of the alphabet -> size of 26.
  • Loading branch information
eliork authored May 9, 2023
1 parent b98ee99 commit a81c08d
Showing 1 changed file with 6 additions and 6 deletions.
12 changes: 6 additions & 6 deletions javascript/0242-valid-anagram.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const reorder = (str) => str

/**
* Hash Map - Frequency Counter
* Time O(N) | Space O(N)
* Time O(N) | Space O(1)
* https://leetcode.com/problems/valid-anagram/
* @param {string} s
* @param {string} t
Expand All @@ -30,8 +30,8 @@ var isAnagram = (s, t, map = new Map()) => {
const isEqual = s.length === t.length;
if (!isEqual) return false;

addFrequency(s, map); /* Time O(N) | Space O(N) */
subtractFrequency(t, map); /* Time O(N) | Space O(N) */
addFrequency(s, map); /* Time O(N) | Space O(1) */
subtractFrequency(t, map); /* Time O(N) | Space O(1) */

return checkFrequency(map);/* Time O(N) */
};
Expand All @@ -40,7 +40,7 @@ const addFrequency = (str, map) => {
for (const char of str) {/* Time O(N) */
const count = (map.get(char) || 0) + 1;

map.set(char, count); /* Space O(N) */
map.set(char, count); /* Space O(1) */
}
}

Expand All @@ -50,7 +50,7 @@ const subtractFrequency = (str, map) => {

const count = map.get(char) - 1;

map.set(char, count); /* Space O(N) */
map.set(char, count); /* Space O(1) */
}
};

Expand All @@ -61,4 +61,4 @@ const checkFrequency = (map) => {
}

return true;
}
}

0 comments on commit a81c08d

Please sign in to comment.