I got this question for an exam:
Given an integer array find the first number which is not repeating in array using O(N) time complexity and O(1) space co
To find first non-repeating number in given integer array
UPDATE: Found a better solution.
I think we can solve it in O(n)
time complexity using an additional data structure such as HashMap. Iterate through the array, and put the element as key and the element's index position in array as the value in the map. if the key already exists, can either remove the key-value pair or just set the value to -1.
Once the entire array is traversed, then we can get the keySet() from the hashmap, and then find the key which has lowest value(ignore -1).
so this would be
Time Complexity: O(N)
Space Complexity: O(N)
Old solution: We can solve this by, creating another array which is obtained by sorting the given array. This would take O(nlogn)
time.
then we can iterate through each element in given input array, try to find the element & compare with next element in the sorted array, if repeated continue for the next element in given array, if not repeated, then we found the first non-repeating element in given input array of integers.
time complexity: O(nlogn)
space complexity: O(n)
P.S: I am sorry, hadn't read all the comments, James Kanze has already provided this solution in comments, credits to him.