Java Substring Comparisons HackerRank Solution

Hello Programmers, In this post, you will know how to solve the Java Substring Comparisons HackerRank Solution. This problem is a part of the HackerRank Java Programming Series.

Java Substring Comparisons HackerRank Solution
Java Substring Comparisons HackerRank Solutions

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.

Java Substring Comparisons HackerRank Solution

Ezoicreport this adObjective

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

Returns

  • 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.

Constraints

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

Sample Input 0

welcometojava
3

Sample Output 0

ava
wel

Java Substring Comparisons HackerRank Solutions

import java.util.Scanner;
public class Solution {
    public static void main(String[] args) {
        /* Save input */
        Scanner scan = new Scanner(System.in);
        String s = scan.nextLine();
        int k    = scan.nextInt();
        scan.close();
        /* 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 */
        System.out.println(smallest);
        System.out.println(largest);
    }
}

Disclaimer: The above Problem (Java Substring Comparisons) is generated by Hackerrank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Next: Java String Reverse HackerRank Solution

Sharing Is Caring

Leave a Comment

Ezoicreport this ad