Data Structures & AlgorithmsModerateTCS NQT · sorting
Problem: Sort [1, 1, 2, 2, 2, 3] by frequency ascending, breaking ties by value ascending. What is printed?
Problem: Sort [1, 1, 2, 2, 2, 3] by frequency ascending, breaking ties by value ascending. What is printed?
from collections import Counter a = [1, 1, 2, 2, 2, 3] c = Counter(a) print(sorted(a, key=lambda x: (c[x], x)))What is printed?
- A. [1, 1, 3, 2, 2, 2]
- B. [3, 2, 2, 2, 1, 1]
- C. [3, 1, 1, 2, 2, 2]
- D. [1, 1, 2, 2, 2, 3]
Correct answer: C. [3, 1, 1, 2, 2, 2]
Value 3 appears once, 1 appears twice and 2 appears three times, so the sort key orders the groups 3, 1, 2.
More Coding Interview Problems questions
- Problem: How many set bits are there in total across the numbers 0 to 7? Run the code. python print(sum(bin(i).count('1') for i in…
- Problem: How many integers in [1, 20] are powers of two? Run the code. python print(sum(1 for x in range(1, 21) if x & (x - 1) == 0)) What…
- Problem: How many integers in [1, 100] are divisible by 7 or by 11? Run the code. python print(sum(1 for x in range(1, 101) if x % 7 == 0…
- Problem: What is 2^100 mod 7? Run the code. python print(pow(2, 100, 7)) What is printed?
- Problem: What is the length of the shortest path from node 1 to node 5 in the undirected graph with edges (1,2), (2,3), (1,4), (4,5)…
- Problem: How many connected components does the graph on vertices 0..5 with edges (0,1), (2,3), (4,5), (1,2) have? Run the union-find…