Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA
Problem: For each element of an array of n = 10⁵, count how many elements to its right are smaller. What is the best complexity?
- A. O(n) with a monotonic stack
- B. O(n²) is required
- C. O(n log n) by sorting once and reading positions
- D. O(n log n) using a Fenwick tree over compressed values scanned from the right (or merge sort with index tracking)
Correct answer: D. O(n log n) using a Fenwick tree over compressed values scanned from the right (or merge sort with index tracking)
Scanning from the right, insert each value into a BIT and query how many inserted values are smaller: O(log n) each. A monotonic stack finds the NEAREST smaller element, not the count. Sorting alone loses the 'to the right' constraint.
More Coding Interview Problems questions
- Problem: A grid of R × C = 10³ × 10³ heights; find the minimum possible 'maximum step height' along any path from top-left to…
- Problem: Count distinct values in every window of size k over n = 10⁶ values. What is the optimal complexity?
- Problem: n = 10⁵ cities connected by roads that are added one at a time; after each addition report the number of connected components…
- Problem: Find the longest substring that appears at least twice in a string of length 10⁵. Which approach is efficient?
- Problem: A recursive solution for 'number of ways to partition n into parts' is memoised on (n, largest part allowed). With n ≤ 1000, how…
- Problem: A function has T(n) = T(n − 1) + T(n − 2) + O(1) without memoisation. What is its growth?