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.
|
|
Tests can be found at REPL.it