Leetcode-Python-Solution-Practice100
Leetcode-Python-Solution-Practice100
1
Table of Contents
2
Unique Binary Search Trees 2.2.13
Unique Binary Search Trees II 2.2.14
Path Sum 2.2.15
Binary Tree Maximum Path Sum 2.2.16
Binary Tree Level Order Traversal 2.2.17
Validate Binary Search Tree 2.2.18
Minimum Depth of Binary Tree 2.2.19
Convert Sorted Array to Binary Search Tree 2.2.20
Flatten Binary Tree to Linked List 2.2.21
Construct Binary Tree from Inorder and Preorder Traversal 2.2.22
Binary Tree Paths 2.2.23
Recover Binary Search Tree 2.2.24
Path Sum II 2.2.25
Binary Level Order Traversal II 2.2.26
Kth Smallest Element in a BST 2.2.27
Construct Binary Tree from Inorder and Postorder Traversal 2.2.28
Binary Tree Right Side View 2.2.29
Sum Root to Leaf Numbers 2.2.30
Binary Tree Zigzag Level Order Traversal 2.2.31
House Robber III 2.2.32
Inorder Successor in BST 2.2.33
Binary Tree Longest Consecutive Sequence 2.2.34
Verify Preorder Sequence in Binary Search Tree 2.2.35
Binary Tree Upside Down 2.2.36
Count Univalue Subtrees 2.2.37
Serialize and Deserialize Binary Tree 2.2.38
Graphs 2.3
Number of Connected Components in an Undirected Graph 2.3.1
Course Schedule 2.3.2
Graph Valid Tree 2.3.3
3
Course Schedule 2 2.3.4
Number of Islands 2.3.5
3
Linked List Cycle
URL: https://leetcode.com/problems/linked-list-cycle/
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head == None:
return False
else:
fast = head
slow = head
return False
4
Reverse Linked List
URL: https://leetcode.com/problems/reverse-linked-list/
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None:
return None
elif head != None and head.next == None:
return head
else:
temp = None
next_node = None
while head != None:
next_node = head.next
head.next = temp
temp = head
head = next_node
return temp
5
Delete Node in a Linked List
Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with
value 3, the linked list should become 1 -> 2 -> 4 after calling your function.
URL: https://leetcode.com/problems/delete-node-in-a-linked-list/
class Solution(object):
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-plac
e instead.
"""
if node == None:
pass
else:
next_node = node.next
node.val = next_node.val
node.next = next_node.next
6
Merge Two Sorted Lists
URL: https://leetcode.com/problems/merge-two-sorted-lists/
7
Merge Two Sorted Lists
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 == None and l2 == None:
return None
elif l1 != None and l2 == None:
return l1
elif l2 != None and l1 == None:
return l2
else:
dummy = ListNode(0)
p = dummy
if l1 != None:
p.next = l1
if l2 != None:
p.next = l2
return dummy.next
8
Intersection of Two Linked Lists
A: a1 → a2 ↘ c1 → c2 → c3 ↗
B: b1 → b2 → b3 begin to intersect at node c1.
Notes:
If the two linked lists have no intersection at all, return null. The linked lists must
retain their original structure after the function returns. You may assume there are
no cycles anywhere in the entire linked structure. Your code should preferably run
in O(n) time and use only O(1) memory.
URL: https://leetcode.com/problems/intersection-of-two-linked-lists/
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if headA == None and headB == None:
return None
elif headA == None and headB != None:
return None
elif headA != None and headB == None:
return None
else:
len_a = 0
9
Intersection of Two Linked Lists
len_b = 0
current = headA
while current != None:
current = current.next
len_a += 1
current = headB
while current != None:
current = current.next
len_b += 1
diff = 0
current = None
if len_a > len_b:
diff = len_a - len_b
currentA = headA
currentB = headB
else:
diff = len_b - len_a
currentA = headB
currentB = headA
count = 0
while count < diff:
currentA = currentA.next
count += 1
10
Linked List Cycle II
URL: https://leetcode.com/problems/linked-list-cycle-ii/
11
Linked List Cycle II
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None:
return head
else:
fast = head
slow = head
has_cycle = False
while fast != None and fast.next != None:
slow = slow.next
fast = fast.next.next
if fast == slow:
has_cycle = True
break
if has_cycle == False:
return None
slow = head
while fast != slow:
fast = fast.next
slow = slow.next
return slow
12
Palindrome Linked List
URL: https://leetcode.com/problems/palindrome-linked-list/
13
Palindrome Linked List
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head == None:
return True
elif head != None and head.next == None:
return True
else:
fast = head
slow = head
stack = []
while fast != None and fast.next != None:
stack.append(slow.val)
slow = slow.next
fast = fast.next.next
#madam
if fast != None:
slow = slow.next
return True
14
Remove Linked List Elements
Example Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 Return: 1 --> 2 --> 3 -->
4 --> 5
URL: https://leetcode.com/problems/remove-linked-list-elements/
15
Remove Linked List Elements
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
if head == None:
return head
elif head != None and head.next == None:
if head.val == val:
return None
else:
return head
else:
dummy = ListNode(0)
dummy.next = head
prev = dummy
return dummy.next
16
Remove Duplicates from Sorted Linked List
For example, Given 1->1->2, return 1->2. Given 1->1->2->3->3, return 1->2->3.
URL: https://leetcode.com/problems/remove-duplicates-from-sorted-list/
17
Remove Duplicates from Sorted Linked List
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None:
return head
elif head != None and head.next == None:
return head
else:
lookup = {}
current = head
prev = head
while current != None:
if current.val in lookup:
prev.next = prev.next.next
else:
lookup[current.val] = True
prev = current
current = current.next
return head
18
Remove Duplicates from Sorted Linked List II
URL: https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None:
return head
else:
dup_dict = {}
current = head
while current != None:
if current.val in dup_dict:
dup_dict[current.val] += 1
else:
dup_dict[current.val] = 1
current = current.next
list_values = []
current = head
while current != None:
19
Remove Duplicates from Sorted Linked List II
if dup_dict[current.val] > 1:
pass
else:
list_values.append(current.val)
current = current.next
if list_values == []:
return None
else:
node1 = ListNode(list_values[0])
head = node1
for entries in list_values[1:]:
new_node = ListNode(entries)
node1.next = new_node
node1 = new_node
return head
20
Remove Nth node from End of List
For example,
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note: Given n will always be valid. Try to do this in one pass.
URL: https://leetcode.com/problems/remove-nth-node-from-end-of-list/
21
Remove Nth node from End of List
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
if head == None:
return head
else:
dummy = ListNode(0)
dummy.next = head
fast = dummy
slow = dummy
for i in range(n):
fast = fast.next
slow.next = slow.next.next
return dummy.next
22
Trees
1
/ \
2 3
/ \
4 5
as
"[1,2,3,null,null,4,5]"
. You do not necessarily need to follow this format, so please be creative and
come up with different approaches yourself.
URL: https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
23
Trees
class Codec:
def init (self):
self.serialized_array = []
self.index = 0
root = TreeNode(data[self.index])
self.index += 1
root.left = self.deserialize(data)
root.right = self.deserialize(data)
return root
24
Trees
25
Preorder Traversal
Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes' values.
URL: https://leetcode.com/problems/binary-tree-preorder-traversal/
class Solution:
# @param {TreeNode} root
# @return {integer[]}
def preorderTraversal(self, root):
if root == None:
return []
else:
preorderList = []
stack = []
stack.append(root)
while(stack != []):
node = stack.pop()
preorderList.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return preorderList
26
BST Iterator
BST Iterator
Implement an iterator over a binary search tree (BST). Your iterator will be
initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Note: next() and hasNext() should run in average O(1) time and uses O(h)
memory, where h is the height of the tree.
URL: https://leetcode.com/problems/binary-search-tree-iterator/
27
BST Iterator
class BSTIterator:
# @param root, a binary search tree's root node
def init (self, root):
self.stack = []
node = root
while node != None:
self.stack.append(node)
node = node.left
28
Inorder Traversal
Inorder Traversal
Given a binary tree, return the inorder traversal of its nodes' values.
URL: https://leetcode.com/problems/binary-tree-inorder-traversal/
class Solution:
# @param {TreeNode} root
# @return {integer[]}
def inorderTraversal(self, root):
if root == None:
return []
else:
result = []
stack = []
node = root
while stack or node:
if node:
stack.append(node)
node = node.left
else:
node = stack.pop()
result.append(node.val)
node = node.right
return result
29
Symmetric Tree
Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its
center).
Note: Bonus points if you could solve it both recursively and iteratively.
URL: https://leetcode.com/problems/symmetric-tree/
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root == None:
return True
else:
return self.isMirror(root.left, root.right)
30
Balanced Binary Tree
For this problem, a height-balanced binary tree is defined as a binary tree in which
the depth of the two subtrees of every node never differ by more than 1.
URL: https://leetcode.com/problems/balanced-binary-tree/
31
Balanced Binary Tree
class Solution:
# @param {TreeNode} root
# @return {boolean}
leftHeight = self.getHeight(root.left)
if leftHeight == -1:
return -1
rightHeight = self.getHeight(root.right)
if rightHeight == -1:
return -1
32
Closest BST Value
Note: Given target value is a floating point. You are guaranteed to have only one
unique value in the BST that is closest to the target.
URL: https://leetcode.com/problems/closest-binary-search-tree-value/
33
Closest BST Value
class Solution(object):
def closestValue(self, root, target):
"""
:type root: TreeNode
:type target: float
:rtype: int
"""
min_dif = float("inf")
closestVal = None
if root == None:
return None
else:
while root:
root_val = root.val
val_dif = abs(root_val - target)
if val_dif < min_dif:
min_dif = val_dif
closestVal = root_val
if target < root_val:
if root.left != None:
root = root.left
else:
root = None
else:
if root.right != None:
root = root.right
else:
root = None
return closestVal
34
Postorder Traversal
Postorder Traversal
Given a binary tree, return the postorder traversal of its nodes' values.
URL: https://leetcode.com/problems/binary-tree-postorder-traversal/
35
Postorder Traversal
class Solution(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root == None:
return []
else:
stack = []
out_stack = []
stack.append(root)
return out_stack[::-1]
36
Maximum Depth of Binary Tree
The maximum depth is the number of nodes along the longest path from the root
node down to the farthest leaf node.
URL: https://leetcode.com/problems/maximum-depth-of-binary-tree/
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
else:
return max(self.maxDepth(root.left), self.maxDepth(r
oot.right)) + 1
37
Invert Binary Tree
38
Invert Binary Tree
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root == None:
return None
else:
stack = []
stack.append(root)
while stack != []:
curr_node = stack.pop()
if curr_node.left != None or curr_node.right !=
None:
temp = curr_node.left
curr_node.left = curr_node.right
curr_node.right = temp
if curr_node.right != None:
stack.append(curr_node.right)
if curr_node.left != None:
stack.append(curr_node.left)
return root
39
Same Tree
Same Tree
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the
nodes have the same value.
URL: https://leetcode.com/problems/same-tree/
class Solution:
# @param {TreeNode} p
# @param {TreeNode} q
# @return {boolean}
def isSameTree(self, p, q):
if p == None and q == None:
return True
else:
if p == None or q == None:
return False
else:
if p.val == q.val:
return self.isSameTree(p.left, q.left) and s
elf.isSameTree(p.right, q.right)
else:
return False
40
Lowest Common Ancestor of a Binary Search Tree
6
/ \
2 8
URL: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-
tree/
class Solution(object):
41
Lowest Common Ancestor of a Binary Search Tree
lca_elem = self.find_elem_max_index(between_elems)
return lca_elem
42
Lowest Common Ancestor of a Binary Search Tree
self.inorder_list.append(node.val)
self.inorder_traversal(node.right)
43
Lowest Common Ancestor in a Binary Tree
3
/ \
5 1
URL: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
44
Lowest Common Ancestor in a Binary Tree
class Solution(object):
if root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left == None:
return right
else:
return left
45
Unique Binary Search Trees
13321\///\\321132//\\2123
URL: https://leetcode.com/problems/unique-binary-search-trees/
46
Unique Binary Search Trees
class Solution(object):
if n < 0:
return 0
if n == 0 or n == 1:
return 1
possibilities = 0
47
Unique Binary Search Trees II
For example, Given n = 3, your program should return all 5 unique BST's shown
below.
13321\///\\321132//\\2123
URL: https://leetcode.com/problems/unique-binary-search-trees-ii/
48
Unique Binary Search Trees II
class Solution(object):
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
if n == 0:
return []
else:
return self.tree_constructor(1, n)
return results
49
Path Sum
Path Sum
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such
that adding up all the values along the path equals the given sum.
For example: Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ \ 7
2 1 return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
URL: https://leetcode.com/problems/path-sum/
class Solution(object):
while s != []:
pathsum = s.pop()
current = s.pop()
50
Path Sum
if pathsum == sum:
return True
if current.right:
rightpathsum = pathsum + current.right.val
s.append(current.right)
s.append(rightpathsum)
if current.left:
leftpathsum = pathsum + current.left.val
s.append(current.left)
s.append(leftpathsum)
return False
51
Binary Tree Maximum Path Sum
For this problem, a path is defined as any sequence of nodes from some starting
node to any node in the tree along the parent-child connections. The path does
not need to go through the root.
1
/ \
2 3
Return 6
URL: https://leetcode.com/problems/binary-tree-maximum-path-sum/
52
Binary Tree Maximum Path Sum
class Solution(object):
def init (self):
self.maxSum = -sys.maxint - 1
def findMax(self,root):
if root == None:
return 0
left = self.findMax(root.left)
right = self.findMax(root.right)
self.maxSum = max(root.val + left + right, self.maxSum)
ret = root.val + max(left,right)
if ret < 0:
return 0
else:
return ret
53
Binary Tree Level Order Traversal
URL: https://leetcode.com/problems/binary-tree-level-order-traversal/
54
Binary Tree Level Order Traversal
import Queue
class Solution:
# @param {TreeNode} root
# @return {integer[][]}
def levelOrder(self, root):
if root == None:
return []
else:
q = Queue.Queue()
q.put(root)
q.put("#")
levelOrderTraversal = []
level = []
while q.empty() == False:
node = q.get()
if node == "#":
if q.empty() == False:
q.put("#")
levelOrderTraversal.append(level)
level = []
else:
level.append(node.val)
if node.left:
q.put(node.left)
if node.right:
q.put(node.right)
return levelOrderTraversal
55
Validate Binary Search Tree
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's
key. Both the left and right subtrees must also be binary search trees. Example 1:
2 / \ 1 3 Binary tree [2,1,3], return true. Example 2: 1 / \ 2 3 Binary tree [1,2,3],
return false.
URL: https://leetcode.com/problems/validate-binary-search-tree/
56
Validate Binary Search Tree
if self.isValidBST(root.left) == False:
return False
data = root.val
if data <= self.lastPrinted:
return False
self.lastPrinted = data
if self.isValidBST(root.right) == False:
return False
return True
57
Minimum Depth of Binary Tree
The minimum depth is the number of nodes along the shortest path from the root
node down to the nearest leaf node.
URL: https://leetcode.com/problems/minimum-depth-of-binary-tree/
58
Minimum Depth of Binary Tree
import sys
# Definition for a binary tree node.
# class TreeNode(object):
# def init (self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
if root.left != None:
left = self.minDepth(root.left)
else:
left = sys.maxsize
if root.right != None:
right = self.minDepth(root.right)
else:
right = sys.maxsize
59
Convert Sorted Array to Binary Search Tree
URL: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
60
Convert Sorted Array to Binary Search Tree
class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if nums == []:
return None
elif len(nums) == 1:
return TreeNode(nums[0])
else:
start = 0
end = len(nums) - 1
return self.to_bst(nums, start, end)
61
Flatten Binary Tree to Linked List
1
/ \
2 5
/ \ \
3 4 6
URL: https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
62
Flatten Binary Tree to Linked List
class Solution(object):
def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-plac
e instead.
"""
if root == None:
return root
stack = []
current = root
if current.right != None:
stack.append(current.right)
if current.left != None:
current.right = current.left
current.left = None
else:
if stack != []:
temp = stack.pop()
current.right = temp
current = current.right
63
Construct Binary Tree from Inorder and Preorder Traversal
Note: You may assume that duplicates do not exist in the tree.
URL: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-
inorder-traversal/
class Solution(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
if len(inorder) == 1:
return TreeNode(inorder[0])
return self.create_tree(inorder, 0, len(inorder) - 1, pr
eorder, 0, len(preorder) - 1)
64
Construct Binary Tree from Inorder and Preorder Traversal
root = TreeNode(preorder[low_preorder])
div_index = self.search_divindex(inorder, low_inorder, h
igh_inorder, root.val)
size_left_subtree = div_index - low_inorder
size_right_subtree = high_inorder - div_index
return root
65
Binary Tree Paths
["1->2->5", "1->3"]
URL: https://leetcode.com/problems/binary-tree-paths/
# class TreeNode:
# def init (self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @return {string[]}
def binaryTreePaths(self, root):
if root == None:
return []
else:
paths = []
current = root
s = []
s.append(current)
s.append(str(current.val))
while s != []:
#pathsum = s.pop()
path = s.pop()
current = s.pop()
66
Binary Tree Paths
if current.right:
rightstr = path + "->" + str(current.right.v
al)
s.append(current.right)
s.append(rightstr)
if current.left:
leftstr = path + "->" + str(current.left.val
)
s.append(current.left)
s.append(leftstr)
return paths
67
Recover Binary Search Tree
Note: A solution using O(n) space is pretty straight forward. Could you devise a
constant space solution?
URL: https://leetcode.com/problems/recover-binary-search-tree/
68
Recover Binary Search Tree
# class TreeNode(object):
# def init (self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def init (self):
self. prev = None
self. node1 = None
self. node2 = None
self.recoverTreeHelp(root.left)
if self. prev != None:
if self. prev.val > root.val:
if self. node1 == None:
self. node1 = self. prev
self. node2 = root
self. prev = root
self.recoverTreeHelp(root.right)
69
Path Sum II
Path Sum II
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum
equals the given sum.
For example: Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ / \
7 2 5 1 return [ [5,4,11,2], [5,8,4,5] ]
URL: https://leetcode.com/problems/path-sum-ii/
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
if root == None:
return []
else:
stack = []
paths = []
current = root
stack.append(current)
stack.append([current.val])
stack.append(current.val)
while stack != []:
pathsum = stack.pop()
path = stack.pop()
curr = stack.pop()
70
Path Sum II
71
Binary Level Order Traversal II
URL: https://leetcode.com/problems/binary-tree-level-order-traversal-ii/
import Queue
class Solution:
# @param {TreeNode} root
# @return {integer[][]}
def levelOrderBottom(self, root):
if root == None:
return []
else:
q = Queue.Queue()
q.put(root)
q.put("#")
levelOrderTraversal = []
level = []
stack = []
72
Binary Level Order Traversal II
level = []
else:
level.append(node.val)
if node.left:
q.put(node.left)
if node.right:
q.put(node.right)
while stack:
levelOrderTraversal.append(stack.pop())
return levelOrderTraversal
73
Kth Smallest Element in a BST
Follow up: What if the BST is modified (insert/delete operations) often and you
need to find the kth smallest frequently? How would you optimize the kthSmallest
routine?
Hint:
Try to utilize the property of a BST. What if you could modify the BST node's
structure? The optimal runtime complexity is O(height of BST).
URL: https://leetcode.com/problems/kth-smallest-element-in-a-bst/
74
Kth Smallest Element in a BST
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
if root == None:
return None
else:
stack = []
node = root
count = 0
while stack!= [] or node != None:
if node != None:
stack.append(node)
node = node.left
else:
inorder_node = stack.pop()
count += 1
if count == k:
return inorder_node.val
node = inorder_node.right
return None
75
Kth Smallest Element in a BST
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
stack = []*k
while True:
while root:
stack.append(root)
root = root.left
root = stack.pop()
if k == 1:
return root.val
else:
k -= 1
root = root.right
76
Construct Binary Tree from Inorder and Postorder Traversal
Note: You may assume that duplicates do not exist in the tree.
class Solution(object):
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
return self.create_tree(inorder, 0, len(inorder) -1 , po
storder, 0, len(postorder) - 1)
77
Construct Binary Tree from Inorder and Postorder Traversal
root = TreeNode(postorder[high_postorder])
return root
78
Binary Tree Right Side View
For example: Given the following binary tree, 1 <--- / \ 2 3 <--- \ \ 5 4 <--- You
should return [1, 3, 4].
URL: https://leetcode.com/problems/binary-tree-right-side-view/
79
Binary Tree Right Side View
import Queue
class Solution:
# @param {TreeNode} root
# @return {integer[]}
def rightSideView(self, root):
if root == None:
return []
else:
q = Queue.Queue()
q.put(root)
q.put("#")
rightSideView = []
level = []
while q.empty() == False:
node = q.get()
if node == "#":
if q.empty() == False:
q.put("#")
rightSideView.append(level[-1])
level = []
else:
level.append(node.val)
if node.left != None:
q.put(node.left)
if node.right != None:
q.put(node.right)
return rightSideView
80
Sum Root to Leaf Numbers
An example is the root-to-leaf path 1->2->3 which represents the number 123.
For example,
/ \ 2 3 The root-to-leaf path 1->2 represents the number 12. The root-to-leaf path
1->3 represents the number 13.
81
Sum Root to Leaf Numbers
class Solution(object):
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
else:
stack = []
paths = []
stack.append(root)
stack.append(str(root.val))
while stack != []:
path = stack.pop()
current = stack.pop()
if current.left == None and current.right == Non
e:
paths.append(int(path))
if current.right:
rightstr = path + str(current.right.val)
stack.append(current.right)
stack.append(rightstr)
if current.left:
leftstr = path + str(current.left.val)
stack.append(current.left)
stack.append(leftstr)
return sum(paths)
82
Binary Tree Zigzag Level Order Traversal
import Queue
class Solution:
# @param {TreeNode} root
# @return {integer[][]}
def zigzagLevelOrder(self, root):
if root == None:
return []
else:
q = Queue.Queue()
q.put(root)
q.put("#")
levelOrderTraversal = []
level = []
levelNo = 0
while q.empty() == False:
node = q.get()
if node == "#":
if q.empty() == False:
q.put("#")
if levelNo == 0 or levelNo % 2 == 0:
levelOrderTraversal.append(level)
83
Binary Tree Zigzag Level Order Traversal
else:
levelOrderTraversal.append(level[::-1])
level = []
levelNo += 1
else:
level.append(node.val)
if node.left:
q.put(node.left)
if node.right:
q.put(node.right)
return levelOrderTraversal
84
House Robber III
Determine the maximum amount of money the thief can rob tonight without
alerting the police.
URL: https://leetcode.com/problems/house-robber-iii/
85
House Robber III
class Solution(object):
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
else:
result = self.rob_max(root)
return max(result[0], result[1])
86
Inorder Successor in BST
Note: If the given node has no in-order successor in the tree, return null.
URL: https://leetcode.com/problems/inorder-successor-in-bst/
87
Inorder Successor in BST
class Solution(object):
def inorderSuccessor(self, root, p):
"""
:type root: TreeNode
:type p: TreeNode
:rtype: TreeNode
"""
successor = None
if root == None:
return None
if root.right == None:
return successor
root = root.right
while root.left != None:
root = root.left
return root
88
Binary Tree Longest Consecutive Sequence
The path refers to any sequence of nodes from some starting node to any node in
the tree along the parent-child connections. The longest consecutive path need to
be from parent to child (cannot be the reverse).
89
Binary Tree Longest Consecutive Sequence
size_q.put(1)
while node_q.empty() == False:
curr_node = node_q.get()
curr_size = size_q.get()
if curr_node.left:
left_size = curr_size
if curr_node.val == curr_node.left.val - 1:
left_size += 1
max_size = max(max_size, left_size)
else:
left_size = 1
node_q.put(curr_node.left)
size_q.put(left_size)
if curr_node.right:
right_size = curr_size
if curr_node.val == curr_node.right.val - 1:
right_size += 1
max_size = max(max_size, right_size)
else:
right_size = 1
node_q.put(curr_node.right)
size_q.put(right_size)
return max_size
90
Verify Preorder Sequence in Binary Search Tree
URL: https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-
tree/
import sys
class Solution(object):
def verifyPreorder(self, preorder):
"""
:type preorder: List[int]
:rtype: bool
"""
stack = []
root = -sys.maxsize-1
stack.append(entries)
return True
91
Binary Tree Upside Down
For example: Given a binary tree {1,2,3,4,5}, 1 / \ 2 3 / \ 4 5 return the root of the
binary tree [4,5,2,#,#,3,1]. 4 / \ 5 2 / \ 3 1
class Solution(object):
def upsideDownBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
p = root
parent = None
parent_right = None
while p:
left = p.left
p.left = parent_right
parent_right = p.right
p.right = parent
parent = p
p = left
return parent
92
Count Univalue Subtrees
A Uni-value subtree means all nodes of the subtree have the same value.
URL: https://leetcode.com/problems/count-univalue-subtrees/
93
Count Univalue Subtrees
class Solution(object):
def init (self):
self. count = 0
94
Number of Connected Components in an Undirected Graph
URL : https://leetcode.com/problems/number-of-connected-components-in-an-
undirected-graph/
import sys
from queue import Queue
class Vertex:
def init (self, node):
self.id = node
self.adjacent = {}
# Set distance to infinity for all nodes
self.distance = sys.maxsize
# Mark all nodes unvisited
self.visited = False
# Mark all nodes color with white
self.color = 'white'
# Predecessor
self.previous = None
def getConnections(self):
return self.adjacent.keys()
def getVertexID(self):
return self.id
95
Number of Connected Components in an Undirected Graph
def getDistance(self):
return self.distance
def getColor(self):
return self.color
def setVisited(self):
self.visited = True
class Graph:
def init (self):
self.vertDictionary = {}
self.numVertices = 0
96
Number of Connected Components in an Undirected Graph
else:
return None
self.vertDictionary[frm].addNeighbor(self.vertDictionary
[to], cost)
self.vertDictionary[to].addNeighbor(self.vertDictionary[
frm], cost)
def getVertices(self):
return self.vertDictionary.keys()
class Solution(object):
def countComponents(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: int
"""
if n == 1 and edges == []:
return 1
else:
G = Graph()
for entries in edges:
G.addEdge(entries[0], entries[1], 1)
count = 0
for vertex in G:
if vertex.getColor() == "white":
count += 1
97
Number of Connected Components in an Undirected Graph
self.bfs(vertex)
return count
n = 5
edges1 = [[0, 1], [1, 2], [3, 4]]
edges2 = [[0, 1], [1, 2], [2, 3], [3, 4]]
soln = Solution()
print(soln.countComponents(n, edges1))
print(soln.countComponents(n, edges2))
98
Course Schedule
Course Schedule
There are a total of n courses you have to take, labeled from 0 to n - 1.
Some courses may have prerequisites, for example to take course 0 you have to
first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible for
you to finish all courses?
For example:
2, [[1,0]] There are a total of 2 courses to take. To take course 1 you should have
finished course 0. So it is possible.
2, [[1,0],[0,1]] There are a total of 2 courses to take. To take course 1 you should
have finished course 0, and to take course 0 you should also have finished course
1. So it is impossible.
URL: https://leetcode.com/problems/course-schedule/
class Vertex:
99
Course Schedule
def get_neighbors(self):
return self.adjacent.keys()
def get_id(self):
return self.id
def get_indegree(self):
return self.indegree
def get_outdegree(self):
return self.outdegree
def get_predecessor(self):
return self.predecessor
def get_visit_time(self):
return self.visit_time
def get_finish_time(self):
return self.finish_time
def get_color(self):
100
Course Schedule
return self.color
class Graph:
if to not in self.vertex_dict:
self.add_vertex(to)
to_vertex = self.get_vertex(to)
101
Course Schedule
else:
to_vertex = self.vertex_dict[to]
from_vertex.add_neighbor(to_vertex, weight)
from_vertex.set_outdegree(from_vertex.get_outdegree() +
1)
to_vertex.set_indegree(to_vertex.get_indegree() + 1)
self.no_edges += 1
def get_edges(self):
edges = []
for u in self.vertex_dict:
for v in self.vertex_dict[u].get_neighbors():
u_id = u
#print(v)
v_id = v.get_id()
edges.append((u_id, v_id, self.vertex_dict[u].ge
t_weight(v)))
return edges
def get_vertices(self):
return self.vertex_dict
class DFS:
def dfs(self):
for vertex in self.graph.get_vertices():
if self.graph.vertex_dict[vertex].get_color() == "wh
ite":
self.dfs_visit(self.graph.vertex_dict[vertex])
102
Course Schedule
self.has_cycle = True
if vert.get_color() == "white":
vert.set_color("gray")
self.dfs_visit(vert)
node.set_color("black")
class Solution(object):
def canFinish(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: bool
"""
if not prerequisites:
return True
else:
g = Graph()
dfs_obj = DFS(g)
dfs_obj.dfs()
if dfs_obj.has_cycle == True:
return False
else:
return True
soln2 = Solution()
print(soln2.canFinish(2, [[1,0],[0,1]]))
103
Graph Valid Tree
For example:
Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true.
Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], return false.
Hint:
Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], what should your return? Is this case
a valid tree? According to the definition of tree on Wikipedia: “a tree is an
undirected graph in which any two vertices are connected by exactly one path. In
other words, any connected graph without simple cycles is a tree.”
URL: https://leetcode.com/problems/graph-valid-tree/
import sys
class Vertex:
def init (self, node):
self.id = node
self.adjacent = {}
# Set distance to infinity for all nodes
self.distance = sys.maxsize
# Mark all nodes unvisited
self.visited = False
# Mark all nodes color with white
self.color = 'white'
# Predecessor
self.previous = None
def getConnections(self):
104
Graph Valid Tree
return self.adjacent.keys()
def getVertexID(self):
return self.id
def getDistance(self):
return self.distance
def getColor(self):
return self.color
def setVisited(self):
self.visited = True
class Graph:
def init (self):
self.vertDictionary = {}
self.numVertices = 0
105
Graph Valid Tree
newVertex = Vertex(node)
self.vertDictionary[node] = newVertex
return newVertex
self.vertDictionary[frm].addNeighbor(self.vertDictionary
[to], cost)
self.vertDictionary[to].addNeighbor(self.vertDictionary[
frm], cost)
def getVertices(self):
return self.vertDictionary.keys()
class Solution:
def validTree(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: bool
"""
if n == 1 and len(edges) == 0:
return True
elif self.check_input(n, edges) == False:
106
Graph Valid Tree
return False
elif n == 0 and len(edges) > 0:
return False
elif n == 1 and len(edges) >= 1:
return False
else:
G = Graph()
for entries in edges:
G.addEdge(entries[0], entries[1], 1)
results = []
for vertex in G:
if vertex.getColor() == "white":
results.append(self.check_validity(vertex))
if len(results) > 1:
return False
else:
return results[0]
107
Graph Valid Tree
if nbr.getColor() == "white":
nbr.setColor("gray")
stack.append(nbr)
curr_node.setColor("black")
return True
108
Course Schedule 2
Course Schedule 2
There are a total of n courses you have to take, labeled from 0 to n - 1.
Some courses may have prerequisites, for example to take course 0 you have to
first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the
ordering of courses you should take to finish all courses.
There may be multiple correct orders, you just need to return one of them. If it is
impossible to finish all courses, return an empty array.
For example:
2, [[1,0]] There are a total of 2 courses to take. To take course 1 you should have
finished course 0. So the correct course order is [0,1]
URL: https://leetcode.com/problems/course-schedule-ii/
class Vertex:
def init (self, node):
self.id = node
self.adjacent = {}
# Set distance to infinity for all nodes
self.distance = sys.maxsize
# Mark all nodes unvisited
self.visited = False
# Mark all nodes color with white
self.color = 'white'
# Predecessor
109
Course Schedule 2
self.previous = None
#indegree of the vertex
self.indegree = 0
def getConnections(self):
return self.adjacent.keys()
def getVertexID(self):
return self.id
def getDistance(self):
return self.distance
def getColor(self):
return self.color
def setVisited(self):
self.visited = True
def getIndegree(self):
return self.indegree
110
Course Schedule 2
class DirectedGraph:
def init (self):
self.vertDictionary = {}
self.numVertices = 0
self.vertDictionary[frm].addNeighbor(self.vertDictionary
[to], cost)
self.vertDictionary[to].setIndegree(self.vertDictionary[
to].getIndegree() + 1)
def getVertices(self):
return self.vertDictionary.keys()
111
Course Schedule 2
class Solution:
def init (self):
self.has_cycle = False
return self.topsort(G)
112
Course Schedule 2
if len(topological_list) != len(nodes):
self.has_cycle = True
return topological_list
soln = Solution()
print(soln.findOrder(4, [[1,0],[2,0],[3,1],[3,2]]))
print(soln.findOrder(2, [[1,0]]))
print(soln.findOrder(3, [[1,0]]))
113
Number of Islands
Number of Islands
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An
island is surrounded by water and is formed by connecting adjacent lands
horizontally or vertically. You may assume all four edges of the grid are all
surrounded by water.
Example 1:
Example 2:
URL: https://leetcode.com/problems/number-of-islands/
114
Number of Islands
class Solution:
# @param {boolean[][]} grid a boolean 2D matrix
# @return {int} an integer
def numIslands(self, grid):
if not grid:
return 0
row = len(grid)
col = len(grid[0])
used = [[False for j in xrange(col)] for i in xrange(row
)]
count = 0
for i in xrange(row):
for j in xrange(col):
if grid[i][j] == '1' and not used[i][j]:
self.dfs(grid, used, row, col, i, j)
count += 1
return count
if x != 0:
self.dfs(grid, used, row, col, x - 1, y)
if x != row - 1:
self.dfs(grid, used, row, col, x + 1, y)
if y != 0:
self.dfs(grid, used, row, col, x, y - 1)
if y != col - 1:
self.dfs(grid, used, row, col, x, y + 1)
115
30DaysCoding.com
Arrays
Easy
- https://leetcode.com/problems/roman-to-integer/
- https://leetcode.com/problems/valid-parentheses/
- https://leetcode.com/problems/remove-duplicates-from-sorted-array/
- https://leetcode.com/problems/remove-element/
- https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
- https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
- https://leetcode.com/problems/intersection-of-two-arrays-ii/
- https://leetcode.com/problems/single-number/
- https://leetcode.com/problems/contains-duplicate/
- https://leetcode.com/problems/plus-one/
- https://leetcode.com/problems/move-zeroes/
- https://leetcode.com/problems/rotate-image/
Medium
- https://leetcode.com/problems/3sum/
- https://leetcode.com/problems/4sum/
- https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array
/
- https://leetcode.com/problems/group-anagrams/
- https://leetcode.com/problems/reduce-array-size-to-the-half/
- https://leetcode.com/problems/merge-intervals/
30DaysCoding.com
Linked list
Easy
- https://leetcode.com/problems/delete-node-in-a-linked-list/
- https://leetcode.com/problems/remove-nth-node-from-end-of-list/
- https://leetcode.com/problems/merge-two-sorted-lists/
- https://leetcode.com/problems/palindrome-linked-list/
- https://leetcode.com/problems/linked-list-cycle/
Medium
- https://leetcode.com/problems/intersection-of-two-linked-lists/
- https://leetcode.com/problems/remove-linked-list-elements/
- https://leetcode.com/problems/middle-of-the-linked-list/
- https://leetcode.com/problems/merge-k-sorted-lists/
Binary search
Easy
- https://leetcode.com/problems/binary-search/
- https://leetcode.com/problems/intersection-of-two-arrays/
- https://leetcode.com/problems/first-bad-version/
- https://leetcode.com/problems/arranging-coins/
- https://leetcode.com/problems/search-insert-position/
Medium
- https://leetcode.com/problems/search-in-rotated-sorted-array/
- https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array
/
- https://leetcode.com/problems/kth-smallest-element-in-a-bst/
- https://leetcode.com/problems/find-peak-element/
- https://leetcode.com/problems/split-array-largest-sum/
30DaysCoding.com
Sliding window
Read
- Leetcode Pattern 2 | Sliding Windows for Strings | by csgator | Leetcode Patterns
Easy/Medium
- https://leetcode.com/problems/longest-substring-without-repeating-characters/
- https://leetcode.com/problems/find-all-anagrams-in-a-string/description/
- https://leetcode.com/problems/minimum-window-substring/description/
- https://leetcode.com/problems/count-number-of-nice-subarrays/
- https://leetcode.com/problems/fruit-into-baskets/
2 pointers
- https://leetcode.com/problems/intersection-of-two-arrays/
- https://leetcode.com/problems/maximum-ascending-subarray-sum/
- https://leetcode.com/problems/backspace-string-compare/
- https://leetcode.com/problems/long-pressed-name/
- https://leetcode.com/problems/fruit-into-baskets/
- https://leetcode.com/problems/max-consecutive-ones-iii/
- https://leetcode.com/problems/container-with-most-water/
Stacks, Queues
- Easy
- https://leetcode.com/problems/valid-parentheses/
- https://leetcode.com/problems/implement-queue-using-stacks/
- https://leetcode.com/problems/min-stack/
- Medium
- https://leetcode.com/problems/design-circular-queue/
- https://leetcode.com/problems/decode-string/
30DaysCoding.com
- https://leetcode.com/problems/open-the-lock/
- https://leetcode.com/problems/daily-temperatures/
- https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/
BFS, DFS
Read
- Leetcode Pattern 1 | BFS + DFS == 25% of the problems — part 1
- Leetcode Pattern 1 | DFS + BFS == 25% of the problems — part 2
Questions
- https://leetcode.com/problems/flood-fill/
- https://leetcode.com/problems/binary-tree-preorder-traversal/
- https://leetcode.com/problems/number-of-islands/
- https://leetcode.com/problems/walls-and-gates/
- https://leetcode.com/problems/max-area-of-island/
- https://leetcode.com/problems/number-of-provinces/
- https://leetcode.com/problems/perfect-squares/
- https://leetcode.com/problems/course-schedule/
- https://www.geeksforgeeks.org/detect-cycle-undirected-graph/
- https://leetcode.com/problems/word-ladder/
- https://leetcode.com/problems/01-matrix/
- https://leetcode.com/problems/rotting-oranges/
- https://leetcode.com/problems/perfect-squares/
- https://leetcode.com/problems/all-paths-from-source-to-target/
- https://leetcode.com/problems/number-of-closed-islands/
Recursion
Easy
- 509. Fibonacci Number
- Reverse String
30DaysCoding.com
Backtracking
Read
- Leetcode Pattern 3 | Backtracking | by csgator | Leetcode Patterns
- A general approach to backtracking questions in Java (Subsets, Permutations,
Combination Sum, Palindrome Partitioning)
Easy
- Word Search
- Leetcode #78 Subsets
- 90. Subsets II
- Letter Case Permutation
Medium
- 39. Combination Sum
- 17. Letter Combinations of a Phone Number
- Combinations
- Leetcode : Combination Sum II
- 216. Combination Sum III
- Combination Sum IV
- 46. Permutations
- 47. Permutations II
- 31. Next Permutation
- 51. N-Queens
30DaysCoding.com
Trees
Read
- Leetcode Pattern 0 | Iterative traversals on Trees | by csgator | Leetcode Patterns
Easy
- https://leetcode.com/problems/binary-tree-preorder-traversal/
- https://leetcode.com/problems/binary-tree-inorder-traversal/
- https://leetcode.com/problems/binary-tree-postorder-traversal/
- https://leetcode.com/problems/validate-binary-search-tree/
- https://leetcode.com/problems/minimum-distance-between-bst-nodes/
- https://leetcode.com/problems/symmetric-tree/
- https://leetcode.com/problems/same-tree/
- https://leetcode.com/problems/path-sum/
- https://leetcode.com/problems/maximum-depth-of-binary-tree/
- https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
- Medium
- https://leetcode.com/problems/validate-binary-search-tree/
- https://leetcode.com/problems/binary-search-tree-iterator/
- https://leetcode.com/problems/unique-binary-search-trees/
- https://leetcode.com/problems/serialize-and-deserialize-bst/
- https://leetcode.com/problems/binary-tree-right-side-view/
- https://leetcode.com/problems/binary-tree-level-order-traversal/
- https://leetcode.com/problems/binary-tree-level-order-traversal-ii/
- https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
Dynamic programming
Easy
- https://leetcode.com/problems/maximum-subarray/
30DaysCoding.com
- https://leetcode.com/problems/fibonacci-number/
- https://leetcode.com/problems/climbing-stairs/
- https://leetcode.com/problems/min-cost-climbing-stairs/
- https://leetcode.com/problems/n-th-tribonacci-number/
Medium
- https://leetcode.com/problems/coin-change/
- https://leetcode.com/problems/minimum-falling-path-sum/
- https://leetcode.com/problems/minimum-cost-for-tickets/
- https://leetcode.com/problems/2-keys-keyboard/
- https://leetcode.com/problems/maximum-product-subarray/
- https://leetcode.com/problems/triangle/
- https://leetcode.com/problems/ones-and-zeroes/
- https://leetcode.com/problems/longest-arithmetic-subsequence/
- https://leetcode.com/problems/partition-equal-subset-sum/
- https://leetcode.com/problems/house-robber/
- https://leetcode.com/problems/decode-ways/
- https://leetcode.com/problems/word-break/
- https://leetcode.com/problems/edit-distance/
- https://leetcode.com/problems/longest-increasing-subsequence/
Graphs
Easy
- https://leetcode.com/problems/employee-importance/
- https://leetcode.com/problems/find-the-town-judge/
Medium
- https://leetcode.com/problems/course-schedule-ii/
- https://leetcode.com/problems/redundant-connection/
- https://leetcode.com/problems/surrounded-regions/
- https://leetcode.com/problems/accounts-merge/
30DaysCoding.com
- https://leetcode.com/problems/network-delay-time/
- https://leetcode.com/problems/is-graph-bipartite/
- https://leetcode.com/problems/find-eventual-safe-states/
- https://leetcode.com/problems/keys-and-rooms/
- https://leetcode.com/problems/possible-bipartition/
- https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/
- https://leetcode.com/problems/rotting-oranges/
- https://leetcode.com/problems/number-of-operations-to-make-network-connected/
Additional questions
- https://leetcode.com/problems/longest-common-prefix/
- https://leetcode.com/problems/implement-trie-prefix-tree/
Random
- https://leetcode.com/explore/
Videos
Some long videos, to revise or study in one long stretch!
- Data Structures Easy to Advanced Course - Full Tutorial from a Google Engineer
- Introduction to Data Structures & Algorithms | Course Details & Prerequisites
- Algorithms Course - Graph Theory Tutorial from a Google Engineer
Most frequently asked
coding questions with
solutions in Python
Part-1
1 1
Table of Contents
Heaps 1.1
Arrays 1.2
2 Sum II 1.2.1
3 Sum 1.2.7
3 2
Trapping Rain Water 1.2.25
Maximum Subarray 1.2.26
Strings 1.2
Maths 1.4
Pow(x,n) 1.4.3
Subsets 1.4.4
Subsets II 1.4.5
4 3
Happy Number 1.4.10
Count Primes 1.4.11
Matrix 1.4.28
Design 1.5.6
5 4
Merge K Sorted Linked Lists
URL: https://leetcode.com/problems/merge-k-sorted-lists/
113 5
Merge K Sorted Linked Lists
import heapq
# Definition for singly-linked list.
class ListNode(object):
def init (self, x):
self.val = x
self.next = None
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if lists == [] or lists == None:
return None
else:
pq = []
for i in range(len(lists)):
if lists[i] != None:
item = (lists[i].val, i, lists[i])
heapq.heappush(pq, item)
dummy = ListNode(0)
p = dummy
while pq != []:
heap_item = heapq.heappop(pq)
p.next = heap_item[2]
p = p.next
if heap_item[2].next != None:
item = (heap_item[2].next.val, heap_item[1],
heap_item[2].next)
heapq.heappush(pq, item)
return dummy.next
114 6
Kth Largest Element in an Array
URL: https://leetcode.com/problems/kth-largest-element-in-an-array/
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if nums == []:
return nums
else:
heap = []
for i in range(0, k):
heapq.heappush(heap, (nums[i], i))
return heapq.heappop(heap)[0]
115 7
2 Sum II
1 Sum II
Given an array of integers that is already sorted in ascending order, find two
numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add
up to the target, where index1 must be less than index2. Please note that your
returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
URL: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
if len(numbers) == 0:
return [-1]
else:
start = 0
end = len(numbers) - 1
while start < end:
curr_sum = numbers[start] + numbers[end]
if curr_sum == target:
return [start+1, end+1]
elif curr_sum < target:
start += 1
elif curr_sum > target:
end -= 1
return [-1]
116 8
2 Sum III
2 Sum III
Design and implement a TwoSum class. It should support the following
operations: add and find.
add - Add the number to an internal data structure. find - Find if there exists any
pair of numbers which sum is equal to the value.
For example, add(1); add(3); add(5); find(4) -> true find(7) -> false
URL: https://leetcode.com/problems/two-sum-iii-data-structure-design/
import collections
class TwoSum(object):
117 9
2 Sum III
if len(self. num_list) == 0:
return False
else:
for entries in self. num_list.keys():
target = value - entries
if (target in self. num_list) and (entries != t
arget or self. num_list[target] > 1):
return True
return False
118 10
Contains Duplicate
Contains Duplicate
Given an array of integers, find if the array contains any duplicates. Your function
should return true if any value appears at least twice in the array, and it should
return false if every element is distinct.
URL: https://leetcode.com/problems/contains-duplicate/
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums:
return False
elif len(nums) == 1:
return False
else:
dup_dict = {}
119 11
Rotate Array
Rotate Array
Rotate an array of n elements to the right by k steps.
Note: Try to come up as many solutions as you can, there are at least 3 different
ways to solve this problem.
URL: https://leetcode.com/problems/rotate-array/
120 12
Rotate Array
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-plac
e instead.
"""
n = len(nums)
if n < 2 or k == 0:
pass
else:
if k >= n:
k = k % n
a = n - k
self.reverse(nums, 0, a-1)
self.reverse(nums, a, n-1)
self.reverse(nums, 0, n-1)
121 13
3 Sum Smaller
3 Sum Smaller
Given an array of n integers nums and a target, find the number of index triplets i,
j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] <
target.
Return 2. Because there are two triplets which sums are less than 2:
[-2, 0, 1] [-2, 0, 3]
URL: https://leetcode.com/problems/3sum-smaller/
122 14
3 Sum Smaller
class Solution(object):
def threeSumSmaller(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if len(nums) == 0 or len(nums) == 2 or len(nums) == 1:
return len([])
else:
triplet_list = []
sorted_nums = sorted(nums)
for i in range(0, len(nums) - 2):
start = i + 1
end = len(nums) - 1
while start < end:
curr_sum = sorted_nums[i] + sorted_nums[star
t] + sorted_nums[end]
if curr_sum == target:
end -= 1
elif curr_sum < target:
triplet = (sorted_nums[i], sorted_nums[s
tart], sorted_nums[end])
triplet_list.append(triplet)
start += 1
elif curr_sum > target:
end -= 1
print(triplet_list)
#return len([list(entries) for entries in set(triple
t_list)])
return len(triplet_list)
123 15
3 Sum Closest
3 Sum Closest
Given an array S of n integers, find three integers in S such that the sum is closest
to a given number, target. Return the sum of the three integers. You may assume
that each input would have exactly one solution.
URL: https://leetcode.com/problems/3sum-closest/
124 16
3 Sum Closest
import sys
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if len(nums) in [0,1,2]:
return 0
else:
min_diff = sys.maxsize
result = 0
sorted_nums = sorted(nums)
for i in range(len(nums)):
start = i + 1
end = len(nums) - 1
while start < end:
curr_sum = sorted_nums[i] + sorted_nums[star
t] + sorted_nums[end]
diff = abs(curr_sum - target)
if diff == 0:
return curr_sum
if diff < min_diff:
min_diff = diff
result = curr_sum
if curr_sum <= target:
start += 1
else:
end -= 1
return result
soln = Solution()
print(soln.threeSumClosest([-1, 2, 1, -4], 1))
print(soln.threeSumClosest([-1, 2, 1, -4], 3))
125 17
3 Sum
3 Sum
Given an array S of n integers, are there elements a, b, c in S such that a + b + c
= 0? Find all unique triplets in the array which gives the sum of zero.
URL: https://leetcode.com/problems/3sum/
126 18
3 Sum
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums) == 0 or len(nums) == 2 or len(nums) == 1:
return []
else:
sum_zero_list = []
sorted_nums = sorted(nums)
for i in range(0, len(nums) - 2):
start = i + 1
end = len(nums) - 1
while start < end:
curr_sum = sorted_nums[i] + sorted_nums[star
t] + sorted_nums[end]
if curr_sum == 0:
zero_triplet = (sorted_nums[i], sorted_n
ums[start], sorted_nums[end])
sum_zero_list.append(zero_triplet)
start += 1
end -= 1
elif curr_sum < 0:
start += 1
elif curr_sum > 0:
end -= 1
127 19
Two Sum
Two Sum
Given an array of integers, return indices of the two numbers such that they add
up to a specific target.
You may assume that each input would have exactly one solution.
URL: https://leetcode.com/problems/two-sum/
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict = {}
for i in range(len(nums)):
x = nums[i]
if target-x in dict:
return (dict[target-x], i)
dict[x] = i
128 20
Plus One
Plus One
Given a non-negative number represented as an array of digits, plus one to the
number.
The digits are stored such that the most significant digit is at the head of the list.
URL: https://leetcode.com/problems/plus-one/
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
if len(digits) <= 0:
return [0]
else:
carry = 1
i = len(digits)-1
running_sum = 0
new_digits = []
while i >= 0:
running_sum = digits[i] + carry
if running_sum >= 10:
carry = 1
else:
carry = 0
new_digits.append(running_sum % 10)
i -= 1
if carry == 1:
new_digits.append(1)
return new_digits[::-1]
else:
return new_digits[::-1]
129 21
Best Time to Buy and Sell Stock
If you were only permitted to complete at most one transaction (ie, buy one and
sell one share of the stock), design an algorithm to find the maximum profit.
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than
buying price) Example 2: Input: [7, 6, 4, 3, 1] Output: 0
URL: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) == 0:
return 0
else:
max_profit = 0
min_price = prices[0]
for i in range(len(prices)):
profit = prices[i] - min_price
max_profit = max(profit, max_profit)
min_price = min(min_price, prices[i])
return max_profit
130 22
Shortest Word Distance
Note: You may assume that word1 does not equal to word2, and word1 and word2
are both in the list.
URL: https://leetcode.com/problems/shortest-word-distance/
131 23
Shortest Word Distance
import sys
class Solution(object):
def shortestDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
word2_positions = []
word1_positions = []
for i in range(len(words)):
if word1 == words[i]:
word1_positions.append(i)
if word2 == words[i]:
word2_positions.append(i)
min_dist = sys.maxint
return min_dist
132 24
Move Zeroes
Move Zeroes
Given an array nums, write a function to move all 0's to the end of it while
maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should
be [1, 3, 12, 0, 0].
Note: You must do this in-place without making a copy of the array. Minimize the
total number of operations.
URL:https://leetcode.com/problems/move-zeroes/
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-plac
e instead.
"""
i = 0
j = 0
while j < len(nums):
if nums[j] == 0:
j += 1
else:
nums[i] = nums[j]
i += 1
j += 1
133 25
Contains Duplicate II
Contains Duplicate II
Given an array of integers and an integer k, find out whether there are two distinct
indices i and j in the array such that nums[i] = nums[j] and the difference between i
and j is at most k.
URL: https://leetcode.com/problems/contains-duplicate-ii/
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
if not nums:
return False
elif len(nums) == 1:
return False
elif len(nums) == 2:
if nums[0] != nums[1]:
return False
else:
if nums[0] == nums[1] and k >= 1:
return True
else:
return False
else:
index_dict = {}
for i in range(len(nums)):
if nums[i] in index_dict:
prev_index = index_dict[nums[i]]
if i - prev_index <= k:
return True
index_dict[nums[i]] = i
return False
134 26
Majority Element
Majority Element
Given an array of size n, find the majority element. The majority element is the
element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always
exist in the array.
URL: https://leetcode.com/problems/majority-element/
135 27
Majority Element
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
candidate = self.get_candidate(nums)
candidate_count = 0
if candidate != None:
for entries in nums:
if entries == candidate:
candidate_count += 1
if candidate_count >= len(nums)//2:
return candidate
else:
return None
else:
return None
136 28
Remove Duplicates from Sorted Array
Do not allocate extra space for another array, you must do this in place with
constant memory.
Your function should return length = 2, with the first two elements of nums being 1
and 2 respectively. It doesn't matter what you leave beyond the new length.
URL: https://leetcode.com/problems/remove-duplicates-from-sorted-array/
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) < 2:
return len(nums)
else:
j = 0
i = 1
while i < len(nums):
if nums[j] == nums[i]:
i += 1
else:
j += 1
nums[j] = nums[i]
i += 1
return j+1
137 29
Nested List Weight Sum
Each element is either an integer, or a list -- whose elements may also be integers
or other lists.
Example 1: Given the list [[1,1],2,[1,1]], return 10. (four 1's at depth 2, one 2 at
depth 1)
Example 2: Given the list [1,[4,[6]]], return 27. (one 1 at depth 1, one 4 at depth 2,
and one 6 at depth 3; 1 + 42 + 63 = 27)
URL: https://leetcode.com/problems/nested-list-weight-sum/
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementa
tion
# """
#class NestedInteger(object):
# def isInteger(self):
# """
# @return True if this NestedInteger holds a single integ
er, rather than a nested list.
# :rtype bool
# """
#
# def getInteger(self):
# """
# @return the single integer that this NestedInteger hold
s, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# :rtype int
# """
#
# def getList(self):
138 30
Nested List Weight Sum
# """
# @return the nested list that this NestedInteger holds,
if it holds a nested list
# Return None if this NestedInteger holds a single intege
r
# :rtype List[NestedInteger]
# """
class Solution(object):
def depthSum(self, nestedList):
"""
:type nestedList: List[NestedInteger]
:rtype: int
"""
return self.depthSum_helper(nestedList, 1)
return sum
139 31
Nested List Weighted Sum II
Each element is either an integer, or a list -- whose elements may also be integers
or other lists.
Different from the previous question where weight is increasing from root to leaf,
now the weight is defined from bottom up. i.e., the leaf level integers have weight
1, and the root level integers have the largest weight.
Example 1: Given the list [[1,1],2,[1,1]], return 8. (four 1's at depth 1, one 2 at
depth 2)
Example 2: Given the list [1,[4,[6]]], return 17. (one 1 at depth 3, one 4 at depth 2,
and one 6 at depth 1; 13 + 42 + 6*1 = 17)
URL: https://leetcode.com/problems/nested-list-weight-sum-ii/
140 32
Remove Element
Remove Element
Given an array and a value, remove all instances of that value in place and return
the new length.
Do not allocate extra space for another array, you must do this in place with
constant memory.
The order of elements can be changed. It doesn't matter what you leave beyond
the new length.
Your function should return length = 2, with the first two elements of nums being 2.
URL: https://leetcode.com/problems/remove-element/
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
if val == []:
return 0
else:
i = 0
j = 0
while j < len(nums):
if nums[j] == val:
j += 1
else:
nums[i] = nums[j]
i += 1
j += 1
return len(nums[0:i])
141 33
Intersection of Two Arrays II
Example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note: Each element in the result should appear as many times as it shows in both
arrays. The result can be in any order. Follow up: What if the given array is
already sorted? How would you optimize your algorithm? What if nums1's size is
small compared to nums2's size? Which algorithm is better? What if elements of
nums2 are stored on disk, and the memory is limited such that you cannot load all
elements into the memory at once?
URL: https://leetcode.com/problems/intersection-of-two-arrays-ii/
142 34
Intersection of Two Arrays II
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
sorted_nums1 = sorted(nums1)
sorted_nums2 = sorted(nums2)
i = 0
j = 0
intersect_list = []
return intersect_list
143 35
Merge Sorted Arrays
Note: You may assume that nums1 has enough space (size that is greater or
equal to m + n) to hold additional elements from nums2. The number of elements
initialized in nums1 and nums2 are m and n respectively.
URL: https://leetcode.com/problems/merge-sorted-array/
144 36
Merge Sorted Arrays
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-pla
ce instead.
"""
last1 = m - 1
last2 = n - 1
last = m + n - 1
145 37
Reverse Vowels of a String
URL: https://leetcode.com/problems/reverse-vowels-of-a-string/
146 38
Reverse Vowels of a String
class Solution(object):
def init (self):
self. vowels = {"a" : True, "e" : True, "i" : True, "o"
: True, "u" : True, "A" : True, "E" : True, "I" : True, "O" : T
rue, "U" : True,}
while i < j:
if s[i] not in self. vowels:
i += 1
continue
if s[j] not in self. vowels:
j -= 1
continue
s[i], s[j] = s[j], s[i]
i += 1
j -= 1
return "".join(s)
147 39
Intersection of Two Arrays
Example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note: Each element in the result must be unique. The result can be in any order.
URL: https://leetcode.com/problems/intersection-of-two-arrays/
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1 = sorted(nums1)
nums2 = sorted(nums2)
intersection = {}
i = 0
j = 0
while i < len(nums1) and j < len(nums2):
if nums1[i] < nums2[j]:
i += 1
elif nums2[j] < nums1[i]:
j += 1
else:
intersection[nums1[i]] = nums1[i]
i += 1
j += 1
return intersection.keys()
148 40
Container With Most Water
URL: https://leetcode.com/problems/container-with-most-water/
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
max_area = 0
i = 0
j = len(height) - 1
while i<j:
max_area = max(max_area, min(height[i], height[j])*(
j-i))
if height[i] < height[j]:
i += 1
else:
j -= 1
return max_area
149 41
Product of Array Except Self
Follow up:
Could you solve it with constant space complexity? (Note: The output arraydoes
notcount as extra space for the purpose of space complexity analysis.)
URL: https://leetcode.com/problems/product-of-array-except-self/
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
before = [1]*len(nums)
after = [1]*len(nums)
product = [0]*len(nums)
return product
150 42
Trapping Rain Water
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1] , return 6 .
URL: https://leetcode.com/problems/trapping-rain-water/
151 43
Trapping Rain Water
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
maxseenright = 0
maxseenright_arr = [0]*len(height)
maxseenleft = 0
rainwater = 0
return rainwater
152 44
Maximum Subarray
Find the contiguous subarray within an array (containing at least one number)
which has the largest sum.
URL: https://leetcode.com/problems/maximum-subarray/
import sys
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums == []:
return 0
elif len(nums) == 1:
return nums[0]
elif len(nums) == 2:
return max(nums[0], nums[1], nums[0]+nums[1])
else:
all_neg = True
for entries in nums:
if entries >= 0:
all_neg = False
if all_neg == False:
curr_sum = 0
max_sum = - sys.maxsize - 1
for i in range(len(nums)):
curr_sum += nums[i]
if curr_sum < 0:
curr_sum = 0
if curr_sum > max_sum:
max_sum = curr_sum
return max_sum
else:
return max(nums)
153 45
Best Time to Buy and Sell Stock II
Say you have an array for which theithelement is the price of a given stock on
dayi.
Design an algorithm to find the maximum profit. You may complete as many
transactions as you like (ie, buy one and sell one share of the stock multiple
times). However, you may not engage in multiple transactions at the same time
(ie, you must sell the stock before you buy again).
URL: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if prices == []:
return 0
else:
profit = 0
for i in range(1, len(prices)):
curr_profit = prices[i] - prices[i-1]
if curr_profit > 0:
profit += curr_profit
return profit
154 46
Find Minimum in Rotated Sorted Array
URL: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
start = 0
end = len(nums) - 1
155 47
Pascal's Triangle
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
URL: https://leetcode.com/problems/pascals-triangle/
156 48
Pascal's Triangle
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows <= 0:
return []
result = []
pre = []
pre.append(1)
result.append(pre)
return result
157 49
Pascal's Triangle II
Note:
Could you optimize your algorithm to use only O(k) extra space?
URL: https://leetcode.com/problems/pascals-triangle-ii/
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
if rowIndex < 0:
return []
elif rowIndex == 0:
return [1]
else:
pre = []
pre.append(1)
for i in range(1, rowIndex+1):
curr = []
curr.append(1)
for j in range(0, len(pre) - 1):
curr.append(pre[j]+pre[j+1])
curr.append(1)
pre = curr
return pre
158 50
Summary Ranges
Given a sorted integer array without duplicates, return the summary of its ranges.
URL: https://leetcode.com/problems/summary-ranges/
class Solution(object):
def summaryRanges(self, nums):
"""
:type nums: List[int]
:rtype: List[str]
"""
if nums == []:
return nums
elif len(nums) == 1:
return [str(nums[0])]
else:
start = nums[0]
end = nums[0]
res = []
for i in range(1, len(nums)):
if nums[i] - nums[i-1] == 1:
end = nums[i]
else:
res.append(self.to_str(start, end))
start = end = nums[i]
res.append(self.to_str(start, end))
return res
159 51
Missing Number
For example,
Givennums= [0, 1, 3] return 2 .
Note:
Your algorithm should run in linear runtime complexity. Could you implement it
using only constant extra space complexity?
URL: https://leetcode.com/problems/missing-number/
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return None
else:
xor_prod = 0
xor_prod_index = 0
for i in range(len(nums)+1):
xor_prod_index ^= i
for i in range(len(nums)):
xor_prod ^= nums[i]
160 52
Valid Anagram
Valid Anagram
Given two strings s and t, write a function to determine if t is an anagram of s.
Note: You may assume the string contains only lowercase alphabets.
URL: https://leetcode.com/problems/valid-anagram/
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t):
return False
elif sorted(s) == sorted(t):
return True
else:
return False
161 53
Valid Palindrome
Valid Palindrome
Given a string, determine if it is a palindrome, considering only alphanumeric
characters and ignoring cases.
For example, "A man, a plan, a canal: Panama" is a palindrome. "race a car" is
not a palindrome.
Note: Have you consider that the string might be empty? This is a good question
to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
URL: https://leetcode.com/problems/valid-palindrome/
import re
class Solution:
# @param {string} s
# @return {boolean}
def isPalindrome(self, s):
if len(s) == 0:
return True
else:
start = 0
s = s.lower()
newS = re.sub(r"[^a-zA-Z0-9]","",s)
end = len(newS)-1
while start < end:
if newS[start] == newS[end]:
start = start + 1
end = end - 1
else:
return False
return True
162 54
Word Pattern
Word Pattern
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in
pattern and a non-empty word in str.
Examples: pattern = "abba", str = "dog cat cat dog" should return true. pattern =
"abba", str = "dog cat cat fish" should return false. pattern = "aaaa", str = "dog cat
cat dog" should return false. pattern = "abba", str = "dog dog dog dog" should
return false. Notes: You may assume pattern contains only lowercase letters, and
str contains lowercase letters separated by a single space.
URL: https://leetcode.com/problems/word-pattern/
163 55
Word Pattern
class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
if pattern == None or str == None:
return False
else:
len_str = len(str.split(" "))
len_pattern = len(pattern)
if len_str != len_pattern:
return False
str = str.split(" ")
lookup = {}
for i in range(0, len(pattern)):
s = str[i]
p = pattern[i]
if p in lookup:
if lookup[p] != s:
return False
else:
if s in lookup.values():
return False
lookup[p] = s
return True
pattern = "abba"
str = "dog cat cat dog"
soln = Solution()
print(soln.wordPattern(pattern, str))
164 56
Valid Parentheses
Valid Parentheses
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the
input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]"
and "([)]" are not.
URL: https://leetcode.com/problems/valid-parentheses/
165 57
Valid Parentheses
class Solution:
# @param {string} s
# @return {boolean}
def isValid(self, s):
if s == []:
return False
else:
stack = []
balanced = True
index = 0
while index < len(s) and balanced:
symbol = s[index]
if symbol in "({[":
stack.append(symbol)
else:
if stack == []:
balanced = False
else:
top = stack.pop()
if not self.matches(top,symbol):
balanced = False
index = index + 1
def matches(self,open,close):
openings = "({["
closings = ")}]"
166 58
Isomorphic Strings
Isomorphic Strings
Given two strings s and t, determine if they are isomorphic.
Note: You may assume both s and t have the same length.
URL: https://leetcode.com/problems/isomorphic-strings/
167 59
Isomorphic Strings
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if s == None or t == None:
return False
elif s == "" and t == "":
return True
else:
if len(s) != len(t):
return False
lookup = {}
for i in range(0, len(s)):
c1 = s[i]
c2 = t[i]
if c1 in lookup:
if lookup[c1] != c2:
return False
else:
if c2 in lookup.values():
return False
lookup[c1] = c2
return True
168 60
Reverse String
Reverse String
Write a function that takes a string as input and returns the string reversed.
URL: https://leetcode.com/problems/reverse-string/
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
i = 0
j = len(s) - 1
while i < j:
temp = current_str[i]
current_str[i] = current_str[j]
current_str[j] = temp
j -= 1
i += 1
return "".join(current_str)
169 61
Sum of Two Integers
URL: https://leetcode.com/problems/sum-of-two-integers/
class Solution(object):
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
if b == 0:
return a
sum = a ^ b
carry = (a & b) << 1
return self.getSum(sum, carry)
170 62
Single Number
Single Number
Given an array of integers, every element appears twice except for one. Find that
single one.
Note: Your algorithm should have a linear runtime complexity. Could you
implement it without using extra memory?
URL: https://leetcode.com/problems/single-number/
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return None
elif len(nums) == 1:
return nums[0]
else:
xor_prod = 0
for entries in nums:
xor_prod ^= entries
return xor_prod
171 63
Reverse Integer
Reverse Integer
Reverse digits of an integer.
Have you thought about this? Here are some good questions to ask before
coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10,
100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-
bit integer, then the reverse of 1000000003 overflows. How should you handle
such cases?
For the purpose of this problem, assume that your function returns 0 when the
reversed integer overflows.
URL: https://leetcode.com/problems/reverse-integer/
import sys
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x < 0:
return -self.reverse(-x)
result = 0
while x:
result = result * 10 + x % 10
x /= 10
return result if result <= 0x7fffffff else 0
172 64
Palindrome Number
Palindrome Number
Determine whether an integer is a palindrome. Do this without extra space.
If you are thinking of converting the integer to string, note the restriction of using
extra space.
You could also try reversing an integer. However, if you have solved the problem
"Reverse Integer", you know that the reversed integer might overflow. How would
you handle such case?
URL: https://leetcode.com/problems/palindrome-number/
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
rev = 0
copy = x
while copy != 0:
rev = rev*10 + copy%10
copy = copy/10
if rev == x:
return True
else:
return False
173 65
Pow(x,n)
Pow(x,n)
Implement pow(x, n).
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n < 0:
return 1/self.power(x, -n)
else:
return self.power(x, n)
v = self.power(x, n//2)
if n % 2 == 0:
return v * v
else:
return v * v * x
174 66
Subsets
Subsets
Given a set of distinct integers, nums, return all possible subsets.
URL: https://leetcode.com/problems/subsets/
Solution1:
class Solution(object):
def subsets(self, S):
def dfs(depth, start, valuelist):
res.append(valuelist)
if depth == len(S): return
for i in range(start, len(S)):
dfs(depth+1, i+1, valuelist+[S[i]])
S.sort()
res = []
dfs(0, 0, [])
return res
Solution2:
175 67
Subsets
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
n = 1 << len(nums)
result = []
for i in range(0, n):
subset = self.convert(i, nums)
result.append(subset)
return result
k >>= 1
index += 1
return res
176 68
Subsets II
Subsets II
Given a collection of integers that might contain duplicates, nums, return all
possible subsets.
URL: https://leetcode.com/problems/subsets-ii/
177 69
Subsets II
class Solution(object):
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
n = 1 << len(nums)
result = []
for i in range(0, n):
subset = self.convert(i, nums)
result.append(tuple(sorted(subset)))
result = set(result)
return [list(entries) for entries in result]
k >>= 1
index += 1
return res
178 70
Self Crossing
Self Crossing
You are given an array x of n positive numbers. You start at point (0,0) and moves
x[0] metres to the north, then x[1] metres to the west, x[2] metres to the south, x[3]
metres to the east and so on. In other words, after each move your direction
changes counter-clockwise.
Write a one-pass algorithm with O(1) extra space to determine, if your path
crosses itself, or not.
Return false (not self crossing) Example 3: Given x = [1, 1, 1, 1], ┌───┐ │ │
└───┼>
URL: https://leetcode.com/problems/self-crossing/
179 71
Self Crossing
class Solution(object):
def isSelfCrossing(self, x):
"""
:type x: List[int]
:rtype: bool
"""
if x == None or len(x) <= 3:
return False
else:
for i in range(3, len(x)):
if (x[i-3] >= x[i-1]) and (x[i-2] <= x[i]):
return True
if (i >= 4) and (x[i-4] + x[i] >= x[i-2]) and (x
[i-3] == x[i-1]):
return True
if (i>=5) and (x[i-5] <= x[i-3]) and (x[i-4] <=
x[i-2]) and (x[i-1] <= x[i-3]) and (x[i-1] >= x[i-3] - x[i-5]) a
nd (x[i] >= x[i-2] - x[i-4]) and (x[i] <= x[i-2]):
return True
return False
180 72
Paint Fence
Paint Fence
There is a fence with n posts, each post can be painted with one of the k colors.
You have to paint all the posts such that no more than two adjacent fence posts
have the same color.
Return the total number of ways you can paint the fence.
URL: https://leetcode.com/problems/paint-fence/
class Solution(object):
def numWays(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
dp = [0, k, k*k, 0]
if n <= 2:
return dp[n]
for i in range(2, n):
dp[3] = (k-1)*(dp[1] + dp[2])
dp[1] = dp[2]
dp[2] = dp[3]
return dp[3]
181 73
Bulb Switcher
Bulb Switcher
There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn
off every second bulb. On the third round, you toggle every third bulb (turning on if
it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth
round, you only toggle the last bulb. Find how many bulbs are on after n rounds.
Example:
Given n = 3.
At first, the three bulbs are [off, off, off]. After first round, the three bulbs are [on,
on, on]. After second round, the three bulbs are [on, off, on]. After third round, the
three bulbs are [on, off, off].
URL: https://leetcode.com/problems/bulb-switcher/
import math
class Solution(object):
def bulbSwitch(self, n):
"""
:type n: int
:rtype: int
"""
return int(math.sqrt(n))
182 74
Nim Game
Nim Game
You are playing the following Nim Game with your friend: There is a heap of
stones on the table, each time one of you take turns to remove 1 to 3 stones. The
one who removes the last stone will be the winner. You will take the first turn to
remove the stones.
Both of you are very clever and have optimal strategies for the game. Write a
function to determine whether you can win the game given the number of stones
in the heap.
For example, if there are 4 stones in the heap, then you will never win the game:
no matter 1, 2, or 3 stones you remove, the last stone will always be removed by
your friend.
Hint:
If there are 5 stones in the heap, could you figure out a way to remove the stones
such that you will always be the winner?
URL: https://leetcode.com/problems/nim-game/
class Solution(object):
def canWinNim(self, n):
"""
:type n: int
:rtype: bool
"""
return n%4 != 0
183 75
Rotate Image
Rotate Image
You are given an n x n 2D matrix representing an image.
URL: https://leetcode.com/problems/rotate-image/
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-pl
ace instead.
"""
if matrix == None or matrix == []:
pass
else:
n = len(matrix)
for layer in range(0, n//2):
first = layer
last = n - 1 - layer
for i in range(first, last):
offset = i - first
top = matrix[first][i]
matrix[first][i] = matrix[last - offset][fir
st]
matrix[last - offset][first] = matrix[last][
last - offset]
matrix[last][last - offset] = matrix[i][last
]
matrix[i][last] = top
184 76
Set Matrix Zeroes
Follow up: Did you use extra space? A straight forward solution using O(mn)
space is probably a bad idea. A simple improvement uses O(m + n) space, but still
not the best solution. Could you devise a constant space solution?
URL: https://leetcode.com/problems/set-matrix-zeroes/
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-pl
ace instead.
"""
if matrix == None or len(matrix) == 0:
pass
elif len(matrix) == 1 and len(matrix[0]) == 1:
pass
else:
rows_with_0 = [False]*len(matrix)
cols_with_0 = [False]*len(matrix[0])
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == 0:
rows_with_0[i] = True
cols_with_0[j] = True
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if rows_with_0[i] or cols_with_0[j]:
matrix[i][j] = 0
185 77
Set Matrix Zeroes
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-pl
ace instead.
"""
first_row = False
first_col = False
for j in range(len(matrix[0])):
if matrix[0][j] == 0:
first_row = True
for i in range(len(matrix)):
if matrix[i][0] == 0:
first_col = True
if first_col:
for i in range(len(matrix)):
matrix[i][0] = 0
if first_row:
for i in range(len(matrix[0])):
matrix[0][i] = 0
186 78
Search a 2D Matrix
Search a 2D Matrix
Write an efficient algorithm that searches for a value in an m x n matrix. This
matrix has the following properties:
Integers in each row are sorted from left to right. The first integer of each row is
greater than the last integer of the previous row. For example,
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] Given target = 3, return true.
187 79
Search a 2D Matrix
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if matrix == []:
return False
else:
no_rows = len(matrix)
no_cols = len(matrix[0])
r = 0
c = no_cols - 1
while r < no_rows and c >= 0:
if target == matrix[r][c]:
return True
elif target > matrix[r][c]:
r += 1
elif target < matrix[r][c]:
c -= 1
return False
188 80
Search a 2D Matrix II
Search a 2D Matrix II
Write an efficient algorithm that searches for a value in an m x n matrix. This
matrix has the following properties:
Integers in each row are sorted in ascending from left to right. Integers in each
column are sorted in ascending from top to bottom. For example,
[ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23,
26, 30] ] Given target = 5, return true.
URL: https://leetcode.com/problems/search-a-2d-matrix-ii/
189 81
Search a 2D Matrix II
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if matrix == []:
return False
else:
no_rows = len(matrix)
no_cols = len(matrix[0])
190 82
Spiral Matrix
Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the
matrix in spiral order.
URL: https://leetcode.com/problems/spiral-matrix/
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if matrix == None or matrix == []:
return matrix
else:
#no of rows
m = len(matrix)
#no of columns
n = len(matrix[0])
#starting row
k = 0
#starting column
l = 0
191 83
Spiral Matrix
s
for i in range(k, m):
spiral.append(matrix[i][n-1])
n-= 1
m -= 1
l += 1
return spiral
192 84
Spiral Matrix II
Spiral Matrix II
Given an integer n, generate a square matrix filled with elements from 1 to n2 in
spiral order.
URL: https://leetcode.com/problems/spiral-matrix-ii/
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
if n == 0:
return []
elif n == 1:
return [[1]]
else:
#no of rows
r = n
#no of columns
c = n
#start of row
k = 0
#start of column
l = 0
193 85
Spiral Matrix II
matrix[k][i] = count
count += 1
k += 1
c -= 1
return matrix
194 86
LRU Cache
LRU Cache
Design and implement a data structure for Least Recently Used (LRU) cache. It
should support the following operations: get and set .
get(key) - Get the value (will always be positive) of the key if the key exists in
the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present.
When the cache reached its capacity, it should invalidate the least recently used
item before inserting a new item.
195 87
LRU Cache
class LRUCache(object):
196 88