Find the first non-repeating element in a given array arr of N integers. Note: Array consists of only positive and negative integers and not zero.
arr
N
Example 1:
Input : arr[] = {-1, 2, -1, 3, 2} Output : 3 Explanation: -1 and 2 are repeating whereas 3 is the only number occurring once. Hence, the output is 3.
Example 2:
Input : arr[] = {1, 1, 1} Output : 0
Expected Time Complexity: O(N)O(N)O(N) Expected Auxiliary Space: O(N)O(N)O(N)
Constraints:
1<=N<=1071 <= N <= 10^71<=N<=107
โ1016<=Ai<=1016-10^{16} <= A_i <= 10^{16}โ1016<=Aiโ<=1016โ
Aiโ 0{A_i \ne0 }Aiโ๎ =0โ
Create a map of frequencies
Traverse the array from left to right
If the element has frequency 1 in the map then return the element
If no such element is found, return -1
int firstNonRepeating(int arr[], int n) { map<int, int> frequency; for(int i = 0; i < n; i++) frequency[arr[i]]++; for(int i = 0; i < n; i++) if(frequency[arr[i]] == 1) return arr[i]; return -1; }
Time Complexity: O(n)O(n)O(n)โ
Space Complexity: O(n)O(n)O(n)โ
Last updated 3 years ago