Given an array (or string), find the first element that does not repeat (i.e., appears exactly once). Return the element itself, or its index if required.
classSolution {
public:int firstUnique(std::vector<int>& arr) {
for (int i =0; i < arr.size(); ++i) {
bool unique = true;
for (int j =0; j < arr.size(); ++j) {
if (i != j && arr[i] == arr[j]) {
unique = false;
break;
}
}
if (unique) return arr[i];
}
return-1;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
publicintfirstUnique(int[] arr) {
for (int i = 0; i < arr.length; i++) {
boolean unique =true;
for (int j = 0; j < arr.length; j++) {
if (i != j && arr[i]== arr[j]) {
unique =false;
break;
}
}
if (unique) return arr[i];
}
return-1;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
deffirst_unique(self, arr: list[int]) -> int:
for i in range(len(arr)):
unique =Truefor j in range(len(arr)):
if i != j and arr[i] == arr[j]:
unique =Falsebreakif unique:
return arr[i]
return-1
classSolution {
public:int firstUnique(std::vector<int>& arr) {
std::unordered_map<int, int> freq;
for (int x : arr) freq[x]++;
for (int x : arr) if (freq[x] ==1) return x;
return-1;
}
};
1
2
3
4
5
6
7
8
classSolution {
publicintfirstUnique(int[] arr) {
Map<Integer, Integer> freq =new HashMap<>();
for (int x : arr) freq.put(x, freq.getOrDefault(x, 0) + 1);
for (int x : arr) if (freq.get(x) == 1) return x;
return-1;
}
}
1
2
3
4
5
6
7
8
9
classSolution:
deffirst_unique(self, arr: list[int]) -> int:
freq = {}
for x in arr:
freq[x] = freq.get(x, 0) +1for x in arr:
if freq[x] ==1:
return x
return-1