-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathisUnique.js
More file actions
41 lines (35 loc) · 904 Bytes
/
isUnique.js
File metadata and controls
41 lines (35 loc) · 904 Bytes
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
const assert = require('assert');
const {generateRandomString, benchmark} = require('./utils');
/*
returns true if the string has unique characters
version BIG O(n^2) ?
*/
function isUnique(str){
for(let i = 0; i < str.length; i++){
for(let j = i + 1; j < str.length; j++){
if(str[i] === str[j]) return false;
}
}
return true;
}
/*
version Big O(n) runtime?
*/
function isUnique2(str){
const memo = {};
for(let i = 0; i < str.length; i++){
if (memo[str[i]]) return false;
memo[str[i]] = true;
}
return true;
}
function basicTests(){
assert.equal(isUnique('a'), true);
assert.equal(isUnique('aa'), false);
assert.equal(isUnique2('a'), true);
assert.equal(isUnique('abca'), false);
}
basicTests();
let str = generateRandomString(500);
console.log(str);
benchmark(isUnique, isUnique2, str, 100_000);