136. Single Number | XOR Explained in C++ | LeetCode Easy
In this video, we solve LeetCode Problem 136: Single Number using C++. We are given a non-empty array of integers where every element appears twice except for one element. Our task is to find that single element. The solution must run in linear time complexity and use only constant extra space. In this solution, we cover: - What the problem is asking - Why every number appears twice except one - How XOR works in this problem - Why duplicate numbers cancel out using XOR - How the single number remains as the final answer - Time and space complexity explanation Approach: We use the XOR operator to solve this problem efficiently. XOR has two important properties: 1. A number XOR with itself becomes 0 2. A number XOR with 0 remains the same number So when we XOR all elements of the array, all duplicate numbers cancel each other out, and only the single number remains. Algorithm: 1. Initialize ans = 0 2. Traverse through every number in nums 3. Apply XOR operation: ans = ans ^ num 4. Duplicate numbers become 0 5. The remaining value in ans is the single number 6. Return ans Complexity: Time Complexity: O(n) Space Complexity: O(1) If you found this explanation helpful, like the video and subscribe for more LeetCode solutions in C++. 🔗 Connect with me: GitHub: https://github.com/atulXdev LeetCode Profile: https://leetcode.com/u/atul_singh_cg/ LinkedIn: https://www.linkedin.com/in/atul-singh-987b0b394/ Tags: LeetCode 136 Single Number C++ LeetCode C++ Solution XOR Approach Bit Manipulation DSA Coding Interview C++ LeetCode Array Problem
Download
1 formatsVideo Formats
Right-click 'Download' and select 'Save Link As' if the file opens in a new tab.