Merge Operations to Turn Array Into a Palindrome - 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.

For example, if nums = [1,2,3,1], you can apply one operation to make it [1,5,1].

Return the minimum number of operations needed to turn the array into a palindrome.

Input & Output

Example 1 — Basic Case
$ Input: nums = [4,3,2,1,2,3,1]
Output: 2
💡 Note: Step by step: [4,3,2,1,2,3,1] → merge last two: [4,3,2,1,2,4] → equal ends, move inward → [4,3,2,1,2,4] → merge middle elements: [4,3,2,3,4] → palindrome achieved in 2 operations
Example 2 — Already Palindrome
$ Input: nums = [1,2,3,2,1]
Output: 0
💡 Note: Array is already a palindrome, so no operations needed
Example 3 — Single Element
$ Input: nums = [1]
Output: 0
💡 Note: Single element is always a palindrome, return 0

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Merge Operations to Turn Array Into a Palindrome INPUT nums = [4,3,2,1,2,3,1] 4 3 2 1 2 3 1 0 1 2 3 4 5 6 Two Pointers Approach L R Goal: Make array palindrome by merging adjacent elements with minimum operations Array length: 7 All positive integers Sum: 4+3+2+1+2+3+1 = 16 ALGORITHM STEPS 1 Initialize Pointers L=0, R=6, ops=0 left=4, right=1 2 Compare & Merge If L < R: merge right side If L > R: merge left side 3 Track Operations Each merge = +1 operation Move pointer after match 4 Continue Until L >= R Return total operations Execution Trace: L=4, R=1 --> merge R: 3+1=4 L=4, R=4 --> match! move both L=3, R=2 --> merge R: 2+2=4 L=3, R=4 --> merge L: 3+2=5 L=5, R=4 --> merge R: 4+1=5 L=5, R=5 --> match! done FINAL RESULT Final Palindrome Array: 5 5 5 [5, 5, 5] is a palindrome - OK Output: 3 Merge Operations: Op 1: [4,3,2,1,2,3,1] --> merge 3+1 = 4 Op 2: [4,3,2,1,2,4] --> merge 3+2 = 5 Op 3: [4,5,1,2,4] --> merge 4+1 = 5 Result: [5, 5, 5] Key Insight: The two-pointer approach works because merging only increases element values. If left sum < right sum, we must merge on the left side to catch up, and vice versa. This greedy strategy ensures minimum operations since we never undo merges. Time: O(n), Space: O(1) - optimal for this problem. TutorialsPoint - Merge Operations to Turn Array Into a Palindrome | Optimized Two Pointers Time: O(n) Space: O(1)
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
24.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen