Data Structures & AlgorithmsVery hardProduct Company SDE · sorting with comparator
Problem: Arrange the numbers 3, 30, 34, 5, 9 so that the concatenation is the largest possible. Run the code and state the printed string.
Problem: Arrange the numbers 3, 30, 34, 5, 9 so that the concatenation is the largest possible. Run the code and state the printed string.
from functools import cmp_to_key
a = ['3', '30', '34', '5', '9']
a.sort(key=cmp_to_key(lambda x, y: -1 if x + y > y + x else (1 if x + y < y + x else 0)))
print(''.join(a))What is printed?- A. 9534330
- B. 9533430
- C. 9534303
- D. 9543330
Correct answer: A. 9534330
The comparator orders two strings by which concatenation is larger (x+y against y+x), not by numeric value. Sorting by plain numeric value would put 3 and 30 in the wrong order.
More Coding Interview Problems questions
- Problem: How many integers x with 1 <= x <= 100 satisfy x^3 ≡ x (mod 7)? python print(sum(1 for x in range(1, 101) if pow(x, 3, 7) == x %…
- Problem: What does the following print? python from math import lcm print(lcm(range(1, 11)))
- Problem: How many integers from 1 to 100 have exactly 3 positive divisors? python print(sum(1 for x in range(1, 101) if sum(1 for d in…
- Problem: Piles of stones are 3, 4 and 5. Two players alternately remove any positive number of stones from one pile, and whoever takes the…
- Problem: A subtraction game lets a player remove 1, 3 or 4 stones. Let g(n) be the Grundy number (mex of the Grundy values reachable in…
- Problem: Two fair six-sided dice are rolled. What is the expected value of the larger of the two faces (the maximum)?