HackerRank in a String

Good morning. It is a cold morning in the Twin Cities of Minneapolis and St. Paul. When I got up around 04:00 AM the temperature was around -1F. I believe it will rise during the day.

My wife left with our neighbor shopping. They should be back around noon. We are planning on making some ravioli from scratch. On workdays my wife cooks, but on weekends we both do. Have some red wine from last week which we did not finish. It should be a nice and cozy lunch.

I looked for the next challenge on Strings in Java at HackerRank. If interested you can look it up here. The challenge deals with subsequences. They picked up the string “hackerrank” to be searched for in the provided strings, hence the title of the challenge.

I developed the solution using the Eclipse IDE.

For simplicity when I work on the solution I changed the following line:

BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));


BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out));

That allows me to run tests in my environment using as much code as possible from HackerRank.

The function for my solution follows:

   static String hackerrankInString(String s) {

    	final String hr = "hackerrank";
    	// **** perform some sanity checks ****
    	if (s.length() < hr.length())
    		return "NO";
    	// **** traverse the hackerrank string ****
    	int startIndex = 0;
    	for (int i = 0; (i < hr.length()) && (startIndex <= s.length()); i++) {
    		// **** get the next character from "hackerrank"****
    		char ch = hr.charAt(i);
    		// **** start at this point in s ****
    		String ss = s.substring(startIndex);
    		// **** get the index for this character in the substring ****
    		int index = ss.indexOf(ch);
    		// **** this character not found ****
    		if (index == -1)
    			return "NO";
    		// **** update the start index ****
    		startIndex += (index + 1);
    	// **** hackerrank found ****
    	return "YES";

If you are interested in the entire solution you can find it here in my GitHub repository.

As usual, if you have comments or questions, please leave me a note bellow.

Keep on learning and practicing;


Please follow me on Twitter:  @john_canessa

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.