Dataset Viewer
Auto-converted to Parquet Duplicate
task_id
stringlengths
16
16
prompt
stringlengths
113
327
canonical_solution
stringclasses
20 values
test
stringclasses
20 values
entry_point
stringclasses
20 values
GenEval/LEV2_001
Write a function `balanced_split(nums)` that splits a list of positive integers into two non-empty subsets such that the absolute difference of their sums is minimized. Return the minimum possible difference. You may assume len(nums) >= 2. (variant 1)
def balanced_split(nums): total = sum(nums) n = len(nums) target = total // 2 dp = [False] * (target+1) dp[0] = True for num in nums: for s in range(target, num-1, -1): if dp[s-num]: dp[s] = True best = total for s in range(1, target+1): if dp[...
def check(): assert balanced_split([1,2,3]) == 0 assert balanced_split([1,5,11,5]) == 0 assert balanced_split([7,3]) == 4 assert balanced_split([10,20,15,5]) == 0
balanced_split
GenEval/LEV2_002
You are given a starting binary string S containing only '0' and '1'. The infinite expansion is defined by repeatedly replacing S with S + flip(reverse(S)), where flip swaps '0' and '1'. Implement `kth_char(S, k)` to return the k-th character (1-indexed) in the infinite expansion without building the full string. (var...
def kth_char(S, k): n = len(S) if k <= n: return S[k-1] length = n while length < k: length *= 2 def solve(length_now, k_pos): if k_pos <= n: return S[k_pos-1] half = length_now // 2 if k_pos <= half: return solve(half, k_pos) m...
def check(): assert kth_char("0",1) == "0" assert kth_char("01",3) == "1" assert kth_char("01",4) == "0" assert kth_char("1",2) == "0"
kth_char
GenEval/LEV2_003
Given two equal-length strings s1 and s2 consisting only of characters 'x' and 'y', return the minimum number of swaps (a swap exchanges positions in the same string) required to make s1 equal s2. Return -1 if impossible. Implement `min_swaps_to_equal(s1, s2)`. (variant 1)
def min_swaps_to_equal(s1, s2): if len(s1) != len(s2): return -1 xy = 0 yx = 0 for a,b in zip(s1, s2): if a == 'x' and b == 'y': xy += 1 elif a == 'y' and b == 'x': yx += 1 if (xy + yx) % 2 == 1: return -1 return xy//2 + yx//2 + 2*(xy%2)
def check(): assert min_swaps_to_equal('xxyy','yyxx') == 2 assert min_swaps_to_equal('xy','yx') == 1 assert min_swaps_to_equal('xx','yy') == -1 assert min_swaps_to_equal('xxyyxy','yyxxxy') == 2
min_swaps_to_equal
GenEval/LEV2_004
Write `longest_ap(arr)` that returns the length of the longest arithmetic subsequence (not necessarily contiguous) in arr. (variant 1)
def longest_ap(arr): n = len(arr) if n <= 2: return n dp = [dict() for _ in range(n)] best = 2 for i in range(n): for j in range(i): diff = arr[i] - arr[j] dp[i][diff] = dp[j].get(diff, 1) + 1 if dp[i][diff] > best: best = dp[i][dif...
def check(): assert longest_ap([1,2,3,4]) == 4 assert longest_ap([1,7,10,15,27,29]) == 3 assert longest_ap([9,4,7,2,10]) == 3 assert longest_ap([20,1,15,3,10,5,8]) == 4
longest_ap
GenEval/LEV2_005
Implement `count_arrays(n, k)` that returns the number of permutations of [1..n] that have exactly k inversions. Use DP (no combinatorics expected). (variant 1)
def count_arrays(n, k): if k < 0: return 0 dp = [[0] * (k+1) for _ in range(n+1)] dp[0][0] = 1 for i in range(1, n+1): for j in range(k+1): total = 0 for x in range(min(j, i-1)+1): total += dp[i-1][j-x] dp[i][j] = total return dp[n]...
def check(): assert count_arrays(3,0) == 1 assert count_arrays(3,1) == 2 assert count_arrays(4,3) == 6 assert count_arrays(5,5) == 22
count_arrays
GenEval/LEV2_006
Given cost[i] (cost to move from i to i+1) and teleport list teleport where teleport[i] = j or None, meaning you can jump from i to j at zero cost, implement `min_path_cost(cost, teleport)` to return minimum cost to reach last index from 0. (variant 1)
def min_path_cost(cost, teleport): import heapq n = len(cost) + 1 adj = [[] for _ in range(n)] for i in range(n-1): adj[i].append((i+1, cost[i])) for i, t in enumerate(teleport): if t is not None and 0 <= t < n: adj[i].append((t, 0)) INF = 10**18 dist = [INF] * n ...
def check(): assert min_path_cost([1,2,3],[None,None,None]) == 6 assert min_path_cost([5,5,5],[3,None,None]) == 0 assert min_path_cost([2,2,2,2],[None,4,None,None]) == 6
min_path_cost
GenEval/LEV2_007
Implement `max_xor(arr)` that returns the maximum XOR of any pair in arr. Use bitwise trie approach. (variant 1)
class Node: def __init__(self): self.child = {} def max_xor(arr): root = Node() def insert(num): cur = root for i in range(31, -1, -1): bit = (num >> i) & 1 if bit not in cur.child: cur.child[bit] = Node() cur = cur.child[bit] d...
def check(): assert max_xor([1,2,3]) == 3 assert max_xor([8,1,2,12]) == 15 assert max_xor([4,6,7]) == 3
max_xor
GenEval/LEV2_008
Write `count_pal_subseq(s)` that counts distinct palindromic subsequences of length >= 2. Return integer count. (variant 1)
def count_pal_subseq(s): n = len(s) if n < 2: return 0 dp = [[0] * n for _ in range(n)] for i in range(n): dp[i][i] = 1 for length in range(2, n+1): for i in range(0, n-length+1): j = i + length - 1 if s[i] == s[j]: dp[i][j] = dp[i+1][j...
def check(): assert count_pal_subseq('aaa') == 3 assert count_pal_subseq('abca') == 5 assert count_pal_subseq('abc') == 0
count_pal_subseq
GenEval/LEV2_009
Implement `smallest_num(d, s)` that returns the smallest non-negative integer (as string) whose digit-sum equals s and is divisible by d. Return -1 if impossible. (variant 1)
from collections import deque def smallest_num(d, s): if s == 0: return '0' if 0 % d == 0 else -1 visited = [[False] * (s+1) for _ in range(d)] parent = {} q = deque() q.append((0, 0)) visited[0][0] = True while q: rem, digit_sum = q.popleft() if digit_sum == s and re...
def check(): assert smallest_num(3,3) == '3' assert smallest_num(5,10) == '55' assert smallest_num(7,7) == '7'
smallest_num
GenEval/LEV2_010
Implement `eval_expr(expr)` to evaluate mathematical expression `expr` containing non-negative integers and operators +, -, *, / and parentheses. Division is integer division truncating toward zero. There will be no unary operators. You may assume expression is valid. (variant 1)
def eval_expr(expr): def precedence(op): if op in ('+', '-'): return 1 if op in ('*', '/'): return 2 return 0 def apply_op(a, b, op): if op == '+': return a + b if op == '-': return a - b if op == '*': return a * b if op == '/': if b == 0: rais...
def check(): assert eval_expr("2+3*4") == 14 assert eval_expr("(2+3)*4") == 20 assert eval_expr("10/3") == 3 assert eval_expr("10-2*3") == 4
eval_expr
GenEval/LEV2_011
Implement `word_break(s, words)` which returns True if string s can be segmented into a sequence of one or more dictionary words in set `words`. (variant 1)
def word_break(s, words): n = len(s) dp = [False] * (n+1) dp[0] = True for i in range(1, n+1): for j in range(i): if dp[j] and s[j:i] in words: dp[i] = True break return dp[n]
def check(): assert word_break("leetcode", {"leet","code"}) assert not word_break("catsandog", {"cats","dog","sand","and","cat"})
word_break
GenEval/LEV2_012
Implement two functions: `serialize(root)` and `deserialize(s)` where s is a string produced by serialize. Use preorder traversal and '#' for nulls. For testing, use tuple-built trees represented as nested tuples: e.g., (val, left, right) or None. (variant 1)
def serialize(root): res = [] def dfs(node): if node is None: res.append('#') return val, left, right = node res.append(str(val)) dfs(left) dfs(right) dfs(root) return ','.join(res) def deserialize(s): parts = s.split(',') idx = 0 ...
def check(): tree = (1, (2, None, None), (3, None, None)) s = serialize(tree) assert deserialize(s) == tree assert serialize(None) == '#'
serialize_deserialize
GenEval/LEV2_013
Implement `sliding_median(nums, k)` returning list of medians for each window of size k over nums. For even k, use the lower median (floor). (variant 1)
import heapq def sliding_median(nums, k): if k == 0: return [] lo = [] # max heap (invert sign) hi = [] # min heap delayed = {} def add(num): if not lo or num <= -lo[0]: heapq.heappush(lo, -num) else: heapq.heappush(hi, num) balance() def remove(...
def check(): assert sliding_median([1,3,-1,-3,5,3,6,7],3) == [1,-1,-1,3,5,6] assert sliding_median([1,2,3,4],2) == [1,2,3]
sliding_median
GenEval/LEV2_014
Given an n x n matrix where each row and column is sorted in ascending order, implement `kth_smallest(matrix, k)` returning the k-th smallest element. (variant 1)
import heapq def kth_smallest(matrix, k): n = len(matrix) if n == 0: return None pq = [] for i in range(min(n, k)): heapq.heappush(pq, (matrix[i][0], i, 0)) val = None for _ in range(k): val, r, c = heapq.heappop(pq) if c+1 < len(matrix[r]): heapq.heappush(pq,...
def check(): mat = [[1,5,9],[10,11,13],[12,13,15]] assert kth_smallest(mat, 8) == 13 assert kth_smallest([[1]],1) == 1
kth_smallest
GenEval/LEV2_015
Implement `tiling_ways(n)` that returns the number of ways to tile a 2 x n board using 2x1 dominos and L-shaped trominoes. Return integer. (Standard DP variant) (variant 1)
def tiling_ways(n): if n == 0: return 1 if n == 1: return 1 a, b = 1, 1 extra = 0 for i in range(2, n+1): cur = a + b + extra extra = b a, b = b, cur return b
def check(): assert tiling_ways(0) == 1 assert tiling_ways(1) == 1 assert tiling_ways(2) == 2 assert isinstance(tiling_ways(5), int)
tiling_ways
GenEval/LEV2_016
Implement `min_window(s, t)` that returns the minimum window substring of s which contains all characters of t (with multiplicity). If none exists, return empty string. (variant 1)
from collections import Counter def min_window(s, t): if not t or not s: return "" need = Counter(t) missing = len(t) left = 0 start = 0 min_len = float('inf') for right, ch in enumerate(s): if need[ch] > 0: missing -= 1 need[ch] -= 1 while missing == 0: ...
def check(): assert min_window("ADOBECODEBANC","ABC") == "BANC" assert min_window("a","a") == "a" assert min_window("a","aa") == ""
min_window
GenEval/LEV2_017
Implement `num_islands(grid)` that counts the number of connected islands of '1's in the grid (4-directional). (variant 1)
def num_islands(grid): if not grid: return 0 m = len(grid); n = len(grid[0]) visited = [[False]*n for _ in range(m)] def dfs(i,j): if i<0 or j<0 or i>=m or j>=n: return if visited[i][j] or grid[i][j] != '1': return visited[i][j] = True for di,dj in ((1,0),(-1,0),(0,1),(0,...
def check(): g = ["11110","11010","11000","00000"] assert num_islands([list(row) for row in g]) == 1 g2 = ["11000","11000","00100","00011"] assert num_islands([list(row) for row in g2]) == 3
num_islands
GenEval/LEV2_018
Given a string s containing only digits, implement `num_decodings(s)` that returns the number of ways to decode it to letters (A=1..Z=26). '0' handling as in standard problem. (variant 1)
def num_decodings(s): if not s: return 0 n = len(s) dp = [0]*(n+1) dp[0] = 1 for i in range(1, n+1): if s[i-1] != '0': dp[i] += dp[i-1] if i>=2 and s[i-2] != '0' and 1 <= int(s[i-2:i]) <= 26: dp[i] += dp[i-2] return dp[n]
def check(): assert num_decodings("12") == 2 assert num_decodings("226") == 3 assert num_decodings("0") == 0
num_decodings
GenEval/LEV2_019
Implement `serialize_graph(adj)` and `deserialize_graph(s)` where adj is dict node->list(neighbors) with integer nodes. Use deterministic serialization. Tests will compare roundtrip. (variant 1)
def serialize_graph(adj): parts = [] for node in sorted(adj.keys()): parts.append(str(node) + ':' + ','.join(map(str, sorted(adj[node])))) return '|'.join(parts) def deserialize_graph(s): if s == '': return {} adj = {} for part in s.split('|'): node, neigh = part.split(':') ...
def check(): adj = {1:[2,3], 2:[3], 3:[]} s = serialize_graph(adj) assert deserialize_graph(s) == {1:[2,3],2:[3],3:[]} assert serialize_graph({}) == ''
serialize_graph
GenEval/LEV2_020
Given a tree represented as adjacency dict and values dict (node -> value), implement `max_independent_set_tree(root, adj, val)` returning max sum of selected nodes with no two adjacent. Root given but tree is undirected; parent relations to be inferred. (variant 1)
def max_independent_set_tree(root, adj, val): def dfs(u, parent): incl = val[u] excl = 0 for v in adj.get(u, []): if v == parent: continue a, b = dfs(v, u) incl += b excl += max(a, b) return incl, excl a,b = dfs(root, None) retu...
def check(): adj = {1:[2,3],2:[1],3:[1]}; val={1:3,2:2,3:1} assert max_independent_set_tree(1, adj, val) == 3 adj2 = {1:[2],2:[1,3],3:[2]}; val2={1:1,2:2,3:3} assert max_independent_set_tree(1, adj2, val2) == 4
max_independent_set_tree
GenEval/LEV2_021
Write a function `balanced_split(nums)` that splits a list of positive integers into two non-empty subsets such that the absolute difference of their sums is minimized. Return the minimum possible difference. You may assume len(nums) >= 2. (variant 2)
def balanced_split(nums): total = sum(nums) n = len(nums) target = total // 2 dp = [False] * (target+1) dp[0] = True for num in nums: for s in range(target, num-1, -1): if dp[s-num]: dp[s] = True best = total for s in range(1, target+1): if dp[...
def check(): assert balanced_split([1,2,3]) == 0 assert balanced_split([1,5,11,5]) == 0 assert balanced_split([7,3]) == 4 assert balanced_split([10,20,15,5]) == 0
balanced_split
GenEval/LEV2_022
You are given a starting binary string S containing only '0' and '1'. The infinite expansion is defined by repeatedly replacing S with S + flip(reverse(S)), where flip swaps '0' and '1'. Implement `kth_char(S, k)` to return the k-th character (1-indexed) in the infinite expansion without building the full string. (var...
def kth_char(S, k): n = len(S) if k <= n: return S[k-1] length = n while length < k: length *= 2 def solve(length_now, k_pos): if k_pos <= n: return S[k_pos-1] half = length_now // 2 if k_pos <= half: return solve(half, k_pos) m...
def check(): assert kth_char("0",1) == "0" assert kth_char("01",3) == "1" assert kth_char("01",4) == "0" assert kth_char("1",2) == "0"
kth_char
GenEval/LEV2_023
Given two equal-length strings s1 and s2 consisting only of characters 'x' and 'y', return the minimum number of swaps (a swap exchanges positions in the same string) required to make s1 equal s2. Return -1 if impossible. Implement `min_swaps_to_equal(s1, s2)`. (variant 2)
def min_swaps_to_equal(s1, s2): if len(s1) != len(s2): return -1 xy = 0 yx = 0 for a,b in zip(s1, s2): if a == 'x' and b == 'y': xy += 1 elif a == 'y' and b == 'x': yx += 1 if (xy + yx) % 2 == 1: return -1 return xy//2 + yx//2 + 2*(xy%2)
def check(): assert min_swaps_to_equal('xxyy','yyxx') == 2 assert min_swaps_to_equal('xy','yx') == 1 assert min_swaps_to_equal('xx','yy') == -1 assert min_swaps_to_equal('xxyyxy','yyxxxy') == 2
min_swaps_to_equal
GenEval/LEV2_024
Write `longest_ap(arr)` that returns the length of the longest arithmetic subsequence (not necessarily contiguous) in arr. (variant 2)
def longest_ap(arr): n = len(arr) if n <= 2: return n dp = [dict() for _ in range(n)] best = 2 for i in range(n): for j in range(i): diff = arr[i] - arr[j] dp[i][diff] = dp[j].get(diff, 1) + 1 if dp[i][diff] > best: best = dp[i][dif...
def check(): assert longest_ap([1,2,3,4]) == 4 assert longest_ap([1,7,10,15,27,29]) == 3 assert longest_ap([9,4,7,2,10]) == 3 assert longest_ap([20,1,15,3,10,5,8]) == 4
longest_ap
GenEval/LEV2_025
Implement `count_arrays(n, k)` that returns the number of permutations of [1..n] that have exactly k inversions. Use DP (no combinatorics expected). (variant 2)
def count_arrays(n, k): if k < 0: return 0 dp = [[0] * (k+1) for _ in range(n+1)] dp[0][0] = 1 for i in range(1, n+1): for j in range(k+1): total = 0 for x in range(min(j, i-1)+1): total += dp[i-1][j-x] dp[i][j] = total return dp[n]...
def check(): assert count_arrays(3,0) == 1 assert count_arrays(3,1) == 2 assert count_arrays(4,3) == 6 assert count_arrays(5,5) == 22
count_arrays
GenEval/LEV2_026
Given cost[i] (cost to move from i to i+1) and teleport list teleport where teleport[i] = j or None, meaning you can jump from i to j at zero cost, implement `min_path_cost(cost, teleport)` to return minimum cost to reach last index from 0. (variant 2)
def min_path_cost(cost, teleport): import heapq n = len(cost) + 1 adj = [[] for _ in range(n)] for i in range(n-1): adj[i].append((i+1, cost[i])) for i, t in enumerate(teleport): if t is not None and 0 <= t < n: adj[i].append((t, 0)) INF = 10**18 dist = [INF] * n ...
def check(): assert min_path_cost([1,2,3],[None,None,None]) == 6 assert min_path_cost([5,5,5],[3,None,None]) == 0 assert min_path_cost([2,2,2,2],[None,4,None,None]) == 6
min_path_cost
GenEval/LEV2_027
Implement `max_xor(arr)` that returns the maximum XOR of any pair in arr. Use bitwise trie approach. (variant 2)
class Node: def __init__(self): self.child = {} def max_xor(arr): root = Node() def insert(num): cur = root for i in range(31, -1, -1): bit = (num >> i) & 1 if bit not in cur.child: cur.child[bit] = Node() cur = cur.child[bit] d...
def check(): assert max_xor([1,2,3]) == 3 assert max_xor([8,1,2,12]) == 15 assert max_xor([4,6,7]) == 3
max_xor
GenEval/LEV2_028
Write `count_pal_subseq(s)` that counts distinct palindromic subsequences of length >= 2. Return integer count. (variant 2)
def count_pal_subseq(s): n = len(s) if n < 2: return 0 dp = [[0] * n for _ in range(n)] for i in range(n): dp[i][i] = 1 for length in range(2, n+1): for i in range(0, n-length+1): j = i + length - 1 if s[i] == s[j]: dp[i][j] = dp[i+1][j...
def check(): assert count_pal_subseq('aaa') == 3 assert count_pal_subseq('abca') == 5 assert count_pal_subseq('abc') == 0
count_pal_subseq
GenEval/LEV2_029
Implement `smallest_num(d, s)` that returns the smallest non-negative integer (as string) whose digit-sum equals s and is divisible by d. Return -1 if impossible. (variant 2)
from collections import deque def smallest_num(d, s): if s == 0: return '0' if 0 % d == 0 else -1 visited = [[False] * (s+1) for _ in range(d)] parent = {} q = deque() q.append((0, 0)) visited[0][0] = True while q: rem, digit_sum = q.popleft() if digit_sum == s and re...
def check(): assert smallest_num(3,3) == '3' assert smallest_num(5,10) == '55' assert smallest_num(7,7) == '7'
smallest_num
GenEval/LEV2_030
Implement `eval_expr(expr)` to evaluate mathematical expression `expr` containing non-negative integers and operators +, -, *, / and parentheses. Division is integer division truncating toward zero. There will be no unary operators. You may assume expression is valid. (variant 2)
def eval_expr(expr): def precedence(op): if op in ('+', '-'): return 1 if op in ('*', '/'): return 2 return 0 def apply_op(a, b, op): if op == '+': return a + b if op == '-': return a - b if op == '*': return a * b if op == '/': if b == 0: rais...
def check(): assert eval_expr("2+3*4") == 14 assert eval_expr("(2+3)*4") == 20 assert eval_expr("10/3") == 3 assert eval_expr("10-2*3") == 4
eval_expr
GenEval/LEV2_031
Implement `word_break(s, words)` which returns True if string s can be segmented into a sequence of one or more dictionary words in set `words`. (variant 2)
def word_break(s, words): n = len(s) dp = [False] * (n+1) dp[0] = True for i in range(1, n+1): for j in range(i): if dp[j] and s[j:i] in words: dp[i] = True break return dp[n]
def check(): assert word_break("leetcode", {"leet","code"}) assert not word_break("catsandog", {"cats","dog","sand","and","cat"})
word_break
GenEval/LEV2_032
Implement two functions: `serialize(root)` and `deserialize(s)` where s is a string produced by serialize. Use preorder traversal and '#' for nulls. For testing, use tuple-built trees represented as nested tuples: e.g., (val, left, right) or None. (variant 2)
def serialize(root): res = [] def dfs(node): if node is None: res.append('#') return val, left, right = node res.append(str(val)) dfs(left) dfs(right) dfs(root) return ','.join(res) def deserialize(s): parts = s.split(',') idx = 0 ...
def check(): tree = (1, (2, None, None), (3, None, None)) s = serialize(tree) assert deserialize(s) == tree assert serialize(None) == '#'
serialize_deserialize
GenEval/LEV2_033
Implement `sliding_median(nums, k)` returning list of medians for each window of size k over nums. For even k, use the lower median (floor). (variant 2)
import heapq def sliding_median(nums, k): if k == 0: return [] lo = [] # max heap (invert sign) hi = [] # min heap delayed = {} def add(num): if not lo or num <= -lo[0]: heapq.heappush(lo, -num) else: heapq.heappush(hi, num) balance() def remove(...
def check(): assert sliding_median([1,3,-1,-3,5,3,6,7],3) == [1,-1,-1,3,5,6] assert sliding_median([1,2,3,4],2) == [1,2,3]
sliding_median
GenEval/LEV2_034
Given an n x n matrix where each row and column is sorted in ascending order, implement `kth_smallest(matrix, k)` returning the k-th smallest element. (variant 2)
import heapq def kth_smallest(matrix, k): n = len(matrix) if n == 0: return None pq = [] for i in range(min(n, k)): heapq.heappush(pq, (matrix[i][0], i, 0)) val = None for _ in range(k): val, r, c = heapq.heappop(pq) if c+1 < len(matrix[r]): heapq.heappush(pq,...
def check(): mat = [[1,5,9],[10,11,13],[12,13,15]] assert kth_smallest(mat, 8) == 13 assert kth_smallest([[1]],1) == 1
kth_smallest
GenEval/LEV2_035
Implement `tiling_ways(n)` that returns the number of ways to tile a 2 x n board using 2x1 dominos and L-shaped trominoes. Return integer. (Standard DP variant) (variant 2)
def tiling_ways(n): if n == 0: return 1 if n == 1: return 1 a, b = 1, 1 extra = 0 for i in range(2, n+1): cur = a + b + extra extra = b a, b = b, cur return b
def check(): assert tiling_ways(0) == 1 assert tiling_ways(1) == 1 assert tiling_ways(2) == 2 assert isinstance(tiling_ways(5), int)
tiling_ways
GenEval/LEV2_036
Implement `min_window(s, t)` that returns the minimum window substring of s which contains all characters of t (with multiplicity). If none exists, return empty string. (variant 2)
from collections import Counter def min_window(s, t): if not t or not s: return "" need = Counter(t) missing = len(t) left = 0 start = 0 min_len = float('inf') for right, ch in enumerate(s): if need[ch] > 0: missing -= 1 need[ch] -= 1 while missing == 0: ...
def check(): assert min_window("ADOBECODEBANC","ABC") == "BANC" assert min_window("a","a") == "a" assert min_window("a","aa") == ""
min_window
GenEval/LEV2_037
Implement `num_islands(grid)` that counts the number of connected islands of '1's in the grid (4-directional). (variant 2)
def num_islands(grid): if not grid: return 0 m = len(grid); n = len(grid[0]) visited = [[False]*n for _ in range(m)] def dfs(i,j): if i<0 or j<0 or i>=m or j>=n: return if visited[i][j] or grid[i][j] != '1': return visited[i][j] = True for di,dj in ((1,0),(-1,0),(0,1),(0,...
def check(): g = ["11110","11010","11000","00000"] assert num_islands([list(row) for row in g]) == 1 g2 = ["11000","11000","00100","00011"] assert num_islands([list(row) for row in g2]) == 3
num_islands
GenEval/LEV2_038
Given a string s containing only digits, implement `num_decodings(s)` that returns the number of ways to decode it to letters (A=1..Z=26). '0' handling as in standard problem. (variant 2)
def num_decodings(s): if not s: return 0 n = len(s) dp = [0]*(n+1) dp[0] = 1 for i in range(1, n+1): if s[i-1] != '0': dp[i] += dp[i-1] if i>=2 and s[i-2] != '0' and 1 <= int(s[i-2:i]) <= 26: dp[i] += dp[i-2] return dp[n]
def check(): assert num_decodings("12") == 2 assert num_decodings("226") == 3 assert num_decodings("0") == 0
num_decodings
GenEval/LEV2_039
Implement `serialize_graph(adj)` and `deserialize_graph(s)` where adj is dict node->list(neighbors) with integer nodes. Use deterministic serialization. Tests will compare roundtrip. (variant 2)
def serialize_graph(adj): parts = [] for node in sorted(adj.keys()): parts.append(str(node) + ':' + ','.join(map(str, sorted(adj[node])))) return '|'.join(parts) def deserialize_graph(s): if s == '': return {} adj = {} for part in s.split('|'): node, neigh = part.split(':') ...
def check(): adj = {1:[2,3], 2:[3], 3:[]} s = serialize_graph(adj) assert deserialize_graph(s) == {1:[2,3],2:[3],3:[]} assert serialize_graph({}) == ''
serialize_graph
GenEval/LEV2_040
Given a tree represented as adjacency dict and values dict (node -> value), implement `max_independent_set_tree(root, adj, val)` returning max sum of selected nodes with no two adjacent. Root given but tree is undirected; parent relations to be inferred. (variant 2)
def max_independent_set_tree(root, adj, val): def dfs(u, parent): incl = val[u] excl = 0 for v in adj.get(u, []): if v == parent: continue a, b = dfs(v, u) incl += b excl += max(a, b) return incl, excl a,b = dfs(root, None) retu...
def check(): adj = {1:[2,3],2:[1],3:[1]}; val={1:3,2:2,3:1} assert max_independent_set_tree(1, adj, val) == 3 adj2 = {1:[2],2:[1,3],3:[2]}; val2={1:1,2:2,3:3} assert max_independent_set_tree(1, adj2, val2) == 4
max_independent_set_tree
GenEval/LEV2_041
Write a function `balanced_split(nums)` that splits a list of positive integers into two non-empty subsets such that the absolute difference of their sums is minimized. Return the minimum possible difference. You may assume len(nums) >= 2. (variant 3)
def balanced_split(nums): total = sum(nums) n = len(nums) target = total // 2 dp = [False] * (target+1) dp[0] = True for num in nums: for s in range(target, num-1, -1): if dp[s-num]: dp[s] = True best = total for s in range(1, target+1): if dp[...
def check(): assert balanced_split([1,2,3]) == 0 assert balanced_split([1,5,11,5]) == 0 assert balanced_split([7,3]) == 4 assert balanced_split([10,20,15,5]) == 0
balanced_split
GenEval/LEV2_042
You are given a starting binary string S containing only '0' and '1'. The infinite expansion is defined by repeatedly replacing S with S + flip(reverse(S)), where flip swaps '0' and '1'. Implement `kth_char(S, k)` to return the k-th character (1-indexed) in the infinite expansion without building the full string. (var...
def kth_char(S, k): n = len(S) if k <= n: return S[k-1] length = n while length < k: length *= 2 def solve(length_now, k_pos): if k_pos <= n: return S[k_pos-1] half = length_now // 2 if k_pos <= half: return solve(half, k_pos) m...
def check(): assert kth_char("0",1) == "0" assert kth_char("01",3) == "1" assert kth_char("01",4) == "0" assert kth_char("1",2) == "0"
kth_char
GenEval/LEV2_043
Given two equal-length strings s1 and s2 consisting only of characters 'x' and 'y', return the minimum number of swaps (a swap exchanges positions in the same string) required to make s1 equal s2. Return -1 if impossible. Implement `min_swaps_to_equal(s1, s2)`. (variant 3)
def min_swaps_to_equal(s1, s2): if len(s1) != len(s2): return -1 xy = 0 yx = 0 for a,b in zip(s1, s2): if a == 'x' and b == 'y': xy += 1 elif a == 'y' and b == 'x': yx += 1 if (xy + yx) % 2 == 1: return -1 return xy//2 + yx//2 + 2*(xy%2)
def check(): assert min_swaps_to_equal('xxyy','yyxx') == 2 assert min_swaps_to_equal('xy','yx') == 1 assert min_swaps_to_equal('xx','yy') == -1 assert min_swaps_to_equal('xxyyxy','yyxxxy') == 2
min_swaps_to_equal
GenEval/LEV2_044
Write `longest_ap(arr)` that returns the length of the longest arithmetic subsequence (not necessarily contiguous) in arr. (variant 3)
def longest_ap(arr): n = len(arr) if n <= 2: return n dp = [dict() for _ in range(n)] best = 2 for i in range(n): for j in range(i): diff = arr[i] - arr[j] dp[i][diff] = dp[j].get(diff, 1) + 1 if dp[i][diff] > best: best = dp[i][dif...
def check(): assert longest_ap([1,2,3,4]) == 4 assert longest_ap([1,7,10,15,27,29]) == 3 assert longest_ap([9,4,7,2,10]) == 3 assert longest_ap([20,1,15,3,10,5,8]) == 4
longest_ap
GenEval/LEV2_045
Implement `count_arrays(n, k)` that returns the number of permutations of [1..n] that have exactly k inversions. Use DP (no combinatorics expected). (variant 3)
def count_arrays(n, k): if k < 0: return 0 dp = [[0] * (k+1) for _ in range(n+1)] dp[0][0] = 1 for i in range(1, n+1): for j in range(k+1): total = 0 for x in range(min(j, i-1)+1): total += dp[i-1][j-x] dp[i][j] = total return dp[n]...
def check(): assert count_arrays(3,0) == 1 assert count_arrays(3,1) == 2 assert count_arrays(4,3) == 6 assert count_arrays(5,5) == 22
count_arrays
GenEval/LEV2_046
Given cost[i] (cost to move from i to i+1) and teleport list teleport where teleport[i] = j or None, meaning you can jump from i to j at zero cost, implement `min_path_cost(cost, teleport)` to return minimum cost to reach last index from 0. (variant 3)
def min_path_cost(cost, teleport): import heapq n = len(cost) + 1 adj = [[] for _ in range(n)] for i in range(n-1): adj[i].append((i+1, cost[i])) for i, t in enumerate(teleport): if t is not None and 0 <= t < n: adj[i].append((t, 0)) INF = 10**18 dist = [INF] * n ...
def check(): assert min_path_cost([1,2,3],[None,None,None]) == 6 assert min_path_cost([5,5,5],[3,None,None]) == 0 assert min_path_cost([2,2,2,2],[None,4,None,None]) == 6
min_path_cost
GenEval/LEV2_047
Implement `max_xor(arr)` that returns the maximum XOR of any pair in arr. Use bitwise trie approach. (variant 3)
class Node: def __init__(self): self.child = {} def max_xor(arr): root = Node() def insert(num): cur = root for i in range(31, -1, -1): bit = (num >> i) & 1 if bit not in cur.child: cur.child[bit] = Node() cur = cur.child[bit] d...
def check(): assert max_xor([1,2,3]) == 3 assert max_xor([8,1,2,12]) == 15 assert max_xor([4,6,7]) == 3
max_xor
GenEval/LEV2_048
Write `count_pal_subseq(s)` that counts distinct palindromic subsequences of length >= 2. Return integer count. (variant 3)
def count_pal_subseq(s): n = len(s) if n < 2: return 0 dp = [[0] * n for _ in range(n)] for i in range(n): dp[i][i] = 1 for length in range(2, n+1): for i in range(0, n-length+1): j = i + length - 1 if s[i] == s[j]: dp[i][j] = dp[i+1][j...
def check(): assert count_pal_subseq('aaa') == 3 assert count_pal_subseq('abca') == 5 assert count_pal_subseq('abc') == 0
count_pal_subseq
GenEval/LEV2_049
Implement `smallest_num(d, s)` that returns the smallest non-negative integer (as string) whose digit-sum equals s and is divisible by d. Return -1 if impossible. (variant 3)
from collections import deque def smallest_num(d, s): if s == 0: return '0' if 0 % d == 0 else -1 visited = [[False] * (s+1) for _ in range(d)] parent = {} q = deque() q.append((0, 0)) visited[0][0] = True while q: rem, digit_sum = q.popleft() if digit_sum == s and re...
def check(): assert smallest_num(3,3) == '3' assert smallest_num(5,10) == '55' assert smallest_num(7,7) == '7'
smallest_num
GenEval/LEV2_050
Implement `eval_expr(expr)` to evaluate mathematical expression `expr` containing non-negative integers and operators +, -, *, / and parentheses. Division is integer division truncating toward zero. There will be no unary operators. You may assume expression is valid. (variant 3)
def eval_expr(expr): def precedence(op): if op in ('+', '-'): return 1 if op in ('*', '/'): return 2 return 0 def apply_op(a, b, op): if op == '+': return a + b if op == '-': return a - b if op == '*': return a * b if op == '/': if b == 0: rais...
def check(): assert eval_expr("2+3*4") == 14 assert eval_expr("(2+3)*4") == 20 assert eval_expr("10/3") == 3 assert eval_expr("10-2*3") == 4
eval_expr
GenEval/LEV2_051
Implement `word_break(s, words)` which returns True if string s can be segmented into a sequence of one or more dictionary words in set `words`. (variant 3)
def word_break(s, words): n = len(s) dp = [False] * (n+1) dp[0] = True for i in range(1, n+1): for j in range(i): if dp[j] and s[j:i] in words: dp[i] = True break return dp[n]
def check(): assert word_break("leetcode", {"leet","code"}) assert not word_break("catsandog", {"cats","dog","sand","and","cat"})
word_break
GenEval/LEV2_052
Implement two functions: `serialize(root)` and `deserialize(s)` where s is a string produced by serialize. Use preorder traversal and '#' for nulls. For testing, use tuple-built trees represented as nested tuples: e.g., (val, left, right) or None. (variant 3)
def serialize(root): res = [] def dfs(node): if node is None: res.append('#') return val, left, right = node res.append(str(val)) dfs(left) dfs(right) dfs(root) return ','.join(res) def deserialize(s): parts = s.split(',') idx = 0 ...
def check(): tree = (1, (2, None, None), (3, None, None)) s = serialize(tree) assert deserialize(s) == tree assert serialize(None) == '#'
serialize_deserialize
GenEval/LEV2_053
Implement `sliding_median(nums, k)` returning list of medians for each window of size k over nums. For even k, use the lower median (floor). (variant 3)
import heapq def sliding_median(nums, k): if k == 0: return [] lo = [] # max heap (invert sign) hi = [] # min heap delayed = {} def add(num): if not lo or num <= -lo[0]: heapq.heappush(lo, -num) else: heapq.heappush(hi, num) balance() def remove(...
def check(): assert sliding_median([1,3,-1,-3,5,3,6,7],3) == [1,-1,-1,3,5,6] assert sliding_median([1,2,3,4],2) == [1,2,3]
sliding_median
GenEval/LEV2_054
Given an n x n matrix where each row and column is sorted in ascending order, implement `kth_smallest(matrix, k)` returning the k-th smallest element. (variant 3)
import heapq def kth_smallest(matrix, k): n = len(matrix) if n == 0: return None pq = [] for i in range(min(n, k)): heapq.heappush(pq, (matrix[i][0], i, 0)) val = None for _ in range(k): val, r, c = heapq.heappop(pq) if c+1 < len(matrix[r]): heapq.heappush(pq,...
def check(): mat = [[1,5,9],[10,11,13],[12,13,15]] assert kth_smallest(mat, 8) == 13 assert kth_smallest([[1]],1) == 1
kth_smallest
GenEval/LEV2_055
Implement `tiling_ways(n)` that returns the number of ways to tile a 2 x n board using 2x1 dominos and L-shaped trominoes. Return integer. (Standard DP variant) (variant 3)
def tiling_ways(n): if n == 0: return 1 if n == 1: return 1 a, b = 1, 1 extra = 0 for i in range(2, n+1): cur = a + b + extra extra = b a, b = b, cur return b
def check(): assert tiling_ways(0) == 1 assert tiling_ways(1) == 1 assert tiling_ways(2) == 2 assert isinstance(tiling_ways(5), int)
tiling_ways
GenEval/LEV2_056
Implement `min_window(s, t)` that returns the minimum window substring of s which contains all characters of t (with multiplicity). If none exists, return empty string. (variant 3)
from collections import Counter def min_window(s, t): if not t or not s: return "" need = Counter(t) missing = len(t) left = 0 start = 0 min_len = float('inf') for right, ch in enumerate(s): if need[ch] > 0: missing -= 1 need[ch] -= 1 while missing == 0: ...
def check(): assert min_window("ADOBECODEBANC","ABC") == "BANC" assert min_window("a","a") == "a" assert min_window("a","aa") == ""
min_window
GenEval/LEV2_057
Implement `num_islands(grid)` that counts the number of connected islands of '1's in the grid (4-directional). (variant 3)
def num_islands(grid): if not grid: return 0 m = len(grid); n = len(grid[0]) visited = [[False]*n for _ in range(m)] def dfs(i,j): if i<0 or j<0 or i>=m or j>=n: return if visited[i][j] or grid[i][j] != '1': return visited[i][j] = True for di,dj in ((1,0),(-1,0),(0,1),(0,...
def check(): g = ["11110","11010","11000","00000"] assert num_islands([list(row) for row in g]) == 1 g2 = ["11000","11000","00100","00011"] assert num_islands([list(row) for row in g2]) == 3
num_islands
GenEval/LEV2_058
Given a string s containing only digits, implement `num_decodings(s)` that returns the number of ways to decode it to letters (A=1..Z=26). '0' handling as in standard problem. (variant 3)
def num_decodings(s): if not s: return 0 n = len(s) dp = [0]*(n+1) dp[0] = 1 for i in range(1, n+1): if s[i-1] != '0': dp[i] += dp[i-1] if i>=2 and s[i-2] != '0' and 1 <= int(s[i-2:i]) <= 26: dp[i] += dp[i-2] return dp[n]
def check(): assert num_decodings("12") == 2 assert num_decodings("226") == 3 assert num_decodings("0") == 0
num_decodings
GenEval/LEV2_059
Implement `serialize_graph(adj)` and `deserialize_graph(s)` where adj is dict node->list(neighbors) with integer nodes. Use deterministic serialization. Tests will compare roundtrip. (variant 3)
def serialize_graph(adj): parts = [] for node in sorted(adj.keys()): parts.append(str(node) + ':' + ','.join(map(str, sorted(adj[node])))) return '|'.join(parts) def deserialize_graph(s): if s == '': return {} adj = {} for part in s.split('|'): node, neigh = part.split(':') ...
def check(): adj = {1:[2,3], 2:[3], 3:[]} s = serialize_graph(adj) assert deserialize_graph(s) == {1:[2,3],2:[3],3:[]} assert serialize_graph({}) == ''
serialize_graph
GenEval/LEV2_060
Given a tree represented as adjacency dict and values dict (node -> value), implement `max_independent_set_tree(root, adj, val)` returning max sum of selected nodes with no two adjacent. Root given but tree is undirected; parent relations to be inferred. (variant 3)
def max_independent_set_tree(root, adj, val): def dfs(u, parent): incl = val[u] excl = 0 for v in adj.get(u, []): if v == parent: continue a, b = dfs(v, u) incl += b excl += max(a, b) return incl, excl a,b = dfs(root, None) retu...
def check(): adj = {1:[2,3],2:[1],3:[1]}; val={1:3,2:2,3:1} assert max_independent_set_tree(1, adj, val) == 3 adj2 = {1:[2],2:[1,3],3:[2]}; val2={1:1,2:2,3:3} assert max_independent_set_tree(1, adj2, val2) == 4
max_independent_set_tree
GenEval/LEV2_061
Write a function `balanced_split(nums)` that splits a list of positive integers into two non-empty subsets such that the absolute difference of their sums is minimized. Return the minimum possible difference. You may assume len(nums) >= 2. (variant 4)
def balanced_split(nums): total = sum(nums) n = len(nums) target = total // 2 dp = [False] * (target+1) dp[0] = True for num in nums: for s in range(target, num-1, -1): if dp[s-num]: dp[s] = True best = total for s in range(1, target+1): if dp[...
def check(): assert balanced_split([1,2,3]) == 0 assert balanced_split([1,5,11,5]) == 0 assert balanced_split([7,3]) == 4 assert balanced_split([10,20,15,5]) == 0
balanced_split
GenEval/LEV2_062
You are given a starting binary string S containing only '0' and '1'. The infinite expansion is defined by repeatedly replacing S with S + flip(reverse(S)), where flip swaps '0' and '1'. Implement `kth_char(S, k)` to return the k-th character (1-indexed) in the infinite expansion without building the full string. (var...
def kth_char(S, k): n = len(S) if k <= n: return S[k-1] length = n while length < k: length *= 2 def solve(length_now, k_pos): if k_pos <= n: return S[k_pos-1] half = length_now // 2 if k_pos <= half: return solve(half, k_pos) m...
def check(): assert kth_char("0",1) == "0" assert kth_char("01",3) == "1" assert kth_char("01",4) == "0" assert kth_char("1",2) == "0"
kth_char
GenEval/LEV2_063
Given two equal-length strings s1 and s2 consisting only of characters 'x' and 'y', return the minimum number of swaps (a swap exchanges positions in the same string) required to make s1 equal s2. Return -1 if impossible. Implement `min_swaps_to_equal(s1, s2)`. (variant 4)
def min_swaps_to_equal(s1, s2): if len(s1) != len(s2): return -1 xy = 0 yx = 0 for a,b in zip(s1, s2): if a == 'x' and b == 'y': xy += 1 elif a == 'y' and b == 'x': yx += 1 if (xy + yx) % 2 == 1: return -1 return xy//2 + yx//2 + 2*(xy%2)
def check(): assert min_swaps_to_equal('xxyy','yyxx') == 2 assert min_swaps_to_equal('xy','yx') == 1 assert min_swaps_to_equal('xx','yy') == -1 assert min_swaps_to_equal('xxyyxy','yyxxxy') == 2
min_swaps_to_equal
GenEval/LEV2_064
Write `longest_ap(arr)` that returns the length of the longest arithmetic subsequence (not necessarily contiguous) in arr. (variant 4)
def longest_ap(arr): n = len(arr) if n <= 2: return n dp = [dict() for _ in range(n)] best = 2 for i in range(n): for j in range(i): diff = arr[i] - arr[j] dp[i][diff] = dp[j].get(diff, 1) + 1 if dp[i][diff] > best: best = dp[i][dif...
def check(): assert longest_ap([1,2,3,4]) == 4 assert longest_ap([1,7,10,15,27,29]) == 3 assert longest_ap([9,4,7,2,10]) == 3 assert longest_ap([20,1,15,3,10,5,8]) == 4
longest_ap
GenEval/LEV2_065
Implement `count_arrays(n, k)` that returns the number of permutations of [1..n] that have exactly k inversions. Use DP (no combinatorics expected). (variant 4)
def count_arrays(n, k): if k < 0: return 0 dp = [[0] * (k+1) for _ in range(n+1)] dp[0][0] = 1 for i in range(1, n+1): for j in range(k+1): total = 0 for x in range(min(j, i-1)+1): total += dp[i-1][j-x] dp[i][j] = total return dp[n]...
def check(): assert count_arrays(3,0) == 1 assert count_arrays(3,1) == 2 assert count_arrays(4,3) == 6 assert count_arrays(5,5) == 22
count_arrays
GenEval/LEV2_066
Given cost[i] (cost to move from i to i+1) and teleport list teleport where teleport[i] = j or None, meaning you can jump from i to j at zero cost, implement `min_path_cost(cost, teleport)` to return minimum cost to reach last index from 0. (variant 4)
def min_path_cost(cost, teleport): import heapq n = len(cost) + 1 adj = [[] for _ in range(n)] for i in range(n-1): adj[i].append((i+1, cost[i])) for i, t in enumerate(teleport): if t is not None and 0 <= t < n: adj[i].append((t, 0)) INF = 10**18 dist = [INF] * n ...
def check(): assert min_path_cost([1,2,3],[None,None,None]) == 6 assert min_path_cost([5,5,5],[3,None,None]) == 0 assert min_path_cost([2,2,2,2],[None,4,None,None]) == 6
min_path_cost
GenEval/LEV2_067
Implement `max_xor(arr)` that returns the maximum XOR of any pair in arr. Use bitwise trie approach. (variant 4)
class Node: def __init__(self): self.child = {} def max_xor(arr): root = Node() def insert(num): cur = root for i in range(31, -1, -1): bit = (num >> i) & 1 if bit not in cur.child: cur.child[bit] = Node() cur = cur.child[bit] d...
def check(): assert max_xor([1,2,3]) == 3 assert max_xor([8,1,2,12]) == 15 assert max_xor([4,6,7]) == 3
max_xor
GenEval/LEV2_068
Write `count_pal_subseq(s)` that counts distinct palindromic subsequences of length >= 2. Return integer count. (variant 4)
def count_pal_subseq(s): n = len(s) if n < 2: return 0 dp = [[0] * n for _ in range(n)] for i in range(n): dp[i][i] = 1 for length in range(2, n+1): for i in range(0, n-length+1): j = i + length - 1 if s[i] == s[j]: dp[i][j] = dp[i+1][j...
def check(): assert count_pal_subseq('aaa') == 3 assert count_pal_subseq('abca') == 5 assert count_pal_subseq('abc') == 0
count_pal_subseq
GenEval/LEV2_069
Implement `smallest_num(d, s)` that returns the smallest non-negative integer (as string) whose digit-sum equals s and is divisible by d. Return -1 if impossible. (variant 4)
from collections import deque def smallest_num(d, s): if s == 0: return '0' if 0 % d == 0 else -1 visited = [[False] * (s+1) for _ in range(d)] parent = {} q = deque() q.append((0, 0)) visited[0][0] = True while q: rem, digit_sum = q.popleft() if digit_sum == s and re...
def check(): assert smallest_num(3,3) == '3' assert smallest_num(5,10) == '55' assert smallest_num(7,7) == '7'
smallest_num
GenEval/LEV2_070
Implement `eval_expr(expr)` to evaluate mathematical expression `expr` containing non-negative integers and operators +, -, *, / and parentheses. Division is integer division truncating toward zero. There will be no unary operators. You may assume expression is valid. (variant 4)
def eval_expr(expr): def precedence(op): if op in ('+', '-'): return 1 if op in ('*', '/'): return 2 return 0 def apply_op(a, b, op): if op == '+': return a + b if op == '-': return a - b if op == '*': return a * b if op == '/': if b == 0: rais...
def check(): assert eval_expr("2+3*4") == 14 assert eval_expr("(2+3)*4") == 20 assert eval_expr("10/3") == 3 assert eval_expr("10-2*3") == 4
eval_expr
GenEval/LEV2_071
Implement `word_break(s, words)` which returns True if string s can be segmented into a sequence of one or more dictionary words in set `words`. (variant 4)
def word_break(s, words): n = len(s) dp = [False] * (n+1) dp[0] = True for i in range(1, n+1): for j in range(i): if dp[j] and s[j:i] in words: dp[i] = True break return dp[n]
def check(): assert word_break("leetcode", {"leet","code"}) assert not word_break("catsandog", {"cats","dog","sand","and","cat"})
word_break
GenEval/LEV2_072
Implement two functions: `serialize(root)` and `deserialize(s)` where s is a string produced by serialize. Use preorder traversal and '#' for nulls. For testing, use tuple-built trees represented as nested tuples: e.g., (val, left, right) or None. (variant 4)
def serialize(root): res = [] def dfs(node): if node is None: res.append('#') return val, left, right = node res.append(str(val)) dfs(left) dfs(right) dfs(root) return ','.join(res) def deserialize(s): parts = s.split(',') idx = 0 ...
def check(): tree = (1, (2, None, None), (3, None, None)) s = serialize(tree) assert deserialize(s) == tree assert serialize(None) == '#'
serialize_deserialize
GenEval/LEV2_073
Implement `sliding_median(nums, k)` returning list of medians for each window of size k over nums. For even k, use the lower median (floor). (variant 4)
import heapq def sliding_median(nums, k): if k == 0: return [] lo = [] # max heap (invert sign) hi = [] # min heap delayed = {} def add(num): if not lo or num <= -lo[0]: heapq.heappush(lo, -num) else: heapq.heappush(hi, num) balance() def remove(...
def check(): assert sliding_median([1,3,-1,-3,5,3,6,7],3) == [1,-1,-1,3,5,6] assert sliding_median([1,2,3,4],2) == [1,2,3]
sliding_median
GenEval/LEV2_074
Given an n x n matrix where each row and column is sorted in ascending order, implement `kth_smallest(matrix, k)` returning the k-th smallest element. (variant 4)
import heapq def kth_smallest(matrix, k): n = len(matrix) if n == 0: return None pq = [] for i in range(min(n, k)): heapq.heappush(pq, (matrix[i][0], i, 0)) val = None for _ in range(k): val, r, c = heapq.heappop(pq) if c+1 < len(matrix[r]): heapq.heappush(pq,...
def check(): mat = [[1,5,9],[10,11,13],[12,13,15]] assert kth_smallest(mat, 8) == 13 assert kth_smallest([[1]],1) == 1
kth_smallest
GenEval/LEV2_075
Implement `tiling_ways(n)` that returns the number of ways to tile a 2 x n board using 2x1 dominos and L-shaped trominoes. Return integer. (Standard DP variant) (variant 4)
def tiling_ways(n): if n == 0: return 1 if n == 1: return 1 a, b = 1, 1 extra = 0 for i in range(2, n+1): cur = a + b + extra extra = b a, b = b, cur return b
def check(): assert tiling_ways(0) == 1 assert tiling_ways(1) == 1 assert tiling_ways(2) == 2 assert isinstance(tiling_ways(5), int)
tiling_ways
GenEval/LEV2_076
Implement `min_window(s, t)` that returns the minimum window substring of s which contains all characters of t (with multiplicity). If none exists, return empty string. (variant 4)
from collections import Counter def min_window(s, t): if not t or not s: return "" need = Counter(t) missing = len(t) left = 0 start = 0 min_len = float('inf') for right, ch in enumerate(s): if need[ch] > 0: missing -= 1 need[ch] -= 1 while missing == 0: ...
def check(): assert min_window("ADOBECODEBANC","ABC") == "BANC" assert min_window("a","a") == "a" assert min_window("a","aa") == ""
min_window
GenEval/LEV2_077
Implement `num_islands(grid)` that counts the number of connected islands of '1's in the grid (4-directional). (variant 4)
def num_islands(grid): if not grid: return 0 m = len(grid); n = len(grid[0]) visited = [[False]*n for _ in range(m)] def dfs(i,j): if i<0 or j<0 or i>=m or j>=n: return if visited[i][j] or grid[i][j] != '1': return visited[i][j] = True for di,dj in ((1,0),(-1,0),(0,1),(0,...
def check(): g = ["11110","11010","11000","00000"] assert num_islands([list(row) for row in g]) == 1 g2 = ["11000","11000","00100","00011"] assert num_islands([list(row) for row in g2]) == 3
num_islands
GenEval/LEV2_078
Given a string s containing only digits, implement `num_decodings(s)` that returns the number of ways to decode it to letters (A=1..Z=26). '0' handling as in standard problem. (variant 4)
def num_decodings(s): if not s: return 0 n = len(s) dp = [0]*(n+1) dp[0] = 1 for i in range(1, n+1): if s[i-1] != '0': dp[i] += dp[i-1] if i>=2 and s[i-2] != '0' and 1 <= int(s[i-2:i]) <= 26: dp[i] += dp[i-2] return dp[n]
def check(): assert num_decodings("12") == 2 assert num_decodings("226") == 3 assert num_decodings("0") == 0
num_decodings
GenEval/LEV2_079
Implement `serialize_graph(adj)` and `deserialize_graph(s)` where adj is dict node->list(neighbors) with integer nodes. Use deterministic serialization. Tests will compare roundtrip. (variant 4)
def serialize_graph(adj): parts = [] for node in sorted(adj.keys()): parts.append(str(node) + ':' + ','.join(map(str, sorted(adj[node])))) return '|'.join(parts) def deserialize_graph(s): if s == '': return {} adj = {} for part in s.split('|'): node, neigh = part.split(':') ...
def check(): adj = {1:[2,3], 2:[3], 3:[]} s = serialize_graph(adj) assert deserialize_graph(s) == {1:[2,3],2:[3],3:[]} assert serialize_graph({}) == ''
serialize_graph
GenEval/LEV2_080
Given a tree represented as adjacency dict and values dict (node -> value), implement `max_independent_set_tree(root, adj, val)` returning max sum of selected nodes with no two adjacent. Root given but tree is undirected; parent relations to be inferred. (variant 4)
def max_independent_set_tree(root, adj, val): def dfs(u, parent): incl = val[u] excl = 0 for v in adj.get(u, []): if v == parent: continue a, b = dfs(v, u) incl += b excl += max(a, b) return incl, excl a,b = dfs(root, None) retu...
def check(): adj = {1:[2,3],2:[1],3:[1]}; val={1:3,2:2,3:1} assert max_independent_set_tree(1, adj, val) == 3 adj2 = {1:[2],2:[1,3],3:[2]}; val2={1:1,2:2,3:3} assert max_independent_set_tree(1, adj2, val2) == 4
max_independent_set_tree
GenEval/LEV2_081
Write a function `balanced_split(nums)` that splits a list of positive integers into two non-empty subsets such that the absolute difference of their sums is minimized. Return the minimum possible difference. You may assume len(nums) >= 2. (variant 5)
def balanced_split(nums): total = sum(nums) n = len(nums) target = total // 2 dp = [False] * (target+1) dp[0] = True for num in nums: for s in range(target, num-1, -1): if dp[s-num]: dp[s] = True best = total for s in range(1, target+1): if dp[...
def check(): assert balanced_split([1,2,3]) == 0 assert balanced_split([1,5,11,5]) == 0 assert balanced_split([7,3]) == 4 assert balanced_split([10,20,15,5]) == 0
balanced_split
GenEval/LEV2_082
You are given a starting binary string S containing only '0' and '1'. The infinite expansion is defined by repeatedly replacing S with S + flip(reverse(S)), where flip swaps '0' and '1'. Implement `kth_char(S, k)` to return the k-th character (1-indexed) in the infinite expansion without building the full string. (var...
def kth_char(S, k): n = len(S) if k <= n: return S[k-1] length = n while length < k: length *= 2 def solve(length_now, k_pos): if k_pos <= n: return S[k_pos-1] half = length_now // 2 if k_pos <= half: return solve(half, k_pos) m...
def check(): assert kth_char("0",1) == "0" assert kth_char("01",3) == "1" assert kth_char("01",4) == "0" assert kth_char("1",2) == "0"
kth_char
GenEval/LEV2_083
Given two equal-length strings s1 and s2 consisting only of characters 'x' and 'y', return the minimum number of swaps (a swap exchanges positions in the same string) required to make s1 equal s2. Return -1 if impossible. Implement `min_swaps_to_equal(s1, s2)`. (variant 5)
def min_swaps_to_equal(s1, s2): if len(s1) != len(s2): return -1 xy = 0 yx = 0 for a,b in zip(s1, s2): if a == 'x' and b == 'y': xy += 1 elif a == 'y' and b == 'x': yx += 1 if (xy + yx) % 2 == 1: return -1 return xy//2 + yx//2 + 2*(xy%2)
def check(): assert min_swaps_to_equal('xxyy','yyxx') == 2 assert min_swaps_to_equal('xy','yx') == 1 assert min_swaps_to_equal('xx','yy') == -1 assert min_swaps_to_equal('xxyyxy','yyxxxy') == 2
min_swaps_to_equal
GenEval/LEV2_084
Write `longest_ap(arr)` that returns the length of the longest arithmetic subsequence (not necessarily contiguous) in arr. (variant 5)
def longest_ap(arr): n = len(arr) if n <= 2: return n dp = [dict() for _ in range(n)] best = 2 for i in range(n): for j in range(i): diff = arr[i] - arr[j] dp[i][diff] = dp[j].get(diff, 1) + 1 if dp[i][diff] > best: best = dp[i][dif...
def check(): assert longest_ap([1,2,3,4]) == 4 assert longest_ap([1,7,10,15,27,29]) == 3 assert longest_ap([9,4,7,2,10]) == 3 assert longest_ap([20,1,15,3,10,5,8]) == 4
longest_ap
GenEval/LEV2_085
Implement `count_arrays(n, k)` that returns the number of permutations of [1..n] that have exactly k inversions. Use DP (no combinatorics expected). (variant 5)
def count_arrays(n, k): if k < 0: return 0 dp = [[0] * (k+1) for _ in range(n+1)] dp[0][0] = 1 for i in range(1, n+1): for j in range(k+1): total = 0 for x in range(min(j, i-1)+1): total += dp[i-1][j-x] dp[i][j] = total return dp[n]...
def check(): assert count_arrays(3,0) == 1 assert count_arrays(3,1) == 2 assert count_arrays(4,3) == 6 assert count_arrays(5,5) == 22
count_arrays
GenEval/LEV2_086
Given cost[i] (cost to move from i to i+1) and teleport list teleport where teleport[i] = j or None, meaning you can jump from i to j at zero cost, implement `min_path_cost(cost, teleport)` to return minimum cost to reach last index from 0. (variant 5)
def min_path_cost(cost, teleport): import heapq n = len(cost) + 1 adj = [[] for _ in range(n)] for i in range(n-1): adj[i].append((i+1, cost[i])) for i, t in enumerate(teleport): if t is not None and 0 <= t < n: adj[i].append((t, 0)) INF = 10**18 dist = [INF] * n ...
def check(): assert min_path_cost([1,2,3],[None,None,None]) == 6 assert min_path_cost([5,5,5],[3,None,None]) == 0 assert min_path_cost([2,2,2,2],[None,4,None,None]) == 6
min_path_cost
GenEval/LEV2_087
Implement `max_xor(arr)` that returns the maximum XOR of any pair in arr. Use bitwise trie approach. (variant 5)
class Node: def __init__(self): self.child = {} def max_xor(arr): root = Node() def insert(num): cur = root for i in range(31, -1, -1): bit = (num >> i) & 1 if bit not in cur.child: cur.child[bit] = Node() cur = cur.child[bit] d...
def check(): assert max_xor([1,2,3]) == 3 assert max_xor([8,1,2,12]) == 15 assert max_xor([4,6,7]) == 3
max_xor
GenEval/LEV2_088
Write `count_pal_subseq(s)` that counts distinct palindromic subsequences of length >= 2. Return integer count. (variant 5)
def count_pal_subseq(s): n = len(s) if n < 2: return 0 dp = [[0] * n for _ in range(n)] for i in range(n): dp[i][i] = 1 for length in range(2, n+1): for i in range(0, n-length+1): j = i + length - 1 if s[i] == s[j]: dp[i][j] = dp[i+1][j...
def check(): assert count_pal_subseq('aaa') == 3 assert count_pal_subseq('abca') == 5 assert count_pal_subseq('abc') == 0
count_pal_subseq
GenEval/LEV2_089
Implement `smallest_num(d, s)` that returns the smallest non-negative integer (as string) whose digit-sum equals s and is divisible by d. Return -1 if impossible. (variant 5)
from collections import deque def smallest_num(d, s): if s == 0: return '0' if 0 % d == 0 else -1 visited = [[False] * (s+1) for _ in range(d)] parent = {} q = deque() q.append((0, 0)) visited[0][0] = True while q: rem, digit_sum = q.popleft() if digit_sum == s and re...
def check(): assert smallest_num(3,3) == '3' assert smallest_num(5,10) == '55' assert smallest_num(7,7) == '7'
smallest_num
GenEval/LEV2_090
Implement `eval_expr(expr)` to evaluate mathematical expression `expr` containing non-negative integers and operators +, -, *, / and parentheses. Division is integer division truncating toward zero. There will be no unary operators. You may assume expression is valid. (variant 5)
def eval_expr(expr): def precedence(op): if op in ('+', '-'): return 1 if op in ('*', '/'): return 2 return 0 def apply_op(a, b, op): if op == '+': return a + b if op == '-': return a - b if op == '*': return a * b if op == '/': if b == 0: rais...
def check(): assert eval_expr("2+3*4") == 14 assert eval_expr("(2+3)*4") == 20 assert eval_expr("10/3") == 3 assert eval_expr("10-2*3") == 4
eval_expr
GenEval/LEV2_091
Implement `word_break(s, words)` which returns True if string s can be segmented into a sequence of one or more dictionary words in set `words`. (variant 5)
def word_break(s, words): n = len(s) dp = [False] * (n+1) dp[0] = True for i in range(1, n+1): for j in range(i): if dp[j] and s[j:i] in words: dp[i] = True break return dp[n]
def check(): assert word_break("leetcode", {"leet","code"}) assert not word_break("catsandog", {"cats","dog","sand","and","cat"})
word_break
GenEval/LEV2_092
Implement two functions: `serialize(root)` and `deserialize(s)` where s is a string produced by serialize. Use preorder traversal and '#' for nulls. For testing, use tuple-built trees represented as nested tuples: e.g., (val, left, right) or None. (variant 5)
def serialize(root): res = [] def dfs(node): if node is None: res.append('#') return val, left, right = node res.append(str(val)) dfs(left) dfs(right) dfs(root) return ','.join(res) def deserialize(s): parts = s.split(',') idx = 0 ...
def check(): tree = (1, (2, None, None), (3, None, None)) s = serialize(tree) assert deserialize(s) == tree assert serialize(None) == '#'
serialize_deserialize
GenEval/LEV2_093
Implement `sliding_median(nums, k)` returning list of medians for each window of size k over nums. For even k, use the lower median (floor). (variant 5)
import heapq def sliding_median(nums, k): if k == 0: return [] lo = [] # max heap (invert sign) hi = [] # min heap delayed = {} def add(num): if not lo or num <= -lo[0]: heapq.heappush(lo, -num) else: heapq.heappush(hi, num) balance() def remove(...
def check(): assert sliding_median([1,3,-1,-3,5,3,6,7],3) == [1,-1,-1,3,5,6] assert sliding_median([1,2,3,4],2) == [1,2,3]
sliding_median
GenEval/LEV2_094
Given an n x n matrix where each row and column is sorted in ascending order, implement `kth_smallest(matrix, k)` returning the k-th smallest element. (variant 5)
import heapq def kth_smallest(matrix, k): n = len(matrix) if n == 0: return None pq = [] for i in range(min(n, k)): heapq.heappush(pq, (matrix[i][0], i, 0)) val = None for _ in range(k): val, r, c = heapq.heappop(pq) if c+1 < len(matrix[r]): heapq.heappush(pq,...
def check(): mat = [[1,5,9],[10,11,13],[12,13,15]] assert kth_smallest(mat, 8) == 13 assert kth_smallest([[1]],1) == 1
kth_smallest
GenEval/LEV2_095
Implement `tiling_ways(n)` that returns the number of ways to tile a 2 x n board using 2x1 dominos and L-shaped trominoes. Return integer. (Standard DP variant) (variant 5)
def tiling_ways(n): if n == 0: return 1 if n == 1: return 1 a, b = 1, 1 extra = 0 for i in range(2, n+1): cur = a + b + extra extra = b a, b = b, cur return b
def check(): assert tiling_ways(0) == 1 assert tiling_ways(1) == 1 assert tiling_ways(2) == 2 assert isinstance(tiling_ways(5), int)
tiling_ways
GenEval/LEV2_096
Implement `min_window(s, t)` that returns the minimum window substring of s which contains all characters of t (with multiplicity). If none exists, return empty string. (variant 5)
from collections import Counter def min_window(s, t): if not t or not s: return "" need = Counter(t) missing = len(t) left = 0 start = 0 min_len = float('inf') for right, ch in enumerate(s): if need[ch] > 0: missing -= 1 need[ch] -= 1 while missing == 0: ...
def check(): assert min_window("ADOBECODEBANC","ABC") == "BANC" assert min_window("a","a") == "a" assert min_window("a","aa") == ""
min_window
GenEval/LEV2_097
Implement `num_islands(grid)` that counts the number of connected islands of '1's in the grid (4-directional). (variant 5)
def num_islands(grid): if not grid: return 0 m = len(grid); n = len(grid[0]) visited = [[False]*n for _ in range(m)] def dfs(i,j): if i<0 or j<0 or i>=m or j>=n: return if visited[i][j] or grid[i][j] != '1': return visited[i][j] = True for di,dj in ((1,0),(-1,0),(0,1),(0,...
def check(): g = ["11110","11010","11000","00000"] assert num_islands([list(row) for row in g]) == 1 g2 = ["11000","11000","00100","00011"] assert num_islands([list(row) for row in g2]) == 3
num_islands
GenEval/LEV2_098
Given a string s containing only digits, implement `num_decodings(s)` that returns the number of ways to decode it to letters (A=1..Z=26). '0' handling as in standard problem. (variant 5)
def num_decodings(s): if not s: return 0 n = len(s) dp = [0]*(n+1) dp[0] = 1 for i in range(1, n+1): if s[i-1] != '0': dp[i] += dp[i-1] if i>=2 and s[i-2] != '0' and 1 <= int(s[i-2:i]) <= 26: dp[i] += dp[i-2] return dp[n]
def check(): assert num_decodings("12") == 2 assert num_decodings("226") == 3 assert num_decodings("0") == 0
num_decodings
GenEval/LEV2_099
Implement `serialize_graph(adj)` and `deserialize_graph(s)` where adj is dict node->list(neighbors) with integer nodes. Use deterministic serialization. Tests will compare roundtrip. (variant 5)
def serialize_graph(adj): parts = [] for node in sorted(adj.keys()): parts.append(str(node) + ':' + ','.join(map(str, sorted(adj[node])))) return '|'.join(parts) def deserialize_graph(s): if s == '': return {} adj = {} for part in s.split('|'): node, neigh = part.split(':') ...
def check(): adj = {1:[2,3], 2:[3], 3:[]} s = serialize_graph(adj) assert deserialize_graph(s) == {1:[2,3],2:[3],3:[]} assert serialize_graph({}) == ''
serialize_graph
GenEval/LEV2_100
Given a tree represented as adjacency dict and values dict (node -> value), implement `max_independent_set_tree(root, adj, val)` returning max sum of selected nodes with no two adjacent. Root given but tree is undirected; parent relations to be inferred. (variant 5)
def max_independent_set_tree(root, adj, val): def dfs(u, parent): incl = val[u] excl = 0 for v in adj.get(u, []): if v == parent: continue a, b = dfs(v, u) incl += b excl += max(a, b) return incl, excl a,b = dfs(root, None) retu...
def check(): adj = {1:[2,3],2:[1],3:[1]}; val={1:3,2:2,3:1} assert max_independent_set_tree(1, adj, val) == 3 adj2 = {1:[2],2:[1,3],3:[2]}; val2={1:1,2:2,3:3} assert max_independent_set_tree(1, adj2, val2) == 4
max_independent_set_tree
README.md exists but content is empty.
Downloads last month
31