301. Remove Invalid Parentheses [hard]
Leetcode: https://leetcode.com/problems/remove-invalid-parentheses/description/
Video: https://www.youtube.com/watch?v=2k_rS_u6EBk
[Solution]
Check whether a input string is valid
1
2count(')') <= count('('), i < n - 1
count('(') == count(')'), i = n - 1Compute min number of ‘(‘ and ‘)’ to remove unbalanced ‘)’ + unbalanced ‘(‘
- Try all possible ways to remove
r
‘)’s andl
‘(‘s. Remove ‘)’ first to make prefix valid. (have to remove ‘)’ first to make sure prefix is )
To avoid duplications: only remove the first parentheses if there are consecutive ones
1 | class Solution { |
1 | class Solution: |
872. Leaf-Similar Trees
Leetcode: https://leetcode.com/problems/leaf-similar-trees/description/
[Solution]
- Use two stacks to traverse two trees
- If node is a leaf, return and compare it
- Compare the number of leaves of each trees
1 | class Solution { |
DFS without tree
394. Decode String
Leetcode: https://leetcode.com/problems/decode-string/
[Solution]
Use a stack to store string and num pairs [[“”, num]]
1 | class Solution: |
127. Word Ladder
Leetcode: https://leetcode.com/problems/word-ladder/
[Solution]
Construct a dictionary like below
1
{"*ot": ["hot", "lot"], "h*t": ["hot"],...}
Have a step tracking queue like below
1
[("hot", 1),...]
Have a visited set to remember visited words
Set() is much faster than list
1 | def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: |
128. Longest Consecutive Sequence
Leetcode: https://leetcode.com/problems/longest-consecutive-sequence/
[Solution]
- Have a visited set to remember visited nodes
- Use a stack
[[num, len]]
to do DFS
1 | def longestConsecutive(self, nums): |
79. Word Search
Leetcode: https://leetcode.com/problems/word-search/
1 | def exist(self, board: List[List[str]], word: str) -> bool: |
332. Reconstruct Itinerary
Leetcode: https://leetcode.com/problems/reconstruct-itinerary/
1 | def findItinerary(self, tickets: List[List[str]]) -> List[str]: |
399. Evaluate Division
Leetcode: https://leetcode.com/problems/evaluate-division/
1 | def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: |
329. Longest Increasing Path in a Matrix
Leetcode: https://leetcode.com/problems/longest-increasing-path-in-a-matrix/
Solution 1: Naive DFS (TLE)
1 | def longestIncreasingPath(self, matrix: List[List[int]]) -> int: |
Optimize: Memoization
Note:
- Use a
cache
matrix to remember if we’ve already calculated the current cell - If so, directly return that from
cache
1 | def longestIncreasingPath(self, matrix: List[List[int]]) -> int: |