most optimal : ```python “”” main idea: Greedy - start from last postion, record the first position that can jump to last position, then update last position to current idex. Check if last position can go back to idx = 0. start from last position, moving towards back. each time...
[Read More]
5. Longest Palindromic Substring
```python class Solution(object): def longestPalindrome(self, s): “”” :type s: str :rtype: str “”” # main idea: start from the middle to extend toward two sides. Two cases need to be processed seperately :1. odd 2. even # time O(N^2) space O(1) size = len(s) if not s or size ==...
[Read More]
339. Nested List Weight Sum
```python class Solution(object): def depthSum(self, nestedList): “”” :type nestedList: List[NestedInteger] :rtype: int “”” if len(nestedList) == 0: return 0 stack = [] sum = 0 for n in nestedList: stack.append((n, 1)) while stack: next, d = stack.pop(0) if next.isInteger(): sum += d * next.getInteger() else: for i in next.getList(): stack.append((i,d+1))...
[Read More]
133. Clone Graph
```python “”” Definition for a Node. class Node: def init(self, val = 0, neighbors = None): self.val = val self.neighbors = neighbors if neighbors is not None else [] “”” BFS class Solution: def cloneGraph(self, node: ‘Node’) -> ‘Node’: #!!!! the key point to solving the problem is to avoid...
[Read More]
199. Binary Tree Right Side View
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def rightSideView(self, root: TreeNode) -> List[int]: res = [] def traverse(node,level): if not node: return if len(res) == level: res.append(node.val)...
[Read More]