Best Poker Hand

easy hash map counting

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".

Inputranks = [13, 2, 3, 1, 9], suits = ["a", "a", "a", "a", "a"]
Output"Flush"
All five suits are "a", so the hand is a Flush — the strongest possibility — regardless of the ranks.

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";
}
Time: O(n) Space: O(n)