714010. Make the array beautiful
Make the Array Beautiful
Summary
Given an array of integers, make it beautiful by rearranging the elements such that all even numbers come before all odd numbers. For example, if the input array is [1, 2, 3, 4], the output should be [2, 4, 1, 3]. This problem involves arrays and basic manipulation of data structures.
Detailed Explanation
To solve this problem, we can use a stack-based approach. We iterate over the input array from left to right, and for each element, we check if it's even or odd. If it's even, we push it onto the stack. If it's odd, we pop all the even numbers from the stack (since they should come before this odd number) and then push the current odd number onto the stack.
Here's a step-by-step breakdown of the solution:
- Initialize an empty stack.
- Iterate over the input array from left to right.
- For each element, check if it's even or odd:
- If it's even, push it onto the stack.
- If it's odd, pop all the even numbers from the stack (since they should come before this odd number) and then push the current odd number onto the stack.
- Once we've iterated over the entire array, the stack will contain the rearranged elements in the desired order.
Time complexity: O(n), where n is the length of the input array. Space complexity: O(n), since we need to store all the even numbers in the stack.
Optimized Solutions
Java
import java.util.Stack;
public class BeautifulArray {
public static int[] makeBeautiful(int[] arr) {
Stack<Integer> stack = new Stack<>();
for (int num : arr) {
if (num % 2 == 0) {
stack.push(num);
} else {
while (!stack.isEmpty() && stack.peek() % 2 == 0) {
stack.pop();
}
stack.push(num);
}
}
int[] result = new int[stack.size()];
for (int i = 0; i < result.length; i++) {
result[i] = stack.pop();
}
return result;
}
}