LeetCode 451: Sort Characters By Frequency Solution

Master LeetCode problem 451 (Sort Characters By Frequency), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation

To solve this problem, we can follow these steps:

  1. Count the frequency of each character in the input string.
  2. Sort the characters based on their frequencies in descending order.
  3. Reconstruct the sorted string by appending the characters based on their frequencies.

Time complexity: O(n log n)
Space complexity: O(n)

Solution Code

import java.util.*;

class Solution {
    public String frequencySort(String s) {
        Map<Character, Integer> charFreq = new HashMap<>();
        for (char c : s.toCharArray()) {
            charFreq.put(c, charFreq.getOrDefault(c, 0) + 1);
        }
        
        List<Character> characters = new ArrayList<>(charFreq.keySet());
        Collections.sort(characters, (a, b) -> charFreq.get(b) - charFreq.get(a));
        
        StringBuilder sb = new StringBuilder();
        for (char c : characters) {
            int freq = charFreq.get(c);
            for (int i = 0; i < freq; i++) {
                sb.append(c);
            }
        }
        
        return sb.toString();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 451 (Sort Characters By Frequency)?

This page provides optimized solutions for LeetCode problem 451 (Sort Characters By Frequency) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 451 (Sort Characters By Frequency)?

The time complexity for LeetCode 451 (Sort Characters By Frequency) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 451 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 451 in Java, C++, or Python.

Back to LeetCode Solutions