Home

Shortest Unsorted Continuous Subarray

581. Shortest Unsorted Continuous Subarray Solution 1 Sort the array. Compare the sorted array with the original one. Solution 2 Find the correct position of the minimum element and maximum element in the unsorted subarray. To determine the correct position of min, we need to find the first element which ...

Read more

Palindrome Linked List

234. Palindrome Linked List Solution 1 Get the mid of the linked list. Reverse the first half of the linked list. Traverse from the head and the node immediate after mid. Check if they are the same. Time Complexity: O(n) Space Complexity: O(1) def isPalindrome(self, head): """ :type head: ListNode :r...

Read more

Min Stack

155. Min Stack Solution When an element is pushed, it doesn’t have to update the min value. Only when the new min is pushed/popped, min get updated. We can bind min with the value, such that when an element is pushed/popped, we can know if it affects the min. Store the information in a list of tuple (x, min)...

Read more

Intersection of Two Linked Lists

160. Intersection of Two Linked Lists Solution 1 The intersection must be the “tail” of both linked list. Use two pointer to traverse the linked list from different head, we can achieve the route as A + intersection + B + intersection and B + intersection + A + intersection. After A/B + intersection + B/A, the point...

Read more

Path Sum III

437. Path Sum III Reference Solution 1 Consider the node need to achieve a target instead of the path to achieve a target. For each node, consider all paths start with it, check if the path can achieve the target. Complexity: $O(n^2)$ Solution 2 Memorize all values of paths from root to current node. Store the v...

Read more

Maximum Subarray

53. Maximum Subarray Solution Consider the sequence as family, the previous one is the next one’s father. To make the last child have most money, we will only inherit wealth but not debt. If the father has sum > 0, the child get it, otherwise the child restart his own life. def maxSubArray(self, nums): """ :type nums: List[int] ...

Read more

Symmetric Tree

101. Symmetric Tree Solution Check symmetrically def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ def isSym(left, right): if left is None and right is None: return True if left and right and (left.val == right.val): return isSym(left.right, right.left) and isSym(le...

Read more