714004. Make Array Elements Equal

Easy

Make Array Elements Equal

Slug: make-array-elements-equal--170647

Difficulty: Easy

Id: 714004

Topic Tags: Arrays, Data Structures, Algorithms

Company Tags: Expedia

Summary

Given an array of integers, the task is to make all elements equal by performing a series of operations. In each operation, you can either increment or decrement any element in the array. The goal is to achieve this in minimum number of operations.

Detailed Explanation

To solve this problem, we need to find the median of the array and then adjust the elements to reach the median. We will iterate through the array, comparing each element with the median. If an element is greater than the median, we decrement it; if it's smaller, we increment it.

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

  1. Find the median of the array.
  2. Iterate through the array.
  3. For each element, check if it's greater than or equal to the median. If so, do nothing (since it's already at or below the target).
  4. If an element is less than the median, increment it until it reaches the median.
  5. Repeat steps 2-4 for all elements in the array.

Time complexity: O(n), where n is the size of the array. Space complexity: O(1), as we're not using any additional space that scales with input size.

Optimized Solutions

Java

View on GeeksforGeeks
public class Main {
    public static void makeEqual(int[] arr) {
        Arrays.sort(arr);
        int median = arr[(arr.length - 1) / 2];
        for (int i : arr) {
            if (i > median) {
                i--;
            } else if (i < median) {
                i++;
            }
        }
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.