1. Two Sum
Description:
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, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
Solution:
Approach 1: Brute Force
class Solution:
def twoSum(self, nums, target):
res = []
l = len(nums)
for i in range(0,l-1):
for j in range(i+1, l):
if nums[i]+nums[j] == target:
res.append(i)
res.append(j)
return res
break
'''
Runtime: 5256 ms
Your runtime beats 21.66 % of python3 submissions.
Memory Usage: 13.7 MB
Your memory usage beats 85.02 % of python3 submissions.
'''
Approach 2: Two-pass Hash Table
class Solution:
def twoSum(self, nums, target):
dic = {}
l = len(nums)
for num in nums:
dic[num] = nums.index(num)
for i in range(l):
tmp = target - nums[i]
if tmp in dic and dic[tmp] != i:
return [i,dic[tmp]]
'''
Runtime: 652 ms
Your runtime beats 38.07 % of python3 submissions.
Memory Usage: 14.9 MB
Your memory usage beats 11.38 % of python3 submissions.
'''
Approach 3: One-pass Hash Table
class Solution:
def twoSum(self, nums, target):
dic = {}
l = len(nums)
for i in range(l):
tmp = target - nums[i]
if tmp in dic:
return [dic[tmp], i]
dic[nums[i]] = i
'''
Runtime: 32 ms
Your runtime beats 98.46 % of python3 submissions.
Memory Usage: 14.3 MB
Your memory usage beats 38.17 % of python3 submissions.
'''
26. Remove Duplicates from Sorted Array
Description:
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Given nums = [1,1,2], 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 returned length.
Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4], Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. It doesn't matter what values are set beyond the returned length.
Solution:
Approach 1:
class Solution:
def removeDuplicates(self, nums):
nums[:] = sorted(list(set(nums)))
return len(nums)
'''
Runtime: 56 ms
Your runtime beats 93.55 % of python3 submissions.
Memory Usage: 14.9 MB
Your memory usage beats 16.42 % of python3 submissions.
'''
Appraoch 2:
class Solution:
def removeDuplicates(self, nums):
if len(nums) == 0:
return 0
else:
i = 0
for j in range(1,len(nums)):
if nums[j] != nums[i]:
i = i+1
nums[i] = nums[j]
return i+1
'''
Runtime: 52 ms
Your runtime beats 97.95 % of python3 submissions.
Memory Usage: 15 MB
Your memory usage beats 11.70 % of python3 submissions.
'''
27. Remove Element
Description:
Given an array nums and a value val, 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 by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example 1:
Given nums = [3,2,2,3], val = 3, Your function should return length = 2, with the first two elements of nums being 2. It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,1,2,2,3,0,4,2], val = 2, Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. Note that the order of those five elements can be arbitrary. It doesn't matter what values are set beyond the returned length.
Solution:
Approach 1:
class Solution:
def removeElement(self, nums, val):
i = 0
for j in range(0, len(nums)):
if nums[j] != val:
nums[i] = nums[j]
i = i+1
return i
'''
Runtime: 36 ms
Your runtime beats 87.93 % of python3 submissions.
Memory Usage: 13.2 MB
Your memory usage beats 49.66 % of python3 submissions.
'''
Approach 2:
class Solution:
def removeElement(self, nums, val):
i = 0
n = len(nums)
while i < n:
if nums[i] == val:
nums[i] = nums[n-1]
n = n-1
else:
i = i+1
return n
'''
Runtime: 36 ms
Your runtime beats 87.93 % of python3 submissions.
Memory Usage: 13.2 MB
Your memory usage beats 39.22 % of python3 submissions.
'''
35. Search Insert Position
Description:
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Example 1:
Input: [1,3,5,6], 5 Output: 2
Example 2:
Input: [1,3,5,6], 2 Output: 1
Example 3:
Input: [1,3,5,6], 7 Output: 4
Example 4:
Input: [1,3,5,6], 0 Output: 0
Solution:
Approach 1:
class Solution:
def searchInsert(self, nums, target):
i = 0
while i < len(nums):
if target > nums[i]:
i = i+1
else:
break
return i
'''
Runtime: 36 ms
Your runtime beats 86.47 % of python3 submissions.
Memory Usage: 13.6 MB
Your memory usage beats 67.38 % of python3 submissions.
'''
Approach 2:
class Solution:
def searchInsert(self, nums, target):
if target in nums:
return nums.index(target)
else:
nums.append(target)
nums = sorted(nums)
return nums.index(target)
'''
Runtime: 28 ms
Your runtime beats 99.06 % of python3 submissions.
Memory Usage: 13.7 MB
Your memory usage beats 65.09 % of python3 submissions.
'''
53. Maximum Subarray
Description:
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6.
Solution:
Approach 1: Dynamic Programming
class Solution:
def maxSubArray(self, nums):
sum = -pow(10,20)
prevsum = nums[0]
for i in range(1,len(nums)):
prevsum = max(nums[i],nums[i]+prevsum)
sum = max(sum,prevsum)
sum = max(nums[0],sum)
return sum
'''
Runtime: 44 ms
Your runtime beats 81.14 % of python3 submissions.
Memory Usage: 13.3 MB
Your memory usage beats 98.56 % of python3 submissions.
'''
Approach 2:
from itertools import accumulate
class Solution:
def maxSubArray(self, nums):
return max(accumulate(nums, lambda x, y: max(y, x+y) ))
'''
Runtime: 44 ms
Your runtime beats 81.14 % of python3 submissions.
Memory Usage: 13.6 MB
Your memory usage beats 66.23 % of python3 submissions.
'''
66. Plus One
Description:
Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: [1,2,3] Output: [1,2,4] Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1] Output: [4,3,2,2] Explanation: The array represents the integer 4321.
Solution:
Approach 1:
class Solution:
def plusOne(self, digits):
digits[-1] += 1
digits.reverse()
if len(digits) != 1:
for i in range(0,len(digits)-1):
if digits[i] == 10:
digits[i] = 0
digits[i+1] += 1
if digits[-1] == 10:
digits[-1] = 0
digits.append(1)
digits.reverse()
return digits
'''
Runtime: 32 ms
Your runtime beats 95.84 % of python3 submissions.
Memory Usage: 13 MB
Your memory usage beats 87.38 % of python3 submissions.
'''
Approach 2:
class Solution:
def plusOne(self, digits):
return [int(i) for i in str(int(''.join([str(i) for i in digits])) + 1)]
'''
Runtime: 36 ms
Your runtime beats 85.71 % of python3 submissions.
Memory Usage: 13.1 MB
Your memory usage beats 70.47 % of python3 submissions.
'''
88. Merge Sorted Array
Description:
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
- The number of elements initialized in nums1 and nums2 are m and n respectively.
- You may assume that nums1 has enough space (size that is greater or equal to m+ n) to hold additional elements from nums2.
Example:
Input: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6]
Solution:
Approach 1:
class Solution:
def merge(self, nums1, m, nums2, n):
nums1[m:] = nums2
nums1.sort()
'''
Runtime: 40 ms
Your runtime beats 78.30 % of python3 submissions.
Memory Usage: 13.2 MB
Your memory usage beats 35.14 % of python3 submissions.
'''
Approach 2:
class Solution:
def merge(self, nums1, m, nums2, n):
j = 0
for i in range(m,len(nums1)):
nums1[i] = nums2[j]
j += 1
nums1.sort()
'''
Runtime: 36 ms
Your runtime beats 91.86 % of python3 submissions.
Memory Usage: 13.2 MB
Your memory usage beats 37.41 % of python3 submissions.
'''
118. Pascal's Triangle
Description:
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 5 Output: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
Solution:
Approach 1:
class Solution:
def generate(self, numRows):
triangle = []
for i in range(numRows):
row = [None for _ in range(i+1)]
row[0], row[-1] = 1, 1
for j in range(1,len(row)-1):
row[j] = triangle[i-1][j-1] + triangle[i-1][j]
triangle.append(row)
return triangle
'''
Runtime: 36 ms
Your runtime beats 79.50 % of python3 submissions.
Memory Usage: 13 MB
Your memory usage beats 87.80 % of python3 submissions.
'''
Approach 2:
class Solution:
def generate(self, numRows):
return [[round(math.factorial(i)/math.factorial(i-j)/math.factorial(j)) for j in range(i+1)] for i in range(numRows)]
'''
Runtime: 32 ms
Your runtime beats 93.26 % of python3 submissions.
Memory Usage: 13.2 MB
Your memory usage beats 43.01 % of python3 submissions.
'''
119. Pascal's Triangle II
Description:
Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.
Note that the row index starts from 0.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 3 Output: [1,3,3,1]
Solution:
Approach 1:
class Solution:
def getRow(self, rowIndex):
triangle = []
for i in range(rowIndex+1):
row = [None for i in range(i+1)]
row[0], row[-1] = 1, 1
for j in range(1,len(row)-1):
row[j] = triangle[i-1][j-1] + triangle[i-1][j]
triangle.append(row)
return triangle[rowIndex]
'''
Runtime: 32 ms
Your runtime beats 94.39 % of python3 submissions.
Memory Usage: 13.2 MB
Your memory usage beats 39.87 % of python3 submissions.
'''
Approach 2:
class Solution:
def getRow(self, rowIndex):
row = [1]
for i in range(rowIndex):
row.append(row[i]*(rowIndex-i)//(i+1))
return row
'''
Runtime: 32 ms
Your runtime beats 94.39 % of python3 submissions.
Memory Usage: 13.2 MB
Your memory usage beats 34.82 % of python3 submissions.
'''
121. Best Time to Buy and Sell Stock
Description:
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
Example 1:
Input: [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 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 Explanation: In this case, no transaction is done, i.e. max profit = 0.
Solution:
Approach 1:
class Solution(object):
def maxProfit(self, prices):
if prices:
max_dif = 0
min_stock = prices[0]
for ele in prices[1:]:
if ele < min_stock:
min_stock = ele
if ele-min_stock > max_dif:
max_dif = ele-min_stock
return max_dif
else:
return 0
'''
Runtime: 40 ms
Your runtime beats 86.27 % of python3 submissions.
Memory Usage: 13.6 MB
Your memory usage beats 99.33 % of python3 submissions
'''
Approach 2:
class Solution(object):
def maxProfit(self, prices):
min = float('inf')
profit = 0
for price in prices:
profit = max(profit, price - min)
min = min(price, min)
return profit
'''
Runtime: 44 ms
Your runtime beats 60.71 % of python3 submissions
Memory Usage: 13.8 MB
Your memory usage beats 92.71 % of python3 submissions.
'''
122. Best Time to Buy and Sell Stock II
Description:
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Example 1:
Input: [7,1,5,3,6,4] Output: 7 Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Example 2:
Input: [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.
Solution:
Approach 1:
class Solution:
def maxProfit(self, prices):
if prices:
valley = prices[0]
peak = prices[0]
maxprofit = 0
i = 0
while i < len(prices)-1:
while i < len(prices)-1 and prices[i] >= prices[i+1]:
i = i+1
valley = prices[i]
while i < len(prices)-1 and prices[i] <= prices[i+1]:
i = i+1
peak = prices[i]
maxprofit += peak - valley
return maxprofit
else:
return 0
'''
Runtime: 36 ms
Your runtime beats 92.91 % of python3 submissions.
Memory Usage: 13.7 MB
Your memory usage beats 98.38 % of python3 submissions.
'''
Approach 2:
class Solution:
def maxProfit(self, prices):
maxprofit = 0
for i in range(1, len(prices)):
if prices[i] > prices[i-1]:
maxprofit += prices[i] - prices[i-1]
return maxprofit
'''
Runtime: 24 ms
Your runtime beats 99.95 % of python3 submissions.
Memory Usage: 13.8 MB
Your memory usage beats 92.32 % of python3 submissions.
'''
167. Two Sum II - Input array is sorted
Description:
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.
Note:
- Your returned answers (both index1 and index2) are not zero-based.
- You may assume that each input would have exactly one solution and you may not use the same element twice.
Example:
Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
Solution:
Approach 1:
class Solution:
def twoSum(self, numbers, target):
p1 = 0
p2 = len(numbers)-1
while p2 > p1:
if numbers[p1] + numbers[p2] < target:
p1 += 1
elif numbers[p1] + numbers[p2] > target:
p2 -= 1
elif numbers[p1] + numbers[p2] == target:
return [p1+1, p2+1]
'''
Runtime: 32 ms
Your runtime beats 98.55 % of python3 submissions.
Memory Usage: 13.5 MB
Your memory usage beats 76.80 % of python3 submissions.
'''
169. Majority Element
Description:
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.
Example 1:
Input: [3,2,3] Output: 3
Example 2:
Input: [2,2,1,1,1,2,2] Output: 2
Solution:
Approach 1:
class Solution:
def majorityElement(self, nums):
dic = {}
for num in nums:
if num in dic:
dic[num] += 1
else:
dic[num] = 1
me = sorted(dic.items(), key = lambda x:x[1], reverse = True)
return me[0][0]
'''
Runtime: 48 ms
Your runtime beats 77.93 % of python3 submissions.
Memory Usage: 14.2 MB
Your memory usage beats 91.57 % of python3 submissions.
'''
Approach 2:
class Solution:
def majorityElement(self, nums):
nums.sort()
return nums[len(nums)//2]
'''
Runtime: 36 ms
Your runtime beats 99.53 % of python3 submissions.
Memory Usage: 14.4 MB
Your memory usage beats 23.43 % of python3 submissions.
'''
Approach 3:
import random
class Solution:
def majorityElement(self, nums):
majority_count = len(nums)//2
while True:
candidate = random.choice(nums)
if sum(1 for elem in nums if elem == candidate) > majority_count:
return candidate
'''
Runtime: 48 ms
Your runtime beats 77.93 % of python3 submissions.
Memory Usage: 14.3 MB
Your memory usage beats 66.97 % of python3 submissions.
'''
Approach 4:
class Solution:
def majorityElement(self, nums):
count = 0
candidate = None
for num in nums:
if count == 0:
candidate = num
count += (1 if num == candidate else -1)
return candidate
'''
Runtime: 48 ms
Your runtime beats 77.93 % of python3 submissions.
Memory Usage: 14.2 MB
Your memory usage beats 85.17 % of python3 submissions.
'''
189. Rotate Array
Description:
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: [1,2,3,4,5,6,7] and k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Input: [-1,-100,3,99] and k = 2 Output: [3,99,-1,-100] Explanation: rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100]
Solution:
Approach 1:Brute Force
class Solution:
def rotate(self, nums, k):
while k > 0:
pre = nums[-1]
for i in range(len(nums)):
tmp = nums[i]
nums[i] = pre
pre = tmp
k = k-1
Approach 2:
class Solution:
def rotate(self, nums, k):
a = nums.copy()
for i in range(len(nums)):
nums[(i+k)%len(nums)] = a[i]
'''
Runtime: 56 ms
Your runtime beats 100.00 % of python3 submissions.
Memory Usage: 13.4 MB
'''
Approach 3:
class Solution:
def rotate(self, nums, k):
k %= len(nums)
self.reverse(nums, 0, len(nums)-1)
self.reverse(nums, 0, k-1)
self.reverse(nums, k, len(nums)-1)
def reverse(self, nums, start, end):
while start < end:
tmp = nums[start]
nums[start] = nums[end]
nums[end] = tmp
start += 1
end -= 1
'''
Runtime: 76 ms
Your runtime beats 51.75 % of python3 submissions.
Memory Usage: 14.9 MB
'''
217. Contains Duplicate
Description:
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.
Example 1:
Input: [1,2,3,1] Output: true
Example 2:
Input: [1,2,3,4] Output: false
Example 3:
Input: [1,1,1,3,3,4,3,2,4,2] Output: true
Solution:
Approach 1:
class Solution:
def containsDuplicate(self, nums):
if len(nums) != len(set(nums)):
return True
else:
return False
'''
Runtime: 136 ms
Your runtime beats 91.58 % of python3 submissions.
Memory Usage: 19 MB
Your memory usage beats 26.41 % of python3 submissions.
'''
Approach 2:
class Solution:
def containsDuplicate(self, nums):
nums.sort()
for i in range(len(nums)-1):
if nums[i] == nums[i+1]:
return True
return False
'''
Runtime: 148 ms
Your runtime beats 35.62 % of python3 submissions.
Memory Usage: 19.1 MB
Your memory usage beats 16.98 % of python3 submissions.
'''
219. Contains Duplicate II
Description:
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 absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3 Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1 Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2 Output: false
Solution:
Approach 1:Brute Force
class Solution:
def containsNearbyDuplicate(self, nums, k):
for i in range(len(nums)):
for j in range(len(nums)):
if nums[i]==nums[j] and i!=j and abs(i-j)<=k:
return True
return False
'''
Time Limit Exceeded
'''
Approach 2:
class Solution:
def containsNearbyDuplicate(self, nums, k):
if len(nums) == len(set(nums)):
return False
else:
d = {}
res = []
for idx, val in enumerate(nums):
if val not in d:
d[val] = idx
else:
if abs(idx - d[val]) <= k:
return True
else:
d[val] = idx
return False
'''
Runtime: 112 ms
Your runtime beats 45.37 % of python3 submissions.
Memory Usage: 18.5 MB
Your memory usage beats 75.00 % of python3 submissions.
'''
Approach 3:
import collections
class Solution:
def containsNearbyDuplicate(self, nums, k):
co = collections.Counter(nums)
for i in range(len(nums)-1):
if co[nums[i]] >1:
for j in range(i+1,i+1+k):
if j < len(nums) and nums[i] == nums[j]: return True
return False
'''
Runtime: 104 ms
Your runtime beats 84.84 % of python3 submissions.
Memory Usage: 20.3 MB
Your memory usage beats 68.75 % of python3 submissions.
'''
268. Missing Number
Description:
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
Example 1:
Input: [3,0,1] Output: 2
Example 2:
Input: [9,6,4,2,3,5,7,0,1] Output: 8
Solution:
Approach 1:
class Solution():
def missingNumber(self, nums):
d = {}
for i in range(len(nums)+1):
d[i] = 0
for num in nums:
d[num] = 1
for key in d:
if d[key] == 0:
return key
'''
Runtime: 164 ms
Your runtime beats 35.29 % of python3 submissions.
Memory Usage: 15.1 MB
Your memory usage beats 6.45 % of python3 submissions.
'''
Approach 2:
class Solution():
def missingNumber(self, nums):
sum1 = sum(nums)
sum2 = sum(range(0,len(nums)+1))
return sum2-sum1
'''
Runtime: 156 ms
Your runtime beats 67.10 % of python3 submissions.
Memory Usage: 14.9 MB
Your memory usage beats 6.45 % of python3 submissions.
'''