├── Extra ├── suffix_array.pyc └── lcp.py ├── 100-200q ├── 191.py ├── 190.py ├── 119.py ├── 179.py ├── 131.py ├── 141.py ├── 118.py ├── 125.py ├── 128.py ├── 140.py ├── 147.py ├── 160.py ├── 142.py ├── 139.py ├── 112.py ├── 134.py ├── 159.py ├── 111.py ├── 143.py ├── 101.py ├── 123.py ├── 153.py ├── 152.py ├── 199.py ├── 100.py ├── 163.py ├── 120.py ├── 129.py ├── 108.py ├── 173.py ├── 102.py ├── 170.py ├── 124.py ├── 132.py ├── 113.py ├── 107.py ├── 116.py ├── 115.py └── 106.py ├── 1-100q ├── 78.py ├── 46.py ├── 32.py ├── TwoSum.py ├── 65.py ├── 53.py ├── 48.py ├── 73.py ├── 60.py ├── 70.py ├── 24.py ├── 22.py ├── 83.py ├── 90.py ├── 03.py ├── 61.py ├── 11.py ├── 62.py ├── 42.py ├── 26.py ├── 45.py ├── 41.py ├── 74.py ├── 19.py ├── 64.py ├── 80.py ├── 82.py ├── 06.py ├── 66.py ├── 75.py ├── 54.py ├── 39.py ├── 93.py ├── 17.py ├── 92.py ├── 94.py ├── 34.py ├── 71.py ├── 81.py ├── 99.py ├── 97.py ├── 16.py ├── 8.py ├── 98.py ├── 25.py ├── 38.py ├── 15.py ├── 67.py ├── 86.py ├── 31.py ├── 91.py ├── 14.py ├── 40.py ├── 44.py ├── 87.py ├── 56.py ├── 57.py └── 63.py ├── 300-400q ├── 326.py ├── 387.py ├── 346.py ├── 347.py ├── 334.py ├── 340.py ├── 322.py ├── 328.py ├── 378.py ├── 350.py ├── 395.py └── 329.py ├── 200-300q ├── 268.py ├── 203.py ├── 206.py ├── 234.py ├── 215.py ├── 238.py ├── 200.py ├── 283.py ├── 239.py ├── 287.py ├── 279.py ├── 285.py ├── 281.py ├── 253.py ├── 298.py ├── 240.py ├── 230.py ├── 289.py ├── 257.py └── 300.py ├── 400-500Q ├── 454.py ├── 442.py ├── 448.py └── 410.py ├── 1200-1300q ├── 1281.py ├── 1295.py ├── 1290.py ├── 1282.py ├── 1296.py ├── 1266.py ├── 1277.py └── 1200.py ├── 1000-1100q ├── 1037.py ├── 1074.py ├── 1073.py ├── 1051.py ├── 1072.py ├── 1064.py ├── 1016.py ├── 1015.py ├── 1014.py ├── 1017.py ├── 1085.py ├── 1018.py ├── 1004.py ├── 1027.py ├── 1043.py ├── 1081.py ├── 1025.py ├── 1053.py ├── 1089.py ├── 1008.py ├── 1009.py ├── 1005.py ├── 1029.py ├── 1013.py ├── 1047.py ├── 1054.py ├── 1071.py ├── 1002.py ├── 1079.py ├── 1065.py └── 1046.py ├── 900-1000q ├── 991.py ├── 995.py ├── 988.py ├── 977.py ├── 926.py ├── 983.py ├── 985.py └── 997.py ├── 1100-1200q ├── 1189.py ├── 1185.py └── 1190.py └── 600-700q ├── 674.py ├── 673.py └── 681.py /Extra/suffix_array.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Garvit244/Leetcode/HEAD/Extra/suffix_array.pyc -------------------------------------------------------------------------------- /100-200q/191.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def hammingWeight(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | bits = 0 8 | mask = 1 9 | 10 | for i in range(32): 11 | if (n&mask) != 0: 12 | bits +=1 13 | mask <<= 1 14 | 15 | return bits -------------------------------------------------------------------------------- /100-200q/190.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param n, an integer 3 | # @return an integer 4 | def reverseBits(self, n): 5 | res = 0 6 | for i in range(32): 7 | res += n & 1 8 | n = n >> 1 9 | if i != 31: 10 | res = res << 1 11 | return res 12 | 13 | print Solution().reverseBits(12) -------------------------------------------------------------------------------- /1-100q/78.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a set of distinct integers, nums, return all possible subsets (the power set). 3 | ''' 4 | 5 | class Solution(object): 6 | def subsets(self, nums): 7 | """ 8 | :type nums: List[int] 9 | :rtype: List[List[int]] 10 | """ 11 | result = [[]] 12 | for num in nums: 13 | for j in range(len(result)): 14 | result.append(result[j] + [num]) 15 | return result -------------------------------------------------------------------------------- /300-400q/326.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer, write a function to determine if it is a power of three. 3 | 4 | Follow up: 5 | Could you do it without using any loop / recursion? 6 | ''' 7 | 8 | class Solution(object): 9 | def isPowerOfThree(self, n): 10 | """ 11 | :type n: int 12 | :rtype: bool 13 | """ 14 | if n <= 0: 15 | return False 16 | 17 | import math 18 | return (math.log10(n)/math.log10(3))%1 == 0 -------------------------------------------------------------------------------- /100-200q/119.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle. 3 | 4 | Note that the row index starts from 0. 5 | ''' 6 | class Solution(object): 7 | def getRow(self, rowIndex): 8 | """ 9 | :type rowIndex: int 10 | :rtype: List[int] 11 | """ 12 | row = [1]*(rowIndex+1) 13 | for i in range(1, rowIndex+1): 14 | for j in range(i-1, 0, -1): 15 | row[j] += row[j-1] 16 | return row -------------------------------------------------------------------------------- /1-100q/46.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def permute(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[List[int]] 6 | """ 7 | 8 | if len(nums) == 0: 9 | return [] 10 | if len(nums) == 1: 11 | return [nums] 12 | 13 | result = [] 14 | for index in range(len(nums)): 15 | for p in self.permute(nums[0:index] + nums[index+1:]): 16 | result.append([nums[index]] + p) 17 | 18 | return result -------------------------------------------------------------------------------- /1-100q/32.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def longestValidParentheses(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | stack, result = [-1], 0 8 | 9 | for index in range(len(s)): 10 | if s[index] == '(': 11 | stack.append(index) 12 | else: 13 | currIndex = stack.pop() 14 | if currIndex == -1: 15 | stack.append(index) 16 | else: 17 | result = max(result, index-currIndex+1) 18 | return result -------------------------------------------------------------------------------- /100-200q/179.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a list of non negative integers, arrange them such that they form the largest number. 3 | 4 | Example 1: 5 | 6 | Input: [10,2] 7 | Output: "210" 8 | Example 2: 9 | 10 | Input: [3,30,34,5,9] 11 | Output: "9534330" 12 | # ''' 13 | 14 | 15 | class Solution: 16 | # @param {integer[]} nums 17 | # @return {string} 18 | def largestNumber(self, nums): 19 | nums = [str(num) for num in nums] 20 | nums.sort(cmp=lambda x, y : cmp(y+x, x+y)) 21 | return ''.join(nums).lstrip("0") or "0" -------------------------------------------------------------------------------- /300-400q/387.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. 3 | 4 | Examples: 5 | 6 | s = "leetcode" 7 | return 0. 8 | 9 | s = "loveleetcode", 10 | return 2. 11 | ''' 12 | 13 | class Solution(object): 14 | def firstUniqChar(self, s): 15 | """ 16 | :type s: str 17 | :rtype: int 18 | """ 19 | letters='abcdefghijklmnopqrstuvwxyz' 20 | index=[s.index(l) for l in letters if s.count(l) == 1] 21 | return min(index) if len(index) > 0 else -1 -------------------------------------------------------------------------------- /200-300q/268.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. 3 | 4 | Example 1: 5 | 6 | Input: [3,0,1] 7 | Output: 2 8 | Example 2: 9 | 10 | Input: [9,6,4,2,3,5,7,0,1] 11 | Output: 8 12 | ''' 13 | 14 | class Solution(object): 15 | def missingNumber(self, nums): 16 | """ 17 | :type nums: List[int] 18 | :rtype: int 19 | """ 20 | if not nums: 21 | return 0 22 | totalSum, n = sum(nums), len(nums) 23 | expectedSum = (n*(n+1))/2 24 | return expectedSum - totalSum -------------------------------------------------------------------------------- /200-300q/203.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def countPrimes(self, n): 3 | """ 4 | :type n: int 5 | :rtype: int 6 | """ 7 | if n < 2: 8 | return 0 9 | 10 | A = [0] * (n + 1) 11 | count = 0 12 | 13 | for pointer1 in range(2, n): 14 | if A[pointer1] == 0: 15 | count += 1 16 | pointer2 = pointer1 17 | while (pointer2 + pointer1 < n): 18 | pointer2 += pointer1 19 | A[pointer2] = 1 20 | 21 | return count 22 | -------------------------------------------------------------------------------- /100-200q/131.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string s, partition s such that every substring of the partition is a palindrome. 3 | 4 | Return all possible palindrome partitioning of s. 5 | ''' 6 | 7 | class Solution(object): 8 | def partition(self, s): 9 | result = [] 10 | def valid(s): 11 | for i in range(len(s)/2): 12 | if s[i] != s[-(i+1)]: 13 | return False 14 | return True 15 | 16 | def partitionRec(curr, s, i): 17 | if i == len(s): 18 | result.append(curr) 19 | else: 20 | for j in range(i, len(s)): 21 | if valid(s[i:j+1]): 22 | partitionRec(curr + [s[i:j+1]], s, j+1) 23 | 24 | partitionRec([], s, 0) 25 | return result -------------------------------------------------------------------------------- /1-100q/TwoSum.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers, return indices of the two numbers such that they add up to a specific target. 3 | 4 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 5 | 6 | Example: 7 | 8 | Given nums = [2, 7, 11, 15], target = 9, 9 | 10 | Because nums[0] + nums[1] = 2 + 7 = 9, 11 | return [0, 1]. 12 | ''' 13 | 14 | class Solution(object): 15 | def twoSum(self, nums, target): 16 | mapping = {} 17 | 18 | for index, val in enumerate(nums): 19 | diff = target - val 20 | if diff in mapping: 21 | return [index, mapping[diff]] 22 | else: 23 | mapping[val] = index 24 | 25 | # Space: O(N) 26 | # Time: O(N) 27 | -------------------------------------------------------------------------------- /1-100q/65.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Validate if a given string is numeric. 3 | 4 | Some examples: 5 | "0" => true 6 | " 0.1 " => true 7 | "abc" => false 8 | "1 a" => false 9 | "2e10" => true 10 | 11 | Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. 12 | ''' 13 | 14 | class Solution(object): 15 | def isNumber(self, s): 16 | """ 17 | :type s: str 18 | :rtype: bool 19 | """ 20 | s = s.strip() 21 | try: 22 | if isinstance(float(s),float) or isinstance(int(s),int): 23 | return True 24 | except Exception as e: 25 | return False 26 | 27 | # Time: O(1) 28 | # Space: O(1) -------------------------------------------------------------------------------- /200-300q/206.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Reverse a singly linked list. 3 | 4 | Example: 5 | 6 | Input: 1->2->3->4->5->NULL 7 | Output: 5->4->3->2->1->NULL 8 | ''' 9 | 10 | # Definition for singly-linked list. 11 | # class ListNode(object): 12 | # def __init__(self, x): 13 | # self.val = x 14 | # self.next = None 15 | 16 | class Solution(object): 17 | def reverseList(self, head): 18 | """ 19 | :type head: ListNode 20 | :rtype: ListNode 21 | """ 22 | if not head: 23 | return None 24 | 25 | prev, curr = None, head 26 | while curr: 27 | temp = curr.next 28 | curr.next = prev 29 | prev = curr 30 | curr = temp 31 | return prev -------------------------------------------------------------------------------- /1-100q/53.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 3 | 4 | Example: 5 | 6 | Input: [-2,1,-3,4,-1,2,1,-5,4], 7 | Output: 6 8 | Explanation: [4,-1,2,1] has the largest sum = 6. 9 | ''' 10 | 11 | class Solution(object): 12 | def maxSubArray(self, nums): 13 | """ 14 | :type nums: List[int] 15 | :rtype: int 16 | """ 17 | if not nums: 18 | return 0 19 | 20 | currSum, result = nums[0], nums[0] 21 | 22 | for index in range(1, len(nums)): 23 | currSum = max(nums[index], currSum+nums[index]) 24 | result = max(result, currSum) 25 | 26 | return result -------------------------------------------------------------------------------- /400-500Q/454.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def fourSumCount(self, A, B, C, D): 3 | """ 4 | :type A: List[int] 5 | :type B: List[int] 6 | :type C: List[int] 7 | :type D: List[int] 8 | :rtype: int 9 | """ 10 | hashTable ={} 11 | 12 | for a in A: 13 | for b in B: 14 | if a+b in hashTable: 15 | hashTable[a+b] += 1 16 | else: 17 | hashTable[a+b] = 1 18 | 19 | result = 0 20 | for c in C: 21 | for d in D: 22 | if -(c+d) in hashTable: 23 | result += hashTable[-(c+d)] 24 | return result 25 | -------------------------------------------------------------------------------- /1-100q/48.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are given an n x n 2D matrix representing an image. 3 | 4 | Rotate the image by 90 degrees (clockwise). 5 | ''' 6 | class Solution(object): 7 | def rotate(self, matrix): 8 | """ 9 | :type matrix: List[List[int]] 10 | :rtype: void Do not return anything, modify matrix in-place instead. 11 | """ 12 | n = len(matrix) 13 | if n%2 == 0: 14 | m = n/2 15 | else: 16 | m = n/2 + 1 17 | 18 | for i in range(n/2): 19 | for j in range(m): 20 | temp = matrix[i][j] 21 | matrix[i][j] = matrix[n-j-1][i] 22 | matrix[n-j-1][i] = matrix[n-i-1][n-j-1] 23 | matrix[n-i-1][n-j-1] = matrix[j][n-i-1] 24 | matrix[j][n-i-1] = temp 25 | -------------------------------------------------------------------------------- /100-200q/141.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a linked list, determine if it has a cycle in it. 3 | 4 | Follow up: 5 | Can you solve it without using extra space? 6 | ''' 7 | 8 | # Definition for singly-linked list. 9 | # class ListNode(object): 10 | # def __init__(self, x): 11 | # self.val = x 12 | # self.next = None 13 | 14 | class Solution(object): 15 | def hasCycle(self, head): 16 | """ 17 | :type head: ListNode 18 | :rtype: bool 19 | """ 20 | 21 | if not head: 22 | return False 23 | 24 | slow, fast = head,head 25 | while fast and fast.next: 26 | slow = slow.next 27 | fast = fast.next.next 28 | if slow == fast: 29 | return True 30 | return False -------------------------------------------------------------------------------- /200-300q/234.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | def isPalindrome(self, head): 9 | """ 10 | :type head: ListNode 11 | :rtype: bool 12 | """ 13 | rev = None 14 | slow, fast = head, head.next 15 | while fast and fast.next: 16 | fast = fast.next.next 17 | temp = slow 18 | slow = slow.next 19 | temp.next = rev 20 | rev = temp 21 | 22 | if fast: 23 | slow = slow.next 24 | 25 | while rev and rev.val == slow.val: 26 | rev = rev.next 27 | slow = slow.next 28 | return not rev -------------------------------------------------------------------------------- /1-100q/73.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def setZeroes(self, matrix): 3 | """ 4 | :type matrix: List[List[int]] 5 | :rtype: void Do not return anything, modify matrix in-place instead. 6 | """ 7 | col0 = 1 8 | for row in range(len(matrix)): 9 | if matrix[row][0] == 0: 10 | col0 = 0 11 | for col in range(1, len(matrix[0])): 12 | if matrix[row][col] == 0: 13 | matrix[row][0] = 0 14 | matrix[0][col] = 0 15 | for row in range(len(matrix)-1, -1, -1): 16 | for col in range(len(matrix[0])-1, 0, -1): 17 | if matrix[row][0] == 0 or matrix[0][col] == 0: 18 | matrix[row][col] = 0 19 | if col0 == 0: 20 | matrix[row][0] = 0 21 | 22 | -------------------------------------------------------------------------------- /200-300q/215.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. 3 | 4 | Example 1: 5 | 6 | Input: [3,2,1,5,6,4] and k = 2 7 | Output: 5 8 | Example 2: 9 | 10 | Input: [3,2,3,1,2,4,5,5,6] and k = 4 11 | Output: 4 12 | ''' 13 | 14 | class Solution(object): 15 | def findKthLargest(self, nums, k): 16 | """ 17 | :type nums: List[int] 18 | :type k: int 19 | :rtype: int 20 | """ 21 | heap = [] 22 | import heapq 23 | for num in nums: 24 | heapq.heappush(heap, -(num)) 25 | 26 | result = 0 27 | for _ in range(k): 28 | result = heapq.heappop(heap) 29 | 30 | return -(result) 31 | -------------------------------------------------------------------------------- /100-200q/118.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. 3 | 4 | Example: 5 | 6 | Input: 5 7 | Output: 8 | [ 9 | [1], 10 | [1,1], 11 | [1,2,1], 12 | [1,3,3,1], 13 | [1,4,6,4,1] 14 | ] 15 | ''' 16 | class Solution(object): 17 | def generate(self, numRows): 18 | """ 19 | :type numRows: int 20 | :rtype: List[List[int]] 21 | """ 22 | triangle = [] 23 | 24 | for row in range(numRows): 25 | new_row = [0 for _ in range(row+1)] 26 | new_row[0], new_row[-1] = 1, 1 27 | 28 | for col in range(1, len(new_row)-1): 29 | new_row[col] = triangle[row-1][col-1] + triangle[row-1][col] 30 | triangle.append(new_row) 31 | return triangle -------------------------------------------------------------------------------- /100-200q/125.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numDistinct(self, s, t): 3 | """ 4 | :type s: str 5 | :type t: str 6 | :rtype: int 7 | """ 8 | 9 | row, col = len(s), len(t) 10 | 11 | if col > row: 12 | return 0 13 | 14 | dp = [[0 for _ in range(col+1)] for _ in range(row+1)] 15 | 16 | for r in range(row+1): 17 | for c in range(col+1): 18 | if r == 0 and c == 0: 19 | dp[r][c] = 1 20 | elif r == 0: 21 | dp[r][c] = 0 22 | elif c == 0: 23 | dp[r][c] = 1 24 | else: 25 | dp[r][c] = dp[r-1][c] 26 | if s[r-1] == t[c-1]: 27 | dp[r][c] += dp[r-1][c-1] 28 | return dp[row][col] 29 | 30 | # Time: O(N^2) 31 | # Space: O(N^2) -------------------------------------------------------------------------------- /1-100q/60.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def getPermutation(self, n, k): 3 | """ 4 | :type n: int 5 | :type k: int 6 | :rtype: str 7 | """ 8 | 9 | nums = [] 10 | for index in range(1, n+1): 11 | nums.append(index) 12 | 13 | def permute(nums): 14 | if len(nums) == 0: 15 | return [] 16 | if len(nums) == 1: 17 | return [nums] 18 | 19 | result = [] 20 | for index in range(len(nums)): 21 | for p in permute(nums[0:index] + nums[index+1:]): 22 | result.append([nums[index]] + p) 23 | 24 | return result 25 | 26 | value = permute(nums)[k-1] 27 | result = "" 28 | for val in value: 29 | result += str(val) 30 | return result -------------------------------------------------------------------------------- /1-100q/70.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are climbing a stair case. It takes n steps to reach to the top. 3 | 4 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 5 | 6 | Note: Given n will be a positive integer. 7 | 8 | Example 1: 9 | 10 | Input: 2 11 | Output: 2 12 | Explanation: There are two ways to climb to the top. 13 | 1. 1 step + 1 step 14 | 2. 2 steps 15 | ''' 16 | 17 | class Solution(object): 18 | def climbStairs(self, n): 19 | """ 20 | :type n: int 21 | :rtype: int 22 | """ 23 | if n == 0: 24 | return 0 25 | 26 | dp = [0]*n 27 | dp[0], dp[1] = 1, 2 28 | 29 | for index in range(2, n): 30 | dp[index] = dp[index-1] + dp[index-2] 31 | return dp[n-1] 32 | 33 | # Time: O(N) 34 | # Space: O(N) 35 | -------------------------------------------------------------------------------- /200-300q/238.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. 3 | 4 | Example: 5 | 6 | Input: [1,2,3,4] 7 | Output: [24,12,8,6] 8 | 1 1 2 6 9 | 12 8 6 10 | ''' 11 | 12 | class Solution(object): 13 | def productExceptSelf(self, nums): 14 | """ 15 | :type nums: List[int] 16 | :rtype: List[int] 17 | """ 18 | if not nums: 19 | return [] 20 | 21 | dp = [1]*len(nums) 22 | 23 | for index in range(1,len(nums)): 24 | dp[index] = dp[index-1]*nums[index-1] 25 | print dp 26 | right = 1 27 | for index in range(len(nums)-1, -1, -1): 28 | dp[index] *= right 29 | right *= nums[index] 30 | return dp -------------------------------------------------------------------------------- /400-500Q/442.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. 3 | 4 | Find all the elements that appear twice in this array. 5 | 6 | Could you do it without extra space and in O(n) runtime? 7 | 8 | Example: 9 | Input: 10 | [4,3,2,7,8,2,3,1] 11 | 12 | Output: 13 | [2,3] 14 | ''' 15 | 16 | class Solution(object): 17 | def findDuplicates(self, nums): 18 | """ 19 | :type nums: List[int] 20 | :rtype: List[int] 21 | """ 22 | if not nums: 23 | return [] 24 | 25 | result = [] 26 | for _, num in enumerate(nums): 27 | index = abs(num)-1 28 | if nums[index] < 0: 29 | result.append(index+1) 30 | nums[index]*=-1 31 | return result 32 | -------------------------------------------------------------------------------- /1-100q/24.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a linked list, swap every two adjacent nodes and return its head. 3 | 4 | Example: 5 | 6 | Given 1->2->3->4, you should return the list as 2->1->4->3. 7 | ''' 8 | 9 | # Definition for singly-linked list. 10 | # class ListNode(object): 11 | # def __init__(self, x): 12 | # self.val = x 13 | # self.next = None 14 | 15 | class Solution(object): 16 | def swapPairs(self, head): 17 | """ 18 | :type head: ListNode 19 | :rtype: ListNode 20 | """ 21 | 22 | if head is None: 23 | return head 24 | 25 | ref = head 26 | 27 | while ref is not None and ref.next is not None: 28 | ref.val, ref.next.val = ref.next.val, ref.val 29 | ref = ref.next.next 30 | 31 | return head -------------------------------------------------------------------------------- /1-100q/22.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 3 | 4 | For example, given n = 3, a solution set is: 5 | 6 | [ 7 | "((()))", 8 | "(()())", 9 | "(())()", 10 | "()(())", 11 | "()()()" 12 | ] 13 | ''' 14 | 15 | class Solution(object): 16 | def generateParenthesis(self, n): 17 | """ 18 | :type n: int 19 | :rtype: List[str] 20 | """ 21 | 22 | result = [] 23 | 24 | def backtracking(S, left, right): 25 | if len(S) == 2*n: 26 | result.append(S) 27 | return 28 | 29 | if left < n: 30 | backtracking(S+'(', left+1, right) 31 | 32 | if right < left: 33 | backtracking(S+')', left, right+1) 34 | 35 | backtracking('', 0, 0) 36 | return result -------------------------------------------------------------------------------- /200-300q/200.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numIslands(self, grid): 3 | """ 4 | :type grid: List[List[str]] 5 | :rtype: int 6 | """ 7 | if not grid: 8 | return 0 9 | 10 | count = 0 11 | for row in range(len(grid)): 12 | for col in range(len(grid[0])): 13 | if grid[row][col] == '1': 14 | count +=1 15 | self.merge(grid, row, col) 16 | 17 | return count 18 | 19 | def merge(self, grid, row, col): 20 | if 0 > row or row >= len(grid) or col < 0 or col >= len(grid[0]): 21 | return 22 | 23 | if grid[row][col] != '1': 24 | return 25 | 26 | grid[row][col] = '#' 27 | self.merge(grid, row+1, col) 28 | self.merge(grid, row-1, col) 29 | self.merge(grid, row, col+1) 30 | self.merge(grid, row, col-1) 31 | -------------------------------------------------------------------------------- /100-200q/128.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an unsorted array of integers, find the length of the longest consecutive elements sequence. 3 | 4 | Your algorithm should run in O(n) complexity. 5 | 6 | Example: 7 | 8 | Input: [100, 4, 200, 1, 3, 2] 9 | Output: 4 10 | Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. 11 | ''' 12 | 13 | class Solution(object): 14 | def longestConsecutive(self, nums): 15 | """ 16 | :type nums: List[int] 17 | :rtype: int 18 | """ 19 | result = 0 20 | nums = set(nums) 21 | 22 | for num in nums: 23 | if num-1 not in nums: 24 | curr = num 25 | length = 1 26 | 27 | while curr+1 in nums: 28 | curr += 1 29 | length += 1 30 | result = max(result, length) 31 | return result -------------------------------------------------------------------------------- /1200-1300q/1281.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer number n, return the difference between the product of its digits and the sum of its digits. 3 | 4 | 5 | Example 1: 6 | 7 | Input: n = 234 8 | Output: 15 9 | Explanation: 10 | Product of digits = 2 * 3 * 4 = 24 11 | Sum of digits = 2 + 3 + 4 = 9 12 | Result = 24 - 9 = 15 13 | Example 2: 14 | 15 | Input: n = 4421 16 | Output: 21 17 | Explanation: 18 | Product of digits = 4 * 4 * 2 * 1 = 32 19 | Sum of digits = 4 + 4 + 2 + 1 = 11 20 | Result = 32 - 11 = 21 21 | ''' 22 | 23 | class Solution(object): 24 | def subtractProductAndSum(self, n): 25 | """ 26 | :type n: int 27 | :rtype: int 28 | """ 29 | 30 | from functools import reduce 31 | from operator import mul 32 | digits = [int(x) for x in str(n)] 33 | return reduce(mul, digits) - sum(digits) 34 | -------------------------------------------------------------------------------- /1-100q/83.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a sorted linked list, delete all duplicates such that each element appear only once. 3 | 4 | Example 1: 5 | 6 | Input: 1->1->2 7 | Output: 1->2 8 | Example 2: 9 | 10 | Input: 1->1->2->3->3 11 | Output: 1->2->3 12 | ''' 13 | 14 | # Definition for singly-linked list. 15 | # class ListNode(object): 16 | # def __init__(self, x): 17 | # self.val = x 18 | # self.next = None 19 | 20 | class Solution(object): 21 | def deleteDuplicates(self, head): 22 | """ 23 | :type head: ListNode 24 | :rtype: ListNode 25 | """ 26 | if not head: 27 | return None 28 | 29 | curr = head 30 | while curr and curr.next: 31 | if curr.val == curr.next.val: 32 | curr.next = curr.next.next 33 | else: 34 | curr = curr.next 35 | 36 | return head -------------------------------------------------------------------------------- /1-100q/90.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set). 3 | 4 | Note: The solution set must not contain duplicate subsets. 5 | 6 | Example: 7 | 8 | Input: [1,2,2] 9 | Output: 10 | [ 11 | [2], 12 | [1], 13 | [1,2,2], 14 | [2,2], 15 | [1,2], 16 | [] 17 | ] 18 | ''' 19 | 20 | class Solution(object): 21 | def subsetsWithDup(self, nums): 22 | """ 23 | :type nums: List[int] 24 | :rtype: List[List[int]] 25 | """ 26 | result = [[]] 27 | for num in nums: 28 | for index in range(len(result)): 29 | new_list = result[index] + [num] 30 | new_list.sort() 31 | result.append(new_list) 32 | unique = set(tuple(val) for val in result) 33 | return list(list(val) for val in unique) -------------------------------------------------------------------------------- /200-300q/283.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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. 3 | 4 | Example: 5 | 6 | Input: [0,1,0,3,12] 7 | Output: [1,3,12,0,0] 8 | Note: 9 | 10 | You must do this in-place without making a copy of the array. 11 | Minimize the total number of operations. 12 | ''' 13 | 14 | class Solution(object): 15 | def moveZeroes(self, nums): 16 | """ 17 | :type nums: List[int] 18 | :rtype: void Do not return anything, modify nums in-place instead. 19 | """ 20 | zeroIndex = 0 21 | for index in range(len(nums)): 22 | if nums[index] != 0: 23 | nums[zeroIndex] = nums[index] 24 | zeroIndex += 1 25 | 26 | for index in range(zeroIndex, len(nums)): 27 | nums[index] = 0 -------------------------------------------------------------------------------- /300-400q/346.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. 3 | 4 | For example, 5 | MovingAverage m = new MovingAverage(3); 6 | m.next(1) = 1 7 | m.next(10) = (1 + 10) / 2 8 | m.next(3) = (1 + 10 + 3) / 3 9 | m.next(5) = (10 + 3 + 5) / 3 10 | ''' 11 | 12 | class Solution(object): 13 | def __init__(self): 14 | self.queue = [] 15 | self.curr_sum = 0 16 | 17 | def movingAverage(self, num, size): 18 | if len(self.queue) >= size: 19 | val = self.queue.pop(0) 20 | self.curr_sum -= val 21 | 22 | self.curr_sum += num 23 | self.queue.append(num) 24 | return float(self.curr_sum)/len(self.queue) 25 | 26 | 27 | 28 | solution = Solution() 29 | window_size = int(input()) 30 | num = int(input()) 31 | while num != -1: 32 | print solution.movingAverage(num, window_size) 33 | num = int(input()) -------------------------------------------------------------------------------- /1-100q/03.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string, find the length of the longest substring without repeating characters. 3 | 4 | Examples: 5 | 6 | Given "abcabcbb", the answer is "abc", which the length is 3. 7 | 8 | Given "bbbbb", the answer is "b", with the length of 1. 9 | 10 | Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. 11 | ''' 12 | 13 | class Solution(object): 14 | def lengthOfLongestSubstring(self, s): 15 | """ 16 | :type s: str 17 | :rtype: int 18 | """ 19 | mapSet = {} 20 | start, result = 0, 0 21 | 22 | for end in range(len(s)): 23 | if s[end] in mapSet: 24 | start = max(mapSet[s[end]], start) 25 | result = max(result, end-start+1) 26 | mapSet[s[end]] = end+1 27 | 28 | return result -------------------------------------------------------------------------------- /1000-1100q/1037.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A boomerang is a set of 3 points that are all distinct and not in a straight line. 3 | 4 | Given a list of three points in the plane, return whether these points are a boomerang. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: [[1,1],[2,3],[3,2]] 11 | Output: true 12 | Example 2: 13 | 14 | Input: [[1,1],[2,2],[3,3]] 15 | Output: false 16 | 17 | 18 | Note: 19 | 20 | points.length == 3 21 | points[i].length == 2 22 | 0 <= points[i][j] <= 100 23 | ''' 24 | 25 | class Solution(object): 26 | def isBoomerang(self, points): 27 | """ 28 | :type points: List[List[int]] 29 | :rtype: bool 30 | """ 31 | x1, x2, x3, y1, y2, y3 = points[0][0], points[1][0], points[2][0], points[0][1], points[1][1] ,points[2][1] 32 | if ((y3 - y2)*(x2 - x1) == (y2 - y1)*(x3 - x2)): 33 | return False 34 | return True 35 | -------------------------------------------------------------------------------- /1000-1100q/1074.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a matrix, and a target, return the number of non-empty submatrices that sum to target. 3 | 4 | A submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and y1 <= y <= y2. 5 | 6 | Two submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate that is different: for example, if x1 != x1'. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0 13 | Output: 4 14 | Explanation: The four 1x1 submatrices that only contain 0. 15 | Example 2: 16 | 17 | Input: matrix = [[1,-1],[-1,1]], target = 0 18 | Output: 5 19 | Explanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix. 20 | 21 | 22 | Note: 23 | 24 | 1 <= matrix.length <= 300 25 | 1 <= matrix[0].length <= 300 26 | -1000 <= matrix[i] <= 1000 27 | -10^8 <= target <= 10^8 28 | ''' -------------------------------------------------------------------------------- /200-300q/239.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | class Solution(object): 3 | def maxSlidingWindow(self, nums, k): 4 | """ 5 | :type nums: List[int] 6 | :type k: int 7 | :rtype: List[int] 8 | """ 9 | if len(nums) == 0: 10 | return [] 11 | q = deque() 12 | for i in range(k): 13 | while q and nums[i] >= nums[q[-1]]: 14 | q.pop() 15 | q.append(i) 16 | 17 | result = [] 18 | for i in range(k, len(nums)): 19 | result.append(nums[q[0]]) 20 | 21 | while q and q[0] <= i-k: 22 | q.popleft() 23 | while q and nums[i] >= nums[q[-1]]: 24 | q.pop() 25 | 26 | q.append(i) 27 | 28 | result.append(nums[q[0]]) 29 | return result 30 | -------------------------------------------------------------------------------- /300-400q/347.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a non-empty array of integers, return the k most frequent elements. 3 | 4 | For example, 5 | Given [1,1,1,2,2,3] and k = 2, return [1,2] 6 | ''' 7 | 8 | class Solution(object): 9 | def topKFrequent(self, nums, k): 10 | """ 11 | :type nums: List[int] 12 | :type k: int 13 | :rtype: List[int] 14 | """ 15 | if not nums: 16 | return [] 17 | frequency = {} 18 | for num in nums: 19 | if num in frequency: 20 | frequency[num] += 1 21 | else: 22 | frequency[num] = 1 23 | 24 | result = [] 25 | import heapq 26 | heap = [] 27 | 28 | for key, value in frequency.iteritems(): 29 | heapq.heappush(heap, (-value, key)) 30 | 31 | for _ in range(k): 32 | result.append(heapq.heappop(heap)[1]) 33 | return result -------------------------------------------------------------------------------- /1-100q/61.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | def rotateRight(self, head, k): 9 | """ 10 | :type head: ListNode 11 | :type k: int 12 | :rtype: ListNode 13 | """ 14 | if k == 0: 15 | return head 16 | if not head: 17 | return None 18 | 19 | tempHead, length = head, 1 20 | while tempHead.next: 21 | length += 1 22 | tempHead = tempHead.next 23 | 24 | tempHead.next = head 25 | jump = (length-k)%length 26 | 27 | previous = tempHead 28 | while jump > 0: 29 | previous = previous.next 30 | jump -= 1 31 | head = previous.next 32 | previous.next = None 33 | 34 | return head -------------------------------------------------------------------------------- /100-200q/140.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def wordBreak(self, s, wordDict): 3 | """ 4 | :type s: str 5 | :type wordDict: List[str] 6 | :rtype: List[str] 7 | """ 8 | self.result = [] 9 | self.dfs(s, wordDict, '') 10 | return self.result 11 | 12 | def dfs(self, s, wordDict, currStr): 13 | if self.check(s, wordDict): 14 | if len(s) == 0: 15 | self.result.append(currStr[1:]) 16 | for i in range(1, len(s)+1): 17 | if s[:i] in wordDict: 18 | self.dfs(s[i:], wordDict, currStr + ' ' + s[:i]) 19 | 20 | def check(self, s, wordDict): 21 | dp = [False for _ in range(len(s)+1)] 22 | dp[0] = True 23 | 24 | for i in range(len(s)): 25 | for j in range(i, -1, -1): 26 | if dp[j] and s[j:i+1] in wordDict: 27 | dp[i+1] = True 28 | break 29 | 30 | return dp[len(s)] -------------------------------------------------------------------------------- /1200-1300q/1295.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array nums of integers, return how many of them contain an even number of digits. 3 | 4 | 5 | Example 1: 6 | 7 | Input: nums = [12,345,2,6,7896] 8 | Output: 2 9 | Explanation: 10 | 12 contains 2 digits (even number of digits). 11 | 345 contains 3 digits (odd number of digits). 12 | 2 contains 1 digit (odd number of digits). 13 | 6 contains 1 digit (odd number of digits). 14 | 7896 contains 4 digits (even number of digits). 15 | Therefore only 12 and 7896 contain an even number of digits. 16 | Example 2: 17 | 18 | Input: nums = [555,901,482,1771] 19 | Output: 1 20 | Explanation: 21 | Only 1771 contains an even number of digits. 22 | ''' 23 | class Solution(object): 24 | def findNumbers(self, nums): 25 | """ 26 | :type nums: List[int] 27 | :rtype: int 28 | """ 29 | return len([num for num in nums if len(str(num))%2 == 0]) -------------------------------------------------------------------------------- /200-300q/287.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. 3 | 4 | Example 1: 5 | 6 | Input: [1,3,4,2,2] 7 | Output: 2 8 | Example 2: 9 | 10 | Input: [3,1,3,4,2] 11 | Output: 3 12 | ''' 13 | 14 | class Solution(object): 15 | def findDuplicate(self, nums): 16 | """ 17 | :type nums: List[int] 18 | :rtype: int 19 | """ 20 | slow, fast = nums[0], nums[0] 21 | while True: 22 | slow = nums[slow] 23 | fast = nums[nums[fast]] 24 | if slow == fast: 25 | break 26 | 27 | num1= nums[0] 28 | num2 = slow 29 | while num1 != num2: 30 | num1 = nums[num1] 31 | num2 = nums[num2] 32 | return num2 -------------------------------------------------------------------------------- /1000-1100q/1073.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two numbers arr1 and arr2 in base -2, return the result of adding them together. 3 | 4 | Each number is given in array format: as an array of 0s and 1s, from most significant bit to least significant bit. For example, arr = [1,1,0,1] represents the number (-2)^3 + (-2)^2 + (-2)^0 = -3. A number arr in array format is also guaranteed to have no leading zeros: either arr == [0] or arr[0] == 1. 5 | 6 | Return the result of adding arr1 and arr2 in the same format: as an array of 0s and 1s with no leading zeros. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: arr1 = [1,1,1,1,1], arr2 = [1,0,1] 13 | Output: [1,0,0,0,0] 14 | Explanation: arr1 represents 11, arr2 represents 5, the output represents 16. 15 | 16 | 17 | Note: 18 | 19 | 1 <= arr1.length <= 1000 20 | 1 <= arr2.length <= 1000 21 | arr1 and arr2 have no leading zeros 22 | arr1[i] is 0 or 1 23 | arr2[i] is 0 or 1 24 | ''' -------------------------------------------------------------------------------- /1-100q/11.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. 3 | 4 | Note: You may not slant the container and n is at least 2. 5 | 6 | ''' 7 | 8 | class Solution(object): 9 | def maxArea(self, height): 10 | """ 11 | :type height: List[int] 12 | :rtype: int 13 | """ 14 | left, right, maxArea = 0, len(height) - 1, 0 15 | 16 | while left < right: 17 | maxArea = max(maxArea, min(height[left], height[right])*(right-left)) 18 | if height[left] < height[right]: 19 | left += 1 20 | else: 21 | right -= 1 22 | 23 | return maxArea 24 | 25 | # Space : O(1) 26 | # Time: O(N) -------------------------------------------------------------------------------- /1-100q/62.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). 3 | 4 | The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). 5 | 6 | How many possible unique paths are there? 7 | ''' 8 | 9 | class Solution(object): 10 | def uniquePaths(self, m, n): 11 | """ 12 | :type m: int 13 | :type n: int 14 | :rtype: int 15 | """ 16 | dp = [[0 for _ in range(n)] for _ in range(m)] 17 | for index in range(m): 18 | dp[index][0] = 1 19 | 20 | for index in range(n): 21 | dp[0][index] = 1 22 | 23 | for index_i in range(1, m): 24 | for index_j in range(1, n): 25 | dp[index_i][index_j] = dp[index_i-1][index_j] + dp[index_i][index_j-1] 26 | 27 | return dp[m-1][n-1] -------------------------------------------------------------------------------- /100-200q/147.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | def insertionSortList(self, head): 9 | """ 10 | :type head: ListNode 11 | :rtype: ListNode 12 | """ 13 | 14 | if not head: 15 | return None 16 | 17 | sortedList = head 18 | head = head.next 19 | sortedList.next = None 20 | 21 | while head: 22 | curr = head 23 | head = head.next 24 | if curr.val <= sortedList.val: 25 | curr.next = sortedList 26 | sortedList = curr 27 | else: 28 | temp = sortedList 29 | while temp.next and temp.next.val < curr.val: 30 | temp = temp.next 31 | curr.next = temp.next 32 | temp.next = curr 33 | return sortedList -------------------------------------------------------------------------------- /1000-1100q/1051.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Students are asked to stand in non-decreasing order of heights for an annual photo. 3 | 4 | Return the minimum number of students not standing in the right positions. (This is the number of students that must move in order for all students to be standing in non-decreasing order of height.) 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: [1,1,4,2,1,3] 11 | Output: 3 12 | Explanation: 13 | Students with heights 4, 3 and the last 1 are not standing in the right positions. 14 | 15 | 16 | Note: 17 | 18 | 1 <= heights.length <= 100 19 | 1 <= heights[i] <= 100 20 | ''' 21 | 22 | class Solution(object): 23 | def heightChecker(self, heights): 24 | """ 25 | :type heights: List[int] 26 | :rtype: int 27 | """ 28 | result = 0 29 | for new_h, hei in zip(heights, sorted(heights)): 30 | if new_h != hei: 31 | result += 1 32 | return result 33 | -------------------------------------------------------------------------------- /1000-1100q/1072.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a matrix consisting of 0s and 1s, we may choose any number of columns in the matrix and flip every cell in that column. Flipping a cell changes the value of that cell from 0 to 1 or from 1 to 0. 3 | 4 | Return the maximum number of rows that have all values equal after some number of flips. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: [[0,1],[1,1]] 11 | Output: 1 12 | Explanation: After flipping no values, 1 row has all values equal. 13 | Example 2: 14 | 15 | Input: [[0,1],[1,0]] 16 | Output: 2 17 | Explanation: After flipping values in the first column, both rows have equal values. 18 | Example 3: 19 | 20 | Input: [[0,0,0],[0,0,1],[1,1,0]] 21 | Output: 2 22 | Explanation: After flipping values in the first two columns, the last two rows have equal values. 23 | 24 | 25 | Note: 26 | 27 | 1 <= matrix.length <= 300 28 | 1 <= matrix[i].length <= 300 29 | All matrix[i].length's are equal 30 | matrix[i][j] is 0 or 1 31 | ''' -------------------------------------------------------------------------------- /200-300q/279.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. 3 | 4 | Example 1: 5 | 6 | Input: n = 12 7 | Output: 3 8 | Explanation: 12 = 4 + 4 + 4. 9 | Example 2: 10 | 11 | Input: n = 13 12 | Output: 2 13 | Explanation: 13 = 4 + 9. 14 | ''' 15 | 16 | class Solution(object): 17 | def numSquares(self, n): 18 | """ 19 | :type n: int 20 | :rtype: int 21 | """ 22 | mapping = {} 23 | squares = [num*num for num in range(1, int(pow(n, 0.5)) + 1)] 24 | for square in squares: 25 | mapping[square] = 1 26 | 27 | for val in range(1, n+1): 28 | if val not in mapping: 29 | mapping[val] = float('inf') 30 | for square in squares: 31 | if square < val: 32 | mapping[val] = min(mapping[val], mapping[square] + mapping[val-square]) 33 | return mapping[n] -------------------------------------------------------------------------------- /200-300q/285.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary search tree and a node in it, find the in-order successor of that node in the BST. 3 | Note: If the given node has no in-order successor in the tree, return null 4 | ''' 5 | 6 | # Definition for a binary tree node. 7 | # class TreeNode(object): 8 | # def __init__(self, x): 9 | # self.val = x 10 | # self.left = None 11 | # self.right = None 12 | 13 | class Solution(object): 14 | def inorderSuccessor(self, root, p): 15 | """ 16 | :type root: TreeNode 17 | :type p: TreeNode 18 | :rtype: TreeNode 19 | """ 20 | 21 | if not root or not p: 22 | return None 23 | 24 | if p.right: 25 | p = p.right 26 | while p.left: 27 | p = p.left 28 | return p 29 | 30 | successor = None 31 | while root and root != p: 32 | if root.val > p.val: 33 | successor = root 34 | root = root.left 35 | else: 36 | root = root.right 37 | return successor -------------------------------------------------------------------------------- /300-400q/334.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array. 3 | 4 | Formally the function should: 5 | Return true if there exists i, j, k 6 | such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false. 7 | Your algorithm should run in O(n) time complexity and O(1) space complexity. 8 | 9 | Examples: 10 | Given [1, 2, 3, 4, 5], 11 | return true. 12 | 13 | Given [5, 4, 3, 2, 1], 14 | return false. 15 | ''' 16 | 17 | class Solution(object): 18 | def increasingTriplet(self, nums): 19 | """ 20 | :type nums: List[int] 21 | :rtype: bool 22 | """ 23 | 24 | first, second = float('inf'), float('inf') 25 | for val in nums: 26 | if val <= first: 27 | first = val 28 | elif val <= second: 29 | second = val 30 | else: 31 | return True 32 | 33 | return False -------------------------------------------------------------------------------- /300-400q/340.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string, find the longest substring that contains only two unique characters. For example, given "abcbbbbcccbdddadacb", the longest substring that contains 2 unique character is "bcbbbbcccb". 3 | ''' 4 | 5 | class Solution(object): 6 | def lengthOfLongestSubstringKDistinct(self, S, K): 7 | charMapping, start = {}, 0 8 | result = 0 9 | for end, s in enumerate(S): 10 | if s in charMapping: 11 | charMapping[s] += 1 12 | else: 13 | charMapping[s] = 1 14 | 15 | if len(charMapping) <= K: 16 | result = max(result, end-start+1) 17 | else: 18 | while len(charMapping) > K : 19 | character = S[start] 20 | freq = charMapping[character] 21 | if freq == 1: 22 | del charMapping[character] 23 | else: 24 | charMapping[character] -= 1 25 | start += 1 26 | return result 27 | 28 | if __name__ == '__main__': 29 | print Solution().lengthOfLongestSubstringKDistinct("abcadcacacaca", 3) -------------------------------------------------------------------------------- /1000-1100q/1064.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array A of distinct integers sorted in ascending order, return the smallest index i that satisfies A[i] == i. Return -1 if no such i exists. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: [-10,-5,0,3,7] 9 | Output: 3 10 | Explanation: 11 | For the given array, A[0] = -10, A[1] = -5, A[2] = 0, A[3] = 3, thus the output is 3. 12 | Example 2: 13 | 14 | Input: [0,2,5,8,17] 15 | Output: 0 16 | Explanation: 17 | A[0] = 0, thus the output is 0. 18 | Example 3: 19 | 20 | Input: [-10,-5,3,4,7,9] 21 | Output: -1 22 | Explanation: 23 | There is no such i that A[i] = i, thus the output is -1. 24 | ''' 25 | 26 | class Solution(object): 27 | def fixedPoint(self, A): 28 | """ 29 | :type A: List[int] 30 | :rtype: int 31 | """ 32 | if not A: 33 | return -1 34 | for index, num in enumerate(A): 35 | if num == index: 36 | return index 37 | return -1 38 | -------------------------------------------------------------------------------- /900-1000q/991.py: -------------------------------------------------------------------------------- 1 | ''' 2 | On a broken calculator that has a number showing on its display, we can perform two operations: 3 | 4 | Double: Multiply the number on the display by 2, or; 5 | Decrement: Subtract 1 from the number on the display. 6 | Initially, the calculator is displaying the number X. 7 | 8 | Return the minimum number of operations needed to display the number Y. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: X = 2, Y = 3 15 | Output: 2 16 | Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}. 17 | ''' 18 | 19 | class Solution(object): 20 | def brokenCalc(self, X, Y): 21 | """ 22 | :type X: int 23 | :type Y: int 24 | :rtype: int 25 | """ 26 | if X == Y: 27 | return 0 28 | if X > Y: 29 | return X-Y 30 | if(Y%2 == 1): 31 | return 1 + self.brokenCalc(X, Y+1) 32 | else: 33 | return 1 + self.brokenCalc(X, Y/2) 34 | -------------------------------------------------------------------------------- /1-100q/42.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. 3 | ''' 4 | 5 | class Solution(object): 6 | def trap(self, height): 7 | """ 8 | :type height: List[int] 9 | :rtype: int 10 | """ 11 | if not height: 12 | return 0 13 | 14 | left, right = 0, len(height) - 1 15 | leftMax, rightMax = 0, 0 16 | result = 0 17 | while left < right: 18 | if height[left] < height[right]: 19 | if height[left] > leftMax: 20 | leftMax = height[left] 21 | else: 22 | result += (leftMax - height[left]) 23 | left += 1 24 | else: 25 | if height[right] > rightMax: 26 | rightMax = height[right] 27 | else: 28 | result += (rightMax - height[right]) 29 | right -= 1 30 | 31 | return result -------------------------------------------------------------------------------- /200-300q/281.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two 1d vectors, implement an iterator to return their elements alternately. 3 | 4 | For example, given two 1d vectors: 5 | 6 | v1 = [1, 2] 7 | v2 = [3, 4, 5, 6] 8 | By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1, 3, 2, 4, 5, 6]. 9 | ''' 10 | 11 | class Solution(object): 12 | def __init__(self, v1, v2): 13 | self.v1 = v1 14 | self.v2 = v2 15 | self.index_v1 = 0 16 | self.index_v2 = 0 17 | 18 | def next(self): 19 | result = -1 20 | if self.index_v1 != len(self.v1) and self.index_v1 <= self.index_v2: 21 | result = self.v1[self.index_v1] 22 | self.index_v1 += 1 23 | else: 24 | result = self.v2[self.index_v2] 25 | self.index_v2 += 1 26 | 27 | return result 28 | 29 | def hasNext(self): 30 | return self.index_v1 < len(self.v1) or self.index_v2 < len(self.v2) 31 | 32 | 33 | solution = Solution([1, 2], [3, 4, 5, 6]) 34 | while solution.hasNext(): 35 | print solution.next() -------------------------------------------------------------------------------- /400-500Q/448.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. 3 | 4 | Find all the elements of [1, n] inclusive that do not appear in this array. 5 | 6 | Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. 7 | 8 | Example: 9 | 10 | Input: 11 | [4,3,2,7,8,2,3,1] 12 | 13 | Output: 14 | [5,6] 15 | ''' 16 | 17 | class Solution(object): 18 | def findDisappearedNumbers(self, nums): 19 | """ 20 | :type nums: List[int] 21 | :rtype: List[int] 22 | """ 23 | if not nums: 24 | return [] 25 | result = [] 26 | for num in nums: 27 | index = abs(num)-1 28 | if nums[index] > 0: 29 | nums[index]*=-1 30 | for index, num in enumerate(nums): 31 | if num >0: 32 | result.append(index+1) 33 | return result 34 | -------------------------------------------------------------------------------- /1000-1100q/1016.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary string S (a string consisting only of '0' and '1's) and a positive integer N, return true if and only if for every integer X from 1 to N, the binary representation of X is a substring of S. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: S = "0110", N = 3 9 | Output: true 10 | Example 2: 11 | 12 | Input: S = "0110", N = 4 13 | Output: false 14 | 15 | 16 | Note: 17 | 18 | 1 <= S.length <= 1000 19 | 1 <= N <= 10^9 20 | ''' 21 | 22 | class Solution(object): 23 | def queryString(self, S, N): 24 | """ 25 | :type S: str 26 | :type N: int 27 | :rtype: bool 28 | """ 29 | for num in range(1, N+1): 30 | binary_str = '' 31 | while (num != 0): 32 | binary_str += str(num%2) 33 | num /= 2 34 | reversed_str = binary_str[::-1] 35 | 36 | if reversed_str not in S: 37 | return False 38 | return True 39 | -------------------------------------------------------------------------------- /1-100q/26.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 3 | Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. 4 | 5 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 6 | 7 | Example 1: 8 | 9 | Given nums = [1,1,2], 10 | 11 | Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. 12 | 13 | It doesn't matter what you leave beyond the returned length. 14 | 15 | ''' 16 | 17 | class Solution(object): 18 | def removeDuplicates(self, nums): 19 | """ 20 | :type nums: List[int] 21 | :rtype: int 22 | """ 23 | if not nums: 24 | return 0 25 | 26 | index_i = 0 27 | 28 | for index_j in range(1, len(nums)): 29 | if nums[index_i] != nums[index_j]: 30 | index_i += 1 31 | nums[index_i] = nums[index_j] 32 | 33 | return index_i + 1 -------------------------------------------------------------------------------- /1-100q/45.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 3 | 4 | Each element in the array represents your maximum jump length at that position. 5 | 6 | Your goal is to reach the last index in the minimum number of jumps. 7 | 8 | Example: 9 | 10 | Input: [2,3,1,1,4] 11 | Output: 2 12 | Explanation: The minimum number of jumps to reach the last index is 2. 13 | Jump 1 step from index 0 to 1, then 3 steps to the last index. 14 | 15 | 16 | ''' 17 | class Solution(object): 18 | def jump(self, nums): 19 | """ 20 | :type nums: List[int] 21 | :rtype: int 22 | """ 23 | steps, lastRearch, maxReach = 0, 0 ,0 24 | 25 | for index in range(len(nums)): 26 | if index > lastRearch: 27 | lastRearch = maxReach 28 | steps += 1 29 | maxReach = max(maxReach, index + nums[index]) 30 | 31 | return steps if maxReach == len(nums) - 1 else 0 32 | -------------------------------------------------------------------------------- /1000-1100q/1015.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a positive integer K, you need find the smallest positive integer N such that N is divisible by K, and N only contains the digit 1. 3 | 4 | Return the length of N. If there is no such N, return -1. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: 1 11 | Output: 1 12 | Explanation: The smallest answer is N = 1, which has length 1. 13 | Example 2: 14 | 15 | Input: 2 16 | Output: -1 17 | Explanation: There is no such positive integer N divisible by 2. 18 | Example 3: 19 | 20 | Input: 3 21 | Output: 3 22 | Explanation: The smallest answer is N = 111, which has length 3. 23 | ''' 24 | 25 | class Solution(object): 26 | def smallestRepunitDivByK(self, K): 27 | """ 28 | :type K: int 29 | :rtype: int 30 | """ 31 | length, value = 0, 0 32 | for no_one in range(100000): 33 | value = (10*value + 1)%K 34 | length += 1 35 | if value == 0: 36 | return length 37 | return -1 38 | -------------------------------------------------------------------------------- /200-300q/253.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of meeting time intervals consisting of start and end times [[s1,e1], [s2,e2],…] (si < ei), find the minimum number of conference rooms required. 3 | For example, 4 | Given [[0, 30],[5, 10],[15, 20]], 5 | return 2. 6 | ''' 7 | 8 | 9 | # Definition for an interval. 10 | # class Interval(object): 11 | # def __init__(self, s=0, e=0): 12 | # self.start = s 13 | # self.end = e 14 | 15 | class Solution: 16 | def minMeetingRooms(self, intervals): 17 | if not intervals or len(intervals) == 0: 18 | return 0 19 | 20 | import heapq 21 | 22 | sorted_intervals = sorted(intervals, key=lambda it:(it.start, it.end)) 23 | heap, result = [], 0 24 | 25 | for interval in sorted_intervals: 26 | start, end = interval.start, interval.end 27 | 28 | while heap and heap[0] <= start: 29 | heapq.heappop(heap) 30 | 31 | heapq.heappush(heap, end) 32 | 33 | result = max(result, len(heap)) 34 | return result -------------------------------------------------------------------------------- /300-400q/322.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. 3 | 4 | Example 1: 5 | coins = [1, 2, 5], amount = 11 6 | return 3 (11 = 5 + 5 + 1) 7 | 8 | Example 2: 9 | coins = [2], amount = 3 10 | return -1. 11 | ''' 12 | 13 | class Solution(object): 14 | def coinChange(self, coins, amount): 15 | """ 16 | :type coins: List[int] 17 | :type amount: int 18 | :rtype: int 19 | """ 20 | if not coins: 21 | return 0 22 | 23 | dp = [float('inf') for _ in range(amount+1)] 24 | dp[0] = 0 25 | 26 | for val in range(1, amount+1): 27 | for coin in coins: 28 | if coin <= val: 29 | dp[val] = min(dp[val-coin]+1, dp[val]) 30 | return dp[amount] if dp[amount] != float('inf') else -1 -------------------------------------------------------------------------------- /1-100q/41.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an unsorted integer array, find the smallest missing positive integer. 3 | 4 | Example 1: 5 | 6 | Input: [1,2,0] 7 | Output: 3 8 | Example 2: 9 | 10 | Input: [3,4,-1,1] 11 | Output: 2 12 | Example 3: 13 | 14 | Input: [7,8,9,11,12] 15 | Output: 1 16 | ''' 17 | class Solution(object): 18 | def firstMissingPositive(self, nums): 19 | """ 20 | :type nums: List[int] 21 | :rtype: int 22 | """ 23 | index_i = 0 24 | for index_j in range(len(nums)): 25 | if nums[index_j] <= 0: 26 | nums[index_i], nums[index_j] = nums[index_j], nums[index_i] 27 | index_i += 1 28 | 29 | for index in range(index_i, len(nums)): 30 | if abs(nums[index]) - 1 < len(nums) and nums[abs(nums[index]) - 1] > 0: 31 | nums[abs(nums[index]) - 1] = -nums[abs(nums[index]) - 1] 32 | 33 | for index in range(nums): 34 | if nums[index] > 0: 35 | return index + 1 36 | return len(nums) + 1 -------------------------------------------------------------------------------- /100-200q/160.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a program to find the node at which the intersection of two singly linked lists begins. 3 | 4 | 5 | For example, the following two linked lists: 6 | 7 | A: a1 → a2 8 | ↘ 9 | c1 → c2 → c3 10 | ↗ 11 | B: b1 → b2 → b3 12 | begin to intersect at node c1. 13 | ''' 14 | 15 | # Definition for singly-linked list. 16 | # class ListNode(object): 17 | # def __init__(self, x): 18 | # self.val = x 19 | # self.next = None 20 | 21 | class Solution(object): 22 | def getIntersectionNode(self, headA, headB): 23 | """ 24 | :type head1, head1: ListNode 25 | :rtype: ListNode 26 | """ 27 | if not headA or not headB: 28 | return None 29 | 30 | pa, pb = headA, headB 31 | while pa != pb: 32 | pa = pa.next if pa is not None else headB 33 | pb = pb.next if pb is not None else headA 34 | 35 | return pa if pa else None -------------------------------------------------------------------------------- /100-200q/142.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a linked list, return the node where the cycle begins. If there is no cycle, return null. 3 | 4 | Note: Do not modify the linked list. 5 | 6 | Follow up: 7 | Can you solve it without using extra space? 8 | ''' 9 | # Definition for singly-linked list. 10 | # class ListNode(object): 11 | # def __init__(self, x): 12 | # self.val = x 13 | # self.next = None 14 | 15 | class Solution(object): 16 | def detectCycle(self, head): 17 | """ 18 | :type head: ListNode 19 | :rtype: ListNode 20 | """ 21 | if not head: 22 | return None 23 | 24 | slow, fast = head, head.next 25 | 26 | while fast and fast.next: 27 | slow = slow.next 28 | fast = fast.next.next 29 | if slow == fast: 30 | break 31 | 32 | if slow == fast: 33 | slow = head 34 | while slow != fast: 35 | slow = slow.next 36 | fast = fast.next 37 | return slow 38 | return None -------------------------------------------------------------------------------- /1100-1200q/1189.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible. 3 | You can use each character in text at most once. Return the maximum number of instances that can be formed. 4 | 5 | 6 | Example 1: 7 | Input: text = "nlaebolko" 8 | Output: 1 9 | 10 | Example 2: 11 | Input: text = "loonbalxballpoon" 12 | Output: 2 13 | 14 | Example 3: 15 | Input: text = "leetcode" 16 | Output: 0 17 | 18 | 19 | Constraints: 20 | 21 | 1 <= text.length <= 10^4 22 | text consists of lower case English letters only. 23 | ''' 24 | 25 | class Solution(object): 26 | def maxNumberOfBalloons(self, text): 27 | """ 28 | :type text: str 29 | :rtype: int 30 | """ 31 | if not text: 32 | return 0 33 | 34 | import collections 35 | cnt = collections.Counter(text) 36 | cnt_ballon = collections.Counter('balloon') 37 | 38 | return min([cnt[c]//cnt_ballon[c] for c in cnt_ballon]) 39 | -------------------------------------------------------------------------------- /1-100q/74.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 3 | 4 | Integers in each row are sorted from left to right. 5 | The first integer of each row is greater than the last integer of the previous row. 6 | Example 1: 7 | 8 | Input: 9 | matrix = [ 10 | [1, 3, 5, 7], 11 | [10, 11, 16, 20], 12 | [23, 30, 34, 50] 13 | ] 14 | target = 3 15 | Output: true 16 | ''' 17 | class Solution(object): 18 | def searchMatrix(self, matrix, target): 19 | """ 20 | :type matrix: List[List[int]] 21 | :type target: int 22 | :rtype: bool 23 | """ 24 | 25 | if not matrix: 26 | return 0 27 | left, right = 0, len(matrix[0])-1 28 | 29 | while left < len(matrix) and right >= 0: 30 | if matrix[left][right] == target: 31 | return True 32 | elif matrix[left][right] < target: 33 | left += 1 34 | else: 35 | right -= 1 36 | return False -------------------------------------------------------------------------------- /1000-1100q/1014.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array A of positive integers, A[i] represents the value of the i-th sightseeing spot, and two sightseeing spots i and j have distance j - i between them. 3 | 4 | The score of a pair (i < j) of sightseeing spots is (A[i] + A[j] + i - j) : the sum of the values of the sightseeing spots, minus the distance between them. 5 | 6 | Return the maximum score of a pair of sightseeing spots. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: [8,1,5,2,6] 13 | Output: 11 14 | Explanation: i = 0, j = 2, A[i] + A[j] + i - j = 8 + 5 + 0 - 2 = 11 15 | 16 | 17 | Note: 18 | 19 | 2 <= A.length <= 50000 20 | 1 <= A[i] <= 1000 21 | ''' 22 | class Solution(object): 23 | def maxScoreSightseeingPair(self, A): 24 | """ 25 | :type A: List[int] 26 | :rtype: int 27 | """ 28 | prev_best, result = 0, 0 29 | for index in range(0, len(A)): 30 | result = max(result, A[index]-index+prev_best) 31 | prev_best = max(prev_best, A[index]+index) 32 | return result 33 | -------------------------------------------------------------------------------- /100-200q/139.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. 3 | 4 | Note: 5 | 6 | The same word in the dictionary may be reused multiple times in the segmentation. 7 | You may assume the dictionary does not contain duplicate words. 8 | Example 1: 9 | 10 | Input: s = "leetcode", wordDict = ["leet", "code"] 11 | Output: true 12 | Explanation: Return true because "leetcode" can be segmented as "leet code". 13 | ''' 14 | 15 | class Solution(object): 16 | def wordBreak(self, s, wordDict): 17 | """ 18 | :type s: str 19 | :type wordDict: List[str] 20 | :rtype: bool 21 | """ 22 | dp = [False for _ in range(len(s)+1)] 23 | dp[0] = True 24 | for index in range(len(s)): 25 | for j in range(i, -1, -1): 26 | if dp[j] and s[j:i+1] in wordDict: 27 | dp[i+1] = True 28 | break 29 | return dp[len(s)] -------------------------------------------------------------------------------- /900-1000q/995.py: -------------------------------------------------------------------------------- 1 | ''' 2 | In an array A containing only 0s and 1s, a K-bit flip consists of choosing a (contiguous) subarray of length K and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0. 3 | 4 | Return the minimum number of K-bit flips required so that there is no 0 in the array. If it is not possible, return -1. 5 | 6 | Input: A = [0,1,0], K = 1 7 | Output: 2 8 | Explanation: Flip A[0], then flip A[2] 9 | ''' 10 | 11 | class Solution: 12 | def minKBitFlips(self, a: 'List[int]', k: 'int') -> 'int': 13 | from collections import deque 14 | q = deque() 15 | res = 0 16 | for i in range(len(a)): 17 | if len(q) % 2 != 0: 18 | if a[i] == 1: 19 | res += 1 20 | q.append(i+k-1) 21 | else: 22 | if a[i] == 0: 23 | res += 1 24 | q.append(i+k-1) 25 | if q and q[0] == i: q.popleft() 26 | if q and q[-1] >= len(a): return -1 27 | return res -------------------------------------------------------------------------------- /600-700q/674.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray). 3 | 4 | Example 1: 5 | Input: [1,3,5,4,7] 6 | Output: 3 7 | Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3. 8 | Even though [1,3,5,7] is also an increasing subsequence, it's not a continuous one where 5 and 7 are separated by 4. 9 | 10 | Example 2: 11 | Input: [2,2,2,2,2] 12 | Output: 1 13 | 14 | Explanation: The longest continuous increasing subsequence is [2], its length is 1. 15 | Note: Length of the array will not exceed 10,000. 16 | ''' 17 | 18 | class Solution(object): 19 | def findLengthOfLCIS(self, nums): 20 | """ 21 | :type nums: List[int] 22 | :rtype: int 23 | """ 24 | if not nums: 25 | return 0 26 | start, result = 0, 1 27 | for end in range(1, len(nums)): 28 | if nums[end-1] >= nums[end]: 29 | start = end 30 | result = max(result, end-start+1) 31 | return result 32 | -------------------------------------------------------------------------------- /1-100q/19.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a linked list, remove the n-th node from the end of list and return its head. 3 | 4 | Example: 5 | 6 | Given linked list: 1->2->3->4->5, and n = 2. 7 | 8 | After removing the second node from the end, the linked list becomes 1->2->3->5. 9 | 10 | ''' 11 | 12 | # Definition for singly-linked list. 13 | # class ListNode(object): 14 | # def __init__(self, x): 15 | # self.val = x 16 | # self.next = None 17 | 18 | class Solution(object): 19 | def removeNthFromEnd(self, head, n): 20 | """ 21 | :type head: ListNode 22 | :type n: int 23 | :rtype: ListNode 24 | """ 25 | if not head: 26 | return None 27 | 28 | ref = head 29 | while n > 0: 30 | ref = ref.next 31 | n -= 1 32 | 33 | if ref is None: 34 | return head.next 35 | else: 36 | main = head 37 | while ref.next: 38 | main = main.next 39 | ref = ref.next 40 | 41 | main.next = main.next.next 42 | return head -------------------------------------------------------------------------------- /Extra/lcp.py: -------------------------------------------------------------------------------- 1 | from suffix_array import SuffixArray 2 | 3 | class LCP(object): 4 | def __init__(self, s): 5 | self.s = s 6 | self.lcp_array = [] 7 | self.suffix_array = SuffixArray(s) 8 | self.suffix_array.create_suffix_array() 9 | 10 | def lcp_w_suffix_str(self): 11 | N = len(self.suffix_array.suffix_array) 12 | array = self.suffix_array.suffix_array 13 | 14 | self.lcp_array = [0]*N 15 | inv_suffix = [0]*N 16 | 17 | for index in range(N): 18 | inv_suffix[array[index].index] = index 19 | 20 | maxLen = 0 21 | 22 | for index in range(N): 23 | if inv_suffix[index] == N-1: 24 | maxLen = 0 25 | continue 26 | 27 | index_j = array[inv_suffix[index]+1].index 28 | while(index+maxLen < N and index_j+maxLen < N and self.s[index+maxLen] == self.s[index_j+maxLen]): 29 | maxLen += 1 30 | 31 | self.lcp_array[inv_suffix[index]] = maxLen 32 | 33 | if maxLen > 0: 34 | maxLen -= 1 35 | 36 | return self.lcp_array 37 | 38 | 39 | if __name__ == '__main__': 40 | lcp = LCP("banana") 41 | lcp.lcp_w_suffix_str() 42 | print lcp.lcp_array -------------------------------------------------------------------------------- /1-100q/64.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. 3 | 4 | Note: You can only move either down or right at any point in time. 5 | ''' 6 | class Solution(object): 7 | def minPathSum(self, grid): 8 | """ 9 | :type grid: List[List[int]] 10 | :rtype: int 11 | """ 12 | if not grid: 13 | return 0 14 | 15 | row, col = len(grid), len(grid[0]) 16 | dp = [[0 for _ in range(col)] for _ in range(row)] 17 | dp[0][0] = grid[0][0] 18 | 19 | for index in range(1, row): 20 | dp[index][0] = dp[index-1][0] + grid[index][0] 21 | 22 | for index in range(1, col): 23 | dp[0][index] = dp[0][index-1] + grid[0][index] 24 | 25 | print dp 26 | for index_i in range(1, row): 27 | for index_j in range(1, col): 28 | dp[index_i][index_j] = min(dp[index_i-1][index_j], dp[index_i][index_j-1]) + grid[index_i][index_j] 29 | 30 | return dp[row-1][col-1] -------------------------------------------------------------------------------- /1-100q/80.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length. 3 | 4 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 5 | 6 | Example 1: 7 | 8 | Given nums = [1,1,1,2,2,3], 9 | 10 | Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively. 11 | 12 | It doesn't matter what you leave beyond the returned length. 13 | ''' 14 | 15 | class Solution(object): 16 | def removeDuplicates(self, nums): 17 | """ 18 | :type nums: List[int] 19 | :rtype: int 20 | """ 21 | if len(nums) <= 2: 22 | return len(nums) 23 | 24 | prev, curr = 1, 2 25 | 26 | while curr < len(nums): 27 | if nums[prev] == nums[curr] and nums[curr] == nums[prev-1]: 28 | curr += 1 29 | else: 30 | prev += 1 31 | nums[prev] = nums[curr] 32 | curr += 1 33 | return prev+1 34 | -------------------------------------------------------------------------------- /100-200q/112.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 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. 3 | 4 | Note: A leaf is a node with no children. 5 | 6 | Example: 7 | 8 | Given the below binary tree and sum = 22, 9 | 10 | 5 11 | / \ 12 | 4 8 13 | / / \ 14 | 11 13 4 15 | / \ \ 16 | 7 2 1 17 | ''' 18 | 19 | 20 | # Definition for a binary tree node. 21 | # class TreeNode(object): 22 | # def __init__(self, x): 23 | # self.val = x 24 | # self.left = None 25 | # self.right = None 26 | 27 | class Solution(object): 28 | def hasPathSum(self, root, sum): 29 | """ 30 | :type root: TreeNode 31 | :type sum: int 32 | :rtype: bool 33 | """ 34 | if not root: 35 | return False 36 | 37 | if not root.left and not root.right and root.val == sum: 38 | return True 39 | 40 | return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val) -------------------------------------------------------------------------------- /200-300q/298.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree, find the length of the longest consecutive sequence path. 3 | 4 | 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). 5 | 6 | For example, 7 | 1 8 | \ 9 | 3 10 | / \ 11 | 2 4 12 | \ 13 | 5 14 | Longest consecutive sequence path is 3-4-5, so return 3. 15 | 2 16 | \ 17 | 3 18 | / 19 | 2 20 | / 21 | 1 22 | Longest consecutive sequence path is 2-3,not3-2-1, so return 2. 23 | ''' 24 | 25 | 26 | class Solution(object): 27 | def dfs(curr, parent, length): 28 | if not curr: 29 | return length 30 | if parent: 31 | length = length + 1 if curr.val == parent.val + 1 32 | else: 33 | length = 1 34 | 35 | return max(length, max(dfs(curr.left, curr, length), dfs(curr.right, curr, length))) 36 | 37 | def longestConsecutive(TreeNode root): 38 | if not root: 39 | return 0 40 | 41 | return dfs(root, null, 0) 42 | -------------------------------------------------------------------------------- /1-100q/82.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. 3 | 4 | Example 1: 5 | 6 | Input: 1->2->3->3->4->4->5 7 | Output: 1->2->5 8 | Example 2: 9 | 10 | Input: 1->1->1->2->3 11 | Output: 2->3 12 | ''' 13 | 14 | # Definition for singly-linked list. 15 | # class ListNode(object): 16 | # def __init__(self, x): 17 | # self.val = x 18 | # self.next = None 19 | 20 | class Solution(object): 21 | def deleteDuplicates(self, head): 22 | """ 23 | :type head: ListNode 24 | :rtype: ListNode 25 | """ 26 | if not head: 27 | return None 28 | 29 | result = ListNode(0) 30 | ans = result 31 | curr = head 32 | while curr: 33 | value = curr.val 34 | count = 0 35 | while curr and curr.val == value: 36 | curr = curr.next 37 | count += 1 38 | if count == 1: 39 | result.next = ListNode(value) 40 | result = result.next 41 | return ans.next -------------------------------------------------------------------------------- /300-400q/328.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. 3 | 4 | You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity. 5 | 6 | Example: 7 | Given 1->2->3->4->5->NULL, 8 | return 1->3->5->2->4->NULL. 9 | ''' 10 | 11 | # Definition for singly-linked list. 12 | # class ListNode(object): 13 | # def __init__(self, x): 14 | # self.val = x 15 | # self.next = None 16 | 17 | class Solution(object): 18 | def oddEvenList(self, head): 19 | """ 20 | :type head: ListNode 21 | :rtype: ListNode 22 | """ 23 | if not head: 24 | return None 25 | 26 | odd, even = head, head.next 27 | evenHead = even 28 | while even and even.next: 29 | odd.next = even.next 30 | odd = odd.next 31 | even.next = odd.next 32 | even = even.next 33 | 34 | odd.next = evenHead 35 | return head -------------------------------------------------------------------------------- /1000-1100q/1017.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a number N, return a string consisting of "0"s and "1"s that represents its value in base -2 (negative two). 3 | 4 | The returned string must have no leading zeroes, unless the string is "0". 5 | 6 | 7 | Example 1: 8 | 9 | Input: 2 10 | Output: "110" 11 | Explantion: (-2) ^ 2 + (-2) ^ 1 = 2 12 | Example 2: 13 | 14 | Input: 3 15 | Output: "111" 16 | Explantion: (-2) ^ 2 + (-2) ^ 1 + (-2) ^ 0 = 3 17 | 18 | Example 3: 19 | 20 | Input: 4 21 | Output: "100" 22 | Explantion: (-2) ^ 2 = 4 23 | 24 | 25 | Note: 26 | 27 | 0 <= N <= 10^9 28 | ''' 29 | 30 | class Solution(object): 31 | def baseNeg2(self, N): 32 | """ 33 | :type N: int 34 | :rtype: str 35 | """ 36 | if N == 0: 37 | digits = ['0'] 38 | else: 39 | digits = [] 40 | while N != 0: 41 | N, remainder = divmod(N, -2) 42 | if remainder < 0: 43 | N, remainder = N+1, remainder + 2 44 | digits.append(str(remainder)) 45 | return ''.join(digits[::-1]) 46 | -------------------------------------------------------------------------------- /100-200q/134.py: -------------------------------------------------------------------------------- 1 | ''' 2 | There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. 3 | 4 | You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations. 5 | 6 | Return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. 7 | ''' 8 | 9 | class Solution(object): 10 | def canCompleteCircuit(self, gas, cost): 11 | """ 12 | :type gas: List[int] 13 | :type cost: List[int] 14 | :rtype: int 15 | """ 16 | start, curr_sum, total_sum =0, 0, 0 17 | for index in range(len(gas)): 18 | diff = gas[index] - cost[index] 19 | total_sum += diff 20 | curr_sum += diff 21 | 22 | if curr_sum < 0: 23 | start = index + 1 24 | curr_sum = 0 25 | 26 | if total_sum >= 0: 27 | return start 28 | return -1 -------------------------------------------------------------------------------- /100-200q/159.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string, find the longest substring that contains only two unique characters. For example, given "abcbbbbcccbdddadacb", the longest substring that contains 2 unique character is "bcbbbbcccb". 3 | ''' 4 | 5 | class Solution(object): 6 | def lengthOfLongestSubstringTwoDistinct(self, s): 7 | """ 8 | :type s: str 9 | :rtype: int 10 | """ 11 | if not s: 12 | return 0 13 | 14 | unique_char, start, result = {}, 0, 0 15 | for index, char in enumerate(s): 16 | if char in unique_char: 17 | unique_char[s] += 1 18 | else: 19 | unique_char[s] = 1 20 | 21 | if len(unique_char) <= 2: 22 | result = max(result, index-start+1) 23 | else: 24 | while len(unique_char) > 2: 25 | char_index = s[start] 26 | count = unique_char[char_index] 27 | if count == 1: 28 | del unique_char[char_index] 29 | else: 30 | unique_char[char_index] -= 1 31 | start += 1 32 | return result 33 | -------------------------------------------------------------------------------- /1-100q/06.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) 3 | 4 | P A H N 5 | A P L S I I G 6 | Y I R 7 | 8 | And then read line by line: "PAHNAPLSIIGYIR" 9 | ''' 10 | 11 | class Solution(object): 12 | def convert(self, s, numRows): 13 | """ 14 | :type s: str 15 | :type numRows: int 16 | :rtype: str 17 | """ 18 | 19 | if numRows == 1: 20 | return s 21 | 22 | result = ["" for _ in range(numRows)] 23 | row, down = 0, 1 24 | for char in s: 25 | result[row] += char 26 | 27 | if row == numRows - 1: 28 | down = 0 29 | if row == 0: 30 | down = 1 31 | 32 | if down: 33 | row += 1 34 | else: 35 | row -= 1 36 | final_string = "" 37 | for value in result: 38 | final_string += value 39 | return final_string 40 | 41 | print Solution().convert("PAYPALISHIRING",3) -------------------------------------------------------------------------------- /1-100q/66.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a non-empty array of digits representing a non-negative integer, plus one to the integer. 3 | 4 | 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. 5 | 6 | You may assume the integer does not contain any leading zero, except the number 0 itself. 7 | 8 | Example 1: 9 | 10 | Input: [1,2,3] 11 | Output: [1,2,4] 12 | Explanation: The array represents the integer 123 13 | ''' 14 | 15 | class Solution(object): 16 | def plusOne(self, digits): 17 | """ 18 | :type digits: List[int] 19 | :rtype: List[int] 20 | """ 21 | result = [] 22 | if not digits: 23 | return [] 24 | 25 | carry = 1 26 | new_digits = digits[::-1] 27 | 28 | for index in range(len(new_digits)): 29 | new_digits[index], carry = (new_digits[index] + carry)%10, (new_digits[index] + carry)/10 30 | 31 | if carry > 0: 32 | new_digits.append(carry) 33 | return new_digits[::-1] 34 | 35 | Time: O(N) 36 | Space: O(1) -------------------------------------------------------------------------------- /100-200q/111.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree, find its minimum depth. 3 | 4 | The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 5 | 6 | Note: A leaf is a node with no children. 7 | 8 | Example: 9 | 10 | Given binary tree [3,9,20,null,null,15,7], 11 | 12 | 3 13 | / \ 14 | 9 20 15 | / \ 16 | 15 7 17 | 18 | return its minimum depth = 2. 19 | ''' 20 | 21 | # Definition for a binary tree node. 22 | # class TreeNode(object): 23 | # def __init__(self, x): 24 | # self.val = x 25 | # self.left = None 26 | # self.right = None 27 | 28 | class Solution(object): 29 | def minDepth(self, root): 30 | if not root: 31 | return 0 32 | depth = float('inf') 33 | stack = [(root, 1)] 34 | 35 | while stack: 36 | node, level = stack.pop() 37 | if node: 38 | 39 | if not node.left and not node.right: 40 | depth = min(depth, level) 41 | 42 | stack.append((node.left, level+1)) 43 | stack.append((node.right, level+1)) 44 | 45 | return depth -------------------------------------------------------------------------------- /1-100q/75.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. 3 | 4 | Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. 5 | 6 | Note: You are not suppose to use the library's sort function for this problem. 7 | 8 | Example: 9 | 10 | Input: [2,0,2,1,1,0] 11 | Output: [0,0,1,1,2,2] 12 | ''' 13 | class Solution(object): 14 | def sortColors(self, nums): 15 | """ 16 | :type nums: List[int] 17 | :rtype: void Do not return anything, modify nums in-place instead. 18 | """ 19 | zero, last = 0, len(nums)-1 20 | index = 0 21 | while index <= last: 22 | if nums[index] == 1: 23 | index += 1 24 | elif nums[index] == 0: 25 | nums[index], nums[zero] = nums[zero], nums[index] 26 | index += 1 27 | zero += 1 28 | elif nums[index] == 2: 29 | nums[last], nums[index] = nums[index], nums[last] 30 | last -= 1 -------------------------------------------------------------------------------- /900-1000q/988.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given the root of a binary tree, each node has a value from 0 to 25 representing the letters 'a' to 'z': a value of 0 represents 'a', a value of 1 represents 'b', and so on. 3 | 4 | Find the lexicographically smallest string that starts at a leaf of this tree and ends at the root. 5 | ''' 6 | # Definition for a binary tree node. 7 | # class TreeNode(object): 8 | # def __init__(self, x): 9 | # self.val = x 10 | # self.left = None 11 | # self.right = None 12 | 13 | class Solution(object): 14 | def smallestFromLeaf(self, root): 15 | """ 16 | :type root: TreeNode 17 | :rtype: str 18 | """ 19 | self.result = "~" 20 | 21 | def dfs(node, A): 22 | if node: 23 | A.append(chr(node.val + ord('a'))) 24 | if not node.left and not node.right: 25 | self.result = min(self.result, "".join(reversed(A))) 26 | 27 | dfs(node.left, A) 28 | dfs(node.right, A) 29 | A.pop() 30 | dfs(root, []) 31 | return self.result 32 | -------------------------------------------------------------------------------- /100-200q/143.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | def reorderList(self, head): 9 | """ 10 | :type head: ListNode 11 | :rtype: void Do not return anything, modify head in-place instead. 12 | """ 13 | if not head: 14 | return None 15 | 16 | slow, fast = head, head.next 17 | 18 | while fast and fast.next: 19 | slow = slow.next 20 | fast = fast.next.next 21 | 22 | head1, head2 = head, slow.next 23 | slow.next = None 24 | prev = None 25 | curr = head2 26 | while curr: 27 | nex = curr.next 28 | curr.next = prev 29 | prev = curr 30 | curr = nex 31 | head2 = prev 32 | 33 | while head2: 34 | n1 = head1.next 35 | n2 = head2.next 36 | head1.next = head2 37 | head1.next.next = n1 38 | head2 = n2 39 | head1 = head1.next.next 40 | 41 | head = head1 42 | -------------------------------------------------------------------------------- /1000-1100q/1085.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array A of positive integers, let S be the sum of the digits of the minimal element of A. 3 | 4 | Return 0 if S is odd, otherwise return 1. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: [34,23,1,24,75,33,54,8] 11 | Output: 0 12 | Explanation: 13 | The minimal element is 1, and the sum of those digits is S = 1 which is odd, so the answer is 0. 14 | Example 2: 15 | 16 | Input: [99,77,33,66,55] 17 | Output: 1 18 | Explanation: 19 | The minimal element is 33, and the sum of those digits is S = 3 + 3 = 6 which is even, so the answer is 1. 20 | 21 | 22 | Note: 23 | 24 | 1 <= A.length <= 100 25 | 1 <= A[i].length <= 100 26 | ''' 27 | class Solution(object): 28 | def sumOfDigits(self, A): 29 | """ 30 | :type A: List[int] 31 | :rtype: int 32 | """ 33 | if not A: 34 | return 0 35 | 36 | mini = min(A) 37 | result = 0 38 | while mini > 0: 39 | quo = mini%10 40 | rem = mini/10 41 | result += quo 42 | mini = rem 43 | 44 | return 0 if result%2 else 1 45 | -------------------------------------------------------------------------------- /900-1000q/977.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: [-4,-1,0,3,10] 9 | Output: [0,1,9,16,100] 10 | Example 2: 11 | 12 | Input: [-7,-3,2,3,11] 13 | Output: [4,9,9,49,121] 14 | ''' 15 | 16 | class Solution(object): 17 | def sortedSquares(self, A): 18 | """ 19 | :type A: List[int] 20 | :rtype: List[int] 21 | """ 22 | N = len(A) 23 | j = 0 24 | while j = 0 and j < N: 29 | if A[i]**2 < A[j]**2: 30 | result.append(A[i]**2) 31 | i -= 1 32 | else: 33 | result.append(A[j]**2) 34 | j += 1 35 | while i>= 0: 36 | result.append(A[i]**2) 37 | i -= 1 38 | 39 | while j < N: 40 | result.append(A[j]**2) 41 | j += 1 42 | 43 | return result 44 | -------------------------------------------------------------------------------- /100-200q/101.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 3 | 4 | For example, this binary tree [1,2,2,3,4,4,3] is symmetric: 5 | 6 | 1 7 | / \ 8 | 2 2 9 | / \ / \ 10 | 3 4 4 3 11 | 12 | But the following [1,2,2,null,3,null,3] is not: 13 | 14 | 1 15 | / \ 16 | 2 2 17 | \ \ 18 | 3 3 19 | 20 | ''' 21 | 22 | # Definition for a binary tree node. 23 | # class TreeNode(object): 24 | # def __init__(self, x): 25 | # self.val = x 26 | # self.left = None 27 | # self.right = None 28 | 29 | class Solution(object): 30 | def isSymmetric(self, root): 31 | """ 32 | :type root: TreeNode 33 | :rtype: bool 34 | """ 35 | if not root: 36 | return True 37 | 38 | def dfs(left, right): 39 | if not left and not right: 40 | return True 41 | 42 | if not left or not right: 43 | return False 44 | return (left.val == right.val) and dfs(left.left, right.right) and dfs(left.right, right.left) 45 | 46 | return dfs(root, root) -------------------------------------------------------------------------------- /300-400q/378.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix. 3 | 4 | Note that it is the kth smallest element in the sorted order, not the kth distinct element. 5 | 6 | Example: 7 | 8 | matrix = [ 9 | [ 1, 5, 9], 10 | [10, 11, 13], 11 | [12, 13, 15] 12 | ], 13 | k = 8, 14 | 15 | return 13. 16 | ''' 17 | 18 | class Solution(object): 19 | def kthSmallest(self, matrix, k): 20 | """ 21 | :type matrix: List[List[int]] 22 | :type k: int 23 | :rtype: int 24 | """ 25 | 26 | if not matrix: 27 | return 0 28 | 29 | import heapq 30 | heap = [] 31 | for col in range(len(matrix[0])): 32 | heapq.heappush(heap, (matrix[0][col], 0, col)) 33 | 34 | val = 0 35 | for index in range(k): 36 | val, row, col = heapq.heappop(heap) 37 | new_val = float('inf') 38 | if row < len(matrix)-1: 39 | new_val = matrix[row+1][col] 40 | heapq.heappush(heap, (new_val, row+1, col)) 41 | return val -------------------------------------------------------------------------------- /1-100q/54.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. 3 | 4 | Example 1: 5 | 6 | Input: 7 | [ 8 | [ 1, 2, 3 ], 9 | [ 4, 5, 6 ], 10 | [ 7, 8, 9 ] 11 | ] 12 | Output: [1,2,3,6,9,8,7,4,5] 13 | ''' 14 | 15 | class Solution(object): 16 | def spiralOrder(self, matrix): 17 | """ 18 | :type matrix: List[List[int]] 19 | :rtype: List[int] 20 | """ 21 | if not matrix: 22 | return [] 23 | 24 | R, C = len(matrix), len(matrix[0]) 25 | dr = [0, 1, 0, -1] 26 | dc = [1, 0, -1, 0] 27 | 28 | result = [] 29 | seen = [[False]*C for _ in range(R)] 30 | row = 0 31 | col = 0 32 | di = 0 33 | for _ in range(R*C): 34 | result.append(matrix[row][col]) 35 | seen[row][col] = True 36 | rr, cc = row + dr[di], col + dc[di] 37 | if 0 <= rr < R and 0 <= cc < C and not seen[rr][cc]: 38 | row, col = rr, cc 39 | else: 40 | di = (di+1)%4 41 | row, col = row + dr[di], col + dc[di] 42 | 43 | return result -------------------------------------------------------------------------------- /1-100q/39.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. 3 | 4 | The same repeated number may be chosen from candidates unlimited number of times. 5 | 6 | Note: 7 | 8 | All numbers (including target) will be positive integers. 9 | The solution set must not contain duplicate combinations. 10 | ''' 11 | 12 | class Solution(object): 13 | def combinationSum(self, candidates, target): 14 | """ 15 | :type candidates: List[int] 16 | :type target: int 17 | :rtype: List[List[int]] 18 | """ 19 | 20 | result = [] 21 | 22 | def recursive(candidates, target, currList, index): 23 | if target < 0: 24 | return 25 | if target == 0: 26 | result.append(currList) 27 | return 28 | 29 | for start in range(index, len(candidates)): 30 | recursive(candidates, target - candidates[start], currList + [candidates[start]], start) 31 | 32 | recursive(candidates, target, [], 0) 33 | return result 34 | -------------------------------------------------------------------------------- /1-100q/93.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string containing only digits, restore it by returning all possible valid IP address combinations. 3 | 4 | Example: 5 | 6 | Input: "25525511135" 7 | Output: ["255.255.11.135", "255.255.111.35"] 8 | ''' 9 | 10 | class Solution(object): 11 | def restoreIpAddresses(self, s): 12 | """ 13 | :type s: str 14 | :rtype: List[str] 15 | """ 16 | result = [] 17 | 18 | def dfs(s, temp, count): 19 | if count == 4: 20 | if not s: 21 | result.append(temp[:-1]) 22 | return 23 | 24 | for index in range(1, 4): 25 | if index <= len(s): 26 | if index == 1: 27 | dfs(s[index:], temp + s[:index] + ".", count+1) 28 | elif index ==2 and s[0] != '0': 29 | dfs(s[index:], temp + s[:index] + ".", count+1) 30 | elif index == 3 and s[0] != '0' and int(s[:3]) <= 255: 31 | dfs(s[index:], temp + s[:index] + ".", count+1) 32 | 33 | dfs(s, "", 0) 34 | return result -------------------------------------------------------------------------------- /1-100q/17.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. 3 | 4 | A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. 5 | ''' 6 | 7 | class Solution(object): 8 | def letterCombinations(self, digits): 9 | """ 10 | :type digits: str 11 | :rtype: List[str] 12 | """ 13 | 14 | phoneMap = { '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7' : 'pqrs', '8': 'tuv', '9':'wxyz'} 15 | number = str(digits) 16 | 17 | if number == "": 18 | return [] 19 | 20 | result = [''] 21 | for char in number: 22 | values = phoneMap[char] 23 | new_result = [] 24 | for prefix in result: 25 | currElement = prefix 26 | for value in values: 27 | new_result.append(currElement+value) 28 | 29 | result = new_result 30 | # result = [prefix+value for prefix in result for value in values] 31 | return result 32 | 33 | print Solution().letterCombinations("23") -------------------------------------------------------------------------------- /200-300q/240.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 3 | 4 | Integers in each row are sorted in ascending from left to right. 5 | Integers in each column are sorted in ascending from top to bottom. 6 | Consider the following matrix: 7 | 8 | [ 9 | [1, 4, 7, 11, 15], 10 | [2, 5, 8, 12, 19], 11 | [3, 6, 9, 16, 22], 12 | [10, 13, 14, 17, 24], 13 | [18, 21, 23, 26, 30] 14 | ] 15 | Example 1: 16 | 17 | Input: matrix, target = 5 18 | Output: true 19 | ''' 20 | 21 | class Solution(object): 22 | def searchMatrix(self, matrix, target): 23 | """ 24 | :type matrix: List[List[int]] 25 | :type target: int 26 | :rtype: bool 27 | """ 28 | 29 | if not matrix: 30 | return False 31 | 32 | left, right = 0, len(matrix[0])-1 33 | while left < len(matrix) and right >= 0: 34 | if matrix[left][right] == target: 35 | return True 36 | elif matrix[left][right] < target: 37 | left += 1 38 | else: 39 | right -= 1 40 | return False -------------------------------------------------------------------------------- /1-100q/92.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Reverse a linked list from position m to n. Do it in one-pass. 3 | 4 | Note: 1 ≤ m ≤ n ≤ length of list. 5 | 6 | Example: 7 | 8 | Input: 1->2->3->4->5->NULL, m = 2, n = 4 9 | Output: 1->4->3->2->5->NULL 10 | ''' 11 | 12 | # Definition for singly-linked list. 13 | # class ListNode(object): 14 | # def __init__(self, x): 15 | # self.val = x 16 | # self.next = None 17 | 18 | class Solution(object): 19 | def reverseBetween(self, head, m, n): 20 | """ 21 | :type head: ListNode 22 | :type m: int 23 | :type n: int 24 | :rtype: ListNode 25 | """ 26 | if m == n : 27 | return head 28 | 29 | result = ListNode(0) 30 | result.next = head 31 | 32 | prev = result 33 | 34 | for index in range(m-1): 35 | prev = prev.next 36 | 37 | reverse = None 38 | curr = prev.next 39 | for i in range(n-m+1): 40 | temp = curr.next 41 | curr.next = reverse 42 | reverse = curr 43 | curr = temp 44 | 45 | prev.next.next = curr 46 | prev.next = reverse 47 | return result.next -------------------------------------------------------------------------------- /100-200q/123.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Say you have an array for which the ith element is the price of a given stock on day i. 3 | 4 | Design an algorithm to find the maximum profit. You may complete at most two transactions. 5 | 6 | Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). 7 | 8 | Example 1: 9 | 10 | Input: [3,3,5,0,0,3,1,4] 11 | Output: 6 12 | Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. 13 | Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. 14 | 15 | ''' 16 | 17 | class Solution(object): 18 | def maxProfit(self, prices): 19 | """ 20 | :type prices: List[int] 21 | :rtype: int 22 | """ 23 | if len(prices) < 2: 24 | return 0 25 | dp = [[0 for _ in range(len(prices))] for _ in range(3)] 26 | for i in range(1,3): 27 | maxDiff = -prices[0] 28 | for j in range(1,len(prices)): 29 | dp[i][j] = max(dp[i][j-1], prices[j] + maxDiff) 30 | maxDiff = max(maxDiff, dp[i-1][j] -prices[j]) 31 | 32 | return dp[2][len(prices)-1] 33 | 34 | -------------------------------------------------------------------------------- /1000-1100q/1018.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array A of 0s and 1s, consider N_i: the i-th subarray from A[0] to A[i] interpreted as a binary number (from most-significant-bit to least-significant-bit.) 3 | 4 | Return a list of booleans answer, where answer[i] is true if and only if N_i is divisible by 5. 5 | 6 | Example 1: 7 | 8 | Input: [0,1,1] 9 | Output: [true,false,false] 10 | Explanation: 11 | The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10. Only the first number is divisible by 5, so answer[0] is true. 12 | Example 2: 13 | 14 | Input: [1,1,1] 15 | Output: [false,false,false] 16 | 17 | Note: 18 | 19 | 1 <= A.length <= 30000 20 | A[i] is 0 or 1 21 | ''' 22 | 23 | class Solution(object): 24 | def prefixesDivBy5(self, A): 25 | """ 26 | :type A: List[int] 27 | :rtype: List[bool] 28 | """ 29 | result = [] 30 | if not A: 31 | return [] 32 | str_bin = '' 33 | for val in A: 34 | str_bin += str(val) 35 | if(int(str_bin, 2)%5 == 0): 36 | result.append(True) 37 | else: 38 | result.append(False) 39 | return result 40 | -------------------------------------------------------------------------------- /100-200q/153.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 3 | 4 | (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). 5 | 6 | Find the minimum element. 7 | 8 | You may assume no duplicate exists in the array. 9 | 10 | Example 1: 11 | 12 | Input: [3,4,5,1,2] 13 | Output: 1 14 | Example 2: 15 | 16 | Input: [4,5,6,7,0,1,2] 17 | Output: 0 18 | ''' 19 | 20 | class Solution(object): 21 | def findMin(self, nums): 22 | """ 23 | :type nums: List[int] 24 | :rtype: int 25 | """ 26 | if not nums: 27 | return 0 28 | 29 | if len(nums) == 1: 30 | return nums[0] 31 | left, right = 0, len(nums)-1 32 | 33 | if nums[left] < nums[right]: 34 | return nums[left] 35 | while left <= right: 36 | while nums[left] == nums[right] and left != right: 37 | left += 1 38 | 39 | if nums[left] <= nums[right]: 40 | return nums[left] 41 | 42 | mid = (left + right)/2 43 | if nums[mid] >= nums[left]: 44 | left = mid+1 45 | else: 46 | right = mid 47 | return -1 -------------------------------------------------------------------------------- /100-200q/152.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. 3 | 4 | Example 1: 5 | 6 | Input: [2,3,-2,4] 7 | Output: 6 8 | Explanation: [2,3] has the largest product 6. 9 | 10 | Example 2: 11 | 12 | Input: [-2,0,-1] 13 | Output: 0 14 | Explanation: The result cannot be 2, because [-2,-1] is not a subarray. 15 | ''' 16 | 17 | class Solution(object): 18 | def maxProduct(self, nums): 19 | """ 20 | :type nums: List[int] 21 | :rtype: int 22 | """ 23 | 24 | if not nums: 25 | return 0 26 | 27 | max_so_far, min_so_far, result = nums[0], nums[0], nums[0] 28 | 29 | for index in range(1, len(nums)): 30 | if nums[index] > 0: 31 | max_so_far = max(max_so_far*nums[index], nums[index]) 32 | min_so_far = min(min_so_far*nums[index], nums[index]) 33 | else: 34 | temp = max_so_far 35 | max_so_far = max(min_so_far*nums[index], nums[index]) 36 | min_so_far = min(temp*nums[index], nums[index]) 37 | 38 | result = max(result, max_so_far) 39 | return result -------------------------------------------------------------------------------- /1-100q/94.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree, return the inorder traversal of its nodes' values. 3 | 4 | Example: 5 | 6 | Input: [1,null,2,3] 7 | 1 8 | \ 9 | 2 10 | / 11 | 3 12 | 13 | Output: [1,3,2] 14 | 15 | Follow up: Recursive solution is trivial, could you do it iteratively? 16 | ''' 17 | 18 | # Definition for a binary tree node. 19 | # class TreeNode(object): 20 | # def __init__(self, x): 21 | # self.val = x 22 | # self.left = None 23 | # self.right = None 24 | 25 | class Solution(object): 26 | def inorderTraversal(self, root): 27 | """ 28 | :type root: TreeNode 29 | :rtype: List[int] 30 | """ 31 | if not root: 32 | return [] 33 | 34 | stack, result = [root], [] 35 | while stack: 36 | if root.left: 37 | stack.append(root.left) 38 | root = root.left 39 | else: 40 | node = stack.pop() 41 | result.append(node.val) 42 | 43 | if node.right: 44 | stack.append(node.right) 45 | root = node.right 46 | return result -------------------------------------------------------------------------------- /100-200q/199.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. 3 | 4 | Example: 5 | 6 | Input: [1,2,3,null,5,null,4] 7 | Output: [1, 3, 4] 8 | Explanation: 9 | 10 | 1 <--- 11 | / \ 12 | 2 3 <--- 13 | \ \ 14 | 5 4 <--- 15 | ''' 16 | 17 | # Definition for a binary tree node. 18 | # class TreeNode(object): 19 | # def __init__(self, x): 20 | # self.val = x 21 | # self.left = None 22 | # self.right = None 23 | 24 | class Solution(object): 25 | def rightSideView(self, root): 26 | """ 27 | :type root: TreeNode 28 | :rtype: List[int] 29 | """ 30 | if not root: 31 | return [] 32 | 33 | stack, node_depth = [(root, 0)], {} 34 | 35 | while stack: 36 | node, depth = stack.pop(0) 37 | if depth not in node_depth: 38 | node_depth[depth] = node.val 39 | 40 | if node.right: 41 | stack.append((node.right, depth+1)) 42 | if node.left: 43 | stack.append((node.left, depth+1)) 44 | return node_depth.values() -------------------------------------------------------------------------------- /1000-1100q/1004.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array A of 0s and 1s, we may change up to K values from 0 to 1. 3 | 4 | Return the length of the longest (contiguous) subarray that contains only 1s. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2 11 | Output: 6 12 | Explanation: 13 | [1,1,1,0,0,1,1,1,1,1,1] 14 | Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. 15 | Example 2: 16 | 17 | Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3 18 | Output: 10 19 | Explanation: 20 | [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1] 21 | Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. 22 | 23 | 24 | Note: 25 | 26 | 1 <= A.length <= 20000 27 | 0 <= K <= A.length 28 | A[i] is 0 or 1 29 | ''' 30 | 31 | class Solution(object): 32 | def longestOnes(self, A, K): 33 | """ 34 | :type A: List[int] 35 | :type K: int 36 | :rtype: int 37 | """ 38 | start_index = 0 39 | for end_index in range(0, len(A)): 40 | K -= 1-A[end_index] 41 | if K < 0: 42 | K += 1-A[start_index] 43 | start_index += 1 44 | return end_index-start_index+1 45 | -------------------------------------------------------------------------------- /1200-1300q/1290.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number. 3 | 4 | Return the decimal value of the number in the linked list. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | 11 | Input: head = [1,0,1] 12 | Output: 5 13 | Explanation: (101) in base 2 = (5) in base 10 14 | Example 2: 15 | 16 | Input: head = [0] 17 | Output: 0 18 | Example 3: 19 | 20 | Input: head = [1] 21 | Output: 1 22 | Example 4: 23 | 24 | Input: head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0] 25 | Output: 18880 26 | Example 5: 27 | 28 | Input: head = [0,0] 29 | Output: 0 30 | ''' 31 | 32 | # Definition for singly-linked list. 33 | # class ListNode(object): 34 | # def __init__(self, x): 35 | # self.val = x 36 | # self.next = None 37 | 38 | class Solution(object): 39 | def getDecimalValue(self, head): 40 | """ 41 | :type head: ListNode 42 | :rtype: int 43 | """ 44 | result = '' 45 | if not head: 46 | return 0 47 | while head: 48 | result+= str(head.val) 49 | head = head.next 50 | return int(result, 2) 51 | -------------------------------------------------------------------------------- /200-300q/230.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. 3 | 4 | Note: 5 | You may assume k is always valid, 1 ≤ k ≤ BST's total elements. 6 | 7 | Example 1: 8 | 9 | Input: root = [3,1,4,null,2], k = 1 10 | Output: 1 11 | ''' 12 | 13 | # Definition for a binary tree node. 14 | # class TreeNode(object): 15 | # def __init__(self, x): 16 | # self.val = x 17 | # self.left = None 18 | # self.right = None 19 | 20 | class Solution(object): 21 | def kthSmallest(self, root, k): 22 | """ 23 | :type root: TreeNode 24 | :type k: int 25 | :rtype: int 26 | """ 27 | 28 | if not root: 29 | return 0 30 | 31 | stack = [root] 32 | count, curr = 0, root 33 | 34 | 35 | while stack: 36 | if curr.left: 37 | stack.append(curr.left) 38 | curr = curr.left 39 | else: 40 | val = stack.pop() 41 | count += 1 42 | if count == k: 43 | return val.val 44 | 45 | if val.right: 46 | stack.append(val.right) 47 | curr = val.right 48 | return float('-inf') -------------------------------------------------------------------------------- /1000-1100q/1027.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array A of integers, return the length of the longest arithmetic subsequence in A. 3 | 4 | Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1). 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: [3,6,9,12] 11 | Output: 4 12 | Explanation: 13 | The whole array is an arithmetic sequence with steps of length = 3. 14 | Example 2: 15 | 16 | Input: [9,4,7,2,10] 17 | Output: 3 18 | Explanation: 19 | The longest arithmetic subsequence is [4,7,10]. 20 | ''' 21 | 22 | class Solution(object): 23 | def longestArithSeqLength(self, A): 24 | """ 25 | :type A: List[int] 26 | :rtype: int 27 | """ 28 | from collections import defaultdict 29 | 30 | dp = defaultdict(int) 31 | # print dp 32 | for index_i in range(len(A)): 33 | for index_j in range(index_i): 34 | diff = A[index_i] - A[index_j] 35 | dp[(index_i, diff)] = max(dp[(index_i, diff)], dp[(index_j, diff)]+1) 36 | # print dp 37 | return max(dp.itervalues())+1 38 | -------------------------------------------------------------------------------- /100-200q/100.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two binary trees, write a function to check if they are the same or not. 3 | 4 | Two binary trees are considered the same if they are structurally identical and the nodes have the same value. 5 | 6 | Example 1: 7 | 8 | Input: 1 1 9 | / \ / \ 10 | 2 3 2 3 11 | 12 | [1,2,3], [1,2,3] 13 | 14 | Output: true 15 | ''' 16 | 17 | # Definition for a binary tree node. 18 | # class TreeNode(object): 19 | # def __init__(self, x): 20 | # self.val = x 21 | # self.left = None 22 | # self.right = None 23 | 24 | class Solution(object): 25 | def isSameTree(self, p, q): 26 | """ 27 | :type p: TreeNode 28 | :type q: TreeNode 29 | :rtype: bool 30 | """ 31 | if not p and not q: 32 | return True 33 | 34 | stack = [(p, q)] 35 | 36 | while stack: 37 | node1, node2 = stack.pop() 38 | if node1 and node2 and node1.val == node2.val: 39 | stack.append((node1.left, node2.left)) 40 | stack.append((node1.right, node2.right)) 41 | else: 42 | if not node1 == node2: 43 | return False 44 | 45 | return True -------------------------------------------------------------------------------- /200-300q/289.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def gameOfLife(self, board): 3 | """ 4 | :type board: List[List[int]] 5 | :rtype: void Do not return anything, modify board in-place instead. 6 | """ 7 | index = [] 8 | 9 | def around(i, j, board): 10 | count = 0 11 | for k in range(i-1, i+2): 12 | for l in range(j-1, j+2): 13 | if 0<=k < len(board) and 0 <= l < len(board[0]): 14 | if board[k][l] == 1: 15 | count += 1 16 | 17 | return count-1 if board[i][j] == 1 else count 18 | 19 | for i in range(len(board)): 20 | for j in range(len(board[0])): 21 | count = around(i, j, board) 22 | if board[i][j] == 1: 23 | if count > 3 or count < 2: 24 | index.append([i, j, 0]) 25 | else: 26 | if count == 3: 27 | index.append([i, j, 1]) 28 | 29 | while index: 30 | i, j, value = index.pop() 31 | board[i][j] =value 32 | 33 | -------------------------------------------------------------------------------- /1-100q/34.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. 3 | 4 | Your algorithm's runtime complexity must be in the order of O(log n). 5 | 6 | If the target is not found in the array, return [-1, -1]. 7 | 8 | Example 1: 9 | 10 | Input: nums = [5,7,7,8,8,10], target = 8 11 | Output: [3,4] 12 | ''' 13 | 14 | class Solution(object): 15 | def searchRange(self, nums, target): 16 | """ 17 | :type nums: List[int] 18 | :type target: int 19 | :rtype: List[int] 20 | """ 21 | left, right = 0, len(nums)-1 22 | 23 | while left <= right: 24 | mid = (left + right) / 2 25 | if target > nums[mid]: 26 | left = mid + 1 27 | else: 28 | right = mid 29 | 30 | if left == len(nums) or nums[left] != target: 31 | return [-1, -1] 32 | 33 | result = [left] 34 | left, right = 0, len(nums) -1 35 | while left <= right: 36 | mid = (left + right) / 2 37 | if nums[mid] > target: 38 | right = mid 39 | else: 40 | left = mid + 1 41 | 42 | result.append(left + 1) 43 | return result -------------------------------------------------------------------------------- /1200-1300q/1282.py: -------------------------------------------------------------------------------- 1 | ''' 2 | There are n people whose IDs go from 0 to n - 1 and each person belongs exactly to one group. Given the array groupSizes of length n telling the group size each person belongs to, return the groups there are and the people's IDs each group includes. 3 | 4 | You can return any solution in any order and the same applies for IDs. Also, it is guaranteed that there exists at least one solution. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: groupSizes = [3,3,3,3,3,1,3] 11 | Output: [[5],[0,1,2],[3,4,6]] 12 | Explanation: 13 | Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]]. 14 | Example 2: 15 | 16 | Input: groupSizes = [2,1,3,3,3,2] 17 | Output: [[1],[0,5],[2,3,4]] 18 | ''' 19 | class Solution(object): 20 | def groupThePeople(self, groupSizes): 21 | """ 22 | :type groupSizes: List[int] 23 | :rtype: List[List[int]] 24 | """ 25 | count = collections.defaultdict(list) 26 | for i, size in enumerate(groupSizes): 27 | count[size].append(i) 28 | result = [] 29 | for s, value in count.items(): 30 | for index in range(0, len(value), s): 31 | result.append(value[index:index + s]) 32 | return result 33 | -------------------------------------------------------------------------------- /1100-1200q/1185.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a date, return the corresponding day of the week for that date. 3 | 4 | The input is given as three integers representing the day, month and year respectively. 5 | 6 | Return the answer as one of the following values {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: day = 31, month = 8, year = 2019 13 | Output: "Saturday" 14 | Example 2: 15 | 16 | Input: day = 18, month = 7, year = 1999 17 | Output: "Sunday" 18 | Example 3: 19 | 20 | Input: day = 15, month = 8, year = 1993 21 | Output: "Sunday" 22 | 23 | 24 | Constraints: 25 | 26 | The given dates are valid dates between the years 1971 and 2100. 27 | ''' 28 | class Solution(object): 29 | def dayOfTheWeek(self, day, month, year): 30 | """ 31 | :type day: int 32 | :type month: int 33 | :type year: int 34 | :rtype: str 35 | """ 36 | day_of_week_map = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] 37 | t = [ 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 ] 38 | year -= month < 3 39 | return day_of_week_map[((year + int(year / 4) - int(year / 100) + int(year / 400) + t[month - 1] + day) % 7)] 40 | -------------------------------------------------------------------------------- /1-100q/71.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an absolute path for a file (Unix-style), simplify it. 3 | 4 | For example, 5 | path = "/home/", => "/home" 6 | path = "/a/./b/../../c/", => "/c" 7 | ''' 8 | 9 | class Solution(object): 10 | def simplifyPath(self, path): 11 | """ 12 | :type path: str 13 | :rtype: str 14 | """ 15 | 16 | result = "/" 17 | stack = [] 18 | 19 | index = 0 20 | while index < len(path): 21 | if path[index] == '/': 22 | index += 1 23 | continue 24 | 25 | 26 | curr_str = "" 27 | while index < len(path) and path[index] != '/': 28 | curr_str += path[index] 29 | index += 1 30 | 31 | if curr_str == '.' or curr_str == "": 32 | index += 1 33 | continue 34 | elif curr_str == "..": 35 | if stack: 36 | stack.pop() 37 | index += 1 38 | else: 39 | stack.append(curr_str) 40 | index += 1 41 | 42 | for index in range(len(stack)): 43 | if index != len(stack) -1: 44 | result += stack[index] + '/' 45 | else: 46 | result += stack[index] 47 | 48 | return result 49 | 50 | # Time: O(N) 51 | # Space: O(N) -------------------------------------------------------------------------------- /1-100q/81.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 3 | 4 | (i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]). 5 | 6 | You are given a target value to search. If found in the array return true, otherwise return false. 7 | 8 | Example 1: 9 | 10 | Input: nums = [2,5,6,0,0,1,2], target = 0 11 | Output: true 12 | Example 2: 13 | 14 | Input: nums = [2,5,6,0,0,1,2], target = 3 15 | Output: false 16 | ''' 17 | 18 | class Solution(object): 19 | def search(self, nums, target): 20 | """ 21 | :type nums: List[int] 22 | :type target: int 23 | :rtype: bool 24 | """ 25 | left, right = 0, len(nums) -1 26 | while left <= right: 27 | mid = (left + right) / 2 28 | if nums[mid] == target: 29 | return True 30 | if nums[left] < nums[mid]: 31 | if nums[left] <= target < nums[mid]: 32 | right = mid - 1 33 | else: 34 | left = mid + 1 35 | elif nums[mid] < nums[left]: 36 | if nums[mid] < target <= nums[right]: 37 | left = mid + 1 38 | else: 39 | right = mid -1 40 | else: 41 | left += 1 42 | 43 | return False -------------------------------------------------------------------------------- /1-100q/99.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Two elements of a binary search tree (BST) are swapped by mistake. 3 | 4 | Recover the tree without changing its structure. 5 | 6 | Example 1: 7 | 8 | Input: [1,3,null,null,2] 9 | 10 | 1 11 | / 12 | 3 13 | \ 14 | 2 15 | 16 | Output: [3,1,null,null,2] 17 | 18 | 3 19 | / 20 | 1 21 | \ 22 | 2 23 | ''' 24 | # Definition for a binary tree node. 25 | # class TreeNode(object): 26 | # def __init__(self, x): 27 | # self.val = x 28 | # self.left = None 29 | # self.right = None 30 | 31 | class Solution(object): 32 | def recoverTree(self, root): 33 | """ 34 | :type root: TreeNode 35 | :rtype: void Do not return anything, modify root in-place instead. 36 | """ 37 | 38 | first, second, prev = None, None, None 39 | def inorder(root): 40 | if root: 41 | inorder(root.left) 42 | if prev is not None and root.val < prev.val: 43 | if first is None: 44 | first = root 45 | else: 46 | second = root 47 | prev = root 48 | inorder(root.right) 49 | 50 | 51 | inorder(root) 52 | if first and second: 53 | first.val, second.val = second.val, first.val -------------------------------------------------------------------------------- /100-200q/163.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a sorted integer array where the range of elements are in the inclusive range [lower, upper], return its missing ranges. 3 | 4 | For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"]. 5 | ''' 6 | 7 | class Solution(object): 8 | def missingRange(self, A, lower, upper): 9 | if not A: 10 | return [] 11 | 12 | result = [] 13 | if A[0] != lower: 14 | end = A[0] - 1 15 | if end == lower: 16 | m_r = str(lower) 17 | else: 18 | m_r = str(lower) + "->" + str(end) 19 | result.append(m_r) 20 | 21 | for index in range(1, len(A)): 22 | if A[index] != A[index-1] + 1: 23 | start = A[index-1] + 1 24 | end = A[index] - 1 25 | if start == end: 26 | m_r = str(start) 27 | else: 28 | m_r = str(start) + "->" + str(end) 29 | result.append(m_r) 30 | 31 | if A[len(A) - 1] != upper: 32 | start = A[len(A)-1] + 1 33 | if start == upper: 34 | m_r = str(start) 35 | else: 36 | m_r = str(start) + "->" + str(upper) 37 | result.append(m_r) 38 | return result 39 | 40 | solution = Solution() 41 | print solution.missingRange([0, 1, 3, 50, 75], 0, 99) 42 | print solution.missingRange([4, 10, 50, 98], 0, 99) 43 | print solution.missingRange([0], 0, 1) -------------------------------------------------------------------------------- /200-300q/257.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree, return all root-to-leaf paths. 3 | 4 | Note: A leaf is a node with no children. 5 | 6 | Example: 7 | 8 | Input: 9 | 10 | 1 11 | / \ 12 | 2 3 13 | \ 14 | 5 15 | 16 | Output: ["1->2->5", "1->3"] 17 | 18 | Explanation: All root-to-leaf paths are: 1->2->5, 1->3 19 | ''' 20 | 21 | # Definition for a binary tree node. 22 | # class TreeNode(object): 23 | # def __init__(self, x): 24 | # self.val = x 25 | # self.left = None 26 | # self.right = None 27 | 28 | class Solution(object): 29 | def binaryTreePaths(self, root): 30 | """ 31 | :type root: TreeNode 32 | :rtype: List[str] 33 | """ 34 | if not root: 35 | return [] 36 | 37 | paths = [] 38 | def dfs(root, curr): 39 | if root.left is None and root.right is None: 40 | paths.append(curr + str(root.val)) 41 | return 42 | 43 | if root.left: 44 | dfs(root.left, curr + str(root.val) + '->') 45 | if root.right: 46 | dfs(root.right, curr + str(root.val) + '->') 47 | 48 | curr = "" 49 | dfs(root, curr) 50 | return paths -------------------------------------------------------------------------------- /1-100q/97.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. 3 | 4 | Example 1: 5 | 6 | Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" 7 | Output: true 8 | Example 2: 9 | 10 | Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc" 11 | Output: false 12 | ''' 13 | 14 | class Solution(object): 15 | def isInterleave(self, s1, s2, s3): 16 | """ 17 | :type s1: str 18 | :type s2: str 19 | :type s3: str 20 | :rtype: bool 21 | """ 22 | 23 | if len(s3) != len(s1) + len(s2): 24 | return False 25 | 26 | dp = [[False for _ in range(len(s2)+1)] for _ in range(len(s1)+1)] 27 | for row in range(len(s1)+1): 28 | for col in range(len(s2)+1): 29 | if row == 0 and col == 0: 30 | dp[row][col] = True 31 | elif row == 0: 32 | dp[row][col] =dp[row][col-1] and s2[col-1] == s3[row+col-1] 33 | elif col == 0: 34 | dp[row][col] = dp[row-1][col] and s1[row-1] == s3[row+col-1] 35 | else: 36 | dp[row][col] = (dp[row][col-1] and s2[col-1] == s3[row+col-1]) or (dp[row-1][col] and s1[row-1] == s3[row+col-1]) 37 | 38 | return dp[len(s1)][len(s2)] 39 | 40 | # Time: O(m*n) 41 | # Space: O(m*n) -------------------------------------------------------------------------------- /100-200q/120.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. 3 | 4 | For example, given the following triangle 5 | 6 | [ 7 | [2], 8 | [3,4], 9 | [6,5,7], 10 | [4,1,8,3] 11 | ] 12 | The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). 13 | ''' 14 | 15 | class Solution(object): 16 | def minimumTotal(self, triangle): 17 | """ 18 | :type triangle: List[List[int]] 19 | :rtype: int 20 | """ 21 | length = len(triangle) 22 | columns = len(triangle[length-1]) 23 | 24 | matrix = [[ 0 for col in range(columns)] for row in range(length)] 25 | row_index = 0 26 | 27 | for row in range(length): 28 | elements = triangle[row] 29 | col_index = 0 30 | 31 | for val in elements: 32 | matrix[row_index][col_index] = val 33 | col_index += 1 34 | row_index += 1 35 | 36 | for row in range(length-2, -1, -1): 37 | for col in range(row+1): 38 | matrix[row][col] += min(matrix[row+1][col+1], matrix[row+1][col]) 39 | return matrix[0][0] -------------------------------------------------------------------------------- /1-100q/16.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. 3 | 4 | Example: 5 | 6 | Given array nums = [-1, 2, 1, -4], and target = 1. 7 | 8 | The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 9 | ''' 10 | 11 | class Solution(object): 12 | def threeSumClosest(self, nums, target): 13 | """ 14 | :type nums: List[int] 15 | :type target: int 16 | :rtype: int 17 | """ 18 | 19 | nums.sort() 20 | result, min_diff = 0, float('inf') 21 | 22 | for index in range(len(nums)-1): 23 | left = index + 1 24 | right = len(nums) - 1 25 | 26 | while left < right: 27 | currSum = nums[index] + nums[left] + nums[right] 28 | diff = abs(target - currSum) 29 | 30 | if diff == 0: 31 | return target 32 | if diff < min_diff: 33 | min_diff = diff 34 | result = currSum 35 | 36 | if currSum < target: 37 | left += 1 38 | else: 39 | right -= 1 40 | return result 41 | 42 | 43 | # Space: O(1) 44 | # Time: O(N^2) -------------------------------------------------------------------------------- /1000-1100q/1043.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer array A, you partition the array into (contiguous) subarrays of length at most K. After partitioning, each subarray has their values changed to become the maximum value of that subarray. 3 | 4 | Return the largest sum of the given array after partitioning. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: A = [1,15,7,9,2,5,10], K = 3 11 | Output: 84 12 | Explanation: A becomes [15,15,15,9,10,10,10] 13 | 14 | 15 | Note: 16 | 17 | 1 <= K <= A.length <= 500 18 | 0 <= A[i] <= 10^6 19 | ''' 20 | 21 | class Solution(object): 22 | def maxSumAfterPartitioning(self, A, K): 23 | """ 24 | :type A: List[int] 25 | :type K: int 26 | :rtype: int 27 | """ 28 | if not A: 29 | return 0 30 | 31 | N = len(A) 32 | dp = [0]*(N+1) 33 | for index_i in range(N): 34 | maxi = 0 35 | for index_j in range(index_i, index_i-K, -1): 36 | if index_j >= 0 and index_j < len(A): 37 | maxi = max(maxi, A[index_j]) 38 | 39 | dp[index_i+1] = max(dp[index_i+1], maxi*(index_i-index_j+1)+dp[index_j]) 40 | # print index_i, maxi 41 | # print dp 42 | 43 | return dp[-1] 44 | -------------------------------------------------------------------------------- /1000-1100q/1081.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Return the lexicographically smallest subsequence of text that contains all the distinct characters of text exactly once. 3 | 4 | 5 | Example 1: 6 | 7 | Input: "cdadabcc" 8 | Output: "adbc" 9 | Example 2: 10 | 11 | Input: "abcd" 12 | Output: "abcd" 13 | Example 3: 14 | 15 | Input: "ecbacba" 16 | Output: "eacb" 17 | Example 4: 18 | 19 | Input: "leetcode" 20 | Output: "letcod" 21 | 22 | 23 | Note: 24 | 25 | 1 <= text.length <= 1000 26 | text consists of lowercase English letters. 27 | ''' 28 | class Solution(object): 29 | def smallestSubsequence(self, text): 30 | """ 31 | :type text: str 32 | :rtype: str 33 | """ 34 | if not text: 35 | return '' 36 | import collections 37 | freq_map = collections.Counter(text) 38 | used = [False]*26 39 | result = '' 40 | 41 | for char in text: 42 | freq_map[char] -= 1 43 | if used[ord(char)-97]: 44 | continue 45 | while (result and result[-1] > char and freq_map[result[-1]] > 0): 46 | used[ord(result[-1])-97] = False 47 | result = result[:-1] 48 | 49 | used[ord(char)-97] = True 50 | result += char 51 | return result 52 | -------------------------------------------------------------------------------- /1-100q/8.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def myAtoi(self, str): 3 | """ 4 | :type str: str 5 | :rtype: int 6 | """ 7 | str = str.strip() 8 | number = "" 9 | 10 | 11 | for x in str: 12 | if x.isalpha() and number == "": 13 | return 0 14 | elif x.isalpha(): 15 | break 16 | elif x == ".": 17 | break 18 | elif x == " ": 19 | break 20 | elif (x == "+" or x == "-") and number == "": 21 | number = number + x 22 | elif (x == "+" or x == "-") and number != "": 23 | break 24 | elif (x == "+" or x == "-") and (number[-1] == "+" or number[-1] == "-"): 25 | return 0 26 | elif (x == "+" or x == "-") and ("+" in number or "-" in number): 27 | break 28 | elif x.isdigit(): 29 | number = number + x 30 | if number == "" or number == "+" or number == "-": 31 | return 0 32 | else: 33 | if int(number) > ((2**31)-1): 34 | return (2**31)-1 35 | elif int(number) < -(2**31): 36 | return -(2**31) 37 | else: 38 | return int(number) -------------------------------------------------------------------------------- /1-100q/98.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree, determine if it is a valid binary search tree (BST). 3 | 4 | Assume a BST is defined as follows: 5 | 6 | The left subtree of a node contains only nodes with keys less than the node's key. 7 | The right subtree of a node contains only nodes with keys greater than the node's key. 8 | Both the left and right subtrees must also be binary search trees. 9 | ''' 10 | 11 | # Definition for a binary tree node. 12 | # class TreeNode(object): 13 | # def __init__(self, x): 14 | # self.val = x 15 | # self.left = None 16 | # self.right = None 17 | 18 | class Solution(object): 19 | def isValidBST(self, root): 20 | """ 21 | :type root: TreeNode 22 | :rtype: bool 23 | """ 24 | if not root: 25 | return True 26 | 27 | stack, result = [], [] 28 | while stack or root: 29 | if root: 30 | stack.append(root) 31 | root = root.left 32 | else: 33 | root = stack.pop() 34 | result.append(root.val) 35 | root = root.right 36 | 37 | previous = result[0] 38 | for index in range(1, len(result)): 39 | if previous >= result[index]: 40 | return False 41 | previous = result[index] 42 | return True -------------------------------------------------------------------------------- /900-1000q/926.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A string of '0's and '1's is monotone increasing if it consists of some number of '0's (possibly 0), followed by some number of '1's (also possibly 0.) 3 | 4 | We are given a string S of '0's and '1's, and we may flip any '0' to a '1' or a '1' to a '0'. 5 | 6 | Return the minimum number of flips to make S monotone increasing. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: "00110" 13 | Output: 1 14 | Explanation: We flip the last digit to get 00111. 15 | Example 2: 16 | 17 | Input: "010110" 18 | Output: 2 19 | Explanation: We flip to get 011111, or alternatively 000111. 20 | Example 3: 21 | 22 | Input: "00011000" 23 | Output: 2 24 | Explanation: We flip to get 00000000. 25 | 26 | 27 | Note: 28 | 29 | 1 <= S.length <= 20000 30 | S only consists of '0' and '1' characters. 31 | ''' 32 | 33 | class Solution(object): 34 | def minFlipsMonoIncr(self, S): 35 | """ 36 | :type S: str 37 | :rtype: int 38 | """ 39 | ones = [0] 40 | for char in S: 41 | ones.append(ones[-1] + int(char)) 42 | # print ones 43 | result = float('inf') 44 | for index in range(len(ones)): 45 | zeroes = len(S) - index - (ones[-1]-ones[index]) 46 | result = min(zeroes+ones[index], result) 47 | return result 48 | -------------------------------------------------------------------------------- /900-1000q/983.py: -------------------------------------------------------------------------------- 1 | ''' 2 | In a country popular for train travel, you have planned some train travelling one year in advance. The days of the year that you will travel is given as an array days. Each day is an integer from 1 to 365. 3 | 4 | Train tickets are sold in 3 different ways: 5 | 6 | a 1-day pass is sold for costs[0] dollars; 7 | a 7-day pass is sold for costs[1] dollars; 8 | a 30-day pass is sold for costs[2] dollars. 9 | The passes allow that many days of consecutive travel. For example, if we get a 7-day pass on day 2, then we can travel for 7 days: day 2, 3, 4, 5, 6, 7, and 8. 10 | 11 | Return the minimum number of dollars you need to travel every day in the given list of days. 12 | 13 | 14 | 15 | Example 1: 16 | 17 | Input: days = [1,4,6,7,8,20], costs = [2,7,15] 18 | Output: 11 19 | ''' 20 | 21 | class Solution: 22 | def mincostTickets(self, days: 'List[int]', costs: 'List[int]') -> 'int': 23 | def get_days_ago(day, ago): 24 | for i in range(len(days)): 25 | if days[i] > days[day-1] - ago: 26 | return i 27 | out = [0] * (len(days) + 1) 28 | for i in range(1, len(days) + 1): 29 | out[i] = min(out[i-1] + costs[0], out[get_days_ago(i,7)] + costs[1], out[get_days_ago(i,30)] + costs[2]) 30 | return out[-1] 31 | -------------------------------------------------------------------------------- /600-700q/673.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an unsorted array of integers, find the number of longest increasing subsequence. 3 | 4 | Example 1: 5 | Input: [1,3,5,4,7] 6 | Output: 2 7 | Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7]. 8 | 9 | Example 2: 10 | Input: [2,2,2,2,2] 11 | Output: 5 12 | Explanation: The length of longest continuous increasing subsequence is 1, and there are 5 subsequences' length is 1, so output 5. 13 | Note: Length of the given array will be not exceed 2000 and the answer is guaranteed to be fit in 32-bit signed int. 14 | ''' 15 | 16 | class Solution(object): 17 | def findNumberOfLIS(self, nums): 18 | length = [1]*len(nums) 19 | count = [1]*len(nums) 20 | result = 0 21 | for end, num in enumerate(nums): 22 | for start in range(end): 23 | if num > nums[start]: 24 | if length[start] >= length[end]: 25 | length[end] = 1+length[start] 26 | count[end] = count[start] 27 | elif length[start] + 1 == length[end]: 28 | count[end] += count[start] 29 | for index, max_subs in enumerate(count): 30 | if length[index] == max(length): 31 | result += max_subs 32 | return result 33 | -------------------------------------------------------------------------------- /1-100q/25.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. 3 | 4 | k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. 5 | 6 | Example: 7 | 8 | Given this linked list: 1->2->3->4->5 9 | 10 | For k = 2, you should return: 2->1->4->3->5 11 | 12 | For k = 3, you should return: 3->2->1->4->5 13 | ''' 14 | 15 | # Definition for singly-linked list. 16 | # class ListNode(object): 17 | # def __init__(self, x): 18 | # self.val = x 19 | # self.next = None 20 | 21 | class Solution(object): 22 | def reverseKGroup(self, head, k): 23 | if head: 24 | slow = head # the mover 25 | while slow: 26 | group = [] 27 | while slow and len(group) < k: 28 | group.append(slow) 29 | slow = slow.next 30 | if not slow and len(group) < k: 31 | return head 32 | for i in range(k/2): 33 | print i,k-i-1 34 | group[i].val,group[k-i-1].val = group[k-i-1].val,group[i].val 35 | return head 36 | 37 | # Space: O(k) 38 | # Time: O(N) -------------------------------------------------------------------------------- /100-200q/129.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. 3 | 4 | An example is the root-to-leaf path 1->2->3 which represents the number 123. 5 | 6 | Find the total sum of all root-to-leaf numbers. 7 | 8 | Note: A leaf is a node with no children. 9 | 10 | Example: 11 | 12 | Input: [1,2,3] 13 | 1 14 | / \ 15 | 2 3 16 | Output: 25 17 | Explanation: 18 | The root-to-leaf path 1->2 represents the number 12. 19 | The root-to-leaf path 1->3 represents the number 13. 20 | Therefore, sum = 12 + 13 = 25. 21 | ''' 22 | 23 | # Definition for a binary tree node. 24 | # class TreeNode(object): 25 | # def __init__(self, x): 26 | # self.val = x 27 | # self.left = None 28 | # self.right = None 29 | 30 | class Solution(object): 31 | def sumNumbers(self, root): 32 | """ 33 | :type root: TreeNode 34 | :rtype: int 35 | """ 36 | if not root: 37 | return 0 38 | 39 | def dfs(root, num, total): 40 | if not root: 41 | return total 42 | num = num*10 + root.val 43 | if not root.left and not root.right: 44 | total += num 45 | return total 46 | 47 | return dfs(root.left, num) + dfs(root.right, num) 48 | 49 | return dfs(root, 0, 0) -------------------------------------------------------------------------------- /1000-1100q/1025.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Alice and Bob take turns playing a game, with Alice starting first. 3 | 4 | Initially, there is a number N on the chalkboard. On each player's turn, that player makes a move consisting of: 5 | 6 | Choosing any x with 0 < x < N and N % x == 0. 7 | Replacing the number N on the chalkboard with N - x. 8 | Also, if a player cannot make a move, they lose the game. 9 | 10 | Return True if and only if Alice wins the game, assuming both players play optimally. 11 | 12 | 13 | 14 | Example 1: 15 | 16 | Input: 2 17 | Output: true 18 | Explanation: Alice chooses 1, and Bob has no more moves. 19 | Example 2: 20 | 21 | Input: 3 22 | Output: false 23 | Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves. 24 | 25 | 26 | Note: 27 | 28 | 1 <= N <= 1000 29 | ''' 30 | 31 | class Solution(object): 32 | def divisorGame(self, N): 33 | """ 34 | :type N: int 35 | :rtype: bool 36 | """ 37 | if N == 0: 38 | return False 39 | 40 | move = 0 41 | while N > 1: 42 | for num in range(1, N): 43 | if N%num == 0: 44 | N -= num 45 | move += 1 46 | break 47 | # print move 48 | if move%2: 49 | return True 50 | return False 51 | -------------------------------------------------------------------------------- /1-100q/38.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The count-and-say sequence is the sequence of integers with the first five terms as following: 3 | 4 | 1. 1 5 | 2. 11 6 | 3. 21 7 | 4. 1211 8 | 5. 111221 9 | 10 | 1 is read off as "one 1" or 11. 11 | 11 is read off as "two 1s" or 21. 12 | 21 is read off as "one 2, then one 1" or 1211. 13 | 14 | Given an integer n, generate the nth term of the count-and-say sequence. 15 | ''' 16 | 17 | class Solution(object): 18 | def countAndSay(self, n): 19 | """ 20 | :type n: int 21 | :rtype: str 22 | """ 23 | 24 | if n == 1: 25 | return "1" 26 | new_num = "" 27 | count_iter = 1 28 | num = "1" 29 | 30 | while count_iter < n: 31 | index_i, index_j = 0, 0 32 | count, new_num = 0, "" 33 | 34 | while index_j < len(num): 35 | if num[index_i] != num[index_j]: 36 | new_num += str(count) + str(num[index_i]) 37 | count = 0 38 | index_i = index_j 39 | else: 40 | count += 1 41 | index_j += 1 42 | 43 | if count > 0: 44 | new_num += str(count) + str(num[index_i]) 45 | num = new_num 46 | count_iter += 1 47 | 48 | return new_num 49 | 50 | # Space: O(1) 51 | # Time: O(N*k) k= length of string -------------------------------------------------------------------------------- /300-400q/350.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two arrays, write a function to compute their intersection. 3 | 4 | Example: 5 | Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]. 6 | 7 | Note: 8 | Each element in the result should appear as many times as it shows in both arrays. 9 | The result can be in any order. 10 | Follow up: 11 | What if the given array is already sorted? How would you optimize your algorithm? 12 | What if nums1's size is small compared to nums2's size? Which algorithm is better? 13 | 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? 14 | ''' 15 | 16 | class Solution(object): 17 | def intersect(self, nums1, nums2): 18 | """ 19 | :type nums1: List[int] 20 | :type nums2: List[int] 21 | :rtype: List[int] 22 | """ 23 | 24 | nums1.sort() 25 | nums2.sort() 26 | 27 | index_i, index_j = 0, 0 28 | result = [] 29 | while index_i < len(nums1) and index_j < len(nums2): 30 | if nums1[index_i] == nums2[index_j]: 31 | result.append(nums1[index_i]) 32 | index_i += 1 33 | index_j += 1 34 | elif nums1[index_i] > nums2[index_j]: 35 | index_j += 1 36 | else: 37 | index_i += 1 38 | return result -------------------------------------------------------------------------------- /1000-1100q/1053.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array A of positive integers (not necessarily distinct), return the lexicographically largest permutation that is smaller than A, that can be made with one swap (A swap exchanges the positions of two numbers A[i] and A[j]). If it cannot be done, then return the same array. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: [3,2,1] 9 | Output: [3,1,2] 10 | Explanation: Swapping 2 and 1. 11 | Example 2: 12 | 13 | Input: [1,1,5] 14 | Output: [1,1,5] 15 | Explanation: This is already the smallest permutation. 16 | Example 3: 17 | 18 | Input: [1,9,4,6,7] 19 | Output: [1,7,4,6,9] 20 | Explanation: Swapping 9 and 7. 21 | Example 4: 22 | 23 | Input: [3,1,1,3] 24 | Output: [1,3,1,3] 25 | Explanation: Swapping 1 and 3. 26 | 27 | 28 | Note: 29 | 30 | 1 <= A.length <= 10000 31 | 1 <= A[i] <= 10000 32 | ''' 33 | class Solution(object): 34 | def prevPermOpt1(self, A): 35 | """ 36 | :type A: List[int] 37 | :rtype: List[int] 38 | """ 39 | 40 | left, right = len(A)-2, len(A)-1 41 | for left in range(len(A)-2, -1, -1): 42 | if A[left] > A[left+1]: 43 | break 44 | else: 45 | return A 46 | right = A.index(max(ele for ele in A[left+1:] if ele < A[left]), left) 47 | A[left], A[right] = A[right], A[left] 48 | return A 49 | -------------------------------------------------------------------------------- /300-400q/395.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times. 3 | 4 | Example 1: 5 | 6 | Input: 7 | s = "aaabb", k = 3 8 | 9 | Output: 10 | 3 11 | 12 | The longest substring is "aaa", as 'a' is repeated 3 times. 13 | Example 2: 14 | 15 | Input: 16 | s = "ababbc", k = 2 17 | 18 | Output: 19 | 5 20 | 21 | The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times. 22 | ''' 23 | 24 | class Solution(object): 25 | def longestSubstring(self, s, k): 26 | """ 27 | :type s: str 28 | :type k: int 29 | :rtype: int 30 | """ 31 | dict = {} 32 | for c in s: 33 | if c not in dict: 34 | dict[c] = 0 35 | dict[c] += 1 36 | if all(dict[i] >= k for i in dict): 37 | return len(s) 38 | 39 | 40 | longest = 0 41 | start = 0 42 | for i in range(len(s)): 43 | c = s[i] 44 | if dict[c] < k: 45 | longest = max(longest, self.longestSubstring(s[start:i], k)) 46 | start = i + 1 47 | 48 | return max(longest, self.longestSubstring(s[start:], k)) 49 | -------------------------------------------------------------------------------- /1-100q/15.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. 3 | 4 | Note: 5 | 6 | The solution set must not contain duplicate triplets. 7 | 8 | Example: 9 | 10 | Given array nums = [-1, 0, 1, 2, -1, -4], 11 | 12 | A solution set is: 13 | [ 14 | [-1, 0, 1], 15 | [-1, -1, 2] 16 | ] 17 | ''' 18 | class Solution(object): 19 | def threeSum(self, nums): 20 | """ 21 | :type nums: List[int] 22 | :rtype: List[List[int]] 23 | """ 24 | nums.sort() 25 | 26 | if (len(nums) >= 3) and (nums[0] == nums[len(nums) -1]) and (nums[0] == 0): 27 | return [[0, 0, 0]] 28 | 29 | result = [] 30 | for index in range(len(nums) - 1): 31 | left = index+1 32 | right = len(nums) - 1 33 | 34 | while left < right: 35 | currSum = nums[index] + nums[left] + nums[right] 36 | if currSum == 0: 37 | result.append([nums[index], nums[left], nums[right]]) 38 | left += 1 39 | right -= 1 40 | elif currSum < 0: 41 | left += 1 42 | else: 43 | right -= 1 44 | return [list(t) for t in set(tuple(element) for element in result)] 45 | 46 | # Space: O(1) 47 | # Time: O(N^2) -------------------------------------------------------------------------------- /1000-1100q/1089.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right. 3 | 4 | Note that elements beyond the length of the original array are not written. 5 | 6 | Do the above modifications to the input array in place, do not return anything from your function. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: [1,0,2,3,0,4,5,0] 13 | Output: null 14 | Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4] 15 | Example 2: 16 | 17 | Input: [1,2,3] 18 | Output: null 19 | Explanation: After calling your function, the input array is modified to: [1,2,3] 20 | 21 | 22 | Note: 23 | 24 | 1 <= arr.length <= 10000 25 | 0 <= arr[i] <= 9 26 | ''' 27 | 28 | class Solution(object): 29 | def duplicateZeros(self, arr): 30 | """ 31 | :type arr: List[int] 32 | :rtype: None Do not return anything, modify arr in-place instead. 33 | """ 34 | arr_copy = arr[:] 35 | index, n = 0, len(arr_copy) 36 | for elem in arr_copy: 37 | arr[index] = elem 38 | index += 1 39 | if index >= n: 40 | break 41 | if elem == 0: 42 | arr[index] = elem 43 | index += 1 44 | if index >= n: 45 | break 46 | -------------------------------------------------------------------------------- /1000-1100q/1008.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Return the root node of a binary search tree that matches the given preorder traversal. 3 | 4 | (Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.) 5 | ''' 6 | 7 | # Definition for a binary tree node. 8 | # class TreeNode(object): 9 | # def __init__(self, x): 10 | # self.val = x 11 | # self.left = None 12 | # self.right = None 13 | 14 | class Solution(object): 15 | def bstFromPreorder(self, preorder): 16 | """ 17 | :type preorder: List[int] 18 | :rtype: TreeNode 19 | """ 20 | root = TreeNode(preorder[0]) 21 | stack = [root] 22 | for index in range(1, len(preorder)): 23 | new_node = TreeNode(preorder[index]) 24 | if new_node.val < stack[-1].val: 25 | stack[-1].left = new_node 26 | else: 27 | parent = None 28 | while stack and new_node.val > stack[-1].val: 29 | parent = stack.pop() 30 | parent.right = new_node 31 | stack.append(new_node) 32 | return root 33 | -------------------------------------------------------------------------------- /1-100q/67.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two binary strings, return their sum (also a binary string). 3 | 4 | The input strings are both non-empty and contains only characters 1 or 0. 5 | 6 | Example 1: 7 | 8 | Input: a = "11", b = "1" 9 | Output: "100" 10 | 11 | Example 2: 12 | 13 | Input: a = "1010", b = "1011" 14 | Output: "10101" 15 | ''' 16 | 17 | class Solution(object): 18 | def addBinary(self, a, b): 19 | """ 20 | :type a: str 21 | :type b: str 22 | :rtype: str 23 | """ 24 | 25 | result = "" 26 | 27 | carry = 0 28 | index_a, index_b = len(a)-1, len(b)-1 29 | while index_a >= 0 and index_b >= 0: 30 | result = (int(a[index_a]) + int(b[index_b]) + carry)%2 + result 31 | carry = (int(a[index_a]) + int(b[index_b]) + carry)%2 32 | index_a -= 1 33 | index_b -= 1 34 | 35 | if index_a >= 0: 36 | while index_a >= 0: 37 | result = (int(a[index_a]) + carry)%2 + result 38 | carry = (int(a[index_a]) + carry)%2 39 | index_a -= 1 40 | elif index_b >= 0: 41 | while index_b >= 0: 42 | result = (int(b[index_b]) + carry)%2 + result 43 | carry = (int(b[index_b]) + carry)%2 44 | index_b -= 1 45 | else: 46 | if carry == 1: 47 | result = str(carry) + result 48 | return result -------------------------------------------------------------------------------- /100-200q/108.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 3 | 4 | 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. 5 | 6 | Example: 7 | 8 | Given the sorted array: [-10,-3,0,5,9], 9 | 10 | One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 11 | 12 | 0 13 | / \ 14 | -3 9 15 | / / 16 | -10 5 17 | ''' 18 | 19 | # Definition for a binary tree node. 20 | # class TreeNode(object): 21 | # def __init__(self, x): 22 | # self.val = x 23 | # self.left = None 24 | # self.right = None 25 | 26 | class Solution(object): 27 | def sortedArrayToBST(self, nums): 28 | """ 29 | :type nums: List[int] 30 | :rtype: TreeNode 31 | """ 32 | 33 | def constructTree(nums, start, end): 34 | if start > end: 35 | return None 36 | 37 | mid = (start+end)/2 38 | node = TreeNode(nums[mid]) 39 | 40 | if start == end: 41 | return node 42 | 43 | node.left = constructTree(nums, start, mid-1) 44 | node.right = constructTree(nums, mid+1, end) 45 | return node 46 | 47 | return constructTree(nums, 0, len(nums)-1) -------------------------------------------------------------------------------- /100-200q/173.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. 3 | 4 | Calling next() will return the next smallest number in the BST. 5 | 6 | Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. 7 | ''' 8 | 9 | 10 | # Definition for a binary tree node 11 | # class TreeNode(object): 12 | # def __init__(self, x): 13 | # self.val = x 14 | # self.left = None 15 | # self.right = None 16 | 17 | class BSTIterator(object): 18 | def __init__(self, root): 19 | """ 20 | :type root: TreeNode 21 | """ 22 | self.stack = [] 23 | while root: 24 | self.stack.append(root) 25 | root = root.left 26 | 27 | 28 | def hasNext(self): 29 | """ 30 | :rtype: bool 31 | """ 32 | return self.stack 33 | 34 | def next(self): 35 | """ 36 | :rtype: int 37 | """ 38 | node = self.stack.pop() 39 | new_node = node.right 40 | while new_node: 41 | self.stack.append(new_node) 42 | new_node = new_node.left 43 | return node.val 44 | 45 | # Your BSTIterator will be called like this: 46 | # i, v = BSTIterator(root), [] 47 | # while i.hasNext(): v.append(i.next()) -------------------------------------------------------------------------------- /1000-1100q/1009.py: -------------------------------------------------------------------------------- 1 | '''Every non-negative integer N has a binary representation. For example, 5 can be represented as "101" in binary, 11 as "1011" in binary, and so on. Note that except for N = 0, there are no leading zeroes in any binary representation. 2 | 3 | The complement of a binary representation is the number in binary you get when changing every 1 to a 0 and 0 to a 1. For example, the complement of "101" in binary is "010" in binary. 4 | 5 | For a given number N in base-10, return the complement of it's binary representation as a base-10 integer. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: 5 12 | Output: 2 13 | Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10. 14 | Example 2: 15 | 16 | Input: 7 17 | Output: 0 18 | Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10. 19 | Example 3: 20 | 21 | Input: 10 22 | Output: 5 23 | Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10. 24 | 25 | 26 | Note: 27 | 28 | 0 <= N < 10^9 29 | ''' 30 | 31 | class Solution(object): 32 | def bitwiseComplement(self, N): 33 | """ 34 | :type N: int 35 | :rtype: int 36 | """ 37 | if N == 0: 38 | return 1 39 | import math 40 | bits = (int)(math.floor(math.log(N) /math.log(2))) + 1 41 | return ((1 << bits) - 1) ^ N -------------------------------------------------------------------------------- /1200-1300q/1296.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers nums and a positive integer k, find whether it's possible to divide this array into sets of k consecutive numbers 3 | Return True if its possible otherwise return False. 4 | 5 | 6 | 7 | Example 1: 8 | 9 | Input: nums = [1,2,3,3,4,4,5,6], k = 4 10 | Output: true 11 | Explanation: Array can be divided into [1,2,3,4] and [3,4,5,6]. 12 | Example 2: 13 | 14 | Input: nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3 15 | Output: true 16 | Explanation: Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11]. 17 | Example 3: 18 | 19 | Input: nums = [3,3,2,2,1,1], k = 3 20 | Output: true 21 | Example 4: 22 | 23 | Input: nums = [1,2,3,4], k = 3 24 | Output: false 25 | Explanation: Each array should be divided in subarrays of size 3. 26 | ''' 27 | class Solution(object): 28 | def isPossibleDivide(self, nums, k): 29 | """ 30 | :type nums: List[int] 31 | :type k: int 32 | :rtype: bool 33 | """ 34 | from collections import Counter 35 | count_map = Counter(nums) 36 | for num in sorted(count_map.keys()): 37 | if count_map[num] <= 0: 38 | continue 39 | for index in range(1, k): 40 | count_map[num+index] -= count_map[num] 41 | if count_map[num+index] < 0: 42 | return False 43 | return True 44 | -------------------------------------------------------------------------------- /1000-1100q/1005.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array A of integers, we must modify the array in the following way: we choose an i and replace A[i] with -A[i], and we repeat this process K times in total. (We may choose the same index i multiple times.) 3 | 4 | Return the largest possible sum of the array after modifying it in this way. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: A = [4,2,3], K = 1 11 | Output: 5 12 | Explanation: Choose indices (1,) and A becomes [4,-2,3]. 13 | Example 2: 14 | 15 | Input: A = [3,-1,0,2], K = 3 16 | Output: 6 17 | Explanation: Choose indices (1, 2, 2) and A becomes [3,1,0,2]. 18 | Example 3: 19 | 20 | Input: A = [2,-3,-1,5,-4], K = 2 21 | Output: 13 22 | Explanation: Choose indices (1, 4) and A becomes [2,3,-1,5,4]. 23 | 24 | 25 | Note: 26 | 27 | 1 <= A.length <= 10000 28 | 1 <= K <= 10000 29 | -100 <= A[i] <= 100 30 | ''' 31 | 32 | class Solution(object): 33 | def largestSumAfterKNegations(self, A, K): 34 | """ 35 | :type A: List[int] 36 | :type K: int 37 | :rtype: int 38 | """ 39 | A.sort() 40 | index = 0 41 | while K > 0: 42 | if A[index] < 0: 43 | A[index] *= -1 44 | if A[index+1] < A[index] and index < len(A)-1: 45 | index += 1 46 | else: 47 | A[index] *= -1 48 | K -= 1 49 | return sum(A) 50 | -------------------------------------------------------------------------------- /1000-1100q/1029.py: -------------------------------------------------------------------------------- 1 | ''' 2 | There are 2N people a company is planning to interview. The cost of flying the i-th person to city A is costs[i][0], and the cost of flying the i-th person to city B is costs[i][1]. 3 | 4 | Return the minimum cost to fly every person to a city such that exactly N people arrive in each city. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: [[10,20],[30,200],[400,50],[30,20]] 11 | Output: 110 12 | Explanation: 13 | The first person goes to city A for a cost of 10. 14 | The second person goes to city A for a cost of 30. 15 | The third person goes to city B for a cost of 50. 16 | The fourth person goes to city B for a cost of 20. 17 | 18 | The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city. 19 | 20 | 21 | Note: 22 | 23 | 1 <= costs.length <= 100 24 | It is guaranteed that costs.length is even. 25 | 1 <= costs[i][0], costs[i][1] <= 1000 26 | ''' 27 | 28 | class Solution(object): 29 | def twoCitySchedCost(self, costs): 30 | """ 31 | :type costs: List[List[int]] 32 | :rtype: int 33 | """ 34 | result = 0 35 | costs = sorted(costs, key=lambda x : x[0] - x[1]) 36 | for index in range(len(costs)): 37 | if index < len(costs)//2: 38 | result += costs[index][0] 39 | else: 40 | result += costs[index][1] 41 | return result 42 | -------------------------------------------------------------------------------- /100-200q/102.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). 3 | 4 | For example: 5 | Given binary tree [3,9,20,null,null,15,7], 6 | 7 | 3 8 | / \ 9 | 9 20 10 | / \ 11 | 15 7 12 | 13 | return its level order traversal as: 14 | 15 | [ 16 | [3], 17 | [9,20], 18 | [15,7] 19 | ] 20 | ''' 21 | 22 | # Definition for a binary tree node. 23 | # class TreeNode(object): 24 | # def __init__(self, x): 25 | # self.val = x 26 | # self.left = None 27 | # self.right = None 28 | 29 | class Solution(object): 30 | def levelOrder(self, root): 31 | """ 32 | :type root: TreeNode 33 | :rtype: List[List[int]] 34 | """ 35 | 36 | if not root: 37 | return [] 38 | 39 | queue = [(root, 0)] 40 | levelMap = {} 41 | 42 | while queue: 43 | node, level = queue.pop(0) 44 | if node.left: 45 | queue.append((node.left, level+1)) 46 | if node.right: 47 | queue.append((node.right, level+1)) 48 | 49 | if level in levelMap: 50 | levelMap[level].append(node.val) 51 | else: 52 | levelMap[level] = [node.val] 53 | 54 | result = [] 55 | for key, value in levelMap.iteritems(): 56 | result.append(value) 57 | return result -------------------------------------------------------------------------------- /100-200q/170.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Design and implement a TwoSum class. It should support the following operations: add and find. 3 | 4 | add – Add the number to an internal data structure. 5 | find – Find if there exists any pair of numbers which sum is equal to the value. 6 | 7 | For example, 8 | add(1); add(3); add(5); 9 | find(4) -> true 10 | find(7) -> false 11 | ''' 12 | 13 | class TwoSum(object): 14 | 15 | def __init__(self): 16 | """ 17 | initialize your data structure here 18 | """ 19 | self.value_count = {} 20 | 21 | def add(self, number): 22 | """ 23 | Add the number to an internal data structure. 24 | :rtype: nothing 25 | """ 26 | if number in self.value_count: 27 | self.value_count[number] += 1 28 | else: 29 | self.value_count[number] = 1 30 | 31 | def find(self, value): 32 | """ 33 | Find if there exists any pair of numbers which sum is equal to the value. 34 | :type value: int 35 | :rtype: bool 36 | """ 37 | for val in self.value_count: 38 | diff = value - val 39 | if diff in self.value_count and (diff != val or self.value_count[val] > 1): 40 | return True 41 | return False 42 | 43 | # Your TwoSum object will be instantiated and called as such: 44 | # twoSum = TwoSum() 45 | # twoSum.add(number) 46 | # twoSum.find(value) -------------------------------------------------------------------------------- /1000-1100q/1013.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array A of integers, return true if and only if we can partition the array into three non-empty parts with equal sums. 3 | 4 | Formally, we can partition the array if we can find indexes i+1 < j with (A[0] + A[1] + ... + A[i] == A[i+1] + A[i+2] + ... + A[j-1] == A[j] + A[j-1] + ... + A[A.length - 1]) 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: [0,2,1,-6,6,-7,9,1,2,0,1] 11 | Output: true 12 | Explanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1 13 | Example 2: 14 | 15 | Input: [0,2,1,-6,6,7,9,-1,2,0,1] 16 | Output: false 17 | Example 3: 18 | 19 | Input: [3,3,6,5,-2,2,5,1,-9,4] 20 | Output: true 21 | Explanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4 22 | 23 | 24 | Note: 25 | 26 | 3 <= A.length <= 50000 27 | -10000 <= A[i] <= 10000 28 | ''' 29 | 30 | class Solution(object): 31 | def canThreePartsEqualSum(self, A): 32 | """ 33 | :type A: List[int] 34 | :rtype: bool 35 | """ 36 | total_sum = 0 37 | for val in A: 38 | total_sum += val 39 | 40 | if(total_sum%3 != 0): 41 | return False 42 | 43 | curr_sum, groups = 0, 0 44 | for val in A: 45 | curr_sum += val 46 | if curr_sum == total_sum/3: 47 | curr_sum = 0 48 | groups +=1 49 | print groups 50 | return groups == 3 51 | 52 | -------------------------------------------------------------------------------- /1-100q/86.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. 3 | 4 | You should preserve the original relative order of the nodes in each of the two partitions. 5 | 6 | Example: 7 | 8 | Input: head = 1->4->3->2->5->2, x = 3 9 | Output: 1->2->2->4->3->5 10 | ''' 11 | 12 | # Definition for singly-linked list. 13 | # class ListNode(object): 14 | # def __init__(self, x): 15 | # self.val = x 16 | # self.next = None 17 | 18 | class Solution(object): 19 | def partition(self, head, x): 20 | """ 21 | :type head: ListNode 22 | :type x: int 23 | :rtype: ListNode 24 | """ 25 | if not head or not head.next: 26 | return head 27 | 28 | left, right = ListNode(0), ListNode(0) 29 | leftPtr, rightPtr = left, right 30 | 31 | while head: 32 | if head.val < x: 33 | leftPtr.next = ListNode(head.val) 34 | leftPtr = leftPtr.next 35 | else: 36 | rightPtr.next = ListNode(head.val) 37 | rightPtr = rightPtr.next 38 | head = head.next 39 | 40 | if not left.next: 41 | return right.next 42 | elif not right.next: 43 | return left.next 44 | else: 45 | leftPtr.next = right.next 46 | return left.next 47 | # Time: O(N) 48 | # Space: O(N) -------------------------------------------------------------------------------- /200-300q/300.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an unsorted array of integers, find the length of longest increasing subsequence. 3 | 4 | For example, 5 | Given [10, 9, 2, 5, 3, 7, 101, 18], 6 | The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length. 7 | 8 | Your algorithm should run in O(n2) complexity. 9 | 10 | Follow up: Could you improve it to O(n log n) time complexity? 11 | ''' 12 | 13 | class Solution(object): 14 | def lengthOfLIS(self, nums): 15 | """ 16 | :type nums: List[int] 17 | :rtype: int 18 | """ 19 | 20 | if len(nums) <= 1: 21 | return len(nums) 22 | 23 | count = [0 for _ in range(len(nums))] 24 | result = 1 25 | count[0] = nums[0] 26 | 27 | for index in range(1, len(nums)): 28 | if nums[index] < count[0]: 29 | count[0] = nums[index] 30 | elif nums[index] > count[result-1]: 31 | count[result] = nums[index] 32 | result += 1 33 | else: 34 | left, right = -1, result-1 35 | while (right-left > 1): 36 | mid = (left+right)/2 37 | if count[mid] >= nums[index]: 38 | right = mid 39 | else: 40 | left = mid 41 | count[right] = nums[index] 42 | 43 | return result -------------------------------------------------------------------------------- /100-200q/124.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a non-empty binary tree, find the maximum path sum. 3 | 4 | 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 must contain at least one node and does not need to go through the root. 5 | 6 | Example 1: 7 | 8 | Input: [1,2,3] 9 | 10 | 1 11 | / \ 12 | 2 3 13 | 14 | Output: 6 15 | Example 2: 16 | 17 | Input: [-10,9,20,null,null,15,7] 18 | 19 | -10 20 | / \ 21 | 9 20 22 | / \ 23 | 15 7 24 | 25 | Output: 42 26 | ''' 27 | 28 | # Definition for a binary tree node. 29 | # class TreeNode(object): 30 | # def __init__(self, x): 31 | # self.val = x 32 | # self.left = None 33 | # self.right = None 34 | 35 | class Solution(object): 36 | def maxPathSum(self, root): 37 | """ 38 | :type root: TreeNode 39 | :rtype: int 40 | """ 41 | self.result = float('-inf') 42 | self.dfs(root) 43 | return self.result 44 | 45 | def dfs(self, root): 46 | if not root: 47 | return 0 48 | 49 | l = self.dfs(root.left) 50 | r = self.dfs(root.right) 51 | 52 | max_one_end = max(max(l, r)+root.val, root.val) 53 | max_path = max(max_one_end, l+r+root.val) 54 | self.result = max(self.result, max_path) 55 | return max_one_end 56 | 57 | 58 | -------------------------------------------------------------------------------- /100-200q/132.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string s, partition s such that every substring of the partition is a palindrome. 3 | 4 | Return the minimum cuts needed for a palindrome partitioning of s. 5 | 6 | Example: 7 | 8 | Input: "aab" 9 | Output: 1 10 | Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut. 11 | ''' 12 | 13 | class Solution(object): 14 | def minCut(self, s): 15 | """ 16 | :type s: str 17 | :rtype: int 18 | """ 19 | if not s: 20 | return 0 21 | 22 | P = [[False for _ in range(len(s))] for _ in range(len(s))] 23 | cuts = [0 for _ in range(len(s))] 24 | 25 | for index in range(len(s)): 26 | P[index][index] = True 27 | 28 | for length in range(2, len(s)+1): 29 | for i in range(len(s)-length+1): 30 | j = i+length - 1 31 | 32 | if length == 2: 33 | P[i][j] = s[i] == s[j] 34 | else: 35 | P[i][j] = (s[i] == s[j]) and P[i+1][j-1] 36 | 37 | for index in range(len(s)): 38 | if P[0][index]: 39 | cuts[index] = 0 40 | else: 41 | cuts[index] = float('inf') 42 | for j in range(index): 43 | if P[j+1][index] and (cuts[index] > 1 + cuts[j]): 44 | cuts[index] = 1+cuts[j] 45 | 46 | return cuts[len(s)-1] 47 | 48 | # Time: O(N^2) 49 | # Space: O(N^2) -------------------------------------------------------------------------------- /1000-1100q/1047.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them. 3 | 4 | We repeatedly make duplicate removals on S until we no longer can. 5 | 6 | Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: "abbaca" 13 | Output: "ca" 14 | Explanation: 15 | For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca". 16 | 17 | 18 | Note: 19 | 20 | 1 <= S.length <= 20000 21 | S consists only of English lowercase letters. 22 | ''' 23 | 24 | class Solution(object): 25 | def removeDuplicates(self, S): 26 | """ 27 | :type S: str 28 | :rtype: str 29 | """ 30 | stack = [] 31 | if not S: 32 | return "" 33 | for char in S: 34 | if not stack: 35 | stack.append(char) 36 | else: 37 | first = stack[-1] 38 | if first == char: 39 | stack.pop() 40 | else: 41 | stack.append(char) 42 | if not stack: 43 | return "" 44 | return ''.join(stack) 45 | -------------------------------------------------------------------------------- /1100-1200q/1190.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string s that consists of lower case English letters and brackets. 3 | 4 | Reverse the strings in each pair of matching parentheses, starting from the innermost one. 5 | 6 | Your result should not contain any bracket. 7 | 8 | 9 | Example 1: 10 | Input: s = "(abcd)" 11 | Output: "dcba" 12 | 13 | Example 2: 14 | Input: s = "(u(love)i)" 15 | Output: "iloveu" 16 | 17 | Example 3: 18 | Input: s = "(ed(et(oc))el)" 19 | Output: "leetcode" 20 | 21 | Example 4: 22 | Input: s = "a(bcdefghijkl(mno)p)q" 23 | Output: "apmnolkjihgfedcbq" 24 | 25 | 26 | Constraints: 27 | 28 | 0 <= s.length <= 2000 29 | s only contains lower case English characters and parentheses. 30 | It's guaranteed that all parentheses are balanced. 31 | ''' 32 | 33 | class Solution(object): 34 | def reverseParentheses(self, s): 35 | """ 36 | :type s: str 37 | :rtype: str 38 | """ 39 | if not s: 40 | return '' 41 | 42 | stack = [] 43 | for char in s: 44 | if char == ')': 45 | combine_str = '' 46 | while stack and stack[-1] != '(': 47 | elem = stack.pop()[::-1] 48 | combine_str += elem 49 | stack.pop() 50 | stack.append(combine_str) 51 | else: 52 | stack.append(char) 53 | return "".join(stack) 54 | -------------------------------------------------------------------------------- /900-1000q/985.py: -------------------------------------------------------------------------------- 1 | ''' 2 | We have an array A of integers, and an array queries of queries. 3 | 4 | For the i-th query val = queries[i][0], index = queries[i][1], we add val to A[index]. Then, the answer to the i-th query is the sum of the even values of A. 5 | 6 | (Here, the given index = queries[i][1] is a 0-based index, and each query permanently modifies the array A.) 7 | 8 | Return the answer to all queries. Your answer array should have answer[i] as the answer to the i-th query. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: A = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]] 15 | Output: [8,6,2,4] 16 | ''' 17 | 18 | class Solution(object): 19 | def sumEvenAfterQueries(self, A, queries): 20 | """ 21 | :type A: List[int] 22 | :type queries: List[List[int]] 23 | :rtype: List[int] 24 | """ 25 | result = 0 26 | for val in A: 27 | if val%2 == 0: 28 | result += val 29 | 30 | f_result = [] 31 | for val_index in queries: 32 | val, index = val_index[0], val_index[1] 33 | prev_val = A[index] 34 | if prev_val%2 == 0: 35 | result -= prev_val 36 | new_val = prev_val + val 37 | if new_val %2 == 0: 38 | result += new_val 39 | A[index] = new_val 40 | f_result.append(result) 41 | return f_result 42 | -------------------------------------------------------------------------------- /1000-1100q/1054.py: -------------------------------------------------------------------------------- 1 | ''' 2 | In a warehouse, there is a row of barcodes, where the i-th barcode is barcodes[i]. 3 | 4 | Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: [1,1,1,2,2,2] 11 | Output: [2,1,2,1,2,1] 12 | Example 2: 13 | 14 | Input: [1,1,1,1,2,2,3,3] 15 | Output: [1,3,1,3,2,1,2,1] 16 | 17 | 18 | Note: 19 | 20 | 1 <= barcodes.length <= 10000 21 | 1 <= barcodes[i] <= 10000 22 | ''' 23 | 24 | class Solution(object): 25 | def rearrangeBarcodes(self, barcodes): 26 | """ 27 | :type barcodes: List[int] 28 | :rtype: List[int] 29 | """ 30 | import heapq 31 | di = collections.Counter(barcodes) 32 | pq = [(-value, key) for key, value in di.items()] 33 | heapq.heapify(pq) 34 | # print pq 35 | result = [] 36 | while len(pq) >= 2: 37 | freq1, barcode1 = heapq.heappop(pq) 38 | freq2, barcode2 = heapq.heappop(pq) 39 | result.extend([barcode1, barcode2]) 40 | 41 | if freq1 + 1: 42 | heapq.heappush(pq, (freq1 + 1, barcode1)) 43 | if freq2 + 1: 44 | heapq.heappush(pq, (freq2 + 1, barcode2)) 45 | 46 | if pq: 47 | result.append(pq[0][1]) 48 | 49 | return result 50 | -------------------------------------------------------------------------------- /1200-1300q/1266.py: -------------------------------------------------------------------------------- 1 | ''' 2 | On a plane there are n points with integer coordinates points[i] = [xi, yi]. Your task is to find the minimum time in seconds to visit all points. 3 | 4 | You can move according to the next rules: 5 | 6 | In one second always you can either move vertically, horizontally by one unit or diagonally (it means to move one unit vertically and one unit horizontally in one second). 7 | You have to visit the points in the same order as they appear in the array. 8 | 9 | Input: points = [[1,1],[3,4],[-1,0]] 10 | Output: 7 11 | Explanation: One optimal path is [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0] 12 | Time from [1,1] to [3,4] = 3 seconds 13 | Time from [3,4] to [-1,0] = 4 seconds 14 | Total time = 7 seconds 15 | Example 2: 16 | 17 | Input: points = [[3,2],[-2,2]] 18 | Output: 5 19 | 20 | 21 | Constraints: 22 | 23 | points.length == n 24 | 1 <= n <= 100 25 | points[i].length == 2 26 | -1000 <= points[i][0], points[i][1] <= 1000 27 | ''' 28 | 29 | class Solution(object): 30 | def minTimeToVisitAllPoints(self, points): 31 | """ 32 | :type points: List[List[int]] 33 | :rtype: int 34 | """ 35 | if not points: 36 | return 0 37 | result = 0 38 | for index in range(1, len(points)): 39 | result += max(abs(points[index][0]-points[index-1][0]), abs(points[index][1]-points[index-1][1])) 40 | return result 41 | -------------------------------------------------------------------------------- /1-100q/31.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. 3 | 4 | If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). 5 | 6 | The replacement must be in-place and use only constant extra memory. 7 | 8 | Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. 9 | 10 | 1,2,3 → 1,3,2 11 | 3,2,1 → 1,2,3 12 | 1,1,5 → 1,5,1 13 | ''' 14 | 15 | class Solution(object): 16 | def nextPermutation(self, nums): 17 | """ 18 | :type nums: List[int] 19 | :rtype: void Do not return anything, modify nums in-place instead. 20 | """ 21 | 22 | index_i = len(nums) - 2 23 | while index_i >= 0 and nums[index_i] >= nums[index_i+1]: 24 | index_i -= 1 25 | 26 | if index_i >= 0: 27 | index_j = len(nums) - 1 28 | while index_j >= index_i and nums[index_j] <= nums[index_i]: 29 | index_j -= 1 30 | 31 | nums[index_i], nums[index_j] = nums[index_j], nums[index_i] 32 | 33 | start = index_i + 1 34 | end = len(nums) - 1 35 | 36 | while start < end: 37 | nums[start], nums[end] = nums[end], nums[start] 38 | start += 1 39 | end -= 1 40 | 41 | 42 | -------------------------------------------------------------------------------- /1-100q/91.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A message containing letters from A-Z is being encoded to numbers using the following mapping: 3 | 4 | 'A' -> 1 5 | 'B' -> 2 6 | ... 7 | 'Z' -> 26 8 | 9 | Given a non-empty string containing only digits, determine the total number of ways to decode it. 10 | 11 | Example 1: 12 | 13 | Input: "12" 14 | Output: 2 15 | Explanation: It could be decoded as "AB" (1 2) or "L" (12). 16 | 17 | Example 2: 18 | 19 | Input: "226" 20 | Output: 3 21 | Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). 22 | ''' 23 | 24 | class Solution(object): 25 | def numDecodings(self, s): 26 | """ 27 | :type s: str 28 | :rtype: int 29 | """ 30 | if not s or s[0] == '0': 31 | return 0 32 | if len(s) == 1: 33 | return 1 34 | 35 | dp = [0]*len(s) 36 | dp[0] = 1 37 | 38 | if int(s[:2]) > 26: 39 | if s[1] != '0': 40 | dp[1] = 1 41 | else: 42 | dp[0] = 0 43 | else: 44 | if s[1] != '0': 45 | dp[1] = 2 46 | else: 47 | dp[1] = 1 48 | 49 | for index in range(2, len(s)): 50 | if s[index] != '0': 51 | dp[index] += dp[index-1] 52 | 53 | val = int(s[index-1:index+1]) 54 | if val >= 10 and val <= 26: 55 | dp[index] += dp[index-2] 56 | return dp[len(s)-1] 57 | 58 | # Time: O(N) 59 | # Space: O(N) -------------------------------------------------------------------------------- /1000-1100q/1071.py: -------------------------------------------------------------------------------- 1 | ''' 2 | For strings S and T, we say "T divides S" if and only if S = T + ... + T (T concatenated with itself 1 or more times) 3 | 4 | Return the largest string X such that X divides str1 and X divides str2. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: str1 = "ABCABC", str2 = "ABC" 11 | Output: "ABC" 12 | Example 2: 13 | 14 | Input: str1 = "ABABAB", str2 = "ABAB" 15 | Output: "AB" 16 | Example 3: 17 | 18 | Input: str1 = "LEET", str2 = "CODE" 19 | Output: "" 20 | 21 | 22 | Note: 23 | 24 | 1 <= str1.length <= 1000 25 | 1 <= str2.length <= 1000 26 | str1[i] and str2[i] are English uppercase letters. 27 | 28 | ''' 29 | class Solution(object): 30 | def gcdOfStrings(self, str1, str2): 31 | """ 32 | :type str1: str 33 | :type str2: str 34 | :rtype: str 35 | """ 36 | if len(str1) > len(str2): 37 | str1, str2 = str2, str1 38 | 39 | l_str1 = len(str1) 40 | for index in range(1, len(str1)+1): 41 | if l_str1%index != 0: 42 | continue 43 | 44 | size_to_take = int(l_str1/index) 45 | substr1 = str1[:size_to_take] 46 | substr2 = str2 47 | 48 | while substr1 == substr2[:size_to_take]: 49 | substr2 = substr2[size_to_take:] 50 | 51 | if substr2 == "": 52 | return substr1 53 | return "" 54 | -------------------------------------------------------------------------------- /100-200q/113.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. 3 | 4 | Note: A leaf is a node with no children. 5 | 6 | Example: 7 | 8 | Given the below binary tree and sum = 22, 9 | 10 | 5 11 | / \ 12 | 4 8 13 | / / \ 14 | 11 13 4 15 | / \ / \ 16 | 7 2 5 1 17 | Return: 18 | 19 | [ 20 | [5,4,11,2], 21 | [5,8,4,5] 22 | ] 23 | 24 | ''' 25 | 26 | # Definition for a binary tree node. 27 | # class TreeNode(object): 28 | # def __init__(self, x): 29 | # self.val = x 30 | # self.left = None 31 | # self.right = None 32 | 33 | class Solution(object): 34 | def pathSum(self, root, sum): 35 | """ 36 | :type root: TreeNode 37 | :type sum: int 38 | :rtype: List[List[int]] 39 | """ 40 | 41 | result = [] 42 | 43 | def dfs(root, curr_sum, sum, path, result): 44 | if not root: 45 | return 46 | 47 | curr_sum += root.val 48 | if curr_sum == sum and not root.left and not root.right: 49 | result.append(path + [root.val]) 50 | return 51 | 52 | if root.left: 53 | dfs(root.left, curr_sum, sum, path + [root.val], result) 54 | if root.right: 55 | dfs(root.right, curr_sum, sum, path + [root.val], result) 56 | 57 | dfs(root, 0, sum, [], result) 58 | return result -------------------------------------------------------------------------------- /1000-1100q/1002.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer. 3 | 4 | You may return the answer in any order. 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: ["bella","label","roller"] 11 | Output: ["e","l","l"] 12 | Example 2: 13 | 14 | Input: ["cool","lock","cook"] 15 | Output: ["c","o"] 16 | ''' 17 | 18 | class Solution(object): 19 | def commonChars(self, A): 20 | """ 21 | :type A: List[str] 22 | :rtype: List[str] 23 | """ 24 | char_map = {} 25 | for char in A[0]: 26 | if char in char_map: 27 | char_map[char] += 1 28 | else: 29 | char_map[char] = 1 30 | 31 | int_map = {} 32 | for index in range(1, len(A)): 33 | for char in char_map.keys(): 34 | if char in A[index]: 35 | char_count = min(A[index].count(char), char_map[char]) 36 | char_map[char] = char_count 37 | else: 38 | del char_map[char] 39 | 40 | result = [] 41 | for key, value in char_map.items(): 42 | result.extend([key]*value) 43 | 44 | return result 45 | -------------------------------------------------------------------------------- /1-100q/14.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a function to find the longest common prefix string amongst an array of strings. 3 | 4 | If there is no common prefix, return an empty string "". 5 | 6 | Example 1: 7 | 8 | Input: ["flower","flow","flight"] 9 | Output: "fl" 10 | Example 2: 11 | 12 | Input: ["dog","racecar","car"] 13 | Output: "" 14 | Explanation: There is no common prefix among the input strings. 15 | Note: 16 | 17 | All given inputs are in lowercase letters a-z. 18 | ''' 19 | 20 | class Solution(object): 21 | def longestCommonPrefix(self, strs): 22 | """ 23 | :type strs: List[str] 24 | :rtype: str 25 | """ 26 | def prefix(strs, index): 27 | check_prefix = strs[0][:index] 28 | for index in range(1, len(strs)): 29 | if not strs[index].startswith(check_prefix): 30 | return False 31 | return True 32 | 33 | 34 | if not strs: 35 | return "" 36 | 37 | minLength = float('inf') 38 | for string in strs: 39 | minLength = min(minLength, len(string)) 40 | 41 | low, high = 0, minLength 42 | 43 | while low <= high: 44 | mid = (low+high)/2 45 | if (prefix(strs, mid)): 46 | low = mid + 1 47 | else: 48 | high = mid - 1 49 | 50 | return strs[0][:(low+high)/2] 51 | -------------------------------------------------------------------------------- /1-100q/40.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. 3 | 4 | Each number in candidates may only be used once in the combination. 5 | 6 | Note: 7 | 8 | All numbers (including target) will be positive integers. 9 | The solution set must not contain duplicate combinations. 10 | Example 1: 11 | 12 | Input: candidates = [10,1,2,7,6,1,5], target = 8, 13 | A solution set is: 14 | [ 15 | [1, 7], 16 | [1, 2, 5], 17 | [2, 6], 18 | [1, 1, 6] 19 | ] 20 | ''' 21 | 22 | class Solution(object): 23 | def combinationSum2(self, candidates, target): 24 | """ 25 | :type candidates: List[int] 26 | :type target: int 27 | :rtype: List[List[int]] 28 | """ 29 | result = [] 30 | candidates.sort() 31 | 32 | def recursive(candidates, target, currList, index): 33 | if target < 0: 34 | return 35 | if target == 0: 36 | result.append(currList) 37 | return 38 | 39 | previous = -1 40 | for start in range(index, len(candidates)): 41 | if previous != candidates[start]: 42 | recursive(candidates, target - candidates[start], currList + [candidates[start]], start+1) 43 | previous = candidates[start] 44 | 45 | 46 | recursive(candidates, target, [], 0) 47 | return result -------------------------------------------------------------------------------- /600-700q/681.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a time represented in the format "HH:MM", form the next closest time by reusing the current digits. There is no limit on how many times a digit can be reused. 3 | 4 | You may assume the given input string is always valid. For example, "01:34", "12:09" are all valid. "1:34", "12:9" are all invalid. 5 | 6 | Example 1: 7 | 8 | Input: "19:34" 9 | Output: "19:39" 10 | Explanation: The next closest time choosing from digits 1, 9, 3, 4, is 19:39, which occurs 5 minutes later. It is not 19:33, because this occurs 23 hours and 59 minutes later. 11 | Example 2: 12 | 13 | Input: "23:59" 14 | Output: "22:22" 15 | Explanation: The next closest time choosing from digits 2, 3, 5, 9, is 22:22. It may be assumed that the returned time is next day's time since it is smaller than the input time numerically. 16 | ''' 17 | 18 | class Solution(object): 19 | def nextClosestTime(self, time): 20 | current_time = 60*int(time[:2]) + int(time[3:]) 21 | allowed = {int(x) for x in time if x != ':'} 22 | result = 24*60 23 | ans = current_time 24 | for h1, h2, m1, m2 in itertools.product(allowed, repeat=4): 25 | hours, minutes = 10*h1+h2, 10*m1+m2 26 | if hours < 24 and minutes < 60: 27 | elapsed = 60*hours + minutes 28 | diff = (current_time - elapsed)%(24*60) 29 | if 0 < diff < result: 30 | result = diff 31 | ans = elapsed 32 | 33 | return "{:02d}:{:02d}".format(divmod(ans, 60)) 34 | -------------------------------------------------------------------------------- /1-100q/44.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'. 3 | 4 | '?' Matches any single character. 5 | '*' Matches any sequence of characters (including the empty sequence). 6 | The matching should cover the entire input string (not partial). 7 | 8 | Note: 9 | 10 | s could be empty and contains only lowercase letters a-z. 11 | p could be empty and contains only lowercase letters a-z, and characters like ? or *. 12 | ''' 13 | 14 | class Solution(object): 15 | def isMatch(self, s, p): 16 | """ 17 | :type s: str 18 | :type p: str 19 | :rtype: bool 20 | """ 21 | 22 | if len(p) == 0: 23 | return len(s) == 0 24 | 25 | dp = [[False for _ in range(len(p) + 1)] for _ in range(len(s) + 1)] 26 | dp[0][0] = True 27 | 28 | for index in range(1,len(dp[0])): 29 | if p[index-1] == '*': 30 | dp[0][index] = dp[0][index-1] 31 | 32 | for index_i in range(1, len(dp)): 33 | for index_j in range(1, len(dp[0])): 34 | if s[index_i - 1] == p[index_j - 1] or p[index_j - 1] == '?': 35 | dp[index_i][index_j] = dp[index_i-1][index_j-1] 36 | elif p[index_j-1] == '*': 37 | dp[index_i][index_j] = dp[index_i][index_j-1] or dp[index_i-1][index_j] 38 | else: 39 | dp[index_i][index_j] = False 40 | return dp[len(s)][len(p)] -------------------------------------------------------------------------------- /1000-1100q/1079.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You have a set of tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: "AAB" 9 | Output: 8 10 | Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". 11 | Example 2: 12 | 13 | Input: "AAABBC" 14 | Output: 188 15 | ''' 16 | 17 | class Solution(object): 18 | def numTilePossibilities(self, tiles): 19 | """ 20 | :type tiles: str 21 | :rtype: int 22 | """ 23 | 24 | if not tiles: 25 | return 0 26 | 27 | import collections 28 | unique = set(tiles) 29 | freq_map = collections.Counter(tiles) 30 | total_len = 1 31 | while total_len < len(tiles): 32 | new = set() 33 | for char in tiles: 34 | for comb in unique: 35 | new_seq = comb+char 36 | up_freq = collections.Counter(new_seq) 37 | flag =True 38 | for key, val in up_freq.items(): 39 | if val > freq_map[key]: 40 | flag = False 41 | if flag: 42 | new.add(new_seq) 43 | # print new 44 | unique.update(new) 45 | 46 | total_len += 1 47 | return len(unique) 48 | -------------------------------------------------------------------------------- /300-400q/329.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer matrix, find the length of the longest increasing path. 3 | 4 | From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed). 5 | 6 | Example 1: 7 | 8 | nums = [ 9 | [9,9,4], 10 | [6,6,8], 11 | [2,1,1] 12 | ] 13 | Return 4 14 | ''' 15 | 16 | class Solution(object): 17 | def longestIncreasingPath(self, matrix): 18 | """ 19 | :type matrix: List[List[int]] 20 | :rtype: int 21 | """ 22 | result = 0 23 | dp = [[0 for col in range(len(matrix[0]))] for row in range(len(matrix))] 24 | for row in range(len(matrix)): 25 | for col in range(len(matrix[0])): 26 | result = max(result, self.dfs(matrix, dp, row, col)) 27 | 28 | return result 29 | 30 | def dfs(self, matrix, dp, i, j): 31 | if dp[i][j]: 32 | return dp[i][j] 33 | max_depth = 0 34 | direction = [[0, 1], [0, -1], [1, 0], [-1, 0]] 35 | for d in direction: 36 | x, y = i + d[0], j + d[1] 37 | if 0 <= x < len(matrix) and 0 <= y < len(matrix[0]) and matrix[x][y] < matrix[i][j] : 38 | max_depth = max(max_depth, self.dfs(matrix, dp, x, y)) 39 | 40 | dp[i][j] = max_depth + 1 41 | return dp[i][j] 42 | -------------------------------------------------------------------------------- /1-100q/87.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. 3 | 4 | Below is one possible representation of s1 = "great": 5 | 6 | great 7 | / \ 8 | gr eat 9 | / \ / \ 10 | g r e at 11 | / \ 12 | a t 13 | 14 | To scramble the string, we may choose any non-leaf node and swap its two children. 15 | 16 | For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat". 17 | 18 | rgeat 19 | / \ 20 | rg eat 21 | / \ / \ 22 | r g e at 23 | / \ 24 | a t 25 | 26 | We say that "rgeat" is a scrambled string of "great". 27 | ''' 28 | 29 | class Solution(object): 30 | def __init__(self): 31 | self.cache = {} 32 | 33 | def isScramble(self, s1, s2): 34 | if s1 == s2: 35 | return True 36 | if s1+s2 in self.cache: 37 | return self.cache[s1+s2] 38 | if len(s1) != len(s2) or sorted(s1) != sorted(s2): 39 | self.cache[s1+s2] = False 40 | return False 41 | for index in range(1, len(s1)): 42 | if self.isScramble(s1[:index], s2[:index]) and self.isScramble(s1[index:], s2[index:]): 43 | self.cache[s1+s2] =True 44 | return True 45 | if self.isScramble(s1[:index], s2[-index:]) and self.isScramble(s1[index:], s2[0:-index]): 46 | self.cache[s1+s2] = True 47 | return True 48 | 49 | self.cache[s1+s2] =False 50 | return False -------------------------------------------------------------------------------- /1200-1300q/1277.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a m * n matrix of ones and zeros, return how many square submatrices have all ones. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: matrix = 9 | [ 10 | [0,1,1,1], 11 | [1,1,1,1], 12 | [0,1,1,1] 13 | ] 14 | Output: 15 15 | Explanation: 16 | There are 10 squares of side 1. 17 | There are 4 squares of side 2. 18 | There is 1 square of side 3. 19 | Total number of squares = 10 + 4 + 1 = 15. 20 | Example 2: 21 | 22 | Input: matrix = 23 | [ 24 | [1,0,1], 25 | [1,1,0], 26 | [1,1,0] 27 | ] 28 | Output: 7 29 | Explanation: 30 | There are 6 squares of side 1. 31 | There is 1 square of side 2. 32 | Total number of squares = 6 + 1 = 7. 33 | 34 | 35 | Constraints: 36 | 37 | 1 <= arr.length <= 300 38 | 1 <= arr[0].length <= 300 39 | 0 <= arr[i][j] <= 1 40 | ''' 41 | class Solution(object): 42 | def countSquares(self, matrix): 43 | """ 44 | :type matrix: List[List[int]] 45 | :rtype: int 46 | """ 47 | 48 | p_arr = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix))] 49 | result = 0 50 | 51 | for index_i in range(1, len(matrix)): 52 | for index_j in range(1, len(matrix[0])): 53 | if matrix[index_i][index_j] == 1: 54 | matrix[index_i][index_j] = min(matrix[index_i-1][index_j-1], min(matrix[index_i-1][index_j], matrix[index_i][index_j-1]))+1 55 | # print p_arr 56 | return sum([ sum(x) for x in matrix]) -------------------------------------------------------------------------------- /100-200q/107.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). 3 | 4 | For example: 5 | Given binary tree [3,9,20,null,null,15,7], 6 | 7 | 3 8 | / \ 9 | 9 20 10 | / \ 11 | 15 7 12 | 13 | return its bottom-up level order traversal as: 14 | 15 | [ 16 | [15,7], 17 | [9,20], 18 | [3] 19 | ] 20 | ''' 21 | 22 | # Definition for a binary tree node. 23 | # class TreeNode(object): 24 | # def __init__(self, x): 25 | # self.val = x 26 | # self.left = None 27 | # self.right = None 28 | 29 | class Solution(object): 30 | def levelOrderBottom(self, root): 31 | """ 32 | :type root: TreeNode 33 | :rtype: List[List[int]] 34 | """ 35 | 36 | if not root: 37 | return [] 38 | 39 | queue = [(root, 0)] 40 | levelMap = {} 41 | 42 | while queue: 43 | node, level = queue.pop(0) 44 | if node.left: 45 | queue.append((node.left, level+1)) 46 | if node.right: 47 | queue.append((node.right, level+1)) 48 | 49 | if level in levelMap: 50 | levelMap[level].append(node.val) 51 | else: 52 | levelMap[level] = [node.val] 53 | 54 | result = [] 55 | for key, value in levelMap.iteritems(): 56 | result.append(value) 57 | return result[::-1] -------------------------------------------------------------------------------- /100-200q/116.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary tree 3 | 4 | struct TreeLinkNode { 5 | TreeLinkNode *left; 6 | TreeLinkNode *right; 7 | TreeLinkNode *next; 8 | } 9 | Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. 10 | 11 | Initially, all next pointers are set to NULL 12 | Example: 13 | 14 | Given the following perfect binary tree, 15 | 16 | 1 17 | / \ 18 | 2 3 19 | / \ / \ 20 | 4 5 6 7 21 | After calling your function, the tree should look like: 22 | 23 | 1 -> NULL 24 | / \ 25 | 2 -> 3 -> NULL 26 | / \ / \ 27 | 4->5->6->7 -> NULL 28 | ''' 29 | 30 | # Definition for binary tree with next pointer. 31 | # class TreeLinkNode: 32 | # def __init__(self, x): 33 | # self.val = x 34 | # self.left = None 35 | # self.right = None 36 | # self.next = None 37 | 38 | class Solution: 39 | # @param root, a tree link node 40 | # @return nothing 41 | def connect(self, root): 42 | def recursive(node): 43 | if node is None: 44 | return 45 | 46 | if node.left: 47 | node.left.next = node.right 48 | if node.right: 49 | if node.next: 50 | node.right.next = node.next.left 51 | else: 52 | node.right.next = None 53 | recursive(node.left) 54 | recursive(node.right) 55 | 56 | if root != None: 57 | root.next = None 58 | recursive(root) -------------------------------------------------------------------------------- /1200-1300q/1200.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements. 3 | 4 | Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows 5 | 6 | a, b are from arr 7 | a < b 8 | b - a equals to the minimum absolute difference of any two elements in arr 9 | 10 | 11 | Example 1: 12 | 13 | Input: arr = [4,2,1,3] 14 | Output: [[1,2],[2,3],[3,4]] 15 | Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order. 16 | Example 2: 17 | 18 | Input: arr = [1,3,6,10,15] 19 | Output: [[1,3]] 20 | Example 3: 21 | 22 | Input: arr = [3,8,-10,23,19,-4,-14,27] 23 | Output: [[-14,-10],[19,23],[23,27]] 24 | 25 | 26 | Constraints: 27 | 28 | 2 <= arr.length <= 10^5 29 | -10^6 <= arr[i] <= 10^6 30 | ''' 31 | 32 | class Solution(object): 33 | def minimumAbsDifference(self, arr): 34 | """ 35 | :type arr: List[int] 36 | :rtype: List[List[int]] 37 | """ 38 | if not arr: 39 | return [] 40 | 41 | arr.sort() 42 | mindiff = arr[1] - arr[0] 43 | for index in range(2, len(arr)): 44 | mindiff = min(mindiff, (arr[index] - arr[index-1])) 45 | 46 | result = [] 47 | for index in range(1, len(arr)): 48 | if arr[index] - arr[index-1] == mindiff: 49 | result.append([arr[index-1], arr[index]]) 50 | return result 51 | -------------------------------------------------------------------------------- /1-100q/56.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a collection of intervals, merge all overlapping intervals. 3 | 4 | Example 1: 5 | 6 | Input: [[1,3],[2,6],[8,10],[15,18]] 7 | Output: [[1,6],[8,10],[15,18]] 8 | Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. 9 | Example 2: 10 | 11 | Input: [[1,4],[4,5]] 12 | Output: [[1,5]] 13 | Explanation: Intervals [1,4] and [4,5] are considerred overlapping. 14 | ''' 15 | 16 | # Definition for an interval. 17 | # class Interval(object): 18 | # def __init__(self, s=0, e=0): 19 | # self.start = s 20 | # self.end = e 21 | 22 | class compare(object): 23 | def __init__(self, interval): 24 | self.interval = interval 25 | 26 | def __lt__(self, other): 27 | if self.interval.start == other.interval.start: 28 | return self.interval.end < other.interval.end 29 | return self.interval.start < other.interval.end 30 | 31 | class Solution(object): 32 | def merge(self, intervals): 33 | """ 34 | :type intervals: List[Interval] 35 | :rtype: List[Interval] 36 | """ 37 | 38 | intervals = sorted(intervals, key= compare) 39 | # intervals.sort(key=lambda x: x.start) 40 | merged = [] 41 | for interval in intervals: 42 | if not merged or merged[-1].end < interval.start: 43 | merged.append(interval) 44 | else: 45 | merged[-1].end = max(merged[-1].end, interval.end) 46 | return merged 47 | 48 | # Time: O(N*log(N)) 49 | # Space: O(1) -------------------------------------------------------------------------------- /1-100q/57.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). 3 | 4 | You may assume that the intervals were initially sorted according to their start times. 5 | 6 | Example 1: 7 | 8 | Input: intervals = [[1,3],[6,9]], newInterval = [2,5] 9 | Output: [[1,5],[6,9]] 10 | Example 2: 11 | 12 | Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] 13 | Output: [[1,2],[3,10],[12,16]] 14 | Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]. 15 | ''' 16 | 17 | # Definition for an interval. 18 | # class Interval(object): 19 | # def __init__(self, s=0, e=0): 20 | # self.start = s 21 | # self.end = e 22 | 23 | class Solution(object): 24 | def insert(self, intervals, newInterval): 25 | """ 26 | :type intervals: List[Interval] 27 | :type newInterval: Interval 28 | :rtype: List[Interval] 29 | """ 30 | result = [] 31 | for interval in intervals: 32 | if newInterval.start > interval.end: 33 | result.append(interval) 34 | elif newInterval.end < interval.start: 35 | result.append(newInterval) 36 | newInterval = interval 37 | elif newInterval.start <= interval.end or newInterval.end >= interval.start: 38 | newInterval = Interval(min(newInterval.start, interval.start), max(interval.end, newInterval.end)) 39 | 40 | result.append(newInterval) 41 | return result -------------------------------------------------------------------------------- /100-200q/115.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string S and a string T, count the number of distinct subsequences of S which equals T. 3 | 4 | A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not). 5 | 6 | Example 1: 7 | 8 | Input: S = "rabbbit", T = "rabbit" 9 | Output: 3 10 | Explanation: 11 | 12 | As shown below, there are 3 ways you can generate "rabbit" from S. 13 | (The caret symbol ^ means the chosen letters) 14 | 15 | rabbbit 16 | ^^^^ ^^ 17 | rabbbit 18 | ^^ ^^^^ 19 | rabbbit 20 | ^^^ ^^^ 21 | ''' 22 | 23 | class Solution(object): 24 | def numDistinct(self, s, t): 25 | """ 26 | :type s: str 27 | :type t: str 28 | :rtype: int 29 | """ 30 | 31 | row, col = len(s), len(t) 32 | 33 | if col > row: 34 | return 0 35 | 36 | dp = [[0 for _ in range(col+1)] for _ in range(row+1)] 37 | 38 | for r in range(row+1): 39 | for c in range(col+1): 40 | if r == 0 and c == 0: 41 | dp[r][c] = 1 42 | elif r == 0: 43 | dp[r][c] = 0 44 | elif c == 0: 45 | dp[r][c] = 1 46 | else: 47 | dp[r][c] = dp[r-1][c] 48 | if s[r-1] == t[c-1]: 49 | dp[r][c] += dp[r-1][c-1] 50 | return dp[row][col] -------------------------------------------------------------------------------- /1000-1100q/1065.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a text string and words (a list of strings), return all index pairs [i, j] so that the substring text[i]...text[j] is in the list of words. 3 | 4 | 5 | 6 | Example 1: 7 | 8 | Input: text = "thestoryofleetcodeandme", words = ["story","fleet","leetcode"] 9 | Output: [[3,7],[9,13],[10,17]] 10 | Example 2: 11 | 12 | Input: text = "ababa", words = ["aba","ab"] 13 | Output: [[0,1],[0,2],[2,3],[2,4]] 14 | Explanation: 15 | Notice that matches can overlap, see "aba" is found in [0,2] and [2,4]. 16 | 17 | 18 | Note: 19 | 20 | All strings contains only lowercase English letters. 21 | It's guaranteed that all strings in words are different. 22 | 1 <= text.length <= 100 23 | 1 <= words.length <= 20 24 | 1 <= words[i].length <= 50 25 | Return the pairs [i,j] in sorted order (i.e. sort them by their first coordinate in case of ties sort them by their second coordinate). 26 | ''' 27 | 28 | class Solution(object): 29 | def indexPairs(self, text, words): 30 | """ 31 | :type text: str 32 | :type words: List[str] 33 | :rtype: List[List[int]] 34 | """ 35 | if not words: 36 | return [] 37 | result = [] 38 | for word in words: 39 | starting = [index for index in range(len(text)) if text.startswith(word, index)] 40 | for start in starting: 41 | result.append([start, start+len(word)-1]) 42 | # print starting 43 | result.sort() 44 | return result 45 | -------------------------------------------------------------------------------- /400-500Q/410.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays. 3 | 4 | Note: 5 | If n is the length of array, assume the following constraints are satisfied: 6 | 7 | 1 ≤ n ≤ 1000 8 | 1 ≤ m ≤ min(50, n) 9 | Examples: 10 | 11 | Input: 12 | nums = [7,2,5,10,8] 13 | m = 2 14 | 15 | Output: 16 | 18 17 | 18 | Explanation: 19 | There are four ways to split nums into two subarrays. 20 | The best way is to split it into [7,2,5] and [10,8], 21 | where the largest sum among the two subarrays is only 18. 22 | ''' 23 | 24 | class Solution(object): 25 | def splitArray(self, nums, m): 26 | """ 27 | :type nums: List[int] 28 | :type m: int 29 | :rtype: int 30 | """ 31 | 32 | left, right = max(nums), sum(nums) 33 | 34 | while left < right: 35 | mid = left + ((right-left) >> 1) 36 | curr_sum, invalid, groups = 0, True, 0 37 | for num in nums: 38 | if num > mid: 39 | inalid = False 40 | break 41 | if num + curr_sum > mid: 42 | groups += 1 43 | curr_sum = 0 44 | curr_sum += num 45 | if invalid and groups < m: 46 | right = mid 47 | else: 48 | left = mid + 1 49 | return left 50 | -------------------------------------------------------------------------------- /900-1000q/997.py: -------------------------------------------------------------------------------- 1 | ''' 2 | In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge. 3 | 4 | If the town judge exists, then: 5 | 6 | The town judge trusts nobody. 7 | Everybody (except for the town judge) trusts the town judge. 8 | There is exactly one person that satisfies properties 1 and 2. 9 | You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b. 10 | 11 | If the town judge exists and can be identified, return the label of the town judge. Otherwise, return -1. 12 | 13 | 14 | 15 | Example 1: 16 | 17 | Input: N = 2, trust = [[1,2]] 18 | Output: 2 19 | Example 2: 20 | 21 | Input: N = 3, trust = [[1,3],[2,3]] 22 | Output: 3 23 | ''' 24 | 25 | class Solution(object): 26 | def findJudge(self, N, trust): 27 | """ 28 | :type N: int 29 | :type trust: List[List[int]] 30 | :rtype: int 31 | """ 32 | if not trust: 33 | return 1 34 | mapping = {} 35 | unique = set() 36 | for truste_list in trust: 37 | unique.add(truste_list[0]) 38 | if truste_list[1] in mapping: 39 | mapping[truste_list[1]] += 1 40 | else: 41 | mapping[truste_list[1]] = 1 42 | 43 | unique_set = len(unique) 44 | for key, value in mapping.items(): 45 | if value == unique_set: 46 | return key 47 | return -1 48 | -------------------------------------------------------------------------------- /1-100q/63.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). 3 | 4 | The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). 5 | 6 | Now consider if some obstacles are added to the grids. How many unique paths would there be? 7 | ''' 8 | 9 | class Solution(object): 10 | def uniquePathsWithObstacles(self, obstacleGrid): 11 | """ 12 | :type obstacleGrid: List[List[int]] 13 | :rtype: int 14 | """ 15 | m, n = len(obstacleGrid), len(obstacleGrid[0]) 16 | dp = [[0 for _ in range(n)] for _ in range(m)] 17 | 18 | if obstacleGrid[0][0] == 1 or obstacleGrid[m-1][n-1] == 1: 19 | return 0 20 | 21 | dp[0][0] = 1 22 | for index in range(1, m): 23 | if obstacleGrid[index][0] == 1: 24 | dp[index][0] = 0 25 | else: 26 | dp[index][0] = dp[index-1][0] 27 | 28 | for index in range(1, n): 29 | if obstacleGrid[0][index] == 1: 30 | dp[0][index] = 0 31 | else: 32 | dp[0][index] = dp[0][index-1] 33 | 34 | for index_i in range(1, m): 35 | for index_j in range(1, n): 36 | if obstacleGrid[index_i][index_j] == 1: 37 | dp[index_i][index_j] = 0 38 | else: 39 | dp[index_i][index_j] = dp[index_i-1][index_j] + dp[index_i][index_j-1] 40 | 41 | return dp[m-1][n-1] 42 | -------------------------------------------------------------------------------- /1000-1100q/1046.py: -------------------------------------------------------------------------------- 1 | ''' 2 | We have a collection of rocks, each rock has a positive integer weight. 3 | 4 | Each turn, we choose the two heaviest rocks and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is: 5 | 6 | If x == y, both stones are totally destroyed; 7 | If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x. 8 | At the end, there is at most 1 stone left. Return the weight of this stone (or 0 if there are no stones left.) 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: [2,7,4,1,8,1] 15 | Output: 1 16 | Explanation: 17 | We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then, 18 | we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then, 19 | we combine 2 and 1 to get 1 so the array converts to [1,1,1] then, 20 | we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of last stone. 21 | 22 | 23 | Note: 24 | 25 | 1 <= stones.length <= 30 26 | 1 <= stones[i] <= 1000 27 | ''' 28 | 29 | class Solution(object): 30 | def lastStoneWeight(self, stones): 31 | """ 32 | :type stones: List[int] 33 | :rtype: int 34 | """ 35 | while len(stones) > 1: 36 | max_x = max(stones) 37 | stones.remove(max_x) 38 | max_y = max(stones) 39 | stones.remove(max_y) 40 | 41 | if max_x != max_y: 42 | stones.append(max_x-max_y) 43 | return stones[0] if stones else 0 44 | -------------------------------------------------------------------------------- /100-200q/106.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given inorder and postorder traversal of a tree, construct the binary tree. 3 | 4 | Note: 5 | You may assume that duplicates do not exist in the tree. 6 | 7 | For example, given 8 | 9 | inorder = [9,3,15,20,7] 10 | postorder = [9,15,7,20,3] 11 | Return the following binary tree: 12 | 13 | 3 14 | / \ 15 | 9 20 16 | / \ 17 | 15 7 18 | ''' 19 | 20 | # Definition for a binary tree node. 21 | # class TreeNode(object): 22 | # def __init__(self, x): 23 | # self.val = x 24 | # self.left = None 25 | # self.right = None 26 | 27 | class Solution(object): 28 | def buildTree(self, inorder, postorder): 29 | """ 30 | :type inorder: List[int] 31 | :type postorder: List[int] 32 | :rtype: TreeNode 33 | """ 34 | self.index = len(inorder)-1 35 | def recursive(postorder, inorder, start, end): 36 | if start > end: 37 | return None 38 | 39 | node = TreeNode(postorder[self.index]) 40 | self.index -= 1 41 | if start == end: 42 | return node 43 | 44 | search_index = 0 45 | for i in range(start, end+1): 46 | if inorder[i] == node.val: 47 | search_index = i 48 | break 49 | node.right = recursive(postorder, inorder, search_index+1, end) 50 | node.left = recursive(postorder, inorder, start, search_index-1) 51 | return node 52 | 53 | return recursive(postorder, inorder, 0, len(inorder)-1) --------------------------------------------------------------------------------