LeetCode 791: Custom Sort String Solution

Master LeetCode problem 791 (Custom Sort String), 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.

791. Custom Sort String

Problem Explanation

Explanation:

To solve this problem, we can first count the frequency of each character in string s. Then, we iterate through the characters in order and append the characters to the result string based on their frequency in s. Finally, we append the remaining characters from s to the result string.

Algorithm:

  1. Create a map to store the frequency of characters in string s.
  2. Iterate through the characters in order:
    • If the character exists in the map, append it to the result string that many times based on its frequency in s.
    • Remove the character from the map.
  3. Append the remaining characters in the map to the result string.
  4. Return the result string.

Time Complexity: O(n), where n is the length of string s. Space Complexity: O(1) since the map will contain at most 26 characters.

: :

Solution Code

class Solution {
    public String customSortString(String order, String s) {
        int[] count = new int[26];
        for (char ch : s.toCharArray()) {
            count[ch - 'a']++;
        }
        
        StringBuilder sb = new StringBuilder();
        for (char ch : order.toCharArray()) {
            while (count[ch - 'a'] > 0) {
                sb.append(ch);
                count[ch - 'a']--;
            }
        }
        
        for (char ch = 'a'; ch <= 'z'; ch++) {
            while (count[ch - 'a'] > 0) {
                sb.append(ch);
                count[ch - 'a']--;
            }
        }
        
        return sb.toString();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 791 (Custom Sort String)?

This page provides optimized solutions for LeetCode problem 791 (Custom Sort String) 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 791 (Custom Sort String)?

The time complexity for LeetCode 791 (Custom Sort String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 791 on DevExCode?

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

Back to LeetCode Solutions