-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgorithm.js
More file actions
59 lines (53 loc) · 1.75 KB
/
Copy pathalgorithm.js
File metadata and controls
59 lines (53 loc) · 1.75 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
48
49
50
51
52
53
54
55
56
57
58
59
// HOW DO YOU PRINT DUPLICATE CHARACTERS FROM A STRING.
//STEPS:
//VERIFY THE INPUTS/PROBLEMS
//Ensure that all inputs are strings, and i should not receive any empty string, i should throw false if not a string.
//THINK ABOUT THE PROBLEM + VERBAL SOLUTION
//Iterate over the string, store a new string in a new count , and add a string that appears more than one as a duplicate
//WRITE OUT THE FIRST VERSION
function printingDuplicateCharacters (str){
if(typeof str !=='string'|| str === ''){
return false;
}
let charCount = {};
let duplicateCount = '';
for(char of str){
console.log('times')
if (charCount[char]){
duplicateCount += char;
} else {
charCount[char] = 1;
}
}
return duplicateCount;
}
//VERIFY THE RESULTS
// console.log(printingDuplicateCharacters(''));
// console.log(printingDuplicateCharacters('Ikenna'));
// console.log(printingDuplicateCharacters('Akuchi'));
// console.log(printingDuplicateCharacters('dvsaghcsgvvhgcgdgcggvvbvbvbxvgagg'))
//DERIVE THE TIME COMPLEXITY
//Best case => Akuchi
//Average case =>Ikenna
//Worst case => dvsaghcsgvvhgcgdgcggvvbvbvbxvgagg
//Proportional to input size of n O(n)
//EXPLORE ALTERNATIVE SOLUTION.
function printingDuplicateCharacters (str){
if (typeof str !=='string' || str === ''){
return null;
}
let charCount = new Set();
let duplicateCount = [];
for(char of str){
if(charCount.has(char)){
duplicateCount.push(char);
}else{
charCount.add(char);
}
}
return duplicateCount;
}
console.log(printingDuplicateCharacters(''));
console.log(printingDuplicateCharacters('Mercy'));
console.log(printingDuplicateCharacters('Ogbenjuwa'));
console.log(printingDuplicateCharacters('dvsaghcsgvvhgcgdgcggvvbvbvbxvgagg'))