Minimum Consecutive Cards to Pick Up

Find the shortest run of neighbouring cards that holds two cards with the same value.

Given an integer array cards, where cards[i] is the value of the card at index i, return the smallest number of consecutive cards you must pick up to hold two cards with the same value. Two such cards are called a matching pair. If no value appears twice, return -1.

Example 1
Input: cards = [3, 4, 2, 3, 4, 7]
Output: 4
Explanation: [3, 4, 2, 3] holds two 3s, and [4, 2, 3, 4] holds two 4s. No shorter run holds a matching pair.
Example 2
Input: cards = [1, 0, 5, 3]
Output: -1
Explanation: no value appears twice.
Solution

The Idea

Picture six cards laid face up in a row: 3, 4, 2, 3, 4 and 7. You may pick up any run of cards that sit next to each other, and you want two cards with the same value in your hand. Picking up all six always works if a pair exists at all, but the question is how few cards will do.

Try a few runs from Example 1. The first three cards, 3, 4 and 2, hold no pair. Add the next card and you have 3, 4, 2, 3, with two 3s: four cards. Starting one card later, 4, 2, 3, 4 also holds a pair, with two 4s, and is also four cards long. So which runs are worth measuring, out of all the runs in the row?

Look at the run 3, 4, 2, 3. Its pair sits at its two ends. That is no accident. If a run had extra cards before its first matching card or after its second one, you could put those extra cards back and still hold the pair. So a shortest run always starts at one card of a pair and ends at the other.

That turns the problem around: find the two equal cards that sit closest together, and count the cards from one to the other. Look at the picture below.

The cards 3, 4, 2, 3, 4, 7 at indexes 0 to 5. The 3 at index 3 looks back to the 3 at index 0, a run of 4 cards. The 4 at index 4 looks back to the 4 at index 1, also 4 cards.

Walk along the row from left to right. At index 3 there is a 3, and the bracket above the cards shows where the last 3 was: index 0. From index 0 to index 3 is 3 - 0 + 1 = 4 cards, counting both ends. At index 4 there is a 4, and the bracket below the cards looks back to index 1: again 4 cards. The cards 2 and 7 have no earlier copy, so they give nothing.

So each card only needs one question answered: where did its value last appear? If a value appears three times, the middle copy is always closer to the third one than the first copy is, so older copies never give a shorter run.

Solution Approach

Turning that idea into code means settling three things: which runs to measure, how to find the last copy of a value quickly, and what to return when there is no pair.

Which runs to measure

Why not check every pair of cards? Two loops, one inside the other, can compare each card with every card after it and keep the closest equal pair. For six cards that is 15 comparisons, but for 100,000 cards it is about five billion. Measuring each card only against the last copy of its value needs one pass along the row instead.

The cards from that last copy up to the current card form a run, sometimes called a window, whose two ends hold the same value. The answer is the smallest window found during the pass.

Finding the last copy of a value

How does the pass know where a value last appeared? It keeps a HashMap, a Java table that stores keys with their values and finds a key in one step on average. Here the key is a card value and the stored value is the index where that card value was last seen.

At each card, the code reads the old index and then writes the current index in its place. Map.put does both in one call: it stores the new value and returns the one it replaced, or null if the key was not in the map yet. Overwriting the old index is exactly right, because only the latest copy of a value matters.

When there is no pair

What if no value appears twice? The smallest run so far starts at Integer.MAX_VALUE, the largest int, so any real run is smaller. If it is still Integer.MAX_VALUE after the pass, no pair was found and the method returns -1.

Java Solution

The method minimumCardPickup works in these steps:

  1. First, create the map lastSeen, from card value to the index where that value was last seen, and set best, the shortest run so far, to Integer.MAX_VALUE.
  2. Walk along the cards with one loop over the index i. For each card, call lastSeen.put(cards[i], i), which stores i and returns the index of the previous copy as prev, or null for a value seen for the first time.
  3. When prev is not null, the cards from prev to i hold a pair. Their count is i - prev + 1, and best keeps the smaller of that count and its current value.
  4. After the loop, return -1 if best is still Integer.MAX_VALUE, and best otherwise.

The main method runs both examples, two equal cards side by side, a single card, and the row [1, 2, 1, 1], where one value appears three times.

Java
import java.util.HashMap;
import java.util.Map;

public class MinimumConsecutiveCardsToPickUp {

    public static int minimumCardPickup(int[] cards) {
        Map<Integer, Integer> lastSeen = new HashMap<>();   // card value -> last index
        int best = Integer.MAX_VALUE;
        for (int i = 0; i < cards.length; i++) {
            Integer prev = lastSeen.put(cards[i], i);       // old index, or null
            if (prev != null) {
                best = Math.min(best, i - prev + 1);        // cards prev .. i hold a pair
            }
        }
        return best == Integer.MAX_VALUE ? -1 : best;
    }

    public static void main(String[] args) {
        System.out.println(minimumCardPickup(new int[] {3, 4, 2, 3, 4, 7}));
        System.out.println(minimumCardPickup(new int[] {1, 0, 5, 3}));
        System.out.println(minimumCardPickup(new int[] {7, 7}));
        System.out.println(minimumCardPickup(new int[] {5}));
        System.out.println(minimumCardPickup(new int[] {1, 2, 1, 1}));
    }
}

Running it prints:

Output
4
-1
2
-1
2

The 4 and the -1 at the top match Examples 1 and 2. The third line, 2, comes from [7, 7]: the two 7s sit next to each other, so i - prev + 1 is 1 - 0 + 1 = 2, the smallest answer possible. The single card [5] cannot form a pair, so its line is -1.

Look at the last line. In [1, 2, 1, 1] the value 1 is at indexes 0, 2 and 3. When the loop reaches index 3, lastSeen holds 2 for the value 1, because index 2 overwrote index 0, and the run from 2 to 3 is 2 cards. A version that keeps the first index instead, with putIfAbsent, which stores an index only for a value not yet in the map, measures from index 0 every time and returns 3 for this row.

Complexity

The work is one pass along the cards, with one map call per card.

  • Time: O(n), because the loop visits each of the n cards once and does a single HashMap.put there, which takes one step on average.
  • Space: O(n), because lastSeen holds one entry per different card value, and when no value repeats, all n cards add their own entry.

Remembering the last index of each value is also what lets Longest Substring Without Repeating Characters run in one pass.