Open In App

Count of given Strings in 2D character Array using Trie

Last Updated : 30 Nov, 2023
Comments
Improve
Suggest changes
1 Like
Like
Report

Counting the number of occurrences of a given string in a 2D character array using a Trie.

Examples:

Input: vector<string> grid = {"abcde", "fghij", "xyabc", "klmno",}; string word = "abc";
Output: 2
Explanation: abc occurs twice in "abcde", "xyabc"

Input: vector<string> grid = {"abcde", "fghij", "xyabc", "klmno",}; string word = "klm";
Output: 1
Explanation: klm occurs once in "klmno"

Approach:

Counting the number of occurrences of a given string in a 2D character array using a Trie approach involves building a Trie data structure from the 2D array and then searching for the given string in the Trie.

  • We first build a Trie from the given word.
  • Then, we iterate through the 2D character array and construct substrings from each starting position.
  • If a substring exists in the Trie, we increment the count.
  • Finally, we return the count, which represents the number of occurrences of the given string in the 2D array.

Implementation:

C++
Java Python3 C# JavaScript

Output
2

Time Complexity: O(K + R * C * N), where K is the length of the input word, R is the number of rows, C is the number of columns, and N is the maximum length of the substrings generated from the 2D array.

Auxiliary Space complexity: O(K), where K is the length of the input word


Similar Reads