Ruby Program to Remove Duplicates from String
string.chars.uniq.join, which splits the string into characters, removes duplicates, and joins them back.Examples
How to Think About It
Algorithm
Code
def remove_duplicates(str) str.chars.uniq.join end puts remove_duplicates("hello") puts remove_duplicates("banana") puts remove_duplicates("")
Dry Run
Let's trace the string "banana" through the code
Input string
"banana"
Split into characters
["b", "a", "n", "a", "n", "a"]
Remove duplicates with uniq
["b", "a", "n"]
Join characters back
"ban"
| Iteration | Character | Unique Characters So Far |
|---|---|---|
| 1 | b | b |
| 2 | a | ba |
| 3 | n | ban |
| 4 | a | ban |
| 5 | n | ban |
| 6 | a | ban |
Why This Works
Step 1: Split string into characters
Using chars breaks the string into an array of single characters so we can work with each one.
Step 2: Remove duplicates
uniq keeps only the first occurrence of each character, removing any repeats.
Step 3: Join characters back
join combines the unique characters array back into a single string without duplicates.
Alternative Approaches
def remove_duplicates(str) seen = {} result = "" str.each_char do |char| unless seen[char] result += char seen[char] = true end end result end puts remove_duplicates("hello")
def remove_duplicates(str) str.gsub(/(.)(?=.*\1)/, '') end puts remove_duplicates("banana")
Complexity: O(n) time, O(n) space
Time Complexity
The method loops through each character once to create an array and then removes duplicates, so it runs in linear time relative to string length.
Space Complexity
Extra space is used to store the array of characters and the unique characters, so space grows linearly with input size.
Which Approach is Fastest?
Using chars.uniq.join is both concise and efficient, while manual loops add overhead and regex can be slower and harder to read.
| Approach | Time | Space | Best For |
|---|---|---|---|
| chars.uniq.join | O(n) | O(n) | Simple and readable code |
| Loop with set | O(n) | O(n) | Explicit control, easy to customize |
| Regex | O(n^2) | O(n) | Compact but less readable, slower on large strings |
string.chars.uniq.join for a quick and readable way to remove duplicates.