In this HackerRank Lonely Integer problem, we have Given an array of integers, where all elements but one occur twice, find the unique element.
Example
The unique element is .
Function Description
Complete the lonelyinteger function in the editor below.
lonelyinteger has the following parameter(s):
- int a[n]: an array of integers
Returns
- int: the element that occurs only once
Input Format
The first line contains a single integer, , the number of integers in the array.
The second line contains space-separated integers that describe the values in .
Constraints
- It is guaranteed that is an odd number and that there is one unique element.
- , where .
Lonely Integer Hacker Rank Problem Solutions
I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.
Problem Solution in C#
Dictionary<int, int> dict = new Dictionary<int, int>();
int n = a.Count, count = 0;
for(int i=0;i<n;i++)
{
if(dict.ContainsKey(a[i]))
{
var val = dict[a[i]];
dict.Remove(a[i]);
dict.Add(a[i], val + 1);
}
else
{
dict.Add(a[i], 1);
}
}
foreach(KeyValuePair<int,int> entry in dict)
{
if(entry.Value == 1)
{
count = entry.Key;
}
}
return count;
Problem Solution in JavaScript
function lonelyinteger(a) {
const findDuplicates = a => a.filter((item, index) => a.indexOf(item) !== index);
let duplicatesArray = findDuplicates(a);
for (let i = 0; i< a.length; i++){
if(!duplicatesArray.includes(a[i])){
return a[i]
}
}
}
Problem Solution in Python
def lonelyinteger(a):
for i in range(n):
pope=a.pop(i)
if pope in a:
a.insert(i,pope)
else:
return pope
Problem Solution in Java
public static int lonelyinteger(List<Integer> a) {
boolean n = true;
for(int i=0; i<a.size();i++){
for (int j=0;j<a.size();j++){
if(j != i){
if(Objects.equals(a.get(i), a.get(j))){
n=false;
break;
}
else{
n=true;
}
}
}
if(n){
return a.get(i);
}
}
return 0;
}
Leave a Reply