Skip to content

Stack Basics

Table of Contents

1441. Build an Array With Stack Operations

1441. Build an Array With Stack Operations - Python Solution
from typing import List


# Stack
def buildArray(target: List[int], n: int) -> List[str]:
    res = []
    m, i, j = len(target), 1, 0

    while i <= n and j < m:
        res.append("Push")
        if target[j] != i:
            res.append("Pop")
        else:
            j += 1
        i += 1

    return res


target = [1, 3, 4]
n = 4
print(buildArray(target, n))
# ['Push', 'Push', 'Pop', 'Push', 'Push']

844. Backspace String Compare

844. Backspace String Compare - Python Solution
def backspaceCompare(s: str, t: str) -> bool:

    def build(text):
        stack = []

        for char in text:
            if char != "#":
                stack.append(char)
            elif stack:
                stack.pop()

        return "".join(stack)

    return build(s) == build(t)


print(backspaceCompare("ab#c", "ad#c"))  # True

682. Baseball Game

682. Baseball Game - Python Solution
from typing import List


# Stack
def calPoints(operations: List[str]) -> int:
    stack = []

    for op in operations:
        if op == "+":
            stack.append(stack[-2] + stack[-1])
        elif op == "D":
            stack.append(2 * stack[-1])
        elif op == "C":
            stack.pop()
        else:
            stack.append(int(op))

    return sum(stack)


ops = ["5", "2", "C", "D", "+"]
print(calPoints(ops))  # 30

2390. Removing Stars From a String

  • LeetCode | LeetCode CH (Medium)

  • Tags: string, stack, simulation

  • Remove all * characters and their adjacent characters from the string.

  • Steps for the string leet**cod*e:

char action stack
l push "l"
e push "le"
e push "lee"
t push "leet"
* pop "lee"
* pop "le"
c push "lec"
o push "leco"
d push "lecod"
* pop "leco"
e push "lecoe"
2390. Removing Stars From a String - Python Solution
# Stack
def removeStars(s: str) -> str:
    stack = []

    for char in s:
        if char == "*":
            stack.pop()
        else:
            stack.append(char)

    return "".join(stack)


s = "leet**cod*e"
print(removeStars(s))  # "lecoe"

1472. Design Browser History

  • LeetCode | LeetCode CH (Medium)

  • Tags: array, linked list, stack, design, doubly linked list, data stream

946. Validate Stack Sequences

3412. Find Mirror Score of a String

71. Simplify Path

Comments