Solve LeetCode stack and tree problems
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This item evaluates proficiency in string processing and tree/graph algorithms, testing competencies such as handling parentheses validity and computing node distances in binary trees. It is commonly asked in Coding & Algorithms interviews to assess core data structures and algorithmic problem-solving, emphasizing practical application of techniques alongside conceptual understanding.
Constraints
- 1 <= len(s) <= 100000
- s contains only '(', ')', and lowercase letters 'a'-'z'
- Return any valid result with the minimum number of removals
- Aim for O(n) time and O(n) extra space or better
Examples
Input: lee(t(c)o)de)
Expected Output: lee(t(c)o)de
Input: a)b(c)d
Expected Output: ab(c)d
Input: ))((
Expected Output:
Input: abc
Expected Output: abc
Input: ((a)
Expected Output: (a)
Input: ())()(((
Expected Output: ()()
Solution
def min_remove_to_make_valid(s: str) -> str:
chars = list(s)
stack = [] # indices of '('
for i, ch in enumerate(chars):
if ch == '(': # potential opener
stack.append(i)
elif ch == ')':
if stack:
stack.pop() # match with a previous '('
else:
chars[i] = '' # remove unmatched ')'
# remove any unmatched '('
for i in stack:
chars[i] = ''
return ''.join(chars)
Explanation
Time complexity: O(n). Space complexity: O(n).
Hints
- Use a stack to store indices of '(' and mark unmatched ')' for removal.
- After the first pass, any indices left in the stack are unmatched '('; remove them.
- Building the result with a list and joining at the end is more efficient than repeated string concatenation.