Trains the technique from
LeetCode 2958Length of Longest Subarray With at Most K FrequencyThis is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.
Same function shape, different story and different numbers.
A support desk writes down the reason code attached to each ticket, in the order the tickets arrived, giving the list codes. Reviewers want to sample a block of consecutive tickets that is varied enough to be worth reading, so they allow a block only when no single reason code shows up in it more than cap times.
Return the number of tickets in the longest block of consecutive entries of codes in which every reason code appears at most cap times.
Example 1
With a cap of one, the block of tickets 3 through 6 carries the codes 52, 63, 74 and 85, each once, so four tickets are allowed. Any block holding both copies of 52 breaks the cap.
Example 2
Tickets 3 through 6 read 2, 6, 2, 2, which holds code 2 three times, so that block is not allowed. Tickets 4 through 7 read 6, 2, 2, 9: code 2 appears twice and the others once, which is within the cap, giving a block of four.
Example 3
Every ticket carries code 7, so a block of three would hold it three times. A block of two is the widest that stays within the cap.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def longest_capped_run(codes: list[int], cap: int) -> int:public int longestCappedRun(int[] codes, int cap)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.