Two pass python solution, O(n), one pass for bulls, one pass for cows


  • 0
    A
    class Solution(object):
    def getHint(self, secret, guess):
        """
        :type secret: str
        :type guess: str
        :rtype: str
        """
        from collections import Counter
        secret_map = Counter(secret)
        bulls = 0,cows = 0
        for i, j in zip(secret, guess):
            if i == j:
                bulls += 1
                secret_map[i] -= 1
        
        for i, j in zip(secret, guess):
            if i != j and j in secret_map and secret_map[j] >= 1:
                cows += 1
                secret_map[j] -= 1
        return str(bulls) + 'A' + str(cows) + 'B'

Log in to reply
 

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