Java Program to find Lexicographically smallest and largest substring of length k
Write a Java Program to find Lexicographically smallest and largest substring of length k. This problem is derived from the String section of Hackerrank in java. I like this problem, so i decided to put my solution on my site.Below is the question and solution of the problem.
Java String Compare
Given a string, find out the lexicographically smallest and largest substring of length k.
[Note: Lexicographic order is also known as alphabetic order dictionary order. So “ball” is smaller than “cat”, “dog” is smaller than “dorm”. Capital letter always comes before smaller letter, so “Happy” is smaller than “happy” and “Zoo” is smaller than “ball”.]
Input Format
First line will consist a string containing english alphabets which has at most characters. 2nd line will consist an integer .
Output Format
In the first line print the lexicographically minimum substring. In the second line print the lexicographically maximum substring.
Sample Input
welcometojava
3
Sample Output
ava
wel
Explanation
Here is the list of all substrings of length :
wel
elc
lco
com
ome
met
eto
toj
oja
jav
ava
Among them ava is the smallest and wel is the largest.
Here below is the source code of the above problem which is successfully compiled and run on Hackerrank code editor as well as on Windows System to produce desired result.Let’s check out the program below :
SOURCE CODE : :
import java.util.Scanner; public class Solution{ public static void main(String[] args) { int i; String temp=""; Scanner sc = new Scanner(System.in); String str= sc.next(); int sub_len = sc.nextInt(); int len = str.length(); int l =len-sub_len+1; String array[] = new String[l]; for(i=0;i<l;i++) { array[i]=str.substring(i,i+sub_len); } int n = array.length; for(int p=0;p<n-1;p++) { for(int u=p+1;u<n;u++) { if(array[u].compareTo(array[p])<0) { temp=array[p]; array[p]=array[u]; array[u]=temp; } } } System.out.println(array[0]); System.out.println(array[n-1]); } }
OUTPUT : :
welcometojava 3 ava wel
If you found any error below in this program, or any difficulty in understanding the program, or any other queries related to website, please let us know by comment section below…..Thanks for visiting and reading the post.
hackerrank question