Javascript Solution, but getting an error? Help appreciated!


  • 0
    P
    var groupAnagrams = function(strs) {
        var groupedAna = [];
        var anaChecker = [];
        
        for(var i = 0; i < strs.length; i++){
        	var sortedItem = strs[i].split('').sort((a,b)=>a<b).join('');
        	if(anaChecker.indexOf(sortedItem)!==-1){
        		var indexToPutInGroupedAna = anaChecker.indexOf(sortedItem)
        		groupedAna[indexToPutInGroupedAna].push(strs[i])
        	}
        	else{
        		anaChecker.push(sortedItem)	
        		groupedAna[anaChecker.indexOf(sortedItem)] = [strs[i]]
        	}
        }
        return groupedAna
    };
    

  • 0
    C

    Fixed couple of issues:
    #1 - Sort callback to include returns for less than and equals
    #2 - Mixing upper and lower case in the stringdidn't work - converted the string to lowercase
    #3 - Used ES6 for-of loop
    #4 - Used ES6 let where ever i could

    Tested in firefox developer edition latest and nodejs latest.

    var groupAnagrams = function (strs) {
      let groupedAna = []
      let anaChecker = []
      
      for (let str of strs) {
        let sortedItem = str.toLowerCase().split('').sort((a, b) => a > b ? 1 : a < b ? -1 : 0).join('');
        if (anaChecker.indexOf(sortedItem) !== - 1) {
          groupedAna[anaChecker.indexOf(sortedItem)].push(str)
        } 
        else {
          anaChecker.push(sortedItem)
          groupedAna[anaChecker.indexOf(sortedItem)] = [str]
        }
      } 
      return groupedAna
    };
    // client
    for (let value of groupAnagrams(['chan', 'keep', 'peek', 'arrigo Boito', 'tobia gorrio'])) {
      console.log(value)
    }
    

  • 0
    P

    @canjur Time still exceeds.

    the only change really you made is to make sure that lower/upper case was checked, besides doing some ES6 fixes which weren't super important.

    the algo exceeds the test's time limit and doesn't resolve the issue /:


Log in to reply
 

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