Best Poker Hand — LeetCode 2347 Python Solution

EasyArrayHash TableCounting
Problem
#2347
Pattern
Hash Map
Reading time
2 min

The problem

You are given an integer array ranks and a character array suits. You have 5 cards where the ith card has a rank of ranks[i] and a suit of suits[i].

Example

Input
ranks = [13,2,3,1,9], suits = ["a","a","a","a","a"]
Output
"Flush"
Explanation
The hand with all the cards consists of 5 cards with the same suit, so we have a "Flush".

Python solution

Python
class Solution:
    def bestHand(self, ranks: List[int], suits: List[str]) -> str:
        # if len(set(suits)) == 1:
        if all(a == b for a, b in pairwise(suits)):
            return 'Flush'
        cnt = Counter(ranks)
        if any(v >= 3 for v in cnt.values()):
            return 'Three of a Kind'
        if any(v == 2 for v in cnt.values()):
            return 'Pair'
        return 'High Card'

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2347. Best Poker Hand is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2347. Best Poker Hand?
LeetCode 2347. Best Poker Hand is rated Easy on LeetCode.
What is the time complexity of LeetCode 2347. Best Poker Hand?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2347. Best Poker Hand?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2347. Best Poker Hand cover?
LeetCode 2347. Best Poker Hand is tagged Array, Hash Table and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview