Next Integer Permutation - Amazon Top Interview Questions


Problem Statement :


Given an integer n, return the next bigger permutation of its digits.

If n is already in its biggest permutation, rotate to the smallest permutation.

Constraints

n < 2 ** 31

Example 1

Input

n = 527

Output

572

Example 2

Input

n = 321

Output

123

Explanation

321 is already the biggest permutation so it rotates to the smallest.

Example 3

Input

n = 20

Output

2



Solution :



title-img




                        Solution in C++ :

int solve(int n) {
    string s = to_string(n);
    int i = 0, j = 0;
    for (i = s.size() - 2; i >= 0; i--) {
        if (s[i] < s[i + 1]) break;
    }
    if (i < 0) {
        sort(s.begin(), s.end());
        return stoi(s);
    }
    for (j = s.size() - 1; j >= 0; j--) {
        if (s[j] > s[i]) break;
    }
    swap(s[i], s[j]);
    sort(s.begin() + i + 1, s.end());
    return stoi(s);
}
                    


                        Solution in Java :

import java.util.*;

class Solution {
    public int solve(int n) {
        ArrayList<Integer> ar = new ArrayList<>();
        int a = n;
        while (a > 0) {
            ar.add(a % 10);
            a = a / 10;
        }
        int arr[] = new int[ar.size()];
        int j = ar.size() - 1;
        for (int x : ar) {
            arr[j--] = x;
        }
        int mark = arr.length - 2;
        while (mark >= 0 && arr[mark + 1] <= arr[mark]) {
            mark--;
        }
        if (mark == -1) {
            reverse(arr, 0);
            return number(arr);
        }
        if (mark >= 0) {
            int k = arr.length - 1;
            while (k >= mark && arr[k] <= arr[mark]) {
                k--;
            }
            swap(arr, mark, k);
        }
        reverse(arr, mark + 1);
        return number(arr);
    }

    private int number(int nums[]) {
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum = sum * 10 + nums[i];
        }
        return sum;
    }
    private void reverse(int nums[], int start) {
        int i = start, j = nums.length - 1;
        while (i < j) {
            swap(nums, i, j);
            i++;
            j--;
        }
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def solve(self, num):
        # convert the number to a list of each digit
        A = list(map(int, str(num)))

        i = len(A) - 1

        # find the position of the rightmost element where we encounter
        # increasing comparison (A[i-1] < A[i])
        # for 527, this will be 27 and i = 2, A[i] = 7
        while i > 0 and A[i - 1] >= A[i]:
            i -= 1

        if i == 0:
            # if i == 0, it means the whole list was sorted in reverse order
            # in other words, it's already the highest permutation
            # so we just reverse it to get the smallest permutation
            A.reverse()
        else:
            j = len(A) - 1
            k = i - 1  # for 527: k = 1, A[k] = 2

            # starting from the position i-1, we go left to find the number
            # that's larger than the that number
            while A[j] <= A[k]:
                j -= 1
            A[j], A[k] = A[k], A[j]  # for 527, we swap 2 and 7 since j=2

            # we reverse the remaining part of the array
            # after the index k + 1, since it should be reset to
            # the smallest permutation
            left, right = k + 1, len(A) - 1
            while left < right:
                A[left], A[right] = A[right], A[left]
                left, right = left + 1, right - 1

        return int("".join(map(str, A)))
                    


View More Similar Problems

Tree: Huffman Decoding

Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only t

View Solution →

Binary Search Tree : Lowest Common Ancestor

You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b

View Solution →

Swap Nodes [Algo]

A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from

View Solution →

Kitty's Calculations on a Tree

Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a

View Solution →

Is This a Binary Search Tree?

For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a

View Solution →

Square-Ten Tree

The square-ten tree decomposition of an array is defined as follows: The lowest () level of the square-ten tree consists of single array elements in their natural order. The level (starting from ) of the square-ten tree consists of subsequent array subsegments of length in their natural order. Thus, the level contains subsegments of length , the level contains subsegments of length , the

View Solution →