Leetcode Problem 2260. Minimum Consecutive Cards to Pick Up

2260. Minimum Consecutive Cards to Pick Up

Leetcode Solutions

Using a HashMap to Track the Last Seen Indices of Cards

  1. Initialize a hash map last_seen to store the last seen index of each card value.
  2. Initialize a variable min_length to store the minimum length of a sequence with a matching pair, set it to a large value initially.
  3. Iterate through the cards array with index i. a. If the current card value cards[i] is in last_seen, calculate the length of the sequence as i - last_seen[cards[i]] + 1. b. If the calculated length is less than min_length, update min_length. c. Update last_seen[cards[i]] with the current index i.
  4. After the loop, if min_length is still the initial large value, return -1, indicating no matching pairs were found.
  5. Otherwise, return min_length as the result.
UML Thumbnail

Sliding Window Approach

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...