ES6: O(n * log(n)) time, O(n) space


  • 0
    Y
    function getStringHistogram(string) {
      const histogram = new Map()
      for (const char of string) {
        histogram.set(char, (histogram.get(char) || 0) + 1)
      }
      return histogram
    }
    
    function frequencySort(string) {
      const histogram = getStringHistogram(string)
      const frequencySortedChars = Array.from(histogram.keys())
        .sort((p, q) => Number.parseInt(histogram.get(q)) - Number.parseInt(histogram.get(p)))
      const frequencySorted = []
      for (const char of frequencySortedChars) {
        frequencySorted.push(char.repeat(histogram.get(char)))
      }
      return frequencySorted.join('')
    }
    

Log in to reply
 

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