Given an array arr[]. Replace every element with the next greatest element (the greatest element on its right side) in the array.
Note: There is no element next to the last element, so replace it with -1.
Examples:
Input: arr[] = [16, 17, 4, 3, 5, 2]
Output: [17, 5, 5, 5, 2, -1]
Explanation: For 16 the greatest element on its right is 17 similarly for 17 it's 5 and also for 2 it's -1 (no element to its right).Input: arr[] = [2, 3, 1, 9]
Output: [9, 9, 9, -1]
Explanation: For each element except 9 the greatest element on its right is 9.
Table of Content
[Naive Approach] Using Brute Force - O(n * n) Time and O(1) Space
Use two nested loops. For each element, scan the remaining elements to its right to find the maximum value. Replace the current element with this maximum. Since the very last element has nothing to its right, manually replace it with -1.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Function to find and return the next greatest element for every array element
vector<int> nextGreatest(vector<int> &arr) {
int n = arr.size();
vector<int> ans;
// Outer loop picks each element one by one
for(int i = 0; i < n; i++) {
// Initialize max_value as -1.
// This also handles the last element automatically.
int max_value = -1;
// Inner loop checks all elements to the RIGHT of the current element
for(int j = i + 1; j < n; j++) {
// Update max_value if we find a strictly greater element
max_value = max(max_value, arr[j]);
}
// Store the maximum element found for the current position
ans.push_back(max_value);
}
return ans;
}
int main() {
vector<int> arr = {16, 17, 4, 3, 5, 2};
vector<int> ans = nextGreatest(arr);
for(int i : ans) {
cout << i << " ";
}
return 0;
}
class GFG {
// Function to replace every element with the next greatest element
// and return the modified array
static int[] nextGreatest(int[] arr) {
int n = arr.length;
// Outer loop picks each element one by one
for (int i = 0; i < n; i++) {
int max_value = -1;
// Inner loop scans all elements strictly to the RIGHT
for (int j = i + 1; j < n; j++) {
// Update max_value if we find a larger element
max_value = Math.max(max_value, arr[j]);
}
// Replace the current element with the maximum value found
arr[i] = max_value;
}
return arr;
}
public static void main(String[] args) {
int[] arr = { 16, 17, 4, 3, 5, 2 };
int[] ans = nextGreatest(arr);
for (int i : ans) {
System.out.print(i + " ");
}
System.out.println();
}
}
# Function to replace every element with the next greatest element
# and return the modified array
def nextGreatest(arr):
n = len(arr)
# Outer loop picks each element one by one
for i in range(n):
# Initialize max_value as -1.
# This naturally handles the last element since the inner loop won't run for it.
max_value = -1
# Inner loop scans all elements strictly to the RIGHT of the current element
for j in range(i + 1, n):
# Update max_value if we find a strictly larger element
max_value = max(max_value, arr[j])
# Replace the current element with the maximum value found
arr[i] = max_value
return arr
if __name__ == '__main__':
arr = [16, 17, 4, 3, 5, 2]
ans = nextGreatest(arr)
for item in ans:
print(item, end=" ")
print()
using System;
public class GFG {
// Function to replace every element with the next greatest element
// and return the modified array
static int[] NextGreatest(int[] arr) {
int n = arr.Length;
// Outer loop picks each element one by one
for (int i = 0; i < n; i++) {
// Initialize max_value as -1.
// This natively handles the last element since the inner loop won't run.
int max_value = -1;
// Inner loop scans all elements strictly to the RIGHT
for (int j = i + 1; j < n; j++) {
// Update max_value if we find a strictly larger element
max_value = Math.Max(max_value, arr[j]);
}
// Replace the current element with the maximum value found
arr[i] = max_value;
}
return arr;
}
public static void Main(string[] args) {
int[] arr = { 16, 17, 4, 3, 5, 2 };
int[] ans = NextGreatest(arr);
foreach (int item in ans) {
Console.Write(item + " ");
}
Console.WriteLine();
}
}
// Function to replace every element with the next greatest element
// and return the modified array
function nextGreatest(arr) {
let n = arr.length;
// Outer loop picks each element one by one
for (let i = 0; i < n; i++) {
// Initialize max_value as -1.
// This natively handles the last element since the inner loop won't run.
let max_value = -1;
// Inner loop scans all elements strictly to the RIGHT
for (let j = i + 1; j < n; j++) {
// Update max_value if we find a strictly larger element
max_value = Math.max(max_value, arr[j]);
}
// Replace the current element with the maximum value found
arr[i] = max_value;
}
return arr;
}
let arr = [16, 17, 4, 3, 5, 2];
let ans = nextGreatest(arr);
console.log(ans.join(" "));
Output
17 5 5 5 2 -1
[Expected Approach] Using Right to Left Traversal - O(n) Time and O(1) Space
Instead of repeatedly looking ahead to the right for every single element, start from the very end of the array and move left, keep track of the "largest number seen so far."
For each position, replace the current number with "largest seen so far," and then check if the number just replaced is bigger than tracked maximum. If it is, it becomes the new maximum for the elements to its left.
For example, arr[] = [16, 17, 4, 3, 5, 2], max_so_far = -1
- Index 5 (Original = 2): Replace 2 with -1. arr is [16, 17, 4, 3, 5, -1]. New max becomes max(-1, 2) = 2
- Index 4 (Original = 5): Replace 5 with 2. arr is [16, 17, 4, 3, 2, -1]. New max becomes max(2, 5) = 5
- Index 3 (Original = 3): Replace 3 with 5. arr is [16, 17, 4, 5, 2, -1]. New max becomes max(5, 3) = 5
- Index 2 (Original = 4): Replace 4 with 5. arr is [16, 17, 5, 5, 2, -1]. New max becomes max(5, 4) = 5
- Index 1 (Original = 17): Replace 17 with 5. arr is [16, 5, 5, 5, 2, -1]. New max becomes max(5, 17) = 17
- Index 0 (Original = 16): Replace 16 with 17. arr is [17, 5, 5, 5, 2, -1]. New max becomes max(17, 16) = 17
Final Array: [17, 5, 5, 5, 2, -1]
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Function to replace every element with the next greatest element
// and return the modified array
vector<int> nextGreatest(vector<int>& arr) {
int n = arr.size();
// Initialize the maximum element seen so far from the right
int maxFromRight = -1;
// Traverse the array backwards (from right to left)
for(int i = n - 1; i >= 0; i--) {
// Store the current element temporarily before we overwrite it
int temp = arr[i];
// Replace the current element with the max seen so far
arr[i] = maxFromRight;
// Update maxFromRight if the original element was larger
maxFromRight = max(maxFromRight, temp);
}
return arr;
}
int main() {
vector<int> arr = {16, 17, 4, 3, 5, 2};
vector<int> ans = nextGreatest(arr);
for(int i : ans) {
cout << i << " ";
}
cout << endl;
return 0;
}
class GFG {
// Function to replace every element with the next greatest element
// and return the modified array
static int[] nextGreatest(int[] arr) {
int n = arr.length;
// Initialize the maximum element seen so far from the right
int maxFromRight = -1;
// Traverse the array backwards (from right to left)
for (int i = n - 1; i >= 0; i--) {
// Store the current element temporarily before we overwrite it
int temp = arr[i];
// Replace the current element with the max seen so far
arr[i] = maxFromRight;
// Update maxFromRight if the original element was larger
maxFromRight = Math.max(maxFromRight, temp);
}
return arr;
}
public static void main (String[] args) {
int[] arr = {16, 17, 4, 3, 5, 2};
int[] ans = nextGreatest(arr);
for (int item : ans) {
System.out.print(item + " ");
}
System.out.println();
}
}
# Function to replace every element with the next greatest element
def nextGreatest(arr):
n = len(arr)
# Initialize the maximum element seen so far from the right
max_from_right = -1
# Traverse the array backwards (from right to left)
for i in range(n - 1, -1, -1):
# Store the current element temporarily before we overwrite it
temp = arr[i]
# Replace the current element with the max seen so far
arr[i] = max_from_right
# Update max_from_right if the original element was larger
max_from_right = max(max_from_right, temp)
return arr
if __name__ == "__main__":
arr = [16, 17, 4, 3, 5, 2]
nextGreatest(arr)
print(*arr)
using System;
public class GFG {
// Function to replace every element with the next greatest element
// and return the modified array
static int[] NextGreatest(int[] arr) {
int n = arr.Length;
// Initialize the maximum element seen so far from the right
int maxFromRight = -1;
// Traverse the array backwards (from right to left)
for (int i = n - 1; i >= 0; i--) {
// Store the current element temporarily before we overwrite it
int temp = arr[i];
// Replace the current element with the max seen so far
arr[i] = maxFromRight;
// Update maxFromRight if the original element was larger
maxFromRight = Math.Max(maxFromRight, temp);
}
return arr;
}
public static void Main() {
int[] arr = { 16, 17, 4, 3, 5, 2 };
int[] ans = NextGreatest(arr);
Console.WriteLine(string.Join(" ", ans));
}
}
// Function to replace every element with the next greatest element
// and return the modified array
function nextGreatest(arr) {
let n = arr.length;
// Initialize the maximum element seen so far from the right
let max_from_right = -1;
// Traverse the array backwards (from right to left)
for (let i = n - 1; i >= 0; i--) {
// Store the current element temporarily before we overwrite it
let temp = arr[i];
// Replace the current element with the max seen so far
arr[i] = max_from_right;
// Update max_from_right if the original element was larger
max_from_right = Math.max(max_from_right, temp);
}
// Return the modified array
return arr;
}
// Driver code
let arr = [16, 17, 4, 3, 5, 2];
let ans = nextGreatest(arr);
console.log(ans.join(" "));
Output
17 5 5 5 2 -1