Modify given array by reducing each element by its next smaller element
Last Updated :
23 Jul, 2025
Given an array arr[] of length N, the task is to modify the given array by replacing each element of the given array by its next smaller element, if possible. Print the modified array as the required answer.
Examples:
Input: arr[] = {8, 4, 6, 2, 3}
Output: 4 2 4 2 3
Explanation: The operations can be performed as follows:
- For arr[0], arr[1] is the next smaller element.
- For arr[1], arr[3] is the next smaller element.
- For arr[2], arr[3] is the next smaller element.
- For arr[3], no smaller element present after it.
- For arr[4], no smaller element present after it.
Input: arr[] = {1, 2, 3, 4, 5}
Output: 1 2 3 4 5
Naive Approach: The simplest approach is to traverse the array and for each element, traverse the remaining elements after it and check if any smaller element is present or not. If found, reduce that element by the first smaller element obtained.
Time Complexity: O(N2)
Auxiliary Space: O(N)
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to print the final array
// after reducing each array element
// by its next smaller element
void printFinalPrices(vector<int>& arr)
{
// Stores the resultant array
vector<int> ans;
// Traverse the array
for (int i = 0; i < arr.size(); i++) {
int flag = 1;
for (int j = i + 1; j < arr.size(); j++) {
// If a smaller element is found
if (arr[j] <= arr[i]) {
// Reduce current element by
// next smaller element
ans.push_back(arr[i] - arr[j]);
flag = 0;
break;
}
}
// If no smaller element is found
if (flag == 1)
ans.push_back(arr[i]);
}
// Print the answer
for (int i = 0; i < ans.size(); i++)
cout << ans[i] << " ";
}
// Driver Code
int main()
{
// Given array
vector<int> arr = { 8, 4, 6, 2, 3 };
// Function Call
printFinalPrices(arr);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to print the final array
// after reducing each array element
// by its next smaller element
static void printFinalPrices(int[] arr)
{
// Stores the resultant array
ArrayList<Integer> ans = new ArrayList<Integer>();
// Traverse the array
for(int i = 0; i < arr.length; i++)
{
int flag = 1;
for(int j = i + 1; j < arr.length; j++)
{
// If a smaller element is found
if (arr[j] <= arr[i])
{
// Reduce current element by
// next smaller element
ans.add(arr[i] - arr[j]);
flag = 0;
break;
}
}
// If no smaller element is found
if (flag == 1)
ans.add(arr[i]);
}
// Print the answer
for(int i = 0; i < ans.size(); i++)
System.out.print(ans.get(i) + " ");
}
// Driver Code
public static void main(String[] args)
{
// Given array
int[] arr = { 8, 4, 6, 2, 3 };
// Function Call
printFinalPrices(arr);
}
}
// This code is contributed by code_hunt
Python3
# Python3 program for the above approach
# Function to print the final array
# after reducing each array element
# by its next smaller element
def printFinalarr(arr):
# Stores resultant array
ans = []
# Traverse the given array
for i in range(len(arr)):
flag = 1
for j in range(i + 1, len(arr)):
# If a smaller element is found
if arr[j] <= arr[i]:
# Reduce current element by
# next smaller element
ans.append(arr[i] - arr[j])
flag = 0
break
if flag:
# If no smaller element is found
ans.append(arr[i])
# Print the final array
for k in range(len(ans)):
print(ans[k], end =' ')
# Driver Code
if __name__ == '__main__':
# Given array
arr = [8, 4, 6, 2, 3]
# Function call
printFinalarr(arr)
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to print the final array
// after reducing each array element
// by its next smaller element
static void printFinalPrices(int[] arr)
{
// Stores the resultant array
List<int> ans = new List<int>();
// Traverse the array
for(int i = 0; i < arr.Length; i++)
{
int flag = 1;
for(int j = i + 1; j < arr.Length; j++)
{
// If a smaller element is found
if (arr[j] <= arr[i])
{
// Reduce current element by
// next smaller element
ans.Add(arr[i] - arr[j]);
flag = 0;
break;
}
}
// If no smaller element is found
if (flag == 1)
ans.Add(arr[i]);
}
// Print the answer
for(int i = 0; i < ans.Count; i++)
Console.Write(ans[i] + " ");
}
// Driver code
static void Main()
{
// Given array
int[] arr = { 8, 4, 6, 2, 3 };
// Function Call
printFinalPrices(arr);
}
}
// This code is contributed by divyeshrabadiya07
JavaScript
<script>
// Js program for the above approach
// Function to print the final array
// after reducing each array element
// by its next smaller element
function printFinalPrices( arr)
{
// Stores the resultant array
let ans = [];
// Traverse the array
for (let i = 0; i < arr.length; i++) {
let flag = 1;
for (let j = i + 1; j < arr.length; j++) {
// If a smaller element is found
if (arr[j] <= arr[i]) {
// Reduce current element by
// next smaller element
ans.push(arr[i] - arr[j]);
flag = 0;
break;
}
}
// If no smaller element is found
if (flag == 1)
ans.push(arr[i]);
}
// Print the answer
for (let i = 0; i < ans.length; i++)
document.write(ans[i], " ");
}
// Driver Code
// Given array
let arr = [ 8, 4, 6, 2, 3 ];
// Function Call
printFinalPrices(arr);
</script>
Time Complexity: O(N^2) ,As we are running two nested loops to traverse the array.
Space Complexity: O(N),As we are storing the resultant array.
Efficient Approach: To optimize the above approach, the idea is to use Stack data structure. Follow the steps below to solve the problem:
- Initialize a Stack and an array ans[] of size N, to store the resultant array.
- Traverse the given array over the indices i = N - 1 to 0.
- If the stack is empty, push the current element arr[i] to the top of the stack.
- Otherwise, if the current element is greater than the element at the top of the stack, push it into the stack and then remove elements from the stack, until the stack becomes empty or an element smaller than or equal to arr[i] is found. After that, if the stack is not empty, set ans[i] = arr[i] - top element of the stack and then remove it from the stack.
- Otherwise, remove the top element from the stack and set ans[i] equal to the top element in the stack and then remove it from the stack.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to print the final array
// after reducing each array element
// by its next smaller element
void printFinalPrices(vector<int>& arr)
{
// Initialize stack
stack<int> minStk;
// Array size
int n = arr.size();
// To store the corresponding element
vector<int> reduce(n, 0);
for (int i = n - 1; i >= 0; i--) {
// If stack is not empty
if (!minStk.empty()) {
// If top element is smaller
// than the current element
if (minStk.top() <= arr[i]) {
reduce[i] = minStk.top();
}
else {
// Keep popping until stack is empty
// or top element is greater than
// the current element
while (!minStk.empty()
&& (minStk.top() > arr[i])) {
minStk.pop();
}
// If stack is not empty
if (!minStk.empty()) {
reduce[i] = minStk.top();
}
}
}
// Push current element
minStk.push(arr[i]);
}
// Print the final array
for (int i = 0; i < n; i++)
cout << arr[i] - reduce[i] << " ";
}
// Driver Code
int main()
{
// Given array
vector<int> arr = { 8, 4, 6, 2, 3 };
// Function call
printFinalPrices(arr);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to print the final array
// after reducing each array element
// by its next smaller element
static void printFinalPrices(int[] arr)
{
// Initialize stack
Stack<Integer> minStk = new Stack<>();
// Array size
int n = arr.length;
// To store the corresponding element
int[] reduce = new int[n];
for(int i = n - 1; i >= 0; i--)
{
// If stack is not empty
if (!minStk.isEmpty())
{
// If top element is smaller
// than the current element
if (minStk.peek() <= arr[i])
{
reduce[i] = minStk.peek();
}
else
{
// Keep popping until stack is empty
// or top element is greater than
// the current element
while (!minStk.isEmpty() &&
(minStk.peek() > arr[i]))
{
minStk.pop();
}
// If stack is not empty
if (!minStk.isEmpty())
{
reduce[i] = minStk.peek();
}
}
}
// Push current element
minStk.add(arr[i]);
}
// Print the final array
for(int i = 0; i < n; i++)
System.out.print(arr[i] - reduce[i] + " ");
}
// Driver Code
public static void main(String[] args)
{
// Given array
int[] arr = { 8, 4, 6, 2, 3 };
// Function call
printFinalPrices(arr);
}
}
// This code is contributed by Rajput-Ji
Python3
# Python3 program for the above approach
# Function to print the final array
# after reducing each array element
# by its next smaller element
def printFinalPrices(arr):
# Initialize stack
minStk = []
# To store the corresponding element
reduce = [0] * len(arr)
for i in range(len(arr) - 1, -1, -1):
# If stack is not empty
if minStk:
# If top element is smaller
# than the current element
if minStk[-1] <= arr[i]:
reduce[i] = minStk[-1]
else:
# Keep popping until stack is empty
# or top element is greater than
# the current element
while minStk and minStk[-1] > arr[i]:
minStk.pop()
if minStk:
# Corresponding elements
reduce[i] = minStk[-1]
# Push current element
minStk.append(arr[i])
# Final array
for i in range(len(arr)):
print(arr[i] - reduce[i], end =' ')
# Driver Code
if __name__ == '__main__':
# Given array
arr = [8, 4, 6, 2, 3]
# Function Call
printFinalPrices(arr)
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to print the readonly array
// after reducing each array element
// by its next smaller element
static void printFinalPrices(int[] arr)
{
// Initialize stack
Stack<int> minStk = new Stack<int>();
// Array size
int n = arr.Length;
// To store the corresponding element
int[] reduce = new int[n];
for(int i = n - 1; i >= 0; i--)
{
// If stack is not empty
if (minStk.Count != 0)
{
// If top element is smaller
// than the current element
if (minStk.Peek() <= arr[i])
{
reduce[i] = minStk.Peek();
}
else
{
// Keep popping until stack is empty
// or top element is greater than
// the current element
while (minStk.Count != 0 &&
(minStk.Peek() > arr[i]))
{
minStk.Pop();
}
// If stack is not empty
if (minStk.Count != 0)
{
reduce[i] = minStk.Peek();
}
}
}
// Push current element
minStk.Push(arr[i]);
}
// Print the readonly array
for(int i = 0; i < n; i++)
Console.Write(arr[i] - reduce[i] + " ");
}
// Driver Code
public static void Main(String[] args)
{
// Given array
int[] arr = { 8, 4, 6, 2, 3 };
// Function call
printFinalPrices(arr);
}
}
// This code contributed by shikhasingrajput
JavaScript
<script>
// javascript program for the above approach
// Function to print the final array
// after reducing each array element
// by its next smaller element
function printFinalPrices(arr)
{
// Initialize stack
var minStk = []
// Array size
var n = arr.length;
var i;
// To store the corresponding element
var reduce = Array(n).fill(0);
for (i = n - 1; i >= 0; i--) {
// If stack is not empty
if (minStk.length>0) {
// If top element is smaller
// than the current element
if (minStk[minStk.length-1] <= arr[i]) {
reduce[i] = minStk[minStk.length-1];
}
else {
// Keep popping until stack is empty
// or top element is greater than
// the current element
while (minStk.length>0
&& (minStk[minStk.length-1] > arr[i])) {
minStk.pop();
}
// If stack is not empty
if (minStk.length>0) {
reduce[i] = minStk[minStk.length-1];
}
}
}
// Push current element
minStk.push(arr[i]);
}
// Print the final array
for (i = 0; i < n; i++)
document.write(arr[i] - reduce[i] + " ");
}
// Driver Code
// Given array
var arr = [8, 4, 6, 2, 3];
// Function call
printFinalPrices(arr);
// This code is contributed by ipg2016107.
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem