Skip to main content

Next Greater Number Set Digits

Task: Given a number N, Find the smallest number with same digits of n and that greater than n.

Example:
Input:
1
143
Output:
314

Here is the Code:
Program in C++:

  1. #include<iostream>
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4. string nextGreaterNumber(string s)
  5. {
  6.     for(int i=1;i<s.length();i++)
  7.     {
  8.         if(s[i-1]>=s[i])
  9.         {
  10.             if(i+1==s.length()) return "not possible";
  11.         }
  12.         else
  13.         {
  14.             break;
  15.         }
  16.     }
  17.     stack<int> st;
  18.     for(int i=s.length()-1;i>=0;i--)
  19.     {
  20.         if(s[i-1]>=s[i])
  21.         {
  22.             st.push(i);
  23.         }
  24.         else
  25.         {
  26.             st.push(i);
  27.             int t;
  28.             while(!st.empty()&&s[i-1]<s[st.top()])
  29.             {
  30.                 t=st.top();
  31.                 st.pop();
  32.             }
  33.             swap(s[i-1],s[t]);
  34.             reverse(s.begin()+i,s.end());
  35.             return s;
  36.         }
  37.     }
  38. }
  39. int main()
  40.  {
  41. int t;
  42. scanf("%d\n",&t);
  43. while(t--)
  44. {
  45.     string s;
  46.     cin>>s;
  47.     cout<<nextGreaterNumber(s)<<endl;
  48. }
  49. return 0;
  50. }

Here is the Video: