Data Structures & AlgorithmsVery hardProduct Company SDE · CP practice

Problem: What is the length of the longest subarray of [5, 1, 4, 2, 3, 6] whose elements can be sorted to form consecutive integers? Run the code (check max - min == length - 1 and all distinct).

Problem: What is the length of the longest subarray of [5, 1, 4, 2, 3, 6] whose elements can be sorted to form consecutive integers? Run the code (check max - min == length - 1 and all distinct).
a = [5, 1, 4, 2, 3, 6]
best = 0
for i in range(len(a)):
    for j in range(i, len(a)):
        w = a[i:j + 1]
        if len(set(w)) == len(w) and max(w) - min(w) == len(w) - 1:
            best = max(best, len(w))
print(best)
What is printed?
  1. A. 6
  2. B. 4
  3. C. 3
  4. D. 2

Correct answer: A. 6

The whole array has distinct values with max − min = 6 − 1 = 5 = length − 1, so 6. [1, 4, 2, 3] gives 4, [4, 2, 3] gives 3, and adjacent consecutive values 2, 3 give only 2.

More Coding Interview Problems questions

Exams that ask this topic