AlgoMaster Logo

Remove Duplicates (Without Set)

Last Updated: June 7, 2026

easy
3 min read

Understanding the Problem

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.

Key Constraints:

  • Array is unsorted → Equal values are not guaranteed to be adjacent. Comparing each element only to its immediate predecessor would miss duplicates that appear far apart, so the check has to cover every value kept so far.
  • No hash set or hash map allowed → Membership cannot be tested in constant time. Each element is checked with a linear scan over the result built up to that point, which is what pushes the running time to O(n^2).
  • First-appearance order preserved → Values must be returned in the order they first appear. Appending to the result the moment a new value is found keeps that order naturally.

Approach 1: Nested Loop

Intuition

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.

Algorithm

  1. Create an empty result list.
  2. For each value x in nums:
    1. Scan the current result list. If any kept value equals x, mark it as already present.
    2. If no kept value equals x, append x to the result.
  3. Convert the result list to an array and return it.

Example Walkthrough

Input:

0
1
1
2
2
2
3
3
4
1
nums

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].

0
1
1
2
2
3
result

Code