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.charAt(i) == guess.charAt(i)) {
9 bulls++;
10 } else {
11 secretCount[secret.charAt(i) - '0']++;
12 guessCount[guess.charAt(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 Java solution uses two integer arrays to keep track of the unmatched digits' frequencies. The result string is created by concatenating the counts of bulls and cows.
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).
1def
Python's solution utilizes a list like a hashmap to handle digit tracking. Each character is evaluated for its matching status, allowing cow counting and updating mappings in one pass.