Skip to main content
Back to problems
#299
Medium Algorithms

Bulls and cows

Hash Table String Counting
52.2% acceptance
Jan 12, 2026
2620
1815
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: The number of "bulls", which are digits in the guess that are in the correct position. The number of "cows", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls. Given the secret number secret and your friend's guess guess, return the hint for your friend's guess. The hint should be formatted as "xAyB", where x is the number of bulls and y is the number of cows. Note that both secret and guess may contain duplicate digits.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn get_hint(secret: String, guess: String) -> String {
    let mut bulls = 0;
    let mut cows = 0;
    let mut secret_counts = [0; 10];
    let mut guess_counts = [0; 10];
    
    let secret_bytes = secret.as_bytes();
    let guess_bytes = guess.as_bytes();
    
    for i in 0..secret_bytes.len() {
      let s = (secret_bytes[i] - b'0') as usize;
      let g = (guess_bytes[i] - b'0') as usize;
      
      if s == g {
        bulls += 1;
      } else {
        secret_counts[s] += 1;
        guess_counts[g] += 1;
      }
    }
    
    for i in 0..10 {
      cows += secret_counts[i].min(guess_counts[i]);
    }
    
    format!("{}A{}B", bulls, cows)
  }
}