Minimum Operations to Collect Elements — LeetCode 2869 Python Solution

EasyBit ManipulationArrayHash Table
Problem
#2869
Reading time
2 min

The 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.

Example

Input
nums = [3,1,5,4,2], k = 2
Output
4
Explanation
After 4 operations, we collect elements 2, 4, 5, and 1, in this order. Our collection contains elements 1 and 2. Hence, the answer is 4.

Python solution

Python
class Solution:
    def minOperations(self, nums: List[int], k: int) -> int:
        is_added = [False] * k
        count = 0
        n = len(nums)
        for i in range(n - 1, -1, -1):
            if nums[i] > k or is_added[nums[i] - 1]:
                continue
            is_added[nums[i] - 1] = True
            count += 1
            if count == k:
                return n - i

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array nums
SpaceO(k) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 2869. Minimum Operations to Collect Elements is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2869. Minimum Operations to Collect Elements?
LeetCode 2869. Minimum Operations to Collect Elements is rated Easy on LeetCode.
What is the time complexity of LeetCode 2869. Minimum Operations to Collect Elements?
The Python solution on this page runs in O(n), where n is the length of the array nums.
What is the space complexity of LeetCode 2869. Minimum Operations to Collect Elements?
The Python solution on this page uses O(k) auxiliary space.
What topics does LeetCode 2869. Minimum Operations to Collect Elements cover?
LeetCode 2869. Minimum Operations to Collect Elements is tagged Bit Manipulation, Array and Hash Table on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview