LeetCode: Single Number Solution

Count occurence of each element

Approach

Use a hash table (Map) to store key-value pairs of number and its occurence

Implementation

1var singleNumber = function (nums) {
2 const numOccMap = nums.reduce(
3 (acc, el) => acc.set(el, (acc.get(el) || 0) + 1),
4 new Map()
5 )
6
7 for (const [num, occ] of numOccMap) {
8 if (occ === 1) {
9 return num
10 }
11 }
12}

References

Original problem

MDN Map()

Comments

Loading comments...

Tags

leetcode

hash table

bit manipulation

Next Post

LeetCode: Simplify Path

Feb 5, 2021

Previous Post

LeetCode: Rotate Array

Feb 4, 2021

Stale solution might be time-limit exceeded someday

HoningJS

Search Posts