Z Algorithm Problem Statement

You are provided with a string S of length N and a string P of length M. Your objective is to determine the number of times P appears in S in linear time.

Example:

Input:
S = "ababa", P = "ab"
Output:
2
Explanation:

The string "ab" occurs twice in the string "ababa".

Constraints:

  • The string consists only of lowercase English alphabets.
  • 1 <= T <= 100
  • 1 <= N, M <= 10^4
  • Time Limit: 1 sec

Input:

The first line of input contains T, the number of test cases.
The first line of each test case contains two integers N and M, representing the lengths of strings S and P respectively.
The second line of each test case contains the string S.
The third line of each test case contains the string P.

Output:

The output for each test case is a single integer indicating the number of occurrences of P in S.

Note:

You do not need to print anything; it has already been handled. Simply implement the function to return the result.
AnswerBot
4mo

Implement a function to count the number of occurrences of a given string within another string in linear time.

  • Use the Z algorithm to preprocess the pattern string and the concatenated string to effic...read more

Help your peers!
Select
Add answer anonymously...
Barclays Business Technology Analyst Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits