C++ bucket sort to find cows


  • 0
    X
    class Solution {
    public:
        string getHint(string secret, string guess) {
            int sz = secret.length(); 
            if(sz < 1) return "0A0B"; 
            
    /*===============================================================================================
        V 1.0 : for-loop string looking for bulls, use bucket save for cows
        Time:   O(n), Space:  O(1)
    *///=============================================================================================
            int bulls = 0, cows = 0;
            vector<char> secretNumFreq(10,0); 
            
            for(int i = 0; i < sz; i++){
                if(secret[i] == guess[i]) {
                    bulls++;
                    guess[i] = '-'; // mark it as checked.
                }
                else {
                    int getNumSec = secret[i] - '0'; 
                    secretNumFreq[getNumSec]++; 
                }
            }
            for(int i = 0; i < sz; i++){ // check cows
                if(guess[i]=='-') continue; // jump over the bulls
                
                int getNumGue = guess[i] - '0'; 
                if(secretNumFreq[getNumGue] > 0){ 
                    cows += 1;
                    secretNumFreq[getNumGue] -= 1; 
                }
            }
            return to_string(bulls) + "A" + to_string(cows) + "B"; 
    
            
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.