VOOZH about

URL: https://www.geeksforgeeks.org/dsa/tutorial-on-precomputation-techniques-in-strings/

⇱ Tutorial on Precomputation techniques in Strings - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Tutorial on Precomputation techniques in Strings

Last Updated : 29 Dec, 2023

Precomputation in strings refers to the process of performing calculations on a given string before actual operations or queries are performed.

The goal of precomputation is to process and store certain information about the string that can be used to optimize and speed up various string-related operations or queries that might be performed later. By pre-computing certain information of the string, redundant calculations can be avoided, and faster runtime for specific tasks can be achieved. Now let's consider the following problem for better understanding.

Given a string s of length n and a set of q queries, each query defined by a triplet (l, r, c) where: For each query, you need to calculate and output the number of occurrences of the character c within the substring s[l...r].

The idea is to iterate from index l to r and count the frequency of character c for each query separately.

For each query, this approach requires iterating through the substring characters and checking if each character is equal to the given character c. The time complexity of this approach for a single query is O(n). Since there are q queries, the overall time complexity is O(q * n).

The naïve approach is simple to implement, but it might be inefficient for large values of q and m since it involves repetitive calculations for each query.

:

To efficiently solve this problem, precomputation technique can be used involving the use of a 2D array that stores prefix sums of each character occurrences. Then, for each query, count of the desired character within the specified substring can be computed in O(1) time using the prefix sum.

Steps to implement the above idea:

  • Initialize a 2D array prefixSum of size n x 26, where n is the length of the input string s, and 26 represents the number of English alphabet characters ('a' to 'z').
  • prefixSum[i][ch] denotes the number of times character ch occurs till i.
  • For each index i from 0 to n - 1:
    • For each character ch from 'a' to 'z', calculate prefixSum[i][ch - 'a'] by adding prefixSum[i - 1][ch - 'a'] to the count of character ch at index i in string s.
  • For each query (l, r, c):
    • The count of character c is prefixSum[r][c 1="a" language="-"][/c] - prefixSum[l - 1][c 1="a" language="-"][/c].

Below is the implementation of above approach:

Time Complexity: O(n+m), where n is length of string and m is number of queries.
Auxiliary Space: O(n)

Comment
Article Tags: