Problem 791

Abstract / Summary

Arrange characters of a string by first placing them in the order of another string then adding the rest in original order.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0791.py

class Solution:
    def customSortString(self, order: str, s: str) -> str:
        freq = defaultdict(int)
        for c in s:
            freq[c] += 1

        result = ""
        for c in order:
            result += c * freq[c]
            freq[c] = 0

        for c in freq:
            result += c * freq[c]

        return result
15 lines | 351 bytes | submitted October 9, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 72% (700k+ submissions).

Typical patterns to solve this problem:
  • Hash Table
  • Sorting
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single method customSortString. The method receives two strings: order, which specifies a desired relative ordering of characters, and s, the string to be reordered. The algorithm builds a frequency map of characters in s, then constructs the result by first emitting characters in the sequence defined by order and finally appending any characters that were not present in order. The approach is concise and leverages Python’s built-in string multiplication to efficiently generate repeated characters.

Key Steps

Building the frequency map

The first phase scans the input string s and records how many times each character appears. A defaultdict of integers is used so that missing keys default to zero, eliminating the need for explicit existence checks.

freq = defaultdict(int)
for c in s:
    freq[c] += 1

This loop runs once over s, guaranteeing that every character’s count is captured regardless of its position or duplication.

Emitting characters according to order

The second phase iterates over the characters in order. For each character, the algorithm appends that character repeated freq[c] times to the result string. After appending, the count for that character is set to zero, ensuring it will not be emitted again in the final pass.

result = ""
for c in order:
    result += c * freq[c]
    freq[c] = 0

Multiplying a single-character string by its frequency produces the required block of repeated characters in a single operation, which is more efficient than concatenating one character at a time.

Adding remaining characters

The final phase processes any characters that were present in s but not listed in order. Since their counts were never zeroed, they remain in the frequency map. The loop iterates over the dictionary’s keys and appends each character multiplied by its remaining count.

for c in freq:
    result += c * freq[c]

Because the dictionary only contains characters that appeared in s, this step automatically skips any characters absent from the original string.

Returning the assembled string

The method concludes by returning the fully constructed result.

return result

Edge Cases Handled

When order contains characters that never appear in s, the frequency lookup yields zero, and the multiplication produces an empty string, leaving the result unchanged for that character.

If s includes characters not listed in order, those characters retain their original counts after the second phase and are emitted in the third phase, preserving them in the output.

Both input strings may be empty. An empty s leads to an empty frequency map, and the loops produce no output, resulting in an empty string. An empty order bypasses the second phase entirely, causing the method to return s unchanged after the third phase.

Repeated characters in order are harmless because the frequency for a character is set to zero after its first occurrence, so subsequent repetitions contribute nothing to the result.

Performance Optimizations

The algorithm achieves linear time behavior by traversing each input string exactly once and iterating over the distinct characters in the frequency map a single additional time.

Using a defaultdict eliminates conditional checks for key existence, allowing the frequency update to be a single statement.

String multiplication (c * freq[c]) creates the required block of characters in one operation, which is faster than repeated concatenation inside a loop.

Zeroing the count after processing a character in order prevents the need for a separate data structure to track which characters have already been emitted, thereby reducing memory overhead.

The final concatenation steps build the result incrementally using the += operator on a Python string. While repeated += can be costly in some contexts, the use of large pre-multiplied substrings minimizes the number of concatenation operations, keeping the overhead low for typical input sizes.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big messy pile of letter blocks, and you want to put them in a special order to match a secret code.

First, you make a count of all the letters in the pile to see how many of each you have. You mark down how many A blocks, B blocks, and every other letter block you found.

Next, you look at the secret code order. You go through that order one letter at a time. Every time you see a letter in the code, you grab all the blocks of that color that you have in your pile and put them in a long line. Once you pull those blocks out, you cross that letter off your count list so you do not use them again.

After you finish following the secret code, you might still have some blocks left over that were not in the code at all. You just take those leftover blocks and stack them onto the end of your line. Now all the blocks are neatly lined up according to the rules.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.63 | σ = 0.87

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Rust Go TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fengvyi C++
gouthampradhan Java
halfrost Go
JoshCrozier JS
Krazune C++
lkwq007 Python
pruthvikp Python
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fengvyi C++
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
Krazune C++
lkwq007 Python
pruthvikp Python
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
YuriSpiridonov Python
zfang399 C++
36 links | 22 authors | 8 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

3 easy 7 medium 1 hard
12 solutions   October 9, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality