JavaScript Program to Check if String Has All Unique Characters
new Set(string).size === string.length which returns true if all characters are unique, otherwise false.Examples
How to Think About It
Algorithm
Code
function hasAllUniqueChars(str) { return new Set(str).size === str.length; } console.log(hasAllUniqueChars('abcde')); // true console.log(hasAllUniqueChars('hello')); // false console.log(hasAllUniqueChars('')); // true
Dry Run
Let's trace the string 'hello' through the code to see how it detects duplicates.
Input string
str = 'hello'
Create Set
Set = {'h', 'e', 'l', 'o'} (size 4)
Compare sizes
Set size (4) !== str length (5)
Return result
false (string has duplicates)
| Iteration | Character | Set Contents | Set Size | String Length | Result |
|---|---|---|---|---|---|
| 1 | h | {'h'} | 1 | 5 | Continue |
| 2 | e | {'h','e'} | 2 | 5 | Continue |
| 3 | l | {'h','e','l'} | 3 | 5 | Continue |
| 4 | l | {'h','e','l'} | 3 | 5 | Duplicate found |
| 5 | o | {'h','e','l','o'} | 4 | 5 | End |
Why This Works
Step 1: Using a Set
A Set stores only unique values, so when we add characters from the string, duplicates are ignored.
Step 2: Comparing sizes
If the number of unique characters (Set size) matches the string length, it means no duplicates exist.
Step 3: Return boolean
The comparison returns true if all characters are unique, otherwise false.
Alternative Approaches
function hasAllUniqueChars(str) { const seen = new Set(); for (const char of str) { if (seen.has(char)) return false; seen.add(char); } return true; } console.log(hasAllUniqueChars('abcde')); // true console.log(hasAllUniqueChars('hello')); // false
function hasAllUniqueChars(str) { const chars = {}; for (let i = 0; i < str.length; i++) { if (chars[str[i]]) return false; chars[str[i]] = true; } return true; } console.log(hasAllUniqueChars('abcde')); // true console.log(hasAllUniqueChars('hello')); // false
Complexity: O(n) time, O(n) space
Time Complexity
Creating a Set from the string takes O(n) time because it processes each character once.
Space Complexity
The Set stores up to n unique characters, so space is O(n).
Which Approach is Fastest?
Using a loop with early return on duplicates can be faster in practice for strings with duplicates, but the Set size comparison is simpler and concise.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Set size comparison | O(n) | O(n) | Simple and concise code |
| Loop with Set and early return | O(n) best, faster on duplicates | O(n) | Performance when duplicates appear early |
| Object tracking | O(n) | O(n) | Compatibility with older JS versions |