Next Smaller Element Python
- Get link
- X
- Other Apps
PROGRAM TO FIND THE NEXT SMALLER ELEMENT FOR EVERY ELEMENT
using
System;
using
System.Collections.Generic;
public
class
GFG
{
/* prints element and NSE pair for all
elements of arr[] of size n */
public
static
void
printNSE(
int
[]arr,
int
n)
{
Stack<
int
> s =
new
Stack<
int
>();
/* push the first element to stack */
s.Push(arr[0]);
// iterate for rest of the elements
for
(
int
i = 1; i < n; i++) {
if
(s.Count==0) {
s.Push(arr[i]);
continue
;
}
/* if stack is not empty, then
pop an element from stack.
If the popped element is greater
than next, then
a) print the pair
b) keep popping while elements are
greater and stack is not empty */
while
(s.Count !=0 && s.Peek() > arr[i]) {
Console.WriteLine(s.Peek() +
" --> "
+ arr[i]);
s.Pop();
}
/* push next to stack so that we can find
next smaller for it */
s.Push(arr[i]);
}
/* After iterating over the loop, the remaining
elements in stack do not have the next smaller
element, so print -1 for them */
while
(s.Count!=0) {
Console.WriteLine(s.Peek() +
" --> "
+
"-1"
);
s.Pop();
}
}
/* Driver program to test above functions */
public
static
void
Main () {
int
[]arr = { 11, 13, 21, 3};
int
n = arr.Length;
printNSE(arr, n);
}
}
OUTPUT:
11 -- 3 13 -- 3 21 -- 3 3 -- -1
- Get link
- X
- Other Apps
Comments
Post a Comment