Algorithmsstack simulation

Stack Simulation — Model a Process

TT
Testlaa Team
May 14, 20261 min read

If a real process is reversible or nested, simulate it with pushes/pops instead of deep custom state machines when learning.

Try this in Python

def reduce_path(path: str) -> str:
    st: list[str] = []
    for part in path.split("/"):
        if part in ("", "."):
            continue
        if part == "..":
            if st:
                st.pop()
        else:
            st.append(part)
    return "/" + "/".join(st)


print(reduce_path("/a/./b/../../c/"))

Key takeaways

  • Each directory segment is a frame; .. pops if possible.
  • Same pattern models browser history or editor undo stacks.
  • Always define behavior on invalid pops.

Tags:

Stacks & queuesPythonStudents