Algorithmswindow boundary update

Window Boundary Update

TT
Testlaa Team
May 14, 20261 min read

Boundary updates focus on what happens at L and R edges: entering element increments, leaving element decrements, and lazy updates when boundaries jump.

Why this shows up in the real world

Warehouse dock doors: each time the left trailer leaves and a new one docks on the right, manifests update incrementally—boundary bookkeeping.

Core idea (explained for students)

Template: add(a[R]) then while bad: remove(a[L]); L++. For multi-char jumps, remove might not run for every index in between—only if you can prove shortcuts.

Try this in Python

def apply_boundary_ops(s: str) -> int:
    freq, L, uniq = {}, 0, 0

    def add(ch):
        nonlocal uniq
        freq[ch] = freq.get(ch, 0) + 1
        if freq[ch] == 1:
            uniq += 1

    def remove(ch):
        nonlocal uniq
        freq[ch] -= 1
        if freq[ch] == 0:
            uniq -= 1

    best = 0
    for R, ch in enumerate(s):
        add(ch)
        while uniq > 2:
            remove(s[L])
            L += 1
        best = max(best, R - L + 1)
    return best


print(apply_boundary_ops("ccaabbb"))

Common mistakes

  • Updating R twice in one iteration accidentally.
  • Removing wrong index after duplicate characters.

Key takeaways

  • Treat add/remove as symmetric APIs—easier to test.

Tags:

Sliding windowPythonStudents