#2967

Minimum Cost to Make Array Equalindromic

Medium
ArrayMathBinary SearchGreedySortingSortingGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution leverages the properties of palindromic numbers and the median of the array. By focusing on the median, we can minimize the total cost effectively.

⚙️

Algorithm

4 steps
  1. 1Step 1: Sort the array to find the median.
  2. 2Step 2: Identify the closest palindromic numbers around the median.
  3. 3Step 3: Calculate the cost to convert all elements to these palindromic candidates.
  4. 4Step 4: Return the minimum cost.
solution.py19 lines
1def is_palindrome(x): return str(x) == str(x)[::-1]
2
3def closest_palindromic(m):
4    candidates = []
5    for i in range(m - 10, m + 10):
6        if is_palindrome(i): candidates.append(i)
7    return candidates
8
9
10def min_cost_to_palindromic(nums):
11    nums.sort()
12    n = len(nums)
13    median = nums[n // 2] if n % 2 != 0 else nums[n // 2 - 1]
14    palindromic_candidates = closest_palindromic(median)
15    min_cost = float('inf')
16    for p in palindromic_candidates:
17        cost = sum(abs(num - p) for num in nums)
18        min_cost = min(min_cost, cost)
19    return min_cost

Complexity note: The time complexity is O(n log n) due to sorting the array, and O(n) for calculating the cost for each candidate palindromic number.

  • 1The median of the array helps minimize the total cost when converting to a palindromic number.
  • 2Palindromic numbers are symmetric, which allows us to focus on a limited range around the median.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.