generated from filipe1309/shubcogen-template
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathsolution.ts
More file actions
54 lines (49 loc) · 1.58 KB
/
solution.ts
File metadata and controls
54 lines (49 loc) · 1.58 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
// Test: make test t=first-duplicate-value
function firstDuplicateValue(array: number[]): number {
// return mySolution1(array); // time O(n) | space O(n)
// return mySolution2(array); // time O(n^2) | space O(1)
// return solution2(array); // time O(n) | space O(n)
return solution3(array); // time O(n) | space O(1)
}
// Hash approach
// Complexity (worst-case): time O(n) | space O(n)
function mySolution1(array: number[]): number {
const hash = new Map<number, number>();
for (let i = 0; i < array.length; i++) {
if (hash.get(array[i])) return array[i];
hash.set(array[i], 1)
}
return -1;
}
// Brute Force approach
// Complexity (worst-case): time O(n^2) | space O(1)
function mySolution2(array: number[]): number {
let minDuplicatedIdx = Infinity;
for (let i = 0; i < array.length - 1; i++) {
for (let j = i + 1; j < array.length; j++) {
if (array[i] === array[j]) minDuplicatedIdx = Math.min(minDuplicatedIdx, j);
}
}
return array[minDuplicatedIdx] ?? -1;
}
// Set approach
// Complexity (worst-case): time O(n) | space O(n)
function solution2(array: number[]): number {
const seen = new Set();
for (let i = 0; i < array.length; i++) {
if (seen.has(array[i])) return array[i];
seen.add(array[i]);
}
return -1;
}
// Indices as values approach
// Complexity (worst-case): time O(n) | space O(1)
function solution3(array: number[]): number {
for (let i = 0; i < array.length; i++) {
const pos = Math.abs(array[i]) - 1;
if (array[pos] < 0) return Math.abs(array[i])
array[pos] *= -1;
}
return -1;
}
export default firstDuplicateValue;