Data Structures & AlgorithmsHard

Sort 4 7 4 2 7 2 9 4 3 so that values with higher FREQUENCY come first; values with equal frequency are ordered by value ascending, and every copy of a value stays together. Give the sorted sequence.

  1. A. 2 2 3 4 4 4 7 7 9
  2. B. 3 9 2 2 7 7 4 4 4
  3. C. 4 4 4 7 7 2 2 9 3
  4. D. 4 4 4 2 2 7 7 3 9

Correct answer: D. 4 4 4 2 2 7 7 3 9

Sort the list with a key of (−frequency, value), so the most frequent values come first and equal-frequency groups are ordered by value. Plain sorting, ascending frequency, or reversing the tie-breaker each give different orders.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic