Problem Description
Given five cards represented by an integer array ranks and a character array suits, determine the best poker hand you can form. The available hands, ranked from best to worst, are "Flush" (all cards having the same suit), "Three of a Kind" (three cards with the same rank), "Pair" (two cards with the same rank), and "High Card" (none of the above).
Key Insights
- Check if all cards have the same suit to determine a "Flush".
- Use a hash table (or dictionary) to count the frequency of each rank.
- If any rank appears three or more times, the best hand is "Three of a Kind".
- If not, but a rank appears twice, the best hand is "Pair".
- Otherwise, the best hand is "High Card".
Space and Time Complexity
Time Complexity: O(n) where n = 5 (constant time practically) Space Complexity: O(1) since the additional storage for counting ranks is bounded by the number of unique ranks
Solution
The solution uses the following approach:
- Use a loop to check if all elements in the suits array are the same; if yes, return "Flush".
- Use a hash table to count the occurrences of each rank.
- Check the hash table for any rank count that is at least three; if found, return "Three of a Kind".
- If no triple exists but a pair is found (i.e., any rank count is at least two), return "Pair".
- If none of the above conditions are met, return "High Card".