710087. Arrange the array
Easy
Arrange the Array
Summary
The problem is to arrange an array in a specific order, given certain constraints. The goal is to sort the elements in the array based on their values and then modify them according to some rules. This problem requires understanding of basic algorithms and data structures.
Detailed Explanation
We are given an array arr of size n, where each element is either 0 or 1. We need to arrange this array such that all elements with value 0 come first, followed by all elements with value 1. This problem can be solved using a simple sorting algorithm like Bubble Sort.
Here's the step-by-step breakdown:
- Start from the beginning of the array.
- Compare each element with its next element in the array. If they are in the correct order (all 0s first, then all 1s), move on to the next pair.
- If an element is out of order (i.e., a 1 appears before any 0s or vice versa), swap it with its next element and repeat step 2 until no more swaps are needed.
Time complexity: O(n^2) Space complexity: O(1)
Here's a diagram to illustrate the process:
Before:
0 1 0 1 0 1
After:
0 0 0 1 1 1
Optimized Solutions
Java
public class ArrangeArray {
public static void arrange(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] == 0 && arr[j + 1] == 1) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}