HackerRank C++ Algorithms: Lonely Integer solution (Bit Manipulation)

preview_player
Показать описание
HackerRank C++ solution for the Bit Manipulation Algorithms coding challenge called Lonely Integer. This C++ algorithm uses the sort function to sort an array in ascending order, and utilizes the bitwise XOR operator to compare integers and find the unique number in the array.

Рекомендации по теме
Комментарии
Автор

*WE CAN SOLVE THIS PROBLEM EASILY BY USING STACK*
*ALTHOUGH IT WONT WORK IF THERE ARE 2 UNIQUE ELEMENT BUT FOR THIS PROGRAMM THIS IS ENOUGH*

int lonelyinteger(vector<int> a) {

sort(a.begin(), a.end());
stack<int> res;
for(unsigned int i=0;i<a.size();i++)
{
if(res.empty())
res.push(a[i]);
else if (res.top()==a[i])
res.pop();
else
res.push(a[i]);
}
return res.top();
}

PurnaChandraReddyTallapaka
Автор

This helped me a lot with reasoning through it myself on HackerRank! Something that can be improved is the complexity and legibility of your condition statement for the while loop. You use "i <= a.size() -1" when "i < a.size()" fulfills the same purpose and is easier to read. Moreover, performing bitwise comparison with the rare '^' operator is unnecessary in this case because simply checking for equality with an "==" works just as well. Nice ideas though; you helped me a lot in figuring it all out!

My solution: (C++)
int lonelyInteger(vector<int>& a) {
// Sort vector in increasing order (e.g., [5, 4, 9, 1, 9, 5, 4] becomes [1, 4, 4, 5, 5, 9, 9])
sort(a.begin(), a.end());
// Counter variable for while condition
int i = 0;
// Iterate through vector and compare each element to its successor
while(i < a.size() && a[i] == a[i+1])
{

// Matches come in pairs, so increment by 2 if a match is found
i+=2;
}
// Return mismatched value
return a[i];
}

john_paul
Автор

The complexity is actually O(nlogn) because you have to sort the array

taynaracruz
Автор

can you tell me whats wrong in this code please ---

int lonelyinteger(vector<int> a) {
int n=a.size();
int arr[101];
for(int i=0;i<n;i++){
int ele=a[i];
arr[ele]++;
}
for(int i=0;i<101;i++){
if(arr[i]==1){
return arr[i];
}
}
}

PIYUSH-lzzq
join shbcf.ru