Leetcode 2347. Best Poker Hand
You are given an integer array ranks
and a character array suits
. You have 5
cards where the i-th
card has a rank of ranks[i]
and a suit of suits[i]
. Return the best possible “poker hand” that you can play with the given cards.
Here are the types of poker hands you can make, ordered from best to worst:
#include <vector>
#include <unordered_map>
#include <algorithm>
std::string bestHand(std::vector<int>& ranks, std::vector<char>& suits) {
// Check for Flush
if (std::count(suits.begin(), suits.end(), suits[0]) == 5) {
return "Flush";
}
// Count ranks
std::unordered_map<int, int> rank_count;
for (int rank : ranks) {
rank_count[rank]++;
}
// Check for Three of a Kind and Pair
bool three_of_a_kind = false;
bool pair = false;
for (const auto& pair : rank_count) {
if (pair.second >= 3) {
three_of_a_kind = true;
}
if (pair.second >= 2) {
pair = true;
}
}
if (three_of_a_kind) {
return "Three of a Kind";
}
if (pair) {
return "Pair";
}
// If none of the above, return High Card
return "High Card";
}
O(1)
because there are always exactly 5 suits.O(5)
, or O(1)
because the input size is constant. Checking the map also takes O(1)
.Overall, the time complexity is O(1)
, which is efficient given the fixed input size.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?