#791

Custom Sort String

Medium
Hash TableStringSortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a frequency count of characters in `s` and constructs the result string based on the order defined in `order`. This is efficient because it processes each character only a couple of times.

⚙️

Algorithm

4 steps
  1. 1Step 1: Count the frequency of each character in `s` using a HashMap.
  2. 2Step 2: Initialize an empty result string.
  3. 3Step 3: Append characters from `order` to the result string based on their frequency in `s`.
  4. 4Step 4: Append any remaining characters from `s` that are not in `order` to the result string.
solution.py12 lines
1from collections import Counter
2
3def customSortString(order, s):
4    count = Counter(s)
5    result = []
6    for char in order:
7        if char in count:
8            result.append(char * count[char])
9            del count[char]
10    for char in count:
11        result.append(char * count[char])
12    return ''.join(result)

Complexity note: The time complexity is O(n) because we traverse the string `s` to count characters and then again to build the result string. The space complexity is O(n) due to the storage of character frequencies.

  • 1Understanding character frequency is crucial for optimal solutions.
  • 2Using a HashMap allows for quick lookups and efficient counting.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.