Partition the digits of an integer such that it satisfies a given condition | Java implementation of the approach ; Function to generate sequence from the given String ; Initialize vector to store sequence ; First add all the digits of group A from left to right ; Then add all the digits of group B from left to right ; Return the sequence ; Function that returns true if the sequence is non - decreasing ; Initialize result ; Function to partition the digits of an integer such that it satisfies the given conditions ; Convert the integer to String ; Length of the String ; Array to store the digits ; Storing the digits of X in array ; Initialize the result ; Loop through the digits ; Put into group A if digit less than D ; Put into group B if digit greater than D ; Put into group C if digit equal to D ; Loop through the digits to decide for group C digits ; Set flag equal to true if group B digit present ; If flag is true put in group A or else put in B ; Generate the sequence from partition ; Check if the sequence is non decreasing ; Return - 1 if no such partition is possible ; Driver code
import java . util . * ; class GFG { static Vector < Integer > makeSeq ( String s , int a [ ] ) { Vector < Integer > seq = new Vector < Integer > ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) if ( s . charAt ( i ) == ' A ' ) seq . add ( a [ i ] ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) if ( s . charAt ( i ) == ' B ' ) seq . add ( a [ i ] ) ; return seq ; } static boolean checkSeq ( Vector < Integer > v ) { boolean check = true ; for ( int i = 1 ; i < v . size ( ) ; i ++ ) if ( v . get ( i ) < v . get ( i - 1 ) ) check = false ; return check ; } static String digitPartition ( int X ) { String num = String . valueOf ( X ) ; int l = num . length ( ) ; int [ ] a = new int [ l ] ; for ( int i = 0 ; i < l ; i ++ ) a [ i ] = ( num . charAt ( i ) - '0' ) ; for ( int D = 0 ; D < 10 ; D ++ ) { String res = " " ; for ( int i = 0 ; i < l ; i ++ ) { if ( a [ i ] < D ) res += ' A ' ; else if ( a [ i ] > D ) res += ' B ' ; else res += ' C ' ; } boolean flag = false ; for ( int i = 0 ; i < l ; i ++ ) { if ( res . charAt ( i ) == ' B ' ) flag = true ; if ( res . charAt ( i ) == ' C ' ) res = res . substring ( 0 , i ) + ( flag ? ' A ' : ' B ' ) + res . substring ( i + 1 ) ; } Vector < Integer > seq = makeSeq ( res , a ) ; if ( checkSeq ( seq ) ) return res ; } return " - 1" ; } public static void main ( String [ ] args ) { int X = 777147777 ; System . out . print ( digitPartition ( X ) ) ; } }