Given an integer X, the task is to partition its digit into two groups either A or B such that the sequence of digits is non decreasing when all the digits of group A are arranged followed by all the digits of group B from left to right as they appear in X. Print -1 if no such partition is possible or else return a string S of the same length as X where S[i] is either A or B.
Input: X = 5164
The digits in group A are 1 and 4 and in group B are 5 and 6. This partition satisfies the condition as when all the digits of A are written and then all the digits of B are written as they appear in X from left to right, the sequence is non-decreasing, i.e., 1456.
Input: X = 654
No such partition is possible that may result in non-decreasing sequence. For example, if we consider BBA and write the sequence, it turns out 465. Similarly for BAA, it is 546. and for AAA it is 654.
- Let us assume a digit D so that all digits less than D goes to group A and all the digits greater than D goes to group B.
- For the digits equal to D, it will go to group A only if any digit of group B is present before it otherwise it will go to group B.
- After such partition, check if it forms a non decreasing sequence. Otherwise try for some different D.
- The value of D ranges from 0 to 9.
Below is the implementation of the above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Subarray permutation that satisfies the given condition
- Smallest index in the given array that satisfies the given condition
- Maximum size of sub-array that satisfies the given condition
- Find the lexicographically smallest string which satisfies the given condition
- Find permutation of first N natural numbers that satisfies the given condition
- Find an integer in the given range that satisfies the given conditions
- Find the maximum sum (a+b) for a given input integer N satisfying the given condition
- Count even and odd digits in an Integer
- Print first k digits of 1/n where n is a positive integer
- Reverse digits of an integer with overflow handled
- Program to count digits in an integer (4 Different Methods)
- Minimum integer that can be obtained by swapping adjacent digits of different parity
- Minimum decrements to make integer A divisible by integer B
- Generate an array of size K which satisfies the given conditions
- Find an array of size N that satisfies the given conditions
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.