# HackerRank Java Substring Comparisons problem solution

In this HackerRank java substring comparisons problem in the java programming language you have Given a string, s, and an integer, k, complete the function so that it finds the lexicographically smallest and largest substrings of length k.

## HackerRank java substring comparisons problem solution.

```import java.util.Scanner;

public class Solution {

public static String getSmallestAndLargest(String s, int k) {
String smallest = "";
String largest = "";

java.util.List<String> a = new java.util.ArrayList<>();

for(int i=0;i<s.length()-k+1;i++){
}
java.util.Collections.sort(a);
smallest = a.get(0);
largest = a.get(a.size()-1);
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));
}
}```

## Second solution

```import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String line = scanner.nextLine();
int k = scanner.nextInt();
String minSubstring = line.substring(0,k);
String maxSubstring = line.substring(0,k);
for (int i = 1; i < line.length()-k+1; i++) {
String sub = line.substring(i,i+k);
if (sub.compareTo(minSubstring) < 0) {
minSubstring = sub;
}
if (sub.compareTo(maxSubstring) > 0) {
maxSubstring = sub;
}
}
System.out.println(minSubstring);
System.out.println(maxSubstring);
}
}```