Solving the Single Number problem in Python

0 min read 109 words

The challenge

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

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:

Input: [2,2,1]
Output: 1

Example 2:

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

The solution in Python

def singleNumber(nums):
    # create a dictionary/hashmap
    found = {}

    # loop through the nums
    for i in nums:
        # add to map if not found
        if i not in found:
            found[i] = i
        else:
            # otherwise remove it
            del found[i]

    # loop through the found map and return the first item
    for i in found:
        return i
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags