Welcome to Subscribe On Youtube
Formatted question description: https://leetcode.ca/all/1713.html
1713. Minimum Operations to Make a Subsequence
Level
Hard
Description
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]
, 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^5
1 <= target[i], arr[i] <= 10^9
target
contains no duplicates.
Solution
The idea is quite straightforward. Find the length of the longest common subsequence of target
and arr
, and calculate the difference between the length of target
and the length of the longest common subsequence. However, an approach of O(n^2) will cause time limit exceeded.
Use a map to store the elements and the corresponding indices in target
. Then loop over arr
and use a list to store indices. If an element in arr
is in target
(which means the element is a key in the map), then add the element’s index in target
to the list. This problem is converted to finding the length of the longest increasing subsequence of list
. Use binary search to find the length of the longest increasing subsequence, which is the length of the longest common subsequence of target
and arr
. Then the minimum operations can be calculated.
-
class Solution { public int minOperations(int[] target, int[] arr) { int length1 = target.length, length2 = arr.length; Map<Integer, Integer> targetMap = new HashMap<Integer, Integer>(); for (int i = 0; i < length1; i++) targetMap.put(target[i], i); List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < length2; i++) { int num = arr[i]; if (targetMap.containsKey(num)) list.add(targetMap.get(num)); } int longestIncreasing = lengthOfLIS(list); return target.length - longestIncreasing; } public int lengthOfLIS(List<Integer> list) { int length = 1, size = list.size(); if (size == 0) return 0; int[] d = new int[size + 1]; d[length] = list.get(0); for (int i = 1; i < size; ++i) { if (list.get(i) > d[length]) { d[++length] = list.get(i); } else { int left = 1, right = length, pos = 0; while (left <= right) { int mid = (left + right) >> 1; if (d[mid] < list.get(i)) { pos = mid; left = mid + 1; } else { right = mid - 1; } } d[pos + 1] = list.get(i); } } return length; } } ############ class BinaryIndexedTree { private int n; private int[] c; public BinaryIndexedTree(int n) { this.n = n; this.c = new int[n + 1]; } public static int lowbit(int x) { return x & -x; } public void update(int x, int val) { while (x <= n) { c[x] = Math.max(c[x], val); x += lowbit(x); } } public int query(int x) { int s = 0; while (x > 0) { s = Math.max(s, c[x]); x -= lowbit(x); } return s; } } class Solution { public int minOperations(int[] target, int[] arr) { Map<Integer, Integer> d = new HashMap<>(); for (int i = 0; i < target.length; ++i) { d.put(target[i], i); } List<Integer> nums = new ArrayList<>(); for (int i = 0; i < arr.length; ++i) { if (d.containsKey(arr[i])) { nums.add(d.get(arr[i])); } } return target.length - lengthOfLIS(nums); } private int lengthOfLIS(List<Integer> nums) { TreeSet<Integer> ts = new TreeSet(); for (int v : nums) { ts.add(v); } int idx = 1; Map<Integer, Integer> d = new HashMap<>(); for (int v : ts) { d.put(v, idx++); } int ans = 0; BinaryIndexedTree tree = new BinaryIndexedTree(nums.size()); for (int v : nums) { int x = d.get(v); int t = tree.query(x - 1) + 1; ans = Math.max(ans, t); tree.update(x, t); } return ans; } }
-
// OJ: https://leetcode.com/problems/minimum-operations-to-make-a-subsequence/ // Time: O(T + AlogA) // Space: O(T + A) class Solution { public: int minOperations(vector<int>& T, vector<int>& A) { unordered_map<int, int> m; for (int i = 0; i < T.size(); ++i) m[T[i]] = i; vector<int> idx, lis; for (int n : A) { if (m.count(n)) idx.push_back(m[n]); } for (int n : idx) { int i = lower_bound(begin(lis), end(lis), n) - begin(lis); if (i == lis.size()) lis.push_back(n); else lis[i] = n; } return T.size() - lis.size(); } };
-
class BinaryIndexedTree: def __init__(self, n): self.n = n self.c = [0] * (n + 1) @staticmethod def lowbit(x): return x & -x def update(self, x, val): while x <= self.n: self.c[x] = max(self.c[x], val) x += BinaryIndexedTree.lowbit(x) def query(self, x): s = 0 while x: s = max(s, self.c[x]) x -= BinaryIndexedTree.lowbit(x) return s class Solution: def minOperations(self, target: List[int], arr: List[int]) -> int: d = {v: i for i, v in enumerate(target)} nums = [d[v] for v in arr if v in d] return len(target) - self.lengthOfLIS(nums) def lengthOfLIS(self, nums): s = sorted(set(nums)) m = {v: i for i, v in enumerate(s, 1)} tree = BinaryIndexedTree(len(m)) ans = 0 for v in nums: x = m[v] t = tree.query(x - 1) + 1 ans = max(ans, t) tree.update(x, t) return ans ############ # 1713. Minimum Operations to Make a Subsequence # https://leetcode.com/problems/minimum-operations-to-make-a-subsequence/ class Solution: def LIS(self, nums): stack = [] for x in nums: index = bisect_left(stack, x) if index == len(stack): stack.append(x) else: stack[index] = x return len(stack) def minOperations(self, target: List[int], arr: List[int]): mp = {x:i for i,x in enumerate(target)} stack = [] for x in arr: if x in mp: stack.append(mp[x]) return len(target) - self.LIS(stack)
-
type BinaryIndexedTree struct { n int c []int } func newBinaryIndexedTree(n int) *BinaryIndexedTree { c := make([]int, n+1) return &BinaryIndexedTree{n, c} } func (this *BinaryIndexedTree) lowbit(x int) int { return x & -x } func (this *BinaryIndexedTree) update(x, val int) { for x <= this.n { if this.c[x] < val { this.c[x] = val } x += this.lowbit(x) } } func (this *BinaryIndexedTree) query(x int) int { s := 0 for x > 0 { if s < this.c[x] { s = this.c[x] } x -= this.lowbit(x) } return s } func minOperations(target []int, arr []int) int { d := map[int]int{} for i, v := range target { d[v] = i } nums := []int{} for _, v := range arr { if i, ok := d[v]; ok { nums = append(nums, i) } } return len(target) - lengthOfLIS(nums) } func lengthOfLIS(nums []int) int { s := map[int]bool{} for _, v := range nums { s[v] = true } t := []int{} for v := range s { t = append(t, v) } sort.Ints(t) d := map[int]int{} for i, v := range t { d[v] = i + 1 } tree := newBinaryIndexedTree(len(d)) ans := 0 for _, v := range nums { x := d[v] t := tree.query(x-1) + 1 ans = max(ans, t) tree.update(x, t) } return ans } func max(a, b int) int { if a > b { return a } return b }