Z Algorithm

You’re given a string S of length N and a string P of length M. Your task is to find the number of occurrences of P in S in linear time.

For example:
If S = "ababa", and P = "ab", then "ab" occurs twice in "ababa".
Note:
The string only consists of lowercase English alphabets.
Input Format:
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, the length of string 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 Format:
The only line of output of each test case should contain an integer denoting the number of occurrences of P in S.
Note:
You don’t need to print anything. It has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 100
1 <= N, M <= 10^4

Time Limit: 1 sec
CodingNinjas
author
2y
Brute Force Approach

A basic approach is to check all substrings of string ‘S’ and see if that substring is equal to ‘P’ or not. Let’s see how we’ll do this.

  • Initialize an integer variable count = 0.
  • St...read more
CodingNinjas
author
2y
Z Algorithm Approach

As we are supposed to find the number of occurrences of 'P' in ‘S’ in linear time. We can do this by maintaining a Z array. The Z array for any string 'S' of length 'N' is an array...read more

Help your peers!
Add answer anonymously...
Barclays Business Technology Analyst Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

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

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter