KatInterview

Longest Run Using Only Two Flavors

Arrays & HashingAuto-graded · 20 test cases
MediumAuto-gradedArrays & Hashingsliding-windowtwo-pointershash-map

Last 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.