1
var possiblyEquals = function (s1, s2) {2
// Memo array, note that we do not need to memoize true results as these bubble up3
const dp = Array.from({ length: s1.length + 1 }, () =>4
Array.from({ length: s2.length + 1 }, () => [])7
const backtrack = (p1, p2, count) => {8
if (p1 === s1.length && p2 === s2.length) return count === 0;9
// Optimization: Exit early if we have already visited here and know that it's false10
if (dp[p1][p2][count] !== undefined) return dp[p1][p2][count];15
// Case 1: string matches exactly21
backtrack(p1 + 1, p2 + 1, count)25
// Case 2: we can delete a character30
backtrack(p1 + 1, p2, count + 1)37
backtrack(p1, p2 + 1, count - 1)41
// Case 3: we can start stacking numbers to delete43
for (let i = 0; i < 3 && p1 + i < s1.length; i++) {46
num = num * 10 + parseInt(c1);48
if (backtrack(p1 + i + 1, p2, count + num)) return true;52
for (let i = 0; i < 3 && p2 + i < s2.length; i++) {55
num = num * 10 + parseInt(c2);57
if (backtrack(p1, p2 + i + 1, count - num)) return true;60
dp[p1][p2][count] = false;64
return backtrack(0, 0, 0);