Shortest Subarray With at Least K Distinct Values
Updated
Problem statement
Given an integer array nums and a positive integer k, return the shortest length of a consecutive part of the array that contains at least k different values.
Return -1 when no such subarray exists.
Function
shortestSubarrayAtLeastKDistinct(nums: int[], k: int) → intExamples
Example 1
nums = [1,2,1,3,4]k = 3return = 3Subarray [2,1,3] has three distinct values and no length-two subarray can.
Example 2
nums = [1,1,1]k = 2return = -1The entire array contains only one distinct value.
Example 3
nums = [5,6]k = 1return = 1Any single element already contains one distinct value.
Constraints
1 <= nums.length <= 200000.1 <= k <= nums.length.-1000000000 <= nums[i] <= 1000000000.
More Google Onsite Interview questions
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Distinct Subset SumsONSITE INTERVIEW · Seen Nov 2026
- Playlist With No Same Artist in a RowONSITE INTERVIEW · Seen Nov 2026
- Delete Nodes and Return Forest RootsONSITE INTERVIEW · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- First and Last Target Position in a Mountain ArrayONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- 0/1 Knapsack with Weight and Volume LimitsONSITE INTERVIEW · Seen Nov 2026
- Batched Subsequence Word MatchesONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Shortest Window with Required CountsOracle · ONSITE INTERVIEWOracle interview questions
- Count Zero Request ServersSalesforce · ONSITE INTERVIEWSalesforce interview questions
- Longest Subarray with K Distinct ValuesAmazon · ONSITE INTERVIEW
- Count Equal Code Pairs Within Distance KInfosys · ONSITE INTERVIEWInfosys interview questions
- Longest Subarray with At Most Two Distinct ValuesMoody's Investors Service · ONSITE INTERVIEW
- 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