Minimum Operations to Make a Subsequence LeetCode solution in JavaScript

1
var lengthOfLIS = function (A) {
2
if (!A.length) return 0;
3
let tails = [-Infinity]; //here -Infinity acts as a Sentinel, for cleaner code (or else I would ahve to place A[0] here)
4

5
for (let i = 0; i < A.length; i++) {
6
// If my curr element is bigger than all possible tails, i just need to create a new subarray, which of course will be of length tails.length-1 +1
7
if (A[i] > tails[tails.length - 1]) tails.push(A[i]);
8
else {
9
let lo = 0,
10
hi = tails.length - 1;
11
//binary search to find where to place my current element so i have more chances of creating a bigger subarray
12
while (lo < hi) {
13
let mid = (lo + hi) >> 1;
14
if (tails[mid] < A[i]) lo = mid + 1;
15
else hi = mid;
16
}
17
tails[lo] = A[i];
18
}
19
}
20
return tails.length - 1; // is the length of the longest possible subarray (-1 because of the -Infinity I added)
21
};
22
var minOperations = function (T, A) {
23
let seen = new Set(T),
24
res = 0,
25
originalIndex = {},
26
n = T.length;
27
//filter out all the unnecessary values
28
A = A.filter((d) => seen.has(d));
29
for (let i = 0; i < T.length; i++) originalIndex[T[i]] = i; //maintain the original indices of the values in T
30
A = A.map((d) => originalIndex[d]);
31
return T.length - lengthOfLIS(A);
32
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0