Taro Logo

Single Number

#22 Most AskedEasy
0 views
Topics:
Bit ManipulationArrays

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

You must implement a solution with a linear runtime complexity and use only constant extra space.

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


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the input array contain negative numbers and zeros, or are we strictly dealing with positive integers?
  2. What should we return if the input array is empty or null, given the problem states the array is non-empty?
  3. Is it guaranteed that a single number always exists, or is there a possibility of an invalid input where all numbers appear twice?
  4. Does the order of elements in the input array matter in any way, or can I assume they are completely unsorted?
  5. Are there any memory restrictions beyond the 'constant extra space' requirement, such as avoiding modification of the input array?

Brute Force Solution

Approach

Imagine you have a pile of items where almost everything comes in matching pairs, but one single item is left without a partner. The brute force strategy involves picking up each item one by one and exhaustively searching through the entire pile to see if a matching partner exists.

Here's how the algorithm would work step-by-step:

  1. Pick your first item from the pile.
  2. Scan through every other item in the pile to see if you can find an exact match for the item you are holding.
  3. If you find another matching item, cross both of them off your mental list and move on.
  4. If you search the entire pile and find no matching partner for the item you are holding, you have found the single item.
  5. If a partner was found, pick up the next available item and repeat the entire search process from the beginning.
  6. Continue this exhaustive comparison process until you find the one item that has no match.

Code Implementation

def single_number(number_pile):
    # Iterate through each item to check if its pair exists elsewhere in the pile
    for current_index in range(len(number_pile)):
        match_found = False
        
        for search_index in range(len(number_pile)):
            if current_index == search_index:
                continue
            if number_pile[current_index] == number_pile[search_index]:
                match_found = True
                break
        
        # Return immediately if we find an item without a matching partner
        if not match_found:
            return number_pile[current_index]

Big(O) Analysis

Time Complexity
O(n²) – For each of the n items in the pile, we execute an exhaustive inner scan across the entire array to search for a matching partner. The first item requires n comparisons, the second requires n comparisons, and this pattern repeats for all elements. This leads to approximately n * n operations, which simplifies to O(n²).
Space Complexity
O(1) – The brute-force strategy described relies entirely on mentally picking and comparing items from the original pile without allocating any additional data structures like hash maps or temporary lists. The only extra memory consumed consists of a few primitive tracking variables used to hold the current item and loop indices, which require a constant amount of storage. Because this auxiliary memory footprint remains completely fixed regardless of how large the input size N grows, the space complexity is strictly constant.

Optimal Solution

Approach

Instead of counting how many times each item appears, the optimal approach uses a clever trick of magic pairing. By combining every item together using this special method, all the items that appear twice cancel each other out, leaving only the single lonely item behind.

Here's how the algorithm would work step-by-step:

  1. Imagine you have a special glowing box that can combine items together.
  2. Take the first item and put it into the glowing box.
  3. Take the next item and combine it with whatever is currently inside the box.
  4. If you combine two identical items together inside the box, they magically cancel each other out and disappear completely.
  5. If you combine an item with nothing, it just stays inside the box.
  6. Continue this process by adding every single item one by one into the box.
  7. Because every item except one has an exact partner, all the pairs will find each other and cancel themselves out.
  8. When you have gone through all the items, the only thing left inside the magical box will be the single number that does not have a pair.

Code Implementation

def single_number(list_of_numbers):
    # Initialize the magical glowing box with a neutral starting value of zero.
    glowing_box_value = 0

    # Process every single item sequentially to allow identical pairs to interact.
    for current_number in list_of_numbers:
        glowing_box_value ^= current_number

    # Only the lonely item remains because all paired numbers canceled out.
    return glowing_box_value

Big(O) Analysis

Time Complexity
O(n) – To find the single number, we iterate through the array of size n exactly once, adding each element into our running calculation using the XOR operation. Because we process every single element in the array one by one without any nested loops or repeated scans, the operation count grows linearly with the input size. This linear progression means total operations directly scale as n, which simplifies to O(n).
Space Complexity
O(1) – The algorithm only uses a single integer variable to accumulate the result as it iterates through the input array. No auxiliary data structures, hash maps, or recursive call stacks are created. Therefore, the extra memory used remains constant regardless of the input size N.

Edge Cases

Minimum valid input with a single element
How to Handle:
The XOR accumulator starts at zero and processes the single element, correctly returning that exact number.
Array containing negative numbers
How to Handle:
Bitwise XOR operates identically on the binary representation of negative integers, correctly canceling out pairs.
Array containing zero
How to Handle:
Zero XORed with any number equals that number, allowing zeros to pair up or stand alone without disrupting the accumulator.
Very large arrays nearing memory or time limits
How to Handle:
A single pass linear scan with O(1) space complexity executes efficiently within optimal time and memory constraints.
Inputs with mixed positive and negative numbers containing extreme boundary values
How to Handle:
Bitwise operations naturally handle integer limits without causing overflow or underflow issues.
The single unique number is located at the very beginning or end of the array
How to Handle:
The commutative and associative properties of XOR ensure the unique element is isolated regardless of its position.
0/37 completed