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.
1public class Solution {
2 public string GetHint(string secret, string guess) {
3 int bulls = 0, cows = 0;
4 int[] secretCount = new int[10];
5 int[] guessCount = new int[10];
6
7 for (int i = 0; i < secret.Length; i++) {
8 if (secret[i] == guess[i]) {
9 bulls++;
10 } else {
11 secretCount[secret[i] - '0']++;
12 guessCount[guess[i] - '0']++;
13 }
14 }
15
16 for (int i = 0; i < 10; i++) {
17 cows += Math.Min(secretCount[i], guessCount[i]);
18 }
19
20 return bulls + "A" + cows + "B";
21 }
22}
This C# implementation uses arrays to perform character counting for unmatched characters. Bulls are counted directly, while cows are parsed through matching counts in unmatched characters.
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).
1function
In JavaScript, an array serves as a frequency map to manage unmatched digits. This approach efficiently updates and uses the frequency counts in one iterative sweep over the data.