Minimum Operations to Make a Subsequence Problem
Description
LeetCode Problem 1713.
You are given an array target that consists of distinct integers and another integer array arr that can have duplicates.
In one operation, you can insert any integer at any position in arr. For example, if arr = [1,4,1,2], you can add 3 in the middle and make it [1,4,3,1,2]. Note that you can insert the integer at the very beginning or end of the array.
Return the minimum number of operations needed to make target a subsequence of arr.
A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the elements in bold), while [2,4,2] is not.
Example 1:
Input: target = [5,1,3], arr = [9,4,2,3,4]
Output: 2
Explanation: You can add 5 and 1 in such a way that makes arr = [5,9,4,1,2,3,4], then target will be a subsequence of arr.
Example 2:
Input: target = [6,4,8,1,3,2], arr = [4,7,6,2,3,8,6,1]
Output: 3
Constraints:
1 <= target.length, arr.length <= 10^51 <= target[i], arr[i] <= 10^9targetcontains no duplicates.
Solution
Approach: Longest Increasing Subsequence + Binary Indexed Tree
The elements of target that we do not insert must already appear in arr in order, so the answer is the length of target minus the longest common subsequence of target and arr. A normal LCS takes O(mn), which is too slow here.
Because target has distinct values, map each value to its index in target. Replace every element of arr that appears in target by that index and drop the rest. A common subsequence is now just an increasing subsequence of these indices, so the LCS length equals the longest strictly increasing subsequence of the new array (see 300. Longest Increasing Subsequence).
Compute it with a binary indexed tree that stores, for each index, the longest increasing subsequence ending there: for each index x, the best length is query(x - 1) + 1.
Complexity: O(n log m) time and O(m) space, where m and n are the lengths of target and arr.
class BinaryIndexedTree:
__slots__ = "n", "c"
def __init__(self, n: int):
self.n = n
self.c = [0] * (n + 1)
def update(self, x: int, v: int):
while x <= self.n:
self.c[x] = max(self.c[x], v)
x += x & -x
def query(self, x: int) -> int:
res = 0
while x:
res = max(res, self.c[x])
x -= x & -x
return res
class Solution:
def minOperations(self, target: List[int], arr: List[int]) -> int:
d = {x: i for i, x in enumerate(target, 1)}
nums = [d[x] for x in arr if x in d]
m = len(target)
tree = BinaryIndexedTree(m)
ans = 0
for x in nums:
v = tree.query(x - 1) + 1
ans = max(ans, v)
tree.update(x, v)
return len(target) - ans