Back to Sliding Window
Sliding Window
Medium

Minimum Consecutive Cards to Pick Up

LAB

Return the length of the shortest contiguous subarray containing a repeated card value, or -1 if none exists.

EXAMPLES

Example 1
Input
{
  "cards": [
    3,
    4,
    2,
    3,
    4,
    7
  ]
}

Output
4

FUNCTION SHAPE

cards: intArrayint
SOLUTION NOTE

Straightforward min template. We are valid once we have a repeating card (freq == 2).

Reveal reference solution +
pythonREFERENCE
def minimumCardPickup(self, cards: List[int]) -> int:
    n, l, freq, res = len(cards), 0, Counter(), float('inf')

    for r in range(n):
        freq[cards[r]] += 1

        while freq[cards[r]] == 2:
            res = min(res, r - l + 1)
            freq[cards[l]] -= 1
            l += 1

    return res if res != float('inf') else -1
TimeO(n)
SpaceO(n)
Open on LeetCode
00:00
3 local tests readyRun with ⌘/Ctrl + Enter. Your code stays in this browser.

Runs solve(...) locally in a browser worker. SWE Playbook does not submit your code. Only run code you trust; Python code may access the network.