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:
- Find the median of the array.
- Iterate through the array.
- 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).
- If an element is less than the median, increment it until it reaches the median.
- 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
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++;
}
}
}
}