Length of Longest Subarray With at Most K Frequency

You are given an integer array `nums` and an integer `k`. A subarray is good if every value in it appears at most `k` times. Return the length of the longest good subarray of `nums`.

30:00

Length of Longest Subarray With at Most K Frequency
medium
Free written solution
Topics
Companies

You are given an integer array nums and an integer k. A subarray is good if every value in it appears at most k times. Return the length of the longest good subarray of nums.

Example 1:
Input: {"nums":[1,2,3,1,2,3,1,2],"k":2}
Output: 6
Constraints:
  • 1≤nums.length≤1051 \leq \text{nums.length} \leq 10^5

  • 1≤nums[i]≤1091 \leq \text{nums}[i] \leq 10^9

  • 1≤k≤nums.length1 \leq k \leq \text{nums.length}

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,2,3,1,2,3,1,2],"k":2}

Grow a window to the right and count each value in it. No value may appear more than k = 2 times; when one does, shrink from the left.

nums · k = 2

1

0

2

1

3

2

1

3

2

4

3

5

1

6

2

7

counts in the window

k = 2empty

window length

-

best

0

Variables
VariableValue
k2
left0
best0
DepthFunction Call
Stack empty
0/19