Longest Subarray with At Most Two Distinct Values
Updated
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[]) → intExamples
Example 1
nums = [1,2,1]return = 3The entire array contains only 1 and 2.
Example 2
nums = [0,1,2,2]return = 3The 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