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 a Subsequence INPUT target = [5, 1, 3] 5 1 3 arr = [9, 4, 2, 3, 4] 9 4 2 3 4 In target Not in target Goal: Make target a subsequence of arr with minimum insertions ALGORITHM STEPS 1 Build Position Map Map: 5-->0, 1-->1, 3-->2 2 Filter arr elements Keep only target elements 3 Convert to indices arr has only 3 --> [2] 4 Find LIS length LIS of [2] = 1 Calculation: Operations = len(target) - LIS Operations = 3 - 1 = 2 FINAL RESULT Output: 2 Insert 5 and 1 into arr: Before: [9,4,2,3,4] After: 5 1 9 4 2 3 4 Subsequence [5,1,3] OK - 2 Operations! Key Insight: This problem transforms into finding LIS! Elements already in correct order don't need insertion. Convert target elements to indices, find LIS in arr. Answer = target.length - LIS length. Time: O(n log n) using binary search for LIS. Space: O(n) for hash map. TutorialsPoint - Minimum Operations to Make a Subsequence | Hash Map + LIS Transformation
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