HackerRank in a String Solution

Hello Programmers, In this post, you will learn how to solve HackerRank in a String Solution. This problem is a part of the HackerRank Algorithms Series.

HackerRank in a String Solution
HackerRank in a String Solution

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.

HackerRank in a String Solution

Task

We say that a string contains the word hackerrank if a subsequence of its characters spell the word hackerrank. Remeber that a subsequence maintains the order of characters selected from a sequence.

More formally, let p[0], p[1], . . . , p[9] be the respective indices of hacker, rank in string s. If p[0] < p[1] < p[2] < . . . < p[9] is true, then s contains hackerrank.

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

s = haacckkerrannkk

This contains a subsequence of all of the characters in the proper order. Answer YES

s = haacckkerrannk

This is missing the second ‘r’. Answer NO.

s = hccaakkerrannkk

There is no ‘c’ after the first occurrence of an ‘a’, so answer NO.

Function Description

Complete the hackerrankInString function in the editor below.

hackerrankInString has the following parameter(s):

  • string s: a string

Returns

  • string: YES or NO

Input Format

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

Constraints

  • 2 <= q <= 102
  • 10 <= length of s <= 104

Sample Input 0

2
hereiamstackerrank
hackerworld

Sample Output 0

YES
NO

Explanation 0

We perform the following q = 2 queries:

  1. s = hereiamstackerrank
    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 return YES.
  2. s = hackerworld does not contain the last three characters of hackerrank, so we return NO.

Sample Input 1

2
hhaacckkekraraannk
rhbaasdndfsdskgbfefdbrsdfhuyatrjtcrtyytktjjt

Sample Output 1

YES
NO

HackerRank in a String Solution

HackerRank in a String Solutions in C

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
char *hackerrank(char *string)
{
    int total;
    int i;
    int j;    
    char *comp = "hackerrank\0";
    
    i = 0;
    j = 0;
    while (string[i] != '\0')
    {
        if (string[i] == comp[j])
            j += 1;
        i += 1;
    }
    if (strlen(comp) == j)
        return ("YES");
    else
        return ("NO");
}
int main(){
    int q; 
    scanf("%d",&q);
    for(int a0 = 0; a0 < q; a0++){
        char* s = (char *)malloc(512000 * sizeof(char));
        scanf("%s",s);
        printf("%s\n", hackerrank(s));
        // your code goes here
    }
    return 0;
}

HackerRank in a String Solutions in Cpp

#include <bits/stdc++.h>
using namespace std;
int main(){
    int q;
    cin >> q;
    for(int a0 = 0; a0 < q; a0++){
        string s;
        cin >> s;
        string cur = "hackerrank";
        int st = 0;
        for (int i= 0; i < s.size() && st < cur.size(); i++) {
            if (s[i] == cur[st]) {
                st++;
            }
        }
        if (st == cur.size()) {
            cout << "YES" << endl;
        } else {
            cout << "NO" << endl;
        }
        // your code goes here
    }
    return 0;
}

HackerRank in a String Solutions in Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int q = in.nextInt();
        for(int a0 = 0; a0 < q; a0++){
            String s = in.next();
            // your code goes here
            System.out.println(hasSubseq(s,"hackerrank") ? "YES" : "NO"); 
        }
    }
    
    private static boolean hasSubseq(String source, String target) {
        if (target.length() == 0) return true; 
        if (source.length() == 0) return false;
        
        int x = 0; 
        for (char c : source.toCharArray()) {
            if (c == target.charAt(x)) 
                x++;
            if (x == target.length()) 
                return true; 
        }
        return false; 
    }
}

HackerRank in a String Solutions in Python

import sys
needle = 'hackerrank'
n = len(needle)
q = int(sys.stdin.readline())
for _ in xrange(q):
    s = sys.stdin.readline().strip()
    i = 0
    for c in s:
        if c == needle[i]: i += 1
        if i == n: break;
    if i == n: print "YES"
    else: print "NO"

HackerRank in a String Solutions using JavaScript

process.stdin.resume();
process.stdin.setEncoding('ascii');
var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;
process.stdin.on('data', function (data) {
    input_stdin += data;
});
process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});
function readLine() {
    return input_stdin_array[input_currentline++];
}
/////////////// ignore above this line ////////////////////
function containsString(string, substring) {
  let charIndex = 0;
  for(let i = 0; i < string.length; i += 1) {
    const char = substring[charIndex];
    if(string[i] === char) {
      charIndex += 1;
    }
  }
  return charIndex === substring.length;
}
function main() {
    var q = parseInt(readLine());
    for(var a0 = 0; a0 < q; a0++){
      var string = readLine();
      const result = containsString(string, 'hackerrank');
      console.log(result ? 'YES' : 'NO');
    }
}

HackerRank in a String Solutions in Scala

import scala.io.StdIn
    
object Solution {
  val hackerrank = List('h', 'a', 'c', 'k', 'e', 'r', 'r', 'a', 'n', 'k')
  def main(args: Array[String]): Unit = {
    val q = StdIn.readInt()
    (0 until q).foreach(i => {
      val s = StdIn.readLine().toList
      println(if (contains(s, hackerrank)) "YES" else "NO")
    })
  }
  def contains(s: List[Char], h: List[Char]): Boolean = h match {
    case Nil => true
    case hHead :: hTail => s match {
      case Nil => false
      case sHead :: sTail => if (sHead == hHead) contains(sTail, hTail) else contains(sTail, h)
    }
  }
}

HackerRank in a String Solutions in Pascal

Disclaimer: This problem (HackerRank in a String) is generated by HackerRank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Next: HackerRank Weighted Uniform Strings Solution

Leave a Reply

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