Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: Reorder the letters of s so that letters listed in order appear in that order; letters not in order go last, keeping their original order.

Problem: Reorder the letters of s so that letters listed in `order` appear in that order; letters not in `order` go last, keeping their original order.
def custom(order, s):
    rank = {c: i for i, c in enumerate(order)}
    return "".join(sorted(s, key=lambda c: rank.get(c, len(order))))
print(custom("tre", "letters"), custom("zyx", "xxyza"))
What is printed?
  1. A. ttrelse azyxx
  2. B. ttreels zyxxa
  3. C. lsttree zyxxa
  4. D. ttreesl zyxxa

Correct answer: B. ttreels zyxxa

Each letter's key is its rank in `order`; unknown letters all share the key len(order) and, because sorted is stable, keep their input order (l before s in "letters"). "letters" → t, t, r, e, e, then l, s. O(n log n), or O(n) with counting.

More Coding Interview Problems questions

Exams that ask this topic