Q1. Make Array Elements Equal to Zero | Easy | LeetCode Weekly Contest
🌐 中文版:繁體中文
Intro
This is my first record of doing a LeetCode Weekly Contest. I jumped on today on a whim, so by the time I was ready to compete there wasn’t much time left. But I’m still a rookie, so I just focused on the first problem to test the waters, and stopped after finishing it.
Problem statement

- Difficulty:
Easy - Statement: given an integer array
nums, you first pick a starting pointcurrwherenums[curr] = 0. From the starting point you can choose to move left or right, then repeat the following steps:
- If
currgoes out of the range[0, n-1], the process stops - Move left or right by decrementing/incrementing
curr: increasingcurrmoves right, decreasingcurrmoves left - After moving, once
nums[curr] > 0:- decrement
nums[curr]by one - reverse the current direction of movement
- take one step in the new direction
- decrement
A run is considered valid if, once the movement ends, all element values are zero. Return the total number of valid selections.
Solution
Initial idea
First we need to iterate over the given array nums and find the starting points (there may be several). Then, starting from a start point, we walk left or right to judge whether it’s valid. During the traversal, as soon as we hit a value greater than 0 we start walking in the opposite direction, until we reach the far end or another value greater than zero.
My solution
1 | class Solution { |
Here I split it into two functions. The main function countValidSelections uses a loop to find the starting points first, and once it finds one it calls isValid twice with different directions. In isValid, we walk back and forth over the elements within the range curr >= 0 && curr < n. Once we hit an element with value zero, we keep walking in the current direction, and if we hit a value greater than 0 we decrement nums[curr] by one and take one step in the reverse direction. After traversing all elements, we check whether every element is now zero; if so it’s valid, otherwise invalid. Back in the main function, if the path is valid we increment the found variable. After trying the different starting points, we can return found.
Execution result

The runtime cost was very high.
Complexity
Time complexity
- $O(n^2)$
countValidSelections: runs at most $n$ times, and for each starting position isValid is called twice. isValid: in the worst case the while loop traverses the whole array, so $O(n)$, and before returning there’s another loop checking whether every element is 0, which also needs $O(n)$. So the overall time complexity is $2 \times (O(n) + O(n)) = O(4n) = O(n)$ per start, times up to $n$ starts.
Space complexity
- $O(n)$
Each call toisValidcreates a copy of the arraynums, so $O(n)$. In each iteration ofcountValidSelections,isValidis called twice, but these copies are local and short-lived, so they don’t accumulate. So the overall space complexity is $O(n)$.








