Skip to main content
Back to problems
Leetcode
Medium
Arrays
Hash Maps
Ordered Structures
Google
Meta
Find The Longest Equal Subarray

Find the maximum length of a subarray that can be made entirely equal after deleting at most kk elements from it.

Acceptance 0%
Also Available On
Other platform versions and source mappings for the same problem.

Longest Equal Subarray

gfg
Problem Statement

Problem

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

Choose a subarray of nums. You may delete at most k elements from inside that chosen subarray. After the deletions, the remaining elements must all be equal.

Return the maximum possible length of the remaining equal subarray.

In other words, for some value x, you want to find a contiguous segment where, after removing up to k non-x elements, all remaining elements are x, and the number of retained elements is as large as possible.

Input Format

  • nums: an integer array
  • k: a non-negative integer

Output Format

  • Return an integer representing the longest equal subarray length achievable after at most k deletions within one chosen subarray.

Constraints

  • 1 <= nums.length <= $10^{5}$
  • 1 <= nums[i] <= $10^{5}$
  • 0 <= k <= nums.length

Hints

  • Think about fixing the value that should remain after deletions.
  • For each value, track the positions where it appears.
  • The number of elements to delete inside a window of occurrences can be inferred from the gap between their positions and how many equal elements are inside the window.

Input Format

  • An integer array nums
  • An integer k

Output Format

  • A single integer: the maximum length of an equal subarray after deleting at most k elements from one chosen subarray

Constraints

  • 1 <= nums.length <= $10^{5}$
  • 1 <= nums[i] <= $10^{5}$
  • 0 <= k <= nums.length
Examples
Sample cases returned by the problem API.

Example 1

Input

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

Output

3

Explanation

Choose the subarray [3,2,3,1,3]. Delete 2 and 1, leaving [3,3,3] of length 3.

Example 2

Input

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

Output

4

Explanation

Choose the whole array. Delete the two 2s, leaving [1,1,1,1].

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.