Python-Two sum-bug in code-accepted


  • 0
    P

    First, nums is mutated and stored in num2,which is then sorted.
    After this, num2 is bisected and the program works with elements that are smaller than the target

    The grader threw an error for the following test case:
    twoSum([-3,4,3,90], 0)

    So, I tweaked the code a bit and checked for the solution linearly,when the list size was small(say N) and went on with bisection when the list size was large.

    The code was accepted.

    The code should fail when given a test case larger than N.By trial and error, N was found to be 6!
    Here's the code:

    import bisect
    class Solution:

    def twoSum(self,nums,target):
        num2=nums[:]
        num2.sort()
        new=[]
    
    
        st = bisect.bisect(num2,target)-1
        end=0
        inc=-1
        if len(nums)<6:
            st=0
            end=len(nums)
            inc=1
        for i in range(st,end,inc):
            find=target-num2[i]
            if find in num2:
                a=nums.index(find)+1
                b=nums.index(num2[i])+1
                if a==b:
                     if nums.count(find)>1:
                         nums.remove(find)
                         b=nums.index(num2[i])+2
                new.append(a)
                new.append(b)
                new.sort()
                break
        return new

Log in to reply
 

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