

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Previous greater element in C++
In this problem, we are given an array. Our task is to return the greatest element that precedes the current element in the array otherwise print -1.
Let’s take an example to understand the problem
Input: {6, 2, 7, 1, 5, 3} Output: -1, 6, -1, 7, 7, 7
To solve this problem, an easy and obvious solution will be using nested loops that will check greater element in the preceding part of the array.
Program to show the implementation of our solution
Example
#include <iostream> using namespace std; void preceddingGreatestElement(int arr[], int n){ cout << "-1\t"; int i, j; for (i = 1; i < n; i++) { for (j = i-1; j >= 0; j--) { if (arr[i]<arr[j]) { cout<<arr[j]<< "\t"; break; } } if (j == -1) cout << "-1\t"; } } int main() { int arr[] = { 6, 2, 7, 1, 12, 5 }; int n = sizeof(arr) / sizeof(arr[0]); preceddingGreatestElement(arr, n); return 0; }
Output
-1 6 -1 7 -1 12
A more effective solution to solve our problem is by using the stack data structure. And maintaining the preceding larger number at the top of the stack.
Program to show the implementation of this solution
Example
#include <bits/stdc++.h> using namespace std; void preceddingGreatestElement(int arr[], int n) { stack<int> elements; elements.push(arr[0]); cout << "-1\t"; for (int i = 1; i < n; i++) { while (elements.empty() == false && elements.top() < arr[i]) elements.pop(); if(elements.empty()) cout<<"-1\t"; else cout<<elements.top()<<"\t"; elements.push(arr[i]); } } int main() { int arr[] = { 6, 2, 7, 1, 12, 5 }; int n = sizeof(arr) / sizeof(arr[0]); preceddingGreatestElement(arr, n); return 0; }
Output
-1 6 -1 7 -1 12
- Related Questions & Answers
- Elements greater than the previous and next element in an Array in C++
- Python – Sort Matrix by Number of elements greater than its previous element
- Rearrange an array such that every odd indexed element is greater than its previous in C++
- Next Greater Element in C++
- C++ Return Previous Element in an Expanding Matrix
- Next Greater Element II in C++
- Next Greater Element III in C++
- Next Greater Element in Circular Array in JavaScript
- Find smallest element greater than K in Python
- Finding distance to next greater element in JavaScript
- How to add the previous element to current jQuery selection?
- Finding element greater than its adjacent elements in JavaScript
- Next greater element in same order as input in C++
- How to replace blanks in a vector with the previous element in R?
- Find closest greater value for every element in array in C++
Advertisements