Skip to content

1713. Minimum Operations to Make a Subsequence

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] (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 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 <= 105
  • 1 <= target[i], arr[i] <= 109
  • target contains no duplicates.

 

Solutions

Solution: Binary Search + Hash Map

  • Time complexity: O(m+nlogn)
  • Space complexity: O(m+n)

 

JavaScript

js
/**
 * @param {number[]} target
 * @param {number[]} arr
 * @return {number}
 */
const minOperations = function (target, arr) {
  const m = target.length;
  const n = arr.length;
  const targetMap = new Map();
  const indices = [];

  for (let index = 0; index < m; index++) {
    const num = target[index];

    targetMap.set(num, index);
  }

  for (let index = 0; index < n; index++) {
    const num = arr[index];

    if (!targetMap.has(num)) continue;

    indices.push(targetMap.get(num));
  }

  const findFirstGreaterEqual = (nums, current) => {
    let left = 0;
    let right = nums.length - 1;

    while (left <= right) {
      const mid = Math.floor((left + right) / 2);

      nums[mid] >= current ? (right = mid - 1) : (left = mid + 1);
    }

    return left;
  };

  const lengthOfLIS = nums => {
    const tails = [];

    for (const num of nums) {
      if (!tails.length || num > tails.at(-1)) {
        tails.push(num);
      } else {
        const index = findFirstGreaterEqual(tails, num);

        tails[index] = num;
      }
    }

    return tails.length;
  };

  return m - lengthOfLIS(indices);
};

Released under the MIT license