An original string, consisting of lowercase English letters, can be encoded by the following steps:
Arbitrarily split it into a sequence of some number of non-empty substrings.
Arbitrarily choose some elements (possibly none) of the sequence, and replace each with its length (as a numeric string).
Concatenate the sequence as the encoded string.
For example, one way to encode an original string "abcdefghijklmnop" might be:
Split it as a sequence: ["ab", "cdefghijklmn", "o", "p"].
Choose the second and third elements to be replaced by their lengths, respectively. The sequence becomes ["ab", "12", "1", "p"].
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 boths1 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.
Example 1:
Input: s1 = "internationalization", s2 = "i18n"
Output: true
Explanation: It is possible that "internationalization" was the original string.
- "internationalization"
-> Split: ["internationalization"]
-> Do not replace any element
-> Concatenate: "internationalization", which is s1.
- "internationalization"
-> Split: ["i", "nternationalizatio", "n"]
-> Replace: ["i", "18", "n"]
-> Concatenate: "i18n", which is s2
Example 2:
Input: s1 = "l123e", s2 = "44"
Output: true
Explanation: It is possible that "leetcode" was the original string.
- "leetcode"
-> Split: ["l", "e", "et", "cod", "e"]
-> Replace: ["l", "1", "2", "3", "e"]
-> Concatenate: "l123e", which is s1.
- "leetcode"
-> Split: ["leet", "code"]
-> Replace: ["4", "4"]
-> Concatenate: "44", which is s2.
Example 3:
Input: s1 = "a5b", s2 = "c5b"
Output: false
Explanation: It is impossible.
- The original string encoded as s1 must start with the letter 'a'.
- The original string encoded as s2 must start with the letter 'c'.
Constraints:
1 <= s1.length, s2.length <= 40
s1 and s2 consist of digits 1-9 (inclusive), and lowercase English letters only.
The number of consecutive digits in s1 and s2 does not exceed 3.
Problem summary: An original string, consisting of lowercase English letters, can be encoded by the following steps: Arbitrarily split it into a sequence of some number of non-empty substrings. Arbitrarily choose some elements (possibly none) of the sequence, and replace each with its length (as a numeric string). Concatenate the sequence as the encoded string. For example, one way to encode an original string "abcdefghijklmnop" might be: Split it as a sequence: ["ab", "cdefghijklmn", "o", "p"]. Choose the second and third elements to be replaced by their lengths, respectively. The sequence becomes ["ab", "12", "1", "p"]. 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,
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming
Example 1
"internationalization"
"i18n"
Example 2
"l123e"
"44"
Example 3
"a5b"
"c5b"
Related Problems
Valid Word Abbreviation (valid-word-abbreviation)
Check If Two String Arrays are Equivalent (check-if-two-string-arrays-are-equivalent)
Step 02
Core Insight
What unlocks the optimal approach
For s1 and s2, divide each into a sequence of single alphabet strings and digital strings. The problem now becomes comparing if two sequences are equal.
A single alphabet string has no variation, but a digital string has variations. For example: "124" can be interpreted as 1+2+4, 12+4, 1+24, and 124 wildcard characters.
There are four kinds of comparisons: a single alphabet vs another; a single alphabet vs a number, a number vs a single alphabet, and a number vs another number. In the case of a number vs another (a single alphabet or a number), can you decrease the number by the min length of both?
There is a recurrence relation in the search which ends when either a single alphabet != another, or one sequence ran out, or both sequences ran out.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2060: Check if an Original String Exists Given Two Encoded Strings
class Solution {
public boolean possiblyEquals(String s1, String s2) {
Map<Integer, Boolean>[][] mem = new Map[s1.length() + 1][s2.length() + 1];
for (int i = 0; i <= s1.length(); ++i)
for (int j = 0; j <= s2.length(); ++j)
mem[i][j] = new HashMap<>();
return f(s1, s2, 0, 0, 0, mem);
}
// Returns true if s1[i..n) matches s2[j..n), accounting for the padding
// difference. Here, `paddingDiff` represents the signed padding. A positive
// `paddingDiff` indicates that s1 has an additional number of offset bytes
// compared to s2.
private boolean f(final String s1, final String s2, int i, int j, int paddingDiff,
Map<Integer, Boolean>[][] mem) {
if (mem[i][j].containsKey(paddingDiff))
return mem[i][j].get(paddingDiff);
if (i == s1.length() && j == s2.length())
return paddingDiff == 0;
if (i < s1.length() && Character.isDigit(s1.charAt(i))) {
// Add padding on s1.
final int nextLetterIndex = getNextLetterIndex(s1, i);
for (final int num : getNums(s1.substring(i, nextLetterIndex)))
if (f(s1, s2, nextLetterIndex, j, paddingDiff + num, mem))
return true;
} else if (j < s2.length() && Character.isDigit(s2.charAt(j))) {
// Add padding on s2.
final int nextLetterIndex = getNextLetterIndex(s2, j);
for (final int num : getNums(s2.substring(j, nextLetterIndex)))
if (f(s1, s2, i, nextLetterIndex, paddingDiff - num, mem))
return true;
} else if (paddingDiff > 0) {
// `s1` has more padding, so j needs to catch up.
if (j < s2.length())
return f(s1, s2, i, j + 1, paddingDiff - 1, mem);
} else if (paddingDiff < 0) {
// `s2` has more padding, so i needs to catch up.
if (i < s1.length())
return f(s1, s2, i + 1, j, paddingDiff + 1, mem);
} else { // paddingDiff == 0
// There's no padding difference, so consume the next letter.
if (i < s1.length() && j < s2.length() && s1.charAt(i) == s2.charAt(j))
return f(s1, s2, i + 1, j + 1, 0, mem);
}
mem[i][j].put(paddingDiff, false);
return false;
}
private int getNextLetterIndex(final String s, int i) {
int j = i;
while (j < s.length() && Character.isDigit(s.charAt(j)))
++j;
return j;
}
private List<Integer> getNums(final String s) {
List<Integer> nums = new ArrayList<>(List.of(Integer.parseInt(s)));
if (s.length() == 2) {
nums.add(Integer.parseInt(s.substring(0, 1)) + Integer.parseInt(s.substring(1, 2)));
} else if (s.length() == 3) {
nums.add(Integer.parseInt(s.substring(0, 1)) + Integer.parseInt(s.substring(1, 3)));
nums.add(Integer.parseInt(s.substring(0, 2)) + Integer.parseInt(s.substring(2, 3)));
nums.add(Integer.parseInt(s.substring(0, 1)) + Integer.parseInt(s.substring(1, 2)) +
Integer.parseInt(s.substring(2, 3)));
}
return nums;
}
}
// Accepted solution for LeetCode #2060: Check if an Original String Exists Given Two Encoded Strings
// Auto-generated Go example from java.
func exampleSolution() {
}
// Reference (java):
// // Accepted solution for LeetCode #2060: Check if an Original String Exists Given Two Encoded Strings
// class Solution {
// public boolean possiblyEquals(String s1, String s2) {
// Map<Integer, Boolean>[][] mem = new Map[s1.length() + 1][s2.length() + 1];
// for (int i = 0; i <= s1.length(); ++i)
// for (int j = 0; j <= s2.length(); ++j)
// mem[i][j] = new HashMap<>();
// return f(s1, s2, 0, 0, 0, mem);
// }
//
// // Returns true if s1[i..n) matches s2[j..n), accounting for the padding
// // difference. Here, `paddingDiff` represents the signed padding. A positive
// // `paddingDiff` indicates that s1 has an additional number of offset bytes
// // compared to s2.
// private boolean f(final String s1, final String s2, int i, int j, int paddingDiff,
// Map<Integer, Boolean>[][] mem) {
// if (mem[i][j].containsKey(paddingDiff))
// return mem[i][j].get(paddingDiff);
// if (i == s1.length() && j == s2.length())
// return paddingDiff == 0;
// if (i < s1.length() && Character.isDigit(s1.charAt(i))) {
// // Add padding on s1.
// final int nextLetterIndex = getNextLetterIndex(s1, i);
// for (final int num : getNums(s1.substring(i, nextLetterIndex)))
// if (f(s1, s2, nextLetterIndex, j, paddingDiff + num, mem))
// return true;
// } else if (j < s2.length() && Character.isDigit(s2.charAt(j))) {
// // Add padding on s2.
// final int nextLetterIndex = getNextLetterIndex(s2, j);
// for (final int num : getNums(s2.substring(j, nextLetterIndex)))
// if (f(s1, s2, i, nextLetterIndex, paddingDiff - num, mem))
// return true;
// } else if (paddingDiff > 0) {
// // `s1` has more padding, so j needs to catch up.
// if (j < s2.length())
// return f(s1, s2, i, j + 1, paddingDiff - 1, mem);
// } else if (paddingDiff < 0) {
// // `s2` has more padding, so i needs to catch up.
// if (i < s1.length())
// return f(s1, s2, i + 1, j, paddingDiff + 1, mem);
// } else { // paddingDiff == 0
// // There's no padding difference, so consume the next letter.
// if (i < s1.length() && j < s2.length() && s1.charAt(i) == s2.charAt(j))
// return f(s1, s2, i + 1, j + 1, 0, mem);
// }
// mem[i][j].put(paddingDiff, false);
// return false;
// }
//
// private int getNextLetterIndex(final String s, int i) {
// int j = i;
// while (j < s.length() && Character.isDigit(s.charAt(j)))
// ++j;
// return j;
// }
//
// private List<Integer> getNums(final String s) {
// List<Integer> nums = new ArrayList<>(List.of(Integer.parseInt(s)));
// if (s.length() == 2) {
// nums.add(Integer.parseInt(s.substring(0, 1)) + Integer.parseInt(s.substring(1, 2)));
// } else if (s.length() == 3) {
// nums.add(Integer.parseInt(s.substring(0, 1)) + Integer.parseInt(s.substring(1, 3)));
// nums.add(Integer.parseInt(s.substring(0, 2)) + Integer.parseInt(s.substring(2, 3)));
// nums.add(Integer.parseInt(s.substring(0, 1)) + Integer.parseInt(s.substring(1, 2)) +
// Integer.parseInt(s.substring(2, 3)));
// }
// return nums;
// }
// }
# Accepted solution for LeetCode #2060: Check if an Original String Exists Given Two Encoded Strings
class Solution:
def possiblyEquals(self, s1: str, s2: str) -> bool:
def getNums(s: str) -> set[int]:
nums = {int(s)}
for i in range(1, len(s)):
nums |= {x + y for x in getNums(s[:i]) for y in getNums(s[i:])}
return nums
def getNextLetterIndex(s: str, i: int) -> int:
j = i
while j < len(s) and s[j].isdigit():
j += 1
return j
@functools.lru_cache(None)
def dp(i: int, j: int, paddingDiff: int) -> bool:
"""
Returns True if s1[i..n) matches s2[j..n), accounting for the padding
difference. Here, `paddingDiff` represents the signed padding. A positive
`paddingDiff` indicates that s1 has an additional number of offset bytes
compared to s2.
"""
if i == len(s1) and j == len(s2):
return paddingDiff == 0
# Add padding on s1.
if i < len(s1) and s1[i].isdigit():
nextLetterIndex = getNextLetterIndex(s1, i)
for num in getNums(s1[i:nextLetterIndex]):
if dp(nextLetterIndex, j, paddingDiff + num):
return True
# Add padding on s2.
elif j < len(s2) and s2[j].isdigit():
nextLetterIndex = getNextLetterIndex(s2, j)
for num in getNums(s2[j:nextLetterIndex]):
if dp(i, nextLetterIndex, paddingDiff - num):
return True
# `s1` has more padding, so j needs to catch up.
elif paddingDiff > 0:
if j < len(s2):
return dp(i, j + 1, paddingDiff - 1)
# `s2` has more padding, so i needs to catch up.
elif paddingDiff < 0:
if i < len(s1):
return dp(i + 1, j, paddingDiff + 1)
# There's no padding difference, so consume the next letter.
else: # paddingDiff == 0
if i < len(s1) and j < len(s2) and s1[i] == s2[j]:
return dp(i + 1, j + 1, 0)
return False
return dp(0, 0, 0)
// Accepted solution for LeetCode #2060: Check if an Original String Exists Given Two Encoded Strings
/**
* [2060] Check if an Original String Exists Given Two Encoded Strings
*
* An original string, consisting of lowercase English letters, can be encoded by the following steps:
*
* Arbitrarily split it into a sequence of some number of non-empty substrings.
* Arbitrarily choose some elements (possibly none) of the sequence, and replace each with its length (as a numeric string).
* Concatenate the sequence as the encoded string.
*
* For example, one way to encode an original string "abcdefghijklmnop" might be:
*
* Split it as a sequence: ["ab", "cdefghijklmn", "o", "p"].
* Choose the second and third elements to be replaced by their lengths, respectively. The sequence becomes ["ab", "12", "1", "p"].
* 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.
*
* Example 1:
*
* Input: s1 = "internationalization", s2 = "i18n"
* Output: true
* Explanation: It is possible that "internationalization" was the original string.
* - "internationalization"
* -> Split: ["internationalization"]
* -> Do not replace any element
* -> Concatenate: "internationalization", which is s1.
* - "internationalization"
* -> Split: ["i", "nternationalizatio", "n"]
* -> Replace: ["i", "18", "n"]
* -> Concatenate: "i18n", which is s2
*
* Example 2:
*
* Input: s1 = "l123e", s2 = "44"
* Output: true
* Explanation: It is possible that "leetcode" was the original string.
* - "leetcode"
* -> Split: ["l", "e", "et", "cod", "e"]
* -> Replace: ["l", "1", "2", "3", "e"]
* -> Concatenate: "l123e", which is s1.
* - "leetcode"
* -> Split: ["leet", "code"]
* -> Replace: ["4", "4"]
* -> Concatenate: "44", which is s2.
*
* Example 3:
*
* Input: s1 = "a5b", s2 = "c5b"
* Output: false
* Explanation: It is impossible.
* - The original string encoded as s1 must start with the letter 'a'.
* - The original string encoded as s2 must start with the letter 'c'.
*
*
* Constraints:
*
* 1 <= s1.length, s2.length <= 40
* s1 and s2 consist of digits 1-9 (inclusive), and lowercase English letters only.
* The number of consecutive digits in s1 and s2 does not exceed 3.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/check-if-an-original-string-exists-given-two-encoded-strings/
// discuss: https://leetcode.com/problems/check-if-an-original-string-exists-given-two-encoded-strings/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn possibly_equals(s1: String, s2: String) -> bool {
false
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_2060_example_1() {
let s1 = "internationalization".to_string();
let s2 = "i18n".to_string();
let result = true;
assert_eq!(Solution::possibly_equals(s1, s2), result);
}
#[test]
#[ignore]
fn test_2060_example_2() {
let s1 = "l123e".to_string();
let s2 = "44".to_string();
let result = true;
assert_eq!(Solution::possibly_equals(s1, s2), result);
}
#[test]
#[ignore]
fn test_2060_example_3() {
let s1 = "a5b".to_string();
let s2 = "c5b".to_string();
let result = false;
assert_eq!(Solution::possibly_equals(s1, s2), result);
}
}
// Accepted solution for LeetCode #2060: Check if an Original String Exists Given Two Encoded Strings
function possiblyEquals(s1: string, s2: string): boolean {
const n = s1.length,
m = s2.length;
let dp: Array<Array<Set<number>>> = Array.from({ length: n + 1 }, v =>
Array.from({ length: m + 1 }, w => new Set()),
);
dp[0][0].add(0);
for (let i = 0; i <= n; i++) {
for (let j = 0; j <= m; j++) {
for (let delta of dp[i][j]) {
// s1为数字
let num = 0;
if (delta <= 0) {
for (let p = i; i < Math.min(i + 3, n); p++) {
if (isDigit(s1[p])) {
num = num * 10 + Number(s1[p]);
dp[p + 1][j].add(delta + num);
} else {
break;
}
}
}
// s2为数字
num = 0;
if (delta >= 0) {
for (let q = j; q < Math.min(j + 3, m); q++) {
if (isDigit(s2[q])) {
num = num * 10 + Number(s2[q]);
dp[i][q + 1].add(delta - num);
} else {
break;
}
}
}
// 数字匹配s1为字母
if (i < n && delta < 0 && !isDigit(s1[i])) {
dp[i + 1][j].add(delta + 1);
}
// 数字匹配s2为字母
if (j < m && delta > 0 && !isDigit(s2[j])) {
dp[i][j + 1].add(delta - 1);
}
// 两个字母匹配
if (i < n && j < m && delta == 0 && s1[i] == s2[j]) {
dp[i + 1][j + 1].add(0);
}
}
}
}
return dp[n][m].has(0);
}
function isDigit(char: string): boolean {
return /^\d{1}$/g.test(char);
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n × m)
Space
O(n × m)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.