VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solution-finding-patterns/

⇱ CSES Solution - Finding Patterns - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solution - Finding Patterns

Last Updated : 23 Jul, 2025

Prerequisite:Aho-Corasick algorithm

Given a string and patterns, check for each pattern if it appears in the string.

Example:

Input: s = "aybabtu", patterns = {"bab", "abc", "ayba"}
Output: YES
NO
YES

Input: s = "bybabtu", patterns = {"bat", "tu"}
Output:
NO
YES

Approach:

The solution uses a method called the Aho-Corasick algorithm. Let's see how it works:

  • Building a Trie: We first create a special kind of tree called a ‘trie’ from the patterns we’re looking for. Each pattern is a path in the trie from the root to a node.
  • Failure Links: We then add "failure links" to the trie. These links help us jump back efficiently in the trie when a character doesn’t match.
  • Searching: We go through the given string, character by character, moving along the paths in the trie. If we reach the end of a path (a pattern), we know that pattern exists in the string.
  • Counting: While searching, we keep track of how many times we reach each node (pattern). This tells us how many times each pattern appears in the string.

This method is fast because it checks all patterns at the same time, instead of one by one.

Steps-by-step approach:

  • Implement a insertPattern() function to insert each pattern into the trie structure.
  • Build failure links in the trie using the buildFailureLinks() function to prepare for pattern matching.
  • Run the Aho-Corasick algorithm on the main string s using the runAhoCorasick() function to identify occurrences of patterns.
  • Perform a Depth-First Search (DFS) on the trie structure to propagate occurrences down and update pattern matches using the dfs function.
  • In the main function, input and insert patterns into the trie, build failure links, run the Aho-Corasick algorithm, and propagate occurrences using DFS.
  • Output the pattern matches by checking the patternFound array for each pattern index and print "YES" if a match is found, otherwise print "NO".

Below is the implementation of the above approach:


Output
YES
NO
YES

Time complexity: O(numPatterns * m + n + s), where: numPatterns is the number of patterns, m is the average length of the patterns, n is the total number of nodes in the trie, s is the length of the main string.
Auxiliary Space: O(n + numPatterns)


Comment
Article Tags:
Article Tags: