Count ways to partition a number into increasing sequences of digits
Input: S = “1345”
Explanation: Possible partitions are as follows:
- [13, 45], [1, 345]
- [1, 3, 45]
- [1, 3, 4, 5]
Input: S = “12”
Approach: This problem can be solved by observing that between each digit either it will be a part of the previous number or it will be a new number so to solve the problem recursion can be used. Follow the steps below to solve the problem:
- Initialize an integer variable, say count as 0, to store the number of ways to partition a string into increasing subsets.
- Declare a function print() with index(storing current position), string S(given string in the question), and string ans( as parameters.
- Now, following two cases are required to be considered:
- If S[index] is inserted in the previous number, then append S[index] at the end of ans and recall the function print() with parameters index + 1, S, and ans.
- If S[index] is not a part of the previous number, then append ” “(space) at the end of ans and then insert S[index] and recall the function print() with parameters index + 1, S, ans.
- If index = S.length(), then check if the the digits in the sequences formed are in increasing order or not. If the sequences formed are increasing, increase count by 1.
- Print count as the answer after performing the above steps.
Below is the implementation of the above approach:
Time Complexity: O(N*2N) where N is the length of string S
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.