Instagram
youtube
Facebook
Twitter

Lexicographically smallest and largest substrings of length 'k' with Java HackerRank Solutions

Problem

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

Function Description

getSmallestAndLargest has the following parameters:

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

Returns

  • string: the string ' + "\n" + ' where and are the two substrings

Input Format

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

Constraints

  • 1<=|s|<=1000
  • s consists of English alphabetic letters only (i.e., [a-zA-Z]).

Sample Input

welcometojava
3

Sample Output

ava
wel

Solution

import java.util.Scanner;

public class LexicographicallySubstring {

    public static String getSmallestAndLargest(String s, int k) {
        String smallest = "";
        String largest = "";
            
         smallest=s.substring(0,k);
         largest=s.substring(0,k);
         for(int i=1;i<=s.length()-k;i++)
         {
             String substr=s.substring(i,i+k);
             if(substr.compareTo(smallest)<0)
                smallest=substr;
             if(substr.compareTo(largest)>0)
                largest=substr;
         }
        
        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));
    }
}

Steps involved in this Solution:

1. Declare a class 'LexicographicallySubstring'.

2. The getSmallestAndLargest() method is defined to find the lexicographically smallest and largest substrings.It takes two parameters: the input string s and the substring length k.

3.  smallest and largest strings are initialized as empty.

4. The initial smallest and largest substrings are set to the first substring of length k from the input string s.

5. A loop starts from index 1 and continues until s.length() - k. In each iteration, a substring of length k starting from the current index is obtained.

6. Compare the current substring with the current smallest and largest substrings using compareTo. Update smallest and largest if the current substring is lexicographically smaller or larger, respectively.

7. Return the lexicographically smallest and largest substrings, separated by a newline.

8. The main method reads the input string s and substring length k using a Scanner. Calls the getSmallestAndLargest() method with the input parameters and prints the returned result.