Skip to content

Latest commit

 

History

History
32 lines (25 loc) · 974 Bytes

File metadata and controls

32 lines (25 loc) · 974 Bytes

Array

Screen Shot 2023-01-07 at 4 34 20 PM

Two Pointers

The time complexity of this code is O(n^2), where n is the length of the input array arr.

This is because for each element in the array, the code performs a loop to find the maximum value among all the elements to the right of the current element. This loop has a time complexity of O(n), and since it is performed for each element in the array, the overall time complexity is O(n^2).

S.C O(1)

/**
 * @param {number[]} arr
 * @return {number[]}
 */
var replaceElements = function(arr) {
    for(let i = 0; i < arr.length; i++) {
        let ptr = i + 1;
        let max = -Infinity;
        while(ptr < arr.length) {
           max = Math.max(max, arr[ptr]);
           ptr++;
        }
        arr[i] = max;
    }
    arr[arr.length - 1] = -1;
    return arr;
};