![]() |
VOOZH | about |
Given an array arr[] of integers of size n, find the first non-repeating element in this array. if no such element exists return 0.
Examples:
Input: arr[] = [-1, 2, -1, 3, 2]
Output: 3
Explanation: -1 and 2 are repeating whereas 3 is the only number occuring once. Hence, the output is 3.Input: arr[] = [1, 1, 1]
Output: 0
Explanation: There is not present any non-repeating element so answer should be 0.
Table of Content
A non-repeating element appears only once, so iterate through the array from left to right, and for each element, scan the array to check if it appears again at any other index. If you find a duplicate, skip it, if you donβt find any, return that element as the first non-repeating one. If every element has a duplicate, return 0.
3
arr[] = {-1, 2, -1, 3, 0}
Frequency map for arr:
- -1 -> 2
- 2 -> 1
- 3 -> 1
- 0 -> 1
Traverse arr[] from left:
At i = 0: Frequency of arr[0] is 2, therefore it can't be first non-repeating element
At i = 1: Frequency of arr[1] is 1, therefore it will be the first non-repeating element.
Hence, 2 is the first non-repeating element.
3