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 [loo... | |||
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... | |||
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 s... | |||
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 s... | |||
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.po... | |||
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: L... | |||
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(se... | |||
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... | |||
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:
... | |||
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):
... | |||
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... | |||
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 ... | |||
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)
retu... | |||
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
r... | |||
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] +... | |||
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... | |||
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))]
... | |||
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:
ru... | |||
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):
... | |||
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... | |||
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:
... | |||
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 ... | |||
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)... | |||
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:
... | |||
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, ... | |||
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... | |||
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 + re... | |||
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 ... | |||
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, pric... | |||
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 ... | |||
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, s... | |||
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.sta... | |||
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):
d... | |||
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 cu... | |||
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:
... | |||
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:
... | |||
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.
... | |||
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[en... | |||
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 & 0xcccccc... | |||
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 ... | |||
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)
ret... | |||
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
... | |||
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"))
... | |||
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... | |||
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 = {}, {}
... | |||
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
# @retur... | |||
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
els... | |||
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,... | |||
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()
... | |||
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... | |||
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) =... | |||
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()
... | |||
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, rev... | |||
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 ro... | |||
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.ne... | |||
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):
... | |||
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 \
... | |||
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)
resul... | |||
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) *... | |||
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 = ... | |||
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[... | |||
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]
"""... | |||
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(st... | |||
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
"""
... | |||
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),
de... | |||
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... | |||
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():
... | |||
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 Soluti... | |||
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
... | |||
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... | |||
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):
... | |||
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)
looku... | |||
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 arr... | |||
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 sho... | |||
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)
... | |||
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 - ... | |||
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'... | |||
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]:
... | |||
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.xo... | |||
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):
... | |||
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
... | |||
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... | |||
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:
... | |||
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:
res... | |||
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':
... | |||
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)
... | |||
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:
... | |||
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... | |||
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... | |||
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
... | |||
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
... | |||
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,... | |||
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] = c... |
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
- 37