Ctrl K

Palindrome From Neighbour Sums

Medium
You are given an array of positive integers values. In one operation you may take two adjacent elements and replace them with a single element equal to their sum. For example, [3, 1, 2, 5] can become [3, 3, 5]. Return the smallest number of operations after which the array is a palindrome, meaning it reads the same from left to right and from right to left.
Example 1
values=[3, 1, 2, 5, 3] → 2

Merge 1 and 2 to get [3, 3, 5, 3], then merge the second 3 with 5 to get [3, 8, 3]. That is a palindrome after two operations.

Example 2
values=[6, 2, 6] → 0

The array is already a palindrome, so no operations are needed.

Example 3
values=[1, 4, 2] → 2

The ends can never be equalised without merging everything into a single number: two operations.

Constraints
  • 1 ≤ len(values) ≤ 10⁵
  • 1 ≤ values[i] ≤ 10⁶
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTwo Boards Holding Water MediumStudios for Recording Sessions MediumFix the Middle of the Line MediumStick Triples That Form a Triangle MediumBest-Paid Gig for Each Worker Medium
loading Python…
Input
values=[3, 1, 2, 5, 3]
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 106 tests on the server, hidden ones included.