Minimum Operations to Make a Subsequence solution and explanation
6 more videos on this problem
【LCS/LIS】花花酱 LeetCode 1713. Minimum Operations to Make a Subsequence - 刷题找工作 EP379Hua Hua · 11:56 · 1K views
LeetCode 1713. Minimum Operations to Make a SubsequenceHappy Coding · 14:10 · 1K views
1713. Minimum Operations to Make a Subsequence (Leetcode Hard)Programming Live with Larry · 32:57 · 649 views
【每日一题】1713. Minimum Operations to Make a Subsequence, 1/4/2021Huifeng Guan · 20:36 · 540 views
Leetcode 1713. Minimum Operations to Make a Subsequence (LIS dp)LetsCode · 10:34 · 201 views
Leetcode 1713. Minimum Operations to Make a SubsequenceAlgorithms for Big Bucks · 13:26 · 143 views
LeetCode 1713: Minimum Operations to Make a SubsequenceAlitaCode · 29:25 · 8 views
The problem
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 makesarr= [5,9,4,1,2,3,4], then target will be a subsequence ofarr.
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 <= 1051 <= target[i], arr[i] <= 109targetcontains no duplicates.
Approach overview
Problem Overview: You are given two arrays: target (with distinct values) and arr. The task is to compute the minimum number of insert operations needed so that target becomes a subsequence of arr. Instead of simulating insertions directly, the key observation is that maximizing the part of target already appearing in order inside arr minimizes the required operations.
Approach 1: Dynamic Programming (O(n * m) time, O(n * m) space)
This approach treats the problem as a variation of the Longest Common Subsequence (LCS). Compute the LCS between target and arr using a DP table where dp[i][j] represents the LCS length for the first i elements of target and first j elements of arr. If elements match, extend the subsequence; otherwise take the maximum of skipping one element from either array. The minimum operations required equals target.length - LCS. While straightforward and useful for understanding subsequence alignment, the O(n * m) time complexity becomes too slow for large inputs.
Approach 2: Hash Map + Longest Increasing Subsequence (O(n log n) time, O(n) space)
The optimal solution converts the problem into a Longest Increasing Subsequence (LIS) problem. Since target contains unique values, create a hash map mapping each value to its index in target. Then iterate through arr and replace each element with its mapped index if it exists in the map. This produces a sequence of indices representing the order of elements relative to target.
The goal becomes finding the longest increasing subsequence of these indices. An increasing sequence means elements appear in the correct order relative to target. Compute LIS efficiently using binary search and a dynamic array that stores the smallest tail value for subsequences of each length. Each index either extends the sequence or replaces a larger tail via binary search.
If the LIS length is k, then k elements of target already appear in correct order inside arr. The remaining target.length - k elements must be inserted. This reduces the problem to a classic binary search optimization combined with hash table indexing and sequence processing over an array.
Recommended for interviews: The hash map + LIS approach is what most interviewers expect. It demonstrates the ability to transform a subsequence matching problem into an index-ordering problem and apply the O(n log n) LIS technique. The dynamic programming solution shows understanding of subsequences but does not scale well for the input constraints.
Approach 1: Using Hash Map and Longest Increasing Subsequence (LIS)
This approach uses a hash map (or dictionary) to map each element of the target to its index. We then convert the problem into finding the longest increasing subsequence in terms of the indices in the target array. By doing so, the number of insertions required corresponds to the difference between the target array length and the length of this subsequence.
from bisect import bisect_left
def minOperations(target, arr):
pos = {num: i for i, num in enumerate(target)}
lis = []
for num in arr:
if num in pos:
idx = pos[num]
insert_point = bisect_left(lis, idx)
if insert_point == len(lis):
lis.append(idx)
else:
lis[insert_point] = idx
return len(target) - len(lis)
# Example Usage
if __name__ == "__main__":
target = [5, 1, 3]
arr = [9, 4, 2, 3, 4]
print(minOperations(target, arr))import java.util.*;
public 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 num : arr) {
if (map.containsKey(num)) {
int idx = map.get(num);
int pos = Collections.binarySearch(lis, idx);
if (pos < 0) pos = -(pos + 1); // Get the insertion point
if (pos == lis.size()) {
lis.add(idx);
} else {
lis.set(pos, idx);
}
}
}
return target.length - lis.size();
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] target = {5, 1, 3};
int[] arr = {9, 4, 2, 3, 4};
System.out.println(sol.minOperations(target, arr));
}
}#include <vector>
#include <unordered_map>
#include <algorithm>
#include <iostream>
int minOperations(std::vector<int>& target, std::vector<int>& arr) {
std::unordered_map<int, int> pos;
for (int i = 0; i < target.size(); ++i) {
pos[target[i]] = i;
}
std::vector<int> lis;
for (int val : arr) {
if (pos.find(val) != pos.end()) {
int idx = pos[val];
auto it = std::lower_bound(lis.begin(), lis.end(), idx);
if (it == lis.end()) {
lis.push_back(idx);
} else {
*it = idx;
}
}
}
return target.size() - lis.size();
}
int main() {
std::vector<int> target = {5, 1, 3};
std::vector<int> arr = {9, 4, 2, 3, 4};
std::cout << minOperations(target, arr) << std::endl;
return 0;
}function minOperations(target, arr) {
const pos = new Map();
target.forEach((num, i) => pos.set(num, i));
const lis = [];
for (const num of arr) {
if (pos.has(num)) {
const idx = pos.get(num);
let left = 0, right = lis.length;
while (left < right) {
const mid = Math.floor((left + right) / 2);
if (lis[mid] < idx) left = mid + 1;
else right = mid;
}
if (left < lis.length) {
lis[left] = idx;
} else {
lis.push(idx);
}
}
}
return target.length - lis.length;
}
// Example Usage
console.log(minOperations([5, 1, 3], [9, 4, 2, 3, 4]));#include <stdio.h>
#include <stdlib.h>
int bisect_left(int* arr, int size, int x) {
int left = 0;
int right = size;
while (left < right) {
int mid = (left + right) / 2;
if (arr[mid] < x)
left = mid + 1;
else
right = mid;
}
return left;
}
int minOperations(int* target, int targetSize, int* arr, int arrSize) {
int *pos = malloc(1000000001 * sizeof(int));
for (int i = 0; i < targetSize; i++) {
pos[target[i]] = i + 1;
}
int *lis = malloc(arrSize * sizeof(int));
int lisSize = 0;
for (int i = 0; i < arrSize; i++) {
if (pos[arr[i]]) { // Means arr[i] is in target
int index = pos[arr[i]] - 1;
int idx = bisect_left(lis, lisSize, index);
if (idx < lisSize) {
lis[idx] = index;
} else {
lis[lisSize++] = index;
}
}
}
free(pos);
free(lis);
return targetSize - lisSize;
}
int main() {
int target[] = {5, 1, 3};
int arr[] = {9, 4, 2, 3, 4};
int operations = minOperations(target, 3, arr, 5);
printf("%d\n", operations);
return 0;
}using System;
using System.Collections.Generic;
public class Solution {
public int MinOperations(int[] target, int[] arr) {
Dictionary<int, int> pos = new Dictionary<int, int>();
for (int i = 0; i < target.Length; i++) {
pos[target[i]] = i;
}
List<int> lis = new List<int>();
foreach (int num in arr) {
if (pos.ContainsKey(num)) {
int index = pos[num];
int i = lis.BinarySearch(index);
if (i < 0) i = ~i; // bitwise negate to find insertion point
if (i == lis.Count) {
lis.Add(index);
} else {
lis[i] = index;
}
}
}
return target.Length - lis.Count;
}
static void Main(string[] args) {
Solution s = new Solution();
Console.WriteLine(s.MinOperations(new int[] { 5, 1, 3 }, new int[] { 9, 4, 2, 3, 4 }));
}
}This Python solution uses a dictionary to map each element of target to its index. It builds a list lis to keep track of the longest increasing indices subsequence. Elements in arr are checked against the dictionary and, if applicable, are dealt with using bisect_left for insertion in lis, ensuring efficiency of operations.
The solution features a time complexity of O(n log n) and a space complexity of O(n), due to the nature of subsequence finding with binary insertion point operations.
Approach 2: Using Dynamic Programming Approach
This approach uses dynamic programming to directly compute the operations necessary to form target directly. It keeps track of the length of the longest subsequence that can be achieved up to each position in arr, using knowledge of target positioning.
def min_operations(target, arr):
dp = [0] * (len(target) + 1)
for a in arr:
prev = 0
for j in range(1, len(target) + 1):
temp = dp[j]
if a == target[j - 1]:
dp[j] = prev + 1
else:
dp[j] = max(dp[j], dp[j - 1])
prev = temp
return len(target) - dp[-1]
# Example Usage
if __name__ == '__main__':
target = [5, 1, 3]
arr = [9, 4, 2, 3, 4]
print(min_operations(target, arr))public class Solution {
public int minOperations(int[] target, int[] arr) {
int[] dp = new int[target.length + 1];
for (int i = 1; i <= arr.length; i++) {
int prev = 0;
for (int j = 1; j <= target.length; j++) {
int temp = dp[j];
if (arr[i - 1] == target[j - 1])
dp[j] = prev + 1;
else
dp[j] = Math.max(dp[j - 1], dp[j]);
prev = temp;
}
}
return target.length - dp[target.length];
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] target = {5, 1, 3};
int[] arr = {9, 4, 2, 3, 4};
System.out.println(sol.minOperations(target, arr));
}
}#include <vector>
#include <iostream>
int minOperations(std::vector<int>& target, std::vector<int>& arr) {
std::vector<int> dp(target.size() + 1, 0);
for (int i = 1; i <= arr.size(); ++i) {
int prev = 0, cur;
for (int j = 1; j <= target.size(); ++j) {
cur = dp[j];
if (arr[i - 1] == target[j - 1])
dp[j] = prev + 1;
else
dp[j] = std::max(dp[j - 1], dp[j]);
prev = cur;
}
}
return target.size() - dp[target.size()];
}
int main() {
std::vector<int> target = {5, 1, 3};
std::vector<int> arr = {9, 4, 2, 3, 4};
std::cout << minOperations(target, arr) << std::endl;
return 0;
}function minOperations(target, arr) {
const dp = Array(target.length + 1).fill(0);
for (const a of arr) {
let prev = 0;
for (let j = 1; j <= target.length; j++) {
const temp = dp[j];
if (a === target[j - 1]) dp[j] = prev + 1;
else dp[j] = Math.max(dp[j], dp[j - 1]);
prev = temp;
}
}
return target.length - dp[target.length];
}
// Example Usage
console.log(minOperations([5, 1, 3], [9, 4, 2, 3, 4]));#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int minOperations(int* target, int targetSize, int* arr, int arrSize) {
int *dp = (int *)malloc((targetSize + 1) * sizeof(int));
memset(dp, 0, sizeof(int) * (targetSize + 1));
for (int i = 1; i <= arrSize; ++i) {
int last = 0, cur;
for (int j = 1; j <= targetSize; ++j) {
cur = dp[j];
if (arr[i - 1] == target[j - 1])
dp[j] = last + 1;
else
dp[j] = (dp[j - 1] > dp[j]) ? dp[j - 1] : dp[j];
last = cur;
}
}
int result = targetSize - dp[targetSize];
free(dp);
return result;
}
int main() {
int target[] = {5, 1, 3};
int arr[] = {9, 4, 2, 3, 4};
int operations = minOperations(target, 3, arr, 5);
printf("%d\n", operations);
return 0;
}using System;
public class Solution {
public int MinOperations(int[] target, int[] arr) {
int[] dp = new int[target.Length + 1];
for (int i = 1; i <= arr.Length; i++) {
int prev = 0;
for (int j = 1; j <= target.Length; j++) {
int temp = dp[j];
if (arr[i - 1] == target[j - 1])
dp[j] = prev + 1;
else
dp[j] = Math.Max(dp[j - 1], dp[j]);
prev = temp;
}
}
return target.Length - dp[target.Length];
}
public static void Main(string[] args) {
Solution s = new Solution();
Console.WriteLine(s.MinOperations(new int[] { 5, 1, 3 }, new int[] { 9, 4, 2, 3, 4 }));
}
}This Python solution utilizes dynamic programming for subsequence detection by maintaining a dp list with potential chain lengths. Each element in arr is matched against elements of target within a nested loop structure, updating dp sequentially.
The solution has a time complexity of O(n * m) with a space complexity of O(m). While less optimal on larger scales, it delivers thorough positional analysis across sequences.
Approach 3: Longest Increasing Subsequence + Binary Indexed Tree
According to the problem statement, the longer the common subsequence between target and arr, the fewer elements need to be added. Therefore, the minimum number of elements to be added equals the length of target minus the length of the longest common subsequence between target and arr.
However, the time complexity of finding the longest common subsequence is O(m times n), which cannot pass this problem. We need to change our approach.
We can use a hash table to record the index of each element in the target array, then iterate through the arr array. For each element in the arr array, if the hash table contains that element, we add the index of that element to an array. This gives us a new array nums, which represents the indices in the target array of elements from arr (excluding elements not in target). The length of the longest increasing subsequence of this array nums is the length of the longest common subsequence between target and arr.
Therefore, the problem is transformed into finding the length of the longest increasing subsequence of the nums array. Refer to 300. Longest Increasing Subsequence.
The time complexity is O(n times log m), and the space complexity is O(m). Here, m and n are the lengths of target and arr, respectively.
class BinaryIndexedTree {
private n: number;
private c: number[];
constructor(n: number) {
this.n = n;
this.c = Array(n + 1).fill(0);
}
update(x: number, v: number): void {
for (; x <= this.n; x += x & -x) {
this.c[x] = Math.max(this.c[x], v);
}
}
query(x: number): number {
let ans = 0;
for (; x > 0; x -= x & -x) {
ans = Math.max(ans, this.c[x]);
}
return ans;
}
}
function minOperations(target: number[], arr: number[]): number {
const m = target.length;
const d: Map<number, number> = new Map();
target.forEach((x, i) => d.set(x, i + 1));
const nums: number[] = [];
arr.forEach(x => {
if (d.has(x)) {
nums.push(d.get(x)!);
}
});
const tree = new BinaryIndexedTree(m);
let ans = 0;
nums.forEach(x => {
const v = tree.query(x - 1) + 1;
ans = Math.max(ans, v);
tree.update(x, v);
});
return m - ans;
}type BinaryIndexedTree struct {
n int
c []int
}
func NewBinaryIndexedTree(n int) BinaryIndexedTree {
return BinaryIndexedTree{n: n, c: make([]int, n+1)}
}
func (bit *BinaryIndexedTree) Update(x, v int) {
for ; x <= bit.n; x += x & -x {
if v > bit.c[x] {
bit.c[x] = v
}
}
}
func (bit *BinaryIndexedTree) Query(x int) int {
ans := 0
for ; x > 0; x -= x & -x {
if bit.c[x] > ans {
ans = bit.c[x]
}
}
return ans
}
func minOperations(target []int, arr []int) int {
m := len(target)
d := make(map[int]int)
for i, x := range target {
d[x] = i + 1
}
var nums []int
for _, x := range arr {
if pos, exists := d[x]; exists {
nums = append(nums, pos)
}
}
tree := NewBinaryIndexedTree(m)
ans := 0
for _, x := range nums {
v := tree.Query(x-1) + 1
if v > ans {
ans = v
}
tree.Update(x, v)
}
return m - ans
}Complexity comparison
| Approach | Complexity |
|---|---|
| Using Hash Map and Longest Increasing Subsequence (LIS) | The solution features a time complexity of O(n log n) and a space complexity of O(n), due to the nature of subsequence finding with binary insertion point operations. |
| Using Dynamic Programming Approach | The solution has a time complexity of O(n * m) with a space complexity of O(m). While less optimal on larger scales, it delivers thorough positional analysis across sequences. |
| Longest Increasing Subsequence + Binary Indexed Tree | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Dynamic Programming (LCS) | O(n * m) | O(n * m) | Good for learning subsequence matching or when constraints are small |
| Hash Map + Longest Increasing Subsequence | O(n log n) | O(n) | Optimal for large inputs; converts order matching into LIS using binary search |
Frequently asked questions
Is Minimum Operations to Make a Subsequence easy or hard?
LeetCode classifies this problem as Hard because it requires recognizing the transformation to a Longest Increasing Subsequence problem. Once that insight is clear, the implementation becomes a standard O(n log n) LIS solution using binary search.
Minimum Operations to Make a Subsequence Python or Java solution?
Python and Java solutions both follow the same strategy: build a map from target values to indices, convert arr into a filtered index sequence, and compute LIS using binary search. The logic remains identical across languages, with only syntax differences in map creation and binary search utilities.
How to solve Minimum Operations to Make a Subsequence in O(n log n)?
First map each value in target to its index using a hash table. Iterate through arr and build a list of indices corresponding to elements that appear in target. Then compute the Longest Increasing Subsequence of this index list using binary search. The number of insert operations required is target.length minus the LIS length.
What is the best approach for Minimum Operations to Make a Subsequence?
The optimal approach uses a hash map combined with the Longest Increasing Subsequence (LIS) algorithm. Map each value in target to its index, convert arr into a sequence of those indices, and compute LIS using binary search. The LIS length represents the longest ordered match, and the required operations equal target.length minus that length. This runs in O(n log n) time with O(n) space.
Is Minimum Operations to Make a Subsequence asked at Google/Amazon/Meta?
Problems involving LIS transformations, subsequences, and hash map indexing are common in interviews at companies like Google, Amazon, and Meta. This specific LeetCode problem tests the ability to reduce a sequence alignment problem into an LIS problem with binary search optimization.
What data structure is used in Minimum Operations to Make a Subsequence?
The main data structures are a hash map for mapping values to indices and a dynamic array used in the LIS algorithm. Binary search is applied on this array to maintain the smallest possible tail values for subsequences of each length.
What is the time complexity of Minimum Operations to Make a Subsequence?
The optimal solution runs in O(n log n) time using a hash map and binary search based LIS algorithm. Building the index map takes O(n), scanning arr takes O(m), and each LIS update costs O(log n). A brute-force dynamic programming approach using LCS would take O(n * m) time and is not practical for large inputs.
