Leetcode #2967: Minimum Cost to Make Array Equalindromic
In this guide, we solve Leetcode #2967 Minimum Cost to Make Array Equalindromic in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given a 0-indexed integer array nums having length n. You are allowed to perform a special move any number of times (including zero) on nums.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Greedy, Array, Math, Binary Search, Sorting
Intuition
The problem structure suggests a monotonic decision, which makes binary search a natural fit.
By halving the search space each step, we reach the answer efficiently.
Approach
Search either directly on a sorted array or on the answer space using a check function.
Each check is fast, and the logarithmic search keeps the overall runtime low.
Steps:
- Define the search bounds.
- Check the mid point condition.
- Narrow the bounds until convergence.
Example
Input: nums = [1,2,3,4,5]
Output: 6
Explanation: We can make the array equalindromic by changing all elements to 3 which is a palindromic number. The cost of changing the array to [3,3,3,3,3] using 4 special moves is given by |1 - 3| + |2 - 3| + |4 - 3| + |5 - 3| = 6.
It can be shown that changing all elements to any palindromic number other than 3 cannot be achieved at a lower cost.
Python Solution
ps = []
for i in range(1, 10**5 + 1):
s = str(i)
t1 = s[::-1]
t2 = s[:-1][::-1]
ps.append(int(s + t1))
ps.append(int(s + t2))
ps.sort()
class Solution:
def minimumCost(self, nums: List[int]) -> int:
def f(x: int) -> int:
return sum(abs(v - x) for v in nums)
nums.sort()
i = bisect_left(ps, nums[len(nums) // 2])
return min(f(ps[j]) for j in range(i - 1, i + 2) if 0 <= j < len(ps))
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.