algoadvance

Leetcode 2347. Best Poker Hand

Problem Statement

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:

  1. “Flush”: Five cards of the same suit.
  2. “Three of a Kind”: Three cards of the same rank.
  3. “Pair”: Two cards of the same rank.
  4. “High Card”: Any single card.

Clarifying Questions

  1. Input Size: Is the input size always 5 cards?
    • Yes, the input size is always exactly 5 cards.
  2. Rank Range: What is the range of card ranks?
    • Card ranks range from 1 to 13.
  3. Suit Range: What are the possible values for the suits?
    • The suits can be ‘A’, ‘B’, ‘C’, or ‘D’.
  4. Output Format: What should the output be?
    • The output should be a string representing the best possible hand: “Flush”, “Three of a Kind”, “Pair”, or “High Card”.

Strategy

  1. Check for Flush: All 5 cards need to have the same suit.
  2. Check for Three of a Kind: Any rank should appear at least 3 times.
  3. Check for Pair: Any rank should appear at least 2 times.
  4. If None of the Above: Return “High Card”.

Code

#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";
}

Time Complexity

Overall, the time complexity is O(1), which is efficient given the fixed input size.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI