-1

I believe the code below is an O(N) solution but I'm being told it is O(N^2) because of the in keyword. Is that true?

Code:

class Solution:
    def twoSum(self, nums, target):
        for i,v in enumerate(nums):
            value = target - v
            if value in nums and nums.index(value)!= I:
                return (nums.index(value),I)
                break
Shaido
  • 27,497
  • 23
  • 70
  • 73
Adedev
  • 1
  • 2
    Does this answer your question? [Python "in" operator speed](https://stackoverflow.com/questions/20234935/python-in-operator-speed) – Welbog Nov 28 '21 at 22:38

1 Answers1

0

x in a_list is O(n) as is nums.index(value) ... so your inner if statement is O(2n) and your outer for loop is O(n)

so you have O(n)*O(2n) = O(2n^2) = O(n^2)

the O(n) solution is as follows

def twoSum(x,targetValue):
    # pending values is a dict of index's mapped where the key is key + x[pendingValues[key]] = targetValue
    pendingValues = {}
    for i,value in enumerate(x):
        if value in pendingValues: # in Dict is only O(1)
           # this is a match return both matching index's
           return (pendingValues[value],i)
        else:
           # not a match store the index as matchedTarget=index
           pendingValues[targetValue-value] = i
 
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179