Best Poker Hand
Problem
You are dealt 5 playing cards. Each card has a rank (an integer from 1 to 13) and a suit (one of four letters). Return the name of the best hand you can make, ranked from strongest to weakest: "Flush" if all five suits are the same, "Three of a Kind" if some rank appears at least three times, "Pair" if some rank appears exactly twice, otherwise "High Card".
ranks = [13, 2, 3, 1, 9], suits = ["a", "a", "a", "a", "a"]"Flush"def best_hand(ranks, suits):
if len(set(suits)) == 1:
return "Flush"
counts = {}
for r in ranks:
counts[r] = counts.get(r, 0) + 1
most = max(counts.values())
if most >= 3:
return "Three of a Kind"
if most == 2:
return "Pair"
return "High Card"
function bestHand(ranks, suits) {
if (new Set(suits).size === 1) return "Flush";
const counts = new Map();
for (const r of ranks) counts.set(r, (counts.get(r) || 0) + 1);
let most = 0;
for (const c of counts.values()) most = Math.max(most, c);
if (most >= 3) return "Three of a Kind";
if (most === 2) return "Pair";
return "High Card";
}
class Solution {
public String bestHand(int[] ranks, char[] suits) {
Set<Character> uniq = new HashSet<>();
for (char s : suits) uniq.add(s);
if (uniq.size() == 1) return "Flush";
Map<Integer, Integer> counts = new HashMap<>();
for (int r : ranks) counts.merge(r, 1, Integer::sum);
int most = 0;
for (int c : counts.values()) most = Math.max(most, c);
if (most >= 3) return "Three of a Kind";
if (most == 2) return "Pair";
return "High Card";
}
}
string bestHand(vector<int>& ranks, vector<char>& suits) {
unordered_set<char> uniq(suits.begin(), suits.end());
if (uniq.size() == 1) return "Flush";
unordered_map<int, int> counts;
for (int r : ranks) counts[r]++;
int most = 0;
for (auto& p : counts) most = max(most, p.second);
if (most >= 3) return "Three of a Kind";
if (most == 2) return "Pair";
return "High Card";
}
Explanation
The hand types are ranked, so we just check them from strongest to weakest and return the first one that fits.
Flush first. A flush only cares about suits: if all five cards share one suit, nothing beats it, so we return "Flush" immediately. The quickest test is to drop the suits into a set and see if the set has size 1.
Then count the ranks. If it is not a flush, the answer depends on how often the most common rank appears. We tally the ranks in a hash map (rank → how many times it shows up) and take the largest tally, call it most.
If most is 3 or more, some rank repeats at least three times, giving "Three of a Kind". If most is exactly 2, the best repeat is a single pair, so "Pair". If every rank is unique (most is 1), there is nothing to combine, so "High Card".
Example: ranks = [13, 2, 3, 1, 9], suits = ["a","a","a","a","a"]. All suits are "a", so the suit set is just {a} — size 1 — and we return "Flush" without ever counting the ranks.