#791

Custom Sort String

Medium Counting by custom order

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

order lists some unique letters in a custom order. Rearrange s so that letters in order appear in that order; other letters can go anywhere.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: reorder s to follow the letter order in order.

Why this works: count letters of s, write them in order's sequence, then the rest.

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

c, b, a, then d → "cbad"

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using a comparator on Character objects with indexOf — slower and more code.

Solve on LeetCode ↗
Complexity
  • Time: O(|s| + |order|).
  • Space: O(26).
Topic: Sorting
🎬 Episodes 24–28: video coming soon