Finding the difference in an array

Viewed 55

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]
4 Answers

According to the question, string t will have length 1 greater than the length of string s. Now imagine what happens when, lets say, string t is formed by appending random character to end of string s.

When you have finished processing all of string s's characters, you will proceed to check the last character of string t, but the character at corresponding index in string s is not present, and that leads to Index Out Of Range

There is a better approach to solve this question, try harder.

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]

Your issue is that you don't stop iterating when you get to the end of the list. If you change your while condition to:

while ss[i] == tt[i] and i < len(ss) and i < len(tt)

you will avoid the IndexError.

Separately, this situation is much better suited for a for loop:

for i in range(min(len(ss), len(tt))):  # Only loop while both lists still have elements
    ...

Maybe your params have a different size.

Like t is abcd and s is aa this is the reason why are you having this issue.

Lets assume that i is 2

ss will be c and tt will throw index out of range

ss[i] == tt[i]

Related