Skip to content

Commit 8b8b79c

Browse files
Fix recursion depth failure in string transformation reconstruction
1 parent 6e03a48 commit 8b8b79c

1 file changed

Lines changed: 14 additions & 14 deletions

File tree

‎strings/min_cost_string_conversion.py‎

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -102,20 +102,20 @@ def assemble_transformation(ops: list[list[str]], i: int, j: int) -> list[str]:
102102
>>> assemble_transformation(ops2, x2, y2)
103103
['C1', 'I2', 'R23']
104104
"""
105-
if i == 0 and j == 0:
106-
return []
107-
elif ops[i][j][0] in {"C", "R"}:
108-
seq = assemble_transformation(ops, i - 1, j - 1)
109-
seq.append(ops[i][j])
110-
return seq
111-
elif ops[i][j][0] == "D":
112-
seq = assemble_transformation(ops, i - 1, j)
113-
seq.append(ops[i][j])
114-
return seq
115-
else:
116-
seq = assemble_transformation(ops, i, j - 1)
117-
seq.append(ops[i][j])
118-
return seq
105+
sequence = []
106+
# Trace backwards without consuming one Python stack frame per operation.
107+
while i != 0 or j != 0:
108+
operation = ops[i][j]
109+
sequence.append(operation)
110+
if operation[0] in {"C", "R"}:
111+
i -= 1
112+
j -= 1
113+
elif operation[0] == "D":
114+
i -= 1
115+
else:
116+
j -= 1
117+
sequence.reverse()
118+
return sequence
119119

120120

121121
if __name__ == "__main__":

0 commit comments

Comments
 (0)