Basic Calculator

Intuition Compute values on the fly, use stack for brackets. Approach Parse each number, use num = 10xnum + current. Keep track of the last sign (starts as positive). When an opening bracket is found, stack the item and the sign. When a closing bracket is found, pop sign and item and do the math. Complexity Time complexity: O(N) Space complexity: O(N) Code class Solution(object): def calculate(self, s): """ :type s: str :rtype: int """ stack = [] res = 0 num = 0 sign = 1 for c in s: if c.isdigit(): num = (num * 10 ) + int(c) elif c == "+": res += sign * num sign = 1 num = 0 elif c == "-": res += sign * num sign = -1 num = 0 elif c == "(": stack.append(res) stack.append(sign) sign = 1 res = 0 elif c == ")": res += sign * num res *= stack.pop() # sign res += stack.pop() # num num = 0 return res + sign * num

May 7, 2025 · 1 min

Candy

Intuition My thought was first going left to right checking both neighbours. For example, for [1,2,3,4] would work perfectly. However it’s not possible to solve this in one pass checking both neighbours. We need to use a two pass approach, LTR, RTL. To visualize better the problem, using [1,2,3,4] let’s see how many candies LTR and RTL would give for each children: LTR [1,2,3,4] -> [1,2,3,4] since it's always increase each children get's one more candy than the previous one. RTL [1,2,3,4] -> [1,1,1,1] From RTL perspective, it's always decreasing, so all children get's one. In this case the correct solution is [1,2,3,4] ...

April 20, 2025 · 2 min

Trapping rain water

Intuition This problem uses a very similar solution to 135. Candy. Important point to notice is: water can’t be at the edges, the edge is either 0 heigh (water leak) or wall with no water on top. So with this in mind we can ignore water on edges. The volume of water in any place is water = max_height - current_height. Let’s take this example [0,2,0,3,0,2], the # represents the walls, the . represents the water. ...

April 20, 2025 · 2 min