I’m doing Leetcode Question Number 49..
I entered this but it did not work.
var groupAnagrams = function(strs) {
if (strs.length <= 1) {
return [strs]
}
const hashMap = {}
for(let i = 0; i < strs.length; i++) {
const currentKey = strs[i].split('').sort().join('')
if (hashMap[currentKey]) {
hashMap[currentKey].push(strs[i])
}
hashMap[currentKey] = [strs[i]]
}
return Object.values(hashMap)
};
Then I asked ChatGPT and it asked me to put it in an else statement
var groupAnagrams = function(strs) {
if (strs.length <= 1) {
return [strs]
}
const hashMap = {}
for(let i = 0; i < strs.length; i++) {
const currentKey = strs[i].split('').sort().join('')
if (hashMap[currentKey]) {
hashMap[currentKey].push(strs[i])
} else {
hashMap[currentKey] = [strs[i]]
}
}
return Object.values(hashMap)
};
It works, but I don’t get why/how it works. Why does it need to be in an else statement? Is it because I’m not returning anything? I thought the event loop will skip the command inside the if statement if the condition is not met?
3
Answers
Issue
Your original code was incorrectly overwriting the
hashMap[currentKey]
value with[strs[i]]
each iteration cycle. It’s like thehashMap[currentKey].push(strs[i])
just never happened.Solution Explanation
Using the
else
correctly either appends the nextstrs[i]
value else creates the array with the firststrs[i]
value already populated.Sometimes you’ll see a "negative" check first to create the array for the key, and then unconditionally pushing into the array.
Without the
else
you overwrite the array after the if, instead of adding to it.You can use the nullish coalescing assignment operator
??=
instead of the if and the missing else.Difference between
??=
and||=
||=
will assign a new value if the variable is any falsy value (like false, 0, "", null, or undefined),??=
will only assign a new value if the variable is null or undefined.The problem in your code is that you want to store and accumulate data inside the if statement if the
currentKey
variable exists within the hashmap. However, after the if statement ends, you are reassigning the samecurrentKey
variable from scratch and losing the stored data. There are many ways to prevent this, but the most common ones are using an if-else structure or utilizing the continue statement in afor
loop. When continue is used inside a for loop, the operations after thecontinue
statement do not occur; it directly moves to the next iteration of the loop. So, you can use the code as follows:Or, without using these structures, you can also achieve the desired outcome by modifying the if condition.