[LeetCode] Longest Semi-Repeating Subarray

3641. Longest Semi-Repeating Subarray

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
int longestSubarray(vector<int>& nums, int k) {
int l = 0, r = 0, n = nums.size(), res = 0, rep = 0;
unordered_map<int,int> freq;
auto add = [&](int x) {
freq[x]++;
if(freq[x] == 2) rep++;
};
auto del = [&](int x) {
--freq[x];
if(freq[x] == 1) rep--;
if(freq[x] == 0) freq.erase(x);
};
while(r < n) {
if(rep <= k) {
add(nums[r]);
r++;
} else {
del(nums[l]);
l++;
}
if(rep <= k) res = max(res, r - l);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/11/27/PS/LeetCode/longest-semi-repeating-subarray/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.