Coding Questions With Solutions in Python
Coding Questions With Solutions in Python
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