Full Solution In JAVA ... Cheak This Out -->


#1

public class Solution {
public String solve(String A) {

    if( A.length() == 1 ) return "-1" ;
    char [] ch = A.toCharArray() ;
     int n = ch.length ;

    if( dec (ch))
    {
        return "-1"  ;
    }
    
   
    int i = n-2 ;
    while( i>= 0 && ch[i] >= ch[i+1] )
    {
        i-- ;
    }
    
    if( i>= 0)
    {
        int j = n-1 ;
        
        while( j >= 0 &&  ch[j] <= ch[i]  ) 
        {
            j-- ;
        }
    
        swap( ch , i , j ) ;
    }
    
    reverse( ch , i+1 , n-1 ) ;
    
  
    
    String s = new String( ch ) ;
  
    return s ;
    
}

void   swap ( char[] ch , int i , int j )
{
    char temp = ch[i] ;
    ch[i] =  ch[j] ;
    ch[j] = temp ;
}

void reverse( char ch[]  , int lo , int hi )
{
    while( lo < hi )
    {
         char temp = ch[lo] ;
         ch[lo] =  ch[hi] ;
        ch[hi] = temp ;
    
    lo++ ;
    hi-- ;
    }
}

public boolean  dec ( char ch[] )
{
     int i = 0 ;
     while( i <= ch.length -2 )
     {
        if( ch[i] >= ch[i+1] )
           {
              i++ ;
           }
           
           else{
               
               return false ; 
           }
   
     }
      
      return true ;  
      
}

}


#2
if( i>= 0)
{
    int j = n-1 ;
    
    while( j >= 0 &&  ch[j] <= ch[i]  ) 
    {
        j-- ;
    }

    swap( ch , i , j ) ;
}

can’t we use binary search instead of using while( j >= 0 && ch[j] <= ch[i] ) { j-- ; }

linear search over here ?