LeetCode Challenge: Single Number

Will Sheppard
2 min readDec 16, 2020

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

Description

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 1

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

Example 2

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

Example 3

Input: nums = [1]
Output: 1

Constraints

  • 1 <= nums.length <= 3 * 104
  • -3 * 104 <= nums[i] <= 3 * 104
  • Each element in the array appears twice except for one element which appears only once.

Solution:

Steps

1. Create a object to keep track of the number of times a integer occurs in our nums array.
2. Loop through nums array.
3. If there is no key in obj matching the corresponding integer, add the key to the obj Object, and assign it with the property 1.
4. If the corresponding integer is already has a key, matching its value, then increment the property of that key in obj.
5. Return the key in obj that has a property of 1.

Code (JavaScript)

Results

Runtime: 104 ms, faster than 29.24% of JavaScript online submissions for Single Number.Memory Usage: 44.4 MB, less than 27.33% of JavaScript online submissions for Single Number.

Thanks for viewing. If you have any feedback on how to improve this code, leave a comment.

--

--

Will Sheppard

Seasoned software engineer with 5+ years of experience in JavaScript, React, GraphQL, and AWS