Best Poker Hand — Easy Problem & Solution

You hold five cards. ranks[i] is the i-th card's rank and suits[i] its suit.

Problem statement

You hold five cards. ranks[i] is the i-th card's rank and suits[i] its suit.

Return the best hand you can make, as one of these strings, in decreasing order of strength:

  • "Flush" — all five suits are the same;
  • "Three of a Kind" — three cards share a rank;
  • "Pair" — two cards share a rank;
  • "High Card" — none of the above.

Example 1

Input: ranks = [13,2,3,1,9], suits = ["a","a","a","a","a"]
Output: Flush
Explanation: All five cards share a suit.

Example 2

Input: ranks = [4,4,2,4,4], suits = ["d","a","a","b","c"]
Output: Three of a Kind
Explanation: Four 4s, which still reports as three of a kind.

Example 3

Input: ranks = [10,10,2,12,9], suits = ["a","b","c","a","d"]
Output: Pair

Constraints

  • ranks.length == suits.length == 5
  • 1 <= ranks[i] <= 13
  • suits[i] is one of 'a', 'b', 'c', 'd'

How to solve Best Poker Hand

Test the categories in order of strength. A flush depends only on the suits; everything below it depends only on the largest number of cards sharing a rank.

Approach

  1. If every suit equals the first, return "Flush".
  2. Tally the ranks and take the largest count.
  3. At least 3 → "Three of a Kind"; exactly 2 → "Pair"; otherwise "High Card".

Why it works

The categories are strictly ordered, so returning the first that matches gives the best hand. Four of a kind is not a listed category, which is why the test is >= 3 rather than == 3 — a hand with four equal ranks is reported as three of a kind.

Complexity

  • Time — O(1)
  • Space — O(1)

Pitfalls

  • Testing for a pair before three of a kind reports the weaker hand.
  • Using == 3 misclassifies four of a kind as "High Card".
  • A flush takes precedence even when the ranks also form a pair.

Reference solution

Python

from typing import List

def bestHand(ranks: List[int], suits: List[str]) -> str:
    if all(s == suits[0] for s in suits):
        return "Flush"
    cnt = {}
    for r in ranks:
        cnt[r] = cnt.get(r, 0) + 1
    best = max(cnt.values())
    if best >= 3:
        return "Three of a Kind"
    if best == 2:
        return "Pair"
    return "High Card"

JavaScript

var bestHand = function(ranks, suits) {
    var same = true;
    for (var i = 1; i < suits.length; i++) {
        if (suits[i] !== suits[0]) { same = false; break; }
    }
    if (same) return "Flush";
    var cnt = {}, best = 0;
    for (var j = 0; j < ranks.length; j++) {
        cnt[ranks[j]] = (cnt[ranks[j]] || 0) + 1;
        if (cnt[ranks[j]] > best) best = cnt[ranks[j]];
    }
    if (best >= 3) return "Three of a Kind";
    if (best === 2) return "Pair";
    return "High Card";
};

Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 667 arrays problems · the whole catalogue