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?- A. 4
- B. 6
- C. 3
- 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
- Problem: Detect a 132 pattern (i < j < k with a[i] < a[k] < a[j]) in O(n) by scanning from the right with a stack. python def has132(a)…
- Problem: A single-threaded CPU log has entries 'id:start:t' and 'id:end:t' (an end at t covers time unit t). Functions can call each…
- Problem: Evaluate an expression with +, −, , / (integer division truncating toward zero) and no parentheses, using a stack. python def…
- Problem: Find every start index in s of a substring that is a concatenation of all the given words (each exactly once, any order; all…
- Problem: Find the shortest contiguous substring of S that contains T as a SUBSEQUENCE (leftmost on ties). Scan forward to complete T, then…
- Problem: Find the longest substring that occurs at least twice (occurrences may overlap): binary search on the length with a set of…