Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: Sort values by increasing frequency; values with the same frequency go in decreasing order.

Problem: Sort values by increasing frequency; values with the same frequency go in decreasing order.
from collections import Counter
def freq_sort(a):
    c = Counter(a)
    return sorted(a, key=lambda x: (c[x], -x))
print(freq_sort([4, 6, 2, 6, 4, 4, 3, 3]))
What is printed?
  1. A. [2, 3, 3, 6, 6, 4, 4, 4]
  2. B. [2, 6, 3, 4, 6, 4, 3, 4]
  3. C. [4, 4, 4, 6, 6, 3, 3, 2]
  4. D. [2, 6, 6, 3, 3, 4, 4, 4]

Correct answer: D. [2, 6, 6, 3, 3, 4, 4, 4]

Key (frequency, −value): 2 appears once; 6 and 3 appear twice, and −6 < −3 puts 6 first; 4 appears three times. Using (frequency, value) would put 3 before 6. O(n log n).

More Coding Interview Problems questions

Exams that ask this topic