
- 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 Greater Element III in C++
Suppose we have a positive 32-bit integer n, we need to find the smallest 32-bit integer which has exactly the same digits existing in the integer n and is greater in value than n. If we have no such positive 32-bit integer number, then return -1.
So if the number is 213, then the result will be 231.
To solve this, we will follow these steps −
- s := n as string, sz := size of s, ok := false
- for i in range sz – 2 to 0
- if s[i] < s[i + 1], then ok := true and break the loop
- if of is false, then return – 1
- smallest := i, curr := i + 1
- for j in range i + 1 to sz – 1
- id s[j] > s[smallest] and s[j] <= s[curr], then curr := j
- exchange s[smallest] with s[curr]
- aux := substring of s from index 0 to smallest
- reverse aux
- ret := substring of s from index 0 to smallest + aux
- return -1 if ret is > 32-bit +ve integer range, otherwise ret
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: int nextGreaterElement(int n) { string s = to_string(n); int sz = s.size(); int i; bool ok = false; for(i = sz - 2; i >= 0; i--){ if(s[i] < s[i + 1]) { ok = true; break; } } if(!ok) return -1; int smallest = i; int curr = i + 1; for(int j = i + 1; j < sz; j++){ if(s[j] > s[smallest] && s[j] <= s[curr]){ curr = j; } } swap(s[smallest], s[curr]); string aux = s.substr(smallest + 1); reverse(aux.begin(), aux.end()); string ret = s.substr(0, smallest + 1) + aux; return stol(ret) > INT_MAX ? -1 : stol(ret); } }; main(){ Solution ob; cout << (ob.nextGreaterElement(213)); }
Input
213
Output
231
- Related Articles
- Next Greater Element in C++
- Next Greater Element II in C++
- Next Greater Element in Circular Array in JavaScript
- Finding distance to next greater element in JavaScript
- Next greater element in same order as input in C++
- Elements greater than the previous and next element in an Array in C++
- Find next Smaller of next Greater in an array in C++
- Interesting Python Implementation for Next Greater Elements
- Next Smaller Element in C++
- Finding next greater node for each node in JavaScript
- jQuery element + next Selector
- Previous greater element in C++
- Remove next element using jQuery?
- Find next sibling element in Selenium, Python?
- Find next greater number with same set of digits in C++

Advertisements