Prepin
Log in

Determine how many times the pattern occurs within the string.

Approach / Explanation

This question essentially requires you to develop an algorithm that counts the occurrences of a specific pattern within a provided string of characters. This task is frequently encountered in various algorithms and computer science applications. Here are some important points to consider: Understand the definition of a pattern. Consider how to efficiently traverse the entire string. Check if the current section of characters corresponds to the specified pattern. Maintain a tally of how many times this match is found. Your algorithm should be capable of addressing scenarios where the pattern is larger than the string or where the pattern does not exist in the string at all.

Suggested Answer

For instance, consider the string "abcabcabc" and the pattern "abc". To determine how many times "abc" appears in the string, we would begin by iterating through the input string. For each segment of characters that matches the length of the pattern, we verify if it corresponds to the pattern. Since the length of the pattern "abc" is 3, we will examine every set of 3 characters in the string. Starting from index 0 to 2, we find "abc," which aligns with the pattern. Next, we check the subsequent set of 3 characters, from index 3 to 5, and again encounter "abc." Finally, examining characters from index 6 to 8, we discover a third occurrence of "abc." Therefore, the pattern "abc" appears 3 times in the string.

Alternative Answer

Let's examine another example where the string is "abababab" and the pattern is "aba". According to the algorithm outlined above, we will check every three characters in the string. Starting from index 0 to 2, we identify "aba," which matches the pattern. Next, we check characters from index 2 to 4 and again find "aba." Continuing, checking characters from index 4 to 6 reveals the third occurrence of "aba." Finally, characters from index 6 to 8 provide us with the fourth "aba." Therefore, the pattern "aba" appears four times in the string. It's important to note that overlapping patterns are treated as separate matches in this algorithm, which is why we proceed to the next character after a match is found, rather than skipping the length of the pattern.

Question Details

Difficulty & Category

Medium
algorithms

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.