Magicsheet logo

Find the Original Typed String II

Hard
12.5%
Updated 8/1/2025

Find the Original Typed String II

1. What is this problem about?

The Find the Original Typed String II interview question is a significantly harder version of the previous problem. You are again given a typed string and need to find the number of possible original strings. However, this version adds a new constraint: the original string must have had a length of at least k. This requirement transforms a simple counting problem into a sophisticated optimization task.

2. Why is this asked in interviews?

Microsoft and Google use the Find the Original Typed String II coding problem to test a candidate's mastery of Dynamic Programming and optimization. It requires more than just counting blocks; it requires partitioning a target length across several choices. It evaluations your ability to use Prefix Sum optimization to reduce the complexity of DP transitions.

3. Algorithmic pattern used

This problem is solved using Dynamic Programming with Prefix Sum Optimization.

  • Blocks: First, find the lengths of all contiguous identical character blocks: L1,L2,,LmL_1, L_2, \dots, L_m.
  • DP State: dp[i][len] is the number of ways to pick character counts from the first ii blocks such that their total length is len.
  • Transitions: dp[i][len] = sum(dp[i-1][len - j]) where 1jLi1 \leq j \leq L_i.
  • Optimization: The transition is a range sum, which can be computed in O(1)O(1) time using a prefix sum array of the previous DP row. This brings the complexity down to O(mk)O(m \cdot k).

4. Example explanation

typed = "aaab", k=3k = 3.

  • Blocks: L1 = 3 ("aaa"), L2 = 1 ("b").
  • Total original strings (any length): 3imes1=33 imes 1 = 3 ("ab", "aab", "aaab").
  • We need length 3\geq 3.
    • "ab" (len 2): NO.
    • "aab" (len 3): YES.
    • "aaab" (len 4): YES. Result: 2.

5. Common mistakes candidates make

  • O(N2)O(N^2) DP: Failing to use prefix sums for the DP transition, leading to Time Limit Exceeded errors.
  • Memory Limit: Using a full 2D array for the DP. Since we only need the previous state, you can optimize to O(k)O(k) space.
  • Handling kk: Forgetting that if kk is smaller than the number of blocks, every possible string is valid because every block contributes at least 1 character.

6. Interview preparation tip

Master "Prefix Sums in DP." This is a classic Dynamic Programming interview pattern used whenever a state depends on a range of values from the previous row. It is essential for solving "Hard" category counting problems efficiently.

Similar Questions