136. Single Number LeetCode Solution

In this guide, you will get 136. Single Number LeetCode Solution with the best time and space complexity. The solution to Single Number problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Single Number solution in C++
  4. Single Number solution in Java
  5. Single Number solution in Python
  6. Additional Resources
136. Single Number LeetCode Solution image

Problem Statement of Single Number

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.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

136. Single Number LeetCode Solution in C++

class Solution {
 public:
  int singleNumber(vector<int>& nums) {
    int ans = 0;

    for (const int num : nums)
      ans ^= num;

    return ans;
  }
};
/* code provided by PROGIEZ */

136. Single Number LeetCode Solution in Java

class Solution {
  public int singleNumber(int[] nums) {
    int ans = 0;

    for (final int num : nums)
      ans ^= num;

    return ans;
  }
}
// code provided by PROGIEZ

136. Single Number LeetCode Solution in Python

class Solution:
  def singleNumber(self, nums: list[int]) -> int:
    return functools.reduce(operator.xor, nums, 0)
# code by PROGIEZ

Additional Resources

See also  1209. Remove All Adjacent Duplicates in String II LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.