Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Split an array (duplicates allowed) into the most chunks such that sorting each chunk separately and concatenating gives the sorted array (monotonic stack of chunk maxima).

Problem: Split an array (duplicates allowed) into the most chunks such that sorting each chunk separately and concatenating gives the sorted array (monotonic stack of chunk maxima).
def chunks(a):
    st = []
    for x in a:
        if not st or x >= st[-1]: st.append(x)
        else:
            top = st.pop()
            while st and st[-1] > x: st.pop()
            st.append(top)
    return len(st)
print(chunks([5, 4, 3, 8, 7, 9, 6, 10, 10, 11]))
What is printed?
  1. A. 4
  2. B. 6
  3. C. 3
  4. D. 5

Correct answer: D. 5

Each stack entry is the maximum of one chunk. A smaller value x merges every chunk whose maximum exceeds x: 6 is below the maxima 8 and 9, so the chunks [8, 7] and [9] merge with it into [8, 7, 9, 6]. The chunks are [5, 4, 3], [8, 7, 9, 6], [10], [10], [11] → 5.

More Coding Interview Problems questions

Exams that ask this topic