Leetcode 556 Solution

This article provides solution to leetcode question 556 (next-greater-element-iii)

https://leetcode.com/problems/next-greater-element-iii

Solution

class Solution {
public:
    int nextGreaterElement(int n) {
        string s = to_string(n);

        int i = s.size() - 1;
        for (; i >= 1; i--)
        {
            if (s[i] > s[i - 1])
                break;
        }

        if (i == 0)
            return -1;

        int j = i;
        for (; j < s.size(); j++)
        {
            if (s[j] <= s[i - 1])
                break;
        }

        swap(s[j - 1], s[i - 1]);
        sort(&s[i], &s[s.size()]);

        int64_t val = atoll(s.c_str());

        return val > INT_MAX ? -1 : val;
    }
};