-
Notifications
You must be signed in to change notification settings - Fork 321
Expand file tree
/
Copy pathch1-q1.js
More file actions
47 lines (42 loc) · 1.07 KB
/
ch1-q1.js
File metadata and controls
47 lines (42 loc) · 1.07 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
'use strict';
/**
* Keep track of seen characters with a Set data structure, fail when
* a repeated character is found.
*
* Time: O(N)
* Additional space: O(N)
*
* @param {string[]} str String to check, passed in as a character array
* @return {boolean} True if unique characters, otherwise false
*/
export function hasUniqueCharactersSet(str) {
const chars = new Set();
for (const ch of str) {
if (chars.has(ch)) {
return false;
}
chars.add(ch);
}
return true;
}
/**
* Sort the original string first then iterate through it. Repeat characters
* will show up next to eachother so fail if any two characters in a row
* are the same.
*
* Time: O(N lg N)
* Additional space: O(1)
*
* @param {string[]} str String to check, passed in as a character array
* @return {boolean} True if unique characters, otherwise false
*/
export function hasUniqueCharactersSort(str) {
// sort string using quicksort
str.sort();
for (var i = 1; i < str.length; ++i) {
if (str[i] === str[i - 1]) {
return false;
}
}
return true;
}