KatInterview

807. Custom Sort String

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Counting Sort

This problem asks us to reorder a string s based on a custom alphabetical order defined by another string order. Characters in s that also appear in order must maintain their relative order as specified in order. Characters in s that do not appear in order can be placed anywhere, typically appended at the end.

Solution

Custom Sort String in Python

class Solution:
    def customSortString(self, order: str, s: str) -> str:
        # Use a frequency map (Counter) to store counts of characters in s.
        s_counts = {}
        for char in s:
            s_counts[char] = s_counts.get(char, 0) + 1

        result = []

        # First, build the part of the string with characters from 'order'.
        for char in order:
            if char in s_counts:
                # Append the character 'count' times.
                count = s_counts[char]
                result.append(char * count)
                # Remove the character from the map to mark it as processed.
                del s_counts[char]
        
        # Now, append the remaining characters from s that were not in 'order'.
        # s_counts now only contains these remaining characters.
        for char, count in s_counts.items():
            result.append(char * count)
            
        # Join the parts to form the final string.
        return "".join(result)

Custom Sort String in Java

class Solution {
    public String customSortString(String order, String s) {
        // Use an array of size 26 as a frequency map for characters 'a' through 'z'.
        int[] count = new int[26];

        // Count the frequency of each character in string s.
        for (char c : s.toCharArray()) {
            count[c - 'a']++;
        }

        StringBuilder result = new StringBuilder();

        // First, append characters to the result based on the custom order.
        for (char c : order.toCharArray()) {
            // While the character from 'order' still has a positive count.
            while (count[c - 'a'] > 0) {
                result.append(c);
                count[c - 'a']--;
            }
        }

        // Now, append the remaining characters that were in 's' but not in 'order'.
        // Their counts are still non-zero.
        for (char c = 'a'; c <= 'z'; c++) {
            while (count[c - 'a'] > 0) {
                result.append(c);
                count[c - 'a']--;
            }
        }

        return result.toString();
    }
}

Custom Sort String in C++

class Solution {
public:
    string customSortString(string order, string s) {
        // Use a vector of size 26 as a frequency map for characters 'a' through 'z'.
        vector<int> count(26, 0);

        // Count the frequency of each character in string s.
        for (char c : s) {
            count[c - 'a']++;
        }

        string result = "";
        // Reserve space to avoid multiple reallocations, improving performance.
        result.reserve(s.length());

        // First, append characters to the result based on the custom order.
        for (char c : order) {
            // If the character from 'order' exists in 's' (count > 0)
            if (count[c - 'a'] > 0) {
                // Append it to the result string 'count' times.
                result.append(count[c - 'a'], c);
                // Set its count to 0 to mark it as processed.
                count[c - 'a'] = 0;
            }
        }

        // Now, append the remaining characters that were in 's' but not in 'order'.
        // Their counts are still non-zero.
        for (char c = 'a'; c <= 'z'; ++c) {
            if (count[c - 'a'] > 0) {
                // Append the character 'count' times.
                result.append(count[c - 'a'], c);
            }
        }

        return result;
    }
};

Custom Sort String in TypeScript

function customSortString(order: string, s: string): string {
    // Use an array of size 26 as a frequency map for characters 'a' through 'z'.
    const counts: number[] = new Array(26).fill(0);
    const aCharCode = 'a'.charCodeAt(0);

    // Count the frequency of each character in string s.
    for (const char of s) {
        counts[char.charCodeAt(0) - aCharCode]++;
    }

    const result: string[] = [];

    // First, append characters to the result based on the custom order.
    for (const char of order) {
        const charCodeIndex = char.charCodeAt(0) - aCharCode;
        if (counts[charCodeIndex] > 0) {
            // Append the character 'count' times.
            result.push(char.repeat(counts[charCodeIndex]));
            // Set its count to 0 to mark it as processed.
            counts[charCodeIndex] = 0;
        }
    }

    // Now, append the remaining characters that were in 's' but not in 'order'.
    // Their counts are still non-zero.
    for (let i = 0; i < 26; i++) {
        if (counts[i] > 0) {
            const char = String.fromCharCode(aCharCode + i);
            result.push(char.repeat(counts[i]));
        }
    }

    return result.join('');
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.