Minimum Cost to Make Array Equalindromic - Problem
Transform Array to Palindromic Equality!

You're given an integer array nums and your mission is to make all elements equal to the same palindromic number with minimum cost.

The Rules:
• You can change any element nums[i] to any positive integer x
• Each change costs |nums[i] - x| (absolute difference)
• The final target must be a palindromic number (reads same forwards and backwards)
• Target must be less than 109

Examples of palindromes: 1, 11, 121, 1331, 12321
Non-palindromes: 10, 123, 1234

Find the minimum total cost to make all array elements equal to some palindromic number!

Input & Output

example_1.py — Basic Case
$ Input: [1,2,3,4,5]
Output: 6
💡 Note: We can change all elements to palindromic number 3. Cost = |1-3| + |2-3| + |3-3| + |4-3| + |5-3| = 2 + 1 + 0 + 1 + 2 = 6. This is the minimum possible cost.
example_2.py — Single Element
$ Input: [10,12,13,14,15]
Output: 11
💡 Note: The optimal palindromic target is 11. Cost = |10-11| + |12-11| + |13-11| + |14-11| + |15-11| = 1 + 1 + 2 + 3 + 4 = 11.
example_3.py — Large Numbers
$ Input: [100,110,120]
Output: 21
💡 Note: The optimal palindromic target is 111. Cost = |100-111| + |110-111| + |120-111| = 11 + 1 + 9 = 21. Other palindromes like 101 or 121 would give higher costs.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109
  • Target palindrome must be less than 109
  • All palindromic numbers from 1 to 9 are valid single-digit targets

Visualization

Tap to expand
Minimum Cost to Make Array Equalindromic INPUT Array nums: 1 [0] 2 [1] 3 [2] 4 [3] 5 [4] Median = 3 Palindromes near median: 1 2 3 Target: Find palindrome that minimizes cost Goal: Make all elements equal to a palindromic number ALGORITHM STEPS 1 Sort Array [1,2,3,4,5] (sorted) 2 Find Median Median = 3 (index 2) 3 Find Nearest Palindrome Check: 3 is palindrome! 4 Calculate Total Cost Sum of |nums[i] - 3| Cost Calculation (target=3): |1 - 3| = 2 |2 - 3| = 1 |3 - 3| = 0 |4 - 3| = 1 |5 - 3| = 2 Total: 2+1+0+1+2=6 FINAL RESULT Optimal Palindrome Target: 3 Transformed Array: 3 3 3 3 3 OUTPUT 6 Verification: 3 is palindromic: OK Minimum cost achieved: OK Key Insight: The optimal target is a palindrome closest to the median of the sorted array. The median minimizes the sum of absolute deviations. Pre-generate palindromes up to 10^9, then binary search for the nearest palindrome(s) to the median and calculate cost. Time: O(n log n), Space: O(P) where P = palindromes count. TutorialsPoint - Minimum Cost to Make Array Equalindromic | Optimal Solution
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
31.5K Views
Medium Frequency
~25 min Avg. Time
1.3K 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