TLE in JNEXT problem in SPOJ Problem Statement: JNEXT


  DevG was challanged to find the just next greater number which can be formed using digits of a given number. Now DevG needs your help to find that just next greater number and win the challenge.
  
  Input
  
  The first line have t number of test cases (1 &lt;= t &lt;= 100). In next 2*t lines for each test case first there is number n (1 &lt;= n &lt;= 1000000) which denotes the number of digits in given number and next line contains n digits of given number separated by space.
  
  Output
  
  Print the just next greater number if possible else print -1 in one line for each test case.
  
  Note : There will be no test case which contains zero in starting digits of any given number.
  
  Example
  
  Input:

2
5
1 5 4 8 3
10
1 4 7 4 5 8 4 1 2 6

  
  Output:

15834
1474584162



My Solution is

public static void main(String[] argh) throws Exception{
        Reader br = new Reader();
        int t= br.nextInt();

        for(int aa=0; aa&lt;t; aa++){
            int n= br.nextInt();
            int[] arr= new int[n];
            int breakPoint= -1;
            int mI= -1;

            for(int qq=0; qq&lt;n; qq++){
                arr[qq]= br.nextInt();
                if(qq !=0 &amp;&amp; arr[qq] &gt; arr[qq-1]){
                    breakPoint= qq-1;
                }
                if(breakPoint != -1){
                    if(arr[breakPoint] &lt; arr[qq]){
                        mI= qq;
                    }
                }
            }
            if(breakPoint == -1 || n == 1){
                System.out.println(-1);
                continue;
            }

            // swap
            arr[breakPoint]= arr[breakPoint] + arr[mI];
            arr[mI]= arr[breakPoint] - arr[mI];
            arr[breakPoint]= arr[breakPoint] - arr[mI];
            breakPoint++;

            for(int ii=0; ii&lt;breakPoint; ii++){
                System.out.print(arr[ii]);
            }
            for(int ii=n-1; ii&gt;=breakPoint; ii--){
                System.out.print(arr[ii]);
            }
            System.out.println("");
        }
    }


My solution is having O(N) time complexity but still I am getting TLE.
Can anyone point out issue?
int[] arr


You can probably create it only once, with maximum possible size, outside for for loop.

System.out.print(arr[ii]);


You need to use StringBuilder and output only whole string in single println call. Multiple System.out.print calls are what makes it slow.