algoadvance

You are given an integer array ranks and a character array suits. You have 5 cards written as ranks[i] and suits[i], where ranks[i] is the rank and suits[i] is the suit of the i-th card. Return the best possible “poker hand” you can make with the given cards.

The “poker hands” are:

  1. “Flush”: Five cards of the same suit.
  2. “Three of a Kind”: Three cards of the same rank.
  3. “Pair”: Two cards of the same rank.
  4. “High Card”: Any single card.

Clarifying Questions

  1. Can we assume that the input will always consist of exactly 5 cards?
  2. Are the card ranks guaranteed to be within a certain range (e.g., 1 to 13)?
  3. Can the input suit characters be guaranteed to be valid (e.g., ‘a’, ‘b’, etc.)?

Assuming the answers to these questions align with reasonable constraints and expected game rules:

  1. Yes, exactly 5 cards.
  2. Yes, ranks between 1 and 13.
  3. Yes, valid suit characters.

Strategy

  1. Check for “Flush”: If all suits in the suits array are the same, return “Flush”.
  2. Count Ranks: Use a dictionary to count the occurrences of each rank.
    • If any rank occurs exactly 3 times, return “Three of a Kind”.
    • If any rank occurs exactly 2 times, return “Pair”.
  3. If none of the conditions are met, return “High Card”.

Time Complexity

The time complexity of this approach is O(1) because we are working with a fixed number of 5 cards, regardless of the operations we perform (iterating over the cards, counting, etc.)

Code

def bestHand(ranks, suits):
    from collections import Counter

    # Check for Flush
    if len(set(suits)) == 1:
        return "Flush"

    # Count the frequency of each rank
    rank_count = Counter(ranks)

    # Check for Three of a Kind and Pair
    if 3 in rank_count.values():
        return "Three of a Kind"
    elif 2 in rank_count.values():
        return "Pair"
    
    # If no special hands are found, return High Card
    return "High Card"

# Example usage
ranks = [10, 10, 2, 12, 9]
suits = ['a', 'a', 'a', 'a', 'a']
print(bestHand(ranks, suits))  # Output: "Flush"

ranks = [10, 10, 2, 12, 9]
suits = ['a', 'b', 'c', 'd', 'e']
print(bestHand(ranks, suits))  # Output: "Pair"

ranks = [10, 10, 10, 12, 9]
suits = ['a', 'b', 'c', 'd', 'e']
print(bestHand(ranks, suits))  # Output: "Three of a Kind"

ranks = [1, 2, 3, 4, 5]
suits = ['a', 'b', 'c', 'd', 'e']
print(bestHand(ranks, suits))  # Output: "High Card"

This code first checks for a Flush, then uses a Counter to tally rank occurrences and determine the best possible hand from the given cards.

Try our interview co-pilot at AlgoAdvance.com