Problem Description
Given a digit string s, determine whether it is possible to break s into a sequence of consecutive substrings – each substring being a “value‐equal” string (i.e. all characters in it are the same) – such that exactly one of these substrings has length 2 and all the remaining substrings have length 3.
Key Insights
- The only allowed substring lengths are 2 and 3.
- You are allowed to partition even a maximal group (of consecutive identical digits) into multiple valid substrings.
- For any contiguous segment (a group) of identical digits of length L, the segment can be split into pieces of size 2 and 3 if and only if there exists nonnegative integers k and r such that 2k + 3r = L.
- The total count of pieces of length 2 across all groups must be exactly one.
- Use dynamic programming to combine the possibilities from individual groups to verify if a global partition meeting the criteria exists.
Space and Time Complexity
Time Complexity: O(n * L) in worst case, where n is the number of groups and L is the length of a group (in the worst-case scenario L can be O(n)); overall O(N^2) for input length N.
Space Complexity: O(n) for the DP state and additional storage for group counts.
Solution
We first break the input string into maximal groups of consecutive equal digits. For each group of length L, we determine all possible ways to partition it into pieces of lengths 2 and 3. Each way can be represented by the count of pieces that are of length 2 in that group. For instance, if L = 5 there is one possibility: one piece of length 2 and one piece of length 3 (because 2+3 = 5).
Once the possibilities for each group are known (as counts of “2-length” pieces), we use dynamic programming to combine these possibilities over all groups and check if it is possible to achieve exactly one piece of length 2 overall.
The DP works as follows:
- Initialize a DP set (or boolean array) with a starting count of 0.
- For each group, for every previously possible overall count, add each possible count that can come from splitting the current group.
- In the end, check if the value 1 is reachable.
This algorithm uses grouping and a knapSack–style DP to combine choices across groups.