Longest Subarray With At Most Two Distinct Values
Implement longestSubarrayWithAtMostTwoDistinct
Given an array
nums, return the length of the longest contiguous subarray that contains at most 2 distinct values.
Checking every starting index and re-scanning forward works, but it forgets everything the previous start already learned about the array. The sliding windowSliding WindowMaintaining a running result over a contiguous range that grows or shrinks one element at a time, instead of recomputing the result for every range from scratch. technique keeps a frequency map of the values currently in view: grow the window by moving the right edge forward, and whenever a 3rd distinct value sneaks in, shrink from the left — dropping counts back to zero — until the window is valid again. Every element enters and leaves the window at most once, so the whole scan runs in O(n).
Example 1:
Input: nums = [1,2,3,2,2]
Output: 4
Example 2:
Input: nums = [1,2,1]
Output: 3
Example 3:
Input: nums = [0,1,2,2]
Output: 3
+ 8 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ nums.length ≤ 10⁵ - ●
0 ≤ nums[i] ≤ 10⁴
nums =
[1, 2, 3, 2, 2]