Skip to content

Bug Report for replace-elements-with-greatest-element-on-right-side #5230

@atachka

Description

@atachka

Bug Report for https://neetcode.io/problems/replace-elements-with-greatest-element-on-right-side

There is no need to create a new array in solution 2

here is a better version that uses the same time and O(1) space complexity.

class Solution {
    /**
     * Replaces each element in the array with the greatest element on its right,
     * and replaces the last element with -1.
     * 
     * @param {number[]} arr
     * @return {number[]}
     */
    replaceElements(arr) {
        let max = -1;

        for (let i = arr.length - 1; i >= 0; i--) {
            const old = arr[i];
            arr[i] = max;
            max = Math.max(old, max);
        }

        return arr;
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions