Given two strings, find the number of times the second string occurs in the first string, whether continuous or discontinuous.
Input: string a = "GeeksforGeeks" string b = "Gks" Output: 4 Explanation: The four strings are - (Check characters marked in bold) GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks
If we carefully analyze the given problem, we can see that it can be easily divided into sub-problems. The idea is to process all characters of both strings one by one staring from either from left or right side. Let us traverse from right corner, there are two possibilities for every pair of character being traversed.
m: Length of str1 (first string) n: Length of str2 (second string) If last characters of two strings are same, 1. We consider last characters and get count for remaining strings. So we recur for lengths m-1 and n-1. 2. We can ignore last character of first string and recurse for lengths m-1 and n. else If last characters are not same, We ignore last character of first string and recurse for lengths m-1 and n.
Below is the implementation of above Naive recursive solution –
The time complexity of above solution is exponential. If we carefully analyze, we can see that many sub-problems are solved again and again. Since same sub-problems are called again, this problem has Overlapping sub-problems property. So the problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming problems, re-computations of same sub-problems can be avoided by constructing a temporary array that stores results of sub-problems.
Below is its implementation using Dynamic Programming –
Time complexity of above solutions is O(MN).
Auxiliary space used by the program is O(MN).
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.GeeksforGeeks.org or mail your article to contribute@GeeksforGeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Number of subsequences of the form a^i b^j c^k
- Count of strings that can be formed using a, b and c under given constraints
- Number of subsequences in a string divisible by n
- Print all longest common sub-sequences in lexicographical order
- Count distinct occurrences as a subsequence
- Find minimum sum such that one of every three consecutive elements is taken
- Count Distinct Subsequences
- Count digit groupings of a number with given constraints
- Minimum Cost To Make Two Strings Identical
- Find length of the longest consecutive path from a given starting character
- Optimal Strategy for a Game | DP-31
- Longest Common Subsequence | DP-4
- Longest Increasing Subsequence | DP-3
- Overlapping Subproblems Property in Dynamic Programming | DP-1
- Largest Sum Contiguous Subarray