Data Structures & AlgorithmsVery hardGATE CS · ICPC regional
For each element of an array of distinct integers, the task is to count how many earlier elements are smaller. Which structure achieves O(n log n) total time?
- A. Fenwick tree (binary indexed tree) over compressed values
- B. Monotonic stack alone
- C. A single prefix-sum array
- D. Sorting the whole array once without indices
Correct answer: A. Fenwick tree (binary indexed tree) over compressed values
Process left to right, query the count of smaller values inserted so far, then insert the current value in a Fenwick tree over compressed ranks. A monotonic stack only finds the nearest smaller element, not the total count.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- What is the length of the longest common subsequence of the three strings "ABCBDAB", "BDCABA" and "BCADB"?
- How many non-empty subsequences of "abcbab" (chosen by index, so the same letters at different positions count as different subsequences)…
- How many index triples i < j < k in [3, 1, 4, 1, 5, 9, 2, 6] satisfy a[i] < a[j] < a[k] (strictly increasing)?
- You stand on index 0 and must reach index 7. From index i you may move to any of the next 2 indices (i+1 or i+2). Landing on index j costs…
- What is the maximum product of THREE distinct elements of [-10, -3, 1, 5, 2, -8, 4] (chosen by position)?
- The substitutions-only distance (Hamming distance) between "karolin" and "kathrin" counts positions where the letters differ. What is that…