Skip to main content
Back to problems
#1713
Hard Algorithms

Minimum operations to make a subsequence

Array Hash Table Binary Search Greedy
49.6% acceptance
Feb 25, 2026
764
15
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. 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.

Solution

Rust
Time O(n log n)
Space O(n)
LeetCode
solution.rs
use std::collections::HashMap;

impl Solution {
  pub fn min_operations(target: Vec<i32>, arr: Vec<i32>) -> i32 {
    // LCS(target, arr) == LIS of mapped arr, since target has distinct elements
    // Map each target value to its index
    let pos: HashMap<i32, usize> = target.iter().enumerate().map(|(i, &v)| (v, i)).collect();
    // Transform arr to indices in target (ignore elements not in target)
    let mapped: Vec<usize> = arr.iter().filter_map(|v| pos.get(v).cloned()).collect();
    // Find LIS length using patience sorting (O(n log n))
    let mut tails: Vec<usize> = Vec::new();
    for &x in &mapped {
      let pos = tails.partition_point(|&t| t < x);
      if pos == tails.len() {
        tails.push(x);
      } else {
        tails[pos] = x;
      }
    }
    (target.len() - tails.len()) as i32
  }
}