Leetcode Python Solutions
Leetcode Python Solutions
of Contents
Introduction 1.1
Linked List 1.2
Linked List Cycle 1.2.1
Reverse Linked List 1.2.2
Delete Node in a Linked List 1.2.3
Merge Two Sorted Lists 1.2.4
Intersection of Two Linked Lists 1.2.5
Linked List Cycle II 1.2.6
Palindrome Linked List 1.2.7
Remove Linked List Elements 1.2.8
Remove Duplicates from Sorted Linked List 1.2.9
Remove Duplicates from Sorted Linked List II 1.2.10
Swap Nodes in Pairs 1.2.11
Remove Nth node from End of List 1.2.12
Trees 1.3
Preorder Traversal 1.3.1
BST Iterator 1.3.2
Inorder Traversal 1.3.3
Symmetric Tree 1.3.4
Balanced Binary Tree 1.3.5
Closest BST Value 1.3.6
Postorder Traversal 1.3.7
Maximum Depth of Binary Tree 1.3.8
Invert Binary Tree 1.3.9
Same Tree 1.3.10
Lowest Common Ancestor of a Binary Search Tree 1.3.11
Lowest Common Ancestor in a Binary Tree 1.3.12
1
Unique Binary Search Trees 1.3.13
Unique Binary Search Trees II 1.3.14
Path Sum 1.3.15
Binary Tree Maximum Path Sum 1.3.16
Binary Tree Level Order Traversal 1.3.17
Validate Binary Search Tree 1.3.18
Minimum Depth of Binary Tree 1.3.19
Convert Sorted Array to Binary Search Tree 1.3.20
Flatten Binary Tree to Linked List 1.3.21
Construct Binary Tree from Inorder and Preorder Traversal 1.3.22
Binary Tree Paths 1.3.23
Recover Binary Search Tree 1.3.24
Path Sum II 1.3.25
Binary Level Order Traversal II 1.3.26
Kth Smallest Element in a BST 1.3.27
Construct Binary Tree from Inorder and Postorder Traversal 1.3.28
Binary Tree Right Side View 1.3.29
Sum Root to Leaf Numbers 1.3.30
Binary Tree Zigzag Level Order Traversal 1.3.31
House Robber III 1.3.32
Inorder Successor in BST 1.3.33
Binary Tree Longest Consecutive Sequence 1.3.34
Verify Preorder Sequence in Binary Search Tree 1.3.35
Binary Tree Upside Down 1.3.36
Count Univalue Subtrees 1.3.37
Serialize and Deserialize Binary Tree 1.3.38
Graphs 1.4
Number of Connected Components in an Undirected Graph 1.4.1
Course Schedule 1.4.2
Graph Valid Tree 1.4.3
2
Course Schedule 2 1.4.4
Number of Islands 1.4.5
Heaps 1.5
Merge K Sorted Linked Lists 1.5.1
Kth Largest Element in an Array 1.5.2
Arrays 1.6
2 Sum II 1.6.1
2 Sum III 1.6.2
Contains Duplicate 1.6.3
Rotate Array 1.6.4
3 Sum Smaller 1.6.5
3 Sum Closest 1.6.6
3 Sum 1.6.7
Two Sum 1.6.8
Plus One 1.6.9
Best Time to Buy and Sell Stock 1.6.10
Shortest Word Distance 1.6.11
Move Zeroes 1.6.12
Contains Duplicate II 1.6.13
Majority Element 1.6.14
Remove Duplicates from Sorted Array 1.6.15
Nested List Weight Sum 1.6.16
Nested List Weighted Sum II 1.6.17
Remove Element 1.6.18
Intersection of Two Arrays II 1.6.19
Merge Sorted Arrays 1.6.20
Reverse Vowels of a String 1.6.21
Intersection of Two Arrays 1.6.22
Container With Most Water 1.6.23
Product of Array Except Self 1.6.24
3
Trapping Rain Water 1.6.25
Maximum Subarray 1.6.26
Best Time to Buy and Sell Stock II 1.6.27
Find Minimum in Rotated Sorted Array 1.6.28
Pascal's Triangle 1.6.29
Pascal's Triangle II 1.6.30
Summary Ranges 1.6.31
Missing Number 1.6.32
Strings 1.7
Valid Anagram 1.7.1
Valid Palindrome 1.7.2
Word Pattern 1.7.3
Valid Parentheses 1.7.4
Isomorphic Strings 1.7.5
Reverse String 1.7.6
Bit Manipulation 1.8
Sum of Two Integers 1.8.1
Single Number 1.8.2
Single Number II 1.8.3
Single Number III 1.8.4
Maths 1.9
Reverse Integer 1.9.1
Palindrome Number 1.9.2
Pow(x,n) 1.9.3
Subsets 1.9.4
Subsets II 1.9.5
Fraction to Recurring Decimal 1.9.6
Excel Sheet Column Number 1.9.7
Excel Sheet Column Title 1.9.8
Factorial Trailing Zeros 1.9.9
4
Happy Number 1.9.10
Count Primes 1.9.11
Plus One 1.9.12
Divide Two Integers 1.9.13
Multiply Strings 1.9.14
Max Points on a Line 1.9.15
Product of Array Except Self 1.9.16
Power of Three 1.9.17
Integer Break 1.9.18
Power of Four 1.9.19
Add Digits 1.9.20
Ugly Number 1.9.21
Ugly Number II 1.9.22
Super Ugly Number 1.9.23
Find K Pairs with Smallest Sums 1.9.24
Self Crossing 1.9.25
Paint Fence 1.9.26
Bulb Switcher 1.9.27
Nim Game 1.9.28
Matrix 1.10
Rotate Image 1.10.1
Set Matrix Zeroes 1.10.2
Search a 2D Matrix 1.10.3
Search a 2D Matrix II 1.10.4
Spiral Matrix 1.10.5
Spiral Matrix II 1.10.6
Design 1.11
LRU Cache 1.11.1
5
Introduction
6
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
7
Linked List Cycle
8
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
9
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
10
Merge Two Sorted Lists
URL: https://leetcode.com/problems/merge-two-sorted-lists/
11
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
12
Merge Two Sorted Lists
13
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
14
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
15
Linked List Cycle II
URL: https://leetcode.com/problems/linked-list-cycle-ii/
16
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
17
Palindrome Linked List
URL: https://leetcode.com/problems/palindrome-linked-list/
18
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
19
Palindrome Linked List
20
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/
21
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
22
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/
23
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
24
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:
25
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
26
Swap Nodes in Pairs
27
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/
28
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
29
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/
30
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
31
Trees
32
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
33
Preorder Traversal
34
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/
35
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
36
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
37
Inorder Traversal
38
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)
39
Symmetric Tree
40
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/
41
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
42
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/
43
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
44
Closest BST Value
45
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/
46
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]
47
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
48
Invert Binary Tree
49
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
50
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
51
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):
def __init__(self):
self.inorder_list = []
self.postorder_list = []
52
Lowest Common Ancestor of a Binary Search Tree
lca_elem = self.find_elem_max_index(between_elems)
return lca_elem
53
Lowest Common Ancestor of a Binary Search Tree
self.inorder_list.append(node.val)
self.inorder_traversal(node.right)
54
Lowest Common Ancestor in a Binary Tree
_______3______
/ \
___5__ ___1__
URL: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
55
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
56
Unique Binary Search Trees
1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
URL: https://leetcode.com/problems/unique-binary-search-trees/
57
Unique Binary Search Trees
class Solution(object):
if n < 0:
return 0
if n == 0 or n == 1:
return 1
possibilities = 0
58
Unique Binary Search Trees II
For example, Given n = 3, your program should return all 5 unique BST's shown
below.
1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
URL: https://leetcode.com/problems/unique-binary-search-trees-ii/
59
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
60
Unique Binary Search Trees II
61
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()
62
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
63
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/
64
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
65
Binary Tree Level Order Traversal
URL: https://leetcode.com/problems/binary-tree-level-order-traversal/
66
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
67
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/
68
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
69
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/
70
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
71
Convert Sorted Array to Binary Search Tree
URL: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
72
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)
73
Flatten Binary Tree to Linked List
1
/ \
2 5
/ \ \
3 4 6
URL: https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
74
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
75
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)
76
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
77
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()
78
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
79
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/
80
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)
81
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()
82
Path Sum II
83
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 = []
84
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
85
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/
86
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
87
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
88
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)
89
Construct Binary Tree from Inorder and Postorder Traversal
root = TreeNode(postorder[high_postorder])
return root
90
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/
91
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
92
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.
93
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)
94
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)
95
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
96
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/
97
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])
98
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/
99
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
100
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).
101
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
102
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
103
Verify Preorder Sequence in Binary Search Tree
104
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
105
Binary Tree Upside Down
106
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/
107
Count Univalue Subtrees
class Solution(object):
def __init__(self):
self.__count = 0
108
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
109
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
def __str__(self):
return str(self.id) + ' adjacent: ' + str([x.id for x in
self.adjacent])
class Graph:
def __init__(self):
self.vertDictionary = {}
self.numVertices = 0
def __iter__(self):
return iter(self.vertDictionary.values())
110
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
111
Number of Connected Components in an Undirected Graph
self.bfs(vertex)
return count
if __name__ == "__main__":
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))
112
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:
113
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):
114
Course Schedule
return self.color
def __str__(self):
return str(self.id) + ' connectedTo: ' + str([x.id for x
in self.adjacent])
class Graph:
def __init__(self):
self.vertex_dict = {}
self.no_vertices = 0
self.no_edges = 0
if to not in self.vertex_dict:
self.add_vertex(to)
to_vertex = self.get_vertex(to)
115
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])
116
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
if __name__ == "__main__":
soln1 = Solution()
print(soln1.canFinish(2, [[1,0]]))
soln2 = Solution()
print(soln2.canFinish(2, [[1,0],[0,1]]))
117
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):
118
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
def __str__(self):
return str(self.id) + ' adjacent: ' + str([x.id for x in
self.adjacent])
class Graph:
def __init__(self):
self.vertDictionary = {}
self.numVertices = 0
def __iter__(self):
return iter(self.vertDictionary.values())
119
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:
120
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]
121
Graph Valid Tree
if nbr.getColor() == "white":
nbr.setColor("gray")
stack.append(nbr)
curr_node.setColor("black")
return True
122
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
123
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
124
Course Schedule 2
def __str__(self):
return str(self.id) + ' adjacent: ' + str([x.id for x in
self.adjacent])
class DirectedGraph:
def __init__(self):
self.vertDictionary = {}
self.numVertices = 0
def __iter__(self):
return iter(self.vertDictionary.values())
self.vertDictionary[frm].addNeighbor(self.vertDictionary
[to], cost)
self.vertDictionary[to].setIndegree(self.vertDictionary[
to].getIndegree() + 1)
def getVertices(self):
return self.vertDictionary.keys()
125
Course Schedule 2
class Solution:
def __init__(self):
self.has_cycle = False
return self.topsort(G)
126
Course Schedule 2
if len(topological_list) != len(nodes):
self.has_cycle = True
return topological_list
if __name__ == "__main__":
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]]))
127
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/
128
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)
129
Merge K Sorted Linked Lists
URL: https://leetcode.com/problems/merge-k-sorted-lists/
130
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
131
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]
132
2 Sum II
2 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]
133
2 Sum II
134
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):
def __init__(self):
"""
initialize your data structure here
"""
self.__num_list = collections.defaultdict(int)
135
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
if __name__ == "__main__":
# Your TwoSum object will be instantiated and called as such
:
twoSum = TwoSum()
twoSum.add(0)
twoSum.add(0)
print(twoSum.find(0))
136
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 = {}
137
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/
138
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)
if __name__ == "__main__":
soln = Solution()
nums = [1,2,3,4,5,6,7]
soln.rotate(nums, 3)
print(nums)
139
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/
140
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)
if __name__ == "__main__":
soln = Solution()
print(soln.threeSumSmaller([3,1,0,-2], 4))
141
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/
142
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
if __name__ == "__main__":
soln = Solution()
print(soln.threeSumClosest([-1, 2, 1, -4], 1))
print(soln.threeSumClosest([-1, 2, 1, -4], 3))
143
3 Sum Closest
144
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/
145
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
if __name__ == "__main__":
soln = Solution()
print(soln.threeSum([-1, 0, 1, 2, -1, -4]))
146
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
147
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]
148
Plus One
149
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
150
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/
151
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
152
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
153
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
154
Contains Duplicate II
155
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/
156
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
157
Majority Element
158
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
159
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):
160
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
161
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/
162
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])
163
Remove Element
164
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/
165
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
166
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/
167
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
168
Reverse Vowels of a String
URL: https://leetcode.com/problems/reverse-vowels-of-a-string/
169
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)
170
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()
171
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
172
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
173
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/
174
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
175
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)
176
Maximum Subarray
177
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
178
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
179
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/
180
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
181
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
182
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
183
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]
184
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
185
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
186
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/
187
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
if __name__ == "__main__":
pattern = "abba"
str = "dog cat cat dog"
soln = Solution()
print(soln.wordPattern(pattern, str))
188
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/
189
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 = ")}]"
190
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/
191
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
192
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)
193
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)
194
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
195
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
196
Reverse Integer
197
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
198
Palindrome Number
199
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
200
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:
201
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
202
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/
203
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
204
Power of Three
Power of Three
205
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/
206
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
207
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]
208
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))
209
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
210
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
211
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
212
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
213
Set Matrix Zeroes
214
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.
215
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
216
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/
217
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])
218
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
219
Spiral Matrix
s
for i in range(k, m):
spiral.append(matrix[i][n-1])
n-= 1
m -= 1
l += 1
return spiral
220
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
221
Spiral Matrix II
matrix[k][i] = count
count += 1
k += 1
c -= 1
return matrix
222
Design
223
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.
224
LRU Cache
class LRUCache(object):
225
LRU Cache
226