Similar Problems

Similar Problems not available

Minimum Consecutive Cards To Pick Up - Leetcode Solution

Companies:

LeetCode:  Minimum Consecutive Cards To Pick Up Leetcode Solution

Difficulty: Medium

Topics: sliding-window hash-table array  

The Minimum Consecutive Cards To Pick Up problem on leetcode is a simple problem that can be solved using sliding window technique. The problem statement is as follows:

Given an array of numbers representing the face values of a deck of cards, find the minimum number of consecutive cards that need to be picked up to make sure that no two cards of the same value are picked up.

For example, if the input is [1, 2, 3, 4, 4, 3, 2, 1], the minimum number of cards to pick up is 4 because we can pick up the cards at index 2, 3, 4, and 5 to make sure that no two 4's are picked up.

One way to approach this problem is to iterate through the array, keeping track of the frequency of each card. When we encounter a card that we have already seen, we can start a new subarray and continue counting until we reach a card that we haven't seen before. At that point, we can compare the length of the subarray with the current minimum and update it if necessary.

Here is a Python code implementation of this approach:

def findMinCards(arr):
    freq = {}
    ans = len(arr)
    lo = 0
    for hi in range(len(arr)):
        freq[arr[hi]] = freq.get(arr[hi], 0) + 1
        while len(freq.keys()) < hi - lo + 1:
            freq[arr[lo]] -= 1
            if freq[arr[lo]] == 0:
                del freq[arr[lo]]
            lo += 1
        if len(freq.keys()) == hi - lo + 1:
            ans = min(ans, hi - lo + 1)
    return ans

The time complexity of this algorithm is O(n), where n is the length of the input array. The space complexity is O(n) as well, due to the use of a dictionary to maintain the frequency of each card.

To test the function, we can pass in the example input [1, 2, 3, 4, 4, 3, 2, 1] as follows:

print(findMinCards([1, 2, 3, 4, 4, 3, 2, 1]))  # Output: 4

In this example, the minimum number of consecutive cards to pick up is 4, as we mentioned earlier.

Minimum Consecutive Cards To Pick Up Solution Code

1