3 Different Python Solutions (Dictionary, Difference, XOR)


  • 16
    class Solution(object):
        """
        dictionary
        """
        def findTheDifference(self, s, t):
            dic = {}
            for ch in s:
                dic[ch] = dic.get(ch, 0) + 1
            for ch in t:
                if dic.get(ch, 0) == 0:
                    return ch
                else:
                    dic[ch] -= 1
    
    class Solution(object):
        """
        difference
        """
        def findTheDifference(self, s, t):
            diff = 0
            for i in range(len(s)):
                diff -= ord(s[i])
                diff += ord(t[i])
            diff += ord(t[-1])
            return chr(diff)
    
    class Solution(object):
        """
        xor
        """
        def findTheDifference(self, s, t):
            code = 0
            for ch in s + t:
                code ^= ord(ch)
            return chr(code)
    

  • 0

    I enjoyed seeing the different ways you solved this problem, thanks!

    I solved this problem using collections.Counter.

    from collections import Counter
    
    
    class Solution(object):
        def findTheDifference(self, s, t):
            return (Counter(t) - Counter(s)).popitem()[0]
    
    

  • 0

    xor always surprises me.


  • 0
    B

    The XOR solution goes even faster (42 ms, beats 96% now) if you don't add the s and t lists:

    class Solution(object):
        """
        xor
        """
        def findTheDifference(self, s, t):
            code = 0
            for ch in s:
                code ^= ord(ch)
            for ch in t:
                code ^= ord(ch)
            return chr(code)
    

Log in to reply
 

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