Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Find the length of the longest substring of a log line with no repeated character.
Problem: Find the length of the longest substring of a log line with no repeated character.
def longest(s):
last = {}
l = best = 0
for r, ch in enumerate(s):
if ch in last and last[ch] >= l:
l = last[ch] + 1
last[ch] = r
best = max(best, r - l + 1)
return best
print(longest("abba"), longest("dvdf"))What is printed?- A. 2 2
- B. 3 3
- C. 1 3
- D. 2 3
Correct answer: D. 2 3
The window start jumps to just after the previous occurrence, but only if that occurrence is inside the window (last[ch] >= l). For "abba" the final 'a' was last seen at 0, outside the window [2..], so l stays 2 and the best is 2; "dvdf" gives "vdf" = 3. Dropping the last[ch] >= l check moves l backwards and gives a wrong length 3 for "abba". O(n).
More Coding Interview Problems questions
- Problem: Find the smallest length of a contiguous block of positive integers whose sum is at least s (0 if none). python def minlen(a, s)…
- 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…