Longest Semi-Repeating Subarray Problem
#3641
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3641.
You are given an integer array nums of length n and an integer k.
A semi‑repeating subarray is a contiguous subarray in which at most k elements repeat (i.e., appear more than once).
Return the length of the longest semi‑repeating subarray in nums.
Example 1:
Input: nums = [1,2,3,1,2,3,4], k = 2
Output: 6
Explanation:
The longest semi-repeating subarray is [2, 3, 1, 2, 3, 4], which has two repeating elements (2 and 3).
Example 2:
Input: nums = [1,1,1,1,1], k = 4
Output: 5
Explanation:
The longest semi-repeating subarray is [1, 1, 1, 1, 1], which has only one repeating element (1).
Example 3:
Input: nums = [1,1,1,1,1], k = 0
Output: 1
Explanation:
The longest semi-repeating subarray is [1], which has no repeating elements.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^50 <= k <= nums.length
Solution
Approach: Sliding Window
Keep a window [l, r] and a hash map cnt with the number of times each value occurs in it. Let cur be the number of values that occur at least twice (the repeating values).
- When
rmoves right and a value's count becomes 2, that value starts repeating, socurgrows by one. - While
cur > k, the window is invalid. Movelright; when a count drops from 2 to 1,curshrinks by one. - After restoring validity,
r - l + 1is a candidate answer.
Complexity: O(n) time and O(n) extra space.
from collections import defaultdict
class Solution:
def longestSubarray(self, nums: List[int], k: int) -> int:
cnt = defaultdict(int)
ans = cur = l = 0
for r, x in enumerate(nums):
cnt[x] += 1
cur += cnt[x] == 2
while cur > k:
cnt[nums[l]] -= 1
cur -= cnt[nums[l]] == 1
l += 1
ans = max(ans, r - l + 1)
return ans