Sorting the list of palindromes
Collections . sort ( palindromes ) ; int l = 0 , r = palindromes . size ( ) - 1 ; while ( l < r ) { if ( palindromes . get ( l ) + palindromes . get ( r ) == N ) { return 2 ; } else if ( palindromes . get ( l ) + palindromes . get ( r ) < N ) { ++ l ; } else { -- r ; } }