Search code examples
pythonarraysstructure

Finding the difference in an array


Here is the link to the original question: https://leetcode.com/problems/find-the-difference/

Here is my code. I keep getting an "index out of range" error but I am not sure why.

class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        i = 0 
        ss = list(s)
        tt = list(t)
        while ss[i] == tt[i]: 
            i += 1 
            if ss[i] != tt[i]:
                return tt[i]

Solution

  • Lets say you give these 2 as inputs

    s = "abcd"
    t = "abcde"
    

    on the 4th circle of your loop i=3 and it will become 4 since ss[i] != tt[i] is false it will go on on the next circle and will evaluate this expression ss[i] == tt[i] and ss's length is 4 and it will try to access the 5th element which doesnt exist and it eventually will throw an indexError you could try something like:

    class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        i = 0 
        ss = list(s)+[None]
        tt = list(t)
        while ss[i] == tt[i]: 
            i += 1 
            if ss[i] != tt[i]:
                return tt[i]