Length of Longest Subarray With at Most K Frequency

You are given an integer array nums and an integer k.

The frequency of an element x is the number of times it occurs in an array.

An array is called good if the frequency of each element in this array is less than or equal to k.

Return the length of the longest good subarray of nums.

A subarray is a contiguous non-empty sequence of elements within an array.

Example 1
Inputnums = [1,2,3,1,2,3,1,2], k = 2
Output6
The longest possible good subarray is [1,2,3,1,2,3] because the values 1, 2, and 3 each occur at most twice, and no good subarray has length more than 6.
Example 2
Inputnums = [1,2,1,2,1,2,1,2], k = 1
Output2
The longest possible good subarray is [1,2] because the values 1 and 2 each occur at most once, and no good subarray has length more than 2.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^9
  • 1 <= k <= nums.length

Asked at 4 companies

Practice questions like this out loud in a mock coding interview with a live AI interviewer. First one free.

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, what to keep, what's wrong, and the complexity of your solution.

Sign in to evaluate