Data Structures & AlgorithmsHardProduct Company SDE · sliding window OA
Problem: What is the length of the longest contiguous subarray containing at most two distinct values?
Problem: What is the length of the longest contiguous subarray containing at most two distinct values?
from collections import Counter
def f(a):
c = Counter()
l = best = 0
for r, x in enumerate(a):
c[x] += 1
while len(c) > 2:
c[a[l]] -= 1
if c[a[l]] == 0:
del c[a[l]]
l += 1
best = max(best, r - l + 1)
return best
print(f([1, 2, 1, 2, 3, 2, 2, 4, 1]))What is printed?- A. 5
- B. 3
- C. 4
- D. 6
Correct answer: C. 4
The windows [1,2,1,2] and [2,3,2,2] both have length 4 and no longer window has only two values. The two-pointer window shrinks until only two distinct values remain.
More Coding Interview Problems questions
- Problem: Remove exactly 3 digits from the number '1432219' to make the smallest possible number, keeping the remaining digits in order…
- Problem: What is the length of the longest palindromic subsequence of 'bbbab'? python def lps(s): n = len(s) dp = [[0] n for in range(n)]…
- Problem: Multiply a chain of matrices with dimensions p = [10, 30, 5, 60] (matrix i is p[i] by p[i+1]). Find the minimum number of scalar…
- Problem: How many ways can 10 be formed as an ordered-free sum of coins 1, 2 and 5 (each coin may be used any number of times, and order…
- Problem: What is the diameter (in edges) of the tree with edges 1-2, 2-3, 2-4, 4-5, 5-6? Use the double BFS code. python from collections…
- Problem: A robot starts at (0, 0) facing north (+y). Commands: F moves one step forward, B one step backward (facing unchanged), L turns…