Data Structures & AlgorithmsVery hardProduct Company SDE · sliding window OA
Problem: What is the length of the shortest substring of 'aabcbcdbca' that contains all distinct characters of the string? Run the sliding-window code.
Problem: What is the length of the shortest substring of 'aabcbcdbca' that contains all distinct characters of the string? Run the sliding-window code.
s = 'aabcbcdbca'
need = len(set(s))
cnt = {}
l = 0
best = float('inf')
for r, ch in enumerate(s):
cnt[ch] = cnt.get(ch, 0) + 1
while len(cnt) == need:
best = min(best, r - l + 1)
cnt[s[l]] -= 1
if cnt[s[l]] == 0:
del cnt[s[l]]
l += 1
print(best)What is printed?- A. 4
- B. 5
- C. 6
- D. 7
Correct answer: A. 4
The string has 4 distinct letters (a, b, c, d), and the shortest window with all of them is 'dbca' of length 4.
More Coding Interview Problems questions
- Problem: What is the Levenshtein distance between 'horse' and 'ros'? Run the DP. python a, b = 'horse', 'ros' dp = [[0] (len(b) + 1) for…
- Problem: What is the sum of |ai - aj| over all pairs i < j of the sorted array [1, 4, 6]? Run the code. python a = sorted([1, 4, 6])…
- Problem: Which complexity does the sieve of Eratosthenes have for finding all primes up to n?
- Problem: How many 3-digit numbers are palindromes? python print(sum(1 for x in range(100, 1000) if str(x) == str(x)[::-1])) What is printed?
- Problem: How many integers in [1, 200] are divisible by 2, 3 or 5? python print(sum(1 for x in range(1, 201) if x % 2 == 0 or x % 3 == 0…
- Problem: How many subsets of {1, 2, 3, 4, 5, 6} have sum exactly 10? python print(sum(1 for m in range(1 << 6) if sum(i + 1 for i in…