Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions chapter01/1.1 - Is Unique/isUnique.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,43 @@ function everyCharUnique(str) {
return true;
}

/**
Sorting solution
Time O(n log n)
Space O(n) [for recursion]

We can also sort the input string as an array
Then iterate over the input string
If we find a duplicate character return false

Otherwise if we get through the entire string return true

**/

function everyCharUnique(string) {
const str = string.split('').sort()
for (let i = 1; i < str.length; i++) {
if (str[i] === str[i - 1]) {
return false
}
}
return true
}

/**
HashSet Solution
Time & Space O(n)

The Hashing function can also be reduced to two lines
Utilizing a HashSet function, we only keep track of unique elements
Then compare the length / size of both string & set respectively
**/
function everyCharUnique(string) {
const set = new Set(string.split(''))
return string.length === set.size
}


/* TESTS */
console.log(everyCharUnique('abcd'), 'true');
console.log(everyCharUnique('abccd'), 'false');
Expand Down