Data Structures & AlgorithmsModerateCodeforces Div2 B · two pointers
Problem: What is the minimum length of a contiguous subarray of [1, 2, 3, 4, 5, 6, 7, 8] with sum at least 15? Run the two-pointer code.
Problem: What is the minimum length of a contiguous subarray of [1, 2, 3, 4, 5, 6, 7, 8] with sum at least 15? Run the two-pointer code.
a = [1, 2, 3, 4, 5, 6, 7, 8]
l = s = 0
best = float('inf')
for r, x in enumerate(a):
s += x
while s >= 15:
best = min(best, r - l + 1)
s -= a[l]
l += 1
print(best)What is printed?- A. 2
- B. 3
- C. 1
- D. 4
Correct answer: A. 2
The pair 7 + 8 = 15 is the shortest window reaching 15, and no single element is that large.
More Coding Interview Problems questions
- Problem: What is the integer floor of the square root of 10^12? Use binary search. python lo, hi = 0, 10 12 while lo < hi: mid = (lo + hi…
- Problem: Split [7, 2, 5, 10, 8] into 2 contiguous parts to minimise the largest part sum. What is the answer? Run the brute-force code…
- Problem: How many contiguous subarrays of [4, 1, -1, 2, 3] have a sum divisible by 4? Run the prefix-count code. python from collections…
- Problem: How many distinct substrings of length 2 does 'abcabc' contain? Run the code. python s = 'abcabc' print(len({s[i:i + 2] for i in…
- Problem: What is the length of the longest valid (well-formed) parenthesis substring of ')()())'? Run the stack code. python s = ')()())'…
- Problem: What is the value of the reverse Polish expression '2 1 + 3 '? Run the stack code. python tokens = '2 1 + 3 '.split() st = [] for…