pythonarrayslistdata-structures

Overcome TLE (Time Limit Exceeded) in Python


I'm trying to solve a very basic problem on Leetcode which runs well but says "Time Limit Exceeded" on submission.

Here is the question : Given an integer array nums, return trueif any value appears at least twice in the array, and return false if every element is distinct.

Example 1 :
Input: nums = [1,2,3,1]
Output: true

Example 2 :
Input: nums = [1,2,3,4]
Output: false

Constraints :

1 <= nums.length <= 105
-109 <= nums[i] <= 109

Here is my Code :

class Solution(object):
def containsDuplicate(self, nums): #self - boolean, nums - list

    count = 0
    for i in range(0,len(nums)):
        for j in range(i+1, len(nums)):
            if nums[i] == nums[j]:
                count += 1
                
    if count>0 :
        return True
    else:
        return False
    

My Output :

TLE - Time Limit Exceeded


Solution

  • you can just use a set to keep track of the elements you've seen so far. If you encounter an element that's already in the set, it means the element appears at least twice in the array, so you can return true or else false like this .

    def contains_duplicate(nums):
            seen = set()
            for num in nums:
                if num in seen:
                    return True
                seen.add(num)
            return False
    

    using a set is the better approach due to its linear time complexity , which makes it more efficient for large sized array.