Basic Calculator II
Medium
Stack
Master top interview questions with our interactive flashcard system
def calculate(s: str) -> int:
stack = []
num = 0
sign = '+'
for i in range(len(s)):
if s[i].isdigit():
num = num * 10 + int(s[i])
if (not s[i].isdigit() and s[i] != '') or i == len(s) - 1:
if sign == '+':
stack.append(num)
elif sign == '-':
stack.append(-num)
elif sign == '*':
stack.append(stack.pop() * num)
elif sign == '/':
stack.append(int(stack.pop() / num))
sign = s[i]
num = 0
return sum(stack)
def closestValue(root: Optional[TreeNode], target: float) -> int:
closest = root.val
while root:
if abs(root.val - target) < abs(closest - target):
closest = root.val
root = root.left if target < root.val else root.right
return closest
def verticalTraversal(root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
column_map = defaultdict(list)
queue = deque([(root, 0, 0)])
while queue:
node, row, col = queue.popleft()
column_map[col].append((row, node.val))
if node.left:
queue.append((node.left, row + 1, col - 1))
if node.right:
queue.append((node.right, row + 1, col + 1))
return [[val for _, val in sorted(column_map[col])]
for col in sorted(column_map.keys())]
def mergeKLists(lists: List[Optional[ListNode]]) -> Optional[ListNode]:
import heapq
heap = []
for i, node in enumerate(lists):
if node:
heapq.heappush(heap, (node.val, i, node))
dummy = ListNode()
current = dummy
while heap:
val, i, node = heapq.heappop(heap)
current.next = node
current = current.next
if node.next:
heapq.heappush(heap, (node.next.val, i, node.next))
return dummy.next
def treeToDoublyList(root: 'Node') -> 'Node':
if not root:
return None
first = None
last = None
def helper(node):
nonlocal first, last
if node:
helper(node.left)
if last:
last.right = node
node.left = last
else:
first = node
last = node
helper(node.right)
helper(root)
last.right = first
first.left = last
return first
def shortestPathBinaryMatrix(grid: List[List[int]]) -> int:
if grid[0][0] == 1:
return -1
n = len(grid)
queue = deque([(0, 0, 1)])
grid[0][0] = 1
directions = [(0, 1), (1, 0), (0, -1), (-1, 0),
(1, 1), (1, -1), (-1, 1), (-1, -1)]
while queue:
x, y, steps = queue.popleft()
if x == n-1 and y == n-1:
return steps
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 <= nx < n and 0 <= ny < n and grid[nx][ny] == 0:
grid[nx][ny] = 1
queue.append((nx, ny, steps + 1))
return -1