Open In App

Replace every element of the array by its next element

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr, the task is to replace each element of the array with the element that appears after it and replace the last element with -1.

Examples: 

Input: arr[] = {5, 1, 3, 2, 4} 
Output: 1 3 2 4 -1

Input: arr[] = {6, 8, 32, 12, 14, 10, 25 } 
Output: 8 32 12 14 10 25 -1 

Approach: Traverse the array from 0 to n-2 and update arr[i] = arr[i+1]. In the end, set a[n-1] = -1 and print the contents of the updated array.

Below is the implementation of the above approach: 

C++




// C++ program to replace every element of the array
// with the element that appears after it
#include <bits/stdc++.h>
using namespace std;
 
// Function to print the array after replacing every element
// of the array with the element that appears after it
void updateArray(int arr[], int n)
{
    // Update array
    for (int i = 0; i <= n - 2; i++)
        arr[i] = arr[i + 1];
 
    // Change the last element to -1
    arr[n - 1] = -1;
 
    // Print the updated array
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
}
 
// Driver program
int main()
{
    int arr[] = { 5, 1, 3, 2, 4 };
    int N = sizeof(arr) / sizeof(arr[0]);
    updateArray(arr, N);
    return 0;
}


Java




// Java program to replace every element
// of the array with the element that
// appears after it
class GFG
{
 
// Function to print the array after
// replacing every element of the array
// with the element that appears after it
static void updateArray(int arr[], int n)
{
    // Update array
    for (int i = 0; i <= n - 2; i++)
        arr[i] = arr[i + 1];
 
    // Change the last element to -1
    arr[n - 1] = -1;
 
    // Print the updated array
    for (int i = 0; i < n; i++)
        System.out.print(arr[i] + " ");
}
 
// Driver Code
public static void main(String []args)
{
    int arr[] = { 5, 1, 3, 2, 4 } ;
    int N = arr.length ;
    updateArray(arr, N);
}
}
 
// This code is contributed by Ryuga


Python3




# Python3 program to replace every
# element of the array with the
# element that appears after it
 
# Function to print the array after
# replacing every element of the
# array with the element that appears
# after it
def updateArray(arr, n):
 
    # Update array
    for i in range (n - 1):
        arr[i] = arr[i + 1]
 
    # Change the last element to -1
    arr[n - 1] = -1
 
    # Print the updated array
    for i in range( n):
        print (arr[i], end = " ")
 
# Driver Code
if __name__ == "__main__":
 
    arr = [ 5, 1, 3, 2, 4 ]
    N = len(arr)
    updateArray(arr, N)
 
# This code is contributed
# by ChitraNayal


C#




// C# program to replace every element
// of the array with the element that
// appears after it
using System;
 
class GFG
{
 
// Function to print the array after
// replacing every element of the array
// with the element that appears after it
static void updateArray(int[] arr, int n)
{
    // Update array
    for (int i = 0; i <= n - 2; i++)
        arr[i] = arr[i + 1];
 
    // Change the last element to -1
    arr[n - 1] = -1;
 
    // Print the updated array
    for (int i = 0; i < n; i++)
        Console.Write(arr[i] + " ");
}
 
// Driver Code
public static void Main()
{
    int[] arr = { 5, 1, 3, 2, 4 } ;
    int N = arr.Length ;
    updateArray(arr, N);
}
}
 
// This code is contributed
// by Akanksha Rai


PHP




<?php
// PHP program to replace every element
// of the array with the element that
// appears after it
 
// Function to print the array after
// replacing every element of the
// array with the element that appears
// after it
function updateArray(&$arr, $n)
{
    // Update array
    for ($i = 0; $i <= $n - 2; $i++)
        $arr[$i] = $arr[$i + 1];
 
    // Change the last element to -1
    $arr[$n - 1] = -1;
 
    // Print the updated array
    for ($i = 0; $i < $n; $i++)
    {
        echo ($arr[$i]);
        echo (" ");
    }
}
 
// Driver Code
$arr = array(5, 1, 3, 2, 4 );
$N = sizeof($arr);
updateArray($arr, $N);
     
// This code is contributed
// by Shivi_Aggarwal
?>


Javascript




<script>
 
// Javascript program to replace every element of the array
// with the element that appears after it
 
// Function to print the array after replacing every element
// of the array with the element that appears after it
function updateArray(arr, n)
{
    // Update array
    for (let i = 0; i <= n - 2; i++)
        arr[i] = arr[i + 1];
 
    // Change the last element to -1
    arr[n - 1] = -1;
 
    // Print the updated array
    for (let i = 0; i < n; i++)
        document.write(arr[i] + " ");
}
 
// Driver program
 
    let arr = [ 5, 1, 3, 2, 4 ];
    let N = arr.length;
    updateArray(arr, N);
 
//This code is contributed by Mayank Tyagi
 
</script>


C




// C program to replace every element of the array
// with the element that appears after it
#include <stdio.h>
 
// Function to print the array after replacing every element
// of the array with the element that appears after it
void updateArray(int arr[], int n)
{
    // Update array
    for (int i = 0; i <= n - 2; i++)
        arr[i] = arr[i + 1];
 
    // Change the last element to -1
    arr[n - 1] = -1;
 
    // Print the updated array
    for (int i = 0; i < n; i++)
        printf("%d ",arr[i]);
}
 
// Driver program
int main()
{
    int arr[] = { 5, 1, 3, 2, 4 };
    int N = sizeof(arr) / sizeof(arr[0]);
    updateArray(arr, N);
    return 0;
}


Output

1 3 2 4 -1 

Complexity Analysis:

  • Time Complexity: O(n)
  • Auxiliary Space: O(1)

Approach 2: Using Stack:

The approach to solving this problem is to use a stack to keep track of the largest element seen so far while traversing the array from right to left. We initialize the stack with the last element of the array since there are no larger elements to the right of it.

Below is the step-by-step algorithm for the above approach:

  • Initialize a stack and put the last element of the array into it.
  • We iterate over the remaining elements of the array in reverse order. For each element, we check if it is greater than the top element of the stack. If it is, we pop the top element of the stack until we find an element that is greater than the current element or until the stack is empty. The element at the top of the stack after this process is the nearest larger element to the right of the current element. We then replace the current element in the array with the top element of the stack.
  • We continue this process for all the elements in the array. At the end, we replace the last element of the array with -1 since there are no larger elements to the right of it.
  • Finally, we print the modified array to the console.

Below is the code for the above approach:

C++




#include <iostream>
#include <stack>
 
void updateArray(int arr[], int n) {
    std::stack<int> st;
    st.push(arr[n - 1]);
    for (int i = n - 2; i >= 0; --i) {
        int curr = arr[i];
        arr[i] = st.top();
        while (!st.empty() && curr > st.top()) {
            st.pop();
        }
        st.push(curr);
    }
    arr[n - 1] = -1;
    for (int i = 0; i < n; ++i) {
        std::cout << arr[i] << " ";
    }
}
 
int main() {
    int arr[] = {5, 1, 3, 2, 4};
    int N = sizeof(arr) / sizeof(arr[0]);
 
    updateArray(arr, N);
 
    return 0;
}


Java




import java.util.Stack;
 
class Main {
    public static void updateArray(int[] arr, int n) {
        Stack<Integer> st = new Stack<>();
        st.push(arr[n - 1]);
        for (int i = n - 2; i >= 0; --i) {
            int curr = arr[i];
            arr[i] = st.peek();
            while (!st.empty() && curr > st.peek()) {
                st.pop();
            }
            st.push(curr);
        }
        arr[n - 1] = -1;
        for (int i = 0; i < n; ++i) {
            System.out.print(arr[i] + " ");
        }
    }
 
    public static void main(String[] args) {
        int[] arr = {5, 1, 3, 2, 4};
        int N = arr.length;
 
        updateArray(arr, N);
    }
}


Python




def update_array(arr, n):
    stack = []
    stack.append(arr[n - 1])
     # Loop through the array from the right
    for i in range(n - 2, -1, -1):
        curr = arr[i]
         # Replace with the maximum so far
        arr[i] = stack[-1]
        # Pop elements from the stack that are smaller than curr
        while stack and curr > stack[-1]:
            stack.pop()
        # Add curr to the stack
        stack.append(curr)
    # Rightmost element is always -1
    arr[n - 1] = -1
    for i in range(n):
        # Print the updated array
        print(arr[i])
#Driver Code    
arr = [5, 1, 3, 2, 4]
N = len(arr)
 
update_array(arr, N)


Javascript




function update_array(arr, n) {
    let stack = [];
    stack.push(arr[n - 1]);
    // Loop through the array from the right
    for (let i = n - 2; i >= 0; i--) {
        let curr = arr[i];
        // Replace with the maximum so far
        arr[i] = stack[stack.length - 1];
        // Pop elements from the stack that are smaller than curr
        while (stack.length && curr > stack[stack.length - 1]) {
            stack.pop();
        }
        // Add curr to the stack
        stack.push(curr);
    }
    // Rightmost element is always -1
    arr[n - 1] = -1;
    for (let i = 0; i < n; i++) {
        // Print the updated array
        console.log(arr[i]);
    }
}
//Driver Code    
let arr = [5, 1, 3, 2, 4];
let N = arr.length;
 
update_array(arr, N);


C#




// C# program to replace every element
// of the array with the element that
// appears after it
using System;
using System.Collections;
 
class GFG
{
 
// Function to print the array after
// replacing every element of the array
// with the element that appears after it
static void updateArray(int[] arr, int n)
{
       
      Stack st = new Stack();
    st.Push(arr[n - 1]);
    for (int i = n - 2; i >= 0; --i) {
        int curr = arr[i];
        arr[i] = Convert.ToInt32(st.Peek());
        while ((st.Count!=0) && (curr > Convert.ToInt32(st.Peek()))) {
            st.Pop();
        }
        st.Push(curr);
    }
    arr[n - 1] = -1;
   
    // Print the updated array
    for (int i = 0; i < n; i++)
        Console.Write(arr[i] + " ");
   
}
 
// Driver Code
public static void Main()
{
    int[] arr = { 5, 1, 3, 2, 4 } ;
    int N = arr.Length ;
    updateArray(arr, N);
}
}
//code contributed by shubhamrajput6156


Output

1 3 2 4 -1 

Complexity Analysis:

Time Complexity: O(n)
Auxiliary Space: O(n)



Last Updated : 23 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads