LeetCode 2347: Best Poker Hand Solution
Master LeetCode problem 2347 (Best Poker Hand), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2347. Best Poker Hand
Problem Explanation
Explanation
To solve this problem, we need to determine the best possible poker hand from the given cards. We can achieve this by iterating through the ranks and suits arrays to count the occurrences of each rank and suit. Based on these counts, we can identify the best hand as per the specified order of poker hands.
- Count the occurrences of each rank and suit.
- Check for a "Flush" by verifying if all cards have the same suit.
- Check for a "Three of a Kind" by finding if any rank occurs three times.
- Check for a "Pair" by identifying if any rank occurs twice.
- Return the best possible hand based on the above checks.
Time Complexity: O(1) - Since we are dealing with a fixed number of cards (5 cards) and ranks (1 to 13), the time complexity is constant. Space Complexity: O(1) - The space used is constant regardless of the input size.
Solution Code
class Solution {
public String bestPokerHand(int[] ranks, char[] suits) {
int[] rankCount = new int[14];
int[] suitCount = new int[4];
for (int i = 0; i < 5; i++) {
rankCount[ranks[i]]++;
suitCount[suits[i] - 'a']++;
}
boolean isFlush = suitCount[suits[0] - 'a'] == 5;
boolean isThreeOfAKind = false;
boolean isPair = false;
for (int i = 1; i <= 13; i++) {
if (rankCount[i] == 3) {
isThreeOfAKind = true;
} else if (rankCount[i] == 2) {
isPair = true;
}
}
if (isFlush) {
return "Flush";
} else if (isThreeOfAKind) {
return "Three of a Kind";
} else if (isPair) {
return "Pair";
} else {
return "High Card";
}
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2347 (Best Poker Hand)?
This page provides optimized solutions for LeetCode problem 2347 (Best Poker Hand) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2347 (Best Poker Hand)?
The time complexity for LeetCode 2347 (Best Poker Hand) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2347 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2347 in Java, C++, or Python.