Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE
Problem: Find the smallest length of a contiguous block of positive integers whose sum is at least s (0 if none).
Problem: Find the smallest length of a contiguous block of positive integers whose sum is at least s (0 if none).
def min_len(a, s):
l = total = 0
best = float('inf')
for r, x in enumerate(a):
total += x
while total >= s:
best = min(best, r - l + 1)
total -= a[l]
l += 1
return 0 if best == float('inf') else best
print(min_len([2, 3, 1, 2, 4, 3], 7), min_len([1, 1, 1], 5))What is printed?- A. 3 0
- B. 2 0
- C. 2 3
- D. 1 0
Correct answer: B. 2 0
Variable window: grow on the right, shrink while the sum is still ≥ s. [4, 3] reaches 7 with length 2. The second array never reaches 5, so the sentinel inf is turned into 0. Every index is added and removed once – O(n). The trick needs positive values.
More Coding Interview Problems questions
- Problem: A binary array may have at most k zeros flipped to 1. Return the longest run of 1s achievable. python def longestones(a, k): l =…
- Problem: Return the maximum of every window of size k in a stream of readings. python from collections import deque def winmax(a, k): dq…
- Problem: For n = 10⁶ readings and window size k = 10⁵, report every window maximum. Which approach fits the limits best?
- Problem: Count how many substrings of length k in a DNA string contain exactly k distinct letters. python def countdistinct(s, k): freq, c…
- Problem: Find the length of the longest substring that can be turned into a single repeated letter by changing at most k characters…
- Problem: Return the smallest window of s that contains every character of t (with multiplicity). python from collections import Counter…