[Leet Code] Single Number

Matthew Boyd
1 min readDec 2, 2020

--

Leetcode: https://leetcode.com/problems/single-number/

Problem:

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory?

Example:

Input: nums = [2,2,1]
Output: 1
Input: nums = [4,1,2,1,2]
Output: 4

Solution:

class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""

answers = {}
for i in range(len(nums)):
if nums[i] in answers:
del answers[nums[i]]
else:
answers[nums[i]] = 1
return int(''.join(map(str, answers)))

Explanation:

First, we create a dictionary, we can then use each of the numbers as keys. If he number is found in the dictionary, we want to delete it. Remember to read the summary, the maximum amount of duplicate values will be 2, therefore if we find another one, we just delete that record. Then by the end of the for loop, we should be left with just one value.

Then we want to turn the list of ints into string using the map function, and then we want to convert this back to an int.

--

--

Matthew Boyd
Matthew Boyd

Written by Matthew Boyd

Learning, and posting my findings!

Responses (1)