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
Palindromic Equalization StrategyInput Array: [10, 15, 25, 30, 35]Step 1: Find Median1015253035Step 2: Generate Palindromic Candidates22Cost: 2833Cost: 1844Cost: 5411Cost: 7255Cost: 90🎯 Winner: 33Minimum Cost: 18Algorithm focuses on palindromes near median for efficiency!
Understanding the Visualization
1
Sort & Find Center
Arrange all values in order and identify the median - this is our starting point
2
Generate Symmetric Targets
Create palindromic numbers around the median systematically
3
Calculate Adjustment Costs
For each palindromic target, sum up the cost to change all elements
4
Select Minimum
Choose the palindromic target that requires least total adjustment cost
Key Takeaway
🎯 Key Insight: The optimal palindromic target is typically close to the median, so we generate palindromes systematically around the median instead of checking all possibilities.
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