Minimum Cost to Make Array Equalindromic — LeetCode 2967 Python Solution

MediumGreedyArrayMathBinary SearchSorting
Problem
#2967
Reading time
3 min

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.

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.

Python solution

Python
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

MeasureComplexity
TimeO(n \times \log n)
SpaceO(M) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 2967. Minimum Cost to Make Array Equalindromic is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2967. Minimum Cost to Make Array Equalindromic?
LeetCode 2967. Minimum Cost to Make Array Equalindromic is rated Medium on LeetCode.
What is the time complexity of LeetCode 2967. Minimum Cost to Make Array Equalindromic?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 2967. Minimum Cost to Make Array Equalindromic?
The Python solution on this page uses O(M) auxiliary space.
What topics does LeetCode 2967. Minimum Cost to Make Array Equalindromic cover?
LeetCode 2967. Minimum Cost to Make Array Equalindromic is tagged Greedy, Array, Math, Binary Search and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview