Great work again Striver! I wouldnt have ever tried learning DSA if i had never ran onto your channel. It is a request that you please make the string playlist next whenever you have free time(ik its hard to find time alongside doing a fulltime job,but you still do so much for us so thanks a lot).
C++ code with comments for better understanding class Solution { public: vector singleNumber(vector& nums) { // brute force using map // optimised using bit manipulation bucket // approach : we know that all duos xor will be 0 and the unique 2 elements xor will contain // nothing but a number which contain bits which are not same in both long long numXor=0; for(auto it:nums)numXor^=it; // now we need to distinguish both the numbers // and xor contains all the bits which are not same in both , we just need one different bit // taking the rightmost one is fine long long rightBit= numXor ^ (numXor &(numXor-1)); // now take 2 bucket integer which store numbers based on this rightBit int a=0,b=0; for(auto it:nums){ // if right bit is set if(it&rightBit)a^=it; else b^=it; } return {a,b}; } };
The best explanation ever. The previous one's last solution blew me away... Amazing Striver, done with Bit manipulation today. Will start greedy from Monday. Hope you sgtart the string and stacks queues playlist soon.
vector singleNumber(vector& nums) { long xorr = 0; //Taking xorr as long for the case of INT_MIN in nums[i] for(auto &it : nums) xorr ^= it; int rightMostBitTurnedOne = xorr & (-xorr); int b1 = 0, b2 = 0; //b1 --> 1st bit is set || b2 --> 1st bit is 0 for(auto &it : nums) { if(it & rightMostBitTurnedOne) b1 ^= it; else b2 ^= it; } return {b1, b2}; }
There is an mistake @19:04 it's not rightMost = (xor & (xor - 1)) & (xor); => rightMost = (xor & (xor - 1)) ^ (xor); or rightMost = xor & -xor is efficent way
here is my python3 code for the given problem 👇 nums=list(map(int,input("Enter the list : ").split(" "))) xor=0 for ele in nums: xor=xor^ele bitmask=xor&(xor-1) bitmask=bitmask^xor num1=0 num2=0 for ele in nums: if bitmask&ele: num1=num1^ele else: num2=num1^ele print(num1,"and",num2,"are the unique numbers out there in the list.")