Data Structures & AlgorithmsHardGATE CS · Codeforces Div2 C
For each index i of [4, 2, 5, 3, 1, 6], let dist(i) be the distance to the next index j > i with a[j] < a[i] (dist = n − i if no such index exists, where n is the length). What is the sum of dist(i) over all i?
- A. 12
- B. 9
- C. 7
- D. 21
Correct answer: B. 9
Monotonic stack (increasing values): when a smaller value arrives, pop each larger index and set its distance to the current index minus its own. Indices left on the stack keep distance n − i. Using the previous smaller element changes the distances.
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
- Let A = [1, 4, 6, 9], B = [2, 3, 7] and S = [5, 9, 10, 13]. Count the ordered pairs (x from A, y from B) whose sum x + y lies in S.
- How many unordered pairs of positions in [5, 1, 4, 7, 2, 6] have bitwise XOR at most 3?
- What is the minimum number of characters you must DELETE from "aabbbccddddeee" so that every letter that remains appears the same number…
- A rod of length 17 must be cut into pieces each of length at most 5. What is the minimum number of cuts?
- What is the maximum number of DISJOINT non-empty contiguous subarrays of [1, -1, 2, -2, 3, 4, -7, 5, -5, 6] that each have sum 0?
- What is the minimum possible length of a single CONTIGUOUS block of [1, 3, 7, 4, 2, 5, 9] that you can delete (the rest is concatenated in…