↓Skip to main content
  1. LeetCode/

LeetCode 2357: Make Array Zero by Subtracting Equal Amounts

·1 min· ·
LeetCode Easy Array Hash-Table Greedy Sorting
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-11-21

  • Submissions: Runtime Error → Accepted

Approach
#

Each operation subtracts the smallest positive x: every value equal to x becomes 0 and the differences among larger values stay the same, so distinct values never merge. Each distinct positive value takes exactly one operation: len(set(nums) - {0}) (Hash Table).

My Attempts
#

Attempt 1 wrote len(set(nums)) - {0}, misplacing the parenthesis and subtracting a set from an integer (TypeError). len(set(nums) - {0}) passed.

Solution
#

class Solution:
    def minimumOperations(self, nums: List[int]) -> int:
        return len(set(nums) - {0})

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • Zeros need no operation; remove 0 from the set.
  • Parenthesize the whole set expression: len(set(nums) - {0}).

Interview Explanation
#

Subtracting the smallest positive value zeroes its group while preserving the gaps among the rest, so each distinct positive value takes one operation and the answer is their count. Time O(n).

Related

LeetCode 1122: Relative Sort Array
·1 min
LeetCode Easy Array Hash-Table Sorting Counting-Sort
LeetCode 1122 note: count first, emit values in arr2’s order, then append the remaining values in ascending order
LeetCode 1005: Maximize Sum Of Array After K Negations
·1 min
LeetCode Easy Array Greedy Sorting
LeetCode 1005 note: negate the smallest value each time; once the smallest is positive, only the parity of the remaining count matters
LeetCode 888: Fair Candy Swap
·2 mins
LeetCode Easy Array Hash-Table Binary-Search Sorting
LeetCode 888 note: equal sums after swapping x and y means y = x + (sumB - sumA) / 2; put B in a set and check each x from A
LeetCode 645: Set Mismatch
·2 mins
LeetCode Easy Array Hash-Table Bit-Manipulation Sorting
LeetCode 645 note: use sums: missing = sum of 1..n - sum of the set, duplicate = array sum - sum of the set
LeetCode 561: Array Partition
·1 min
LeetCode Easy Array Greedy Sorting Counting-Sort
LeetCode 561 note: sort and pair neighbors; each pair’s minimum is the element at an even index, so sum those
LeetCode 455: Assign Cookies
·2 mins
LeetCode Easy Array Two-Pointers Greedy Sorting
LeetCode 455 note: sort children and cookies, satisfying the least greedy child with the smallest cookie that suffices; each pointer walks once