Solution: First Non-Repeating Integer in a List
Let’s solve the First NonRepeating Integer in a List problem.
We'll cover the following
Statement
Given a list nums
, find the first nonrepeating integer in it.
Constraints:
nums.length
nums[i]
Solution
The brute force approach involves comparing elements pairwise in the list to check if a given element is unique. Here are the steps of the algorithm:
Traverse the list with the pointer
p1
from the beginning to the end.For each element pointed by
p1
, initialize another pointer,p2
, to the start of the list.Use
p2
to traverse the list from the beginning to the end. During this traversal, check if the elements at the locations pointed byp1
andp2
are the same, ensuringp1
andp2
are not pointing to the same location.If an element pointed by
p1
is found to be equal to an element pointed byp2
(wherep1
does not point to the same location asp2
), it indicates that the element atp1
is not unique. Break the inner loop (the traversal withp2
) and movep1
to the next element to restart the check for uniqueness.If
p2
completes its traversal (reaches the end of the list) without finding a duplicate, the element atp1
is unique. We can then return this element.Repeat this process until
p1
has traversed the entire list.
Let’s look at the illustrations below to better understand the solution:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.