#3354

Make Array Elements Equal to Zero

Easy
ArraySimulationPrefix SumSimulationArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach leverages the fact that we can determine valid starting positions based on the number of zeros in the array. We can count how many zeros are present and check if they can cover all non-zero elements.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the number of zeros in the array.
  2. 2Step 2: For each zero, check if it can reach all non-zero elements by simulating the process.
  3. 3Step 3: Return the count of valid starting positions.
solution.py21 lines
1def countValidSelections(nums):
2    n = len(nums)
3    count = 0
4    for i in range(n):
5        if nums[i] == 0:
6            left, right = i, i
7            temp = nums[:]
8            while left >= 0 or right < n:
9                if left >= 0:
10                    if temp[left] > 0:
11                        temp[left] -= 1
12                        right += 1
13                    left -= 1
14                if right < n:
15                    if temp[right] > 0:
16                        temp[right] -= 1
17                        left -= 1
18                    right += 1
19            if all(x == 0 for x in temp):
20                count += 1
21    return count

Complexity note: This complexity is O(n) because we iterate through the array once and perform a constant amount of work for each zero found.

  • 1The number of zeros in the array directly influences the number of valid starting positions.
  • 2Simulating the process helps to understand the movement and how it affects the array.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.