Skip to main content

Custom Sort String - Solution & Explanation

MediumHash TableStringSorting12 min readAsked at: Amazon, Microsoft, Meta +2
Practice this problem

Problem Statement

You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously.

Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string.

Return any permutation of s that satisfies this property.

 

Example 1:

Input: order = "cba", s = "abcd"

Output: "cbad"

Explanation: "a", "b", "c" appear in order, so the order of "a", "b", "c" should be "c", "b", and "a".

Since "d" does not appear in order, it can be at any position in the returned string. "dcba", "cdba", "cbda" are also valid outputs.

Example 2:

Input: order = "bcafg", s = "abcd"

Output: "bcad"

Explanation: The characters "b", "c", and "a" from order dictate the order for the characters in s. The character "d" in s does not appear in order, so its position is flexible.

Following the order of appearance in order, "b", "c", and "a" from s should be arranged as "b", "c", "a". "d" can be placed at any position since it's not in order. The output "bcad" correctly follows this rule. Other arrangements like "dbca" or "bcda" would also be valid, as long as "b", "c", "a" maintain their order.

 

Constraints:

  • 1 <= order.length <= 26
  • 1 <= s.length <= 200
  • order and s consist of lowercase English letters.
  • All the characters of order are unique.

Approach Overview

Problem Overview: You receive two strings: order and s. The characters in order define the required priority. Rearrange characters in s so they follow this custom order. Characters not present in order can appear anywhere after the ordered ones.

Approach 1: Counting Sort with Frequency Map (O(n + m) time, O(1) space)

This approach treats the problem like a constrained counting sort. First build a frequency table for characters in s using a simple array or hash table. Then iterate through each character in order and append it to the result as many times as its frequency indicates. After processing all characters in order, append the remaining characters from the frequency map that were not specified in the custom order.

The key insight is that you never need to compare characters directly. The custom order already defines the sequence. Counting occurrences lets you reconstruct the string in linear time. Because the alphabet size is fixed (typically 26 lowercase letters), the extra memory is constant. This method is essentially a specialized form of sorting optimized for character frequencies.

Approach 2: Sorting with Custom Comparator (O(n log n) time, O(n) space)

This approach leverages a standard sorting algorithm but modifies how characters are compared. First build a lookup table that maps each character in order to its index. Then convert the string s into a list and sort it using a custom comparator or key function. During comparison, characters with lower order indices come first. Characters not present in order can be assigned a default large index so they naturally move to the end.

This method uses built-in sorting utilities and keeps the implementation straightforward. The algorithm repeatedly compares characters using the custom ranking, which leads to O(n log n) time complexity. It relies on concepts from string manipulation and custom sorting logic. The approach is useful when adapting to problems where frequency counting is not feasible or when the ordering rule becomes more complex.

Recommended for interviews: The counting sort approach is the expected solution. It achieves linear time by avoiding comparisons and directly reconstructing the result using frequency counts. Interviewers often accept the comparator-based solution first since it demonstrates understanding of custom sorting, but the counting strategy shows stronger algorithmic optimization and awareness of fixed character constraints.

Approach 1: Counting Sort Approach

This approach involves counting the occurrence of each character in string s and then constructing the result string by iterating through characters in order, followed by any characters in s that do not appear in order. This ensures the output string follows the custom order defined.

The solution uses a frequency array to count occurrences of characters in string s. Next, it iterates through the custom order string order to construct part of the result by taking corresponding characters from s. Finally, any leftover characters from s are added to the result in their natural order.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n + m), where n is the length of s and m is the length of order, since we iterate through each character of both strings.
Space Complexity: O(1), only a fixed extra space for the frequency array is used.

Try this approach in the editor →

Approach 2: Sorting with Custom Comparator

This approach involves sorting the string s using a custom comparator function derived from the order string. You respect the sequence provided in order and sort the characters of s accordingly.

In this C++ solution, an unordered_map is used to assign indices as priorities based on order. The custom comparator used in the sort function rearranges s to fit these priorities.

Code

C++

Java

Python

JavaScript

Complexity

Time Complexity: O(n log n), due to the sorting operation.
Space Complexity: O(1) for map usage and additional space for sort function.

Try this approach in the editor →

Approach 3: Default Approach

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Counting Sort Approach

Time Complexity: O(n + m), where n is the length of s and m is the length of order, since we iterate through each character of both strings.
Space Complexity: O(1), only a fixed extra space for the frequency array is used.

Sorting with Custom Comparator

Time Complexity: O(n log n), due to the sorting operation.
Space Complexity: O(1) for map usage and additional space for sort function.

Default Approach—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Counting Sort with Frequency MapO(n + m)O(1)Best general solution when characters come from a limited alphabet
Sorting with Custom ComparatorO(n log n)O(n)Useful when relying on built-in sorting or when ordering rules are more flexible

Video Solution

CUSTOM SORT STRING | PYTHON | LEETCODE # 791 • Cracking FAANG • 9,074 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Custom Sort String easy or hard?
Custom Sort String is generally considered a medium difficulty problem. The challenge lies in recognizing that direct sorting is unnecessary and that a frequency counting strategy can produce a linear-time solution.
Custom Sort String Python/Java solution
Python and Java implementations typically use a frequency map or array to count characters. The algorithm then iterates through the order string to rebuild the result. Both languages can implement the counting approach in O(n) time with minimal extra memory.
How to solve Custom Sort String in O(n)?
Use a frequency array or hash map to count characters in s. Iterate through the order string and append characters based on their counts. Finally append any remaining characters not included in order. Each character is processed once, giving O(n + m) complexity.
What is the best approach for Custom Sort String?
The counting sort approach using a frequency map is the most efficient solution. Count occurrences of each character in the input string, then rebuild the result by iterating through the custom order string. This avoids comparisons and runs in linear time O(n + m).
Is Custom Sort String asked at Google/Amazon/Meta?
Custom ordering and frequency-based sorting problems commonly appear in interviews at companies like Amazon, Google, and Meta. Variations of this question test understanding of hash tables, counting techniques, and custom sorting logic.
What data structure is used in Custom Sort String?
A hash table or fixed-size frequency array is the main data structure used in the optimal solution. It stores the count of each character in the string and allows quick reconstruction according to the custom order.
What is the time complexity of Custom Sort String?
The optimal solution runs in O(n + m) time, where n is the length of string s and m is the length of the order string. The algorithm counts character frequencies and reconstructs the string according to the given order.

Ready to solve this problem?

Practice Custom Sort String with our built-in code editor and test cases.

Practice on FleetCode