Merge Operations to Turn Array Into a Palindrome — LeetCode 2422 Python Solution

MediumLeetCode PremiumGreedyArrayTwo Pointers
Problem
#2422
Reading time
3 min

The problem

You are given an array nums consisting of positive integers. You can perform the following operation on the array any number of times: Choose any two adjacent elements and replace them with their sum.

Example

Input
nums = [4,3,2,1,2,3,1]
Output
2
Explanation
We can turn the array into a palindrome in 2 operations as follows:

Python solution

Python
class Solution:
    def minimumOperations(self, nums: List[int]) -> int:
        i, j = 0, len(nums) - 1
        a, b = nums[i], nums[j]
        ans = 0
        while i < j:
            if a < b:
                i += 1
                a += nums[i]
                ans += 1
            elif b < a:
                j -= 1
                b += nums[j]
                ans += 1
            else:
                i, j = i + 1, j - 1
                a, b = nums[i], nums[j]
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 2422. Merge Operations to Turn Array Into a Palindrome is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2422. Merge Operations to Turn Array Into a Palindrome?
LeetCode 2422. Merge Operations to Turn Array Into a Palindrome is rated Medium on LeetCode.
What is the time complexity of LeetCode 2422. Merge Operations to Turn Array Into a Palindrome?
The Python solution on this page runs in O(n), where n is the length of the array.
What is the space complexity of LeetCode 2422. Merge Operations to Turn Array Into a Palindrome?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2422. Merge Operations to Turn Array Into a Palindrome cover?
LeetCode 2422. Merge Operations to Turn Array Into a Palindrome is tagged Greedy, Array and Two Pointers on LeetCode.
Is LeetCode 2422. Merge Operations to Turn Array Into a Palindrome a premium problem?
Yes. LeetCode 2422. Merge Operations to Turn Array Into a Palindrome is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview