Concise JavaScript O(nk log k) using sorted keys


  • 0
    var groupAnagrams = function(strs) {
        const groups = {};
        for (let s of strs) {
            let key = s.split('').sort().join('');
            groups[key] = [...groups[key] || [], s];
        }
        return Object.values(groups);
    };
    

    And here is the unreadable one-liner:

    var groupAnagrams = function(strs) {
        return Object.values(strs.reduce((g, s, k) => (g[k = s.split('').sort().join('')] = [...g[k] || [], s], g), {}));
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.