Java Substring Comparisons – Hacker Rank Solution

 

Objective

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 – Hacker Rank Solution

Code:

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 MultiplexCoder. This tutorial is only for Educational and Learning purposes.

Tags:    hackerrank Java solutions | Functions Discussions | java | HackerRank | student analysis java hackerrank solution | challenges java hackerrank solution | hackerrank java basic certification solutions | hackerrank-java certification solutions | basic data types hackerrank solution in java | hackerrank java questions and answers | hackerrank java certification solutions | hackerrank java coding questions and answers | hackerrank-java certification solutions github | hackerrank java tutorial | hackerrank java interview questions | hackerrank java compiler | welcome to java hackerrank solution | 2021
Previous
Next Post »