The usual algorithm, in Swift 3, can't beat TLE


  • 0
    F

    I've written a solution in Swift 3, as follows:

    class Solution {
    	struct Pairs {
    		var hash = 0
    		var strings = [String]()
    	}
    
    	func groupAnagrams(_ strs: [String]) -> [[String]] {
    		var grams = [Pairs]()
    
    		for s in strs {
    			let hash = String(describing: s.unicodeScalars.sorted()).hashValue
    			if let ix = grams.index(where: {hash == $0.hash}) {
    				grams[ix].strings.append(s)
    			} else {
    				let g = Pairs(hash: hash, strings: [s])
    				grams.append(g)
    			}
    		}
    
    		let arr = grams.map{$0.strings}
    		return arr
    	}
    }
    

    Despite trying the utf8, utf16, and characters variations on unicodeScalars when computing the hash value, I can't get the run time to beat TLE. I suppose this might simply be a condemnation of string processing in Swift's comprehensive use of Unicode, but I more suspect I'm simply missing something important. Anyone have a good idea to suggest?


Log in to reply
 

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