Substring Comparisons HackerRank Solution

The problem context involves taking a string input and an integer 'k' from the user. The task is to find the lexicographically smallest and largest substrings of length 'k' from the given string.

Secure your next interview 🎯

CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷

Here is the Substring Comparisons HackerRank Solution HackerRank solution using CodeRankGPT:

The solution approach involves creating all possible substrings of length 'k' from the given string and adding them to an ArrayList. The list is then sorted in lexicographical order. The smallest substring is the first element in the sorted list and the largest substring is the last element in the sorted list. These two substrings are then printed out.


/**
 * 
 */
package com.javaaid.hackerrank.solutions.languages.java.strings;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

/**
 *
 */
public class JavaSubstringComparisons {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		ArrayList list = new ArrayList();
		String s = sc.next();
		int k = sc.nextInt();
		for (int i = 0; i <= s.length() - k; i++) {
			String tmp = s.substring(i, k + i);
			list.add(tmp);
		}
		Collections.sort(list);
		System.out.println(list.get(0));
		System.out.println(list.get(list.size() - 1));
		sc.close();
	}
}

If you have a HackerRank coding test coming up, you can use CodeRankGPT to your advantage. It will assist you during your interview and help ensure you get the job.

AI is here now, and other candidates might be using it to get ahead and win the job. 🧐

Built on Unicorn Platform