LeetCode 1713: Minimum Operations to Make a Subsequence

Problem Description

Explanation

To solve this problem, we can first create a mapping of elements in the target array to their indices. Then, we iterate through the arr array and for each element that is present in the target array, we update the longest increasing subsequence (LIS) ending with that element. Finally, the answer to the problem will be the length of the target array minus the length of the LIS we found.

Algorithm:

  1. Create a mapping of elements in target to their indices.
  2. Initialize an empty array to store the LIS ending with each element in arr.
  3. Iterate through each element in arr.
    • If the element is present in the target array, update the LIS ending with that element.
  4. Return the answer as the length of target minus the length of the longest LIS found.

Time Complexity: O(nlogn) where n is the length of the arr array.
Space Complexity: O(n) where n is the length of the arr array.

Solutions

class Solution {
    public int minOperations(int[] target, int[] arr) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < target.length; i++) {
            map.put(target[i], i);
        }
        
        List<Integer> lis = new ArrayList<>();
        for (int val : arr) {
            if (map.containsKey(val)) {
                int idx = map.get(val);
                int pos = Collections.binarySearch(lis, idx);
                if (pos < 0) {
                    pos = -(pos + 1);
                }
                if (pos == lis.size()) {
                    lis.add(idx);
                } else {
                    lis.set(pos, idx);
                }
            }
        }
        
        return target.length - lis.size();
    }
}

Loading editor...