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: 1
💡 Note: Only need to collect number 1. Working backwards, we don't find 1 in the last element (2), but we only need k=1 distinct numbers from 1 to k, so we need more operations until we find 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 1 through kGoal: Collect all numbers from 1 to k by removing from end31542Input: nums = [3,1,5,4,2], k = 2Remove from end →← Until we collect {1,2}Op 4: Remove 3Op 3: Remove 1 ✓Op 2: Remove 5Op 1: Remove 4Op 0: Remove 2 ✓Output: 4 operations neededStop when we have collected all numbers from 1 to k
Understanding the Visualization
1
Input
Array [3,1,5,4,2] and k=2 (need to collect 1,2)
2
Process
Remove from end: 2→4→5→1, stop when we have {1,2}
3
Output
Return 4 (minimum operations needed)
Key Takeaway
🎯 Key Insight: Work backwards from the end and stop as soon as you've collected all required numbers
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