--- tags: leetcode --- # [299. Bulls and Cows](https://leetcode.com/problems/bulls-and-cows/) --- # My Solution ## The Key Idea for Solving This Coding Question ## C++ Code ```cpp= #define MATCHED ('x') class Solution { public: string getHint(string secret, string guess) { vector<int> digitCnt(10, 0); int bullCnt = 0; for (int i = 0; i < secret.size(); ++i) { if (secret[i] == guess[i]) { ++bullCnt; guess[i] = MATCHED; } else { ++digitCnt[secret[i] - '0']; } } int cowCnt = 0; for (int i = 0; i < guess.size(); ++i) { if (guess[i] != MATCHED && digitCnt[guess[i] - '0'] > 0) { // guess[i] is in secret, but not located at the // correct position. ++cowCnt; --digitCnt[guess[i] - '0']; } } return to_string(bullCnt) + "A" + to_string(cowCnt) + "B"; } }; ``` ## Time Complexity $O(n)$ $n$ is the length of `secret`. ## Space Complexity $O(1)$ # Miscellane <!-- # Test Cases ``` "1807" "7810" ``` ``` "1123" "0111" ``` ``` "1" "0" ``` ``` "1" "1" ``` ``` "1234" "0111" ``` ``` "11" "10" ``` ``` "1122" "2211" ``` ``` "1234" "4321" ``` ``` "1234" "5678" ``` -->