Lonely Integer Problem - HackerRank | Code Challenge #1

preview_player
Показать описание
In this video, I show present to you the Lonely Integer coding problem and give you an opportunity to try it on your own, and then I show you how I solved it and some other clever ways of solving it. #Java #CodeChallenge #hackerrank

Want to Support the Channel?

My Socials:

More Videos coming soon.
Leave a comment for any future video suggestions.
Рекомендации по теме
Комментарии
Автор

i did it in c++ by using a map<int, int>. when iterating through the list, it checks if the number is a key in the map, if it is not, then map[num] = 1, if it does exist, map[num]++.

finally iterate through the map and return when a value is 1

px
Автор

An easy (in place) n ln (n) solution is obtained by sorting the array, comparing each 2 elements consecutive elements (n/2 comparisons) and returning the first elements where you get non equality. Lonely elements will be at odd index in a sorted array.

othmanemazhar
Автор

Nice video thanks, but the bitwise XOR operator will only work if the repeated values are in pairs so the XOR gets 0, for this array [1, 4, 1, 1, 1, 1, 3, 3, 3] it won't work ;)

jokioki
Автор

java solution from me, i dont know what is the name of algorithm that i used.

List<Integer> nonUnique = new ArrayList<>();

for (int i = 0; i <= a.size() - 2; i++){
for (int j = i + 1; j <= a.size() - 1; j++){
if (a.get(i) == a.get(j)){
nonUnique.add(a.get(i));
nonUnique.add(a.get(j));
}
}

}
a.removeAll(nonUnique);

return(a.get(0));

ichsanpratama
Автор

This is what I came up with in Python 3:

```
# will return only the *first* integer that appears only once
def lonelyinteger(a):
length = len(a)
list_before_iteration = list(a)

for i in range(0, length):
list_after_iteration = list(a)
value_of_current_index = list_after_iteration.pop(i)

if
continue
else:
return value_of_current_index
```

Basically my idea was:

- go one index at a time
- record the value of the index and also remove it temporarily from the list
- check if the mutated list still contains another copy of that value; If it does, move on to next index, else return that value

lysergikdubz
Автор

Python :
def lonelyinteger(a):
for i in a :
if a.count(i) == 1 :
return i

ahotman
Автор

Bitwise operators are a bit weird. You could do it like this in a single iteration. Time complexity should be O(n) while space complexity is a bit worse than your solution, but I don't feel like space complexity is a concern nowadays.

public static int lonelyinteger(List<Integer> a) {
Set<Integer> firstSet = new HashSet<>(); // Contains all elements
Set<Integer> secondSet = new HashSet<>(); // Contains duplicated elements only
for (int i : a) {
if (!firstSet.contains(i)) {
firstSet.add(i);
} else {
secondSet.add(i);
}
}

return
}

cvetkovicslobodan
welcome to shbcf.ru