Check if an Original String Exists Given Two Encoded Strings - Problem

An original string, consisting of lowercase English letters, can be encoded by the following steps:

  1. Arbitrarily split it into a sequence of some number of non-empty substrings.
  2. Arbitrarily choose some elements (possibly none) of the sequence, and replace each with its length (as a numeric string).
  3. Concatenate the sequence as the encoded string.

For example, one way to encode an original string "abcdefghijklmnop" might be:

  1. Split it as a sequence: ["ab", "cdefghijklmn", "o", "p"].
  2. Choose the second and third elements to be replaced by their lengths, respectively. The sequence becomes ["ab", "12", "1", "p"].
  3. Concatenate the elements of the sequence to get the encoded string: "ab121p".

Given two encoded strings s1 and s2, consisting of lowercase English letters and digits 1-9 (inclusive), return true if there exists an original string that could be encoded as both s1 and s2. Otherwise, return false.

Note: The test cases are generated such that the number of consecutive digits in s1 and s2 does not exceed 3.

Input & Output

Example 1 — Different Interpretations
$ Input: s1 = "a5b", s2 = "a5b"
Output: true
💡 Note: Both strings are identical, so they can definitely encode the same original string (either "a5b" or "a" + 5 characters + "b")
Example 2 — Number as Length
$ Input: s1 = "ab", s2 = "a2"
Output: false
💡 Note: s1 = "ab" means original has 'a' then 'b'. s2 = "a2" could mean 'a' + 2 characters, but that would be 3 total chars vs 2 in s1
Example 3 — Complex Case
$ Input: s1 = "a5b", s2 = "abc"
Output: false
💡 Note: s1 could be "a5b" (3 chars) or "a" + 5chars + "b" (7 chars). s2 is "abc" (3 chars). Only 3-char interpretation works, but "a5b" ≠ "abc"

Constraints

  • 1 ≤ s1.length, s2.length ≤ 40
  • s1 and s2 consist of digits 1-9 and lowercase English letters
  • The number of consecutive digits in s1 and s2 does not exceed 3

Visualization

Tap to expand
Check if Original String Exists: "a5b" vs "abc"s1: "a5b"s2: "abc"Try different interpretations of "5" in s1"a5b" (literal)"a" + 5chars + "b"Length: 3Length: 7s2 = "abc" has length 3, but "a5b" ≠ "abc"Result: false (no matching original string)
Understanding the Visualization
1
Input
Two encoded strings with letters and digits
2
Process
Try different interpretations of digits
3
Output
True if both can encode same original
Key Takeaway
🎯 Key Insight: Track character count difference to determine if both strings can represent the same original
Asked in
Google 42 Facebook 38 Microsoft 25
23.5K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen