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?
  1. A. [1, 1, 3, 2, 2, 2]
  2. B. [3, 2, 2, 2, 1, 1]
  3. C. [3, 1, 1, 2, 2, 2]
  4. 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

Exams that ask this topic