Minimum Operations to Make Array Equal - Problem

You start with a special array where each element follows the pattern arr[i] = (2 * i) + 1. This creates an array of consecutive odd numbers: [1, 3, 5, 7, 9, ...].

Your goal is to make all elements equal using the minimum number of operations. In each operation, you can:

  • Choose any two indices x and y
  • Subtract 1 from arr[x]
  • Add 1 to arr[y]

This is essentially redistributing values between array elements. The total sum remains constant, but you're trying to balance the array perfectly.

Example: For n = 3, the array is [1, 3, 5]. The target value is 3 (average), so you need 2 operations to transform it to [3, 3, 3].

Input & Output

example_1.py โ€” Small Array
$ Input: n = 3
โ€บ Output: 2
๐Ÿ’ก Note: Array is [1, 3, 5]. Target is 3. Element 1 needs +2, element 5 gives -2. Total: 2 operations.
example_2.py โ€” Even Length
$ Input: n = 6
โ€บ Output: 9
๐Ÿ’ก Note: Array is [1, 3, 5, 7, 9, 11]. Target is 6. Left half deficits: 5+3+1 = 9 operations needed.
example_3.py โ€” Single Element
$ Input: n = 1
โ€บ Output: 0
๐Ÿ’ก Note: Array is [1]. Already equal, no operations needed.

Constraints

  • 1 โ‰ค n โ‰ค 104
  • Array elements follow the pattern arr[i] = (2 * i) + 1
  • All elements can be made equal using the given operations

Visualization

Tap to expand
Water Tank Balancing ProblemLevel: 1Need: +2Level: 3Need: +0Level: 5Give: -2Target Water Level = 3Mathematical Formula DerivationFor array [1, 3, 5, 7, 9, ...] with length n:โ€ข Target value = n (middle element)โ€ข Left half elements are below targetโ€ข Right half elements are above targetResult: Operations = n ร— n รท 4
Understanding the Visualization
1
Initial State
Tanks have levels 1, 3, 5, 7, ... (consecutive odd numbers)
2
Target Level
All tanks should reach level n (the middle value)
3
Transfer Operations
Left tanks need water, right tanks provide it
4
Minimum Operations
Sum of all deficits = nยฒ/4 transfers needed
Key Takeaway
๐ŸŽฏ Key Insight: The array is perfectly symmetric around its middle value n, so we only need to calculate how much the first half is 'short' and that equals our minimum operations.
Asked in
Google 45 Meta 38 Amazon 32 Microsoft 28 Apple 22
87.6K Views
Medium Frequency
~15 min Avg. Time
2.3K 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