FastPrepLongest Subarray with At Most Two Distinct Values
Problems/Longest Subarray with At Most Two Distinct Values

Longest Subarray with At Most Two Distinct Values

Moody's Investors Service logoMoody's Investors Service● MediumONSITE INTERVIEW

Updated Sep 2026

QuestionFunctionExamples

Problem statement

Source note: This problem is backed by a real Moody's onsite interview report. The report clearly gave the at-most-two-distinct subarray objective, but it did not include the exact function interface, examples, or constraints. The core task match is about 95%.

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.

Similar questions at other companies

  • Shortest Window with Required CountsOracle · ONSITE INTERVIEWOracle interview questions
  • Count Zero Request ServersSalesforce · ONSITE INTERVIEWSalesforce interview questions
  • High-Traffic IPs in a Sliding WindowGoogle · ONSITE INTERVIEWGoogle interview questions
  • Longest Subarray with K Distinct ValuesAmazon · ONSITE INTERVIEW
  • Count Equal Code Pairs Within Distance KInfosys · ONSITE INTERVIEWInfosys interview questions
  • Maximum Sum of a Unique-Element SubarrayTekion · ONSITE INTERVIEWTekion interview questions
  • Sliding Window: Target Containment and Most-Repeated WindowRoblox · ONSITE INTERVIEWRoblox interview questions
  • Invalid Transactions in Time OrderBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
  • Duplicate Transactions Within 60 SecondsCapital One · ONSITE INTERVIEWCapital One interview questions
  • Sliding Window MedianNotion · ONSITE INTERVIEWNotion interview questions
See Moody's Investors Service hiring insights
Saved
class Solution {
    public int longestSubarrayAtMostTwoDistinct(int[] nums) {
      // write your code here
    }
}
Checking account…