Minimum Operations to Collect Elements

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.

Example 1
Inputnums = [3,1,5,4,2], k = 2
Output4
After 4 operations, we collect elements 2, 4, 5, and 1, in this order, so the collection contains elements 1 and 2.
Example 2
Inputnums = [3,1,5,4,2], k = 5
Output5
After 5 operations, we collect elements 2, 4, 5, 1, and 3, in this order, so the collection contains elements 1 through 5.

Constraints

  • 1 <= nums.length <= 50
  • 1 <= nums[i] <= nums.length
  • 1 <= k <= nums.length
  • The input is generated such that you can collect elements 1, 2, ..., k.

Asked at 1 companies

Practice questions like this out loud in a mock coding interview with a live AI interviewer. First one free.

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, what to keep, what's wrong, and the complexity of your solution.

Sign in to evaluate