Skip to content

Commit a12ace4

Browse files
committed
added another problem
1 parent dbfa9d3 commit a12ace4

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.thealgorithms.slidingwindow;
2+
3+
import java.util.HashMap;
4+
5+
/**
6+
* The MinimumConsecutiveCards algorithm finds the minimum number of consecutive cards
7+
* that need to be picked up to get a pair of the same card.
8+
*
9+
* <p>
10+
* Worst-case performance O(n)
11+
* Best-case performance O(n)
12+
* Average performance O(n)
13+
* Worst-case space complexity O(n)
14+
*
15+
* @author (https://github.com/Chiefpatwal)
16+
*/
17+
public final class MinimumConsecutiveCards {
18+
19+
// Prevent instantiation
20+
private MinimumConsecutiveCards() {
21+
}
22+
23+
/**
24+
* This method finds the minimum number of consecutive cards needed to be picked up
25+
* to get a pair of the same card.
26+
*
27+
* @param cards an array of integers representing card numbers
28+
* @return the minimum number of consecutive cards to pick up, or -1 if no pairs exist
29+
*/
30+
public static int minimumCardPickup(int[] cards) {
31+
HashMap<Integer, Integer> cardIndexMap = new HashMap<>();
32+
int minLength = Integer.MAX_VALUE;
33+
34+
for (int i = 0; i < cards.length; i++) {
35+
if (cardIndexMap.containsKey(cards[i])) {
36+
int prevIndex = cardIndexMap.get(cards[i]);
37+
minLength = Math.min(minLength, i - prevIndex + 1);
38+
}
39+
cardIndexMap.put(cards[i], i);
40+
}
41+
42+
return minLength == Integer.MAX_VALUE ? -1 : minLength;
43+
}
44+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.thealgorithms.slidingwindow;
2+
3+
import org.junit.jupiter.api.Test;
4+
import static org.junit.jupiter.api.Assertions.assertEquals;
5+
6+
/**
7+
* Unit tests for the MinimumConsecutiveCards class.
8+
*
9+
* @author (https://github.com/Chiefpatwal)
10+
*/
11+
public class MinimumConsecutiveCardsTest {
12+
13+
@Test
14+
public void testMinimumCardPickup() {
15+
// Test cases for the minimumCardPickup method
16+
assertEquals(2, MinimumConsecutiveCards.minimumCardPickup(new int[]{1, 2, 3, 2, 4, 1}));
17+
assertEquals(-1, MinimumConsecutiveCards.minimumCardPickup(new int[]{1, 2, 3, 4, 5}));
18+
assertEquals(2, MinimumConsecutiveCards.minimumCardPickup(new int[]{1, 1, 1, 1}));
19+
assertEquals(2, MinimumConsecutiveCards.minimumCardPickup(new int[]{2, 2, 3, 4, 5}));
20+
}
21+
}

0 commit comments

Comments
 (0)