Skip to content

2347. Best Poker Hand 👍

  • Time: $O(|\texttt{ranks}| + |\texttt{suits}|)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  string bestHand(vector<int>& ranks, vector<char>& suits) {
    if (ranges::all_of(suits,
                       [&suits](const char suit) { return suit == suits[0]; }))
      return "Flush";

    constexpr int kMax = 13;
    vector<int> count(kMax + 1);

    for (const int rank : ranks)
      ++count[rank];

    const int mx = ranges::max(count);
    if (mx > 2)
      return "Three of a Kind";
    if (mx == 2)
      return "Pair";
    return "High Card";
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public String bestHand(int[] ranks, char[] suits) {
    if (new String(suits).chars().allMatch(s -> s == suits[0]))
      return "Flush";

    final int kMax = 13;
    int[] count = new int[kMax + 1];

    for (final int rank : ranks)
      ++count[rank];

    final int mx = Arrays.stream(count).max().getAsInt();
    if (mx > 2)
      return "Three of a Kind";
    if (mx == 2)
      return "Pair";
    return "High Card";
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def bestHand(self, ranks: list[int], suits: list[str]) -> str:
    if all(suit == suits[0] for suit in suits):
      return 'Flush'

    match max(Counter(ranks).values()):
      case 5 | 4 | 3:
        return 'Three of a Kind'
      case 2:
        return 'Pair'
      case _:
        return 'High Card'