Java Substring Comparisons – Hacker Rank Solution

Java Substring Comparisons - Hacker Rank Solution
Java Substring Comparisons – Hacker Rank Solution


We define the following terms:

  • Lexicographical Order, also known as alphabetic or dictionary order, orders characters as follows; A<B<…….. Y<Z<… a<b<… y<z
    For example, ball < catdog < dormHappy < happyZoo < ball.
  • substring of a string is a contiguous block of characters in the string. For example, the substrings of abc are abcabbc, and abc.

Given a string,8, and an integer,k, complete the function so that it finds the lexicographically smallest and largest substrings of length k.

Function Description

Complete the getSmallestAndLargest function in the editor below.

getSmallestAndLargest has the following parameters:

  • string s: a string
  • int k: the length of the substrings to find


  • string: the string ‘ + “\n” + ‘ where and are the two substrings

Input Format

The first line contains a string denoting 8.
The second line contains an integer denoting k.


  • 8 consists of English alphabetic letters only (i.e., [a-zA-Z]).

Sample Input 0


Sample Output 0


Java Substring Comparisons – Hacker Rank Solution

import java.util.Scanner;
public class Solution {
    public static void main(String[] args) {
        /* Save input */
        Scanner scan = new Scanner(;
        String s = scan.nextLine();
        int k    = scan.nextInt();
        /* Create smallest and largest strings and initialize them */
        String smallest = s.substring(0, k);
        String largest  = s.substring(0, k);
        for (int i = 0; i <= s.length() - k; i++) {
            String curr = s.substring(i, i + k);
            if (smallest.compareTo(curr) > 0){
                smallest = curr;
            if (largest.compareTo(curr) < 0) {
                largest = curr;
        /* Print results */

Disclaimer: The above Problem (Java Substring Comparisons) is generated by Hackerrank but the Solution is Provided by Chase2Learn. This tutorial is only for Educational and Learning purposes. Authority if any of the queries regarding this post or website fill the following contact form thank you.

Leave a Comment