HackerRank in a String! Solution

HackerRank in a String! Solution

We say that a string contains the word hackerrank if a subsequence of its characters spell the word hackerrank. For example, if string  it does contain hackerrank, but  does not. In the second case, the second r is missing. If we reorder the first string as , it no longer contains the subsequence due to ordering.

More formally, let  be the respective indices of h, a, c, k, e, r, r, a, n, k in string . If  is true, then  contains hackerrank.

For each query, print YES on a new line if the string contains hackerrank, otherwise, print NO.

Function Description

Complete the hackerrankInString function in the editor below. It must return YES or NO.

hackerrankInString has the following parameter(s):

  • s: a string

Input Format

The first line contains an integer , the number of queries.
Each of the next  lines contains a single query string .


Output Format

For each query, print YES on a new line if  contains hackerrank, otherwise, print NO.

Sample Input 0


Sample Output 0


Explanation 0

We perform the following  queries:

  1. The characters of hackerrank are bolded in the string above. Because the string contains all the characters in hackerrank in the same exact order as they appear in hackerrank, we print YES on a new line.
  2. does not contain the last three characters of hackerrank, so we print NO on a new line.

Sample Input 1


Sample Output 1


Solution in Python

import re

def hackerrankInString(s):
    return "YES" if re.search(".*".join(list("hackerrank")), s) else "NO"

for _ in range(int(input())):

Answer explanation

The code


Creates the following regex pattern


.* just means "0 or more of any character"

It's broken down into two parts:

. - a "dot" indicates any character
* - means "0 or more instances of the preceding regex token"

So it matches any word that has hackerrank in it such as

s ="h--ac++ke---zzz---r--ra??nk"

Without using regex

def hackerrankInString(s):
    a = 0
    for i in s:
        if a<10 and i == "hackerrank"[a]:
    return "YES" if a==10 else "NO"

for _ in range(int(input())):

Answer Explanation

Assume our string is


So we will be looping the above string

for i in "papahopackerank"

Initially a = 0 means "hackerrank"[0] = "h"

In our for loop once we find a "h" we will increase a. "papa" is completely ignored

After finding "h" it will increase a and now "hackerrank"[1] = "a" which means it will start searching "a" in rest of the string then "c" then "k" up to the end.

if a becomes 9 we can just break the loop and print "YES". Since a = 9 means we have found all letters of hackerrank.

In our example string, a will become 5 since it will match only up to "hacker". So our program will print "No"

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]