The below code snippet matches ONLY A FEW test cases
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class substring { public static String getSmallestAndLargest(String s, int k) { String smallest = ""; String sub=""; String largest = ""; for(int i=0;i<=(s.length()-k);i++) { sub=s.substring(i,i+k); if(i==0) smallest=sub; if(sub.compareToIgnoreCase(largest) > 0) largest = sub ; if(sub.compareToIgnoreCase(smallest)<0) smallest=sub; } return smallest + "\n" + largest; } public static void main(String[] args) { Scanner scan = new Scanner(System.in); String s = scan.next(); int k = scan.nextInt(); scan.close(); System.out.println(getSmallestAndLargest(s, k)); } }