Problem Description
Given an array where each element represents the value of a card, find the minimum number of consecutive cards you need to pick such that there is at least one pair of matching cards. If there is no way to obtain a pair from any consecutive subarray, return -1.
Key Insights
- Use a hash table (or map) to store the last seen index of each card.
- As you iterate over the array, check if a card has been seen before; if so, calculate the length of the subarray between the previous appearance and the current index.
- Update the minimum length whenever a shorter valid subarray is found.
- The problem can be solved in one pass through the array, ensuring an efficient O(n) time complexity.
Space and Time Complexity
Time Complexity: O(n) - We iterate over the array once. Space Complexity: O(n) - In the worst-case scenario, we store each element's index in the hash table.
Solution
The solution involves iterating through the array using a hash table to record the most recent index when each card value is encountered. If a duplicate card is found, calculate the subarray length (current index - last seen index + 1) and update the minimum length accordingly. After processing, if a valid subarray was found, return its length; otherwise, return -1.