Problem Description
Given a 0-indexed integer array nums, you can perform a "special move" any number of times. In each move, you choose an index i and a positive integer x, add |nums[i] - x| to the total cost, and update nums[i] to x. An array is considered equalindromic if all of its elements are equal to a palindromic number (a positive integer that remains the same when its digits are reversed) that is less than 10^9. The goal is to determine the minimum possible total cost needed to transform the input array into an equalindromic array.
Key Insights
- The target transformation requires every element to become some palindromic number y (<10^9).
- The cost for changing an element from a to y is |a - y|.
- If there were no restrictions on y (palindromicity), the median minimizes the sum of absolute differences.
- The median might not be palindromic, so we generate candidate palindromic numbers around the median.
- Sorting the array to get the median and then checking nearby palindromic numbers can efficiently lead to the optimal solution.
Space and Time Complexity
Time Complexity: O(n log n + P * n) where n is the size of the input array and P is the number of palindromic candidates (kept small by limiting the search around the median).
Space Complexity: O(n) for storing and sorting the array.
Solution
We first sort the array to quickly find the median. Since changing all elements to the median minimizes the sum of absolute differences, we generate candidate palindromic numbers in a small window around the median. For each candidate, we compute the cost of transforming the entire array (by summing |num - candidate| for each element) and select the candidate with the minimal cost.
The solution uses:
- Sorting (to determine the median).
- A helper function to check whether a number is palindromic.
- A candidate generation strategy that considers only a limited range around the median (thus keeping P small).
This approach balances the need to satisfy the palindromic requirement while still relying on the median heuristic for optimal cost.