Leetcode 136: Single Number

grid47
grid47
Exploring patterns and algorithms
Oct 24, 2024 4 min read

A glowing, solitary number standing out in a sequence, signifying its uniqueness.
Solution to LeetCode 136: Single Number Problem

Given a non-empty array of integers where every element appears twice except for one element that appears once, find the single element that appears only once. The solution must have linear time complexity and use only constant space.
Problem
Approach
Steps
Complexity
Input: You are given an array of integers where all but one element appear twice. The array is non-empty and contains at least one element.
Example: nums = [5, 5, 3]
Constraints:
• 1 <= nums.length <= 3 * 10^4
• -3 * 10^4 <= nums[i] <= 3 * 10^4
Output: Return the element that appears only once in the array.
Example: Output: 3
Constraints:
• The array contains exactly one element that appears once.
Goal: Find the element that appears once by using XOR.
Steps:
• 1. Use the XOR operation to find the element that appears once. XORing the same number twice cancels it out, leaving only the unique element.
• 2. Initialize a variable to 0 and XOR it with each element in the array.
• 3. Return the result after the final XOR operation, which will be the single number.
Goal: The constraints ensure that the solution operates efficiently even for large arrays.
Steps:
• 1 <= nums.length <= 3 * 10^4
• -3 * 10^4 <= nums[i] <= 3 * 10^4
Assumptions:
• The array is guaranteed to contain one unique element and all other elements appear exactly twice.
Input: nums = [5, 5, 3]
Explanation: In this example, the number 3 appears once while 5 appears twice. The result is 3.

Input: nums = [7, 9, 7, 3, 9]
Explanation: In this case, 3 appears once, and all other numbers appear twice. The result is 3.

Input: nums = [4]
Explanation: Since there is only one number in the array, the result is that number itself, 4.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus