How to determine if a string contains only unique characters in JavaScript

Here are two ways to determine whether a string contains unique characters in JavaScript.

  • Hashmap solution:

    • Space complexity: O(n)
    • Time complexity: O(n)
  • Bit solution:

    • Space complexity: O(1)
    • Time complexity: O(n)

The bit solution can be likened to a mold of amber. Each letter carries a different bit signature. If we hold onto a variable that retains a 1 for each different character. If there ever is a case where that variable and the current character we are on overlap, that means we do not have a unique character and can return false.

Another approach could involve 2 for loops or sorting the string and checking it’s neighbor.
or another space efficient approach (at the expense of time) could involve using indexOf.

isUniqueTry in REPL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
function isUniqueMapWise(string) {
let isUnique = true;
const chars = string
.split('')
.reduce((map, char) => {
if (map[char]) {
map[char]++;
isUnique = false;
} else {
map[char] = 1;
}
return map;
}, {});
return isUnique;
}
function isUniqueBitwise(string) {
let checker = 0;
for (let i = 0; i < string.length; i++) {
const value = string.charCodeAt(i) - 'a'.charCodeAt(0);
if ((checker & (1 << value)) > 0) return false;
checker |= (1 << value);
}
return true;
}

Tests can be found at REPL.it