VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-number-of-same-end-substrings/

⇱ Find Number of Same-End Substrings - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find Number of Same-End Substrings

Last Updated : 28 Apr, 2024

Given a 0-indexed string s, and a 2D array of integers queries, where queries[i] = [li, ri] represents a substring of s starting from the index li and ending at the index ri (both inclusive), i.e. s[li..ri]. A 0-indexed string t of length n is called same-end if it has the same character at both of its ends, i.e., t[0] == t[n - 1]. The task is to return an array ans where ans[i] is the number of same-end substrings of queries[i].

Example:

Input: s = "abcaab", queries = {{0,0},{1,4},{2,5},{0,5}}
Output: {1,5,5,10}
Explanation: Here is the same-end substrings of each query:

  • 1st query: s[0..0] is "a" which has 1 same-end substring: "a".
  • 2nd query: s[1..4] is "bcaa" which has 5 same-end substrings: "bcaa", "bcaa", "bcaa", "bcaa", "bcaa".
  • 3rd query: s[2..5] is "caab" which has 5 same-end substrings: "caab", "caab", "caab", "caab", "caab".
  • 4th query: s[0..5] is "abcaab" which has 10 same-end substrings: "abcaab", "abcaab", "abcaab", "abcaab", "abcaab", "abcaab", "abcaab", "abcaab", "abcaab", "abcaab".

Input: s = "abcd", queries = {{0,3}}
Output: {4}
Explanation: The only query is s[0..3] which is "abcd". It has 4 same-end substrings: "abcd", "abcd", "abcd", "abcd".

Approach:

Store for each character c from a ... z for upto each index i. Then we count for each query from L to R the frequency of each character in the range and we count the number of possible substrings with that character c.

Consider this :

String s = abaabcbcbca

For a Query [ 1 , 4 ] here we have a[baabcb]cbca we have

For b we can pair each the number of characters in front of it

So if b is present 3 times we can create 3 + 2 + 1 = 6 substrings with b as start and end.

Generalizing we can get if for a query we have k times the character c then K + K-1 + K-2 + K-3 + ... + 1 substrings are possible so the answer is K*(K+1)/2

Steps-by-step approach:

  • Create result vector ans, get number of queries Q, and length of string N.
  • Create and populate frequency vector freq to store character frequencies.
  • Process each query: calculate count of substrings with same end character.
  • Calculate total substrings for each character within query indices.
  • Store counts of substrings for each query in ans.
  • Return ans containing counts of substrings for each query.

Below is the implementation of the above approach:


Output
1 5 5 10 

Time complexity: O(max(N,Q)āˆ—26)
Auxiliary space: O(Nāˆ—26)

Comment
Article Tags: