Bird
Raised Fist0
Interview Prepsliding-windowmediumAmazonGoogle

Minimum Consecutive Cards to Pick Up

Choose your preparation mode4 modes available
📋
Problem

Imagine you have a deck of cards laid out in a row, and you want to quickly find the smallest group of consecutive cards that contains two identical cards.

Given an integer array cards where cards[i] represents the value of the ith card, return the minimum number of consecutive cards you need to pick up to have at least two cards with the same value. If no such group exists, return -1.

1 ≤ cards.length ≤ 10^51 ≤ cards[i] ≤ 10^6
Edge cases: All cards are unique → output -1All cards are the same → output 2 (minimum length)Duplicates appear at the very start and end → output minimum gap
</>
IDE
def minimumCardPickup(cards: list[int]) -> int:public int minimumCardPickup(int[] cards)int minimumCardPickup(vector<int>& cards)function minimumCardPickup(cards)
def minimumCardPickup(cards):
    # Write your solution here
    pass
class Solution {
    public int minimumCardPickup(int[] cards) {
        // Write your solution here
        return -1;
    }
}
#include <vector>
using namespace std;

int minimumCardPickup(vector<int>& cards) {
    // Write your solution here
    return -1;
}
function minimumCardPickup(cards) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: -1 when duplicates existNot updating minimum length when duplicates are found.✅ Update min length whenever a duplicate card is found by comparing current index and last seen index.
Wrong: Minimum length larger than actualStopping at first duplicate or not checking all duplicates for minimal gap.✅ Continue scanning entire array and update min length for every duplicate occurrence.
Wrong: Positive number when no duplicates existNot returning -1 when no duplicates found.✅ Return -1 if minimum length remains infinity after processing all cards.
Wrong: TLE on large inputUsing brute force O(n^2) approach.✅ Implement O(n) solution using last seen map to track indices and update min length.
✓
Test Cases
t1_01basic
Input{"cards":[3,4,2,3,4,7]}
Expected3

The smallest subarray with duplicate cards is [3,4,2,3] length 4 but closer duplicates are [4,2,3,4] length 4 and [3,4,2,3] length 4. However, the minimal length is actually 3 for the subarray [3,4,3] at indices 0,1,3 is invalid since 3 and 3 are at indices 0 and 3, length 4. The minimal length is 3 for subarray [4,2,3,4] is length 4. Rechecking, duplicates of 3 at indices 0 and 3 length 4, duplicates of 4 at indices 1 and 4 length 4. So minimal length is 4. But checking carefully, minimal length is 4. So original 4 is correct. Re-verified minimal length is 4.

t1_02basic
Input{"cards":[1,0,5,3]}
Expected-1

No duplicates in the array, so return -1.

t2_01edge
Input{"cards":[]}
Expected-1

Empty array means no duplicates, so return -1.

t2_02edge
Input{"cards":[7]}
Expected-1

Single element array cannot have duplicates, so return -1.

t2_03edge
Input{"cards":[5,5]}
Expected2

Two identical cards adjacent, minimum length is 2.

t3_01corner
Input{"cards":[1,2,3,4,1,2,3,4]}
Expected5

First duplicate pair is 1 at indices 0 and 4, subarray length 5 is minimal.

t3_02corner
Input{"cards":[1,2,1,2,1,2]}
Expected3

Minimum length subarray with duplicates is 3 (e.g., cards[0..2] = [1,2,1] or cards[1..3] = [2,1,2]). Adjacent duplicates do not exist, minimal length is 3.

t3_03corner
Input{"cards":[1,2,3,4,5,6,7,8,9,10]}
Expected-1

All unique cards, no duplicates, return -1.

t4_01performance
Input{"cards":[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,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100]}
⏱ Performance - must finish in 2000ms

Input size n=100, solution must run in O(n) or O(n log n) time to complete within 2 seconds.

Practice

(1/5)
1. Consider the following Python code implementing the optimal solution for the problem. What is the returned value when calling longestOnes([1,0,1,0], 1)?
from collections import deque

def longestOnes(nums, k):
    zero_positions = deque()
    left = 0
    max_length = 0
    for right in range(len(nums)):
        if nums[right] == 0:
            zero_positions.append(right)
        if len(zero_positions) > k:
            left = zero_positions.popleft() + 1
        max_length = max(max_length, right - left + 1)
    return max_length
easy
A. 4
B. 2
C. 1
D. 3

Solution

  1. Step 1: Trace iterations with input [1,0,1,0], k=1

    Right=0: nums[0]=1, zero_positions=[], max_length=1 Right=1: nums[1]=0, zero_positions=[1], max_length=2 Right=2: nums[2]=1, zero_positions=[1], max_length=3 Right=3: nums[3]=0, zero_positions=[1,3], length=2 > k=1 triggers left update left = zero_positions.popleft()+1 = 1+1=2, zero_positions=[3], max_length remains 3
  2. Step 2: Final max_length after loop ends is 3

    The longest subarray with at most 1 zero flipped is length 3.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Manual trace confirms max_length=3 [OK]
Hint: Track zero positions and window boundaries carefully [OK]
Common Mistakes:
  • Off-by-one errors in window length
  • Not updating left pointer correctly
  • Confusing max_length update timing
2. What is the time complexity of the optimized sliding window algorithm that uses a hash map to track the last seen indices of characters for finding the longest substring without repeating characters?
medium
A. O(n) because each character is visited at most twice by the right and left pointers
B. O(n^2) because each character may cause the left pointer to move multiple times
C. O(n log n) due to hash map operations on each character
D. O(n * m) where m is the size of the character set

Solution

  1. Step 1: Analyze pointer movements

    Right pointer moves forward once per character. Left pointer only moves forward when duplicates are found, never backward. Each character is visited at most twice.
  2. Step 2: Consider hash map operations

    Hash map lookups and updates are O(1) average. Thus total time is O(n).
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Two-pointer sliding window with hash map -> linear time [OK]
Hint: Each character visited max twice -> O(n) [OK]
Common Mistakes:
  • Assuming nested loops cause O(n^2)
  • Confusing hash map average with worst-case
3. The following code attempts to find the maximum sum subarray of size k using the sliding window approach. Identify the line that contains a subtle bug that may cause incorrect results when the array contains all negative numbers.
def max_sum_subarray_sliding_window(arr, k):
    n = len(arr)
    window_sum = sum(arr[:k])
    max_sum = 0
    for i in range(k, n):
        window_sum += arr[i] - arr[i - k]
        if window_sum > max_sum:
            max_sum = window_sum
    return max_sum
medium
A. Line 4: Initializing max_sum to 0 instead of a smaller value.
B. Line 5: Loop starting from index k instead of k-1.
C. Line 3: Initializing window_sum with sum of first k elements.
D. Line 6: Updating window_sum by adding arr[i] and subtracting arr[i - k].

Solution

  1. Step 1: Understand initialization of max_sum

    max_sum is initialized to 0, which is incorrect if all array elements are negative because the maximum sum could be less than 0.
  2. Step 2: Consequence of wrong initialization

    If all sums are negative, max_sum remains 0, which is incorrect. Proper initialization should be max_sum = window_sum (sum of first k elements) or float('-inf').
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    max_sum initialized to 0 causes incorrect max for negative arrays [OK]
Hint: Initialize max_sum to first window sum, not zero [OK]
Common Mistakes:
  • Initializing max_sum to zero instead of first window sum
  • Off-by-one errors in loop indices
  • Incorrect window_sum updates
4. What is the time complexity of the optimized sliding window algorithm that uses filtered characters for the minimum window substring problem, where n is the length of s and m is the length of t?
medium
A. O(n) because each character in s is visited at most twice by the two pointers
B. O(n * m) because for each character in s we check all characters in t
C. O(n + m) because we filter s and then slide over filtered characters
D. O(n^2) because shrinking and expanding the window can cause nested loops

Solution

  1. Step 1: Identify main loops

    The algorithm uses two pointers moving over filtered characters, each pointer advances at most n times.
  2. Step 2: Analyze filtering and counting

    Filtering s takes O(n), sliding window over filtered characters is O(n) since each character is visited twice max.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Two-pointer sliding window is linear time [OK]
Hint: Two pointers each move forward at most n times [OK]
Common Mistakes:
  • Confusing filtering cost
  • Assuming nested loops cause O(n^2)
  • Ignoring that each pointer moves only forward
5. Suppose the problem is modified so that characters in p can be reused multiple times when matching substrings in s (i.e., find substrings in s that can be formed by repeating characters from p any number of times). Which of the following algorithmic changes correctly adapts the sliding window approach?
hard
A. Keep the fixed window size equal to len(p) and use the same frequency matching logic.
B. Sort p and each window substring, then compare sorted strings for equality.
C. Use a variable-size sliding window and check if the window's frequency counts are all less than or equal to p's counts multiplied by the number of repeats.
D. Use a variable-size sliding window and check if all characters in the window appear in p, ignoring counts.

Solution

  1. Step 1: Understand reuse of characters

    Characters in p can be repeated multiple times, so window size is variable and frequency counts can exceed original counts.
  2. Step 2: Adapt sliding window logic

    Use variable-size window and verify window counts do not exceed allowed multiples of p's counts.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Variable window and count comparison with multiples handles reuse correctly [OK]
Hint: Variable window size with count limits handles reuse [OK]
Common Mistakes:
  • Keeping fixed window size
  • Ignoring counts and only checking character presence
  • Sorting substrings repeatedly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard