Ctrl K

Level Out to a Palindrome

Medium
A warehouse has a row of shelves, and shelf i holds values[i] boxes. The manager wants every shelf to hold the **same** number of boxes, and that number must be a palindrome: a positive integer that reads the same forwards and backwards (for example 7, 44 or 1331). Adding or removing a single box costs 1, so turning a shelf with values[i] boxes into one with y boxes costs |values[i] − y|. Return the minimum total cost to make all shelves hold the same palindromic number of boxes.
Example 1
values=[7, 9, 15] → 8

The median is 9, which is a palindrome. Setting everything to 9 costs |7 − 9| + |15 − 9| = 2 + 6 = 8.

Example 2
values=[20, 25, 30] → 13

The palindromes closest to the median 25 are 22 and 33. Going to 22 costs 2 + 3 + 8 = 13, going to 33 costs 13 + 8 + 3 = 24. The answer is 13.

Example 3
values=[44] → 0
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 problemsPrices That Fade With Each Sale MediumGrowing Groups Without Repeats HardStick Triples That Form a Triangle MediumBest-Paid Gig for Each Worker MediumUp or Down for Every Post Medium
loading Python…
Input
values=[7, 9, 15]
Expected
8

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