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?- A. ttrelse azyxx
- B. ttreels zyxxa
- C. lsttree zyxxa
- 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
- Problem: A sorted list of distinct positive IDs has gaps. Find the k-th positive integer missing from it in O(log n): before index i, a[i]…
- Problem: Find the minimum of a rotated sorted array that may contain DUPLICATES. python def findmin(a): lo, hi = 0, len(a) - 1 while lo <…
- Problem: Arrange non-negative integers so that their concatenation forms the largest number (returned as a string). Sort with the…
- Problem: A company sends 2n candidates to two interview centres, n to each; costs[i] = (cost at A, cost at B). Minimise the total cost by…
- Problem: Delete the fewest characters so that no two distinct letters have the same (non-zero) frequency. python from collections import…
- Problem: Does an array contain indices i < j < k with a[i] < a[j] < a[k]? An O(n), O(1) greedy keeps the smallest 'first' and the smallest…