Algorithm


Problem Name: Java Substring Comparisons

Problem Link: https://www.hackerrank.com/challenges/java-string-compare/problem?isFullScreen=true

In this HackerRank Functions in Java programming problem solution,

We define the following terms:

A < B ... < 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, , 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 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 0

welcometojava
3

Sample Output 0

ava
wel

 

 

 

 

 

Code Examples

#1 Code Example with Java Programming

Code - Java Programming


import java.util.Scanner;

public class Solution {

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


    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)>;
    }
}
Copy The Code & Try With Live Editor
Advertisements

Demonstration


Previous
[Solved] Java Substring in Java solution in Hackerrank - Hacerrank solution Java
Next
[Solved] Java Anagrams in Java solution in Hackerrank - Hacerrank solution Java