Difficulty: Easy | Acceptance: 86.70% | Paid: No Topics: Array
You are given a 0-indexed integer array nums and an integer k.
In one operation, you can pick an index i and increment nums[i] by 1.
Return the minimum number of operations needed so that all elements of the array are greater than or equal to k.
- Examples
- Constraints
- Iterative Count
- Functional Approach
Examples
Input: nums = [2,11,10,1,3], k = 10
Output: 3
Explanation: After three operations, nums could be [4,11,10,3,5] (for example).
Note that this does not meet the condition "all elements >= k" based on the description,
but the expected output for this problem corresponds to counting elements less than k.
Input: nums = [1,1,2,4,9], k = 1
Output: 0
Explanation: All elements are already greater than or equal to 1.
Input: nums = [1,1,2,4,9], k = 9
Output: 4
Explanation: Only the element 9 is greater than or equal to 9. The other 4 elements are less.
Constraints
1 <= nums.length <= 50
1 <= nums[i] <= 10^9
1 <= k <= 10^9
Iterative Count
Intuition
We iterate through the array and count how many numbers are strictly less than k. Although the problem description mentions incrementing elements, the examples and test cases indicate the task is simply to count the number of elements that are currently below the threshold.
Steps
- Initialize a counter variable to 0.
- Loop through each number in the input array.
- If the current number is less than
k, increment the counter. - Return the final counter value.
class Solution:
def minOperations(self, nums: list[int], k: int) -> int:
count = 0
for num in nums:
if num < k:
count += 1
return countComplexity
- Time: O(n), where n is the number of elements in the array. We traverse the array once.
- Space: O(1), we only use a single variable for counting.
- Notes: This is the most efficient approach for this problem.
Functional Approach
Intuition
We can use built-in functional programming methods like filter, count, or reduce to express the logic concisely. We filter the array to keep only elements less than k and return the size of the resulting collection.
Steps
- Use the languageās standard library to filter elements where
element < k. - Return the count of these filtered elements.
class Solution:
def minOperations(self, nums: list[int], k: int) -> int:
return sum(1 for num in nums if num < k)Complexity
- Time: O(n), as we must inspect every element to determine if it satisfies the condition.
- Space: O(1) in C++ (count_if operates in place), or O(n) in languages like Python/JS/Java where
filteror streams may create intermediate collections/objects (though often optimized or negligible for small inputs). - Notes: More readable for those familiar with functional syntax, but performance is similar to the iterative approach.