Replace Elements with Greatest Element on Right Side
Given an array nums-1
After doing so, return the array.
Example 1
Output: [18, 6, 6, 6, 1, -1]
Explanation:
For index 0 - largest element to right side from idex 0 is 18.
For index 1 - largest element to right side from idex 1 is 6.
For index 2 - largest element to right side from idex 2 is 6.
For index 3 - largest element to right side from idex 3 is 6.
For index 4 - largest element to right side from idex 4 is 1.
For index 5 - last element should be replaced with -1.
Example 2
Output: [-1]
Explanation: There are no elements to the right of index 0.
Contents
Solution 1 - using brute force approach
In this approach, for every number at index iini
public class ReplaceElementsWithGreatestFromRight {
/* brute force approach */
static int[] usingBruteForce(int[] nums) {
int[] ans = new int[nums.length];
for(int i=0; i<nums.length-1; i++) {
int greatest = 0;
for(int j=i+1; j<nums.length; j++) {
if(nums[j]>greatest) {
greatest = nums[j];
}
}
nums[i] = greatest;
}
nums[nums.length -1] = -1;
return nums;
}
}
Complexity Analysis:
Time complexity: Above code runs in O(n2) time where nnumsnums
Space complexity: O(n) for the ans
Solution 2 - start copying largest elements from right side
In this approach, we are going to start from the right end of numsansi+1numsi+1ans[i] = MAX(ans[i+1], nums[i+1]);
-
When we are at index
ini+1 arraynums array holds maximum value up untilans index.i+2 -
When we are at index
ini arraynums array holds maximum value up untilans index.i+1
ansansnums
Let's look at below diagram for input nums= {17, 18, 5, 4, 6, 1}
public class ReplaceElementsWithGreatestFromRight {
/* we start copying largest from right side*/
static int[] copyLargestFromRightSide(int[] nums) {
int[] ans = new int[nums.length];
ans[nums.length -1] = -1;
for(int i=nums.length-2; i>=0; i--) {
ans[i] = Math.max(nums[i+1], ans[i+1]);
}
return ans;
}
}
Complexity Analysis:
Time complexity: Above code runs in O(n) time where nnums
Space complexity: O(n) for the ans