Problem Description
Given two arrays target and arr, the goal is to determine the minimum number of insert operations needed on arr so that target becomes a subsequence of arr. The target array contains distinct integers, while arr may include duplicates. An insert operation allows you to add any integer at any position in arr.
Key Insights
- Map each value in target to its index so that the relative order in target is maintained.
- Transform arr into a sequence of indices based on the mapping (ignoring elements not in target).
- The problem then reduces to finding the Longest Increasing Subsequence (LIS) in this transformed sequence.
- The minimum operations required equals the length of target minus the length of the LIS.
Space and Time Complexity
Time Complexity: O(n log n) where n is the length of arr (each element is processed and binary search is used for the LIS). Space Complexity: O(n) for storing the mapped sequence and the auxiliary list used in computing the LIS.
Solution
We start by creating a mapping from each element in target to its index. Then, iterate through arr and, for each element that exists in target, convert it to its corresponding index. This gives us a new sequence. The task of finding the longest matching subsequence in arr now becomes finding the longest increasing subsequence (LIS) in this new sequence, which can be efficiently computed using a binary search technique. The final answer is obtained by subtracting the length of this LIS from the length of target.