Data Structures & AlgorithmsHardGoogle · Flipkart interview
Problem: Find the shortest substring of s that contains every character of t, counting duplicates (return the leftmost one on ties).
Problem: Find the shortest substring of s that contains every character of t, counting duplicates (return the leftmost one on ties).
from collections import Counter
def minwin(s, t):
need, missing = Counter(t), len(t)
l, best = 0, (0, float('inf'))
for r, c in enumerate(s):
if need[c] > 0: missing -= 1
need[c] -= 1
while missing == 0:
if r - l < best[1] - best[0]: best = (l, r)
need[s[l]] += 1
if need[s[l]] > 0: missing += 1
l += 1
return s[best[0]:best[1] + 1]
print(minwin("baacbaab", "aab"))What is printed?- A. aab
- B. aacb
- C. cbaab
- D. baa
Correct answer: D. baa
t needs two a's and one b. The window shrinks whenever it is valid; 'baa' (indices 0–2) is the first length-3 window, and 'aab' at the end is also length 3, but the strict < keeps the leftmost. A window such as 'aacb' also has the letters but is longer.
More Coding Interview Problems questions
- Problem: Count subarrays with EXACTLY k distinct values using exactly(k) = atMost(k) − atMost(k − 1). python def atmost(a, k): cnt, l, res…
- Find the bug: the code below should return the length of the longest substring without repeating characters. python def longest(s): last…
- Problem: Count the UNIQUE triplets (as value sets) that sum to zero, using sort + two pointers with duplicate skipping. python def…
- Problem: Count subarrays whose sum is exactly k when values may be negative (prefix sums + hash map of prefix counts). python def count(a…
- Search for a value in a sorted array that was rotated and MAY CONTAIN DUPLICATES (e.g. [1, 1, 1, 1, 0, 1, 1]). What is the worst-case time…
- Problem: Return the index of ANY peak element (strictly greater than its neighbours; a[−1] = a[n] = −∞) in O(log n). python def peak(a)…