Python 1144.py
class Solution:
def movesToMakeZigzag(self, nums: List[int]) -> int:
result = +inf
size = len(nums)
for start in [ 0, 1 ]:
steps = 0
# decrement every second value until it's lower than its neighbors
for i in range(start, size, 2):
low = nums[i]
# must be lower than left side
if i > 0:
low = min(low, nums[i - 1] - 1)
# must be lower than right side
if i < size - 1:
low = min(low, nums[i + 1] - 1)
steps += nums[i] - low
result = min(result, steps)
return result
Difficulty
and has an acceptance rate of about 49% (50k+ submissions).
Typical patterns to solve this problem:
- Array
- Greedy
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution class implements a method that computes the minimum number of decrement operations required to transform an integer array into a zig-zag pattern. A zig-zag array is defined such that every element at an even index is either strictly greater than both of its neighbors (peak) or strictly smaller than both of its neighbors (valley). The algorithm evaluates both possible configurations-valleys at even positions and valleys at odd positions-and returns the cheaper of the two.
Initialization
result = +inf
size = len(nums)
The variable result starts with positive infinity, guaranteeing that any concrete step count will replace it. size stores the length of the input list, allowing the loops to avoid repeated calls to len.
Exploring the two possible patterns
for start in [ 0, 1 ]:
steps = 0
...
result = min(result, steps)
The outer loop iterates twice: first assuming that indices 0, 2, 4, … should become valleys, then assuming that indices 1, 3, 5, … should become valleys. The variable steps accumulates the total decrements needed for the current assumption. After processing each pattern, result is updated with the smaller of the previously recorded best and the newly computed steps.
Selecting the target height for each valley
for i in range(start, size, 2):
low = nums[i]
if i > 0:
low = min(low, nums[i - 1] - 1)
if i < size - 1:
low = min(low, nums[i + 1] - 1)
steps += nums[i] - low
The inner loop walks through every index that must become a valley (i takes values start, start+2, …). low is initialized to the current element value. The two conditional blocks enforce the valley condition by ensuring low is at most one less than each neighbor that exists. The min calls guarantee that the chosen low never exceeds the permissible bound imposed by either neighbor. The decrement needed for the current position is the difference between the original value and the computed low, which is added to steps.
Handling the left neighbor
When i is greater than zero, the left neighbor exists. The expression nums[i - 1] - 1 represents the highest value the current element may take while still being strictly lower than its left neighbor. By taking the minimum with the current low, the algorithm respects this constraint.
Handling the right neighbor
When i is less than size - 1, a right neighbor exists. The same logic applies with nums[i + 1] - 1. If the element is at the array boundary, the corresponding conditional block is skipped, meaning the element only needs to be lower than the single existing neighbor.
Accumulating the total cost
The statement steps += nums[i] - low records the exact number of unit decrements applied to the element at index i. Because low is never larger than the original value, the subtraction yields a non-negative integer, and the cumulative steps reflects the total work required for the current valley configuration.
Choosing the optimal configuration
After the inner loop finishes for a given start, the line result = min(result, steps) compares the cost of the just-processed pattern with the best cost seen so far. Since the outer loop runs exactly twice, result ends up holding the minimum number of decrements needed to achieve either of the two valid zig-zag arrangements.
Edge-case handling
When the input list contains a single element, the inner loop executes once (either with start = 0 or start = 1 depending on the iteration) and both neighbor checks are bypassed because the index is neither greater than zero nor less than size - 1. Consequently, low remains equal to the original value, no decrement is added, and the method correctly returns zero.
For a two-element list, each iteration treats one of the positions as a valley. The neighbor check on the opposite side is performed, forcing the valley element to be at most one less than its sole neighbor. The algorithm therefore computes the exact number of decrements needed to make the pair alternate, handling both possible orientations.
If the array is already a valid zig-zag for one of the two patterns, the corresponding steps accumulation yields zero because each low will be equal to the original element value. The result variable will then be updated to zero, and the method returns the optimal (zero) cost.
When neighboring values are equal, the - 1 adjustment ensures strict inequality. For example, if nums[i-1] and nums[i] are both 5, the left-side condition reduces low to at most 4, guaranteeing the valley property.
Large integer values are safely handled because the algorithm only performs subtraction and comparison operations; Python’s arbitrary-precision integers prevent overflow.
Performance optimizations
The algorithm uses a constant amount of extra memory: only a few scalar variables (result, size, steps, low, i, start) are allocated regardless of input size. This in-place approach avoids auxiliary arrays or data structures.
By iterating with a step of two (range(start, size, 2)), the inner loop processes exactly the elements that need to become valleys, halving the number of iterations compared to a naïve scan of every index. The two-pass structure (one pass per possible pattern) is the minimal work required to evaluate both configurations.
The use of the built-in min function for neighbor constraints provides a fast, C-level implementation for the comparison, reducing interpreter overhead compared with manual conditional branching.
Initializing result with positive infinity (+inf) eliminates the need for a separate flag to detect the first computed steps value, allowing a single min call to update the best result.
Overall, the method achieves the desired outcome with a tight loop, minimal branching, and no unnecessary data copying, delivering an efficient solution for the zig-zag transformation problem.
ELI5 - Simplified Explanation
Imagine a long line of toy blocks standing next to each other, each with a different height. A zigzag pattern means that every single block must be shorter than the blocks standing right next to it. If a block is too tall, it breaks the pattern, so some blocks need to be pushed down to make them shorter.
To solve this, look at the blocks in two different ways. First, imagine picking every other block starting with the very first one, and then imagine picking every other block starting with the second one. For each way, walk along the line and check if each chosen block is shorter than its neighbors. If a neighbor is taller, the chosen block needs to be pushed down until it is just a tiny bit smaller than those neighbors. Every time a block is pushed down, it counts as a step. After testing both ways, the goal is to see which way requires the smallest number of steps to make the whole line look like a perfect zigzag pattern.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||
| WalkCCC | C++ | Java | Python | |||||
| leetcode.ca | C++ | Java | C# | Go | Python | TS | ||
| Progiez | C++ | Java | Python | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, C#, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 1156: Swap For Longest Repeated Character Substring
- problem 1223: Dice Roll Simulation
- problem 1224: Maximum Equal Frequency
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality