Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save AbdullahMagat/dd823ea3a4041626d1369875e610bda1 to your computer and use it in GitHub Desktop.
Save AbdullahMagat/dd823ea3a4041626d1369875e610bda1 to your computer and use it in GitHub Desktop.
Hackerrank Java Substring Comparisons
import java.util.Scanner;
public class Solution {
public static String getSmallestAndLargest(String s, int k) {
String smallest = "";
String largest = "";
smallest = s.substring(0,k);
largest = s.substring(0,k);
// "Compare to" method doesn't turn just the equel case it also turns a value.
for(int i=0; i<=s.length()-k; i++ ){
String str = s.substring(i,k+i);
if (smallest.compareTo(str)>0){
smallest = str;
}
if(largest.compareTo(str)<0){
largest=str;
}
}
return smallest + "\n" + largest;
}
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));
}
}
@just-tugsuu
Copy link

thanks lot dude

@blankhat1610
Copy link

omg, you're so awesome, bro

@dipsaili2001
Copy link

Why we have done i < s.length() - k in the for loop Please explain the logic

@abhinit21
Copy link

Why we have done i < s.length() - k in the for loop Please explain the logic

we are generating the substring of length 'k' so the last substring would be from the length of s - k till the end;
example: "GitHub" and k = 3 substring are ["Git", "itH", "tHu", "Hub"] and 'i' pointer of the for loop is going from 0 to 3 i.e s.length()-k

@abhinit21
Copy link

abhinit21 commented May 13, 2020

There is a correction in the code view this for changes

<script src="https://gist.github.com/abhinit21/a8f66269082f85646aec9e2545d7a0a4.js"></script>

or go to forks\abhinit21\viewfork

@avinashoguri
Copy link

avinashoguri commented Jul 20, 2020

Thanks it's working 👍

input s= "ZASKFDLklhfsdfsDLJFSJGIHEKHIPEINNNFIGHKkjgksfgjrotyotoyjtkjkLJOIOEHEKHKKDJGKFGJkfjhglfhjtrhkjfkhjnfglhkjflgjhtrljhfljhfgljhfgljhfgljhtrklyjhtrkjhfgkljhfgjhfljhtrljlfjhfgljhfglkjhflyjtljtrlyjhtryjtrtykhrktherktjhtrkyjhkujhtykhtryhrthHKLJHLHRLHTLRHLKHTRLKHLHRLHLKHLKHKLHLKHLHKLHKHJKHKJHKJHJKHKHJKHKHHLHLHLHKHKJHKJKKHKHKHKHKHHKHKHKHKHkhktryhtlhtklhtrkyhtrkyhtrkjyhtrkyhrekthtrkyhtrkhtrkyhtrkhtrkyhtrkhtrkyhtrkhtrkyhtrkhtrkyhtrkhtrkyhtrkhtrkyhtrkrtkyhtrklyhjrOEOHKDHFksdhfklHLHKHLHKKJHJHKGKLHLHJLJHLHLHLHLHHLHLHLHH"
k=1;

It's returning out put : A and Z

Suppose i have requirement constraint we need to check only small letters :

Constraints:
1<=s<=1000
S consists of English alphabetic letters only (i.e., [a-zA-Z])

how to check only lowercase letters and ignore uppercase?

can we suggest ??

input "SAME AS ABOVE";

Exp-output :" a" and "y"

@n0it-ameh
Copy link

import java.util.Scanner;

public class Solution {

public static String getSmallestAndLargest(String s, int k) {
    String smallest = "";
    String largest = "";
    char[] chArr = s.toCharArray();
    String[] str = new String[chArr.length-k+1];
    // 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=0,j=k; i<str.length; i++,j++){
        str[i] = s.substring(j-k, j);
    }
    
   java.util.Arrays.sort(str);
   smallest = str[0];
   largest = str[str.length-1];
    return smallest + "\n" + largest;
}


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));
}

}

@nithish143
Copy link

nithish143 commented Dec 24, 2020

Why we have done i < s.length() - k in the for loop Please explain the logic
logic : let string s be "welcometojava"and k=3 as the sample test case in hakerrank. so acc to this 3 letter words should be formed as shown below
1-wel
2-elc
3-lco
4-com
5-ome
6-met
7-eto
8-toj
9-oja
10-jav
11-ava
so smallest and largest should be found only among these words. But length of the string is 13 so i<=s.length means i<=13 loop runs 14 times and the substring indexes are also out of bounds due to k+i.So if we subtract k=3 from length i.e i<=s.length-k(3) then i<=10 now the loop runs 11 times as we need and index values of substring are also within limits and hence output.

@nithish143
Copy link

import java.util.Scanner;

public class Solution {

public static String getSmallestAndLargest(String s, int k) {
    String smallest = "";
    String largest = "";
    int count=0;
    String[] str=new String[s.length()-k+1];
    for (int i =0;i<str.length && k<=s.length() && count<str.length;i++){
        str[i]=s.substring(count,k);

        count++;
        k++;
    }
    smallest=str[0];
    largest=str[0];
    for (int j=1;j<str.length;j++){
        System.out.println(str[j]);
        if (str[j].compareTo(smallest)<0){
            smallest=str[j];
        }
        if (str[j].compareTo(largest)>0){
            largest=str[j];
        }
    }
    // Complete the function
    // 'smallest' must be the lexicographically smallest substring of length 'k'
    // 'largest' must be the lexicographically largest substring of length 'k'

    return smallest + "\n" + largest;
}


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));
}

}

@CaptainHandyman
Copy link

CaptainHandyman commented Jun 8, 2021

My solution:

package org.redbull4.helloworld;

import java.util.*;

public class Hello {
    static Scanner sc = new Scanner(System.in);

    public static String getSmallestAndLargest(String s, int k) {
        String _String = "", smallest = s.substring(0, k),
                largest = s.substring(0, k), output = "";

        for (int i = 0; i < s.length(); i++) {
            if (i + k > s.length())
                break;

            _String += s.substring(i, i + k);

            if (smallest.compareTo(_String) > 0)
                smallest = _String;
            if (largest.compareTo(_String) < 0)
                largest = _String;

            _String = "";
        }

        output = smallest + '\n' + largest;

        return output;
    }

    public static void main(String[] args) {
        String s = sc.nextLine();
        int k = sc.nextInt();

        System.out.println(getSmallestAndLargest(s, k));
    }
}

@Rieyanshi
Copy link

Should be
String smallest = s.substring(0,k+1);
String largest = s.substring(s.length()-k);

@Anjaneekumar
Copy link

Do anyone have list of all test cases ?
String Comparision Java - HackerRank

@Anjaneekumar
Copy link

we save one iteration by using i=1 instead of i=0;

@adhikari-sakar
Copy link

adhikari-sakar commented Mar 31, 2023

What about this?

public static String getSmallestAndLargest(String s, int k) {
		List<String> subs = new ArrayList<>();
		for (int i = 0; i < s.length(); i++) {
			if (k > s.length()) {
				break;
			}
			subs.add( s.substring(i, k));
			k++;
		}
		subs = subs.stream().sorted().collect(Collectors.toList());
		return subs.get(0) + "\n" + subs.get(subs.size() - 1);
	}

@mstgdk
Copy link

mstgdk commented Aug 27, 2023

public static String getSmallestAndLargest(String s, int k) {
String smallest = "";
String largest = "";

    ArrayList<String> st = new ArrayList<>();
    int s_len = s.length();
    for (int i =0; i<=s_len-k; i++){
        String sk = s.substring(i,i+k);
        st.add(sk);
    }
   
    smallest = Collections.min(st);
    largest = Collections.max(st);

    return smallest + "\n" + largest;
}


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));
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment