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.
1#include <iostream>
2#include <vector>
3#include <string>
4#include <sstream>
5
6std::string getHint(std::string secret, std::string guess) {
7 int bulls = 0, cows = 0;
8 std::vector<int> secretCount(10, 0), guessCount(10, 0);
9
10 for (size_t i = 0; i < secret.size(); i++) {
11 if (secret[i] == guess[i]) {
12 bulls++;
13 } else {
14 secretCount[secret[i] - '0']++;
15 guessCount[guess[i] - '0']++;
16 }
17 }
18
19 for (int i = 0; i < 10; i++) {
20 cows += std::min(secretCount[i], guessCount[i]);
21 }
22
23 std::ostringstream oss;
24 oss << bulls << "A" << cows << "B";
25 return oss.str();
26}
The C++ solution uses vectors to store digit counts. Similar to the C solution, it separately counts bulls and then compares digit frequencies of unmatched parts to compute 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.