Sponsored
Sponsored
The idea is to first determine the number of bulls by comparing characters at the same position in both the secret and the guess. In the first pass over the strings, count all bulls and track unmatched characters using two separate frequency arrays. In the second pass, use the frequency arrays to compute the number of cows by checking the minimum frequency of each character in unmatched parts.
Time Complexity: O(n), Space Complexity: O(1), where n is the length of the secret or guess.
1def getHint(secret: str, guess: str) -> str:
2 bulls = 0
3 cows = 0
4 secret_count = [0] * 10
5 guess_count = [0] * 10
6
7 for s, g in zip(secret, guess):
8 if s == g:
9 bulls += 1
10 else:
11 secret_count[int(s)] += 1
12 guess_count[int(g)] += 1
13
14 for sc, gc in zip(secret_count, guess_count):
15 cows += min(sc, gc)
16
17 return f"{bulls}A{cows}B"
In the Python solution, the zip
function efficiently pairs characters from secret
and guess
for comparison. A second loop then determines the number of potential cow matches.
Instead of performing two separate passes, this method uses a hashmap (or dictionary) to update the unmatched digits' count as it checks for bulls and non-bulls in a single iteration over the inputs. It utilizes incremental checking for cows during the mismatched segments.
Time Complexity: O(n), Space Complexity: O(1).
1public class Solution {
2 public string GetHint(string secret, string guess) {
int bulls = 0, cows = 0;
int[] map = new int[10];
for (int i = 0; i < secret.Length; i++) {
if (secret[i] == guess[i]) {
bulls++;
} else {
if (map[secret[i] - '0'] < 0) cows++;
if (map[guess[i] - '0'] > 0) cows++;
map[secret[i] - '0']++;
map[guess[i] - '0']--;
}
}
return bulls + "A" + cows + "B";
}
}
This C# solution uses an array for mapping digits. The key operation is simultaneous counting for potential cow adjustment upon mismatched digits.