id
stringlengths 11
11
| difficulty
stringclasses 1
value | code
stringlengths 171
6.24k
| render_light
imagewidth (px) 436
1.6k
| render_dark
imagewidth (px) 436
1.6k
| photo
imagewidth (px) 964
4.08k
|
|---|---|---|---|---|---|
easy_000001
|
easy
|
# Time: O(n)
# Space: O(n)
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
lookup = {}
for i, num in enumerate(nums):
if target - num in lookup:
return [lookup[target - num], i]
lookup[num] = i
def twoSum2(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in nums:
j = target - i
tmp_nums_start_index = nums.index(i) + 1
tmp_nums = nums[tmp_nums_start_index:]
if j in tmp_nums:
return [nums.index(i), tmp_nums_start_index + tmp_nums.index(j)]
| |||
easy_000002
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1:
return s
step, zigzag = 2 * numRows - 2, ""
for i in xrange(numRows):
for j in xrange(i, len(s), step):
zigzag += s[j]
if 0 < i < numRows - 1 and j + step - 2 * i < len(s):
zigzag += s[j + step - 2 * i]
return zigzag
| |||
easy_000003
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
INT_MAX = 2147483647
INT_MIN = -2147483648
result = 0
if not str:
return result
i = 0
while i < len(str) and str[i].isspace():
i += 1
if len(str) == i:
return result
sign = 1
if str[i] == "+":
i += 1
elif str[i] == "-":
sign = -1
i += 1
while i < len(str) and '0' <= str[i] <= '9':
if result > (INT_MAX - int(str[i])) / 10:
return INT_MAX if sign > 0 else INT_MIN
result = result * 10 + int(str[i])
i += 1
return sign * result
| |||
easy_000004
|
easy
|
# Time: O(1)
# Space: O(1)
class Solution(object):
# @return a boolean
def isPalindrome(self, x):
if x < 0:
return False
copy, reverse = x, 0
while copy:
reverse *= 10
reverse += copy % 10
copy //= 10
return x == reverse
| |||
easy_000005
|
easy
|
# Time: O(n * k), k is the length of the common prefix
# Space: O(1)
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
for i in xrange(len(strs[0])):
for string in strs[1:]:
if i >= len(string) or string[i] != strs[0][i]:
return strs[0][:i]
return strs[0]
# Time: O(n * k), k is the length of the common prefix
# Space: O(k)
class Solution2(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
prefix = ""
for chars in zip(*strs):
if all(c == chars[0] for c in chars):
prefix += chars[0]
else:
return prefix
return prefix
| |||
easy_000006
|
easy
|
# Time: O(n)
# Space: O(n)
class Solution(object):
# @return a boolean
def isValid(self, s):
stack, lookup = [], {"(": ")", "{": "}", "[": "]"}
for parenthese in s:
if parenthese in lookup:
stack.append(parenthese)
elif len(stack) == 0 or lookup[stack.pop()] != parenthese:
return False
return len(stack) == 0
| |||
easy_000007
|
easy
|
# Time: O(n)
# Space: O(1)
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
if self:
return "{} -> {}".format(self.val, self.next)
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
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
| |||
easy_000008
|
easy
|
# Time: O(n)
# Space: O(1)
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
if self:
return "{} -> {}".format(self.val, self.next)
class Solution(object):
# @param a ListNode
# @return a ListNode
def swapPairs(self, head):
dummy = ListNode(0)
dummy.next = head
current = dummy
while current.next and current.next.next:
next_one, next_two, next_three = current.next, current.next.next, current.next.next.next
current.next = next_two
next_two.next = next_one
next_one.next = next_three
current = next_one
return dummy.next
| |||
easy_000009
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
# @param a list of integers
# @return an integer
def removeDuplicates(self, A):
if not A:
return 0
last = 0
for i in xrange(len(A)):
if A[last] != A[i]:
last += 1
A[last] = A[i]
return last + 1
| |||
easy_000010
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
# @param A a list of integers
# @param elem an integer, value need to be removed
# @return an integer
def removeElement(self, A, elem):
i, last = 0, len(A) - 1
while i <= last:
if A[i] == elem:
A[i], A[last] = A[last], A[i]
last -= 1
else:
i += 1
return last + 1
| |||
easy_000011
|
easy
|
# Time: O(n + k)
# Space: O(k)
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if not needle:
return 0
return self.KMP(haystack, needle)
def KMP(self, text, pattern):
prefix = self.getPrefix(pattern)
j = -1
for i in xrange(len(text)):
while j > -1 and pattern[j + 1] != text[i]:
j = prefix[j]
if pattern[j + 1] == text[i]:
j += 1
if j == len(pattern) - 1:
return i - j
return -1
def getPrefix(self, 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] = j
return prefix
# Time: O(n * k)
# Space: O(k)
class Solution2(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
for i in xrange(len(haystack) - len(needle) + 1):
if haystack[i : i + len(needle)] == needle:
return i
return -1
| |||
easy_000012
|
easy
|
# Time: O(9^2)
# Space: O(9)
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
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) \
for m in xrange(3 * i, 3 * i + 3)]):
return False
return True
def isValidList(self, xs):
xs = filter(lambda x: x != '.', xs)
return len(set(xs)) == len(xs)
| |||
easy_000013
|
easy
|
# Time: O(n * 2^n)
# Space: O(2^n)
class Solution(object):
# @return a string
def countAndSay(self, n):
seq = "1"
for i in xrange(n - 1):
seq = self.getNext(seq)
return seq
def getNext(self, seq):
i, next_seq = 0, ""
while i < len(seq):
cnt = 1
while i < len(seq) - 1 and seq[i] == seq[i + 1]:
cnt += 1
i += 1
next_seq += str(cnt) + seq[i]
i += 1
return next_seq
| |||
easy_000014
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result, curr = float("-inf"), float("-inf")
for x in nums:
curr = max(curr+x, x)
result = max(result, curr)
return result
| |||
easy_000015
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
# @param s, a string
# @return an integer
def lengthOfLastWord(self, s):
length = 0
for i in reversed(s):
if i == ' ':
if length:
break
else:
length += 1
return length
# Time: O(n)
# Space: O(n)
class Solution2(object):
# @param s, a string
# @return an integer
def lengthOfLastWord(self, s):
return len(s.strip().split(" ")[-1])
| |||
easy_000016
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
for i in reversed(xrange(len(digits))):
if digits[i] == 9:
digits[i] = 0
else:
digits[i] += 1
return digits
digits[0] = 1
digits.append(0)
return digits
# Time: O(n)
# Space: O(n)
class Solution2(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
result = digits[::-1]
carry = 1
for i in xrange(len(result)):
result[i] += carry
carry, result[i] = divmod(result[i], 10)
if carry:
result.append(carry)
return result[::-1]
| |||
easy_000017
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
# @param a, a string
# @param b, a string
# @return a string
def addBinary(self, a, b):
result, 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 = divmod(val, 2)
result += str(val)
if carry:
result += str(carry)
return result[::-1]
# Time: O(n)
# Space: O(1)
from itertools import izip_longest
class Solution2(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
result = ""
carry = 0
for x, y in izip_longest(reversed(a), reversed(b), fillvalue="0"):
carry, remainder = divmod(int(x)+int(y)+carry, 2)
result += str(remainder)
if carry:
result += str(carry)
return result[::-1]
| |||
easy_000018
|
easy
|
# Time: O(logn)
# Space: O(1)
import itertools
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
def matrix_expo(A, K):
result = [[int(i==j) for j in xrange(len(A))] \
for i in xrange(len(A))]
while K:
if K % 2:
result = matrix_mult(result, A)
A = matrix_mult(A, A)
K /= 2
return result
def matrix_mult(A, B):
ZB = zip(*B)
return [[sum(a*b for a, b in itertools.izip(row, col)) \
for col in ZB] for row in A]
T = [[1, 1],
[1, 0]]
return matrix_mult([[1, 0]], matrix_expo(T, n))[0][0] # [a0, a(-1)] * T^n
# Time: O(n)
# Space: O(1)
class Solution2(object):
"""
:type n: int
:rtype: int
"""
def climbStairs(self, n):
prev, current = 0, 1
for i in xrange(n):
prev, current = current, prev + current,
return current
| |||
easy_000019
|
easy
|
# Time: O(n)
# Space: O(1)
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
cur = head
while cur:
runner = cur.next
while runner and runner.val == cur.val:
runner = runner.next
cur.next = runner
cur = runner
return head
def deleteDuplicates2(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head: return head
if head.next:
if head.val == head.next.val:
head = self.deleteDuplicates2(head.next)
else:
head.next = self.deleteDuplicates2(head.next)
return head
| |||
easy_000020
|
easy
|
# Time: O(n)
# Space: O(h), h is height of binary tree
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
# @param p, a tree node
# @param q, a tree node
# @return a boolean
def isSameTree(self, p, q):
if p is None and q is None:
return True
if p is not None and q is not None:
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
return False
| |||
easy_000021
|
easy
|
# Time: O(n)
# Space: O(h), h is height of binary tree
# Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# Iterative solution
class Solution(object):
# @param root, a tree node
# @return a boolean
def isSymmetric(self, root):
if root is None:
return True
stack = []
stack.append(root.left)
stack.append(root.right)
while stack:
p, q = stack.pop(), stack.pop()
if p is None and q is None:
continue
if p is None or q is None or p.val != q.val:
return False
stack.append(p.left)
stack.append(q.right)
stack.append(p.right)
stack.append(q.left)
return True
# Recursive solution
class Solution2(object):
# @param root, a tree node
# @return a boolean
def isSymmetric(self, root):
if root is None:
return True
return self.isSymmetricRecu(root.left, root.right)
def isSymmetricRecu(self, left, right):
if left is None and right is None:
return True
if left is None or right is None or left.val != right.val:
return False
return self.isSymmetricRecu(left.left, right.right) and self.isSymmetricRecu(left.right, right.left)
| |||
easy_000022
|
easy
|
# Time: O(n)
# Space: O(h), h is height of binary tree
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
# @param root, a tree node
# @return an integer
def maxDepth(self, root):
if root is None:
return 0
else:
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
| |||
easy_000023
|
easy
|
# Time: O(n)
# Space: O(n)
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root is None:
return []
result, current = [], [root]
while current:
next_level, vals = [], []
for node in current:
vals.append(node.val)
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
current = next_level
result.append(vals)
return result[::-1]
| |||
easy_000024
|
easy
|
# Time: O(n)
# Space: O(h), h is height of binary tree
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
# @param root, a tree node
# @return a boolean
def isBalanced(self, root):
def getHeight(root):
if root is None:
return 0
left_height, right_height = \
getHeight(root.left), getHeight(root.right)
if left_height < 0 or right_height < 0 or \
abs(left_height - right_height) > 1:
return -1
return max(left_height, right_height) + 1
return (getHeight(root) >= 0)
| |||
easy_000025
|
easy
|
# Time: O(n)
# Space: O(h), h is height of binary tree
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
# @param root, a tree node
# @return an integer
def minDepth(self, root):
if root is None:
return 0
if root.left and root.right:
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
else:
return max(self.minDepth(root.left), self.minDepth(root.right)) + 1
| |||
easy_000026
|
easy
|
# Time: O(n)
# Space: O(h), h is height of binary tree
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
# @param root, a tree node
# @param sum, an integer
# @return a boolean
def hasPathSum(self, root, sum):
if root is None:
return False
if root.left is None and root.right is None and root.val == sum:
return True
return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)
| |||
easy_000027
|
easy
|
# Time: O(n^2)
# Space: O(1)
class Solution(object):
# @return a list of lists of integers
def generate(self, numRows):
result = []
for i in xrange(numRows):
result.append([])
for j in xrange(i + 1):
if j in (0, i):
result[i].append(1)
else:
result[i].append(result[i - 1][j - 1] + result[i - 1][j])
return result
def generate2(self, numRows):
if not numRows: return []
res = [[1]]
for i in range(1, numRows):
res += [map(lambda x, y: x + y, res[-1] + [0], [0] + res[-1])]
return res[:numRows]
def generate3(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows == 0: return []
if numRows == 1: return [[1]]
res = [[1], [1, 1]]
def add(nums):
res = nums[:1]
for i, j in enumerate(nums):
if i < len(nums) - 1:
res += [nums[i] + nums[i + 1]]
res += nums[:1]
return res
while len(res) < numRows:
res.extend([add(res[-1])])
return res
| |||
easy_000028
|
easy
|
# Time: O(n^2)
# Space: O(1)
class Solution(object):
# @return a list of integers
def getRow(self, rowIndex):
result = [0] * (rowIndex + 1)
for i in xrange(rowIndex + 1):
old = result[0] = 1
for j in xrange(1, i + 1):
old, result[j] = result[j], old + result[j]
return result
def getRow2(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
row = [1]
for _ in range(rowIndex):
row = [x + y for x, y in zip([0] + row, row + [0])]
return row
def getRow3(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
if rowIndex == 0: return [1]
res = [1, 1]
def add(nums):
res = nums[:1]
for i, j in enumerate(nums):
if i < len(nums) - 1:
res += [nums[i] + nums[i + 1]]
res += nums[:1]
return res
while res[1] < rowIndex:
res = add(res)
return res
# Time: O(n^2)
# Space: O(n)
class Solution2(object):
# @return a list of integers
def getRow(self, rowIndex):
result = [1]
for i in range(1, rowIndex + 1):
result = [1] + [result[j - 1] + result[j] for j in xrange(1, i)] + [1]
return result
| |||
easy_000029
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
max_profit, min_price = 0, float("inf")
for price in prices:
min_price = min(min_price, price)
max_profit = max(max_profit, price - min_price)
return max_profit
| |||
easy_000030
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
profit = 0
for i in xrange(len(prices) - 1):
profit += max(0, prices[i + 1] - prices[i])
return profit
def maxProfit2(self, prices):
return sum(map(lambda x: max(prices[x + 1] - prices[x], 0),
xrange(len(prices[:-1]))))
| |||
easy_000031
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
# @param s, a string
# @return a boolean
def isPalindrome(self, s):
i, j = 0, len(s) - 1
while i < j:
while i < j and not s[i].isalnum():
i += 1
while i < j and not s[j].isalnum():
j -= 1
if s[i].lower() != s[j].lower():
return False
i, j = i + 1, j - 1
return True
| |||
easy_000032
|
easy
|
# Time: O(n)
# Space: O(1)
import operator
from functools import reduce
class Solution(object):
"""
:type nums: List[int]
:rtype: int
"""
def singleNumber(self, A):
return reduce(operator.xor, A)
| |||
easy_000033
|
easy
|
# Time: O(n)
# Space: O(1)
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
# @param head, a ListNode
# @return a boolean
def hasCycle(self, head):
fast, slow = head, head
while fast and fast.next:
fast, slow = fast.next.next, slow.next
if fast is slow:
return True
return False
| |||
easy_000034
|
easy
|
# Time: O(n)
# Space: O(1)
class MinStack(object):
def __init__(self):
self.min = None
self.stack = []
# @param x, an integer
# @return an integer
def push(self, x):
if not self.stack:
self.stack.append(0)
self.min = x
else:
self.stack.append(x - self.min)
if x < self.min:
self.min = x
# @return nothing
def pop(self):
x = self.stack.pop()
if x < 0:
self.min = self.min - x
# @return an integer
def top(self):
x = self.stack[-1]
if x > 0:
return x + self.min
else:
return self.min
# @return an integer
def getMin(self):
return self.min
# Time: O(n)
# Space: O(n)
class MinStack2(object):
def __init__(self):
self.stack, self.minStack = [], []
# @param x, an integer
# @return an integer
def push(self, x):
self.stack.append(x)
if len(self.minStack):
if x < self.minStack[-1][0]:
self.minStack.append([x, 1])
elif x == self.minStack[-1][0]:
self.minStack[-1][1] += 1
else:
self.minStack.append([x, 1])
# @return nothing
def pop(self):
x = self.stack.pop()
if x == self.minStack[-1][0]:
self.minStack[-1][1] -= 1
if self.minStack[-1][1] == 0:
self.minStack.pop()
# @return an integer
def top(self):
return self.stack[-1]
# @return an integer
def getMin(self):
return self.minStack[-1][0]
# time: O(1)
# space: O(n)
class MinStack3(object):
def __init__(self):
self.stack = []
def push(self, x):
if self.stack:
current_min = min(x, self.stack[-1][0])
self.stack.append((current_min, x))
else:
self.stack.append((x, x))
def pop(self):
return self.stack.pop()[1]
def top(self):
return self.stack[-1][1]
def getMin(self):
return self.stack[-1][0]
| |||
easy_000035
|
easy
|
# Time: O(n)
# Space: O(1)
def read4(buf):
global file_content
i = 0
while i < len(file_content) and i < 4:
buf[i] = file_content[i]
i += 1
if len(file_content) > 4:
file_content = file_content[4:]
else:
file_content = ""
return i
class Solution(object):
def read(self, buf, n):
"""
:type buf: Destination buffer (List[str])
:type n: Maximum number of characters to read (int)
:rtype: The number of characters read (int)
"""
read_bytes = 0
buffer = [''] * 4
for i in xrange((n+4-1)//4):
size = min(read4(buffer), n-read_bytes)
buf[read_bytes:read_bytes+size] = buffer[:size]
read_bytes += size
return read_bytes
| |||
easy_000036
|
easy
|
# Time: O(m + n)
# Space: O(1)
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
# @param two ListNodes
# @return the intersected ListNode
def getIntersectionNode(self, headA, headB):
curA, curB = headA, headB
while curA != curB:
curA = curA.next if curA else headB
curB = curB.next if curB else headA
return curA
| |||
easy_000037
|
easy
|
# Time: O(n)
# Space: O(1)
import itertools
class Solution(object):
def compareVersion(self, version1, version2):
"""
:type version1: str
:type version2: str
:rtype: int
"""
n1, n2 = len(version1), len(version2)
i, j = 0, 0
while i < n1 or j < n2:
v1, v2 = 0, 0
while i < n1 and version1[i] != '.':
v1 = v1 * 10 + int(version1[i])
i += 1
while j < n2 and version2[j] != '.':
v2 = v2 * 10 + int(version2[j])
j += 1
if v1 != v2:
return 1 if v1 > v2 else -1
i += 1
j += 1
return 0
# Time: O(n)
# Space: O(n)
class Solution2(object):
def compareVersion(self, version1, version2):
"""
:type version1: str
:type version2: str
:rtype: int
"""
v1, v2 = version1.split("."), version2.split(".")
if len(v1) > len(v2):
v2 += ['0' for _ in xrange(len(v1) - len(v2))]
elif len(v1) < len(v2):
v1 += ['0' for _ in xrange(len(v2) - len(v1))]
i = 0
while i < len(v1):
if int(v1[i]) > int(v2[i]):
return 1
elif int(v1[i]) < int(v2[i]):
return -1
else:
i += 1
return 0
def compareVersion2(self, version1, version2):
"""
:type version1: str
:type version2: str
:rtype: int
"""
v1 = [int(x) for x in version1.split('.')]
v2 = [int(x) for x in version2.split('.')]
while len(v1) != len(v2):
if len(v1) > len(v2):
v2.append(0)
else:
v1.append(0)
return cmp(v1, v2)
def compareVersion3(self, version1, version2):
splits = (map(int, v.split('.')) for v in (version1, version2))
return cmp(*zip(*itertools.izip_longest(*splits, fillvalue=0)))
def compareVersion4(self, version1, version2):
main1, _, rest1 = ('0' + version1).partition('.')
main2, _, rest2 = ('0' + version2).partition('.')
return cmp(int(main1), int(main2)) or len(rest1 + rest2) and self.compareVersion4(rest1, rest2)
| |||
easy_000038
|
easy
|
# Time: O(logn)
# Space: O(1)
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
result = []
while n:
result += chr((n-1)%26 + ord('A'))
n = (n-1)//26
result.reverse()
return "".join(result)
| |||
easy_000039
|
easy
|
# Time: O(n)
# Space: O(1)
import collections
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def boyer_moore_majority_vote():
result, cnt = None, 0
for x in nums:
if not cnt:
result = x
if x == result:
cnt += 1
else:
cnt -= 1
return result
return boyer_moore_majority_vote()
# Time: O(n)
# Space: O(n)
import collections
class Solution2(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return collections.Counter(nums).most_common(1)[0][0]
# Time: O(nlogn)
# Space: O(n)
import collections
class Solution3(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sorted(collections.Counter(nums).items(), key=lambda a: a[1], reverse=True)[0][0]
| |||
easy_000040
|
easy
|
# Time: O(n)
# Space: O(n)
from collections import defaultdict
class TwoSum(object):
def __init__(self):
"""
initialize your data structure here
"""
self.lookup = defaultdict(int)
def add(self, number):
"""
Add the number to an internal data structure.
:rtype: nothing
"""
self.lookup[number] += 1
def find(self, value):
"""
Find if there exists any pair of numbers which sum is equal to the value.
:type value: int
:rtype: bool
"""
for key in self.lookup:
num = value - key
if num in self.lookup and (num != key or self.lookup[key] > 1):
return True
return False
| |||
easy_000041
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
result = 0
for i in xrange(len(s)):
result *= 26
result += ord(s[i]) - ord('A') + 1
return result
| |||
easy_000042
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
def rotate(self, nums, k):
def reverse(nums, start, end):
while start < end:
nums[start], nums[end - 1] = nums[end - 1], nums[start]
start += 1
end -= 1
k %= len(nums)
reverse(nums, 0, len(nums))
reverse(nums, 0, k)
reverse(nums, k, len(nums))
# Time: O(n)
# Space: O(1)
from fractions import gcd
class Solution2(object):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
def rotate(self, nums, k):
def apply_cycle_permutation(k, offset, cycle_len, nums):
tmp = nums[offset]
for i in xrange(1, cycle_len):
nums[(offset + i * k) % len(nums)], tmp = tmp, nums[(offset + i * k) % len(nums)]
nums[offset] = tmp
k %= len(nums)
num_cycles = gcd(len(nums), k)
cycle_len = len(nums) / num_cycles
for i in xrange(num_cycles):
apply_cycle_permutation(k, i, cycle_len, nums)
# Time: O(n)
# Space: O(1)
class Solution3(object):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
def rotate(self, nums, k):
count = 0
start = 0
while count < len(nums):
curr = start
prev = nums[curr]
while True:
idx = (curr + k) % len(nums)
nums[idx], prev = prev, nums[idx]
curr = idx
count += 1
if start == curr:
break
start += 1
# Time: O(n)
# Space: O(n)
class Solution4(object):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
nums[:] = nums[len(nums) - k:] + nums[:len(nums) - k]
# Time: O(k * n)
# Space: O(1)
class Solution5(object):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
def rotate(self, nums, k):
while k > 0:
nums.insert(0, nums.pop())
k -= 1
| |||
easy_000043
|
easy
|
# Time : O(32)
# Space: O(1)
class Solution(object):
# @param n, an integer
# @return an integer
def reverseBits(self, n):
n = (n >> 16) | (n << 16)
n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8)
n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4)
n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2)
n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1)
return n
# Time : O(logn) = O(32)
# Space: O(1)
class Solution2(object):
# @param n, an integer
# @return an integer
def reverseBits(self, n):
result = 0
for i in xrange(32):
result <<= 1
result |= n & 1
n >>= 1
return result
| |||
easy_000044
|
easy
|
# Time: O(32), bit shift in python is not O(1), it's O(k), k is the number of bits shifted
# , see https://github.com/python/cpython/blob/2.7/Objects/longobject.c#L3652
# Space: O(1)
class Solution(object):
# @param n, an integer
# @return an integer
def hammingWeight(self, n):
n = (n & 0x55555555) + ((n >> 1) & 0x55555555)
n = (n & 0x33333333) + ((n >> 2) & 0x33333333)
n = (n & 0x0F0F0F0F) + ((n >> 4) & 0x0F0F0F0F)
n = (n & 0x00FF00FF) + ((n >> 8) & 0x00FF00FF)
n = (n & 0x0000FFFF) + ((n >> 16) & 0x0000FFFF)
return n
# Time: O(logn/4) = O(32/4 + 8*4) = O(32)
# Space: O(1)
# https://github.com/gcc-mirror/gcc/blob/master/libgcc/libgcc2.c#L856
class Solution2(object):
def __init__(self):
self.__popcount_tab = \
[ \
0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5, \
1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, \
1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, \
2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, \
1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, \
2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, \
2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, \
3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8 \
]
# @param n, an integer
# @return an integer
def hammingWeight(self, n):
result = 0
while n:
result += self.__popcount_tab[n & 0xff]
n >>= 8
return result
# Time: O(logn) = O(32)
# Space: O(1)
class Solution3(object):
# @param n, an integer
# @return an integer
def hammingWeight(self, n):
result = 0
while n:
n &= n - 1
result += 1
return result
# Time: O(logn) = O(32)
# Space: O(1)
class Solution4(object):
# @param n, an integer
# @return an integer
def hammingWeight(self, n: int) -> int:
b="{0:b}".format(n)
result=b.count("1")
return result
| |||
easy_000045
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
# @param num, a list of integer
# @return an integer
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
last, now = 0, 0
for i in nums:
last, now = now, max(last + i, now)
return now
| |||
easy_000046
|
easy
|
# Time: O(k), where k is the steps to be happy number
# Space: O(k)
class Solution(object):
# @param {integer} n
# @return {boolean}
def isHappy(self, n):
lookup = {}
while n != 1 and n not in lookup:
lookup[n] = True
n = self.nextNumber(n)
return n == 1
def nextNumber(self, n):
new = 0
for char in str(n):
new += int(char)**2
return new
| |||
easy_000047
|
easy
|
# Time: O(n)
# Space: O(1)
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
# @param {ListNode} head
# @param {integer} val
# @return {ListNode}
def removeElements(self, head, val):
dummy = ListNode(float("-inf"))
dummy.next = head
prev, curr = dummy, dummy.next
while curr:
if curr.val == val:
prev.next = curr.next
else:
prev = curr
curr = curr.next
return dummy.next
| |||
easy_000048
|
easy
|
# Time: O(n/2 + n/3 + ... + n/p) = O(nlog(logn)), see https://mathoverflow.net/questions/4596/on-the-series-1-2-1-3-1-5-1-7-1-11
# Space: O(n)
class Solution(object):
# @param {integer} n
# @return {integer}
def countPrimes(self, n):
if n <= 2:
return 0
is_prime = [True]*(n//2)
cnt = len(is_prime)
for i in xrange(3, n, 2):
if i * i >= n:
break
if not is_prime[i//2]:
continue
for j in xrange(i*i, n, 2*i):
if not is_prime[j//2]:
continue
cnt -= 1
is_prime[j//2] = False
return cnt
# Time: O(n)
# Space: O(n)
class Solution_TLE(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
def linear_sieve_of_eratosthenes(n):
primes = []
spf = [-1]*(n+1) # the smallest prime factor
for i in xrange(2, n+1):
if spf[i] == -1:
spf[i] = i
primes.append(i)
for p in primes:
if i*p > n or p > spf[i]:
break
spf[i*p] = p
return primes
return len(linear_sieve_of_eratosthenes(n-1))
| |||
easy_000049
|
easy
|
# Time: O(n)
# Space: O(1)
from itertools import izip # Generator version of zip.
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t):
return False
s2t, t2s = {}, {}
for p, w in izip(s, t):
if w not in s2t and p not in t2s:
s2t[w] = p
t2s[p] = w
elif w not in s2t or s2t[w] != p:
# Contradict mapping.
return False
return True
# Time: O(n)
# Space: O(1)
class Solution2(object):
def isIsomorphic(self, s, t):
if len(s) != len(t):
return False
return self.halfIsom(s, t) and self.halfIsom(t, s)
def halfIsom(self, s, t):
lookup = {}
for i in xrange(len(s)):
if s[i] not in lookup:
lookup[s[i]] = t[i]
elif lookup[s[i]] != t[i]:
return False
return True
| |||
easy_000050
|
easy
|
# Time: O(n)
# Space: O(1)
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
if self:
return "{} -> {}".format(self.val, repr(self.next))
# Iterative solution.
class Solution(object):
# @param {ListNode} head
# @return {ListNode}
def reverseList(self, head):
dummy = ListNode(float("-inf"))
while head:
dummy.next, head.next, head = head, dummy.next, head.next
return dummy.next
# Time: O(n)
# Space: O(n)
# Recursive solution.
class Solution2(object):
# @param {ListNode} head
# @return {ListNode}
def reverseList(self, head):
[begin, end] = self.reverseListRecu(head)
return begin
def reverseListRecu(self, head):
if not head:
return [None, None]
[begin, end] = self.reverseListRecu(head.next)
if end:
end.next = head
head.next = None
return [begin, head]
else:
return [head, head]
| |||
easy_000051
|
easy
|
# Time: O(n)
# Space: O(n)
class Solution(object):
# @param {integer[]} nums
# @param {integer} k
# @return {boolean}
def containsNearbyDuplicate(self, nums, k):
lookup = {}
for i, num in enumerate(nums):
if num not in lookup:
lookup[num] = i
else:
# If the value occurs before, check the difference.
if i - lookup[num] <= k:
return True
# Update the index of the value.
lookup[num] = i
return False
| |||
easy_000052
|
easy
|
# Time: O(1)
# Space: O(1)
class Solution(object):
# @param {integer} A
# @param {integer} B
# @param {integer} C
# @param {integer} D
# @param {integer} E
# @param {integer} F
# @param {integer} G
# @param {integer} H
# @return {integer}
def computeArea(self, A, B, C, D, E, F, G, H):
return (D - B) * (C - A) + \
(G - E) * (H - F) - \
max(0, (min(C, G) - max(A, E))) * \
max(0, (min(D, H) - max(B, F)))
| |||
easy_000053
|
easy
|
# Time: push: O(n), pop: O(1), top: O(1)
# Space: O(n)
import collections
class Queue(object):
def __init__(self):
self.data = collections.deque()
def push(self, x):
self.data.append(x)
def peek(self):
return self.data[0]
def pop(self):
return self.data.popleft()
def size(self):
return len(self.data)
def empty(self):
return len(self.data) == 0
class Stack(object):
# initialize your data structure here.
def __init__(self):
self.q_ = Queue()
# @param x, an integer
# @return nothing
def push(self, x):
self.q_.push(x)
for _ in xrange(self.q_.size() - 1):
self.q_.push(self.q_.pop())
# @return nothing
def pop(self):
self.q_.pop()
# @return an integer
def top(self):
return self.q_.peek()
# @return an boolean
def empty(self):
return self.q_.empty()
# Time: push: O(1), pop: O(n), top: O(1)
# Space: O(n)
class Stack2(object):
# initialize your data structure here.
def __init__(self):
self.q_ = Queue()
self.top_ = None
# @param x, an integer
# @return nothing
def push(self, x):
self.q_.push(x)
self.top_ = x
# @return nothing
def pop(self):
for _ in xrange(self.q_.size() - 1):
self.top_ = self.q_.pop()
self.q_.push(self.top_)
return self.q_.pop()
# @return an integer
def top(self):
return self.top_
# @return an boolean
def empty(self):
return self.q_.empty()
| |||
easy_000054
|
easy
|
# Time: O(n)
# Space: O(h)
import collections
# BFS solution.
class Queue(object):
def __init__(self):
self.data = collections.deque()
def push(self, x):
self.data.append(x)
def peek(self):
return self.data[0]
def pop(self):
return self.data.popleft()
def size(self):
return len(self.data)
def empty(self):
return len(self.data) == 0
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
# @param {TreeNode} root
# @return {TreeNode}
def invertTree(self, root):
if root is not None:
nodes = Queue()
nodes.push(root)
while not nodes.empty():
node = nodes.pop()
node.left, node.right = node.right, node.left
if node.left is not None:
nodes.push(node.left)
if node.right is not None:
nodes.push(node.right)
return root
# Time: O(n)
# Space: O(h)
# Stack solution.
class Solution2(object):
# @param {TreeNode} root
# @return {TreeNode}
def invertTree(self, root):
if root is not None:
nodes = []
nodes.append(root)
while nodes:
node = nodes.pop()
node.left, node.right = node.right, node.left
if node.left is not None:
nodes.append(node.left)
if node.right is not None:
nodes.append(node.right)
return root
# Time: O(n)
# Space: O(h)
# DFS, Recursive solution.
class Solution3(object):
# @param {TreeNode} root
# @return {TreeNode}
def invertTree(self, root):
if root is not None:
root.left, root.right = self.invertTree(root.right), \
self.invertTree(root.left)
return root
| |||
easy_000055
|
easy
|
# Time: O(1)
# Space: O(1)
class Solution(object):
# @param {integer} n
# @return {boolean}
def isPowerOfTwo(self, n):
return n > 0 and (n & (n - 1)) == 0
class Solution2(object):
# @param {integer} n
# @return {boolean}
def isPowerOfTwo(self, n):
return n > 0 and (n & ~-n) == 0
| |||
easy_000056
|
easy
|
# Time: O(1), amortized
# Space: O(n)
class MyQueue(object):
def __init__(self):
self.A, self.B = [], []
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.A.append(x)
def pop(self):
"""
:rtype: int
"""
self.peek()
return self.B.pop()
def peek(self):
"""
:rtype: int
"""
if not self.B:
while self.A:
self.B.append(self.A.pop())
return self.B[-1]
def empty(self):
"""
:rtype: bool
"""
return not self.A and not self.B
| |||
easy_000057
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
# @param {ListNode} head
# @return {boolean}
def isPalindrome(self, head):
reverse, fast = None, head
# Reverse the first half part of the list.
while fast and fast.next:
fast = fast.next.next
head.next, reverse, head = reverse, head, head.next
# If the number of the nodes is odd,
# set the head of the tail list to the next of the median node.
tail = head.next if fast else head
# Compare the reversed first half list with the second half list.
# And restore the reversed first half list.
is_palindrome = True
while reverse:
is_palindrome = is_palindrome and reverse.val == tail.val
reverse.next, head, reverse = head, reverse, reverse.next
tail = tail.next
return is_palindrome
| |||
easy_000058
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
# @param {TreeNode} root
# @param {TreeNode} p
# @param {TreeNode} q
# @return {TreeNode}
def lowestCommonAncestor(self, root, p, q):
s, b = sorted([p.val, q.val])
while not s <= root.val <= b:
# Keep searching since root is outside of [s, b].
root = root.left if s <= root.val else root.right
# s <= root.val <= b.
return root
| |||
easy_000059
|
easy
|
# Time: O(1)
# Space: O(1)
class Solution(object):
# @param {ListNode} node
# @return {void} Do not return anything, modify node in-place instead.
def deleteNode(self, node):
if node and node.next:
node_to_delete = node.next
node.val = node_to_delete.val
node.next = node_to_delete.next
del node_to_delete
| |||
easy_000060
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
# @param {string[]} words
# @param {string} word1
# @param {string} word2
# @return {integer}
def shortestDistance(self, words, word1, word2):
dist = float("inf")
i, index1, index2 = 0, None, None
while i < len(words):
if words[i] == word1:
index1 = i
elif words[i] == word2:
index2 = i
if index1 is not None and index2 is not None:
dist = min(dist, abs(index1 - index2))
i += 1
return dist
| |||
easy_000061
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
lookup = {'0':'0', '1':'1', '6':'9', '8':'8', '9':'6'}
# @param {string} num
# @return {boolean}
def isStrobogrammatic(self, num):
n = len(num)
for i in xrange((n+1) / 2):
if num[n-1-i] not in self.lookup or \
num[i] != self.lookup[num[n-1-i]]:
return False
return True
| |||
easy_000062
|
easy
|
# Time: O(nlogn)
# Space: O(n)
import collections
class Solution(object):
# @param {string[]} strings
# @return {string[][]}
def groupStrings(self, strings):
groups = collections.defaultdict(list)
for s in strings: # Grouping.
groups[self.hashStr(s)].append(s)
result = []
for key, val in groups.iteritems():
result.append(sorted(val))
return result
def hashStr(self, s):
base = ord(s[0])
hashcode = ""
for i in xrange(len(s)):
if ord(s[i]) - base >= 0:
hashcode += unichr(ord('a') + ord(s[i]) - base)
else:
hashcode += unichr(ord('a') + ord(s[i]) - base + 26)
return hashcode
| |||
easy_000063
|
easy
|
# Time: O(1)
# Space: O(1)
class Solution(object):
"""
:type num: int
:rtype: int
"""
def addDigits(self, num):
return (num - 1) % 9 + 1 if num > 0 else 0
| |||
easy_000064
|
easy
|
# Time: O(n)
# Space: O(1)
import collections
class Solution(object):
def canPermutePalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
return sum(v % 2 for v in collections.Counter(s).values()) < 2
| |||
easy_000065
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
def numWays(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
if n == 0:
return 0
elif n == 1:
return k
ways = [0] * 3
ways[0] = k
ways[1] = (k - 1) * ways[0] + k
for i in xrange(2, n):
ways[i % 3] = (k - 1) * (ways[(i - 1) % 3] + ways[(i - 2) % 3])
return ways[(n - 1) % 3]
# Time: O(n)
# Space: O(n)
# DP solution.
class Solution2(object):
def numWays(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
if n == 0:
return 0
elif n == 1:
return k
ways = [0] * n
ways[0] = k
ways[1] = (k - 1) * ways[0] + k
for i in xrange(2, n):
ways[i] = (k - 1) * (ways[i - 1] + ways[i - 2])
return ways[n - 1]
| |||
easy_000066
|
easy
|
# Time: O(logn)
# Space: O(1)
class Solution(object):
def firstBadVersion(self, n):
"""
:type n: int
:rtype: int
"""
left, right = 1, n
while left <= right:
mid = left + (right - left) / 2
if isBadVersion(mid): # noqa
right = mid - 1
else:
left = mid + 1
return left
| |||
easy_000067
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
pos = 0
for i in xrange(len(nums)):
if nums[i]:
nums[i], nums[pos] = nums[pos], nums[i]
pos += 1
def moveZeroes2(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
nums.sort(cmp=lambda a, b: 0 if b else -1)
class Solution2(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
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
| |||
easy_000068
|
easy
|
# Time: ctor: O(n), n is number of words in the dictionary.
# lookup: O(1)
# Space: O(k), k is number of unique words.
import collections
class ValidWordAbbr(object):
def __init__(self, dictionary):
"""
initialize your data structure here.
:type dictionary: List[str]
"""
self.lookup_ = collections.defaultdict(set)
for word in dictionary:
abbr = self.abbreviation(word)
self.lookup_[abbr].add(word)
def isUnique(self, word):
"""
check if a word is unique.
:type word: str
:rtype: bool
"""
abbr = self.abbreviation(word)
return self.lookup_[abbr] <= {word}
def abbreviation(self, word):
if len(word) <= 2:
return word
return word[0] + str(len(word)-2) + word[-1]
| |||
easy_000069
|
easy
|
# Time: O(n)
# Space: O(c), c is unique count of pattern
from itertools import izip # Generator version of zip.
class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
if len(pattern) != self.wordCount(str):
return False
w2p, p2w = {}, {}
for p, w in izip(pattern, self.wordGenerator(str)):
if w not in w2p and p not in p2w:
# Build mapping. Space: O(c)
w2p[w] = p
p2w[p] = w
elif w not in w2p or w2p[w] != p:
# Contradict mapping.
return False
return True
def wordCount(self, str):
cnt = 1 if str else 0
for c in str:
if c == ' ':
cnt += 1
return cnt
# Generate a word at a time without saving all the words.
def wordGenerator(self, str):
w = ""
for c in str:
if c == ' ':
yield w
w = ""
else:
w += c
yield w
# Time: O(n)
# Space: O(n)
class Solution2(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
words = str.split() # Space: O(n)
if len(pattern) != len(words):
return False
w2p, p2w = {}, {}
for p, w in izip(pattern, words):
if w not in w2p and p not in p2w:
# Build mapping. Space: O(c)
w2p[w] = p
p2w[p] = w
elif w not in w2p or w2p[w] != p:
# Contradict mapping.
return False
return True
| |||
easy_000070
|
easy
|
# Time: O(1)
# Space: O(1)
class Solution(object):
def canWinNim(self, n):
"""
:type n: int
:rtype: bool
"""
return n % 4 != 0
| |||
easy_000071
|
easy
|
# Time: O(n)
# Space: O(10) = O(1)
import operator
# One pass solution.
from collections import defaultdict, Counter
from itertools import izip, imap
class Solution(object):
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
A, B = 0, 0
lookup = defaultdict(int)
for s, g in izip(secret, guess):
if s == g:
A += 1
else:
B += int(lookup[s] < 0) + int(lookup[g] > 0)
lookup[s] += 1
lookup[g] -= 1
return "%dA%dB" % (A, B)
# Two pass solution.
class Solution2(object):
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
A = sum(imap(operator.eq, secret, guess))
B = sum((Counter(secret) & Counter(guess)).values()) - A
return "%dA%dB" % (A, B)
| |||
easy_000072
|
easy
|
# Time: ctor: O(n),
# lookup: O(1)
# Space: O(n)
class NumArray(object):
def __init__(self, nums):
"""
initialize your data structure here.
:type nums: List[int]
"""
self.accu = [0]
for num in nums:
self.accu.append(self.accu[-1] + num),
def sumRange(self, i, j):
"""
sum of elements nums[i..j], inclusive.
:type i: int
:type j: int
:rtype: int
"""
return self.accu[j + 1] - self.accu[i]
| |||
easy_000073
|
easy
|
# Time: O(1)
# Space: O(1)
import math
class Solution(object):
def __init__(self):
self.__max_log3 = int(math.log(0x7fffffff) / math.log(3))
self.__max_pow3 = 3 ** self.__max_log3
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and self.__max_pow3 % n == 0
class Solution2(object):
def isPowerOfThree(self, n):
return n > 0 and (math.log10(n)/math.log10(3)).is_integer()
| |||
easy_000074
|
easy
|
# Time: O(n)
# Space: O(h)
class Solution(object):
def depthSum(self, nestedList):
"""
:type nestedList: List[NestedInteger]
:rtype: int
"""
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)
| |||
easy_000075
|
easy
|
# Time: O(1)
# Space: O(1)
class Solution(object):
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
return num > 0 and (num & (num - 1)) == 0 and \
((num & 0b01010101010101010101010101010101) == num)
# Time: O(1)
# Space: O(1)
class Solution2(object):
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
while num and not (num & 0b11):
num >>= 2
return (num == 1)
class Solution3(object):
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
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
| |||
easy_000076
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
def reverseString(self, s):
"""
:type s: List[str]
:rtype: None Do not return anything, modify s in-place instead.
"""
i, j = 0, len(s) - 1
while i < j:
s[i], s[j] = s[j], s[i]
i += 1
j -= 1
| |||
easy_000077
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
vowels = "aeiou"
string = list(s)
i, j = 0, len(s) - 1
while i < j:
if string[i].lower() not in vowels:
i += 1
elif string[j].lower() not in vowels:
j -= 1
else:
string[i], string[j] = string[j], string[i]
i += 1
j -= 1
return "".join(string)
| |||
easy_000078
|
easy
|
# Time: O(1)
# Space: O(w)
from collections import deque
class MovingAverage(object):
def __init__(self, size):
"""
Initialize your data structure here.
:type size: int
"""
self.__size = size
self.__sum = 0
self.__q = deque()
def next(self, val):
"""
:type val: int
:rtype: float
"""
if len(self.__q) == self.__size:
self.__sum -= self.__q.popleft()
self.__sum += val
self.__q.append(val)
return 1.0 * self.__sum / len(self.__q)
| |||
easy_000079
|
easy
|
# Time: O(m + n)
# Space: O(min(m, n))
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
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
def intersection2(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
return list(set(nums1) & set(nums2))
# Time: O(max(m, n) * log(max(m, n)))
# Space: O(1)
# Binary search solution.
class Solution2(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
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:
left = mid + 1
return left
nums1.sort(), nums2.sort()
res = []
left = 0
for i in nums1:
left = binary_search(lambda x, y: x >= y, nums2, left, len(nums2), i)
if left != len(nums2) and nums2[left] == i:
res += i,
left = binary_search(lambda x, y: x > y, nums2, left, len(nums2), i)
return res
# Time: O(max(m, n) * log(max(m, n)))
# Space: O(1)
# Two pointers solution.
class Solution3(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
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]:
res += nums1[it1],
it1 += 1
it2 += 1
return res
| |||
easy_000080
|
easy
|
# If the given array is not sorted and the memory is unlimited:
# - Time: O(m + n)
# - Space: O(min(m, n))
# elif the given array is already sorted:
# if m << n or m >> n:
# - Time: O(min(m, n) * log(max(m, n)))
# - Space: O(1)
# else:
# - Time: O(m + n)
# - Soace: O(1)
# else: (the given array is not sorted and the memory is limited)
# - Time: O(max(m, n) * log(max(m, n)))
# - Space: O(1)
import collections
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
if len(nums1) > len(nums2):
return self.intersect(nums2, nums1)
lookup = collections.defaultdict(int)
for i in nums1:
lookup[i] += 1
res = []
for i in nums2:
if lookup[i] > 0:
res += i,
lookup[i] -= 1
return res
def intersect2(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
c = collections.Counter(nums1) & collections.Counter(nums2)
intersect = []
for i in c:
intersect.extend([i] * c[i])
return intersect
# If the given array is already sorted, and the memory is limited, and (m << n or m >> n).
# Time: O(min(m, n) * log(max(m, n)))
# Space: O(1)
# Binary search solution.
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
if len(nums1) > len(nums2):
return self.intersect(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:
left = mid + 1
return left
nums1.sort(), nums2.sort() # Make sure it is sorted, doesn't count in time.
res = []
left = 0
for i in nums1:
left = binary_search(lambda x, y: x >= y, nums2, left, len(nums2), i)
if left != len(nums2) and nums2[left] == i:
res += i,
left += 1
return res
# If the given array is already sorted, and the memory is limited or m ~ n.
# Time: O(m + n)
# Space: O(1)
# Two pointers solution.
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1.sort(), nums2.sort() # Make sure it is sorted, doesn't count in time.
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:
res += nums1[it1],
it1 += 1
it2 += 1
return res
# If the given array is not sorted, and the memory is limited.
# Time: O(max(m, n) * log(max(m, n)))
# Space: O(1)
# Two pointers solution.
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1.sort(), nums2.sort() # O(max(m, n) * log(max(m, n)))
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:
res += nums1[it1],
it1 += 1
it2 += 1
return res
| |||
easy_000081
|
easy
|
# Time: O(1), amortized
# Space: O(k), k is the max number of printed messages in last 10 seconds
import collections
class Logger(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.__dq = collections.deque()
self.__printed = set()
def shouldPrintMessage(self, timestamp, message):
"""
Returns true if the message should be printed in the given timestamp, otherwise returns false. The timestamp is in seconds granularity.
:type timestamp: int
:type message: str
:rtype: bool
"""
while self.__dq and self.__dq[0][0] <= timestamp - 10:
self.__printed.remove(self.__dq.popleft()[1])
if message in self.__printed:
return False
self.__dq.append((timestamp, message))
self.__printed.add(message)
return True
| |||
easy_000082
|
easy
|
# Time: O(1)
# Space: O(1)
class Solution(object):
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
bit_length = 32
neg_bit, mask = (1 << bit_length) >> 1, ~(~0 << bit_length)
a = (a | ~mask) if (a & neg_bit) else (a & mask)
b = (b | ~mask) if (b & neg_bit) else (b & mask)
while b:
carry = a & b
a ^= b
a = (a | ~mask) if (a & neg_bit) else (a & mask)
b = carry << 1
b = (b | ~mask) if (b & neg_bit) else (b & mask)
return a
def getSum2(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
# 32 bits integer max
MAX = 0x7FFFFFFF
# 32 bits interger min
MIN = 0x80000000
# mask to get last 32 bits
mask = 0xFFFFFFFF
while b:
# ^ get different bits and & gets double 1s, << moves carry
a, b = (a ^ b) & mask, ((a & b) << 1) & mask
# if a is negative, get a's 32 bits complement positive first
# then get 32-bit positive's Python complement negative
return a if a <= MAX else ~(a ^ mask)
def minus(self, a, b):
b = self.getSum(~b, 1)
return self.getSum(a, b)
def multiply(self, a, b):
isNeg = (a > 0) ^ (b > 0)
x = a if a > 0 else self.getSum(~a, 1)
y = b if b > 0 else self.getSum(~b, 1)
ans = 0
while y & 0x01:
ans = self.getSum(ans, x)
y >>= 1
x <<= 1
return self.getSum(~ans, 1) if isNeg else ans
def divide(self, a, b):
isNeg = (a > 0) ^ (b > 0)
x = a if a > 0 else self.getSum(~a, 1)
y = b if b > 0 else self.getSum(~b, 1)
ans = 0
for i in range(31, -1, -1):
if (x >> i) >= y:
x = self.minus(x, y << i)
ans = self.getSum(ans, 1 << i)
return self.getSum(~ans, 1) if isNeg else ans
| |||
easy_000083
|
easy
|
# Time: O(logn)
# Space: O(1)
class Solution(object):
def guessNumber(self, n):
"""
:type n: int
:rtype: int
"""
left, right = 1, n
while left <= right:
mid = left + (right - left) / 2
if guess(mid) <= 0: # noqa
right = mid - 1
else:
left = mid + 1
return left
| |||
easy_000084
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
counts = [0] * 26
letters = 0
for c in ransomNote:
if counts[ord(c) - ord('a')] == 0:
letters += 1
counts[ord(c) - ord('a')] += 1
for c in magazine:
counts[ord(c) - ord('a')] -= 1
if counts[ord(c) - ord('a')] == 0:
letters -= 1
if letters == 0:
break
return letters == 0
# Time: O(n)
# Space: O(1)
import collections
class Solution2(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
return not collections.Counter(ransomNote) - collections.Counter(magazine)
| |||
easy_000085
|
easy
|
# Time: O(n)
# Space: O(n)
from collections import defaultdict
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
lookup = defaultdict(int)
candidtates = set()
for i, c in enumerate(s):
if lookup[c]:
candidtates.discard(lookup[c])
else:
lookup[c] = i+1
candidtates.add(i+1)
return min(candidtates)-1 if candidtates else -1
| |||
easy_000086
|
easy
|
# Time: O(n)
# Space: O(1)
import operator
import collections
from functools import reduce
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
return chr(reduce(operator.xor, map(ord, s), 0) ^ reduce(operator.xor, map(ord, t), 0))
def findTheDifference2(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
t = list(t)
s = list(s)
for i in s:
t.remove(i)
return t[0]
def findTheDifference3(self, s, t):
return chr(reduce(operator.xor, map(ord, s + t)))
def findTheDifference4(self, s, t):
return list((collections.Counter(t) - collections.Counter(s)))[0]
def findTheDifference5(self, s, t):
s, t = sorted(s), sorted(t)
return t[-1] if s == t[:-1] else [x[1] for x in zip(s, t) if x[0] != x[1]][0]
| |||
easy_000087
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
def maxRotateFunction(self, A):
"""
:type A: List[int]
:rtype: int
"""
s = sum(A)
fi = 0
for i in xrange(len(A)):
fi += i * A[i]
result = fi
for i in xrange(1, len(A)+1):
fi += s - len(A) * A[-i]
result = max(result, fi)
return result
| |||
easy_000088
|
easy
|
# Time: O(logn)
# Space: O(1)
class Solution(object):
def findNthDigit(self, n):
"""
:type n: int
:rtype: int
"""
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
return nth_digit
| |||
easy_000089
|
easy
|
# Time: O(1)
# Space: O(1)
class Solution(object):
def readBinaryWatch(self, num):
"""
:type num: int
:rtype: List[str]
"""
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]
def readBinaryWatch2(self, num):
"""
:type num: int
:rtype: List[str]
"""
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]
| |||
easy_000090
|
easy
|
# Time: O(n)
# Space: O(h)
class Solution(object):
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
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(root, False)
| |||
easy_000091
|
easy
|
# Time: O(logn)
# Space: O(1)
class Solution(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
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(result)
| |||
easy_000092
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
def validWordAbbreviation(self, word, abbr):
"""
:type word: str
:type abbr: str
:rtype: bool
"""
i , digit = 0, 0
for c in abbr:
if c.isdigit():
if digit == 0 and c == '0':
return False
digit *= 10
digit += int(c)
else:
if digit:
i += digit
digit = 0
if i >= len(word) or word[i] != c:
return False
i += 1
if digit:
i += digit
return i == len(word)
| |||
easy_000093
|
easy
|
# Time: O(n)
# Space: O(1)
import collections
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
odds = 0
for k, v in collections.Counter(s).iteritems():
odds += v & 1
return len(s) - odds + int(odds > 0)
def longestPalindrome2(self, s):
"""
:type s: str
:rtype: int
"""
odd = sum(map(lambda x: x & 1, collections.Counter(s).values()))
return len(s) - odd + int(odd > 0)
| |||
easy_000094
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
result = []
for i in xrange(1, n+1):
if i % 15 == 0:
result.append("FizzBuzz")
elif i % 5 == 0:
result.append("Buzz")
elif i % 3 == 0:
result.append("Fizz")
else:
result.append(str(i))
return result
def fizzBuzz2(self, n):
"""
:type n: int
:rtype: List[str]
"""
l = [str(x) for x in range(n + 1)]
l3 = range(0, n + 1, 3)
l5 = range(0, n + 1, 5)
for i in l3:
l[i] = 'Fizz'
for i in l5:
if l[i] == 'Fizz':
l[i] += 'Buzz'
else:
l[i] = 'Buzz'
return l[1:]
def fizzBuzz3(self, n):
return ['Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or str(i) for i in range(1, n + 1)]
def fizzBuzz4(self, n):
return ['FizzBuzz'[i % -3 & -4:i % -5 & 8 ^ 12] or repr(i) for i in range(1, n + 1)]
| |||
easy_000095
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = 0
top = [float("-inf")] * 3
for num in nums:
if num > top[0]:
top[0], top[1], top[2] = num, top[0], top[1]
count += 1
elif num != top[0] and num > top[1]:
top[1], top[2] = num, top[1]
count += 1
elif num != top[0] and num != top[1] and num >= top[2]:
top[2] = num
count += 1
if count < 3:
return top[0]
return top[2]
| |||
easy_000096
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
result = int(len(s) and s[-1] != ' ')
for i in xrange(1, len(s)):
if s[i] == ' ' and s[i-1] != ' ':
result += 1
return result
def countSegments2(self, s):
"""
:type s: str
:rtype: int
"""
return len([i for i in s.strip().split(' ') if i])
| |||
easy_000097
|
easy
|
# Time: O(n)
# Space: O(h)
import collections
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
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, sum, lookup)
lookup[curr] -= 1
if lookup[curr] == 0:
del lookup[curr]
return result
lookup = collections.defaultdict(int)
lookup[0] = 1
return pathSumHelper(root, 0, sum, lookup)
# Time: O(n^2)
# Space: O(h)
class Solution2(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
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) + \
self.pathSum(root.left, sum) + \
self.pathSum(root.right, sum)
| |||
easy_000098
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
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
left += 1
if right - left + 1 == len(p):
result.append(left)
right += 1
return result
| |||
easy_000099
|
easy
|
# Time: O(logn)
# Space: O(1)
import math
class Solution(object):
def arrangeCoins(self, n):
"""
:type n: int
:rtype: int
"""
return int((math.sqrt(8*n+1)-1) / 2) # sqrt is O(logn) time.
# Time: O(logn)
# Space: O(1)
class Solution2(object):
def arrangeCoins(self, n):
"""
:type n: int
:rtype: int
"""
def check(mid, n):
return mid*(mid+1) <= 2*n
left, right = 1, n
while left <= right:
mid = left + (right-left)//2
if not check(mid, n):
right = mid-1
else:
left = mid+1
return right
| |||
easy_000100
|
easy
|
# Time: O(n)
# Space: O(1)
class Solution(object):
def compress(self, chars):
"""
:type chars: List[str]
:rtype: int
"""
anchor, write = 0, 0
for read, c in enumerate(chars):
if read+1 == len(chars) or chars[read+1] != c:
chars[write] = chars[anchor]
write += 1
if read > anchor:
n, left = read-anchor+1, write
while n > 0:
chars[write] = chr(n%10+ord('0'))
write += 1
n /= 10
right = write-1
while left < right:
chars[left], chars[right] = chars[right], chars[left]
left += 1
right -= 1
anchor = read+1
return write
|
pretty_name: "CodeOCR Dataset (Python Code Images + Ground Truth)" license: mit language: - en task_categories: - image-to-text tags: - ocr - code - python - leetcode - synthetic - computer-vision size_categories: - 1K<n<10K
CodeOCR Dataset (Python Code Images + Ground Truth)
This dataset is designed for Optical Character Recognition (OCR) of source code.
Each example pairs Python code (ground-truth text) with image renderings of that code (light/dark themes) and a real photo.
Dataset Summary
- Language: Python (text ground truth), images of code
- Splits:
easy,medium,hard - Total examples: 1,000
easy: 700medium: 200hard: 100
- Modalities: image + text
What is “ground truth” here?
The code field is exactly the content of gt.py used to generate the synthetic renderings.
During dataset creation, code is normalized to ensure stable GT properties:
- UTF-8 encoding
- newline normalization to LF (
\n) - tabs expanded to 4 spaces
- syntax checked with Python
compile()(syntax/indentation correctness)
This makes the dataset suitable for training/evaluating OCR models that output plain code text.
Data Fields
Each row contains:
id(string): sample identifier (e.g.,easy_000123)difficulty(string):easy/medium/hardcode(string): ground-truth Python coderender_light(image): synthetic rendering (light theme)render_dark(image): synthetic rendering (dark theme)photo(image): real photo of the code
How to Use
Load with 🤗 Datasets
from datasets import load_dataset
ds = load_dataset("maksonchek/codeocr-dataset")
print(ds)
print(ds["easy"][0].keys())
Access code and images
ex = ds["easy"][0]
# Ground-truth code
print(ex["code"][:500])
# Images are stored as `datasets.Image` features.
render = ex["render_light"]
print(render)
If your environment returns image dicts with local paths:
from PIL import Image
img = Image.open(ex["render_light"]["path"])
img.show()
Real photo (always present in this dataset):
from PIL import Image
photo = Image.open(ex["photo"]["path"])
photo.show()
Dataset Creation
1) Code selection
Python solutions were collected from an open-source repository of LeetCode solutions (MIT licensed).
2) Normalization to produce stable GT
The collected code is written into gt.py after:
- newline normalization to LF
- tab expansion to 4 spaces
- basic cleanup (no hidden control characters)
- Python syntax check via
compile()
3) Synthetic rendering
Synthetic images are generated from the normalized gt.py in:
- light theme (
render_light) - dark theme (
render_dark)
4) Real photos
Real photos are manually captured and linked for every sample.
Statistics (high-level)
Average code length by difficulty (computed on this dataset):
easy: ~27 lines, ~669 charsmedium: ~36 lines, ~997 charshard: ~55 lines, ~1767 chars
(Exact values may vary if the dataset is extended.)
Intended Use
- OCR for programming code
- robust text extraction from screenshot-like renders and real photos
- benchmarking OCR pipelines for code formatting / indentation preservation
Not Intended Use
- generating or re-distributing problem statements
- competitive programming / cheating use-cases
Limitations
- Code is checked for syntax correctness, but not necessarily for runtime correctness.
- Rendering style is controlled and may differ from real-world photos.
License & Attribution
This dataset is released under the MIT License.
The included solution code is derived from kamyu104/LeetCode-Solutions (MIT License):
https://github.com/kamyu104/LeetCode-Solutions
If you use this dataset in academic work, please cite the dataset and credit the original solution repository.
Citation
BibTeX
@dataset{codeocr_leetcode_2025,
author = {Maksonchek},
title = {CodeOCR Dataset (Python Code Images + Ground Truth)},
year = {2025},
publisher = {Hugging Face},
url = {https://huggingface.co/datasets/maksonchek/codeocr-dataset}
}
- Downloads last month
- -