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 underlined elements), 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 makesarr
= [5,9,4,1,2,3,4], then target will be a subsequence ofarr
.
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 <= 105
1 <= target[i], arr[i] <= 109
target
contains no duplicates.
Solution: Reduce to LIS
The original problem is a LCS (Longest common subsequence) problem that can be solved in O(n*m) time.
Since the elements in the target array is unique, we can convert the numbers into indices that helps to reduce the problem to LIS (Longest increasing subsequence) that can be solved in O(mlogn) time.
e.g.
target: [6,4,8,1,3,2] => [0, 1, 2, 3, 4, 5]
array: [4,7,6,2,3,8,6,1] => [1,-1, 0, 5, 4, 2, 0, 3] => [1, 0, 5, 4, 2, 3]
and the LIS is [0, 2, 3] => [6, 8, 1], we need to insert the rest of the numbers.
Ans = len(target) – len(LIS)
Time complexity: O(nlogm)
Space complexity: O(m)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Author: Huahua class Solution { public: int minOperations(vector<int>& A, vector<int>& B) { unordered_map<int, int> m; for (int i = 0; i < A.size(); ++i) m[A[i]] = i; vector<int> dp; for (int x : B) { auto mit = m.find(x); if (mit == end(m)) continue; const int idx = mit->second; if (dp.empty() || idx > dp.back()) dp.push_back(idx); else *lower_bound(begin(dp), end(dp), idx) = idx; } return A.size() - dp.size(); } }; |
Python3
1 2 3 4 5 6 7 8 9 10 |
# Author: Huahua class Solution: def minOperations(self, A: List[int], B: List[int]) -> int: m = {x: i for i, x in enumerate(A)} dp = [] for x in B: if x not in m: continue if not dp or m[x] > dp[-1]: dp.append(m[x]) else: dp[bisect_left(dp, m[x])] = m[x] return len(A) - len(dp) |