-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0316-remove-duplicate-letters.js
More file actions
32 lines (26 loc) · 1022 Bytes
/
0316-remove-duplicate-letters.js
File metadata and controls
32 lines (26 loc) · 1022 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
/**
* Remove Duplicate Letters
* Time Complexity: O(N)
* Space Complexity: O(1)
*/
var removeDuplicateLetters = function (s) {
const characterLastIndices = new Map();
for (let currentPosition = 0; currentPosition < s.length; currentPosition++) {
characterLastIndices.set(s[currentPosition], currentPosition);
}
const outputStack = [];
const addedChars = new Set();
for (let stringIterator = 0; stringIterator < s.length; stringIterator++) {
const charFromSource = s[stringIterator];
if (addedChars.has(charFromSource)) {
continue;
}
while (outputStack.length > 0 && outputStack[outputStack.length - 1] > charFromSource && characterLastIndices.get(outputStack[outputStack.length - 1]) > stringIterator) {
const poppedElement = outputStack.pop();
addedChars.delete(poppedElement);
}
outputStack.push(charFromSource);
addedChars.add(charFromSource);
}
return outputStack.join('');
};