Skip to content

Instantly share code, notes, and snippets.

@alexspark
Last active May 20, 2017 22:34
Show Gist options
  • Save alexspark/b822803466d895b5c5f2297a3318ae90 to your computer and use it in GitHub Desktop.
Save alexspark/b822803466d895b5c5f2297a3318ae90 to your computer and use it in GitHub Desktop.
inUnique created by alexspark - https://repl.it/IIzm/1
// Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?
// brute force: for each character, iterate over each character in word, if character is not self and is found, return false. time: O(n^2) where n is # of characters in word, space: O(1);
// first appraoch: for each character, look up visited hash table to see if it exists, if not add it to visited. if exists, return false. return true at end of loop. time: O(n), space: O(n);
let isUnique = (word) => {
let visited = {};
for (var char of word) {
if (!!visited[char]) {
return false
} else {
visited[char] = true;
}
}
return true;
};
// optimized approach: have an array of length that is the number of characters possible in a word and the values initialized to false. Same appraoch as the first. characters during iteration are lookedup based on their ASCII code point and if the code point was already visited, return false. time: O(n), space: O(1)
let isUniqueOptimized = (word) => {
let visited = (new Array(26)).fill(false);
let ascii = (char) => char.toLowerCase().charCodeAt(0) - 97;
for (var char of word) {
let code = ascii(char);
if (!!visited[code]) {
return false;
} else {
visited[code] = true;
}
}
return true;
}
let isUniqueBin = (word) => {
let visited = 0b0;
for (var char of word) {
let charAsBinary = 1 << (char.toLowerCase().charCodeAt(0) - 97);
if (visited & charAsBinary > 0) {
return false;
} else {
visited |= charAsBinary
}
}
return true;
}
let words = [
"elephant",
"flower",
"dog",
"cat",
"racecar"
];
for (var word of words) {
console.log(`${word}: isUnique:${isUnique(word)}, \
isUniqueOptimized:${isUniqueOptimized(word)} \
isUniqueBin:${isUniqueBin(word)}`)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment