#1713
Minimum Operations to Make a Subsequence
HardArrayHash TableBinary SearchGreedyHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
Instead of generating subsequences, we can map elements of `arr` to their indices in `target` to find the longest increasing subsequence (LIS). The number of operations needed will be the difference between the length of `target` and the length of the LIS.
⚙️
Algorithm
4 steps- 1Step 1: Create a mapping of each element in `target` to its index.
- 2Step 2: Transform `arr` into a new array of indices based on the mapping from `target` (ignore elements not in `target`).
- 3Step 3: Find the length of the longest increasing subsequence (LIS) in this new array.
- 4Step 4: The minimum operations needed is the difference between the length of `target` and the length of the LIS.
solution.py15 lines
1# Full working Python code
2from bisect import bisect_left
3
4def min_operations_optimal(target, arr):
5 index_map = {num: i for i, num in enumerate(target)}
6 transformed = [index_map[num] for num in arr if num in index_map]
7 lis = []
8 for num in transformed:
9 pos = bisect_left(lis, num)
10 if pos == len(lis):
11 lis.append(num)
12 else:
13 lis[pos] = num
14 return len(target) - len(lis)
15ℹ
Complexity note: The complexity is O(n log n) due to the binary search used to find the position in the LIS, and O(n) for transforming the array.
- 1Mapping elements to indices allows us to focus on the order rather than the values.
- 2Finding the longest increasing subsequence helps minimize the number of insertions needed.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.