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 <stdio.h>
2#include <string.h>
3
4char* getHint(char* secret, char* guess) {
5 static char hint[10];
6 int bulls = 0, cows = 0;
7 int secretCount[10] = {0}, guessCount[10] = {0};
8 int length = strlen(secret);
9
10 for (int i = 0; i < length; 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 += secretCount[i] < guessCount[i] ? secretCount[i] : guessCount[i];
21 }
22
23 sprintf(hint, "%dA%dB", bulls, cows);
24 return hint;
25}
In this C solution, two integer arrays secretCount
and guessCount
are used to count how many times each digit appears in the unmatched parts of secret
and guess
. After counting bulls and populating these arrays in the first loop, the second loop calculates cows by summing the minimum of matched counts in secretCount
and guessCount
.
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
This C function uses a single-pass approach with an array used as a hashmap to track digits. When encountering a mismatch, it checks and updates the hashmap to calculate cows immediately.