Ruby Program to Remove Duplicates from an Array
uniq method like this: array.uniq which returns a new array without duplicates.Examples
How to Think About It
uniq method does this by creating a new list with only unique elements, preserving their order.Algorithm
Code
array = [1, 2, 2, 3, 4, 4, 5] unique_array = array.uniq puts unique_array.inspect
Dry Run
Let's trace the array [1, 2, 2, 3, 4, 4, 5] through the code using the uniq method.
Start with original array
[1, 2, 2, 3, 4, 4, 5]
Check each element and keep unique ones
Keep 1, keep 2, skip second 2, keep 3, keep 4, skip second 4, keep 5
Resulting array after removing duplicates
[1, 2, 3, 4, 5]
| Element | Action | Current Unique Array |
|---|---|---|
| 1 | Keep | [1] |
| 2 | Keep | [1, 2] |
| 2 | Skip | [1, 2] |
| 3 | Keep | [1, 2, 3] |
| 4 | Keep | [1, 2, 3, 4] |
| 4 | Skip | [1, 2, 3, 4] |
| 5 | Keep | [1, 2, 3, 4, 5] |
Why This Works
Step 1: Using uniq method
The uniq method scans the array and builds a new array with only the first occurrence of each element.
Step 2: Preserves order
uniq keeps the original order of elements, so the first time an element appears is kept.
Step 3: Returns new array
It returns a new array without duplicates, leaving the original array unchanged.
Alternative Approaches
array = [1, 2, 2, 3, 4, 4, 5] seen = {} unique_array = array.select { |e| !seen[e] && (seen[e] = true) } puts unique_array.inspect
array = [1, 2, 2, 3, 4, 4, 5] array.uniq! puts array.inspect
Complexity: O(n) time, O(n) space
Time Complexity
The uniq method scans each element once, so it runs in linear time relative to the array size.
Space Complexity
It creates a new array and a set of seen elements, so it uses extra space proportional to the number of unique elements.
Which Approach is Fastest?
Using uniq is the fastest and simplest for most cases; manual hash tracking is similar but more verbose; uniq! saves space by modifying in place.
| Approach | Time | Space | Best For |
|---|---|---|---|
| array.uniq | O(n) | O(n) | Simple, non-destructive duplicate removal |
| Manual hash tracking | O(n) | O(n) | Custom duplicate logic |
| array.uniq! | O(n) | O(1) extra | In-place modification to save memory |
array.uniq to quickly get a new array without duplicates while keeping the original array intact.uniq, which is less efficient and more error-prone.