Last Updated: June 7, 2026
Keep each distinct value once and drop repeats, preserving the order in which values first appear. For [1, 2, 2, 3, 1], the output is [1, 2, 3]. The second 2 and the second 1 repeat values already seen, so they are dropped.
The fast way is normally a hash set: walk the array, check the set in constant time, and add only new values. That is not allowed here. Without a set, membership checks have to be done by scanning the values already kept.
The array is also unsorted. If it were sorted, duplicates would sit next to each other and you could compare each element to the previous one. Since the input can arrive in any order, a repeat might appear many positions after the original, so each value has to be compared against everything kept so far.
O(n^2).The result list itself is the record of what has been seen. For each value in the input, ask: is this value already in the result? If yes, skip it. If no, append it.
The membership check is an inner loop. Scan the result from start to end and compare each kept value against the current one. A match means a duplicate. Reaching the end without a match means it is new. Appending each new value the instant it is found keeps the result in first-appearance order.
x in nums:x, mark it as already present.x, append x to the result.Input:
Start with an empty result [].
Take 1. The result is empty, so the scan finds nothing. Append 1. Result is now [1].
Take 2. Scan [1]. No match against 1. Append 2. Result is now [1, 2].
Take the second 2. Scan [1, 2]. The kept 2 matches. It is a duplicate, so skip it. Result stays [1, 2].
Take 3. Scan [1, 2]. No match against 1 or 2. Append 3. Result is now [1, 2, 3].
Take the second 1. Scan [1, 2, 3]. The kept 1 matches. It is a duplicate, so skip it. Result stays [1, 2, 3].
Every value has been processed. The final result is [1, 2, 3].
n input values, the inner loop scans the kept result, which can hold up to k distinct values. With no hash set for constant-time lookups, this nested scan is the cost of checking membership by hand.k is the number of distinct values. The result holds one copy of each distinct value and nothing else.