From de2dbacb7dd23d9adefceaac585f09a59e2da1c5 Mon Sep 17 00:00:00 2001 From: "green.carlos" Date: Sat, 28 Feb 2026 09:26:39 -0800 Subject: [PATCH] Sorting and HashSet solutions for 1.1 isUnique --- chapter01/1.1 - Is Unique/isUnique.js | 37 +++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/chapter01/1.1 - Is Unique/isUnique.js b/chapter01/1.1 - Is Unique/isUnique.js index 3321571..ff435be 100644 --- a/chapter01/1.1 - Is Unique/isUnique.js +++ b/chapter01/1.1 - Is Unique/isUnique.js @@ -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');