Problem · Array

Longest Subarray with At Most Two Distinct Values

Learn this problem
MediumMoody'sONSITE INTERVIEW

Problem statement

Given an integer array nums, return the maximum length of a contiguous subarray containing at most two distinct values.

The chosen subarray may contain either one or two distinct values.

Interview follow-up

  • The candidate proposed binary search on the answer with fixed-size window validation, and the interviewer asked them to implement that approach.
  • After reviewing the implementation, the interviewer pointed out that the problem can be solved directly with a sliding window.
  • The candidate explained the sliding-window approach and offered to implement it instead. The interviewer said another implementation was not necessary.

Function

longestSubarrayAtMostTwoDistinct(nums: int[]) → int

Examples

Example 1

nums = [1,2,1]return = 3

The entire array contains only 1 and 2.

Example 2

nums = [0,1,2,2]return = 3

The subarray [1,2,2] has length 3 and uses two distinct values.

drafts saved locally
public int longestSubarrayAtMostTwoDistinct(int[] nums) {
  // write your code here
}
nums[1,2,1]
expected3
checking account