desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
':type s: str :rtype: List[int]'
def findPermutation(self, s):
result = [] for i in xrange((len(s) + 1)): if ((i == len(s)) or (s[i] == 'I')): result += range((i + 1), len(result), (-1)) return result
':type s: str :rtype: int'
def longestPalindrome(self, s):
odds = 0 for (k, v) in collections.Counter(s).iteritems(): odds += (v & 1) return ((len(s) - odds) + int((odds > 0)))
':type s: str :rtype: int'
def longestPalindrome2(self, s):
odd = sum(map((lambda x: (x & 1)), collections.Counter(s).values())) return ((len(s) - odd) + int((odd > 0)))
':type num1: str :type num2: str :rtype: str'
def addStrings(self, num1, num2):
result = [] (i, j, carry) = ((len(num1) - 1), (len(num2) - 1), 0) while ((i >= 0) or (j >= 0) or carry): if (i >= 0): carry += (ord(num1[i]) - ord('0')) i -= 1 if (j >= 0): carry += (ord(num2[j]) - ord('0')) j -= 1 result.append(str((ca...
':type num1: str :type num2: str :rtype: str'
def addStrings2(self, num1, num2):
length = max(len(num1), len(num2)) num1 = num1.zfill(length)[::(-1)] num2 = num2.zfill(length)[::(-1)] (res, plus) = ('', 0) for (index, num) in enumerate(num1): tmp = str(((int(num) + int(num2[index])) + plus)) res += tmp[(-1)] if (int(tmp) > 9): plus = 1 ...
':type n: int :type primes: List[int] :rtype: int'
def nthSuperUglyNumber(self, n, primes):
(heap, uglies, idx, ugly_by_last_prime) = ([], ([0] * n), ([0] * len(primes)), ([0] * n)) uglies[0] = 1 for (k, p) in enumerate(primes): heapq.heappush(heap, (p, k)) for i in xrange(1, n): (uglies[i], k) = heapq.heappop(heap) ugly_by_last_prime[i] = k idx[k] += 1 ...
':type n: int :type primes: List[int] :rtype: int'
def nthSuperUglyNumber(self, n, primes):
(uglies, idx, heap, ugly_set) = (([0] * n), ([0] * len(primes)), [], set([1])) uglies[0] = 1 for (k, p) in enumerate(primes): heapq.heappush(heap, (p, k)) ugly_set.add(p) for i in xrange(1, n): (uglies[i], k) = heapq.heappop(heap) while ((primes[k] * uglies[idx[k]]) in ug...
':type n: int :type primes: List[int] :rtype: int'
def nthSuperUglyNumber(self, n, primes):
(uglies, idx, heap) = ([1], ([0] * len(primes)), []) for (k, p) in enumerate(primes): heapq.heappush(heap, (p, k)) for i in xrange(1, n): (min_val, k) = heap[0] uglies += [min_val] while (heap[0][0] == min_val): (min_val, k) = heapq.heappop(heap) idx[k...
':type n: int :type primes: List[int] :rtype: int'
def nthSuperUglyNumber(self, n, primes):
uglies = ([0] * n) uglies[0] = 1 ugly_by_prime = list(primes) idx = ([0] * len(primes)) for i in xrange(1, n): uglies[i] = min(ugly_by_prime) for k in xrange(len(primes)): if (uglies[i] == ugly_by_prime[k]): idx[k] += 1 ugly_by_prime[k] = (...
':type n: int :type primes: List[int] :rtype: int'
def nthSuperUglyNumber(self, n, primes):
ugly_number = 0 heap = [] heapq.heappush(heap, 1) for p in primes: heapq.heappush(heap, p) for _ in xrange(n): ugly_number = heapq.heappop(heap) for i in xrange(len(primes)): if ((ugly_number % primes[i]) == 0): for j in xrange((i + 1)): ...
':type s: str :rtype: str'
def reverseWords(self, s):
def reverse(s, begin, end): for i in xrange(((end - begin) // 2)): (s[(begin + i)], s[((end - 1) - i)]) = (s[((end - 1) - i)], s[(begin + i)]) (s, i) = (list(s), 0) for j in xrange((len(s) + 1)): if ((j == len(s)) or (s[j] == ' ')): reverse(s, i, j) i =...
':type grid: List[List[int]] :rtype: int'
def islandPerimeter(self, grid):
(count, repeat) = (0, 0) for i in xrange(len(grid)): for j in xrange(len(grid[i])): if (grid[i][j] == 1): count += 1 if ((i != 0) and (grid[(i - 1)][j] == 1)): repeat += 1 if ((j != 0) and (grid[i][(j - 1)] == 1)): ...
':type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.'
def wiggleSort(self, nums):
nums.sort() med = ((len(nums) - 1) / 2) (nums[::2], nums[1::2]) = (nums[med::(-1)], nums[:med:(-1)])
':type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.'
def wiggleSort(self, nums):
def findKthLargest(nums, k): (left, right) = (0, (len(nums) - 1)) while (left <= right): pivot_idx = randint(left, right) new_pivot_idx = partitionAroundPivot(left, right, pivot_idx, nums) if (new_pivot_idx == (k - 1)): return nums[new_pivot_idx] ...
':type nums: List[int] :rtype: int'
def reversePairs(self, nums):
def merge(nums, start, mid, end): r = (mid + 1) tmp = [] for i in xrange(start, (mid + 1)): while ((r <= end) and (nums[i] > nums[r])): tmp.append(nums[r]) r += 1 tmp.append(nums[i]) nums[start:(start + len(tmp))] = tmp def ...
':type nums: List[int] :rtype: int'
def findDuplicate(self, nums):
slow = nums[0] fast = nums[nums[0]] while (slow != fast): slow = nums[slow] fast = nums[nums[fast]] fast = 0 while (slow != fast): slow = nums[slow] fast = nums[fast] return slow
':type nums: List[int] :rtype: int'
def findDuplicate(self, nums):
(left, right) = (1, (len(nums) - 1)) while (left <= right): mid = (left + ((right - left) / 2)) count = 0 for num in nums: if (num <= mid): count += 1 if (count > mid): right = (mid - 1) else: left = (mid + 1) return...
':type nums: List[int] :rtype: int'
def findDuplicate(self, nums):
duplicate = 0 for num in nums: if (nums[(abs(num) - 1)] > 0): nums[(abs(num) - 1)] *= (-1) else: duplicate = abs(num) break for num in nums: if (nums[(abs(num) - 1)] < 0): nums[(abs(num) - 1)] *= (-1) else: break ...
':type n: int :rtype: str'
def findContestMatch(self, n):
matches = map(str, range(1, (n + 1))) while (len(matches) / 2): matches = ['({},{})'.format(matches[i], matches[((- i) - 1)]) for i in xrange((len(matches) / 2))] return matches[0]
':type matrix: List[List[int]] :type target: int :rtype: bool'
def searchMatrix(self, matrix, target):
if (not matrix): return False (m, n) = (len(matrix), len(matrix[0])) (left, right) = (0, (m * n)) while (left < right): mid = (left + ((right - left) / 2)) if (matrix[(mid / n)][(mid % n)] >= target): right = mid else: left = (mid + 1) return (...
':type nums: List[int] :rtype: int'
def maxSubArray(self, nums):
if (max(nums) < 0): return max(nums) (global_max, local_max) = (float('-inf'), 0) for x in nums: local_max = max(0, (local_max + x)) global_max = max(global_max, local_max) return global_max
':type nums: List[int] :rtype: List[List[int]]'
def threeSum(self, nums):
(nums, result, i) = (sorted(nums), [], 0) while (i < (len(nums) - 2)): if ((i == 0) or (nums[i] != nums[(i - 1)])): (j, k) = ((i + 1), (len(nums) - 1)) while (j < k): if (((nums[i] + nums[j]) + nums[k]) < 0): j += 1 elif (((nums...
':type nums: List[int] :rtype: List[List[int]]'
def threeSum2(self, nums):
d = collections.Counter(nums) nums_2 = [x[0] for x in d.items() if (x[1] > 1)] nums_new = sorted([x[0] for x in d.items()]) rtn = ([[0, 0, 0]] if (d[0] >= 3) else []) for (i, j) in enumerate(nums_new): if (j <= 0): numss2 = nums_new[(i + 1):] for (x, y) in enumerate(n...
'Initialize your q structure here. :type v1: List[int] :type v2: List[int]'
def __init__(self, v1, v2):
self.q = collections.deque([(len(v), iter(v)) for v in (v1, v2) if v])
':rtype: int'
def next(self):
(len, iter) = self.q.popleft() if (len > 1): self.q.append(((len - 1), iter)) return next(iter)
':rtype: bool'
def hasNext(self):
return bool(self.q)
':type nums: List[int] :rtype: int'
def triangleNumber(self, nums):
result = 0 nums.sort() for i in xrange((len(nums) - 2)): if (nums[i] == 0): continue k = (i + 2) for j in xrange((i + 1), (len(nums) - 1)): while ((k < len(nums)) and ((nums[i] + nums[j]) > nums[k])): k += 1 result += ((k - j) - 1) ...
':type matrix: List[List[int]] :rtype: List[List[int]]'
def pacificAtlantic(self, matrix):
(PACIFIC, ATLANTIC) = (1, 2) def pacificAtlanticHelper(matrix, x, y, prev_height, prev_val, visited, res): if ((not (0 <= x < len(matrix))) or (not (0 <= y < len(matrix[0]))) or (matrix[x][y] < prev_height) or ((visited[x][y] | prev_val) == visited[x][y])): return visited[x][y] |= pr...
':type pairs: List[List[int]] :rtype: int'
def findLongestChain(self, pairs):
pairs.sort(key=(lambda x: x[1])) (cnt, i) = (0, 0) for j in xrange(len(pairs)): if ((j == 0) or (pairs[i][1] < pairs[j][0])): cnt += 1 i = j return cnt
':type head: ListNode :rtype: ListNode'
def deleteDuplicates(self, head):
cur = head while cur: runner = cur.next while (runner and (runner.val == cur.val)): runner = runner.next cur.next = runner cur = runner return head
':type head: ListNode :rtype: ListNode'
def deleteDuplicates2(self, head):
if (not head): return head if head.next: if (head.val == head.next.val): head = self.deleteDuplicates(head.next) else: head.next = self.deleteDuplicates(head.next) return head
':type people: List[List[int]] :rtype: List[List[int]]'
def reconstructQueue(self, people):
people.sort(key=(lambda (h, k): ((- h), k))) blocks = [[]] for p in people: index = p[1] for (i, block) in enumerate(blocks): if (index <= len(block)): break index -= len(block) block.insert(index, p) if ((len(block) * len(block)) > len...
':type people: List[List[int]] :rtype: List[List[int]]'
def reconstructQueue(self, people):
people.sort(key=(lambda (h, k): ((- h), k))) result = [] for p in people: result.insert(p[1], p) return result
':type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.'
def moveZeroes(self, nums):
pos = 0 for i in xrange(len(nums)): if nums[i]: (nums[i], nums[pos]) = (nums[pos], nums[i]) pos += 1
':type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.'
def moveZeroes2(self, nums):
nums.sort(cmp=(lambda a, b: (0 if b else (-1))))
':type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.'
def moveZeroes(self, nums):
pos = 0 for i in xrange(len(nums)): if nums[i]: nums[pos] = nums[i] pos += 1 for i in xrange(pos, len(nums)): nums[i] = 0
':type nums: List[int] :type k: int :rtype: float'
def findMaxAverage(self, nums, k):
def getDelta(avg, nums, k): accu = ([0.0] * (len(nums) + 1)) minval_pos = None delta = 0.0 for i in xrange(len(nums)): accu[(i + 1)] = ((nums[i] + accu[i]) - avg) if (i >= (k - 1)): if ((minval_pos == None) or (accu[((i - k) + 1)] < accu[minval...
':type nums: List[int] :rtype: List[List[int]]'
def subsets(self, nums):
nums.sort() result = [[]] for i in xrange(len(nums)): size = len(result) for j in xrange(size): result.append(list(result[j])) result[(-1)].append(nums[i]) return result
':type nums: List[int] :rtype: List[List[int]]'
def subsets(self, nums):
result = [] (i, count) = (0, (1 << len(nums))) nums.sort() while (i < count): cur = [] for j in xrange(len(nums)): if (i & (1 << j)): cur.append(nums[j]) result.append(cur) i += 1 return result
':type nums: List[int] :rtype: List[List[int]]'
def subsets(self, nums):
return self.subsetsRecu([], sorted(nums))
':type A: List[int] :rtype: int'
def numberOfArithmeticSlices(self, A):
(res, i) = (0, 0) while ((i + 2) < len(A)): start = i while (((i + 2) < len(A)) and ((A[(i + 2)] + A[i]) == (2 * A[(i + 1)]))): res += ((i - start) + 1) i += 1 i += 1 return res
':type head: ListNode :type k: int :rtype: ListNode'
def rotateRight(self, head, k):
if ((not head) or (not head.next)): return head (n, cur) = (1, head) while cur.next: cur = cur.next n += 1 cur.next = head (cur, tail) = (head, cur) for _ in xrange((n - (k % n))): tail = cur cur = cur.next tail.next = None return cur
':type s: str :rtype: TreeNode'
def str2tree(self, s):
def str2treeHelper(s, i): start = i if (s[i] == '-'): i += 1 while ((i < len(s)) and s[i].isdigit()): i += 1 node = TreeNode(int(s[start:i])) if ((i < len(s)) and (s[i] == '(')): i += 1 (node.left, i) = str2treeHelper(s, i) ...
':type root: TreeNode :type k: int :rtype: bool'
def findTarget(self, root, k):
class BSTIterator(object, ): def __init__(self, root, forward): self.__node = root self.__forward = forward self.__s = [] self.__cur = None self.next() def val(self): return self.__cur def next(self): while (...
':type nums: List[int] :rtype: int'
def wiggleMaxLength(self, nums):
if (len(nums) < 2): return len(nums) (length, up) = (1, None) for i in xrange(1, len(nums)): if ((nums[(i - 1)] < nums[i]) and ((up is None) or (up is False))): length += 1 up = True elif ((nums[(i - 1)] > nums[i]) and ((up is None) or (up is True))): ...
':type word: str :rtype: List[str]'
def generateAbbreviations(self, word):
def generateAbbreviationsHelper(word, i, cur, res): if (i == len(word)): res.append(''.join(cur)) return cur.append(word[i]) generateAbbreviationsHelper(word, (i + 1), cur, res) cur.pop() if ((not cur) or (not cur[(-1)][(-1)].isdigit())): f...
':type n: int :rtype: int'
def countPrimes2(self, n):
if (n < 3): return 0 primes = ([True] * n) primes[0] = primes[1] = False for i in range(2, (int((n ** 0.5)) + 1)): if primes[i]: primes[(i * i):n:i] = ([False] * len(primes[(i * i):n:i])) return sum(primes)
':type nums: List[int] :rtype: int'
def findMaxLength(self, nums):
(result, count) = (0, 0) lookup = {0: (-1)} for (i, num) in enumerate(nums): count += (1 if (num == 1) else (-1)) if (count in lookup): result = max(result, (i - lookup[count])) else: lookup[count] = i return result
':type nums: List[int] :type target: int :rtype: List[List[int]]'
def fourSum(self, nums, target):
nums.sort() res = [] for i in xrange((len(nums) - 3)): if (i and (nums[i] == nums[(i - 1)])): continue for j in xrange((i + 1), (len(nums) - 2)): if ((j != (i + 1)) and (nums[j] == nums[(j - 1)])): continue sum = ((target - nums[i]) - nums[...
':type nums: List[int] :type target: int :rtype: List[List[int]]'
def fourSum(self, nums, target):
(nums, result, lookup) = (sorted(nums), [], collections.defaultdict(list)) for i in xrange(0, (len(nums) - 1)): for j in xrange((i + 1), len(nums)): is_duplicated = False for [x, y] in lookup[(nums[i] + nums[j])]: if (nums[x] == nums[i]): is_du...
':type nums: List[int] :type target: int :rtype: List[List[int]]'
def fourSum(self, nums, target):
(nums, result, lookup) = (sorted(nums), [], collections.defaultdict(list)) for i in xrange(0, (len(nums) - 1)): for j in xrange((i + 1), len(nums)): lookup[(nums[i] + nums[j])].append([i, j]) for i in lookup.keys(): if ((target - i) in lookup): for x in lookup[i]: ...
':type nums: List[int] :type k: int :rtype: bool'
def checkSubarraySum(self, nums, k):
count = 0 lookup = {0: (-1)} for (i, num) in enumerate(nums): count += num if k: count %= k if (count in lookup): if ((i - lookup[count]) > 1): return True else: lookup[count] = i return False
':type strs: List[str] :type m: int :type n: int :rtype: int'
def findMaxForm(self, strs, m, n):
dp = [[0 for _ in xrange((n + 1))] for _ in xrange((m + 1))] for s in strs: (zero_count, one_count) = (0, 0) for c in s: if (c == '0'): zero_count += 1 elif (c == '1'): one_count += 1 for i in reversed(xrange(zero_count, (m + 1))): ...
':type timePoints: List[str] :rtype: int'
def findMinDifference(self, timePoints):
minutes = map((lambda x: ((int(x[:2]) * 60) + int(x[3:]))), timePoints) minutes.sort() return min((((y - x) % (24 * 60)) for (x, y) in zip(minutes, (minutes[1:] + minutes[:1]))))
':type maze: List[List[int]] :type ball: List[int] :type hole: List[int] :rtype: str'
def findShortestWay(self, maze, ball, hole):
(ball, hole) = (tuple(ball), tuple(hole)) dirs = {'u': ((-1), 0), 'r': (0, 1), 'l': (0, (-1)), 'd': (1, 0)} def neighbors(maze, node): for (dir, vec) in dirs.iteritems(): (cur_node, dist) = (list(node), 0) while ((0 <= (cur_node[0] + vec[0]) < len(maze)) and (0 <= (cur_node[1...
':type n: int :rtype: int'
def integerBreak(self, n):
if (n < 4): return (n - 1) res = 0 if ((n % 3) == 0): res = (3 ** (n // 3)) elif ((n % 3) == 2): res = ((3 ** (n // 3)) * 2) else: res = ((3 ** ((n // 3) - 1)) * 4) return res
':type n: int :rtype: int'
def integerBreak(self, n):
if (n < 4): return (n - 1) res = [0, 1, 2, 3] for i in xrange(4, (n + 1)): res[(i % 4)] = max((res[((i - 2) % 4)] * 2), (res[((i - 3) % 4)] * 3)) return res[(n % 4)]
':type nums: List[List[int]] :rtype: List[int]'
def smallestRange(self, nums):
(left, right) = (float('inf'), float('-inf')) min_heap = [] for row in nums: left = min(left, row[0]) right = max(right, row[0]) it = iter(row) heapq.heappush(min_heap, (next(it, None), it)) result = (left, right) while min_heap: (val, it) = heapq.heappop(min_...
':type machines: List[int] :rtype: int'
def findMinMoves(self, machines):
total = sum(machines) if (total % len(machines)): return (-1) (result, target, curr) = (0, (total / len(machines)), 0) for n in machines: curr += (n - target) result = max(result, max((n - target), abs(curr))) return result
':type x: int :type y: int :type z: int :rtype: bool'
def canMeasureWater(self, x, y, z):
return ((z == 0) or (((x + y) >= z) and ((z % gcd(x, y)) == 0)))
':type num: int :rtype: str'
def toHex(self, num):
if (not num): return '0' result = [] while (num and (len(result) != 8)): h = (num & 15) if (h < 10): result.append(str(chr((ord('0') + h)))) else: result.append(str(chr(((ord('a') + h) - 10)))) num >>= 4 result.reverse() return ''.join(...
':type n: int :rtype: int'
def findNthDigit(self, n):
digit_len = 1 while (n > ((digit_len * 9) * (10 ** (digit_len - 1)))): n -= ((digit_len * 9) * (10 ** (digit_len - 1))) digit_len += 1 num = ((10 ** (digit_len - 1)) + ((n - 1) / digit_len)) nth_digit = (num / (10 ** ((digit_len - 1) - ((n - 1) % digit_len)))) nth_digit %= 10 ret...
':type nums: List[int] :rtype: int'
def findMaximumXOR(self, nums):
result = 0 for i in reversed(xrange(32)): result <<= 1 prefixes = set() for n in nums: prefixes.add((n >> i)) for p in prefixes: if (((result | 1) ^ p) in prefixes): result += 1 break return result
':type nums: List[int] :type a: int :type b: int :type c: int :rtype: List[int]'
def sortTransformedArray(self, nums, a, b, c):
f = (lambda x, a, b, c: ((((a * x) * x) + (b * x)) + c)) result = [] if (not nums): return result (left, right) = (0, (len(nums) - 1)) d = ((-1) if (a > 0) else 1) while (left <= right): if ((d * f(nums[left], a, b, c)) < (d * f(nums[right], a, b, c))): result.append(...
':type root: TreeNode :type sum: int :rtype: int'
def pathSum(self, root, sum):
def pathSumHelper(root, curr, sum, lookup): if (root is None): return 0 curr += root.val result = (lookup[(curr - sum)] if ((curr - sum) in lookup) else 0) lookup[curr] += 1 result += (pathSumHelper(root.left, curr, sum, lookup) + pathSumHelper(root.right, curr, s...
':type root: TreeNode :type sum: int :rtype: int'
def pathSum(self, root, sum):
def pathSumHelper(root, prev, sum): if (root is None): return 0 curr = (prev + root.val) return ((int((curr == sum)) + pathSumHelper(root.left, curr, sum)) + pathSumHelper(root.right, curr, sum)) if (root is None): return 0 return ((pathSumHelper(root, 0, sum) + s...
':type s: str :type k: int :rtype: str'
def reverseStr(self, s, k):
s = list(s) for i in xrange(0, len(s), (2 * k)): s[i:(i + k)] = reversed(s[i:(i + k)]) return ''.join(s)
':type words: List[str] :rtype: int'
def maxProduct(self, words):
def counting_sort(words): k = 1000 buckets = [[] for _ in xrange(k)] for word in words: buckets[len(word)].append(word) res = [] for i in reversed(xrange(k)): if buckets[i]: res += buckets[i] return res words = counting_sort...
':type words: List[str] :rtype: int'
def maxProduct(self, words):
words.sort(key=(lambda x: len(x)), reverse=True) bits = ([0] * len(words)) for (i, word) in enumerate(words): for c in word: bits[i] |= (1 << (ord(c) - ord('a'))) max_product = 0 for i in xrange((len(words) - 1)): if ((len(words[i]) ** 2) <= max_product): brea...
':type strs: List[str] :rtype: int'
def findLUSlength(self, strs):
def isSubsequence(a, b): i = 0 for j in xrange(len(b)): if (i >= len(a)): break if (a[i] == b[j]): i += 1 return (i == len(a)) strs.sort(key=len, reverse=True) for i in xrange(len(strs)): all_of = True for j in x...
':type dict: List[str] :rtype: List[str]'
def wordsAbbreviation(self, dict):
def isUnique(prefix, words): return (sum((word.startswith(prefix) for word in words)) == 1) def toAbbr(prefix, word): abbr = ((prefix + str(((len(word) - 1) - len(prefix)))) + word[(-1)]) return (abbr if (len(abbr) < len(word)) else word) abbr_to_word = collections.defaultdict(set) ...
':type A: List[int] :rtype: int'
def numberOfArithmeticSlices(self, A):
result = 0 dp = [collections.defaultdict(int) for i in xrange(len(A))] for i in xrange(1, len(A)): for j in xrange(i): diff = (A[i] - A[j]) dp[i][diff] += 1 if (diff in dp[j]): dp[i][diff] += dp[j][diff] result += dp[j][diff] re...
':type nums1: List[int] :type nums2: List[int] :rtype: float'
def findMedianSortedArrays(self, nums1, nums2):
(len1, len2) = (len(nums1), len(nums2)) if (((len1 + len2) % 2) == 1): return self.getKth(nums1, nums2, (((len1 + len2) / 2) + 1)) else: return ((self.getKth(nums1, nums2, ((len1 + len2) / 2)) + self.getKth(nums1, nums2, (((len1 + len2) / 2) + 1))) * 0.5)
':type nums1: List[int] :type nums2: List[int] :rtype: float'
def findMedianSortedArrays(self, nums1, nums2):
(len1, len2) = (len(nums1), len(nums2)) if (((len1 + len2) % 2) == 1): return self.getKth([nums1, nums2], (((len1 + len2) / 2) + 1)) else: return ((self.getKth([nums1, nums2], ((len1 + len2) / 2)) + self.getKth([nums1, nums2], (((len1 + len2) / 2) + 1))) * 0.5)
':type num: int :rtype: int'
def findIntegers(self, num):
dp = ([0] * 32) (dp[0], dp[1]) = (1, 2) for i in xrange(2, len(dp)): dp[i] = (dp[(i - 1)] + dp[(i - 2)]) (result, prev_bit) = (0, 0) for i in reversed(xrange(31)): if ((num & (1 << i)) != 0): result += dp[i] if (prev_bit == 1): result -= 1 ...
':type nums: List[int] :rtype: str'
def optimalDivision(self, nums):
if (len(nums) == 1): return str(nums[0]) if (len(nums) == 2): return ((str(nums[0]) + '/') + str(nums[1])) result = [((str(nums[0]) + '/(') + str(nums[1]))] for i in xrange(2, len(nums)): result += ('/' + str(nums[i])) result += ')' return ''.join(result)
':type n: str :rtype: str'
def smallestGoodBase(self, n):
num = int(n) max_len = int(math.log(num, 2)) for l in xrange(max_len, 1, (-1)): b = int((num ** (l ** (-1)))) if ((((b ** (l + 1)) - 1) // (b - 1)) == num): return str(b) return str((num - 1))
':type s1: str :type n1: int :type s2: str :type n2: int :rtype: int'
def getMaxRepetitions(self, s1, n1, s2, n2):
repeat_count = ([0] * (len(s2) + 1)) lookup = {} (j, count) = (0, 0) for k in xrange(1, (n1 + 1)): for i in xrange(len(s1)): if (s1[i] == s2[j]): j = ((j + 1) % len(s2)) count += (j == 0) if (j in lookup): i = lookup[j] ...
':type l1: ListNode :type l2: ListNode :rtype: ListNode'
def mergeTwoLists(self, 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 l2) return dummy.next
':type pid: List[int] :type ppid: List[int] :type kill: int :rtype: List[int]'
def killProcess(self, pid, ppid, kill):
def killAll(pid, children, killed): killed.append(pid) for child in children[pid]: killAll(child, children, killed) result = [] children = collections.defaultdict(set) for i in xrange(len(pid)): children[ppid[i]].add(pid[i]) killAll(kill, children, result) ret...
':type pid: List[int] :type ppid: List[int] :type kill: int :rtype: List[int]'
def killProcess(self, pid, ppid, kill):
def killAll(pid, children, killed): killed.append(pid) for child in children[pid]: killAll(child, children, killed) result = [] children = collections.defaultdict(set) for i in xrange(len(pid)): children[ppid[i]].add(pid[i]) q = collections.deque() q.append(ki...
':type nums: List[int] :rtype: List[str]'
def findRelativeRanks(self, nums):
sorted_nums = sorted(nums)[::(-1)] ranks = (['Gold Medal', 'Silver Medal', 'Bronze Medal'] + map(str, range(4, (len(nums) + 1)))) return map(dict(zip(sorted_nums, ranks)).get, nums)
':type org: List[int] :type seqs: List[List[int]] :rtype: bool'
def sequenceReconstruction(self, org, seqs):
if (not seqs): return False pos = ([0] * (len(org) + 1)) for i in xrange(len(org)): pos[org[i]] = i is_matched = ([False] * (len(org) + 1)) cnt_to_match = (len(org) - 1) for seq in seqs: for i in xrange(len(seq)): if (not (0 < seq[i] <= len(org))): ...
':type org: List[int] :type seqs: List[List[int]] :rtype: bool'
def sequenceReconstruction(self, org, seqs):
graph = collections.defaultdict(set) indegree = collections.defaultdict(int) integer_set = set() for seq in seqs: for i in seq: integer_set.add(i) if (len(seq) == 1): if (seq[0] not in indegree): indegree[seq[0]] = 0 continue fo...
':type s: str :rtype: int'
def numDecodings(self, s):
(M, W) = (1000000007, 3) dp = ([0] * W) dp[0] = 1 dp[1] = (9 if (s[0] == '*') else (dp[0] if (s[0] != '0') else 0)) for i in xrange(1, len(s)): if (s[i] == '*'): dp[((i + 1) % W)] = (9 * dp[(i % W)]) if (s[(i - 1)] == '1'): dp[((i + 1) % W)] = ((dp[((i...
':type root: TreeNode :rtype: int'
def findTilt(self, root):
def postOrderTraverse(root, tilt): if (not root): return (0, tilt) (left, tilt) = postOrderTraverse(root.left, tilt) (right, tilt) = postOrderTraverse(root.right, tilt) tilt += abs((left - right)) return (((left + right) + root.val), tilt) return postOrderTrav...
':type intervals: List[Interval] :rtype: int'
def eraseOverlapIntervals(self, intervals):
intervals.sort(key=(lambda interval: interval.start)) (result, prev) = (0, 0) for i in xrange(1, len(intervals)): if (intervals[i].start < intervals[prev].end): if (intervals[i].end < intervals[prev].end): prev = i result += 1 else: prev = ...
'Initialize your data structure here.'
def __init__(self):
self.__set = [] self.__used = {}
'Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: int :rtype: bool'
def insert(self, val):
if (val in self.__used): return False self.__set += (val,) self.__used[val] = (len(self.__set) - 1) return True
'Removes a value from the set. Returns true if the set contained the specified element. :type val: int :rtype: bool'
def remove(self, val):
if (val not in self.__used): return False self.__used[self.__set[(-1)]] = self.__used[val] (self.__set[self.__used[val]], self.__set[(-1)]) = (self.__set[(-1)], self.__set[self.__used[val]]) self.__used.pop(val) self.__set.pop() return True
'Get a random element from the set. :rtype: int'
def getRandom(self):
return self.__set[randint(0, (len(self.__set) - 1))]
':type nums: List[int] :rtype: int'
def findPeakElement(self, nums):
(left, right) = (0, (len(nums) - 1)) while (left < right): mid = (left + ((right - left) / 2)) if (((mid == 0) or (nums[(mid - 1)] < nums[mid])) and (((mid + 1) == len(nums)) or (nums[mid] > nums[(mid + 1)]))): return mid elif (not ((mid == 0) or (nums[(mid - 1)] < nums[mid])...
':type s: str :rtype: bool'
def canPermutePalindrome(self, s):
return (sum(((v % 2) for v in collections.Counter(s).values())) < 2)
':type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.'
def rotate2(self, nums, k):
nums[:] = (nums[(len(nums) - k):] + nums[:(len(nums) - k)])
':type root: TreeNode :rtype: int'
def sumOfLeftLeaves(self, root):
def sumOfLeftLeavesHelper(root, is_left): if (not root): return 0 if ((not root.left) and (not root.right)): return (root.val if is_left else 0) return (sumOfLeftLeavesHelper(root.left, True) + sumOfLeftLeavesHelper(root.right, False)) return sumOfLeftLeavesHelper...
':type root: TreeNode :rtype: int'
def longestConsecutive(self, root):
self.max_len = 0 def longestConsecutiveHelper(root): if (not root): return 0 left_len = longestConsecutiveHelper(root.left) right_len = longestConsecutiveHelper(root.right) cur_len = 1 if (root.left and (root.left.val == (root.val + 1))): cur_len =...
':type n: int :rtype: int'
def numTrees(self, n):
if (n == 0): return 1 def combination(n, k): count = 1 for i in xrange(1, (k + 1)): count = ((count * ((n - i) + 1)) / i) return count return (combination((2 * n), n) - combination((2 * n), (n - 1)))
':type nums: List[int] :type n: int :rtype: int'
def minPatches(self, nums, n):
(patch, miss, i) = (0, 1, 0) while (miss <= n): if ((i < len(nums)) and (nums[i] <= miss)): miss += nums[i] i += 1 else: miss += miss patch += 1 return patch
':type nums: List[int] :rtype: bool'
def increasingTriplet(self, nums):
(min_num, a, b) = (float('inf'), float('inf'), float('inf')) for c in nums: if (min_num >= c): min_num = c elif (b >= c): (a, b) = (min_num, c) else: return True return False
':type nums: List[int] :rtype: bool'
def increasingTriplet(self, nums):
def increasingKUplet(nums, k): inc = ([float('inf')] * (k - 1)) for num in nums: i = bisect.bisect_left(inc, num) if (i >= (k - 1)): return True inc[i] = num return (k == 0) return increasingKUplet(nums, 3)