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?- A. 3
- B. 5
- C. 2
- 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
- Problem: How many pairs (i < j) of [1, 2, 3, 4, 5] have a[i] a[j] at most 10? Run the code. python a = [1, 2, 3, 4, 5] print(sum(1 for i…
- Problem: How many distinct values appear among the minima of all subarrays of [3, 1, 2]? Run the code. python a = [3, 1, 2] mins =…
- Problem: What is the maximum value of a[i] + a[j] - (j - i) over pairs i < j of a = [1, 3, -2, 5]? Run the code. python a = [1, 3, -2, 5]…
- Problem: What is the total number of 1-bits in the binary representations of 1 through 10? Run the code. python…
- Problem: What is the minimum number of coins from {1, 2, 5} that sum to 11? Run the DP. python INF = 10 9 d = [0] + [INF] 11 for v in…
- Problem: How many binary strings of length 3 contain an even number of 1s? Run the code. python print(sum(1 for t in range(8) if…