HackerRank Find a Sub Word Solution

Hello Programmers, In this post, you will learn how to solve HackerRank Find a Sub Word Solution. This problem is a part of the Regex HackerRank Series.

One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions. We are going to solve the  Regex HackerRank Solutions using  CPP, JAVA, PYTHON, JavaScript & PHP Programming Languages.

You can practice and submit all HackerRank problem solutions in one place. Find a solution for other domains and Sub-domain. I.e. Hacker Rank solution for HackerRank C ProgrammingHackerRank C++ ProgrammingHackerRank Java Programming, HackerRank Python ProgrammingHackerRank Linux ShellHackerRank SQL Programming, and HackerRank 10 days of Javascript.

HackerRank Find a Sub Word Solution
HackerRank Find a Sub Word Solution

As you already know that this site does not contain only the Hacker Rank solutions here, you can also find the solution for other problems. I.e. Web Technology, Data StructuresRDBMS ProgramsJava Programs Solutions,  Fiverr Skills Test answersGoogle Course AnswersLinkedin Assessment, and Coursera Quiz Answers.

HackerRank Find a Sub Word Solution


We define a word character to be any of the following:

  • An English alphabetic letter (i.e., a-z and A-Z).
  • A decimal digit (i.e.0-9).
  • An underscore (i.e., _, which corresponds to ASCII value 95).

We define a word to be a contiguous sequence of one or more word characters that is preceded and succeeded by one or more occurrences of non-word-characters or line terminators. For example, in the string I l0ve-cheese_?, the words are Il0ve, and cheese_.

We define a sub-word as follows:

  • A sequence of word characters (i.e., English alphabetic letters, digits, and/or underscores) that occur in the same exact order (i.e., as a contiguous sequence) inside another word.
  • It is preceded and succeeded by word characters only.

Given n sentences consisting of one or more words separated by non-word characters, process q queries where each query consists of a single string, s. To process each query, count the number of occurrences of s as a sub-word in all n sentences, then print the number of occurrences on a new line.

Input Format

The first line contains an integer, n, denoting the number of sentences.
Each of the n subsequent lines contains a sentence consisting of words separated by non-word characters.
The next line contains an integer, q, denoting the number of queries.
Each line i of the q subsequent lines contains a string, si, to check.


  • 1 <= n <= 100
  • 1 <= q <= 10

Output Format

For each query string, si, print the total number of times it occurs as a subword within all words in all n sentences.

Sample Input

existing pessimist optimist this is

Sample Output



We must count the number of times s = is occurs as a sub-word in our n = 1 input sentence(s):

  • s occurs 1 time as a sub-word of existing.
  • s occurs 1 time as a subword of pessimist.
  • s occurs 1 time as a sub-word of optimist.
  • While s is a substring of the word this, it’s followed by a blank space; because a blank space is non-alphabetic, non-numeric, and not an underscore, we do not count it as a sub-word occurrence.
  • While s is a substring of the word is in the sentence, we do not count it as a match because it is preceded and succeeded by non-word characters (i.e., blank spaces) in the sentence. This means it doesn’t count as a sub-word occurrence.

Next, we sum the occurrences of s as a sub-word of all our words as 1 + 1 + 1 + 0 + 0 = 3. Thus, we print 3 on a new line.

HackerRank Find a Sub Word Solution in Cpp

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <string>
using namespace std;

bool chK(char ch)
    if(ch>='a' && ch<='z' )
        return true;
    if(ch>='A' && ch<='Z')
        return true;
    if(ch>='0' && ch<='9')
        return true;
        return true;
   return false;

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */  
    int i,j,num,test;
    string str,in;
    vector<string> list;
        //making the list of all the word given
    for(int t=1;t<=test;t++)
        int cnt=0;
            int p=0;
            bool prec=false;
            char ch;
                    if(chK(list[i].at(j)) && prec==true)
                    if(p==0 && j>=1 && chK(list[i].at(j-1)))
    return 0;

HackerRank Find a Sub Word Solution in Java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Solution {

	public static void main(String[] args) throws IOException {

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		int n = Integer.parseInt(br.readLine());
		String inputs[] = new String[n];
		for (int i = 0; i < inputs.length; i++) {
			inputs[i] = br.readLine();

		int testWords = Integer.parseInt(br.readLine());
		String regex_right="\\w.*";
		String regex_left=".*\\w";
		while (testWords > 0) {
			int count = 0;
			String word=br.readLine();
			for (int i = 0; i < inputs.length; i++) {
				String arr[] = inputs[i].split(" ");
				for (int j = 0; j < arr.length; j++) {
					//System.out.println(arr[j]+" is "+arr[j].matches(regex_left+"is"+regex_right));
					if (arr[j].matches(regex_left+word+regex_right)) {


HackerRank Find a Sub Word Solution in Python

import re
n = int(raw_input())
words = []
for i in range(0, n):
    words += re.split("[^a-zA-Z0-9_]+", raw_input())
t = int(raw_input())
for i in range(0, t):
    s = raw_input()
    count = 0
    for w in words:
        if (re.match("[a-zA-Z0-9_]+"+s+"[a-zA-Z0-9_]+", w)): count += 1
    print count

HackerRank Find a Sub Word Solution in JavaScript

process.stdin.on("data", function (input) {
	input = input.split('\n');
	var n = parseInt(input[0]),
		t = parseInt(input[n+1]),
		ts = n+2,
		strs = input.slice(1,n+1).join(' ').split(' '),
		tc = input.slice(ts,ts+t),
		tcc = new Array(),
		c = 0, r, m = false;
	for (i=0, j=tc.length; i<j; i+=1) {
		c = 0;
		r = new RegExp('(?:\\w+'+tc[i]+'\\w+)','ig');
			for (ii=0, jj=strs.length; ii<jj; ii+=1) {
				m = strs[ii].match(r);
				if (m) {
					c += m.length;

HackerRank Find a Sub Word Solution in PHP

$_fp = fopen("php://stdin", "r");
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
fscanf($_fp, "%d", $m);
$lines = array();
for ($i = 0; $i < $m; $i++) {
    $lines[] = fgets($_fp);
$lines = preg_split('/[^0-9a-z_]+/', implode(' ', $lines));
$lines = implode(' ', $lines);
fscanf($_fp, "%d", $m);
$searches = array();
for ($i = 0; $i < $m; $i++) {
    $searches[] = trim(fgets($_fp));
foreach ($searches as $search) {
    $search = '/[0-9a-z_]' . $search . '[0-9a-z_]/';
    print preg_match_all($search, $lines, $matches) . PHP_EOL;

Disclaimer: This problem (Find a Sub Word) is generated by HackerRank but the solution is provided by Chase2learn. This tutorial is only for Educational and Learning purposes.


1. How do you solve the first question in HackerRank?

If you want to solve the first question of Hackerrank then you have to decide which programing language you want to practice i.e C programming, Cpp Programing, or Java programming then you have to start with the first program HELLO WORLD.

2. How do I find my HackerRank ID?

You will receive an email from HackerRank to confirm your access to the ID. Once you have confirmed your email, the entry will show up as verified on the settings page. You will also have an option to “Make primary”. Click on that option. Read more

3. Does HackerRank detect cheating?

yes, HackerRank uses a powerful tool to detect plagiarism in the candidates’ submitted code. The Test report of a candidate highlights any plagiarized portions in the submitted code and helps evaluators to verify the integrity of answers provided in the Test.

4. Does HackerRank use camera?

No for coding practice Hackerrank does not use camera but for companies’ interviews code submission time Hackerrank uses the camera.

5. Should I put HackerRank certificate on resume?

These certificates are useless, and you should not put them on your resume. The experience you gained from getting them is not useless. Use it to build a portfolio, and link to it on your resume. 

6. Can I retake HackerRank test?

The company which sent you the HackerRank Test invite owns your Test submissions and results. It’s their discretion to permit a reattempt for a particular Test. If you wish to retake the test, we recommend that you contact the concerned recruiter who invited you to the Test and request a re-invite. 

7. What is HackerRank?

HackerRank is a tech company that focuses on competitive programming challenges for both consumers and businesses. Developers compete by writing programs according to provided specifications. Wikipedia

Finally, we are now, in the end, I just want to conclude some important message for you

Note:- I compile all programs, if there is any case program is not working and showing an error please let me know in the comment section. If you are using adblocker, please disable adblocker because some functions of the site may not work correctly.

Please share our posts on social media platforms and also suggest to your friends to Join Our Groups. Don’t forget to subscribe. 

Sharing Is Caring

Leave a Comment