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
Minimum Operations to Collect Elements INPUT nums array: 3 i=0 1 i=1 5 i=2 4 i=3 2 i=4 Scan from END Input Values: nums = [3, 1, 5, 4, 2] k = 2 Need to collect: 1 2 ALGORITHM STEPS 1 i=4: Remove 2 collected={2}, ops=1 2 i=3: Remove 4 4 > k, skip. ops=2 3 i=2: Remove 5 5 > k, skip. ops=3 4 i=1: Remove 1 collected={1,2}, ops=4 Check: collected all 1..k? {1, 2} has size k=2: YES! Collection Progress: 2 4 5 1 FINAL RESULT Elements collected from end: 2 op 1 4 op 2 5 op 3 1 op 4 Needed (1 to k) Extra OUTPUT 4 operations OK - Verified! After 4 ops: collected {1, 2} = all of 1..k Key Insight: Single pass from end: We can only remove from the END, so scan backwards and track which elements 1..k we've seen. Use a Set to track collected elements. Stop when Set size equals k. Time: O(n), Space: O(k) for the collection set. Only add elements if they're in range [1, k]. TutorialsPoint - Minimum Operations to Collect Elements | Single Pass from End Approach
Asked in
Meta 15 Amazon 12 Google 8
15.0K Views
Medium Frequency
~15 min Avg. Time
450 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