Find the first non-repeating element in a given array of integers.
Input : -1 2 -1 3 2 Output : 3 Explanation : The first number that does not repeat is : 3 Input : 9 4 9 6 7 4 Output : 6
A Simple Solution is to use two loops. The outer loop picks elements one by one and inner loop checks if the element is present more than once or not.
An Efficient Solution is to use hashing.
1) Traverse array and insert elements and their counts in hash table.
2) Traverse array again and print first element with count equals to 1.
Time Complexity : O(n)
Auxiliary Space : O(n)
Further Optimization: If array has many duplicates, we can also store index in hash table, using a hash table where value is a pair. Now we only need to traverse keys in hash table (not complete array) to find first non repeating.
Printing all non-repeating elements:
- Replace each element by the difference of the total size of the array and frequency of that element
- Range Query on array whose each element is XOR of index value and previous element
- Replace every element with the greatest element on its left side
- Longest Subarray with first element greater than or equal to Last element
- Find last element after deleting every second element in array of n integers
- Replace every array element by Bitwise Xor of previous and next element
- Replace every element with the smallest element on its left side
- Replace every element of the array by its previous element
- Replace every element with the greatest element on right side
- Replace every element of the array by its next element
- Replace every element with the least greater element on its right
- Sum of product of each element with each element after it
- Find the element that appears once in an array where every other element appears twice
- Closest greater element for every array element from another array
- Next Smaller Element
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : jit_t