702843. Balanced Array

Basic

Balanced Array

Slug: balanced-array07200720 Difficulty: Basic Id: 702843 Topic Tags: Arrays, Data Structures Company Tags: None

Summary

The Balanced Array problem is about finding a way to balance an array by moving elements from one end to the other. The goal is to distribute the elements evenly throughout the array, making sure that the difference between the maximum and minimum values is minimized.

Detailed Explanation

To solve this problem, we can start by sorting the array in ascending order. This will help us identify the range of values present in the array. Then, we can calculate the mean (average) value of the array. The idea is to move elements from one end of the array to the other until the difference between the maximum and minimum values is minimized.

Here's a step-by-step breakdown of the solution:

  1. Sort the array in ascending order.
  2. Calculate the mean (average) value of the array.
  3. Initialize two pointers, left and right, at the beginning and end of the array, respectively.
  4. Compare the values at the left and right pointers. If the value at the left pointer is less than or equal to the mean, move the left pointer one step forward. Otherwise, move the right pointer one step backward.
  5. Repeat steps 3-4 until the difference between the maximum and minimum values of the array is minimized.

Here's an ASCII art diagram illustrating the process:

  +---------------+
  |       mean      |
  +---------------+
           |
           v
  +---------------+-----------+
  |        left    |         right|
  |  (small values) | (large values) |
  +---------------+-----------+

Time complexity: O(n log n) due to sorting the array. Space complexity: O(1), as we only use a few extra variables.

Optimized Solutions

Java

View on GeeksforGeeks
public class BalancedArray {
    public static void balanceArray(int[] arr) {
        Arrays.sort(arr);
        double mean = (double) Arrays.stream(arr).sum() / arr.length;
        int left = 0, right = arr.length - 1;
        while (Math.abs(mean - arr[left]) > Math.abs(mean - arr[right])) {
            if (arr[left] <= mean) {
                left++;
            } else {
                right--;
            }
        }
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.