Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Checking if a string contains all unique characters using JavaScript
Problem
We are required to write a JavaScript function that takes in a string and returns true if all the characters in the string appear only once and false otherwise.
Method 1: Using indexOf() and lastIndexOf()
This approach compares the first and last occurrence of each character. If they differ, the character appears multiple times.
const str = 'thisconaluqe';
const allUnique = (str = '') => {
for(let i = 0; i < str.length; i++){
const el = str[i];
if(str.indexOf(el) !== str.lastIndexOf(el)){
return false;
};
};
return true;
};
console.log(allUnique(str));
true
Method 2: Using Set
A Set automatically removes duplicates. If the Set size equals the string length, all characters are unique.
const str = 'hello';
const allUniqueSet = (str = '') => {
return new Set(str).size === str.length;
};
console.log(allUniqueSet(str));
console.log(allUniqueSet('world'));
false true
Method 3: Using Object to Track Characters
This approach uses an object to track seen characters and returns false immediately when a duplicate is found.
const str = 'abcdef';
const allUniqueObject = (str = '') => {
const seen = {};
for(let char of str) {
if(seen[char]) {
return false;
}
seen[char] = true;
}
return true;
};
console.log(allUniqueObject(str));
console.log(allUniqueObject('aabbcc'));
true false
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| indexOf/lastIndexOf | O(n²) | O(1) | Good |
| Set | O(n) | O(n) | Excellent |
| Object tracking | O(n) | O(n) | Good |
Conclusion
The Set method is the most concise and efficient solution. Use indexOf/lastIndexOf for simplicity or object tracking for early termination on large strings.
Advertisements
