desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Initialize your data structure here.
:type iterator: Iterator'
| def __init__(self, iterator):
| self.iterator = iterator
self.val_ = None
self.has_next_ = iterator.hasNext()
self.has_peeked_ = False
|
'Returns the next element in the iteration without advancing the iterator.
:rtype: int'
| def peek(self):
| if (not self.has_peeked_):
self.has_peeked_ = True
self.val_ = self.iterator.next()
return self.val_
|
':rtype: int'
| def next(self):
| self.val_ = self.peek()
self.has_peeked_ = False
self.has_next_ = self.iterator.hasNext()
return self.val_
|
':rtype: bool'
| def hasNext(self):
| return self.has_next_
|
':type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.'
| def wiggleSort(self, nums):
| for i in xrange(1, len(nums)):
if (((i % 2) and (nums[(i - 1)] > nums[i])) or ((not (i % 2)) and (nums[(i - 1)] < nums[i]))):
(nums[(i - 1)], nums[i]) = (nums[i], nums[(i - 1)])
|
':type matrix: List[List[str]]
:rtype: int'
| def maximalRectangle(self, matrix):
| def largestRectangleArea(heights):
(increasing, area, i) = ([], 0, 0)
while (i <= len(heights)):
if ((not increasing) or ((i < len(heights)) and (heights[i] > heights[increasing[(-1)]]))):
increasing.append(i)
i += 1
else:
last ... |
':type matrix: List[List[str]]
:rtype: int'
| def maximalRectangle(self, matrix):
| if (not matrix):
return 0
result = 0
m = len(matrix)
n = len(matrix[0])
L = [0 for _ in xrange(n)]
H = [0 for _ in xrange(n)]
R = [n for _ in xrange(n)]
for i in xrange(m):
left = 0
for j in xrange(n):
if (matrix[i][j] == '1'):
L[j] = m... |
':type nums1: List[int]
:type nums2: List[int]
:type k: int
:rtype: List[int]'
| def maxNumber(self, nums1, nums2, k):
| def get_max_digits(nums, start, end, max_digits):
max_digits[end] = max_digit(nums, end)
for i in reversed(xrange(start, end)):
max_digits[i] = delete_digit(max_digits[(i + 1)])
def max_digit(nums, k):
drop = (len(nums) - k)
res = []
for num in nums:
... |
':type num: str
:rtype: bool'
| def isAdditiveNumber(self, num):
| def add(a, b):
(res, carry, val) = ('', 0, 0)
for i in xrange(max(len(a), len(b))):
val = carry
if (i < len(a)):
val += int(a[(- (i + 1))])
if (i < len(b)):
val += int(b[(- (i + 1))])
(carry, val) = ((val / 10), (val % 1... |
':type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]'
| def findOrder(self, numCourses, prerequisites):
| (res, zero_in_degree_queue, in_degree, out_degree) = ([], collections.deque(), {}, {})
for (i, j) in prerequisites:
if (i not in in_degree):
in_degree[i] = set()
if (j not in out_degree):
out_degree[j] = set()
in_degree[i].add(j)
out_degree[j].add(i)
f... |
':type nums: List[int]
:rtype: int'
| def majorityElement(self, nums):
| (idx, cnt) = (0, 1)
for i in xrange(1, len(nums)):
if (nums[idx] == nums[i]):
cnt += 1
else:
cnt -= 1
if (cnt == 0):
idx = i
cnt = 1
return nums[idx]
|
':type nums: List[int]
:rtype: int'
| def majorityElement2(self, nums):
| return sorted(collections.Counter(nums).items(), key=(lambda a: a[1]), reverse=True)[0][0]
|
':type nums: List[int]
:rtype: int'
| def findMin(self, nums):
| (left, right) = (0, (len(nums) - 1))
while (left < right):
mid = (left + ((right - left) / 2))
if (nums[mid] == nums[right]):
right -= 1
elif (nums[mid] < nums[right]):
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]):
left += 1
elif (nums[mid] < nums[left]):
right = mid
else:
left = (mid + 1)
retur... |
':type p: str
:rtype: int'
| def findSubstringInWraproundString(self, p):
| letters = ([0] * 26)
(result, length) = (0, 0)
for i in xrange(len(p)):
curr = (ord(p[i]) - ord('a'))
if ((i > 0) and (ord(p[(i - 1)]) != (((curr - 1) % 26) + ord('a')))):
length = 0
length += 1
if (length > letters[curr]):
result += (length - letters[... |
':type stones: List[int]
:rtype: bool'
| def canCross(self, stones):
| if (stones[1] != 1):
return False
last_jump_units = {s: set() for s in stones}
last_jump_units[1].add(1)
for s in stones[:(-1)]:
for j in last_jump_units[s]:
for k in ((j - 1), j, (j + 1)):
if ((k > 0) and ((s + k) in last_jump_units)):
las... |
':type price: List[int]
:type special: List[List[int]]
:type needs: List[int]
:rtype: int'
| def shoppingOffers(self, price, special, needs):
| def shoppingOffersHelper(price, special, needs, i):
if (i == len(special)):
return sum(map((lambda x, y: (x * y)), price, needs))
result = shoppingOffersHelper(price, special, needs, (i + 1))
for j in xrange(len(needs)):
needs[j] -= special[i][j]
if all(((need... |
'Initialize your data structure here.'
| def __init__(self):
| self.__list = []
self.__used = defaultdict(list)
|
'Inserts a value to the collection. Returns true if the collection did not already contain the specified element.
:type val: int
:rtype: bool'
| def insert(self, val):
| has = (val in self.__used)
self.__list += (val,)
self.__used[val] += ((len(self.__list) - 1),)
return (not has)
|
'Removes a value from the collection. Returns true if the collection contained the specified element.
:type val: int
:rtype: bool'
| def remove(self, val):
| if (val not in self.__used):
return False
self.__used[self.__list[(-1)]][(-1)] = self.__used[val][(-1)]
(self.__list[self.__used[val][(-1)]], self.__list[(-1)]) = (self.__list[(-1)], self.__list[self.__used[val][(-1)]])
self.__used[val].pop()
if (not self.__used[val]):
self.__used.po... |
'Get a random element from the collection.
:rtype: int'
| def getRandom(self):
| return self.__list[randint(0, (len(self.__list) - 1))]
|
':type s: str
:rtype: int'
| def strongPasswordChecker(self, s):
| missing_type_cnt = 3
if any((('a' <= c <= 'z') for c in s)):
missing_type_cnt -= 1
if any((('A' <= c <= 'Z') for c in s)):
missing_type_cnt -= 1
if any((c.isdigit() for c in s)):
missing_type_cnt -= 1
total_change_cnt = 0
(one_change_cnt, two_change_cnt, three_change_cnt)... |
':type nums: List[int]
:rtype: int'
| def maximumProduct(self, nums):
| (min1, min2) = (float('inf'), float('inf'))
(max1, max2, max3) = (float('-inf'), float('-inf'), float('-inf'))
for n in nums:
if (n <= min1):
min2 = min1
min1 = n
elif (n <= min2):
min2 = n
if (n >= max1):
max3 = max2
max2 =... |
':type buf: Destination buffer (List[str])
:type n: Maximum number of characters to read (int)
:rtype: The number of characters read (int)'
| def read(self, buf, n):
| i = 0
while (i < n):
if (self.__i4 < self.__n4):
buf[i] = self.__buf4[self.__i4]
i += 1
self.__i4 += 1
else:
self.__n4 = read4(self.__buf4)
if self.__n4:
self.__i4 = 0
else:
break
return i... |
':type nums: List[int]
:rtype: int'
| def missingNumber(self, nums):
| return reduce(operator.xor, nums, reduce(operator.xor, xrange((len(nums) + 1))))
|
':type a: int
:rtype: int'
| def smallestFactorization(self, a):
| if (a < 2):
return a
(result, mul) = (0, 1)
for i in reversed(xrange(2, 10)):
while ((a % i) == 0):
a /= i
result = ((mul * i) + result)
mul *= 10
return (result if ((a == 1) and (result < (2 ** 31))) else 0)
|
':type word1: str
:type word2: str
:rtype: int'
| def minDistance(self, word1, word2):
| (m, n) = (len(word1), len(word2))
dp = [([0] * (n + 1)) for _ in xrange(2)]
for i in xrange(m):
for j in xrange(n):
dp[((i + 1) % 2)][(j + 1)] = max(dp[(i % 2)][(j + 1)], dp[((i + 1) % 2)][j], (dp[(i % 2)][j] + (word1[i] == word2[j])))
return ((m + n) - (2 * dp[(m % 2)][n]))
|
'Initialize your data structure here.
:type nestedList: List[NestedInteger]'
| def __init__(self, nestedList):
| self.__depth = [[nestedList, 0]]
|
':rtype: int'
| def next(self):
| (nestedList, i) = self.__depth[(-1)]
self.__depth[(-1)][1] += 1
return nestedList[i].getInteger()
|
':rtype: bool'
| def hasNext(self):
| while self.__depth:
(nestedList, i) = self.__depth[(-1)]
if (i == len(nestedList)):
self.__depth.pop()
elif nestedList[i].isInteger():
return True
else:
self.__depth[(-1)][1] += 1
self.__depth.append([nestedList[i].getList(), 0])
re... |
':type root: TreeNode
:rtype: List[int]'
| def preorderTraversal(self, root):
| (result, curr) = ([], root)
while curr:
if (curr.left is None):
result.append(curr.val)
curr = curr.right
else:
node = curr.left
while (node.right and (node.right != curr)):
node = node.right
if (node.right is None):
... |
':type root: TreeNode
:rtype: List[int]'
| def preorderTraversal(self, root):
| (result, stack) = ([], [(root, False)])
while stack:
(root, is_visited) = stack.pop()
if (root is None):
continue
if is_visited:
result.append(root.val)
else:
stack.append((root.right, False))
stack.append((root.left, False))
... |
':type a: str
:type b: str
:rtype: int'
| def findLUSlength(self, a, b):
| if (a == b):
return (-1)
return max(len(a), len(b))
|
'Initialize your data structure here.
@param width - screen width
@param height - screen height
@param food - A list of food positions
E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].
:type width: int
:type height: int
:type food: List[List[int]]'
| def __init__(self, width, height, food):
| self.__width = width
self.__height = height
self.__score = 0
self.__food = deque(food)
self.__snake = deque([(0, 0)])
self.__direction = {'U': ((-1), 0), 'L': (0, (-1)), 'R': (0, 1), 'D': (1, 0)}
self.__lookup = collections.defaultdict(int)
self.__lookup[(0, 0)] += 1
|
'Moves the snake.
@param direction - \'U\' = Up, \'L\' = Left, \'R\' = Right, \'D\' = Down
@return The game\'s score after the move. Return -1 if game over.
Game over when snake crosses the screen boundary or bites its body.
:type direction: str
:rtype: int'
| def move(self, direction):
| def valid(x, y):
return ((0 <= x < self.__height) and (0 <= y < self.__width) and ((x, y) not in self.__lookup))
d = self.__direction[direction]
(x, y) = ((self.__snake[(-1)][0] + d[0]), (self.__snake[(-1)][1] + d[1]))
tail = self.__snake[(-1)]
self.__lookup[self.__snake[0]] -= 1
if (sel... |
':type n: int
:type k: int
:rtype: str'
| def getPermutation(self, n, k):
| (seq, k, fact) = ('', (k - 1), math.factorial((n - 1)))
perm = [i for i in xrange(1, (n + 1))]
for i in reversed(xrange(n)):
curr = perm[(k / fact)]
seq += str(curr)
perm.remove(curr)
if (i > 0):
k %= fact
fact /= i
return seq
|
':type ring: str
:type key: str
:rtype: int'
| def findRotateSteps(self, ring, key):
| lookup = collections.defaultdict(list)
for i in xrange(len(ring)):
lookup[ring[i]].append(i)
dp = [([0] * len(ring)) for _ in xrange(2)]
prev = [0]
for i in xrange(1, (len(key) + 1)):
dp[(i % 2)] = ([float('inf')] * len(ring))
for j in lookup[key[(i - 1)]]:
for k ... |
'Encodes a URL to a shortened URL.
:type longUrl: str
:rtype: str'
| def encode(self, longUrl):
| def getRand():
rand = []
for _ in xrange(self.__random_length):
rand += self.__alphabet[random.randint(0, (len(self.__alphabet) - 1))]
return ''.join(rand)
key = getRand()
while (key in self.__lookup):
key = getRand()
self.__lookup[key] = longUrl
return (s... |
'Decodes a shortened URL to its original URL.
:type shortUrl: str
:rtype: str'
| def decode(self, shortUrl):
| return self.__lookup[shortUrl[len(self.__tiny_url):]]
|
':type words: List[str]
:rtype: List[str]'
| def findWords(self, words):
| rows = [set(['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p']), set(['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l']), set(['z', 'x', 'c', 'v', 'b', 'n', 'm'])]
result = []
for word in words:
k = 0
for i in xrange(len(rows)):
if (word[0].lower() in rows[i]):
k = i
... |
':type s: str
:type wordDict: Set[str]
:rtype: List[str]'
| 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))]
valid = [([False] * n) for _ in xrange(n)]
can_break[0] = True
for i in xrange(1, (n + 1)):
for l in xrange(1, (min(i, max_len) + 1)):
i... |
':type s: str
:rtype: int'
| def longestValidParentheses(self, s):
| def length(it, start, c):
(depth, longest) = (0, 0)
for i in it:
if (s[i] == c):
depth += 1
else:
depth -= 1
if (depth < 0):
(start, depth) = (i, 0)
elif (depth == 0):
long... |
':type board: List[List[str]]
:rtype: bool'
| def isValidSudoku(self, board):
| for i in xrange(9):
if ((not self.isValidList([board[i][j] for j in xrange(9)])) or (not self.isValidList([board[j][i] for j in xrange(9)]))):
return False
for i in xrange(3):
for j in xrange(3):
if (not self.isValidList([board[m][n] for n in xrange((3 * j), ((3 * j) + 3)... |
'type n: int
rtype: int'
| def bulbSwitch(self, n):
| return int(math.sqrt(n))
|
':type n: int
:rtype: bool'
| def isPowerOfThree(self, n):
| return ((n > 0) and ((self.__max_pow3 % n) == 0))
|
':type expression: str
:rtype: str'
| def parseTernary(self, expression):
| if (not expression):
return ''
stack = []
for c in expression[::(-1)]:
if (stack and (stack[(-1)] == '?')):
stack.pop()
first = stack.pop()
stack.pop()
second = stack.pop()
if (c == 'T'):
stack.append(first)
... |
':type num: int
:rtype: List[str]'
| def readBinaryWatch(self, num):
| def bit_count(bits):
count = 0
while bits:
bits &= (bits - 1)
count += 1
return count
return [('%d:%02d' % (h, m)) for h in xrange(12) for m in xrange(60) if ((bit_count(h) + bit_count(m)) == num)]
|
':type num: int
:rtype: List[str]'
| def readBinaryWatch2(self, num):
| return ['{0}:{1}'.format(str(h), str(m).zfill(2)) for h in range(12) for m in range(60) if ((bin(h) + bin(m)).count('1') == num)]
|
':type n: int
:rtype: int'
| def integerReplacement(self, n):
| result = 0
while (n != 1):
b = (n & 3)
if (n == 3):
n -= 1
elif (b == 3):
n += 1
elif (b == 1):
n -= 1
else:
n /= 2
result += 1
return result
|
':type n: int
:rtype: int'
| def integerReplacement(self, n):
| if (n < 4):
return [0, 0, 1, 2][n]
if ((n % 4) in (0, 2)):
return (self.integerReplacement((n / 2)) + 1)
elif ((n % 4) == 1):
return (self.integerReplacement(((n - 1) / 4)) + 3)
else:
return (self.integerReplacement(((n + 1) / 4)) + 3)
|
':type dict: List[str]
:type sentence: str
:rtype: str'
| def replaceWords(self, dict, sentence):
| _trie = (lambda : collections.defaultdict(_trie))
trie = _trie()
for s in dict:
curr = trie
for c in s:
curr = curr[c]
curr.setdefault('_end')
def replace(word):
curr = trie
for (i, c) in enumerate(word):
if (c not in curr):
... |
':type area: int
:rtype: List[int]'
| def constructRectangle(self, area):
| w = int(math.sqrt(area))
while (area % w):
w -= 1
return [(area // w), w]
|
':type sentence: List[str]
:type rows: int
:type cols: int
:rtype: int'
| def wordsTyping(self, sentence, rows, cols):
| def words_fit(sentence, start, cols):
if (len(sentence[start]) > cols):
return 0
(s, count) = (len(sentence[start]), 1)
i = ((start + 1) % len(sentence))
while (((s + 1) + len(sentence[i])) <= cols):
s += (1 + len(sentence[i]))
count += 1
... |
':type head: ListNode
:rtype: ListNode'
| def oddEvenList(self, head):
| if head:
(odd_tail, cur) = (head, head.next)
while (cur and cur.next):
even_head = odd_tail.next
odd_tail.next = cur.next
odd_tail = odd_tail.next
cur.next = odd_tail.next
odd_tail.next = even_head
cur = cur.next
return head... |
':type words: List[str]
:rtype: List[List[int]]'
| def palindromePairs(self, words):
| res = []
lookup = {}
for (i, word) in enumerate(words):
lookup[word] = i
for i in xrange(len(words)):
for j in xrange((len(words[i]) + 1)):
prefix = words[i][j:]
suffix = words[i][:j]
if ((prefix == prefix[::(-1)]) and (suffix[::(-1)] in lookup) and (l... |
':type words: List[str]
:rtype: List[List[int]]'
| def palindromePairs(self, words):
| def manacher(s, P):
def preProcess(s):
if (not s):
return ['^', '$']
T = ['^']
for c in s:
T += ['#', c]
T += ['#', '$']
return T
T = preProcess(s)
(center, right) = (0, 0)
for i in xrange(1, ... |
':type words: List[str]
:rtype: List[List[int]]'
| def palindromePairs(self, words):
| res = []
trie = TrieNode()
for i in xrange(len(words)):
trie.insert(words[i], i)
for i in xrange(len(words)):
trie.find(words[i], i, res)
return res
|
':type strs: List[str]
:rtype: List[List[str]]'
| def groupAnagrams(self, strs):
| (anagrams_map, result) = (collections.defaultdict(list), [])
for s in strs:
sorted_str = ''.join(sorted(s))
anagrams_map[sorted_str].append(s)
for anagram in anagrams_map.values():
anagram.sort()
result.append(anagram)
return result
|
':type n: int
:rtype: int'
| def arrangeCoins(self, n):
| return int(((math.sqrt(((8 * n) + 1)) - 1) / 2))
|
':type n: int
:rtype: int'
| def arrangeCoins(self, n):
| (left, right) = (1, n)
while (left <= right):
mid = (left + ((right - left) / 2))
if ((2 * n) < (mid * (mid + 1))):
right = (mid - 1)
else:
left = (mid + 1)
return (left - 1)
|
':type num: int
:rtype: bool'
| def isPowerOfFour(self, num):
| return ((num > 0) and ((num & (num - 1)) == 0) and ((num & 1431655765) == num))
|
':type num: int
:rtype: bool'
| def isPowerOfFour(self, num):
| while (num and (not (num & 3))):
num >>= 2
return (num == 1)
|
':type num: int
:rtype: bool'
| def isPowerOfFour(self, num):
| num = bin(num)
return (True if (num[2:].startswith('1') and (len(num[2:]) == num.count('0')) and (num.count('0') % 2) and ('-' not in num)) else False)
|
':type numCourses: int
:type prerequisites: List[List[int]]
:rtype: bool'
| def canFinish(self, numCourses, prerequisites):
| (zero_in_degree_queue, in_degree, out_degree) = (collections.deque(), {}, {})
for (i, j) in prerequisites:
if (i not in in_degree):
in_degree[i] = set()
if (j not in out_degree):
out_degree[j] = set()
in_degree[i].add(j)
out_degree[j].add(i)
for i in x... |
':type a: str
:type b: str
:rtype: str'
| def complexNumberMultiply(self, a, b):
| (ra, ia) = map(int, a[:(-1)].split('+'))
(rb, ib) = map(int, b[:(-1)].split('+'))
return ('%d+%di' % (((ra * rb) - (ia * ib)), ((ra * ib) + (ia * rb))))
|
'initialize your data structure here.
:type nums: List[int]'
| def __init__(self, nums):
| if (not nums):
return
self.__nums = nums
self.__bit = ([0] * (len(self.__nums) + 1))
for i in xrange(1, len(self.__bit)):
self.__bit[i] = (nums[(i - 1)] + self.__bit[(i - 1)])
for i in reversed(xrange(1, len(self.__bit))):
last_i = (i - (i & (- i)))
self.__bit[i] -= s... |
':type i: int
:type val: int
:rtype: int'
| def update(self, i, val):
| if (val - self.__nums[i]):
self.__add(i, (val - self.__nums[i]))
self.__nums[i] = val
|
'sum of elements nums[i..j], inclusive.
:type i: int
:type j: int
:rtype: int'
| def sumRange(self, i, j):
| return (self.__sum(j) - self.__sum((i - 1)))
|
'initialize your data structure here.
:type nums: List[int]'
| def __init__(self, nums):
| self.__nums = nums
def buildHelper(nums, start, end):
if (start > end):
return None
root = self._SegmentTreeNode(start, end, 0)
if (start == end):
root.sum = nums[start]
return root
root.left = buildHelper(nums, start, ((start + end) / 2))
... |
':type i: int
:type val: int
:rtype: int'
| def update(self, i, val):
| def updateHelper(root, i, val):
if ((not root) or (root.start > i) or (root.end < i)):
return
if ((root.start == i) and (root.end == i)):
root.sum = val
return
updateHelper(root.left, i, val)
updateHelper(root.right, i, val)
root.sum = ((ro... |
'sum of elements nums[i..j], inclusive.
:type i: int
:type j: int
:rtype: int'
| def sumRange(self, i, j):
| def sumRangeHelper(root, start, end):
if ((not root) or (root.start > end) or (root.end < start)):
return 0
if ((root.start >= start) and (root.end <= end)):
return root.sum
return (sumRangeHelper(root.left, start, end) + sumRangeHelper(root.right, start, end))
re... |
':type t: TreeNode
:rtype: str'
| def tree2str(self, t):
| if (not t):
return ''
s = str(t.val)
if (t.left or t.right):
s += (('(' + self.tree2str(t.left)) + ')')
if t.right:
s += (('(' + self.tree2str(t.right)) + ')')
return s
|
':type buf: Destination buffer (List[str])
:type n: Maximum number of characters to read (int)
:rtype: The number of characters read (int)'
| def read(self, buf, n):
| read_bytes = 0
buffer = ([''] * 4)
for i in xrange(((n / 4) + 1)):
size = read4(buffer)
if size:
buf[read_bytes:(read_bytes + size)] = buffer
read_bytes += size
else:
break
return min(read_bytes, n)
|
':type points: List[List[int]]
:rtype: int'
| def numberOfBoomerangs(self, points):
| result = 0
for i in xrange(len(points)):
group = collections.defaultdict(int)
for j in xrange(len(points)):
if (j == i):
continue
(dx, dy) = ((points[i][0] - points[j][0]), (points[i][1] - points[j][1]))
group[((dx ** 2) + (dy ** 2))] += 1
... |
':type points: List[List[int]]
:rtype: int'
| def numberOfBoomerangs2(self, points):
| cnt = 0
for (a, i) in enumerate(points):
dis_list = []
for (b, k) in enumerate((points[:a] + points[(a + 1):])):
dis_list.append((((k[0] - i[0]) ** 2) + ((k[1] - i[1]) ** 2)))
for z in collections.Counter(dis_list).values():
if (z > 1):
cnt += (z *... |
':type n: int
:rtype: bool'
| def canWinNim(self, n):
| return ((n % 4) != 0)
|
':type grid: List[List[int]]
:rtype: int'
| def shortestDistance(self, grid):
| def bfs(grid, dists, cnts, x, y):
(dist, m, n) = (0, len(grid), len(grid[0]))
visited = [[False for _ in xrange(n)] for _ in xrange(m)]
pre_level = [(x, y)]
visited[x][y] = True
while pre_level:
dist += 1
cur_level = []
for (i, j) in pre_le... |
':type s: str
:rtype: List[str]'
| def removeInvalidParentheses(self, s):
| def findMinRemove(s):
(left_removed, right_removed) = (0, 0)
for c in s:
if (c == '('):
left_removed += 1
elif (c == ')'):
if (not left_removed):
right_removed += 1
else:
left_removed -= 1... |
':type pattern: str
:type str: str
:rtype: bool'
| def wordPatternMatch(self, pattern, str):
| (w2p, p2w) = ({}, {})
return self.match(pattern, str, 0, 0, w2p, p2w)
|
':type nums: List[int]
:type target: int
:rtype: List[int]'
| def twoSum(self, nums, target):
| lookup = {}
for (i, num) in enumerate(nums):
if ((target - num) in lookup):
return [lookup[(target - num)], i]
lookup[num] = i
return []
|
':type nums: List[int]
:type target: int
:rtype: List[int]'
| def twoSum2(self, nums, target):
| k = 0
for i in nums:
j = (target - i)
k += 1
tmp_nums = nums[k:]
if (j in tmp_nums):
return [(k - 1), (tmp_nums.index(j) + k)]
|
':type board: List[List[str]]
:type words: List[str]
:rtype: List[str]'
| def findWords(self, board, words):
| visited = [[False for j in xrange(len(board[0]))] for i in xrange(len(board))]
result = {}
trie = TrieNode()
for word in words:
trie.insert(word)
for i in xrange(len(board)):
for j in xrange(len(board[0])):
if self.findWordsRecu(board, trie, 0, i, j, visited, [], result):... |
':type code: str
:rtype: bool'
| def isValid(self, code):
| def validText(s, i):
j = i
i = s.find('<', i)
return ((i != j), i)
def validCData(s, i):
if (s.find('<![CDATA[', i) != i):
return (False, i)
j = s.find(']]>', i)
if (j == (-1)):
return (False, i)
return (True, (j + 3))
def parse... |
':type nums: List[int]
:rtype: int'
| def findMaxConsecutiveOnes(self, nums):
| (result, local_max) = (0, 0)
for n in nums:
local_max = ((local_max + 1) if n else 0)
result = max(result, local_max)
return result
|
':type s: str
:rtype: str'
| def shortestPalindrome(self, s):
| def getPrefix(pattern):
prefix = ([(-1)] * len(pattern))
j = (-1)
for i in xrange(1, len(pattern)):
while ((j > (-1)) and (pattern[(j + 1)] != pattern[i])):
j = prefix[j]
if (pattern[(j + 1)] == pattern[i]):
j += 1
prefix[i]... |
':type s: str
:rtype: str'
| def shortestPalindrome(self, s):
| def preProcess(s):
if (not s):
return ['^', '$']
string = ['^']
for c in s:
string += ['#', c]
string += ['#', '$']
return string
string = preProcess(s)
palindrome = ([0] * len(string))
(center, right) = (0, 0)
for i in xrange(1, (len(s... |
':type compressedString: str'
| def __init__(self, compressedString):
| self.__result = re.findall('([a-zA-Z])(\\d+)', compressedString)
(self.__index, self.__num, self.__ch) = (0, 0, ' ')
|
':rtype: str'
| def next(self):
| if (not self.hasNext()):
return ' '
if (self.__num == 0):
self.__ch = self.__result[self.__index][0]
self.__num = int(self.__result[self.__index][1])
self.__index += 1
self.__num -= 1
return self.__ch
|
':rtype: bool'
| def hasNext(self):
| return ((self.__index != len(self.__result)) or (self.__num != 0))
|
':type strs: List[str]
:rtype: str'
| def splitLoopedString(self, strs):
| tmp = []
for s in strs:
tmp += max(s, s[::(-1)])
s = ''.join(tmp)
(result, st) = ('a', 0)
for i in xrange(len(strs)):
body = ''.join([s[(st + len(strs[i])):], s[0:st]])
for p in (strs[i], strs[i][::(-1)]):
for j in xrange(len(strs[i])):
if (p[j] >=... |
':type root: TreeNode
:type p: TreeNode
:rtype: TreeNode'
| def inorderSuccessor(self, root, p):
| if (p and p.right):
p = p.right
while p.left:
p = p.left
return p
successor = None
while (root and (root != p)):
if (root.val > p.val):
successor = root
root = root.left
else:
root = root.right
return successor
|
':type nums: List[int]
:type target: int
:rtype: List[int]'
| def searchRange(self, nums, target):
| left = self.binarySearch((lambda x, y: (x >= y)), nums, target)
if ((left >= len(nums)) or (nums[left] != target)):
return [(-1), (-1)]
right = self.binarySearch((lambda x, y: (x > y)), nums, target)
return [left, (right - 1)]
|
':type nums: List[int]
:rtype: List[int]'
| def nextGreaterElements(self, nums):
| (result, stk) = (([0] * len(nums)), [])
for i in reversed(xrange((2 * len(nums)))):
while (stk and (stk[(-1)] <= nums[(i % len(nums))])):
stk.pop()
result[(i % len(nums))] = (stk[(-1)] if stk else (-1))
stk.append(nums[(i % len(nums))])
return result
|
':type x: int
:rtype: int'
| def mySqrt(self, x):
| if (x < 2):
return x
(left, right) = (1, (x // 2))
while (left <= right):
mid = (left + ((right - left) // 2))
if (mid > (x / mid)):
right = (mid - 1)
else:
left = (mid + 1)
return (left - 1)
|
':type n: int
:rtype: int'
| def numSquares(self, n):
| num = self._num
while (len(num) <= n):
num += ((min((num[((- i) * i)] for i in xrange(1, int(((len(num) ** 0.5) + 1))))) + 1),)
return num[n]
|
':type s: str
:rtype: bool'
| def checkRecord(self, s):
| count_A = 0
for i in xrange(len(s)):
if (s[i] == 'A'):
count_A += 1
if (count_A == 2):
return False
if ((i < (len(s) - 2)) and (s[i] == s[(i + 1)] == s[(i + 2)] == 'L')):
return False
return True
|
':type nestedList: List[NestedInteger]
:rtype: int'
| def depthSumInverse(self, nestedList):
| def depthSumInverseHelper(list, depth, result):
if (len(result) < (depth + 1)):
result.append(0)
if list.isInteger():
result[depth] += list.getInteger()
else:
for l in list.getList():
depthSumInverseHelper(l, (depth + 1), result)
result... |
':type words: List[str]
:type maxWidth: int
:rtype: List[str]'
| def fullJustify(self, words, maxWidth):
| def addSpaces(i, spaceCnt, maxWidth, is_last):
if (i < spaceCnt):
return (1 if is_last else ((maxWidth // spaceCnt) + int((i < (maxWidth % spaceCnt)))))
return 0
def connect(words, maxWidth, begin, end, length, is_last):
s = []
n = (end - begin)
for i in xrang... |
':type costs: List[List[int]]
:rtype: int'
| def minCostII(self, costs):
| return (min(reduce(self.combine, costs)) if costs else 0)
|
':type costs: List[List[int]]
:rtype: int'
| def minCostII(self, costs):
| if (not costs):
return 0
n = len(costs)
k = len(costs[0])
min_cost = [costs[0], ([0] * k)]
for i in xrange(1, n):
(smallest, second_smallest) = (float('inf'), float('inf'))
for j in xrange(k):
if (min_cost[((i - 1) % 2)][j] < smallest):
(smallest, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.