Note that it is the kth smallest element in the sorted order, not the kth distinct element. Example: matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ], k = 8, return 13. """ from alg.label import Label Label(Label.BinarySearch, Label.Heap, Label.LinearithmicTime, Label.LeetCode) class KthSmallestElementInASortedMatrix(object): def kthSmallest(self, matrix, k): from heapq import heappush, heappop heap = [] row = len(matrix) col = len(matrix[0]) for i in range(col): heappush(heap, (matrix[0][i], (0, i))) for j in range(k - 1): curr = heappop(heap) x, y = curr[1]
Hint: 1 bull and 3 cows. (The bull is 8, the cows are 0, 1 and 7.) According to Wikipedia: "Bulls and Cows (also known as Cows and Bulls or Pigs and Bulls or Bulls and Cleots) is an old code-breaking mind or paper and pencil game for two or more players, predating the similar commercially marketed board game Mastermind. The numerical version of the game is usually played with 4 digits, but can also be played with 3 or any other number of digits." Write a function to return a hint according to the secret number and friend's guess, use A to indicate the bulls and B to indicate the cows, in the above example, your function should return 1A3B. You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal. """ from alg.label import Label Label(Label.String, Label.Array, Label.Hash, Label.LeetCode) class BullsAndCows: def getHint(self, secret, guess): def one_pass(secret, guess): # table records the appearance of a digit # digit from secret will increase the counter # digit from guess will decrease the counter count = [0] * 10 bull_cnt = 0 cow_cnt = 0 for i in range(len(secret)): a = ord(secret[i]) - ord('0') b = ord(guess[i]) - ord('0')
""" You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope. What is the maximum number of envelopes can you Russian doll? (put one inside other) Example: Given envelopes = [[5,4],[6,4],[6,7],[2,3]], the maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]). """ from alg.label import Label Label(Label.Array, Label.DynamicProgramming, Label.LinearithmicTime, Label.LeetCode) class RussianDollEnvelopes(object): def maxEnvelopes(self, envelopes): # sorted base on width then reversed height, so that dolls with the same width # will only contribute at most one height to the LIS. nums = sorted(envelopes, cmp=lambda x, y: x[0] - y[0] if x[0] != y[0] else y[1] - x[1]) size = len(nums) dp = [] for x in range(size): # LIS: given x, replace first ele >= x in LIS with x. low, high = -1, len(dp) while low + 1 < high: mid = (low + high) / 2
Example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]. Note: Follow up: What if the given array is already sorted? How would you optimize your algorithm? What if nums1's size is small compared to num2's size? Which algorithm is better? What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once? """ from alg.label import Label Label(Label.Array, Label.Greedy, Label.LeetCode) class IntersectionOfTwoArrays(object): def intersectII(self, nums1, nums2): """ Each element in the result should appear as many times as it shows in both arrays. The result can be in any order. """ from collections import Counter import itertools c1, c2 = Counter(nums1), Counter(nums2) common_keys = list(set(nums1) & set(nums2)) return list( itertools.chain.from_iterable( map(lambda x: [x] * min(c1[x], c2[x]), common_keys)))
""" Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results. Note: The input string may contain letters other than the parentheses '(' and ')'. Examples: "()())()" -> ["()()()", "(())()"] "(a)())()" -> ["(a)()()", "(a())()"] ")(" -> [""] """ from alg.label import Label Label(Label.BFS, Label.DFS, Label.LeetCode) class Solution(object): def removeInvalidParentheses(self, s): def _remove_invalid_parentheses(s, left_right_diff, st, cur): if left_right_diff < 0: return if s == '': if left_right_diff == 0: st.add(cur) return c = s[0] if c not in ['(', ')']: _remove_invalid_parentheses(s[1:], left_right_diff, st, cur + c) else: if c is '(':
Example 2: nums1 = [6, 7] nums2 = [6, 0, 4] k = 5 return [6, 7, 6, 0, 4] Example 3: nums1 = [3, 9] nums2 = [8, 9] k = 3 return [9, 8, 9] """ from alg.label import Label Label(Label.Array, Label.Sorting, Label.Stack, Label.LeetCode) class CreateMaxNumber(object): def maxNumber(self, nums1, nums2, k): def getMax(nums, t): ans = [] size = len(nums) for x in range(size): while ans and len(ans) + size - x > t and ans[-1] < nums[x]: ans.pop() if len(ans) < t: ans += nums[x], return ans def merge(nums1, nums2):
3 Explanation: 8 -> 4 -> 2 -> 1 Example 2: Input: 7 Output: 4 Explanation: 7 -> 8 -> 4 -> 2 -> 1 or 7 -> 6 -> 3 -> 2 -> 1 """ from alg.label import Label Label(Label.Math, Label.Recursion, Label.LeetCode) class IntegerReplacement(object): def integerReplacement(self, n): cnt = 0 while n > 1: if n & 1 == 0: n >>= 1 else: if n == 3 or ((n >> 1) & 1) == 0: n -= 1 else: n += 1 cnt += 1 return cnt
Given a list of unique words. Find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome. Example 1: Given words = ["bat", "tab", "cat"] Return [[0, 1], [1, 0]] The palindromes are ["battab", "tabbat"] Example 2: Given words = ["abcd", "dcba", "lls", "s", "sssll"] Return [[0, 1], [1, 0], [3, 2], [2, 4]] The palindromes are ["dcbaabcd", "abcddcba", "slls", "llssssll"] """ from alg.label import Label Label(Label.DynamicProgramming, Label.CubicTime, Label.LeetCode) class PalindromePairs(object): # O(l^2n), l=max(map(len, words)), n=len(words) def palindromePairs(self, words): def palindromePairsForOneWord(word, idx): n = len(word) pairs = [] if n == 1: return pairs is_palindrome = [[False] * n for _ in range(n)] for size in range(1, n + 1): for l in range(0, n - size + 1):
Example: // Init a singly linked list [1,2,3]. ListNode head = new ListNode(1); head.next = new ListNode(2); head.next.next = new ListNode(3); Solution solution = new Solution(head); // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning. solution.getRandom(); """ from alg.label import Label Label(Label.Math, Label.ReservoirSampling, Label.LinearithmicTime, Label.LeetCode) # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class LinkedListRandomNode(object): def __init__(self, head): self.head = head def getRandom(self): import random ans, cnt = 0, 0
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). Example 1: s = "abc", t = "ahbgdc" Return true. Example 2: s = "axc", t = "ahbgdc" Return false. Follow up: If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1 billion, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code? """ from alg.label import Label Label(Label.Queue, Label.LinearTime, Label.LeetCode) import collections class IsSubsequence(object): def isSubsequence(self, s, t): queue = collections.deque(s) for c in t: if not queue: return True if c == queue[0]: queue.popleft() return not queue
You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. Example: [[0,1,0,0], [1,1,1,0], [0,1,0,0], [1,1,0,0]] Answer: 16 Explanation: The perimeter is the 16 yellow stripes in the image below: """ from alg.label import Label Label(Label.MatrixGraph, Label.Math, Label.LeetCode, Label.LinearTime) class IslandPerimeter(object): def islandPerimeter(self, grid): perimeter = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 0: continue perimeter += 4 if i > 0 and grid[i - 1][j] == 1: perimeter -= 2 if j > 0 and grid[i][j - 1] == 1: perimeter -= 2 return perimeter
(2, 1, 1) (2, 2) (3, 1) Note that different sequences are counted as different combinations. Therefore the output is 7. Follow up: What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers? """ from alg.label import Label Label(Label.QuadraticTime, Label.DynamicProgramming, Label.LeetCode) class CombinationSumIV(object): def combinationSum4(self, nums, target): dp = [1] + [0] * target for i in range(1, target + 1): for n in nums: prev = i - n if prev == 0 or (prev > 0 and dp[prev] > 0): dp[i] += dp[prev] return dp[target] ins = CombinationSumIV() print ins.combinationSum4([1, 2, 3], 5)
""" Given a non-empty array of integers, return the k most frequent elements. For example, Given [1,1,1,2,2,3] and k = 2, return [1,2]. Note: You may assume k is always valid, 1 <= k <= number of unique elements. Your algorithm's time complexity must be better than O(n log n), where n is the array's size. """ from alg.label import Label Label(Label.Hash, Label.Heap, Label.LeetCode) class TopKFrequentElements(object): def topKFrequent(self, nums, K): from collections import defaultdict import heapq as hq d = defaultdict(int) for n in nums: d[n] += 1 heap = [(-v, k) for k, v in d.iteritems()] hq.heapify(heap) ret = [] while len(ret) < K: ret.append(hq.heappop(heap)[1]) return ret ins = TopKFrequentElements() print ins.topKFrequent([1,1,1,2,2,3], 2)
The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Now your job is to find the total Hamming distance between all pairs of the given numbers. Example: Input: 4, 14, 2 Output: 6 Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just showing the four bits relevant in this case). So the answer will be: HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. """ from alg.label import Label Label(Label.BitManipulation, Label.LeetCode, Label.LinearTime) class TotalHammingDistance(object): def totalHammingDistance(self, nums): cnt = 0 for i in range(32): zeros, ones = 0, 0 for n in nums: bit = (n >> i) & 1 if bit == 1: ones += 1 else: zeros += 1 cnt += ones * zeros return cnt
""" Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. """ from alg.label import Label Label(Label.DynamicProgramming, Label.Substring, Label.QuadraticTime, Label.LinearTime, Label.LeetCode) def fastLongestPalindromes(seq): """ Behaves identically to naiveLongestPalindrome (see below), but runs in linear time. """ seqLen = len(seq) l = [] i = 0 palLen = 0 # Loop invariant: seq[(i - palLen):i] is a palindrome. # Loop invariant: len(l) >= 2 * i - palLen. The code path that # increments palLen skips the l-filling inner-loop. # Loop invariant: len(l) < 2 * i + 1. Any code path that # increments i past seqLen - 1 exits the loop early and so skips # the l-filling inner loop. while i < seqLen: # First, see if we can extend the current palindrome. Note # that the center of the palindrome remains fixed. if i > palLen and seq[i - palLen - 1] == seq[i]: palLen += 2 i += 1
A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. For example: "112358" is an additive number because the digits can form an additive sequence: 1, 1, 2, 3, 5, 8. 1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8 "199100199" is also an additive number, the additive sequence is: 1, 99, 100, 199. 1 + 99 = 100, 99 + 100 = 199 Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid. Given a string represents an integer, write a function to determine if it's an additive number. """ from alg.label import Label Label(Label.Recursion, Label.Backtracking, Label.LeetCode) class Solution(object): def isAdditiveNumber(self, num): n = len(num) for j in range(1, n - 1): for k in range(j + 1, n): if self.is_additive_number_recur(num, n, 0, j, k): return True return False def is_additive_number_recur(self, num, n, i, j, k): if k >= n: return False res_len = max(j - i, k - j)
the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue. Note: The number of people is less than 1,100. Example Input: [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] Output: [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]] """ from alg.label import Label Label(Label.Queue, Label.Greedy, Label.QuadraticTime, Label.LeetCode) class QueueReconstructionByHeight(object): def reconstructQueue(self, people): import heapq as hq heap = [] rest = [[t[0], t[1], t[1]] for t in people] for t in rest: if t[1] == 0: hq.heappush(heap, t) ret = [] while heap: chosen = hq.heappop(heap) ret.append(chosen[:-1])
Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. You need to output 1. Example 2: Input: [1,2], [1,2,3] Output: 2 Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children, You need to output 2. """ from alg.label import Label Label(Label.Greedy, Label.Array, Label.LeetCode, Label.LinearTime) class AssignCookies(object): def findContentChildren(self, g, s): g = sorted(g) s = sorted(s) gi = si = 0 while si < len(s) and gi < len(g): if s[si] >= g[gi]: gi += 1 si += 1 return gi ins = AssignCookies()
Input: [3, 1, 4, 2] Output: True Explanation: There is a 132 pattern in the sequence: [1, 4, 2]. Example 3: Input: [-1, 3, 2, 0] Output: True Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0]. """ from alg.label import Label Label(Label.Array, Label.Stack, Label.Subarray, Label.LeetCode, Label.LinearTime) class Pattern132(object): def find132pattern(self, nums): e3, st = float('-inf'), [] for e in reversed(nums): if e < e3: return True while st and e > st[-1]: e3 = st.pop() st.append(e) return False ins = Pattern132()
Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6]. So we only need 1 patch. Example 2: nums = [1, 5, 10], n = 20 Return 2. The two patches can be [2, 4]. Example 3: nums = [1, 2, 2], n = 5 Return 0. """ from alg.label import Label Label(Label.Math, Label.Greedy, Label.LeetCode) class PatchingArray(object): def minPatches(self, nums, n): assert len(nums) == 0 or nums[0] == 1 next_sum, i, no_of_patch = 1, 0, 0 l = len(nums) while next_sum < n: if i < l and nums[i] <= next_sum: next_sum += nums[i] i += 1 else: no_of_patch += 1 next_sum <<= 1 return no_of_patch
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4]. Examples: s = "3[a]2[bc]", return "aaabcbc". s = "3[a2[c]]", return "accaccacc". s = "2[abc]3[cd]ef", return "abcabccdcdcdef". """ from alg.label import Label Label(Label.Stack, Label.ConstantTime, Label.LeetCode) class DecodeString(object): def decodeString(self, s): def pop(): poped = [] while string_stck and string_stck[-1] != '[': poped.insert(0, string_stck.pop()) if string_stck and string_stck[-1] == '[': string_stck.pop() return num_stck.pop() * ''.join(poped) ret = '' num_stck, string_stck = [1], [] i = 0
[4, 1, 0, 1, 7], [1, 0, 3, 0, 5] ] sumRegion(2, 1, 4, 3) -> 8 sumRegion(1, 1, 2, 2) -> 11 sumRegion(1, 2, 2, 4) -> 12 Note: You may assume that the matrix does not change. There are many calls to sumRegion function. You may assume that row1 <= row2 and col1 <= col2. """ from alg.label import Label Label(Label.Array, Label.MatrixGraph, Label.DynamicProgramming, Label.QuadraticTime, Label.LeetCode) class NumMatrix(object): def __init__(self, matrix): self._matrix = matrix for r in range(0, len(matrix)): for c in range(0, len(matrix[r])): self._matrix[r][c] += self._matrix[r][c - 1] if c > 0 else 0 for c in range(0, len(matrix[r])): self._matrix[r][c] += self._matrix[r - 1][c] if r > 0 else 0 def sumRegion(self, row1, col1, row2, col2): return self._matrix[row2][col2] + (self._matrix[row1 - 1][col1 - 1] if row1 > 0 and col1 > 0 else 0) - \ (self._matrix[row1 - 1][col2] if row1 > 0 else 0) - \ (self._matrix[row2][col1 - 1] if col1 > 0 else 0)
Given s = "324", You should return a NestedInteger object which contains a single integer 324. Example 2: Given s = "[123,[456,[789]]]", Return a NestedInteger object containing a nested list with 2 elements: 1. An integer containing value 123. 2. A nested list containing two elements: i. An integer containing value 456. ii. A nested list with one element: a. An integer containing value 789. """ from alg.label import Label Label(Label.Stack, Label.LinearTime, Label.LeetCode) # """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ class NestedInteger(object): def __init__(self, value=None): """ If value is not specified, initializes an empty list. Otherwise initializes a single integer equal to value. """ def isInteger(self): """
""" Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Example: Given a = 1 and b = 2, return 3. """ from alg.label import Label Label(Label.BitManipulation, Label.LeetCode) class SumOfTwoIntegers(object): def getSum(self, a, b): MAX_INT = 0x7FFFFFFF MIN_INT = 0x80000000 MASK = 0x100000000 while b: a, b = (a ^ b) % MASK, ((a & b) << 1) % MASK return a if a <= MAX_INT else ~((a % MIN_INT) ^ MAX_INT) ins = SumOfTwoIntegers() for a, b in [(-2, 2), (1, -9), (-14, 16), (-2, -3)]: print a + b, ins.getSum(a, b)
The input is: vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries , where equations.size() == values.size(), and the values are positive. This represents the equations. Return vector<double>. According to the example above: equations = [ ["a", "b"], ["b", "c"] ], values = [2.0, 3.0], queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ]. The input is always valid. You may assume that evaluating the queries will result in no division by zero and there is no contradiction. """ from alg.label import Label Label(Label.DirectedGraph, Label.UnionFind, Label.LeetCode) from collections import defaultdict class EvaluateDivision(object): def calcEquation(self, equations, values, queries): multiples = defaultdict(list) variables = {} parent = {} def get_cluster(c): x = c while x in parent: x = parent[x] return x def assign_values():
Operations allowed: Fill any of the jugs completely. Empty any of the jugs. Pour water from one jug into another till the other jug is completely full or the first jug itself is empty. Example 1: Input: x = 2, y = 6, z = 4 Output: True Example 2: Input: x = 2, y = 6, z = 5 Output: False """ from alg.label import Label Label(Label.Math, Label.LeetCode) class WaterAndJugProblem(object): def canMeasureWater(self, x, y, z): if x > y: x, y = y, x gcd = self.gcd(x, y) if gcd == 0: return z == 0 return z % gcd == 0 and z <= x + y def gcd(self, a, b): return self.gcd(b % a, a) if a > 0 else b
For example, you may serialize the following tree 1 / \ 2 3 / \ 4 5 as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself. Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless. """ from alg.data_structure import TreeNode from alg.label import Label Label(Label.BinaryTree, Label.LeetCode) class SerializeAndDeserializeBinaryTree: # pre-order with left subtree prefixed with its size def serialize(self, root): if root is None: return None ret = [str(root.val)] left = self.serialize(root.left) if not left is None: left_list = left.split(',') ret += [str(len(left_list))] + left_list else: ret.append('0') right = self.serialize(root.right) if not right is None:
""" Given a positive integer num, write a function which returns True if num is a perfect square else False. Note: Do not use any built-in library function such as sqrt. """ from alg.label import Label Label(Label.Arithmetic, Label.BinarySearch, Label.LeetCode) class ValidPerfectSquare(object): def isPerfectSquare(self, num): l, r = 0, num while l + 1 < r: m = (l + r) / 2 square = m**2 if square == num: return True if square > num: r = m else: l = m return r**2 == num ins = ValidPerfectSquare() for i in range(1, 20): print i, ins.isPerfectSquare(i)
""" Given two strings s and t which consist of only lowercase letters. String t is generated by random shuffling string s and then add one more letter at a random position. Find the letter that was added in t. Example: Input: s = "abcd" t = "abcde" Output: e Explanation: 'e' is the letter that was added. """ from alg.label import Label Label(Label.Hash, Label.LinearTime, Label.LeetCode) class FindTheDifference(object): def findTheDifference(self, s, t): from collections import Counter sc = Counter(s) tc = Counter(t) for c in tc: if c not in sc or sc[c] != tc[c]: return c return None
""" There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the nth round, you only toggle the last bulb. Find how many bulbs are on after n rounds. """ from alg.label import Label Label(Label.Arithmetic, Label.LeetCode) class BulbSwitcher(object): def bulbSwitch(self, n): return int(n**0.5)