Minimum Operations to Collect Elements - Problem
You are given an array nums of positive integers and an integer k.
In one operation, you can remove the last element of the array and add it to your collection.
Return the minimum number of operations needed to collect elements 1, 2, ..., k.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [3,1,5,4,2], k = 2
›
Output:
4
💡 Note:
Working backwards: remove 2 (have {2}), remove 4 (have {2}), remove 5 (have {2}), remove 1 (have {1,2}). We need 4 operations to collect both 1 and 2.
Example 2 — Numbers at End
$
Input:
nums = [3,1,3,2,2], k = 1
›
Output:
4
💡 Note:
Need to collect number 1. Working backwards: remove 2 (not ≤ 1), remove 2 (not ≤ 1), remove 3 (not ≤ 1), remove 1 (have {1}). We need 4 operations to collect 1.
Example 3 — All Numbers Present
$
Input:
nums = [2,1,3], k = 2
›
Output:
3
💡 Note:
Working backwards: remove 3 (not needed), remove 1 (have {1}), remove 2 (have {1,2}). Need 3 operations total.
Constraints
- 1 ≤ nums.length ≤ 1000
- 1 ≤ k ≤ nums.length
- 1 ≤ nums[i] ≤ 1000
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code