• + 13 comments

    My logic is: To find the next bigger string, we should start from the end of string, and find the first character that can be exchanged with something bigger on its right. Swap those chars. So, this new string has everything same with original string till the left of this exchange position. Just sort everything right of this position and we got the next possible bigger string.

        for (i = 0; i < t; i++)
        {
                string w;
                cin >> w;
    
                int n = w.length();
                int j, k;
                for (j = n - 2; j >= 0; j--)
                {
                        for (k = n - 1; k > j && w[k] <= w[j]; k--)
                                ;
                        if (k == j)
                                continue;
                        char tmp = w[k];
                        w[k] = w[j];
                        w[j] = tmp;
                        sort(w.begin() + j + 1, w.end());
                        break;
                }
                if (j < 0)
                        cout << "no answer" << endl;
                else
                        cout << w << endl;
        }