Longest Run Using Only Two Flavors
Arrays & HashingAuto-graded · 20 test casesLast updated
Find the longest contiguous stretch of an integer array containing at most two distinct values, testing sliding window and frequency tracking.
A shelf holds a line of sweets. The array sweets lists the flavor of each one in order, so sweets[i] is the flavor code of the sweet at position i.
You pick any starting position and walk to the right, collecting every sweet you pass. Your bag can hold sweets of at most two different flavors. As soon as the next sweet would introduce a third flavor, you stop without taking it (you may also stop earlier if you reach the end of the shelf).
Return the largest number of sweets you can collect, over all possible starting positions.
Details
- The collected sweets always form a contiguous block of the array beginning at your chosen start.
- Flavors are identified only by their integer values; two sweets have the same flavor exactly when their values are equal.
- If the array is empty, the answer is
0.
Constraints
0 <= len(sweets) <= 10^5- Each
sweets[i]is an integer (it may be negative or large). - Aim for a solution that runs in linear time.
Examples
Example 1
Input: longest_two_flavor_run([1, 2, 1, 2, 3, 2, 2])
Output: 4
Hints
Hint 1
Collecting from a start until a third flavor appears means you end up with a contiguous subarray that has at most two distinct values. So the goal is the longest such subarray.
Hint 2
Maintain a window with two pointers and a dictionary of flavor counts inside the window. Grow the right end one step at a time.
Hint 3
When the dictionary holds more than two flavors, advance the left pointer, decrementing counts and deleting a flavor when its count reaches zero. Record the window length after each right-end step.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Walking right from a start and stopping before a third flavor yields a contiguous block with at most two distinct values. Conversely, any such block can be collected by starting at its left end (you might even continue past its right end, which only helps). So the answer is the length of the longest contiguous subarray with at most two distinct values.
Use a sliding window [left, right] with a dictionary counts mapping flavor to its frequency in the window:
- Move
rightforward and addsweets[right]tocounts. - While
countshas more than two keys, removesweets[left]from the counts (deleting the key when it reaches zero) and incrementleft. - Update the best length with
right - left + 1.
Why it is correct
Validity is monotone: if a window has more than two distinct flavors, any larger window containing it does too; if a window is valid, any sub-window is valid. Hence, for each right, after shrinking, left is the smallest index making [left, right] valid, and it never needs to move backward because the smallest valid left for right is at least the one for right - 1. Taking the maximum window length over all right gives the global optimum.
Deleting zero-count keys is essential so that len(counts) equals the number of distinct flavors in the window.
Complexity
- Time: O(n), since each pointer moves at most n times and each step does O(1) dictionary work.
- Space: O(1), since the dictionary never holds more than three keys.
Reference solution
from typing import List
def longest_two_flavor_run(sweets: List[int]) -> int:
counts = {}
left = 0
best = 0
for right, flavor in enumerate(sweets):
counts[flavor] = counts.get(flavor, 0) + 1
while len(counts) > 2:
old = sweets[left]
counts[old] -= 1
if counts[old] == 0:
del counts[old]
left += 1
best = max(best, right - left + 1)
return best