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?
  1. A. 4 1 1
  2. B. 4 4 1
  3. C. 4 4 2
  4. 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

Exams that ask this topic