My Ruby Solution


  • 0
    T

    Time Complexity - O(n log n)
    Space Complexity - O(n)

    • n = length of s
    def frequency_sort(s)
      result = ""
      letter_freq = Hash.new { |h, k| h[k] = 0}
    
      s.each_char do |c|
        letter_freq[c] += 1
      end
    
      letters = letter_freq.keys.sort_by { |k| letter_freq[k] }.reverse
    
      letters.each do |letter|
        result += letter * letter_freq[letter]
      end
        
      result
    end
    

Log in to reply
 

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