Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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:
i in the range [0, n - 1], and a positive integer x.|nums[i] - x| to the total cost.nums[i] to x.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] <= 109Problem summary: 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 i in the range [0, n - 1], and a positive integer x. Add |nums[i] - x| to the total cost. Change the value of nums[i] to x. 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Math · Binary Search · Greedy
[1,2,3,4,5]
[10,12,13,14,15]
[22,33,22,33,22]
minimum-moves-to-equal-array-elements-ii)minimum-cost-to-make-array-equal)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2967: Minimum Cost to Make Array Equalindromic
public class Solution {
private static long[] ps;
private int[] nums;
static {
ps = new long[2 * (int) 1e5];
for (int i = 1; i <= 1e5; i++) {
String s = Integer.toString(i);
String t1 = new StringBuilder(s).reverse().toString();
String t2 = new StringBuilder(s.substring(0, s.length() - 1)).reverse().toString();
ps[2 * i - 2] = Long.parseLong(s + t1);
ps[2 * i - 1] = Long.parseLong(s + t2);
}
Arrays.sort(ps);
}
public long minimumCost(int[] nums) {
this.nums = nums;
Arrays.sort(nums);
int i = Arrays.binarySearch(ps, nums[nums.length / 2]);
i = i < 0 ? -i - 1 : i;
long ans = 1L << 60;
for (int j = i - 1; j <= i + 1; j++) {
if (0 <= j && j < ps.length) {
ans = Math.min(ans, f(ps[j]));
}
}
return ans;
}
private long f(long x) {
long ans = 0;
for (int v : nums) {
ans += Math.abs(v - x);
}
return ans;
}
}
// Accepted solution for LeetCode #2967: Minimum Cost to Make Array Equalindromic
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
}
# Accepted solution for LeetCode #2967: Minimum Cost to Make Array Equalindromic
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))
// Accepted solution for LeetCode #2967: Minimum Cost to Make Array Equalindromic
impl Solution {
pub fn minimum_cost(nums: Vec<i32>) -> i64 {
use std::cmp::min;
use std::sync::Once;
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
}
}
// Accepted solution for LeetCode #2967: Minimum Cost to Make Array Equalindromic
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;
}
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.