HackerRank ‘HackerRank in a String!’ Solution

Short Problem Definition:

We say that a string contains the word hackerrank if a subsequence of its characters spell the word hackerrank. For example, if string s = haacckkerrannkk  it does contain hackerrank, but s = haacckkerannk 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.


HackerRank in a String!


time complexity is O(N)

space complexity is O(1)


Keep two pointers. One to the expected string (needle) and one to the input string. If you find the needle in the haystack before you run out of characters, you are good.

def hackerrankInString(s):
    needle = 'hackerrank'
    idx_in_needle = 0
    for c in s:
        if c == needle[idx_in_needle]:
            idx_in_needle += 1
        if idx_in_needle == len(needle):
    if idx_in_needle == len(needle):
        return "YES"
        return "NO"

If you enjoyed this post, then make sure you subscribe to my Newsletter and/or Feed.