Given an array of integers, replace every element with the least greater element on its right side in the array. If there are no greater elements on the right side, replace it with -1.
Examples:
Input: [8, 58, 71, 18, 31, 32, 63, 92,
43, 3, 91, 93, 25, 80, 28]
Output: [18, 63, 80, 25, 32, 43, 80, 93,
80, 25, 93, -1, 28, -1, -1]
A naive method is to run two loops. The outer loop will one by one pick array elements from left to right. The inner loop will find the smallest element greater than the picked element on its right side. Finally, the outer loop will replace the picked element with the element found by inner loop. The time complexity of this method will be O(n2).
A tricky solution would be to use Binary Search Trees. We start scanning the array from right to left and insert each element into the BST. For each inserted element, we replace it in the array by its inorder successor in BST. If the element inserted is the maximum so far (i.e. its inorder successor doesn’t exist), we replace it by -1.
Below is the implementation of the above idea –
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
};
Node* newNode( int item)
{
Node* temp = new Node;
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
Node* insert(Node* root, int val, int & suc)
{
if (!root)
return newNode(val);
if (val >= root->data)
root->right = insert(root->right, val, suc);
else {
suc = root->data;
root->left = insert(root->left, val, suc);
}
return root;
}
void replace( int arr[], int n)
{
Node* root = nullptr;
for ( int i = n - 1; i >= 0; i--) {
int suc = -1;
root = insert(root, arr[i], suc);
arr[i] = suc;
}
}
int main()
{
int arr[] = { 8, 58, 71, 18, 31, 32, 63, 92,
43, 3, 91, 93, 25, 80, 28 };
int n = sizeof (arr) / sizeof (arr[0]);
replace(arr, n);
for ( int i = 0; i < n; i++)
cout << arr[i] << " " ;
return 0;
}
|
Java
import java.io.*;
class BinarySearchTree {
class Node {
int data;
Node left, right;
Node( int d)
{
data = d;
left = right = null ;
}
}
static Node root;
static Node succ;
BinarySearchTree()
{
root = null ;
succ = null ;
}
Node insert(Node node, int data)
{
if (node == null ) {
node = new Node(data);
}
if (data < node.data) {
succ = node;
node.left = insert(node.left, data);
}
else if (data > node.data)
node.right = insert(node.right, data);
return node;
}
static void replace( int arr[], int n)
{
BinarySearchTree tree = new BinarySearchTree();
for ( int i = n - 1 ; i >= 0 ; i--) {
succ = null ;
root = tree.insert(root, arr[i]);
if (succ != null )
arr[i] = succ.data;
else
arr[i] = - 1 ;
}
}
public static void main(String[] args)
{
int arr[]
= new int [] { 8 , 58 , 71 , 18 , 31 , 32 , 63 , 92 ,
43 , 3 , 91 , 93 , 25 , 80 , 28 };
int n = arr.length;
replace(arr, n);
for ( int i = 0 ; i < n; i++)
System.out.print(arr[i] + " " );
}
}
|
Python3
class Node:
def __init__( self , d):
self .data = d
self .left = None
self .right = None
def insert(node, data):
global succ
root = node
if (node = = None ):
return Node(data)
if (data < node.data):
succ = node
root.left = insert(node.left, data)
elif (data > node.data):
root.right = insert(node.right, data)
return root
def replace(arr, n):
global succ
root = None
for i in range (n - 1 , - 1 , - 1 ):
succ = None
root = insert(root, arr[i])
if (succ):
arr[i] = succ.data
else :
arr[i] = - 1
return arr
if __name__ = = '__main__' :
arr = [ 8 , 58 , 71 , 18 , 31 , 32 , 63 ,
92 , 43 , 3 , 91 , 93 , 25 , 80 , 28 ]
n = len (arr)
succ = None
arr = replace(arr, n)
print ( * arr)
|
C#
using System;
class BinarySearchTree {
public class Node {
public int data;
public Node left, right;
public Node( int d)
{
data = d;
left = right = null ;
}
}
public static Node root;
public static Node succ;
public BinarySearchTree()
{
root = null ;
succ = null ;
}
public static Node insert(Node node, int data)
{
if (node == null ) {
node = new Node(data);
}
if (data < node.data) {
succ = node;
node.left = insert(node.left, data);
}
else if (data > node.data) {
node.right = insert(node.right, data);
}
return node;
}
public static void replace( int [] arr, int n)
{
for ( int i = n - 1; i >= 0; i--) {
succ = null ;
root = BinarySearchTree.insert(root, arr[i]);
if (succ != null ) {
arr[i] = succ.data;
}
else {
arr[i] = -1;
}
}
}
static public void Main()
{
int [] arr = { 8, 58, 71, 18, 31, 32, 63, 92,
43, 3, 91, 93, 25, 80, 28 };
int n = arr.Length;
replace(arr, n);
for ( int i = 0; i < n; i++) {
Console.Write(arr[i] + " " );
}
}
}
|
Javascript
<script>
class Node{
constructor(d)
{
this .data=d;
this .left= this .right= null ;
}
}
let root= null ;
let succ= null ;
function insert(node,data)
{
if (node == null )
{
node = new Node(data);
}
if (data < node.data)
{
succ = node;
node.left = insert(node.left, data);
}
else if (data > node.data)
node.right = insert(node.right, data);
return node;
}
function replace(arr,n)
{
for (let i = n - 1; i >= 0; i--)
{
succ = null ;
root = insert(root, arr[i]);
if (succ != null )
arr[i] = succ.data;
else
arr[i] = -1;
}
}
let arr=[8, 58, 71, 18, 31,
32, 63, 92, 43, 3,
91, 93, 25, 80, 28 ];
let n = arr.length;
replace(arr, n);
for (let i = 0; i < n; i++)
document.write(arr[i] + " " );
</script>
|
Output
18 63 80 25 32 43 80 93 80 25 93 -1 28 -1 -1
Time complexity: O(n2), As it uses BST. The worst-case will happen when array is sorted in ascending or descending order. The complexity can easily be reduced to O(nlogn) by using balanced trees like red-black trees.
Auxiliary Space: O(h), Here h is the height of the BST and the extra space is used in recursion call stack.
Another Approach:
We can use the Next Greater Element using stack algorithm to solve this problem in O(Nlog(N)) time and O(N) space.
Algorithm:
- First, we take an array of pairs namely temp, and store each element and its index in this array,i.e. temp[i] will be storing {arr[i],i}.
- Sort the array according to the array elements.
- Now get the next greater index for each and every index of the temp array in an array namely index by using Next Greater Element using stack.
- Now index[i] stores the index of the next least greater element of the element temp[i].first and if index[i] is -1, then it means that there is no least greater element of the element temp[i].second at its right side.
- Now take a result array where result[i] will be equal to a[indexes[temp[i].second]] if index[i] is not -1 otherwise result[i] will be equal to -1.
Below is the implementation of the above approach
C++
#include <bits/stdc++.h>
using namespace std;
vector< int > nextGreaterIndex(vector<pair< int , int > >& temp)
{
int n = temp.size();
vector< int > res(n, -1);
stack< int > stack;
for ( int i = 0; i < n; i++) {
if (stack.empty() || temp[i].second < stack.top())
stack.push(
temp[i].second);
else {
while (!stack.empty()
&& temp[i].second > stack.top()) {
res[stack.top()] = temp[i].second;
stack.pop();
}
stack.push(temp[i].second);
}
}
return res;
}
vector< int > replaceByLeastGreaterUsingStack( int arr[],
int n)
{
vector<pair< int , int > > temp;
for ( int i = 0; i < n; i++) {
temp.push_back({ arr[i], i });
}
sort(temp.begin(), temp.end(),
[]( const pair< int , int >& a,
const pair< int , int >& b) {
if (a.first == b.first)
return a.second > b.second;
return a.first < b.first;
});
vector< int > indexes = nextGreaterIndex(temp);
vector< int > res(n, -1);
for ( int i = 0; i < n; i++) {
if (indexes[temp[i].second] != -1)
res[temp[i].second]
= arr[indexes[temp[i].second]];
}
return res;
}
int main()
{
int arr[] = { 8, 58, 71, 18, 31, 32, 63, 92,
43, 3, 91, 93, 25, 80, 28 };
int n = sizeof (arr) / sizeof ( int );
auto res = replaceByLeastGreaterUsingStack(arr, n);
cout << "Least Greater elements on the right side are "
<< endl;
for ( int i : res)
cout << i << ' ' ;
cout << endl;
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Stack;
public class GFF {
static int [] nextGreaterIndex(ArrayList< int []> temp)
{
int n = temp.size();
int [] res = new int [n];
Arrays.fill(res, - 1 );
Stack<Integer> stack = new Stack<Integer>();
for ( int i = 0 ; i < n; i++) {
if (stack.empty()
|| temp.get(i)[ 1 ] < stack.peek())
stack.push(temp.get(
i)[ 1 ]);
else {
while (!stack.empty()
&& temp.get(i)[ 1 ] > stack.peek()) {
res[stack.peek()] = temp.get(i)[ 1 ];
stack.pop();
}
stack.push(temp.get(i)[ 1 ]);
}
}
return res;
}
static int [] replaceByLeastGreaterUsingStack( int arr[],
int n)
{
ArrayList< int []> temp = new ArrayList< int []>();
for ( int i = 0 ; i < n; i++) {
temp.add( new int [] { arr[i], i });
}
Collections.sort(temp, (a, b) -> {
if (a[ 0 ] == b[ 0 ])
return b[ 1 ] - a[ 1 ];
return a[ 0 ] - b[ 0 ];
});
int [] indexes = nextGreaterIndex(temp);
int [] res = new int [n];
Arrays.fill(res, - 1 );
for ( int i = 0 ; i < n; i++) {
if (indexes[temp.get(i)[ 1 ]] != - 1 )
res[temp.get(i)[ 1 ]]
= arr[indexes[temp.get(i)[ 1 ]]];
}
return res;
}
public static void main(String[] args)
{
int arr[] = { 8 , 58 , 71 , 18 , 31 , 32 , 63 , 92 ,
43 , 3 , 91 , 93 , 25 , 80 , 28 };
int n = arr.length;
int [] res = replaceByLeastGreaterUsingStack(arr, n);
System.out.println(
"Least Greater elements on the right side are " );
for ( int i : res)
System.out.print(i + " " );
System.out.println();
}
}
|
Python3
def nextGreaterIndex(temp):
n = len (temp)
res = [ - 1 for i in range (n)]
stack = []
for i in range (n):
if ( len (stack) = = 0 or temp[i][ 1 ] < stack[ - 1 ]):
stack.append(temp[i][ 1 ])
else :
while ( len (stack) > 0 and temp[i][ 1 ] > stack[ - 1 ]):
res[stack[ - 1 ]] = temp[i][ 1 ]
stack.pop()
stack.append(temp[i][ 1 ])
return res
def replaceByLeastGreaterUsingStack(arr, n):
temp = []
for i in range (n):
temp.append([arr[i], i])
temp.sort()
indexes = nextGreaterIndex(temp)
res = [ - 1 for i in range (n)]
for i in range (n):
if (indexes[temp[i][ 1 ]] ! = - 1 ):
res[temp[i][ 1 ]] = arr[indexes[temp[i][ 1 ]]]
return res
arr = [ 8 , 58 , 71 , 18 , 31 , 32 , 63 , 92 , 43 , 3 , 91 , 93 , 25 , 80 , 28 ]
n = len (arr)
res = replaceByLeastGreaterUsingStack(arr, n)
print ( "Least Greater elements on the right side are " )
for i in res:
print (i, end = ' ' )
print ()
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class GFG {
static int [] nextGreaterIndex(List< int []> temp)
{
int n = temp.Count();
int [] res = new int [n];
for ( int i = 0; i < n; i++) {
res[i] = -1;
}
Stack< int > stack = new Stack< int >();
for ( int i = 0; i < n; i++) {
if (stack.Count() == 0
|| temp[i][1] < stack.Peek()) {
stack.Push(temp[i][1]);
}
else {
while (stack.Count() != 0
&& temp[i][1] > stack.Peek()) {
res[stack.Peek()] = temp[i][1];
stack.Pop();
}
stack.Push(temp[i][1]);
}
}
return res;
}
static int [] replaceByLeastGreaterUsingStack( int [] arr,
int n)
{
List< int []> temp = new List< int []>();
for ( int i = 0; i < n; i++) {
temp.Add( new int [] { arr[i], i });
}
temp.Sort((a, b) = > {
if (a[0] == b[0])
return a[1] - b[1];
return a[0] - b[0];
});
int [] indexes = nextGreaterIndex(temp);
int [] res = new int [n];
for ( int i = 0; i < n; i++) {
res[i] = -1;
}
for ( int i = 0; i < n; i++) {
if (indexes[temp[i][1]] != -1)
res[temp[i][1]] = arr[indexes[temp[i][1]]];
}
return res;
}
public static void Main()
{
int [] arr
= new int [] { 8, 58, 71, 18, 31, 32, 63, 92,
43, 3, 91, 93, 25, 80, 28 };
int n = arr.Length;
int [] res = replaceByLeastGreaterUsingStack(arr, n);
Console.WriteLine(
"Least Greater elements on the right side are " );
foreach ( var i in res) Console.Write(i + " " );
Console.WriteLine();
}
}
|
Javascript
<script>
function mycmp(a,b){
if (a[0] == b[0])
return b[1] - a[1];
return a[0] - b[0];
}
function nextGreaterIndex(temp)
{
let n = temp.length;
let res = new Array(n).fill(-1);
let stack = [];
for (let i = 0; i < n; i++) {
if (stack.length == 0 || temp[i][1] < stack[stack.length-1])
stack.push(temp[i][1]);
else {
while (stack.length > 0 && temp[i][1] > stack[stack.length-1]) {
res[stack[stack.length-1]] = temp[i][1];
stack.pop();
}
stack.push(temp[i][1]);
}
}
return res;
}
function replaceByLeastGreaterUsingStack(arr,n)
{
let temp = [];
for (let i = 0; i < n; i++) {
temp.push([arr[i], i]);
}
temp.sort(mycmp);
let indexes = nextGreaterIndex(temp);
let res = new Array(n).fill(-1);
for (let i = 0; i < n; i++) {
if (indexes[temp[i][1]] != -1)
res[temp[i][1]]
= arr[indexes[temp[i][1]]];
}
return res;
}
let arr = [ 8, 58, 71, 18, 31, 32, 63, 92,
43, 3, 91, 93, 25, 80, 28 ];
let n = arr.length;
let res = replaceByLeastGreaterUsingStack(arr, n);
document.write( "Least Greater elements on the right side are " , "</br>" );
for (let i of res)
document.write(i,' ');
document.write( "</br>" );
</script>
|
Output
Least Greater elements on the right side are
18 63 80 25 32 43 80 93 80 25 93 -1 28 -1 -1
Time Complexity: O(N log N)
Space Complexity: O(N)
Another approach with set
A different way to think about the problem is listing our requirements and then thinking over it to find a solution. If we traverse the array from backwards, we need a data structure(ds) to support:
- Insert an element into our ds in sorted order (so at any point of time the elements in our ds are sorted)
- Finding the upper bound of the current element (upper bound will give just greater element from our ds if present)
Carefully observing at our requirements, a set is what comes in mind.
Why not multiset? Well we can use a multiset but there is no need to store an element more than once.
Let’s code our approach
Time and space complexity: We insert each element in our set and find upper bound for each element using a loop so its time complexity is O(n*log(n)). We are storing each element in our set so space complexity is O(n)
C++
#include <iostream>
#include <set>
#include <vector>
using namespace std;
void solve(vector< int >& arr)
{
set< int > s;
for ( int i = arr.size() - 1; i >= 0;
i--) {
s.insert(arr[i]);
auto it
= s.upper_bound(arr[i]);
if (it == s.end())
arr[i] = -1;
else
arr[i] = *it;
}
}
void printArray(vector< int >& arr)
{
for ( int i : arr)
cout << i << " " ;
cout << "\n" ;
}
int main()
{
vector< int > arr = { 8, 58, 71, 18, 31, 32, 63, 92,
43, 3, 91, 93, 25, 80, 28 };
printArray(arr);
solve(arr);
printArray(arr);
return 0;
}
|
Java
import java.util.*;
public class Main {
public static void main(String[] args)
{
int [] arr = { 8 , 58 , 71 , 18 , 31 , 32 , 63 , 92 ,
43 , 3 , 91 , 93 , 25 , 80 , 28 };
printArray(arr);
solve(arr);
printArray(arr);
}
public static void solve( int [] arr)
{
TreeSet<Integer> s = new TreeSet<>();
for ( int i = arr.length - 1 ; i >= 0 ;
i--) {
s.add(arr[i]);
Integer it
= s.higher(arr[i]);
if (it == null )
arr[i] = - 1 ;
else
arr[i] = it;
}
}
public static void printArray( int [] arr)
{
for ( int i : arr)
System.out.print(i + " " );
System.out.println();
}
}
|
Python3
from typing import List
from bisect import bisect_right
def solve(arr: List [ int ]) - > List [ int ]:
s = set ()
for i in range ( len (arr) - 1 , - 1 , - 1 ):
s.add(arr[i])
upper_bound = bisect_right( sorted (s), arr[i])
if upper_bound = = len (s):
arr[i] = - 1
else :
arr[i] = sorted (s)[upper_bound]
return arr
def print_array(arr: List [ int ]):
print ( * arr)
if __name__ = = "__main__" :
arr = [ 8 , 58 , 71 , 18 , 31 , 32 , 63 , 92 , 43 , 3 , 91 , 93 , 25 , 80 , 28 ]
print_array(arr)
solve(arr)
print_array(arr)
|
C#
using System;
using System.Collections.Generic;
public class GFG {
public static void Main(String[] args)
{
int [] arr = { 8, 58, 71, 18, 31, 32, 63, 92,
43, 3, 91, 93, 25, 80, 28 };
GFG.printArray(arr);
GFG.solve(arr);
GFG.printArray(arr);
}
public static void solve( int [] arr)
{
var s = new SortedSet< int >();
for ( int i = arr.Length - 1; i >= 0; i--) {
s.Add(arr[i]);
var it = -1;
foreach ( int j in s)
{
if (j > arr[i]) {
it = j;
break ;
}
}
if (it == -1) {
arr[i] = -1;
}
else {
arr[i] = it;
}
}
}
public static void printArray( int [] arr)
{
foreach ( int i in arr)
{
Console.Write(i.ToString() + " " );
}
Console.WriteLine();
}
}
|
Javascript
function solve(arr) {
let s = new Set();
for (let i = arr.length - 1; i >= 0; i--) {
s.add(arr[i]);
let it = -1;
for (let j of s) {
if (j > arr[i]) {
it = j;
break ;
}
}
if (it == -1) {
arr[i] = -1;
} else {
arr[i] = it;
}
}
}
function printArray(arr) {
for (let i of arr) {
console.log(i + " " );
}
console.log();
}
let arr = [8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28];
printArray(arr);
solve(arr);
printArray(arr);
|
Output
8 58 71 18 31 32 63 92 43 3 91 93 25 80 28
18 63 80 25 32 43 80 93 80 25 93 -1 28 -1 -1
Time complexity -The time complexity of the given program is O(n*logn), where n is the size of the input array.
The reason for this is that the program uses a set to store the unique elements of the input array, and for each element in the array, it performs a single insertion operation and a single upper_bound operation on the set. Both of these operations have a time complexity of O(logn) in the average case, and since they are performed n times, the overall time complexity is O(n*logn).
Space complexity-The space complexity of the program is also O(n), as it uses a set to store the unique elements of the input array. In the worst case, where all elements of the array are unique, the set will have to store n elements, leading to a space complexity of O(n).
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Approach#4:using 2 loops
Algorithm
1. Initialize a new list with all -1 values to represent the elements for which there is no greater element on its right.
2. For each element in the input list:
a. Initialize a variable “min_greater” with a value of infinity.
b. Use another loop to find the minimum element in the input list that is greater than the current element.
c. If such an element is found, update the value of “min_greater” to be the minimum element found in step b.
d. If the value of “min_greater” is still infinity, it means there is no greater element on the right of the current element, so do nothing.
e. Otherwise, update the corresponding element in the new list with the value of “min_greater”.
5. Return the new list.
C++
#include <iostream>
#include <vector>
#include <limits>
using namespace std;
vector< int > replace_with_least_greater( const vector< int >& arr) {
int n = arr.size();
vector< int > new_arr(n, -1);
for ( int i = 0; i < n; i++) {
int min_greater = numeric_limits< int >::max();
for ( int j = i + 1; j < n; j++) {
if (arr[j] > arr[i] && arr[j] < min_greater) {
min_greater = arr[j];
}
}
if (min_greater != numeric_limits< int >::max()) {
new_arr[i] = min_greater;
}
}
return new_arr;
}
int main() {
vector< int > arr = {8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28};
vector< int > result = replace_with_least_greater(arr);
for ( int val : result) {
cout << val << " " ;
}
cout << endl;
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.List;
public class Main {
public static List<Integer> replaceWithLeastGreater(List<Integer> arr) {
int n = arr.size();
List<Integer> newArr = new ArrayList<>(n);
for ( int i = 0 ; i < n; i++) {
int minGreater = Integer.MAX_VALUE;
for ( int j = i + 1 ; j < n; j++) {
if (arr.get(j) > arr.get(i) && arr.get(j) < minGreater) {
minGreater = arr.get(j);
}
}
if (minGreater != Integer.MAX_VALUE) {
newArr.add(minGreater);
} else {
newArr.add(- 1 );
}
}
return newArr;
}
public static void main(String[] args) {
List<Integer> arr = List.of( 8 , 58 , 71 , 18 , 31 , 32 , 63 , 92 , 43 , 3 , 91 , 93 , 25 , 80 , 28 );
List<Integer> result = replaceWithLeastGreater(arr);
for ( int val : result) {
System.out.print(val + " " );
}
System.out.println();
}
}
|
Python3
def replace_with_least_greater(arr):
n = len (arr)
new_arr = [ - 1 ] * n
for i in range (n):
min_greater = float ( 'inf' )
for j in range (i + 1 , n):
if arr[j] > arr[i] and arr[j] < min_greater:
min_greater = arr[j]
if min_greater ! = float ( 'inf' ):
new_arr[i] = min_greater
return new_arr
arr = [ 8 , 58 , 71 , 18 , 31 , 32 , 63 , 92 , 43 , 3 , 91 , 93 , 25 , 80 , 28 ]
print (replace_with_least_greater(arr))
|
C#
using System;
using System.Collections.Generic;
class Program
{
static List< int > ReplaceWithLeastGreater(List< int > arr)
{
int n = arr.Count;
List< int > newArr = new List< int >(n);
for ( int i = 0; i < n; i++)
{
int minGreater = int .MaxValue;
for ( int j = i + 1; j < n; j++)
{
if (arr[j] > arr[i] && arr[j] < minGreater)
{
minGreater = arr[j];
}
}
if (minGreater != int .MaxValue)
{
newArr.Add(minGreater);
}
else
{
newArr.Add(-1);
}
}
return newArr;
}
static void Main()
{
List< int > arr = new List< int > { 8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28 };
List< int > result = ReplaceWithLeastGreater(arr);
foreach ( int val in result)
{
Console.Write(val + " " );
}
Console.WriteLine();
}
}
|
Javascript
function replaceWithLeastGreater(arr) {
const n = arr.length;
const newArr = [];
for (let i = 0; i < n; i++) {
let minGreater = Number.MAX_VALUE;
for (let j = i + 1; j < n; j++) {
if (arr[j] > arr[i] && arr[j] < minGreater) {
minGreater = arr[j];
}
}
if (minGreater !== Number.MAX_VALUE) {
newArr.push(minGreater);
} else {
newArr.push(-1);
}
}
return newArr;
}
const arr = [8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28];
const result = replaceWithLeastGreater(arr);
for (const val of result) {
process.stdout.write(val + ' ' );
}
process.stdout.write( '\n' );
|
Output
[18, 63, 80, 25, 32, 43, 80, 93, 80, 25, 93, -1, 28, -1, -1]
Time Complexity: O(n^2), where n is the length of the input array. This is because we use two nested loops to iterate over all pairs of elements in the input array.
Space Complexity: O(n), where n is the length of the input array. This is because we create a new list of the same length as the input array to store the output.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
26 Oct, 2023
Like Article
Save Article