DEV Community

codingpineapple
codingpineapple

Posted on • Edited on

LeetCode 49. Group Anagrams (javascript solution)

Description:

Given the root of a binary search tree, and an integer k, return the kth (1-indexed) smallest element in the tree.

Solution:

Time Complexity : O(n^2log(n))
Space Complexity: O(n^2)

var groupAnagrams = function(strs) {
    // define output array
    const output = []
    // define map
    const map = {}
    // loop through strs
    for(let i = 0; i < strs.length; i++) {
       // sort current str
        const strSorted = strs[i].split('').sort().join('')
        // if sorted string is present in map
        if(map[strSorted]!==undefined) {
           // get index of output array to push current str
            output[map[strSorted]].push(strs[i])
        } else {
             // push current str into output array
            output.push([strs[i]])
            // add sorted str to map
            // set map[sorted str] = output array length - 1 
            map[strSorted] = output.length-1
        }

    }

    // return output array
    return output 
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)