DEV Community

Ankan Bhattacharya
Ankan Bhattacharya

Posted on

Single Number

Problem Statement

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

You must implement a solution with a linear runtime complexity and use only constant extra space.


  • First if there are no elements in the list return None.
  • Keep track of numbers occurring once in singleSet and multiple times in multipleSet.
  • Now go over each element in singleSet, and return the first element in singleSet.


Image description


class Solution:
    def singleNumber(self, nums: list[int]) -> int:
        if len(nums) < 1: return None

        singleSet: set = set()
        multipleSet: set = set()

        startingPoint: int = 0
        endingPoint: int = len(nums) - 1

        while startingPoint <= endingPoint:
            if nums[startingPoint] in singleSet:

            elif nums[startingPoint] not in multipleSet:

            if startingPoint == endingPoint:
                startingPoint += 1
                endingPoint -= 1

            if nums[endingPoint] in singleSet:

            elif nums[endingPoint] not in multipleSet:

            startingPoint += 1
            endingPoint -= 1

        for num in singleSet:
            return num

        return None
Enter fullscreen mode Exit fullscreen mode

Leetcode Result

Image description

So that's it... make sure if you liked the post and got to learn something, like the post and follow us. If you want me to improve at some point... leave that in the comment...

Top comments (0)