Wednesday, January 29, 2025

Replace Elements with Greatest Element on Right Side

Profile Pic of Akash AmanAkash Aman

Updated: January 2025

Replace Elements with Greatest Element on Right Side
easy

💡 Intuition

  • When starting from the left, each index i has (n - i - 1) elements to its right, from which we need to determine the maximum. This approach has a time complexity of O(n ^2 ).

17546If we start with left then for each index we will have (n-i-1) no to its right fromwhich we have to get the max1811754618117546181175461811754618117546181Iteration 6Iteration 5Iteration 4Iteration 3Iteration 2Iteration 1Max (18,5,4,6,1) = 18 18618661816661866618-1166618Max (5,4,6,1) = 6 Max (4,6,1) = 6 Max (6,1) = 6 Max (1) = 1 Max () = -1


  • When starting from the right, we can maintain a running maximum, and at each step, we only need to compare two values: num[i+1] and the maximum encountered so far. This approach has a time complexity of O(n).

17546Iteration 118117546Iteration 218117546Iteration 318117546Iteration 418117546Iteration 518117546Iteration 6181-1Max = -1Max (-1,1) = 1 Max (1,6) = 6 Max (6,4) = 6 Max (6,5) = 6Max (6,18) = 18 -11-116-1166-1166-11661866If we start from the right, we can track the maximum value, and at eachiteration, we only need to compare two values: num[i+1] and the maximum foundso far.

🚀 Solution

go
function replaceElements(arr: number[]): number[] { let result : number[] = []; let length = arr.length; let maxnum = -1; for ( let i = length - 2; i >=0 ; i-- ) { maxnum = Math.max(maxnum,arr[i+1]); result[i] = maxnum } result[length-1] = -1; return result; };

⏳ Time Complexity

  • Since we are taking single loop for the array of length n, the time complexity will be O(n)