HackerRank Lonely Integer problem solution in java python c++ c and javascript programming with practical program code example
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
HackerRank Lonely Integer SOLUTIONS:
You are given an array of integers and every integer except one occurs more than once. The integer that doesn’t have a repeating value inside the array is considered unique. The goal of the function is to output that unique number.
let a = [1,1,2,2,6];
Looking at our array input above, values 1
and 2
have repeating values but 6
is the only number that doesn’t. The function will return 6
because it is a unique number.
Let’s turn this problem into code.
HackerRank Lonely Integer Solution in JavaScript:
function lonelyinteger(a) { let loneValue=a[0]; for(let i=1; i<a.length; i++) loneValue ^= a[i]; return loneValue; }
Lonely Integer Solution in Python:
def lonelyinteger(a): unique=0 for i in a: unique^= i return unique
Lonely Integer Solution in Java:
public static int lonelyinteger(List<Integer> a) { // Write your code here int unique=a.get(0); for(int i=1;i<a.size();i++){ unique^=a.get(i); } return unique; }
3 Possible Approches of Solving Lonely Integer :
# Naive Approach for i in range(len(a)): single = True for j in range(len(a)): if i!=j and a[i] == a[j]: single = False break if single: return a[i] # Using Hash map hash_map = {} for i in a: if i not in hash_map: hash_map[i] = 1 else: hash_map[i] += 1 for key, value in hash_map.items(): if value == 1: return key # Using Xor result = 0 for i in a: result ^= i return result
Leave a Reply