Day 64 — Basic Calculator II

Coding problem

ProblemBasic Calculator II
LeetCode ID(s)LeetCode #227
DifficultyMedium
PatternStack / Parsing
Company tagsMeta
Suggested time25m

Solution outline (coding)

  • Use a stack for numbers; on operator, pop two operands and apply (watch integer division truncates toward zero).
  • Handle precedence: only + - * / — use one stack and apply on the fly with last operator.
  • Ignore spaces; reject invalid.

Time complexity: O(n) — single pass.

Space complexity: O(n) — stack.

Show Python solution
class Solution:
  def calculate(self, s: str) -> int:
    num = 0
    sign = '+'
    st = []
    for i, ch in enumerate(s + '+'):
      if ch.isdigit():
        num = num * 10 + int(ch)
      elif ch in '+-*/' or ch == ' ':
        if ch == ' ':
          continue
        if sign == '+':
          st.append(num)
        elif sign == '-':
          st.append(-num)
        elif sign == '*':
          st.append(st.pop() * num)
        else:
          st.append(int(st.pop() / num))
        sign = ch
        num = 0
    return sum(st)


# Input:  s = "3+2*2"
# Output: 7

SQL interview practice

1. Interview question

Companies / track: Meta

Meta: expect event logging, ads / integrity, and social product analytics—deduping, sessionization, and window functions are frequent themes.

What you are asked to write (SQL prompt):

Frame this as metrics work for **Meta**-scale surfaces (ads, product, or engagement — as the tables suggest).
expressions(expr_id, expr_string). BigQuery: build a simple arithmetic evaluator UDF, evaluate expressions, and log invalid ones with error categories.

Tables implied by the prompt:

  • expressions(expr_id, expr_string)

Engine: BigQuery — use its date, array, and approximate functions as documented.

2. Solution outline

  • Clarify out loud: result grain (one row per what?), join keys, time zone, and any ORDER BY / LIMIT / tie-breakers.
  • Map Stack / Parsing to SQL: say the relational equivalent (e.g. hash map → GROUP BY + key; two pointers → ordered window + filter).
  • Arrays / UDFs: UNNEST and offsets for index; say when logic belongs in SQL vs a UDF.
  • Structure: CTEs (WITH) — one step per CTE; validate on a tiny slice (counts, nulls, duplicates).
Show SQL solution (BigQuery)

Main query

SELECT expr_id, expr_string, SAFE_CAST(expr_string AS FLOAT64) AS evaluated
FROM expressions
LIMIT 100;