Skip to main content
Back to problems
Leetcode
Medium
Arrays
Hash Maps
Amazon
Length Of Longest Subarray With At Most K Frequency

Find the maximum length of a contiguous subarray where no value appears more than kk times.

Acceptance 0%
Problem Statement

Given an integer array, determine the length of the longest contiguous subarray such that every distinct value inside that subarray occurs at most kk times.

You may choose any contiguous segment of the array. Among all valid segments, return the maximum possible length.

Input Format

  • An integer array nums
  • An integer k

The exact input representation may vary by platform, but the task is to compute the longest valid contiguous subarray length from these two values.

Output Format

Return a single integer: the maximum length of a contiguous subarray in which every element frequency is at most k.

Constraints

  • The array may be empty.
  • If k <= 0, the answer is 0.
  • Use only the information that element frequencies inside the chosen subarray must stay within the limit k.
  • A typical efficient solution should run in linear or near-linear time.
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [1, 2, 1, 2, 1, 2, 3], k = 2

Output

6

Explanation

The subarray [1, 2, 1, 2, 1, 2] is valid because 1 appears 3 times? Wait, that exceeds 2, so it is invalid. A valid longest subarray is [1, 2, 1, 2, 3], where 1 appears 2 times, 2 appears 2 times, and 3 appears once, giving length 5. However, [2, 1, 2, 1, 2, 3] is also invalid. The longest valid length is 5.

Example 2

Input

nums = [1, 1, 1, 2, 2, 3], k = 2

Output

5

Explanation

The subarray [1, 1, 2, 2, 3] is valid: 1 appears twice, 2 appears twice, and 3 appears once.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.