Leetcode 2260: Minimum Consecutive Cards to Pick Up

grid47
grid47
Exploring patterns and algorithms
Mar 26, 2024 5 min read

You are given an array cards where each element represents a card’s value. A matching pair of cards occurs when two cards have the same value. Your task is to find the minimum number of consecutive cards you need to pick to guarantee that you have a pair of matching cards. If it’s impossible to find a matching pair, return -1.
Problem
Approach
Steps
Complexity
Input: The input consists of a list `cards` containing integers where each integer represents the value of a card.
Example: cards = [7, 2, 3, 7, 5, 6]
Constraints:
• 1 <= cards.length <= 105
• 0 <= cards[i] <= 106
Output: Return the minimum number of consecutive cards you need to pick up to have at least one matching pair of cards. If no pair exists, return -1.
Example: Output: 4
Constraints:
Goal: The goal is to find the smallest subarray of consecutive cards that contains at least one pair of matching cards.
Steps:
• Use a hashmap to keep track of the last seen index of each card.
• As you iterate over the cards, check if the current card has been seen before.
• If a match is found, calculate the number of consecutive cards between the current and previous occurrence of the card.
• Keep track of the smallest such subarray length.
Goal: Make sure the solution works within the constraints of large input sizes.
Steps:
• The length of the `cards` array is between 1 and 100,000.
• The card values are between 0 and 1,000,000.
Assumptions:
• The array will contain at least one pair of matching cards, or none at all.
Input: cards = [7, 2, 3, 7, 5, 6]
Explanation: We can pick the cards [7, 2, 3, 7], which contains a matching pair of 7's. Therefore, the minimum number of consecutive cards is 4.

Input: cards = [1, 2, 3, 4]
Explanation: There are no matching cards, so it is impossible to have a pair of matching cards. The output is -1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus