2357. Make Array Zero by Subtracting Equal Amounts LeetCode Solution
In this guide, you will get 2357. Make Array Zero by Subtracting Equal Amounts LeetCode Solution with the best time and space complexity. The solution to Make Array Zero by Subtracting Equal Amounts problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Make Array Zero by Subtracting Equal Amounts solution in C++
- Make Array Zero by Subtracting Equal Amounts solution in Java
- Make Array Zero by Subtracting Equal Amounts solution in Python
- Additional Resources
Problem Statement of Make Array Zero by Subtracting Equal Amounts
You are given a non-negative integer array nums. In one operation, you must:
Choose a positive integer x such that x is less than or equal to the smallest non-zero element in nums.
Subtract x from every positive element in nums.
Return the minimum number of operations to make every element in nums equal to 0.
Example 1:
Input: nums = [1,5,0,3,5]
Output: 3
Explanation:
In the first operation, choose x = 1. Now, nums = [0,4,0,2,4].
In the second operation, choose x = 2. Now, nums = [0,2,0,0,2].
In the third operation, choose x = 2. Now, nums = [0,0,0,0,0].
Example 2:
Input: nums = [0]
Output: 0
Explanation: Each element in nums is already 0 so no operations are needed.
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 100
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(n)
2357. Make Array Zero by Subtracting Equal Amounts LeetCode Solution in C++
class Solution {
public:
int minimumOperations(vector<int>& nums) {
unordered_set<int> seen(nums.begin(), nums.end());
return seen.size() - seen.contains(0);
}
};
/* code provided by PROGIEZ */
2357. Make Array Zero by Subtracting Equal Amounts LeetCode Solution in Java
class Solution {
public int minimumOperations(int[] nums) {
Set<Integer> seen = Arrays.stream(nums).boxed().collect(Collectors.toSet());
return seen.size() - (seen.contains(0) ? 1 : 0);
}
}
// code provided by PROGIEZ
2357. Make Array Zero by Subtracting Equal Amounts LeetCode Solution in Python
class Solution:
def minimumOperations(self, nums: list[int]) -> int:
return len(set(nums) - {0})
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.