Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Arrange non-negative integers so that their concatenation forms the largest number (returned as a string). Sort with the comparator 'a before b if a + b > b + a'.
Problem: Arrange non-negative integers so that their concatenation forms the largest number (returned as a string). Sort with the comparator 'a before b if a + b > b + a'.
from functools import cmp_to_key
def largest(nums):
s = sorted(map(str, nums), key=cmp_to_key(lambda a, b: (b + a > a + b) - (b + a < a + b)))
r = "".join(s)
return "0" if r[0] == "0" else r
print(largest([7, 50, 5, 56, 4]), largest([0, 0]), largest([8, 89, 898]))What is printed?- A. 7565504 0 898898
- B. 7565504 0 898988
- C. 7565054 0 898898
- D. 7565504 00 898988
Correct answer: B. 7565504 0 898988
The pairwise rule 'a + b > b + a' is a valid total order, and sorting by it gives the optimum. 5 vs 50: "550" > "505", so 5 first; 56 vs 5: "565" > "556", so 56 first → 7 56 5 50 4. Plain reverse string sorting puts 50 before 5 ("7565054") and 898 before 89 ("898898" < "898988"). All zeros must collapse to "0". O(n log n · L).
More Coding Interview Problems questions
- 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…
- Problem: Can a hand of cards be split into groups of exactly w consecutive values? Greedily start groups at the smallest remaining card…
- Problem: Swap at most two digits of a number once to obtain the maximum value. Record the last position of each digit and, scanning left…
- Problem: Flower i blooms on day bloom[i]. A bouquet needs k ADJACENT bloomed flowers, each flower used once. Find the minimum day by which…