Data Structures & AlgorithmsHardAmazon · Microsoft OA
Find the bug: the code below should return the length of the longest substring without repeating characters.
Find the bug: the code below should return the length of the longest substring without repeating characters.
def longest(s):
last, left, best = {}, 0, 0
for i, c in enumerate(s):
if c in last:
left = last[c] + 1
last[c] = i
best = max(best, i - left + 1)
return best
print(longest("abba"))What is printed?- A. 3
- B. 2
- C. 4
- D. 1
Correct answer: A. 3
At the final 'a', last['a'] = 0, so left jumps BACK from 2 to 1 and the window 'bba' (length 3) is counted although it repeats b. The fix is left = max(left, last[c] + 1); the correct answer for 'abba' is 2.
More Coding Interview Problems questions
- 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)…
- Problem: In an n × n matrix whose rows and columns are both sorted, find the k-th smallest value by binary searching on the VALUE and…
- Problem: Reverse the nodes of a singly linked list from position m to n (1-based) in one pass. python class N: def init(s, v, nx=None)…