Data Structures & AlgorithmsModerateTCS NQT · Product Company OA

Problem: What is the length of the longest subarray of [1, 2, 3, 4, 5] whose sum is at most 10? Run the two-pointer code.

Problem: What is the length of the longest subarray of [1, 2, 3, 4, 5] whose sum is at most 10? Run the two-pointer code.
a = [1, 2, 3, 4, 5]
l = s = best = 0
for r, x in enumerate(a):
    s += x
    while s > 10:
        s -= a[l]
        l += 1
    best = max(best, r - l + 1)
print(best)
What is printed?
  1. A. 3
  2. B. 5
  3. C. 2
  4. D. 4

Correct answer: D. 4

The window [1, 2, 3, 4] sums to exactly 10 and has length 4, which is the longest valid window.

More Coding Interview Problems questions

Exams that ask this topic