Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
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
Advertisements