DEV Community

ashwins-code
ashwins-code

Posted on

Leetcode Problem 260: Single Number III

Hi! Welcome to today's post which is a solution to Leetcode Problem 260. This question is a Medium level difficulty question. Here's the solution on GitHub https://github.com/ashwins-code/leetcode-solutions/blob/main/medium/problem260-single-number-iii.py

The Question

Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order.

Example 1:

Input: nums = [1,2,1,3,2,5]

Output: [3,5]

Explanation:  [5, 3] is also a valid answer.


Example 2:

Input: nums = [-1,0]

Output: [-1,0]


Example 3:

Input: nums = [0,1]

Output: [1,0]
Enter fullscreen mode Exit fullscreen mode

Solution

We can start off with an empty list (ans) and go through the nums list. For each element in the nums list, we append this to ans if we haven't encountered this element before (we know this by checking if the element is already in ans). If we have encountered it, remove this element from ans. After we have finished iterating through nums, ans should only contain the numbers which appeared once. Here's an example

nums = [1,2,1,3,2,5]

ans = []

Go through nums

1 => add this to ans as we have never seen this before (ans = [1])

2  => add this to ans as we have never seen this before (ans = [1, 2])

1 => remove this from ans as we have seen this before (ans = [2])

3 => add this to ans as we have never seen this before (ans = [2, 3])

2 => remove this from ans as we have seen this before (ans = [3])

5 => add this to ans as we have never seen this before (ans = [3, 5])


Ans now has the correct answer
Enter fullscreen mode Exit fullscreen mode

The Code

class Solution:
    def singleNumber(self, nums: List[int]) -> List[int]:
        ans = []

        for i in nums:
            if i not in ans:
                ans.append(i)
            else:
                ans.remove(i)

        return ans
Enter fullscreen mode Exit fullscreen mode

Top comments (0)