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.
1function getHint(secret, guess) {
2 let bulls = 0;
3 let cows = 0;
4 const secretCount = new Array(10).fill(0);
5 const guessCount = new Array(10).fill(0);
6
7 for (let i = 0; i < secret.length; i++) {
8 if (secret[i] === guess[i]) {
9 bulls++;
10 } else {
11 secretCount[secret[i]]++;
12 guessCount[guess[i]]++;
13 }
14 }
15
16 for (let i = 0; i < 10; i++) {
17 cows += Math.min(secretCount[i], guessCount[i]);
18 }
19
20 return `${bulls}A${cows}B`;
21}
This JavaScript solution employs arrays to maintain the counts of unmatched digits. The second loop finds where these counts overlap, contributing to the cow count, and the result string is built using template literals.
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).
1#include <iostream>
#include <unordered_map>
#include <string>
#include <sstream>
std::string getHint(std::string secret, std::string guess) {
int bulls = 0, cows = 0;
std::unordered_map<char, int> map;
for (size_t i = 0; i < secret.length(); i++) {
if (secret[i] == guess[i]) {
bulls++;
} else {
if (map[secret[i]] < 0) cows++;
if (map[guess[i]] > 0) cows++;
map[secret[i]]++;
map[guess[i]]--;
}
}
return std::to_string(bulls) + "A" + std::to_string(cows) + "B";
}
The C++ solution uses an unordered map for managing digit counts during misalignments, providing flexibility for each character comparison and adjustment in a single pass.