O(n) Intuitive Javascript Solution


  • 0
    S
    /**
     * @param {string} secret
     * @param {string} guess
     * @return {string}
     */
    var getHint = function(secret, guess) {
        var len = secret.length;
        var bull = 0;
        var cow = 0;
        var i;
        var secretArr = secret.split("").map(function(e) { return Number.parseInt(e); });
        var guessArr = guess.split("").map(function(e) { return Number.parseInt(e); });
    
        for(i = 0; i < len;){
            if(secretArr[i] === guessArr[i]){
                bull += 1;
                secretArr.splice(i, 1);
                guessArr.splice(i, 1);
                len--;
            } else {
                i++;
            }
        }
        
        for(i = 0; i < guessArr.length; i++){
            if(secretArr.indexOf(guessArr[i]) > -1){
                cow++;
                secretArr.splice(secretArr.indexOf(guessArr[i]), 1);
            }
        }
        
        return bull+'A'+cow+'B';
    };
    

  • 0

    @superdtx share my solution . beats 94%

    var getHint = function(secret, guess) {
        let bull = 0;
        let cow = 0;
        const hashMap = {};
        for (var i = 0, l = secret.length; i < l; i++) {
            if (secret[i] === guess[i]) {
                bull++;
            }
        }
        for (i = 0, l = secret.length; i < l; i++) {
            if (!hashMap[secret[i]]) {
                hashMap[secret[i]] = 1;
            } else {
                hashMap[secret[i]]++;
            }
        }
        for (i = 0, l = guess.length; i < l; i++) {
            if (hashMap[guess[i]]) {
                hashMap[guess[i]]--;
                cow++;
            }
        }
        return bull + 'A' + (cow - bull) + 'B';
    };
    

Log in to reply
 

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