Time Complexity of "in" keyword in python when using a list? Leetcode

129 Views Asked by At

I read a little bit everywhere that the "in" operator have a time complexity of O(n), yet I used it in a code and idk why but it's acting as if it have the time complexity O(1)

So I was solving a problem on leetcode and ended up having this algorithm

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        i=0
        n=len(nums)
        for i in range (0, n-1):
            if (target-nums[i]) in nums:
                for j in range (i+1, n):
                    if nums[i]+nums[j]==target:
                        return[i, j]

No.1 and I ended up having runtime pretty similar to code like these that involve hashmaps:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        hash_map = {}

        for i in range(len(nums)):
            complement = target - nums[i]
            if complement in hash_map.keys():
                return [i, hash_map[complement]]
            hash_map[nums[i]] = i

No.2 It's weird because I read everywhere that the time complexity of the in operator for list is O(n), so I assumed this line

if (target-nums[i]) in nums:

would make my code equivalent to

class Solution(object):
    def twoSum(self, nums, target):
        self=list()
        n=len(nums)
        for i in range(n-1):
          for j in range(i+1,n):
            if nums[i]+nums[j]==target:
              return [i,j]

No.3

yet it has the runtime of a code using hashmaps, and uses the memory of the code using the same list so O(1), anyone could explain that to me please? To recap shouldn't solution1 have a runtime closer or exactly as solution3? Yet it's closer to solution2.

No1 No2 and No3 have screenshots of runtime and memory of each code.

1

There are 1 best solutions below

0
Kelly Bundy On

You chose to use Python 2, so if complement in hash_map.keys(): creates a list of keys and searches in that list. Instead of doing the fast lookup in the hashmap. Entirely negating why it was used in the first place. That's why the hashmap solution isn't much faster. Remove the .keys(). Or choose Python 3, which you should anyway. Python 2 is dead.