Leetcode 2347. Best Poker Hand
Alice has a hand of 5 cards, which might only contain integers from 1 to 13 (inclusive). The cards can be represented as an integer array where each value represents the card’s face value.
Alice needs to determine the best possible poker hand that can be made with these 5 cards.
The possible poker hands are:
Write a function to determine the best poker hand Alice can have.
Example:
Input: cards = [4,4,4,4,5]
Output: "Four of a Kind"
Input: cards = [10,10,10,4,4]
Output: "Full House"
import java.util.HashMap;
import java.util.Map;
public class BestPokerHand {
public String bestHand(int[] cards) {
Map<Integer, Integer> countMap = new HashMap<>();
for (int card : cards) {
countMap.put(card, countMap.getOrDefault(card, 0) + 1);
}
boolean hasThree = false, hasPair = false;
int pairs = 0;
for (int count : countMap.values()) {
if (count == 4) {
return "Four of a Kind";
} else if (count == 3) {
hasThree = true;
} else if (count == 2) {
hasPair = true;
pairs++;
}
}
if (hasThree && hasPair) {
return "Full House";
} else if (hasThree) {
return "Three of a Kind";
} else if (pairs == 2) {
return "Two Pair";
} else if (pairs == 1) {
return "Pair";
}
return "High Card";
}
public static void main(String[] args) {
BestPokerHand pokerHand = new BestPokerHand();
System.out.println(pokerHand.bestHand(new int[]{4, 4, 4, 4, 5})); // Four of a Kind
System.out.println(pokerHand.bestHand(new int[]{10, 10, 10, 4, 4})); // Full House
System.out.println(pokerHand.bestHand(new int[]{2, 4, 4, 5, 6})); // Pair
System.out.println(pokerHand.bestHand(new int[]{1, 2, 3, 4, 5})); // High Card
}
}
The time complexity of this solution is O(n), where n is the number of cards. Given that n is always 5 in this problem, our algorithm runs in constant time, O(1).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?