703183. Modify the Array
Ease the Array
Slug: ease-the-array0633
Difficulty: Easy
Id: 703183
Topic Tags: Arrays, Data Structures, Greedy
Company Tags: Zoho, Microsoft
Summary
Modify the Array is a classic problem of array manipulation that involves modifying an array to satisfy certain conditions. The key concept involved in this problem is the greedy approach, where we make locally optimal choices in the hope that these choices will lead to a global optimum.
Detailed Explanation
Given an array arr of integers, our task is to modify it such that all the elements are non-decreasing (i.e., each element is either equal or less than the previous one). We can achieve this by iterating through the array and comparing each element with its previous one. If the current element is greater than the previous one, we need to make it smaller.
Here's a step-by-step breakdown of the solution:
- Initialize an empty stack
st. - Iterate through the array from left to right.
- For each element
arr[i], check if it is less than or equal to the top element of the stack (st.top()). If not, pop elements from the stack until the popped element is less than or equal toarr[i]or the stack becomes empty. - Push
arr[i]onto the stack. - Repeat steps 2-4 until the end of the array.
- The resulting array will have all non-decreasing elements.
Time Complexity: O(n), where n is the size of the input array. Space Complexity: O(n) for storing the modified array.
Here's an ASCII art diagram to illustrate the process:
arr = [5, 3, 8, 2, 4]
stack = []
1. 5 (pushed onto stack)
2. 3 (popped from stack, since 3 < 5)
stack = []
arr = [3]
3. 8 (popped from stack, since 8 > 3)
stack = [5]
arr = [3, 5]
4. 2 (popped from stack, since 2 < 5)
stack = []
arr = [3, 5, 2]
5. 4 (pushed onto stack)
stack = [5, 2]
arr = [3, 5, 2, 4]
Result: [3, 3, 4, 4]
Optimized Solutions
#### Java
public static int[] modifyArray(int[] arr) {
Stack<Integer> st = new Stack<>();
for (int i : arr) {
while (!st.isEmpty() && st.peek() > i) {
st.pop();
}
st.push(i);
}
int[] res = new int[st.size()];
for (int i = 0; i < res.length; i++) {
res[i] = st.pop();
}
return res;
}