First Unique Number in Data Stream
tim johnson
1 reply
The problem of finding the first unique number in a data stream can be solved using a data structure known as a "LinkedHashSet" in Java. Here's an example implementation:
java
import java.util.LinkedHashSet;
class FirstUnique {
private LinkedHashSet set;
public FirstUnique(int[] nums) {
set = new LinkedHashSet<>();
for (int num : nums) {
add(num);
}
}
public int showFirstUnique() {
if (set.isEmpty()) {
return -1;
}
return set.iterator().next();
}
public void add(int value) {
if (set.contains(value)) {
set.remove(value);
} else {
set.add(value);
}
}
}
In this implementation, the https://newtoki.me/ LinkedHashSet data structure is used to maintain a collection of unique numbers in the order they are encountered in the data stream. The add method adds numbers to the set, removing them if they are already present. The showFirstUnique method returns the first unique number in the set, or -1 if there are no unique numbers present.
Replies
Carol Williams@carwilliams21
In a stream of data, how would you efficiently identify the first unique number, meaning the first number that doesn't repeat?
Share