Minimum Array Changes to Make Differences Equal - Problem

You are given an integer array nums of size n where n is even, and an integer k.

You can perform some changes on the array, where in one change you can replace any element in the array with any integer in the range from 0 to k.

You need to perform some changes (possibly none) such that the final array satisfies the following condition:

There exists an integer X such that abs(a[i] - a[n - i - 1]) = X for all (0 <= i < n).

Return the minimum number of changes required to satisfy the above condition.

Input & Output

Example 1 — Already Optimal
$ Input: nums = [1,2,4,3], k = 4
Output: 0
💡 Note: Pairs are (1,3) with diff=2 and (2,4) with diff=2. Both pairs already have the same difference X=2, so 0 changes needed.
Example 2 — Need Some Changes
$ Input: nums = [0,1,2,3], k = 3
Output: 1
💡 Note: Pairs are (0,3) with diff=3 and (1,2) with diff=1. We can change one element to make both pairs have difference 2, requiring 1 change total.
Example 3 — Multiple Changes
$ Input: nums = [1,0,1,2], k = 2
Output: 0
💡 Note: Pairs are (1,2) with diff=1 and (0,1) with diff=1. Both pairs already have difference 1, so 0 changes needed.

Constraints

  • 2 ≤ nums.length ≤ 105
  • nums.length is even
  • 0 ≤ nums[i] ≤ k ≤ 105

Visualization

Tap to expand
Minimum Array Changes to Make Differences Equal INPUT Array nums: 1 i=0 2 i=1 4 i=2 3 i=3 Pairs to compare: Pair 1 Pair 2 nums[0]=1 nums[3]=3 nums[1]=2 nums[2]=4 Input Values: nums = [1, 2, 4, 3] k = 4 n = 4 (even) n/2 = 2 pairs ALGORITHM STEPS 1 Calculate Differences |nums[i] - nums[n-i-1]| |1-3| = 2 (Pair 1) |2-4| = 2 (Pair 2) 2 Check for Common X Find X where all pairs match X = 2 works for ALL pairs! 3 Count Changes Needed Changes = pairs not equal X Pair 1: diff=2, X=2 -- OK Pair 2: diff=2, X=2 -- OK 4 Return Minimum 0 pairs need changes Changes = 0 FINAL RESULT Solution Found: X = 2 All differences equal! Verification: |nums[0]-nums[3]| = |1-3| = 2 |nums[1]-nums[2]| = |2-4| = 2 Both equal X=2 -- OK OUTPUT 0 No changes required! Key Insight: For each pair (nums[i], nums[n-i-1]), calculate the absolute difference. If a common value X exists such that all pairs already have difference X, no changes needed. Otherwise, use difference arrays to find minimum changes for each possible X value from 0 to k. Optimal X minimizes total changes. TutorialsPoint - Minimum Array Changes to Make Differences Equal | Optimal Solution
Asked in
Google 25 Amazon 18 Microsoft 15
27.9K Views
Medium Frequency
~25 min Avg. Time
845 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen