Skip to content
Programmingoneonone
Programmingoneonone
  • Engineering Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
    • 100+ C++ Programs
  • Solutions
    • HackerRank
      • Algorithms Solutions
      • C solutions
      • C++ solutions
      • Java solutions
      • Python solutions
    • Leetcode Solutions
    • HackerEarth Solutions
  • Work with US
Programmingoneonone
Programmingoneonone

HackerEarth A Needle in the Haystack problem solution

YASH PAL, 31 July 202414 February 2026
In this HackerEarth A Needle in the Haystack problem solution Our hacker, Little Stuart lately has been fascinated by ancient puzzles. One day going through some really old books he finds something scribbled on the corner of a page. Now Little Stuart believes that the scribbled text is more mysterious than it originally looks, so he decides to find every occurrence of all the permutations of the scribbled text in the entire book.
 
Since this is a huge task, Little Stuart needs your help, he needs you to only figure out if any permutation of the scribbled text exists in the given text string, so he can save time and analyze only those text strings where a valid permutation is present.
 
 
HackerEarth A Needle in the Haystack problem solution

 

 

HackerEarth A Needle in the Haystack problem solution.

#include <iostream>
#include <cstring>
#include <vector>
using namespace std;

int main()
{
int t;
cin>>t;
char c;
cin.get(c);
while(t--)
{
char p[10002],hay[101000];
cin>>p>>hay;

int lp = strlen(p);
int lh = strlen(hay);

int p_abc[26] = {0};
int f = 0;
for(int i=0;i<lp;i++)
p_abc[p[i]-'a']++;

int checker_abc[26] = {0};

for(int i=0;i<lp;i++)
{
checker_abc[hay[i]-'a']++;
}

for(int i=lp;i<lh;i++)
{
int found = 1;
for(int k=0;k<26;k++)
{
if(p_abc[k] != checker_abc[k])
{
found = 0;break;
}
}
if(found)
{
f=1;break;
}

checker_abc[hay[i-lp]-'a']--;
checker_abc[hay[i]-'a']++;
}
int found = 1;
for(int k=0;k<26 && !f;k++)
{
if(p_abc[k] != checker_abc[k])
{
found = 0;break;
}
}
if(found) f=1;

if(!f)
cout<<"NO"<<endl;
else
cout<<"YES"<<endl;
}
return 0;
}
 
 
coding problems solutions HackerEarth HackerEarth

Post navigation

Previous post
Next post

Leave a Reply

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

Programmingoneonone

We at Programmingoneonone, also known as Programming101 is a learning hub of programming and other related stuff. We provide free learning tutorials/articles related to programming and other technical stuff to people who are eager to learn about it.

Pages

  • About US
  • Contact US
  • Privacy Policy

Practice

  • Java
  • C++
  • C

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes