Skip to content
Programmingoneonone
Programmingoneonone

Learn everything about programming

  • Home
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programmingoneonone
Programmingoneonone

Learn everything about programming

HackerEarth A Needle in the Haystack problem solution

YASH PAL, 31 July 2024
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

Post navigation

Previous post
Next post

Pages

  • About US
  • Contact US
  • Privacy Policy

Follow US

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