← Meta Interview Insights

Meta·Machine Learning Engineer·Technical Phone Screen·Senior

SeniorPrefer not to say
Jun 2026

Summary

Interviewed for an ML engineer role at Meta, got a coding question that looks deceptively simple on the surface but has a few edge cases that'll trip you up if you're not careful.

Questions Asked (1)

Q1

Given a string containing parentheses and possibly other characters, find the minimum number of parentheses that need to be added to make the string valid (fully balanced).

Algorithms & Data Structures
Author's notes

I went straight to a stack-based approach and it worked fine, but I fumbled explaining why I was tracking unmatched opens separately from unmatched closes.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Use a single-pass counter approach: track the number of unmatched opening parentheses and the number of unmatched closing parentheses. Iterate through the string, incrementing the opening counter for '(' and decrementing it for ')' if possible; otherwise, increment the closing counter. The answer is the sum of both counters.

Pro tip: Clarify that only parentheses matter; other characters are ignored. Also, mention that this greedy approach works because any unmatched closing parenthesis must be fixed by adding an opening before it, and any unmatched opening must be fixed by adding a closing after it.

1. Understand the problem

Restate the problem: Given a string with parentheses and other characters, find the minimum number of parentheses to add to make it valid. Confirm that only parentheses are considered and that other characters are ignored.

2. Define counters

Initialize two counters: one for unmatched opening parentheses (open) and one for unmatched closing parentheses (close). These will track the minimum additions needed.

3. Iterate and update counters

Traverse the string. For each '(', increment open. For each ')', if open > 0, decrement open (match it); otherwise, increment close (unmatched closing). Ignore other characters.

4. Compute result

After traversal, the minimum number of parentheses to add is open + close. Return this sum.

5. Analyze complexity

State that the algorithm runs in O(n) time and O(1) space, which is optimal. Discuss edge cases like empty string, all parentheses, or no parentheses.

Key Points to Mention

  • Only parentheses matter; other characters are ignored.
  • Greedy matching of closing parentheses to previous openings is optimal.
  • Unmatched closing parentheses require adding an opening before them.
  • Unmatched opening parentheses require adding a closing after them.
  • Time complexity O(n) and space complexity O(1).
  • Edge cases: empty string, string with no parentheses, string with only opening or only closing parentheses.

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.