Minimum Cost to Make Array Equalindromic solution and explanation
6 more videos on this problem
2967 Minimum Cost to Make Array Equalindromic || (Median ✅) (why Mean❓ and Range Till 10^4 🙋♂️)Ayush Rao · 13:58 · 1K views
2967. Minimum Cost to Make Array Equalindromic || Leetcode Weekly Contest 376Ashish Kumar · 18:20 · 1K views
Minimum Cost to Make Array Equalindromic - LEETCODE WEEKLY CONTEST 376Joyjit Codes · 6:22 · 942 views
【每日一题】LeetCode 2967. Minimum Cost to Make Array EqualindromicHuifeng Guan · 13:31 · 312 views
2967. Minimum Cost to Make Array Equalindromic (Leetcode Medium)Programming Live with Larry · 21:58 · 242 views
Minimum Cost to Make Array Equalindromic - LeetCode 2967 - PythonAlpha-Code · 28:54 · 193 views
2967. Minimum Cost to Make Array Equalindromic Leetcode solutionJayanth Puthalapattu · 7:18 · 63 views
The problem
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. In one special move you perform the following steps in order:
- Choose an index
iin the range[0, n - 1], and a positive integerx. - Add
|nums[i] - x|to the total cost. - Change the value of
nums[i]tox.
A palindromic number is a positive integer that remains the same when its digits are reversed. For example, 121, 2552 and 65756 are palindromic numbers whereas 24, 46, 235 are not palindromic numbers.
An array is considered equalindromic if all the elements in the array are equal to an integer y, where y is a palindromic number less than 109.
Return an integer denoting the minimum possible total cost to make nums equalindromic by performing any number of special moves.
Example 1:
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.
Example 2:
Input: nums = [10,12,13,14,15] Output: 11 Explanation: We can make the array equalindromic by changing all elements to 11 which is a palindromic number. The cost of changing the array to [11,11,11,11,11] using 5 special moves is given by |10 - 11| + |12 - 11| + |13 - 11| + |14 - 11| + |15 - 11| = 11. It can be shown that changing all elements to any palindromic number other than 11 cannot be achieved at a lower cost.
Example 3:
Input: nums = [22,33,22,33,22] Output: 22 Explanation: We can make the array equalindromic by changing all elements to 22 which is a palindromic number. The cost of changing the array to [22,22,22,22,22] using 2 special moves is given by |33 - 22| + |33 - 22| = 22. It can be shown that changing all elements to any palindromic number other than 22 cannot be achieved at a lower cost.
Constraints:
1 <= n <= 1051 <= nums[i] <= 109
Approach overview
Problem Overview: You are given an integer array and can change every element to the same value. The catch: the final value must be a palindromic number. The cost of converting an element is |nums[i] - target|. Your task is to choose a palindromic target that minimizes the total cost.
Approach 1: Brute Force with Palindromic Number List (O(P * n) time, O(P) space)
Generate all palindromic numbers within the valid integer range (up to 1e9). Store them in a list. For each palindrome p, iterate through the array and compute the total cost sum(|nums[i] - p|). Track the minimum cost across all candidates. This works because the valid targets are restricted to palindromes, but the search space can still contain tens of thousands of numbers. The method is straightforward and easy to implement, but it becomes expensive since each palindrome requires a full pass through the array.
This approach relies mostly on sequential iteration over an array. It demonstrates the brute-force baseline clearly and guarantees correctness because every valid palindromic target is tested.
Approach 2: Median + Nearest Palindrome Search (O(n log n + n) time, O(P) space)
The key observation comes from the property of absolute differences: the sum sum(|nums[i] - x|) is minimized when x is the median of the array. Start by sorting the array to find its median using sorting. The optimal target without constraints would be this median. Since the target must be a palindrome, search for the closest palindromic numbers around the median.
Precompute the sorted list of palindromes. Use binary search to find the palindrome closest to the median. Typically, only a few candidates around that position (the nearest lower and higher palindromes) need evaluation. Compute the cost for these candidates and choose the minimum.
This drastically reduces the search space because you no longer evaluate every palindrome. Instead, you leverage the convex nature of the absolute difference function around the median.
Recommended for interviews: The median-based approach with a palindrome search is what interviewers expect. The brute force version proves you understand the constraint that the target must be palindromic. The optimized approach shows deeper insight into how absolute deviation behaves and how to combine that with binary search over candidate palindromes.
Approach 1: Brute Force with Palindromic Number List
This approach involves generating all possible palindromic numbers up to a specified limit and calculating the cost of converting the entire array to each of these palindromic numbers. The minimum cost among all conversions is the desired solution.
The key steps are:
- Generate all potential palindromic numbers up to 109.
- For each palindromic number, calculate the total cost to convert all elements in nums into this number.
- Keep track of the minimal cost encountered during these calculations.
def generate_palindromes(limit):
palindromes = []
for length in range(1, 10):
for first_half in range(10**(length-1), 10**length):
s = str(first_half)
palindromes.append(int(s + s[-2::-1])) # Odd length
palindromes.append(int(s + s[::-1])) # Even length
palindromes = [p for p in palindromes if p < limit]
return palindromes
def min_cost_to_equalindromic(nums):
palindromes = generate_palindromes(10**9)
min_cost = float('inf')
for p in palindromes:
cost = sum(abs(num - p) for num in nums)
min_cost = min(min_cost, cost)
return min_cost
nums = [1, 2, 3, 4, 5]
print(min_cost_to_equalindromic(nums))import java.util.*;
class Solution {
public int minCostToEqualindromic(int[] nums) {
List<Integer> palindromes = generatePalindromes(1000000000);
int minCost = Integer.MAX_VALUE;
for (int p : palindromes) {
int cost = 0;
for (int num : nums) {
cost += Math.abs(num - p);
}
minCost = Math.min(minCost, cost);
}
return minCost;
}
private List<Integer> generatePalindromes(int limit) {
List<Integer> palindromes = new ArrayList<>();
for (int length = 1; length < 10; length++) {
int start = (int)Math.pow(10, length - 1);
int end = (int)Math.pow(10, length);
for (int first_half = start; first_half < end; first_half++) {
String s = Integer.toString(first_half);
String sReverse = new StringBuilder(s).reverse().toString();
palindromes.add(Integer.parseInt(s + sReverse.substring(1)));
if (Integer.parseInt(s + sReverse) < limit) {
palindromes.add(Integer.parseInt(s + sReverse));
}
}
}
return palindromes;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums = {1, 2, 3, 4, 5};
System.out.println(sol.minCostToEqualindromic(nums));
}
}The implemented code generates all possible palindromic numbers below 109 and iterates through each palindromic number to calculate the total cost of converting the entire array to this number. generate_palindromes constructs these numbers by mirroring the digits, both odd and even-length variations, then sorts through this list for any values below 109.
Next, min_cost_to_equalindromic iterates over these generated palindromes, computes the cost for each, and keeps track of the minimum found.
Time Complexity: O(n * k), where n is the number of elements in the input array, and k is the number of palindromic numbers generated and considered.
Space Complexity: O(k), for storing palindromic numbers.
Approach 2: Preprocessing + Sorting + Binary Search
The range of palindrome numbers in the problem is [1, 10^9]. Due to the symmetry of palindrome numbers, we can enumerate in the range of [1, 10^5], then reverse and concatenate them to get all palindrome numbers. Note that if it is an odd-length palindrome number, we need to remove the last digit before reversing. The array of palindrome numbers obtained by preprocessing is denoted as ps. We sort the array ps.
Next, we sort the array nums and take the median x of nums. We only need to find a number in the palindrome array ps that is closest to x through binary search, and then calculate the cost of nums becoming this number to get the answer.
The time complexity is O(n times log n), and the space complexity is O(M). Here, n is the length of the array nums, and M is the length of the palindrome array ps.
Similar problems:
using ll = long long;
ll ps[2 * 100000];
int init = [] {
for (int i = 1; i <= 100000; i++) {
string s = to_string(i);
string t1 = s;
reverse(t1.begin(), t1.end());
string t2 = s.substr(0, s.length() - 1);
reverse(t2.begin(), t2.end());
ps[2 * i - 2] = stoll(s + t1);
ps[2 * i - 1] = stoll(s + t2);
}
sort(ps, ps + 2 * 100000);
return 0;
}();
class Solution {
public:
long long minimumCost(vector<int>& nums) {
sort(nums.begin(), nums.end());
int i = lower_bound(ps, ps + 2 * 100000, nums[nums.size() / 2]) - ps;
auto f = [&](ll x) {
ll ans = 0;
for (int& v : nums) {
ans += abs(v - x);
}
return ans;
};
ll ans = LLONG_MAX;
for (int j = i - 1; j <= i + 1; j++) {
if (0 <= j && j < 2 * 100000) {
ans = min(ans, f(ps[j]));
}
}
return ans;
}
};const ps = Array(2e5).fill(0);
const init = (() => {
for (let i = 1; i <= 1e5; ++i) {
const s: string = i.toString();
const t1: string = s.split('').reverse().join('');
const t2: string = s.slice(0, -1).split('').reverse().join('');
ps[2 * i - 2] = parseInt(s + t1, 10);
ps[2 * i - 1] = parseInt(s + t2, 10);
}
ps.sort((a, b) => a - b);
})();
function minimumCost(nums: number[]): number {
const search = (x: number): number => {
let [l, r] = [0, ps.length];
while (l < r) {
const mid = (l + r) >> 1;
if (ps[mid] >= x) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
};
const f = (x: number): number => {
return nums.reduce((acc, v) => acc + Math.abs(v - x), 0);
};
nums.sort((a, b) => a - b);
const i: number = search(nums[nums.length >> 1]);
let ans: number = Number.MAX_SAFE_INTEGER;
for (let j = i - 1; j <= i + 1; j++) {
if (j >= 0 && j < ps.length) {
ans = Math.min(ans, f(ps[j]));
}
}
return ans;
}var ps [2 * 100000]int64
func init() {
for i := 1; i <= 100000; i++ {
s := strconv.Itoa(i)
t1 := reverseString(s)
t2 := reverseString(s[:len(s)-1])
ps[2*i-2], _ = strconv.ParseInt(s+t1, 10, 64)
ps[2*i-1], _ = strconv.ParseInt(s+t2, 10, 64)
}
sort.Slice(ps[:], func(i, j int) bool {
return ps[i] < ps[j]
})
}
func reverseString(s string) string {
cs := []rune(s)
for i, j := 0, len(cs)-1; i < j; i, j = i+1, j-1 {
cs[i], cs[j] = cs[j], cs[i]
}
return string(cs)
}
func minimumCost(nums []int) int64 {
sort.Ints(nums)
i := sort.Search(len(ps), func(i int) bool {
return ps[i] >= int64(nums[len(nums)/2])
})
f := func(x int64) int64 {
var ans int64
for _, v := range nums {
ans += int64(abs(int(x - int64(v))))
}
return ans
}
ans := int64(math.MaxInt64)
for j := i - 1; j <= i+1; j++ {
if 0 <= j && j < len(ps) {
ans = min(ans, f(ps[j]))
}
}
return ans
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}impl Solution {
pub fn minimum_cost(nums: Vec<i32>) -> i64 {
use std::sync::Once;
use std::cmp::min;
static INIT: Once = Once::new();
static mut PS: Vec<i64> = Vec::new();
INIT.call_once(|| {
let mut ps_local = Vec::with_capacity(2 * 100_000);
for i in 1..=100_000 {
let s = i.to_string();
let mut t1 = s.clone();
t1 = t1.chars().rev().collect();
ps_local.push(format!("{}{}", s, t1).parse::<i64>().unwrap());
let mut t2 = s[0..s.len() - 1].to_string();
t2 = t2.chars().rev().collect();
ps_local.push(format!("{}{}", s, t2).parse::<i64>().unwrap());
}
ps_local.sort();
unsafe {
PS = ps_local;
}
});
let mut nums = nums;
nums.sort();
let mid = nums[nums.len() / 2] as i64;
let i = unsafe {
match PS.binary_search(&mid) {
Ok(i) => i,
Err(i) => i,
}
};
let f = |x: i64| -> i64 {
nums.iter().map(|&v| (v as i64 - x).abs()).sum()
};
let mut ans = i64::MAX;
for j in i.saturating_sub(1)..=(i + 1).min(2 * 100_000 - 1) {
let x = unsafe { PS[j] };
ans = min(ans, f(x));
}
ans
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Brute Force with Palindromic Number List | Time Complexity: O(n * k), where n is the number of elements in the input array, and k is the number of palindromic numbers generated and considered. |
| Preprocessing + Sorting + Binary Search | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force with Palindromic Number List | O(P * n) | O(P) | Good baseline approach when constraints are small or when demonstrating correctness first. |
| Median + Nearest Palindrome Search | O(n log n + n) | O(P) | Preferred solution for large arrays. Uses sorting and evaluates only the closest palindrome candidates. |
Frequently asked questions
Is Minimum Cost to Make Array Equalindromic easy or hard?
This problem is rated Medium because the brute-force idea is simple but the optimal solution requires recognizing that absolute difference sums are minimized at the median. Combining that insight with palindrome generation and binary search makes it a multi-concept problem.
Minimum Cost to Make Array Equalindromic Python/Java solution
The typical implementation generates all palindromes up to the limit, sorts the input array, finds the median, then checks the nearest palindromes using binary search. For each candidate, compute the sum of absolute differences. Both Python and Java implementations follow the same logic with O(n log n) complexity.
How to solve Minimum Cost to Make Array Equalindromic in O(n)?
A strict O(n) solution is difficult because the typical approach requires sorting to obtain the median. However, if the median could be found in linear time using a selection algorithm, the remaining computation would still require evaluating candidate palindromes in O(n). In practice, the accepted solution is O(n log n).
What is the best approach for Minimum Cost to Make Array Equalindromic?
The most efficient approach uses the median of the array combined with a search for the nearest palindromic number. Since the sum of absolute differences is minimized at the median, you sort the array, find the median, and evaluate the closest palindromes around it. This reduces the search space dramatically and runs in O(n log n) time due to sorting.
Is Minimum Cost to Make Array Equalindromic asked at Google/Amazon/Meta?
Problems involving minimizing absolute differences, medians, and constrained target values appear frequently in interviews at companies like Google, Amazon, and Meta. While this exact problem may vary, the underlying concepts—median optimization, greedy reasoning, and candidate pruning—are common interview patterns.
What data structure is used in Minimum Cost to Make Array Equalindromic?
The main data structures are arrays and a precomputed list of palindromic numbers. Sorting is used to find the median, and binary search helps locate the closest palindrome candidates efficiently.
What is the time complexity of Minimum Cost to Make Array Equalindromic?
The optimized solution runs in O(n log n) time because the array must be sorted to find the median. After that, only a few nearby palindromes are evaluated, each costing O(n) to compute the total absolute difference. Space complexity is O(P) to store precomputed palindromic numbers.
