~/coding-interview/leetcode-solution-find-single-number-array-pairs.md

Single Number - Leet Code Solution

// TL;DR

XOR all elements together — pairs cancel out (a ^ a = 0), leaving only the single number. O(n) time, O(1) space, no extra data structures.

Single Number - Leet Code Solution

Problem Statement

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

Example

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

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

Solution using Extra Memory

We can take help of HashMap where we can save numbers and their counts.

  • In first iteration, just fill this HashMap
  • Iterate over this HashMap, and find the number whose count is not 2

Code

public int singleNumber_extraMemory(int[] nums) {
   int l = nums.length;
   
   Map<Integer, Integer> map = new HashMap<Integer, Integer>();
   for (int i=0; i<l; i++) {
      Integer count = map.get(nums[i]);
      if (count == null) {
         count = 1;
      }
      else {
         count ++;
      }
      
      map.put(nums[i], count);
   }
   
   for (Integer key : map.keySet()) {
      if (map.get(key) != 2) {
         return key;
      }
   }
   return -1;
}

Complexity

The complexity of above code is O(n)

Solution using Sorting

If we can sort the numbers, then we will have all pair of numbers adjascent to each other.
Then, we can check pair of numbers where they are not equal.

Code

public int singleNumber_sort(int[] nums) {
   int l = nums.length;
   
   Arrays.sort(nums);
   int i=0;
   while (i<l-1) {
      if (nums[i] != nums[i+1]) {
         return nums[i];
      }
      
      i += 2;
   }
   //check for last element
   if (l % 2 == 1) {
      return nums[l-1];
   }
   return -1;
}

Complexity

Since we are sorting, and iterating over array once. The complexity is O(nlogn)

Solution using Simple Maths

Assuming our array has all pairs. i.e. we don’t have a single number. Then, following is true:

2 (sum of unique numbers) = (sum of all numbers)

Now, if we know one of the number is missing in pairs. Following must be true:

2 (sum of unique numbers) - (sum of all numbers) = Missing Number

Lets take a look at example:

#input [2, 2, 1]

2 * (2 + 1) - (2 + 2 + 1)
= 6 - 5 
= 1
Result = 1

#Another example
# input [4,1,2,1,2]
2 * (4 + 1 + 2) - (4+1+2+1+2)
= 14 - 10
= 4
Result = 4

Code

public int singleNumber(int[] nums) {
   int l = nums.length;
   Set<Integer> set = new HashSet<>();
   
   int sum = 0;
   int uniqueElementSum = 0;
   
   for (int i=0; i<l; i++) {
      if (!set.contains(nums[i])) {
         set.add(nums[i]);
         uniqueElementSum += nums[i];
      }
      
      //all sum
      sum += nums[i];
   }
   
   return 2 * uniqueElementSum - sum;
}

We require a HashSet just to check for unique elements.

Complexity

The complexity is O(n)

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Replace all spaces in a string with %20

Replace all spaces in a string with %20

Problem Statement Replace all spaces in a string with ‘%20’ (three characters…

Valid Palindrome - Leet Code Solution

Valid Palindrome - Leet Code Solution

Problem Statement Given a string, determine if it is a palindrome, considering…

Valid Anagrams - Leet Code Solution

Valid Anagrams - Leet Code Solution

Problem Statement Given two strings s and t , write a function to determine if t…

Rotate Image - Leet Code Solution

Rotate Image - Leet Code Solution

Problem Statement You are given an n x n 2D matrix representing an image, rotate…

Validate Sudoku - Leet Code Solution

Validate Sudoku - Leet Code Solution

Problem Statement Determine if a 9x9 Sudoku board is valid. Only the filled…

Plus One - Leet Code Solution

Plus One - Leet Code Solution

Problem Statement Given a non-empty array of digits representing a non-negative…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…