logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
instagramtwitterfacebookyoutubelinkedinmailgithubrss
Copyright © 2026 All rights reserved.
•
VIKI
Built with Vikramaditya Singh
Built with
VIKI - A posts created with Next.js and Tailwind.css
About
leetcode
Title
Table Of Contents
easy
13. Roman to Integer
14. Longest Common Prefix
20. Valid Parentheses
26. Remove Duplicates from Sorted Array
35. Search Insert Position
69. Sqrt(x)
70. Climbing Stairs
88. Merge Sorted Array (In-Place)
104. Maximum Depth of Binary Tree
118. Pascal's Triangle
121. Best Time to Buy and Sell Stock
205. Isomorphic Strings
242. Valid Anagram
283. Move Zeroes
345. Reverse Vowels of a String
605. Can Place Flowers
704. Binary Search
796. Rotate String
1071. Greatest Common Divisor of Strings
1299. Replace Elements with Greatest Element on Right Side
1431. Kids With the Greatest Number of Candies
1614. Maximum Nesting Depth of the Parentheses
1752. Check if Array Is Sorted and Rotated
1768. Merge Strings Alternately
1903. Largest Odd Number in String
2965. Find Missing and Repeated Values
hard
25. Reverse Nodes in k-Group
26. Remove Duplicates from Sorted Array
27. Remove Element
42. Trapping Rain Water
51. N-Queens
55. Jump Game
80. Remove Duplicates from Sorted Array II
88. Merge Sorted Array
121. Best Time to Buy and Sell Stock
122. Best Time to Buy and Sell Stock II
189. Rotate Array
274. H-Index
medium
2. Add Two Numbers
3. Longest Substring Without Repeating Characters
5. Longest Palindromic Substring
8. String to Integer (atoi)
11. Container With Most Water
15. 3Sum
17. Letter Combinations of a Phone Number
19. Remove Nth Node From End of List
22. Generate Parentheses
33. Search in Rotated Sorted Array
34. Find First and Last Position of Element in Sorted Array
48. Rotate Image
49. Group Anagrams
50. Pow(x, n)
53. Maximum Subarray
54. Spiral Matrix
56. Merge Intervals
61. Rotate List
73. Set Matrix Zeroes
74. Search a 2D Matrix
75. Sort Colors
78. Subsets
137. Single Number II
138. Copy List with Random Pointer
150. Evaluate Reverse Polish Notation
151. Reverse Words in a String
153. Find Minimum in Rotated Sorted Array
155. Min Stack
162. Find Peak Element
169. Majority Element
198. House Robber
207. Course Schedule
215. Kth Largest Element in an Array
227. Basic Calculator II
236. Lowest Common Ancestor of a Binary Tree
237. Delete Node in a Linked List
238. Product of Array Except Self
451. Sort Characters By Frequency
540. Single Element in a Sorted Array
560. Subarray Sum Equals K
636. Exclusive Time of Functions
875. Koko Eating Bananas
1011. Capacity To Ship Packages Within D Days
1101. The Earliest Moment When Everyone Become Friends
1283. Find the Smallest Divisor Given a Threshold
2140. Solving Questions With Brainpower
3169. Count Days Without Meetings
3481. Apply Substitutions
rotate-array-approach-1
189. Rotate Array (Approach 2 )
189. Rotate Array (Approach 1 )
number-of-islands-approach-1
200. Number of Islands (Approach 2)
200. Number of Islands (Approach 1)
meeting-rooms-ii-approach-1
253. Approach Using Priority Queue
253. Meeting Rooms II
misc
Calculate Floor & Ceiling
Find Nth Root Of M
Flatten A Linked List
Implement Lower Bound
Implement Upper Bound
Number of occurrence
take-u-forward
Recently Solved
arrays
The Ultimate Array Pattern Playbook
faqs-hard
Count Inversions in an Array
Find The Repeating And Missing Number
Majority Element II
Maximum Product Subarray
Merge Sorted Array (In-Place)
Reverse Pairs
faqs-medium
3. 3Sum
4. 4Sum
Maximum Subarray
Leaders in an Array
Majority Element
Next Permutation
Get specific element from Pascal's Triangle
Pascal's Triangle II (Row Generation)
Generate Pascal's Triangle (Full)
Spiral Matrix Traversal
Rearrange Array Elements by Sign
Rotate Image
Sort Colors (Dutch National Flag)
Two Sum
fundamentals
Check if Array is Sorted
Largest Element in an Array
Array Rotation (Left and Right)
Left Rotate Array by One
Linear Search
Max Consecutive Ones
Second Largest Element in an Array
Single Number
logic-building
Missing Number
Intersection of Two Sorted Arrays (with Duplicates)
Move Zeros to End
Remove Duplicates from Sorted Array
Union of Two Sorted Arrays
binary-search
About
d-arrays
Find Row With Maximum 1'S
Search In A 2D Matrix
faqs
Aggressive Cows
Allocate Books
Find Peak Element
Kth Element Of 2 Sorted Arrays
Minimise Max Distance to Gas Stations
Split Array - Largest Sum
fundamentals
Lower Bound
Binary Search
Upper Bound
logic-building
Count Occurrences in a Sorted Array
Find Minimum in Rotated Sorted Array
Find out how many times the array is rotated
Find First and Last Position of Element in Sorted Array
Floor and Ceil in Sorted Array
Kth Missing Positive Number
Search in Rotated Sorted Array
Search in Rotated Sorted Array II (With Duplicates)
Search Insert Position
Single Element in a Sorted Array
on-answers
Capacity To Ship Packages Within D Days
Find Nth Root of M
Find Square Root of a Number
Smallest Divisor Given a Threshold
Koko Eating Bananas (Minimum Rate)
Minimum Days to Make M Bouquets
Painter's Partition Problem
Split Array Largest Sum
hashing
Theory
faqs
Subarray Sum Equals K
Count Subarrays with Given XOR K
Largest Subarray with 0 Sum
Longest Consecutive Sequence
Longest Subarray with Sum K
recursion
faqs-medium
Combination Sum II (Unique Combinations)
Combination Sum (Unbounded)
Subset Sums
hard
Letter Combinations of a Phone Number
implementation-problems
Generate Parentheses
Power Function: pow(x, n)
Subsets (The Power Set)
subsequence-pattern-problems
Subsequence Sum Existence
Count All Subsequences With Sum K
sorting
Bubble Sort
Insertion Sort
Merge Sort
Quick Sort
Selection Sort
string
Isomorphic Strings
Largest Odd Number in String
Longest Common Prefix
Reverse Words in a String
Code Scratch›leetcode›easy

1299. Replace Elements with Greatest Element on Right Side

# Question

Given an array arr, replace every element in that array with the greatest element strictly to its right, and replace the last element with -1. Return the modified array in-place.

# Solution

# Pattern

Reverse Traversal (Right-to-Left) When a problem requires aggregating information from elements to the right of the current index, iterate from right to left. This carries the "future" state backward, allowing you to compute answers in O(1)O(1)O(1) time per element.

# How to Identify

  • The problem requires making decisions based on the "remaining" array (everything to the right).
  • A brute force approach naturally leans toward nested loops O(N2)O(N^2)O(N2).
  • The information needed from the right side is an aggregate metric (e.g., maximum, minimum, sum, product).

# Description

Step-by-step explanation:

  1. Validate the input to ensure the array is not null or empty.
  2. Initialize a state variable, maxRight, to -1. This mathematically satisfies the requirement for the last element and seeds our maximum tracker.
  3. Iterate backward through the array, starting from arr.length - 1 down to 0.
  4. At each step, store the actual value of arr[i] into a temporary variable currentVal. We need this because we are about to overwrite arr[i], but we still need its original value to calculate the max for the elements to its left.
  5. Overwrite arr[i] with maxRight.
  6. Update maxRight by taking the maximum of its current value and currentVal.
  7. Continue until the loop terminates, then return the in-place modified array.

# The Intuition

Think of this algorithm as walking backward through time. If you walk forward (left-to-right), you don't know what the biggest number ahead of you is unless you run ahead to check (costing O(N)O(N)O(N) time per step). But if you start at the end and walk backward, you can just carry the biggest number you've found so far in your pocket. When you step onto a new number, you simply take the big number out of your pocket, write it down, and then check if the number you just stepped on is bigger than the one in your pocket. If it is, you swap it. This gives you perfect "hindsight" in a single pass.

# Complexity

LabelWorstAverage
Time ComplexityO(N)O(N)O(N)O(N)O(N)O(N)
Space ComplexityO(1)O(1)O(1)O(1)O(1)O(1)

# Time Complexity

We traverse the array of size NNN exactly once. Inside the loop, we perform O(1)O(1)O(1) constant-time operations (variable assignments and a Math.max comparison). Total time complexity is strictly O(N)O(N)O(N).

# Space Complexity

We modify the input array in-place. We allocate exactly two integer primitives (maxRight and currentVal) regardless of how large the input array is. Therefore, auxiliary space is strictly O(1)O(1)O(1).

# Code

class Solution {
    public int[] replaceElements(int[] arr) {
        if (arr == null || arr.length == 0) {
            return arr; 
        }
 
        int maxRight = -1;
        
        for (int i = arr.length - 1; i >= 0; i--) {
            // Cache the current element before overwriting
            int currentVal = arr[i];
            
            // Replace with the greatest element seen so far from the right
            arr[i] = maxRight;
            
            // Update the max for the next iteration (moving left)
            maxRight = Math.max(maxRight, currentVal);
        }
 
        return arr;
    }
}

# Caveats

  • Immutability Constraints: In some strict functional programming environments or multi-threaded contexts, mutating the input array (arr[i] = ...) is an anti-pattern or expressly forbidden. In such cases, you must sacrifice O(1)O(1)O(1) space and allocate a new result array of size NNN.
  • Stream Processing: If the array is arriving as an unbounded stream (e.g., live stock prices) where you must output the answer for day iii immediately before seeing day i+1i+1i+1, this reverse-traversal approach is physically impossible.

# Concepts to Think About

  • State Propagation: Notice how the state (maxRight) strictly propagates in one direction. This is a foundational building block for 1D Dynamic Programming.
  • In-Place Swapping Mechanics: The temp variable pattern used here is universal. Whenever you need to read and write to the same memory location where the old value influences future writes, a temporary cache is required.
  • Cache Locality: Reverse iteration has the exact same highly efficient cache locality as forward iteration. The CPU prefetches the contiguous memory blocks backward just as effectively.

# Logical Follow-up

Question: Find all the "Leaders" in an array. An element is a leader if it is strictly greater than all the elements to its right side. Solution: We use the exact same reverse-traversal pattern. Initialize maxRight = -infinity. Iterate from right to left. If arr[i] > maxRight, it is a leader; add it to the result list, and update maxRight = arr[i]. This solves the problem in O(N)O(N)O(N) time and O(1)O(1)O(1) space (excluding the output list).

Question: What if you needed to replace every element with the next strictly greater element to its right (not the absolute maximum), and -1 if none exists? (Next Greater Element) Solution: A single state variable no longer works because the "next greater" isn't necessarily the global maximum. We must use a Monotonic Stack. Iterate right-to-left. While the stack is not empty and the top of the stack is ≤arr[i]\le arr[i]≤arr[i], pop it. If the stack becomes empty, the answer is -1. Otherwise, the answer is the top of the stack. Push arr[i]arr[i]arr[i] to the stack. This requires O(N)O(N)O(N) time and O(N)O(N)O(N) space.

Previous1071. Greatest Common Divisor of StringsNext1431. Kids With the Greatest Number of Candies
CONTENTS
QuestionSolutionPatternHow to IdentifyDescriptionThe IntuitionComplexityCodeCaveatsConcepts to Think AboutLogical Follow-up