desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
':type picture: List[List[str]] :rtype: int'
def findLonelyPixel(self, picture):
(rows, cols) = (([0] * len(picture)), ([0] * len(picture[0]))) for i in xrange(len(picture)): for j in xrange(len(picture[0])): if (picture[i][j] == 'B'): rows[i] += 1 cols[j] += 1 result = 0 for i in xrange(len(picture)): if (rows[i] == 1): ...
':type picture: List[List[str]] :type N: int :rtype: int'
def findLonelyPixel(self, picture):
return sum(((col.count('B') == 1 == picture[col.index('B')].count('B')) for col in zip(*picture)))
':type M: List[List[int]] :rtype: int'
def findCircleNum(self, M):
class UnionFind(object, ): def __init__(self, n): self.set = range(n) self.count = n def find_set(self, x): if (self.set[x] != x): self.set[x] = self.find_set(self.set[x]) return self.set[x] def union_set(self, x, y): ...
':type num: int :rtype: bool'
def checkPerfectNumber(self, num):
if (num <= 0): return False sqrt_num = int((num ** 0.5)) total = sum(((i + (num // i)) for i in xrange(1, (sqrt_num + 1)) if ((num % i) == 0))) if ((sqrt_num ** 2) == num): total -= sqrt_num return ((total - num) == num)
':type s: str :type p: str :rtype: List[int]'
def findAnagrams(self, s, p):
result = [] cnts = ([0] * 26) for c in p: cnts[(ord(c) - ord('a'))] += 1 (left, right) = (0, 0) while (right < len(s)): cnts[(ord(s[right]) - ord('a'))] -= 1 while ((left <= right) and (cnts[(ord(s[right]) - ord('a'))] < 0)): cnts[(ord(s[left]) - ord('a'))] += 1 ...
':type nums1: List[int] :type nums2: List[int] :rtype: List[int]'
def intersection(self, nums1, nums2):
if (len(nums1) > len(nums2)): return self.intersection(nums2, nums1) lookup = set() for i in nums1: lookup.add(i) res = [] for i in nums2: if (i in lookup): res += (i,) lookup.discard(i) return res
':type nums1: List[int] :type nums2: List[int] :rtype: List[int]'
def intersection2(self, nums1, nums2):
return list((set(nums1) & set(nums2)))
':type nums1: List[int] :type nums2: List[int] :rtype: List[int]'
def intersection(self, nums1, nums2):
if (len(nums1) > len(nums2)): return self.intersection(nums2, nums1) def binary_search(compare, nums, left, right, target): while (left < right): mid = (left + ((right - left) / 2)) if compare(nums[mid], target): right = mid else: ...
':type nums1: List[int] :type nums2: List[int] :rtype: List[int]'
def intersection(self, nums1, nums2):
(nums1.sort(), nums2.sort()) res = [] (it1, it2) = (0, 0) while ((it1 < len(nums1)) and (it2 < len(nums2))): if (nums1[it1] < nums2[it2]): it1 += 1 elif (nums1[it1] > nums2[it2]): it2 += 1 else: if ((not res) or (res[(-1)] != nums1[it1])): ...
':type n: int :rtype: int'
def findDerangement(self, n):
M = 1000000007 (mul, total) = (1, 0) for i in reversed(xrange((n + 1))): total = (((total + M) + ((1 if ((i % 2) == 0) else (-1)) * mul)) % M) mul = ((mul * i) % M) return total
':type n: int :type edges: List[List[int]] :rtype: int'
def countComponents(self, n, edges):
union_find = UnionFind(n) for (i, j) in edges: union_find.union_set(i, j) return union_find.count
':type lists: List[ListNode] :rtype: ListNode'
def mergeKLists(self, lists):
def mergeTwoLists(l1, l2): curr = dummy = ListNode(0) while (l1 and l2): if (l1.val < l2.val): curr.next = l1 l1 = l1.next else: curr.next = l2 l2 = l2.next curr = curr.next curr.next = (l1 or...
':type numerator: int :type denominator: int :rtype: str'
def fractionToDecimal(self, numerator, denominator):
result = '' if (((numerator > 0) and (denominator < 0)) or ((numerator < 0) and (denominator > 0))): result = '-' (dvd, dvs) = (abs(numerator), abs(denominator)) result += str((dvd / dvs)) dvd %= dvs if (dvd > 0): result += '.' lookup = {} while (dvd and (dvd not in looku...
':type s: str :type k: int :rtype: int'
def longestSubstring(self, s, k):
def longestSubstringHelper(s, k, start, end): count = ([0] * 26) for i in xrange(start, end): count[(ord(s[i]) - ord('a'))] += 1 max_len = 0 i = start while (i < end): while ((i < end) and (count[(ord(s[i]) - ord('a'))] < k)): i += 1 ...
':type senate: str :rtype: str'
def predictPartyVictory(self, senate):
n = len(senate) (radiant, dire) = (collections.deque(), collections.deque()) for (i, c) in enumerate(senate): if (c == 'R'): radiant.append(i) else: dire.append(i) while (radiant and dire): (r_idx, d_idx) = (radiant.popleft(), dire.popleft()) if (r...
':type n: int :type edges: List[List[int]] :rtype: List[int]'
def findMinHeightTrees(self, n, edges):
if (n == 1): return [0] neighbors = collections.defaultdict(set) for (u, v) in edges: neighbors[u].add(v) neighbors[v].add(u) (pre_level, unvisited) = ([], set()) for i in xrange(n): if (len(neighbors[i]) == 1): pre_level.append(i) unvisited.add(i)...
'Initialize your data structure here.'
def __init__(self):
self.__intervals = []
':type val: int :rtype: void'
def addNum(self, val):
def upper_bound(nums, target): (left, right) = (0, (len(nums) - 1)) while (left <= right): mid = (left + ((right - left) / 2)) if (nums[mid].start > target): right = (mid - 1) else: left = (mid + 1) return left i = upper...
':rtype: List[Interval]'
def getIntervals(self):
return self.__intervals
':type words: List[str] :rtype: List[List[str]]'
def wordSquares(self, words):
result = [] trie = TrieNode() for i in xrange(len(words)): trie.insert(words, i) curr = [] for s in words: curr.append(s) self.wordSquaresHelper(words, trie, curr, result) curr.pop() return result
':type s: str :rtype: str'
def decodeString(self, s):
(curr, nums, strs) = ([], [], []) n = 0 for c in s: if c.isdigit(): n = (((n * 10) + ord(c)) - ord('0')) elif (c == '['): nums.append(n) n = 0 strs.append(curr) curr = [] elif (c == ']'): strs[(-1)].extend((curr ...
':type a: int :type b: List[int] :rtype: int'
def superPow(self, a, b):
def myPow(a, n, b): result = 1 x = (a % b) while n: if (n & 1): result = ((result * x) % b) n >>= 1 x = ((x * x) % b) return (result % b) result = 1 for digit in b: result = ((myPow(result, 10, 1337) * myPow(a, digit...
':type buckets: int :type minutesToDie: int :type minutesToTest: int :rtype: int'
def poorPigs(self, buckets, minutesToDie, minutesToTest):
return int(math.ceil((math.log(buckets) / math.log(((minutesToTest / minutesToDie) + 1)))))
':type nums: List[int] :rtype: int'
def totalHammingDistance(self, nums):
result = 0 for i in xrange(32): counts = ([0] * 2) for num in nums: counts[((num >> i) & 1)] += 1 result += (counts[0] * counts[1]) return result
'Find the point to partition n keys for a perfect binary search tree'
@staticmethod def perfect_tree_pivot(n):
x = 1 x = (1 << (n.bit_length() - 1)) if (((x // 2) - 1) <= (n - x)): return (x - 1) else: return (n - (x // 2))
':type nums: List[int] :rtype: int'
def arrayNesting(self, nums):
result = 0 for num in nums: if (num != None): (start, count) = (num, 0) while (nums[start] != None): temp = start start = nums[start] nums[temp] = None count += 1 result = max(result, count) return re...
':type nums: List[int] :rtype: List[int]'
def countSmaller(self, nums):
def countAndMergeSort(num_idxs, start, end, counts): if ((end - start) <= 0): return 0 mid = (start + ((end - start) / 2)) countAndMergeSort(num_idxs, start, mid, counts) countAndMergeSort(num_idxs, (mid + 1), end, counts) r = (mid + 1) tmp = [] fo...
':type nums: List[int] :rtype: List[int]'
def countSmaller(self, nums):
def binarySearch(A, target, compare): (start, end) = (0, (len(A) - 1)) while (start <= end): mid = (start + ((end - start) / 2)) if compare(target, A[mid]): end = (mid - 1) else: start = (mid + 1) return start class BIT(...
':type nums: List[int] :rtype: List[int]'
def countSmaller(self, nums):
res = ([0] * len(nums)) bst = self.BST() for i in reversed(xrange(len(nums))): bst.insertNode(nums[i]) res[i] = bst.query(nums[i]) return res
':type s: str :rtype: bool'
def isNumber(self, s):
transition_table = [[(-1), 0, 3, 1, 2, (-1)], [(-1), 8, (-1), 1, 4, 5], [(-1), (-1), (-1), 4, (-1), (-1)], [(-1), (-1), (-1), 1, 2, (-1)], [(-1), 8, (-1), 4, (-1), 5], [(-1), (-1), 6, 7, (-1), (-1)], [(-1), (-1), (-1), 7, (-1), (-1)], [(-1), 8, (-1), 7, (-1), (-1)], [(-1), 8, (-1), (-1), (-1), (-1)]] state = 0 ...
':type s: str :rtype: bool'
def isNumber(self, s):
import re return bool(re.match('^\\s*[\\+-]?((\\d+(\\.\\d*)?)|\\.\\d+)([eE][\\+-]?\\d+)?\\s*$', s))
':type haystack: str :type needle: str :rtype: int'
def strStr(self, haystack, needle):
if (not needle): return 0 return self.KMP(haystack, needle)
':type haystack: str :type needle: str :rtype: int'
def strStr2(self, haystack, needle):
try: return haystack.index(needle) except: return (-1)
':type haystack: str :type needle: str :rtype: int'
def strStr(self, haystack, needle):
for i in xrange(((len(haystack) - len(needle)) + 1)): if (haystack[i:(i + len(needle))] == needle): return i return (-1)
':type root: TreeNode :rtype: int'
def rob(self, root):
def robHelper(root): if (not root): return (0, 0) (left, right) = (robHelper(root.left), robHelper(root.right)) return (((root.val + left[1]) + right[1]), (max(left) + max(right))) return max(robHelper(root))
':type nums: List[int] :rtype: int'
def findMaxConsecutiveOnes(self, nums):
(result, prev, curr) = (0, 0, 0) for n in nums: if (n == 0): result = max(result, ((prev + curr) + 1)) (prev, curr) = (curr, 0) else: curr += 1 return min(max(result, ((prev + curr) + 1)), len(nums))
':type nums: List[int] :type lower: int :type upper: int :rtype: int'
def countRangeSum(self, nums, lower, upper):
def countAndMergeSort(sums, start, end, lower, upper): if ((end - start) <= 1): return 0 mid = (start + ((end - start) / 2)) count = (countAndMergeSort(sums, start, mid, lower, upper) + countAndMergeSort(sums, mid, end, lower, upper)) (j, k, r) = (mid, mid, mid) t...
':type nums: List[int] :type lower: int :type upper: int :rtype: int'
def countRangeSum(self, nums, lower, upper):
def countAndMergeSort(sums, start, end, lower, upper): if ((end - start) <= 0): return 0 mid = (start + ((end - start) / 2)) count = (countAndMergeSort(sums, start, mid, lower, upper) + countAndMergeSort(sums, (mid + 1), end, lower, upper)) (j, k, r) = ((mid + 1), (mid + ...
'Encodes a list of strings to a single string. :type strs: List[str] :rtype: str'
def encode(self, strs):
encoded_str = '' for s in strs: encoded_str += (('%0*x' % (8, len(s))) + s) return encoded_str
'Decodes a single string to a list of strings. :type s: str :rtype: List[str]'
def decode(self, s):
i = 0 strs = [] while (i < len(s)): l = int(s[i:(i + 8)], 16) strs.append(s[(i + 8):((i + 8) + l)]) i += (8 + l) return strs
'@param head The linked list\'s head. Note that the head is guanranteed to be not null, so it contains at least one node. :type head: ListNode'
def __init__(self, head):
self.__head = head
'Returns a random node\'s value. :rtype: int'
def getRandom(self):
reservoir = self.__head.val (curr, n) = (self.__head.next, 1) while curr: reservoir = (curr.val if (randint(1, (n + 1)) == 1) else reservoir) (curr, n) = (curr.next, (n + 1)) return reservoir
':type x: List[int] :rtype: bool'
def isSelfCrossing(self, x):
if ((len(x) >= 5) and (x[3] == x[1]) and ((x[4] + x[0]) >= x[2])): return True for i in xrange(3, len(x)): if ((x[i] >= x[(i - 2)]) and (x[(i - 3)] >= x[(i - 1)])): return True elif ((i >= 5) and (x[(i - 4)] <= x[(i - 2)]) and ((x[i] + x[(i - 4)]) >= x[(i - 2)]) and (x[(i - 1...
':type points: List[Point] :rtype: int'
def maxPoints(self, points):
max_points = 0 for (i, start) in enumerate(points): (slope_count, same) = (collections.defaultdict(int), 1) for j in xrange((i + 1), len(points)): end = points[j] if ((start.x == end.x) and (start.y == end.y)): same += 1 else: s...
':type words: List[str] :rtype: str'
def alienOrder(self, words):
(result, zero_in_degree_queue, in_degree, out_degree) = ([], collections.deque(), {}, {}) nodes = sets.Set() for word in words: for c in word: nodes.add(c) for i in xrange(1, len(words)): if ((len(words[(i - 1)]) > len(words[i])) and (words[(i - 1)][:len(words[i])] == words[i...
':type words: List[str] :rtype: str'
def alienOrder(self, words):
(nodes, ancestors) = (sets.Set(), {}) for i in xrange(len(words)): for c in words[i]: nodes.add(c) for node in nodes: ancestors[node] = [] for i in xrange(1, len(words)): if ((len(words[(i - 1)]) > len(words[i])) and (words[(i - 1)][:len(words[i])] == words[i])): ...
':type maze: List[List[int]] :type start: List[int] :type destination: List[int] :rtype: bool'
def hasPath(self, maze, start, destination):
(start, destination) = (tuple(start), tuple(destination)) def neighbors(maze, node): for dir in [((-1), 0), (0, 1), (0, (-1)), (1, 0)]: (cur_node, dist) = (list(node), 0) while ((0 <= (cur_node[0] + dir[0]) < len(maze)) and (0 <= (cur_node[1] + dir[1]) < len(maze[0])) and (not ma...
':type s: str :type t: str :rtype: bool'
def isOneEditDistance(self, s, t):
(m, n) = (len(s), len(t)) if (m > n): return self.isOneEditDistance(t, s) if ((n - m) > 1): return False (i, shift) = (0, (n - m)) while ((i < m) and (s[i] == t[i])): i += 1 if (shift == 0): i += 1 while ((i < m) and (s[i] == t[(i + shift)])): i += 1 ...
':type path: str :rtype: List[str]'
def ls(self, path):
curr = self.__getNode(path) if curr.is_file: return [self.__split(path, '/')[(-1)]] return sorted(curr.children.keys())
':type path: str :rtype: void'
def mkdir(self, path):
curr = self.__putNode(path) curr.is_file = False
':type filePath: str :type content: str :rtype: void'
def addContentToFile(self, filePath, content):
curr = self.__putNode(filePath) curr.is_file = True curr.content += content
':type filePath: str :rtype: str'
def readContentFromFile(self, filePath):
return self.__getNode(filePath).content
':type nums: List[int] :type k: int :rtype: List[int]'
def topKFrequent(self, nums, k):
counts = collections.defaultdict(int) for i in nums: counts[i] += 1 p = [] for (key, val) in counts.iteritems(): p.append((val, key)) self.kthElement(p, k) result = [] for i in xrange(k): result.append(p[i][1]) return result
':type nums: List[int] :type k: int :rtype: List[int]'
def topKFrequent(self, nums, k):
return [key for (key, _) in collections.Counter(nums).most_common(k)]
':type nestedList: List[NestedInteger] :rtype: int'
def depthSum(self, nestedList):
def depthSumHelper(nestedList, depth): res = 0 for l in nestedList: if l.isInteger(): res += (l.getInteger() * depth) else: res += depthSumHelper(l.getList(), (depth + 1)) return res return depthSumHelper(nestedList, 1)
':type sentences: List[str] :type times: List[int]'
def __init__(self, sentences, times):
self.__trie = TrieNode() self.__cur_node = self.__trie self.__search = [] self.__sentence_to_count = collections.defaultdict(int) for (sentence, count) in zip(sentences, times): self.__sentence_to_count[sentence] = count self.__trie.insert(sentence, count)
':type c: str :rtype: List[str]'
def input(self, c):
result = [] if (c == '#'): self.__sentence_to_count[''.join(self.__search)] += 1 self.__trie.insert(''.join(self.__search), self.__sentence_to_count[''.join(self.__search)]) self.__cur_node = self.__trie self.__search = [] else: self.__search.append(c) if self...
':type S: str :type K: int :rtype: str'
def licenseKeyFormatting(self, S, K):
result = [] for i in reversed(xrange(len(S))): if (S[i] == '-'): continue if ((len(result) % (K + 1)) == K): result += '-' result += S[i].upper() return ''.join(reversed(result))
':type root: TreeNode :type target: float :rtype: int'
def closestValue(self, root, target):
gap = float('inf') closest = float('inf') while root: if (abs((root.val - target)) < gap): gap = abs((root.val - target)) closest = root if (target == root.val): break elif (target < root.val): root = root.left else: ...
':type board: str :type hand: str :rtype: int'
def findMinStep(self, board, hand):
def shrink(s): stack = [] start = 0 for i in xrange((len(s) + 1)): if ((i == len(s)) or (s[i] != s[start])): if (stack and (stack[(-1)][0] == s[start])): stack[(-1)][1] += (i - start) if (stack[(-1)][1] >= 3): ...
':type nums: List[int] :type k: int :rtype: float'
def findMaxAverage(self, nums, k):
total = 0 for i in xrange(k): total += nums[i] result = total for i in xrange(k, len(nums)): total += (nums[i] - nums[(i - k)]) result = max(result, total) return (float(result) / k)
':type nums: List[int] :rtype: int'
def findMin(self, nums):
(left, right) = (0, len(nums)) target = nums[(-1)] while (left < right): mid = (left + ((right - left) / 2)) if (nums[mid] <= target): right = mid else: left = (mid + 1) return nums[left]
':type nums: List[int] :rtype: int'
def findMin(self, nums):
(left, right) = (0, (len(nums) - 1)) while ((left < right) and (nums[left] >= nums[right])): mid = (left + ((right - left) / 2)) if (nums[mid] < nums[left]): right = mid else: left = (mid + 1) return nums[left]
':type start: str :type end: str :type bank: List[str] :rtype: int'
def minMutation(self, start, end, bank):
lookup = {} for b in bank: lookup[b] = False q = deque([(start, 0)]) while q: (cur, level) = q.popleft() if (cur == end): return level for i in xrange(len(cur)): for c in ['A', 'T', 'C', 'G']: if (cur[i] == c): c...
':type s: str :type wordDict: Set[str] :rtype: bool'
def wordBreak(self, s, wordDict):
n = len(s) max_len = 0 for string in wordDict: max_len = max(max_len, len(string)) can_break = [False for _ in xrange((n + 1))] can_break[0] = True for i in xrange(1, (n + 1)): for l in xrange(1, (min(i, max_len) + 1)): if (can_break[(i - l)] and (s[(i - l):i] in word...
':type root: TreeNode :rtype: List[int]'
def findMode(self, root):
def inorder(root, prev, cnt, max_cnt, result): if (not root): return (prev, cnt, max_cnt) (prev, cnt, max_cnt) = inorder(root.left, prev, cnt, max_cnt, result) if prev: if (root.val == prev.val): cnt += 1 else: cnt = 1 ...
'Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory. :type maxNumbers: int'
def __init__(self, maxNumbers):
self.__curr = 0 self.__numbers = range(maxNumbers) self.__used = ([False] * maxNumbers)
'Provide a number which is not assigned to anyone. @return - Return an available number. Return -1 if none is available. :rtype: int'
def get(self):
if (self.__curr == len(self.__numbers)): return (-1) number = self.__numbers[self.__curr] self.__curr += 1 self.__used[number] = True return number
'Check if a number is available or not. :type number: int :rtype: bool'
def check(self, number):
return ((0 <= number < len(self.__numbers)) and (not self.__used[number]))
'Recycle or release a number. :type number: int :rtype: void'
def release(self, number):
if ((not (0 <= number < len(self.__numbers))) or (not self.__used[number])): return self.__used[number] = False self.__curr -= 1 self.__numbers[self.__curr] = number
':type boxes: List[int] :rtype: int'
def removeBoxes(self, boxes):
def dfs(boxes, l, r, k, lookup): if (l > r): return 0 if lookup[l][r][k]: return lookup[l][r][k] (ll, kk) = (l, k) while ((l < r) and (boxes[(l + 1)] == boxes[l])): l += 1 k += 1 result = (dfs(boxes, (l + 1), r, 0, lookup) + ((k...
'Initialize your data structure here. :type n: int'
def __init__(self, n):
self.__rows = [[0, 0] for _ in xrange(n)] self.__cols = [[0, 0] for _ in xrange(n)] self.__diagonal = [0, 0] self.__anti_diagonal = [0, 0]
'Player {player} makes a move at ({row}, {col}). @param row The row of the board. @param col The column of the board. @param player The player, can be either 1 or 2. @return The current winning condition, can be either: 0: No one wins. 1: Player 1 wins. 2: Player 2 wins. :type row: int :type col: int :type player: int ...
def move(self, row, col, player):
i = (player - 1) self.__rows[row][i] += 1 self.__cols[col][i] += 1 if (row == col): self.__diagonal[i] += 1 if (col == ((len(self.__rows) - row) - 1)): self.__anti_diagonal[i] += 1 if any([(self.__rows[row][i] == len(self.__rows)), (self.__cols[col][i] == len(self.__cols)), (self...
':type nums: List[int] :rtype: bool'
def canPartition(self, nums):
s = sum(nums) if (s % 2): return False dp = ([False] * ((s / 2) + 1)) dp[0] = True for num in nums: for i in xrange(1, len(dp)): if (num <= i): dp[i] = (dp[i] or dp[(i - num)]) return dp[(-1)]
':type preorder: str :rtype: bool'
def isValidSerialization(self, preorder):
def split_iter(s, tok): start = 0 for i in xrange(len(s)): if (s[i] == tok): (yield s[start:i]) start = (i + 1) (yield s[start:]) if (not preorder): return False (depth, cnt) = (0, (preorder.count(',') + 1)) for tok in split_ite...
':type nums: List[int] :rtype: int'
def maxCoins(self, nums):
coins = (([1] + [i for i in nums if (i > 0)]) + [1]) n = len(coins) max_coins = [[0 for _ in xrange(n)] for _ in xrange(n)] for k in xrange(2, n): for left in xrange((n - k)): right = (left + k) for i in xrange((left + 1), right): max_coins[left][right] = ...
':type list1: List[str] :type list2: List[str] :rtype: List[str]'
def findRestaurant(self, list1, list2):
lookup = {} for (i, s) in enumerate(list1): lookup[s] = i result = [] min_sum = float('inf') for (j, s) in enumerate(list2): if (j > min_sum): break if (s in lookup): if ((j + lookup[s]) < min_sum): result = [s] min_sum ...
':type arrays: List[List[int]] :rtype: int'
def maxDistance(self, arrays):
(result, min_val, max_val) = (0, arrays[0][0], arrays[0][(-1)]) for i in xrange(1, len(arrays)): result = max(result, max((max_val - arrays[i][0]), (arrays[i][(-1)] - min_val))) min_val = min(min_val, arrays[i][0]) max_val = max(max_val, arrays[i][(-1)]) return result
':type citations: List[int] :rtype: int'
def hIndex(self, citations):
n = len(citations) (left, right) = (0, (n - 1)) while (left <= right): mid = ((left + right) / 2) if (citations[mid] >= (n - mid)): right = (mid - 1) else: left = (mid + 1) return (n - left)
':type rooms: List[List[int]] :rtype: void Do not return anything, modify rooms in-place instead.'
def wallsAndGates(self, rooms):
INF = 2147483647 q = deque([(i, j) for (i, row) in enumerate(rooms) for (j, r) in enumerate(row) if (not r)]) while q: (i, j) = q.popleft() for (I, J) in (((i + 1), j), ((i - 1), j), (i, (j + 1)), (i, (j - 1))): if ((0 <= I < len(rooms)) and (0 <= J < len(rooms[0])) and (rooms[I]...
':type target: str :type dictionary: List[str] :rtype: str'
def minAbbreviation(self, target, dictionary):
def bits_len(target, bits): return sum(((((bits >> i) & 3) == 0) for i in xrange((len(target) - 1)))) diffs = [] for word in dictionary: if (len(word) != len(target)): continue diffs.append(sum(((2 ** i) for (i, c) in enumerate(word) if (target[i] != c)))) if (not dif...
':type input: str :rtype: int'
def lengthLongestPath(self, input):
def split_iter(s, tok): start = 0 for i in xrange(len(s)): if (s[i] == tok): (yield s[start:i]) start = (i + 1) (yield s[start:]) max_len = 0 path_len = {0: 0} for line in split_iter(input, '\n'): name = line.lstrip(' DCTB ') ...
':type root: TreeNode :rtype: List[int]'
def largestValues(self, root):
def largestValuesHelper(root, depth, result): if (not root): return if (depth == len(result)): result.append(root.val) else: result[depth] = max(result[depth], root.val) largestValuesHelper(root.left, (depth + 1), result) largestValuesHelpe...
':type root: TreeNode :rtype: List[int]'
def largestValues(self, root):
result = [] curr = [root] while any(curr): result.append(max((node.val for node in curr))) curr = [child for node in curr for child in (node.left, node.right) if child] return result
':type image: List[List[str]] :type x: int :type y: int :rtype: int'
def minArea(self, image, x, y):
def binarySearch(left, right, find, image, has_one): while (left <= right): mid = (left + ((right - left) / 2)) if find(image, has_one, mid): right = (mid - 1) else: left = (mid + 1) return left searchColumns = (lambda image, ha...
':type digits: List[int] :rtype: List[int]'
def plusOne2(self, digits):
digits = [str(x) for x in digits] num = (int(''.join(digits)) + 1) return [int(x) for x in str(num)]
':type s: str :rtype: str'
def originalDigits(self, s):
cnts = [Counter(_) for _ in ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']] order = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9] unique_chars = ['z', 'o', 'w', 't', 'u', 'f', 'x', 's', 'g', 'n'] cnt = Counter(list(s)) res = [] for i in order: while (cnt[unique_chars[i...
':type n: int :rtype: int'
def firstBadVersion(self, n):
(left, right) = (1, n) while (left <= right): mid = (left + ((right - left) / 2)) if isBadVersion(mid): right = (mid - 1) else: left = (mid + 1) return left
':type board: List[List[int]] :rtype: void Do not return anything, modify board in-place instead.'
def gameOfLife(self, board):
m = len(board) n = (len(board[0]) if m else 0) for i in xrange(m): for j in xrange(n): count = 0 for I in xrange(max((i - 1), 0), min((i + 2), m)): for J in xrange(max((j - 1), 0), min((j + 2), n)): count += (board[I][J] & 1) if...
':type nums: List[int] :rtype: TreeNode'
def constructMaximumBinaryTree(self, nums):
nodeStack = [] for num in nums: node = TreeNode(num) while (nodeStack and (num > nodeStack[(-1)].val)): node.left = nodeStack[(-1)] nodeStack.pop() if nodeStack: nodeStack[(-1)].right = node nodeStack.append(node) return nodeStack[0]
'initialize your data structure here. :type matrix: List[List[int]]'
def __init__(self, matrix):
if (not matrix): return (m, n) = (len(matrix), len(matrix[0])) self.__sums = [[0 for _ in xrange((n + 1))] for _ in xrange((m + 1))] for i in xrange(1, (m + 1)): for j in xrange(1, (n + 1)): self.__sums[i][j] = (self.__sums[i][(j - 1)] + matrix[(i - 1)][(j - 1)]) for j in...
'sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :type row2: int :type col2: int :rtype: int'
def sumRegion(self, row1, col1, row2, col2):
return (((self.__sums[(row2 + 1)][(col2 + 1)] - self.__sums[(row2 + 1)][col1]) - self.__sums[row1][(col2 + 1)]) + self.__sums[row1][col1])
':type flights: List[List[int]] :type days: List[List[int]] :rtype: int'
def maxVacationDays(self, flights, days):
if ((not days) or (not flights)): return 0 dp = [([0] * len(days)) for _ in xrange(2)] for week in reversed(xrange(len(days[0]))): for cur_city in xrange(len(days)): dp[(week % 2)][cur_city] = (days[cur_city][week] + dp[((week + 1) % 2)][cur_city]) for dest_city in xr...
':type H: int :type W: str'
def __init__(self, H, W):
self.__exl = [[0 for _ in xrange(((ord(W) - ord('A')) + 1))] for _ in xrange((H + 1))] self.__fward = collections.defaultdict((lambda : collections.defaultdict(int))) self.__bward = collections.defaultdict(set)
':type r: int :type c: str :type v: int :rtype: void'
def set(self, r, c, v):
self.__reset_dependency(r, c) self.__update_others(r, c, v)
':type r: int :type c: str :rtype: int'
def get(self, r, c):
return self.__exl[r][(ord(c) - ord('A'))]
':type r: int :type c: str :type strs: List[str] :rtype: int'
def sum(self, r, c, strs):
self.__reset_dependency(r, c) result = self.__calc_and_update_dependency(r, c, strs) self.__update_others(r, c, result) return result
':type nums: List[int] :rtype: List[int]'
def findDisappearedNumbers(self, nums):
for i in xrange(len(nums)): if (nums[(abs(nums[i]) - 1)] > 0): nums[(abs(nums[i]) - 1)] *= (-1) result = [] for i in xrange(len(nums)): if (nums[i] > 0): result.append((i + 1)) else: nums[i] *= (-1) return result
':type nums: List[int] :rtype: List[int]'
def findDisappearedNumbers2(self, nums):
return list((set(range(1, (len(nums) + 1))) - set(nums)))
':type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.'
def sortColors(self, nums):
def triPartition(nums, target): (i, j, n) = (0, 0, (len(nums) - 1)) while (j <= n): if (nums[j] < target): (nums[i], nums[j]) = (nums[j], nums[i]) i += 1 j += 1 elif (nums[j] > target): (nums[j], nums[n]) = (nums...