Data Structures & AlgorithmsHardProduct company OA
Problem: An array is a permutation of 0..n−1. Split it into the maximum number of chunks so that sorting each chunk separately and concatenating gives the sorted array.
Problem: An array is a permutation of 0..n−1. Split it into the maximum number of chunks so that sorting each chunk separately and concatenating gives the sorted array.
def max_chunks(a):
mx = cnt = 0
for i, x in enumerate(a):
mx = max(mx, x)
if mx == i:
cnt += 1
return cnt
print(max_chunks([2, 0, 1, 3, 5, 4, 6]), max_chunks([0, 1, 2, 3]), max_chunks([3, 0, 1, 2]))What is printed?- A. 4 1 1
- B. 4 4 1
- C. 4 4 2
- D. 3 4 1
Correct answer: B. 4 4 1
A chunk can end at index i exactly when the prefix a[0..i] holds the values 0..i, which for a permutation means max(prefix) = i. [2, 0, 1, 3, 5, 4, 6]: prefix maxima 2, 2, 2, 3, 5, 5, 6 match the index at i = 2, 3, 5, 6 → chunks [2,0,1] [3] [5,4] [6] = 4. A sorted array splits into n chunks; [3, 0, 1, 2] needs the whole array. O(n).
More Coding Interview Problems questions
- Problem: Seat numbers must become pairwise distinct; one move increments a seat number by 1. Find the minimum moves (sort, then push each…
- Problem: Two engineers list their free slots as sorted, internally disjoint closed intervals. Return every common free interval. python…
- Problem: A sensor array is 'steady' between positions i < j if a[j] − a[i] = j − i. Count steady pairs in O(n) by grouping a[i] − i…
- Problem: Four price lists A, B, C, D (each of length n ≤ 500). Count index tuples (i, j, k, l) with A[i] + B[j] + C[k] + D[l] = 0 by…
- Problem: A hiking trail is a list of heights. Find the length of the longest 'ridge' – a contiguous stretch that strictly rises and then…
- Problem: Return the sum of min(sub) over all contiguous subarrays using a monotonic stack. Ties must be broken so every subarray's minimum…