algoadvance

Leetcode 299. Bulls and Cows

Problem Statement

You are playing the Bulls and Cows game with your friend.

You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:

Given the secret number and your friend’s guess, return the hint in the format xAyB where x is the number of bulls and y is the number of cows.

Note:

Clarifying Questions:

  1. Should we check for any invalid input or can we consider the inputs are always valid?
    • Assume the inputs are always valid.
  2. What should be the format of the output string?
    • The format should be xAyB where x is the number of bulls and y is the number of cows.

Strategy:

  1. Initialize two counters - one for bulls, one for cows.
  2. Use two arrays (or hash maps) to keep track of the frequency of digits in the secret and the guess that are not bulls.
  3. Iterate through both strings simultaneously:
    • If the characters match, increment the bulls counter.
    • If the characters don’t match, update the frequency counts for both secret and guess.
  4. After the first pass through the strings, for each digit (0-9), the potential cows can be determined by the minimum of the frequency counts in secret and guess.
  5. Construct the result string in the format xAyB.

Time Complexity:

Code:

#include <string>
#include <vector>
#include <algorithm>

std::string getHint(std::string secret, std::string guess) {
    int bulls = 0, cows = 0;
    std::vector<int> secretFrequency(10, 0), guessFrequency(10, 0);

    // First pass to count bulls and record frequencies
    for (int i = 0; i < secret.size(); ++i) {
        if (secret[i] == guess[i]) {
            ++bulls;
        } else {
            ++secretFrequency[secret[i] - '0'];
            ++guessFrequency[guess[i] - '0'];
        }
    }

    // Count cows
    for (int i = 0; i < 10; ++i) {
        cows += std::min(secretFrequency[i], guessFrequency[i]);
    }

    return std::to_string(bulls) + "A" + std::to_string(cows) + "B";
}

In the code:

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