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:
Assuming the answers to these questions align with reasonable constraints and expected game rules:
suits
array are the same, return “Flush”.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.)
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.
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?