skip to Main Content

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


  1. Issue

    Your original code was incorrectly overwriting the hashMap[currentKey] value with [strs[i]] each iteration cycle. It’s like the hashMap[currentKey].push(strs[i]) just never happened.

    for(let i = 0; i < strs.length; i++) {
      const currentKey = strs[i].split('').sort().join('')
    
      if (hashMap[currentKey]) {
        // Push into hashMap[currentKey] array
        hashMap[currentKey].push(strs[i])
      }
    
      // Overwrite current hashMap[currentKey] value!!
      hashMap[currentKey] = [strs[i]]
    }
    

    Solution Explanation

    Using the else correctly either appends the next strs[i] value else creates the array with the first strs[i] value already populated.

    if (hashMap[currentKey]) {
      // Push strs[i] into existing array
      hashMap[currentKey].push(strs[i]);
    } else {
      // Create new array reference and place strs[i] as first element
      hashMap[currentKey] = [strs[i]];
    }
    

    Sometimes you’ll see a "negative" check first to create the array for the key, and then unconditionally pushing into the array.

    // No array value for key, create empty array
    if (!hashMap[currentKey]) {
      hashMap[currentKey] = [];
    }
    
    // Push current strs[i] into array
    hashMap[currentKey].push(strs[i]);
    
    Login or Signup to reply.
  2. 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.

    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('');
            hashMap[currentKey] ??= [];
            hashMap[currentKey].push(strs[i])
        }
    
        return Object.values(hashMap)
    };
    
    // shorter alternative using reduce, OR assignment and comma operator
    
    const groupAnagrams1 = strs => Object.values(
      strs.reduce((map, str) => (
        (map[[...str].sort().join('')] ||= []).push(str), map
      ), {})
    );
    
    console.log(groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"])); 
    console.log(groupAnagrams1(["eat", "tea", "tan", "ate", "nat", "bat"])); 
    console.log(groupAnagrams([""])); 
    console.log(groupAnagrams1([""])); 
    console.log(groupAnagrams(["a"])); 
    console.log(groupAnagrams1(["a"])); 

    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.

    Login or Signup to reply.
  3. 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 same currentKey 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 a for loop. When continue is used inside a for loop, the operations after the continue statement do not occur; it directly moves to the next iteration of the loop. So, you can use the code as follows:

    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])
              continue;
            }
    
            hashMap[currentKey] = [strs[i]]
        }
    
        return Object.values(hashMap)
    }
    

    Or, without using these structures, you can also achieve the desired outcome by modifying the if condition.

    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 (!Object.prototype.hasOwnProperty.call(hashMap,currentKey)) {
              hashMap[currentKey] = [];
          }
    
          hashMap[currentKey].push(strs[i])
      }
    
      return Object.values(hashMap)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search