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 GitHubhttps://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]
Solution
We can start off with an empty list (ans) and go through thenums list. For each element in thenums list, we append this toans if we haven't encountered this element before (we know this by checking if the element is already inans). If we have encountered it, remove this element fromans. 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 nums1 => 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
The Code
classSolution:defsingleNumber(self,nums:List[int])->List[int]:ans=[]foriinnums:ifinotinans:ans.append(i)else:ans.remove(i)returnans
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse