Data Structures & AlgorithmsVery hardProduct company OA
Minimum window of s containing every character of t WITH multiplicity, using a need-counter. What is printed?
Minimum window of s containing every character of t WITH multiplicity, using a need-counter. What is printed?
from collections import Counter
def min_window(s, t):
need, have, missing = Counter(t), {}, len(t)
lo, best = 0, (10**9, 0, 0)
for hi, ch in enumerate(s):
if need[ch] > 0: missing -= 1
need[ch] -= 1
if missing == 0:
while need[s[lo]] < 0: need[s[lo]] += 1; lo += 1
best = min(best, (hi - lo + 1, lo, hi))
need[s[lo]] += 1; missing += 1; lo += 1
return s[best[1]:best[2] + 1] if best[0] < 10**9 else ""
print(min_window("cabwefgewcwaefgcf", "cae"), min_window("aabbaac", "aab"), repr(min_window("ab", "aa")))- A. cwae aab 'ab'
- B. cwae aab ''
- C. aefgc aab ''
- D. cwae aabb ''
Correct answer: B. cwae aab ''
need[c] > 0 means c is still missing; once missing hits 0 the left edge is advanced past surplus characters (need < 0), the window is recorded, and then one required character is released to look for a later window. 'cwae' (indices 9–12) is the shortest window with c, a, e. For aab the first three letters already work. t = 'aa' needs two a's but 'ab' has one, so the answer is empty. O(|s| + |t|).
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Shortest subarray with sum ≥ 5 in an array WITH negative numbers: an increasing deque of prefix-sum indices versus the usual shrinking…
- Probe-sequence coverage for open addressing: how many distinct slots can the offsets i² (quadratic) and i(i+1)/2 (triangular) reach in…
- An LRU cache of capacity 3 (OrderedDict, oldest first) processes page requests. How many misses, and what is the final order? python from…
- Minimum number of brackets to INSERT to make a string balanced, returned as (total, unmatched ')', unmatched '('). What is printed? python…
- Boyer–Moore majority vote WITHOUT the verification pass, returning (candidate, final counter). What is printed? python def vote(a): cand…
- Inversions counted during merge sort (pairs i < j with a[i] > a[j]). What is printed? python def inv(a): if len(a) <= 1: return a, 0 m =…