#2347
Best Poker Hand
EasyArrayHash TableCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
In the optimal approach, we will use a single pass to count the ranks and check the suits simultaneously. This reduces the number of checks and improves efficiency.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a counter for ranks and a flag for suits.
- 2Step 2: Traverse through the ranks and suits to populate the rank counter and check if all suits are the same.
- 3Step 3: Determine the best hand based on the counts.
solution.py10 lines
1def bestHand(ranks, suits):
2 suit_check = len(set(suits)) == 1
3 count = Counter(ranks)
4 if suit_check:
5 return 'Flush'
6 if any(v >= 3 for v in count.values()):
7 return 'Three of a Kind'
8 if any(v == 2 for v in count.values()):
9 return 'Pair'
10 return 'High Card'ℹ
Complexity note: The complexity is O(n) because we are only making a single pass through the ranks and suits, counting occurrences and checking conditions simultaneously.
- 1Understanding the hierarchy of poker hands is crucial.
- 2Efficient counting and checking can significantly reduce complexity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.