Sort a string by custom order
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This interview question evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer for Sort a string by custom order states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- Characters in P are distinct.
- S may contain repeated characters.
- Either P or S may be empty.
- If P is empty, return S unchanged.
- Characters of S not in P must preserve their original relative order.
Examples
Input: ("cba", "abcd")
Expected Output: "cbad"
Explanation: a,b,c are in P -> ordered c,b,a; d not in P -> last.
Input: ("bcafg", "abcd")
Expected Output: "bcad"
Explanation: P order b,c,a; d is not in P so it trails. f,g in P are absent from S and ignored.
Input: ("", "hello")
Expected Output: "hello"
Explanation: Empty priority string: no character is in P, so S is returned unchanged in original order.
Input: ("xyz", "")
Expected Output: ""
Explanation: Empty text string returns empty.
Input: ("ba", "aabbcc")
Expected Output: "bbaacc"
Explanation: Duplicates: b (x2) before a (x2) per P; c (x2) not in P keeps trailing order.
Input: ("kqep", "pekeq")
Expected Output: "kqeep"
Explanation: Counts k=1,q=1,e=2,p=1 emitted in P order -> k,q,e,e,p.
Hints
- Build a hash set (or map) of the characters in P so you can test membership in O(1).
- Single pass over S: count occurrences of each character that is in P, and append (in order) characters that are not in P to a separate buffer.
- Emit the result by walking P once and writing each character as many times as it was counted, then append the not-in-P buffer.
- For Unicode: iterate over code points (Python str already does; in Java/C++ decode UTF-8/UTF-16 to code points) rather than bytes, and key the count map by code point. For case-insensitive ordering, normalize both P and the matched characters with a consistent case fold before comparing, but emit the original characters.