We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Best Poker Hand

Number: 2433

Difficulty: Easy

Paid? No

Companies: Apple, Amazon


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:

  1. Use a loop to check if all elements in the suits array are the same; if yes, return "Flush".
  2. Use a hash table to count the occurrences of each rank.
  3. Check the hash table for any rank count that is at least three; if found, return "Three of a Kind".
  4. If no triple exists but a pair is found (i.e., any rank count is at least two), return "Pair".
  5. If none of the above conditions are met, return "High Card".

Code Solutions

# Function to determine the best poker hand
def best_poker_hand(ranks, suits):
    # Check if all suits are the same for a "Flush"
    if len(set(suits)) == 1:
        return "Flush"
    
    # Dictionary to count frequency of each rank
    rank_count = {}
    for rank in ranks:
        # Increase the count for the rank
        rank_count[rank] = rank_count.get(rank, 0) + 1
    
    # Check for "Three of a Kind"
    for count in rank_count.values():
        if count >= 3:
            return "Three of a Kind"
    
    # Check for "Pair"
    for count in rank_count.values():
        if count == 2:
            return "Pair"
    
    # If none of the conditions met, return "High Card"
    return "High Card"

# Example Usage:
# ranks = [13,2,3,1,9]
# suits = ["a", "a", "a", "a", "a"]
# print(best_poker_hand(ranks, suits))  # Output: "Flush"
← Back to All Questions