#1144

Decrease Elements To Make Array Zigzag

Medium
ArrayGreedyGreedyArray
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(1)

The optimal solution leverages the fact that we can calculate the moves required for both zigzag patterns (even index greater and odd index greater) in a single pass, significantly reducing the time complexity.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize two move counters for both zigzag patterns.
  2. 2Step 2: Iterate through the array, checking conditions for both even and odd indexed elements.
  3. 3Step 3: For each element, calculate the required moves and update the respective counter.
  4. 4Step 4: Return the minimum of the two move counters.
solution.py16 lines
1def movesToMakeZigzag(nums):
2    even_moves = 0
3    odd_moves = 0
4    n = len(nums)
5    for i in range(n):
6        if i % 2 == 0:  # Even index
7            if i > 0:
8                even_moves += max(0, nums[i] - nums[i - 1] + 1)
9            if i < n - 1:
10                even_moves += max(0, nums[i] - nums[i + 1] + 1)
11        else:  # Odd index
12            if i > 0:
13                odd_moves += max(0, nums[i] - nums[i - 1] + 1)
14            if i < n - 1:
15                odd_moves += max(0, nums[i] - nums[i + 1] + 1)
16    return min(even_moves, odd_moves)

Complexity note: The time complexity is O(n) because we only make a single pass through the array, checking conditions for both zigzag patterns simultaneously.

  • 1Understanding the zigzag pattern is crucial for solving the problem efficiently.
  • 2Calculating moves for both patterns simultaneously can save time.

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