
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Next Smaller Element in C++
The next smaller element is the element that is the first smaller element after it. Let's see an example.
arr = [1, 2, 3, 5, 4]
The next smaller element for 5 is 4 and the next smaller element for elements 1, 2, 3 is -1 as there is no smaller element after them.
Algorithm
Initialise the array with random numbers
Initialise a stack.
Add first element to the stack.
Iterate through the element of the array.
If the stack is empty, add the current element to the stack.
While the current element is smaller than the top element of the stack.
Print the top element with the next smaller element as current element.
Pop the top element.
Add the element to the stack.
While stack is not empty.
Print the elements with next smaller element as -1.
Implementation
Following is the implementation of the above algorithm in C++
#include <bits/stdc++.h> using namespace std; void nextSmallerElements(int arr[], int n) { stack<int> s; s.push(arr[0]); for (int i = 1; i < n; i++) { if (s.empty()) { s.push(arr[i]); continue; } while (!s.empty() && s.top() > arr[i]) { cout << s.top() << " -> " << arr[i] << endl; s.pop(); } s.push(arr[i]); } while (!s.empty()) { cout << s.top() << " -> " << -1 << endl; s.pop(); } } int main() { int arr[] = { 5, 4, 3, 2, 1 }; int n = 5; nextSmallerElements(arr, n); return 0; }
Output
If you run the above code, then you will get the following result.
1 -> 2 2 -> 3 3 -> 4 4 -> 5 5 -> -1
- Related Articles
- Find next Smaller of next Greater in an array in C++
- Next Greater Element in C++
- Next Greater Element II in C++
- Next Greater Element III in C++
- Next Larger element in n-ary tree in C++
- Next greater element in same order as input in C++
- Find closest smaller value for every element in array in C++
- jQuery element + next Selector
- Find next sibling element in Selenium, Python?
- Remove next element using jQuery?
- Elements greater than the previous and next element in an Array in C++
- Next Greater Element in Circular Array in JavaScript
- 3Sum Smaller in C++
- Finding distance to next greater element in JavaScript
- Program to find maximum difference of any number and its next smaller number in Python
