Lexicographical Order - Hacker Rank Solution

Lexicographical Order - Hacker Rank Solution

Lexicographical Order - Hacker Rank Solution
Monday, 28 September 2020

 

Java hackerRank solution

We define the following terms:

 

Lexicographical Order, also known as alphabetic or dictionary order, orders characters as follows:

A<B<Z....Y<Z<A<B....<Y<Z.

For example, ball < cat, dog < dorm, Happy < happy, Zoo < ball.

 

A substring of a string is a contiguous block of characters in the string. For example, the substrings of abc are a, b, c, ab, bc, and ABC.

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

 

Input Format

 

The first line contains a string denoting s.

The second line contains an integer denoting s.

 

Constraints

1<=|s|<=1000

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

Output Format

 

Return the respective lexicographically smallest and largest substrings as a single newline-separated string.

 

Sample Input 0

 

welcometojava

3

Sample Output 0

 

ava

wel


Solution:

import java.util.Scanner;

public class Solution {

    public static String getSmallestAndLargest(String sint k) {
        String currStr = s.substring(0, k);
        String smallest = currStr;
        String largest = currStr;

   
        
        // Complete the function
        // 'smallest' must be the lexicographically smallest substring of length 'k'
        // 'largest' must be the lexicographically largest substring of length 'k'
        
        for (int i = k; i < s.length(); i++) { 
            currStr = currStr.substring(1, k) + s.charAt(i); 
            if (largest.compareTo(currStr) < 0)      
                 largest = currStr; 
            if (smallest.compareTo(currStr) > 0
                 smallest = currStr;             
        } 
  
        // Print result. 
         
        return smallest + "\n" + largest;
    }


Lexicographical Order - Hacker Rank Solution
4/ 5
Oleh