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?- A. [2, 3, 3, 6, 6, 4, 4, 4]
- B. [2, 6, 3, 4, 6, 4, 3, 4]
- C. [4, 4, 4, 6, 6, 3, 3, 2]
- 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
- Problem: A researcher's h-index is the largest h such that at least h papers have ≥ h citations each. python def hindex(c): c = sorted(c…
- Problem: A 3 × 4 matrix is sorted row-wise and each row starts after the previous row ends. Search it as one virtual sorted array of R·C…
- Problem: A truck holds at most 8 boxes. Each box type is (count, units per box). Maximise the total units loaded. python def…
- Problem: Reorder the letters of s so that letters listed in order appear in that order; letters not in order go last, keeping their…
- Problem: A sorted list of distinct positive IDs has gaps. Find the k-th positive integer missing from it in O(log n): before index i, a[i]…
- Problem: Find the minimum of a rotated sorted array that may contain DUPLICATES. python def findmin(a): lo, hi = 0, len(a) - 1 while lo <…