int nextGreaterElement(int n) {
auto digits = to_string(n);
next_permutation(begin(digits), end(digits));
auto res = stoll(digits);
return (res > INT_MAX  res <= n) ? 1 : res;
}
C++ 4 lines (next_permutation)

@justin40 I think that the point of this problem is to recognize and apply the next premutation. Problem 31, in contrary, specifically asks to implementation next premutation.
As an interviewer, I would add points if a candidate is familiar with next_permutation. I may ask to implement it, but probably I would just move on to more interesting problems.


With next_permutation implemented myself
class Solution { public: int nextGreaterElement(int n) { string nums = to_string(n); if(!nextPermutation(nums)) return 1; long long result=stoll(nums); return (result>INT_MAX  result<=n)? 1:result; } private: bool nextPermutation(string& nums) { if(nums.empty()) return false; int i=nums.size()1; while(i>=1 && nums[i]<=nums[i1]) i; if(i==0) return false; // no next permutation, i.e. already largest int j=nums.size()1; while(nums[j]<=nums[i1]) j; swap(nums[i1],nums[j]); reverse(nums.begin()+i,nums.end()); return true; } };