Minimum Operations to Make a Subsequence - 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.

Input & Output

Example 1 — Basic Case
$ Input: target = [5,1,3], arr = [9,4,2,3,4]
Output: 2
💡 Note: Only element 3 from target appears in arr at the correct relative position. We need to insert 5 and 1, so 2 operations are needed.
Example 2 — Multiple Elements Match
$ Input: target = [6,4,8,1,3,2], arr = [4,7,6,2,3,8,6,1]
Output: 3
💡 Note: The longest subsequence we can form is [4,6,8] or [4,2,3] or [6,8] etc. The optimal is length 3, so we need 6-3=3 operations.
Example 3 — No Common Elements
$ Input: target = [1,2,3], arr = [4,5,6]
Output: 3
💡 Note: No elements from target appear in arr, so we need to insert all 3 elements.

Constraints

  • 1 ≤ target.length ≤ 105
  • 1 ≤ arr.length ≤ 105
  • 1 ≤ target[i], arr[i] ≤ 109
  • All elements in target are distinct

Visualization

Tap to expand
Minimum Operations to Make SubsequenceTarget (need as subsequence):513Array (insert elements here):94234insert 5insert 1found!Longest common subsequence: [3] (length = 1)Operations needed: 3 - 1 = 2
Understanding the Visualization
1
Input Arrays
target=[5,1,3], arr=[9,4,2,3,4] - need target as subsequence of arr
2
Find Common Elements
Only element 3 appears in both arrays in valid position
3
Calculate Operations
Need to insert missing elements: 5 and 1 → 2 operations
Key Takeaway
🎯 Key Insight: Transform the problem into finding the Longest Increasing Subsequence after mapping elements to positions
Asked in
Google 15 Amazon 12 Facebook 8
12.5K Views
Medium Frequency
~35 min Avg. Time
456 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen