151 DSA Problem journey

151 DSA Problem journey

Single number

Q25: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 :

Input: nums = [2,2,1]
Output: 1
Solution:
class Solution {
public:
    int singleNumber(vector<int>& nums) {
         unordered_map<int,int> a;
       for(auto x: nums)
           a[x]++;
       for(auto z:a)
           if(z.second==1)
               return z.first;
       return -1;

    }
};
Explantion:
.The code defines a class named Solution.
.Inside the class, there's a public method called singleNumber.
.The method takes a vector of integers (vector<int>& nums) as input.
.It uses an unordered map (unordered_map<int, int> a;) to store the 
 frequency count of each number in the input vector.
.The first loop iterates through each element (x) in the input vector 
 and increments the corresponding count in the unordered map.
.The second loop iterates through the unordered map.
.For each key-value pair (z), it checks if the count (z.second) is equal to 1.
.If found, it means that the corresponding number is the single number in
 the input vector, and the function returns that number (return z.first).
.If no single number is found, the function returns -1 (return -1).
.The overall purpose of the code is to find and return the number that 
 appears only once in the input vector, assuming all other numbers appear twice.
.The time complexity of the solution is O(n), where n is the size of the 
input vector, and the space complexity is also O(n) considering the 
worst-case scenario.

Did you find this article valuable?

Support GAURAV YADAV by becoming a sponsor. Any amount is appreciated!