version stringclasses 1
value | style stringclasses 2
values | subset stringclasses 12
values | question_id stringlengths 9 23 | question stringlengths 27 8.13k | solution stringlengths 99 5.97k | test stringlengths 105 4.45k | test_info listlengths 0 13 | gpt_pass_sequence listlengths 1 10 | gpt_pass_trial_num int64 1 10 | gpt_difficulty stringclasses 3
values | gpt_pass_percentage float64 0.1 1 | trials dict | chosen_trial stringclasses 10
values | metadata dict | benchmark_similarity float64 0.16 0.93 | benchmark_instruction stringclasses 1
value | benchmark_task_id stringclasses 1
value | filter_reason stringclasses 1
value | base_id stringlengths 7 21 | variant stringclasses 2
values | top_function_names listlengths 2 13 | n_top_functions int64 2 13 | helper_call_edges listlengths 1 16 | n_helper_call_edges int64 1 16 | harness_functions listlengths 0 3 | structural_wrapper bool 1
class | class_names listlengths 0 5 | has_class bool 2
classes | test_kind stringclasses 1
value | test_has_solution_import bool 2
classes | third_party_imports listlengths 0 5 | stdlib_only bool 2
classes | question_norm_sha1 stringlengths 40 40 | solution_ast_sha1 stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
v1.0 | complete | Leetcode | Leetcode_12263_C | from typing import List
def is_subsequence(s: str, word: str) -> bool:
"""Check if a word is a subsequence of a string.
>>> is_subsequence("abracadabra", "abra") True
>>> is_subsequence("abracadabra", "bara") True
>>> is_subsequence("abracadabra", "cd") True
>>> is_subsequence("abracadabra", "xyz")... | def is_subsequence(s, word):
it = iter(s)
return all(char in it for char in word)
def max_subsequences_count(s, words):
count = 0
for word in words:
if is_subsequence(s, word):
count += 1
return count | from solution import max_subsequences_count, is_subsequence
def test_max_subsequences_count_basic():
s = "abracadabra"
words = ["abra", "bara", "cd", "xyz"]
assert max_subsequences_count(s, words) == 3
def test_max_subsequences_count_no_subsequences():
s = "abracadabra"
words = ["xyz", "mnop"]
... | [
{
"docstring": null,
"function_declaration": "def is_subsequence(s, word):",
"function_name": "is_subsequence",
"parameter_list": "(s, word)"
},
{
"docstring": null,
"function_declaration": "def max_subsequences_count(s, words):",
"function_name": "max_subsequences_count",
"param... | [
1,
1,
1,
1,
0,
1,
0,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_subsequence(s, word):\n \"\"\"\n Helper function to check if `word` is a subsequence of `s`.\n \"\"\"\n it = iter(s)\n return all(char in it for char in... | trial_gpt4o_9 | {
"original_instruction": "You are given a string `s` and a list of strings `words`. Your task is to find the **maximum** number of strings in `words` that are subsequences of `s`. A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters withou... | 0.7164 | Leetcode_12263 | C | [
"is_subsequence",
"max_subsequences_count"
] | 2 | [
[
"max_subsequences_count",
"is_subsequence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e1a42bdaaeae6a6dcfdd3e932f34b34bd67404ac | 79c7fe6262c5c86c092f721c256426be26a28d61 | |||
v1.0 | complete | Leetcode | Leetcode_12480_C | def find_kth_largest(arr: List[int], k: int) -> int:
""" Find the kth largest element in an unsorted array using the Quickselect algorithm.
>>> find_kth_largest([3, 2, 1, 5, 6, 4], 2) 5
>>> find_kth_largest([3, 2, 1, 5, 6, 4], 1) 6
>>> find_kth_largest([], 1) Raises IndexError
>>> find_kth_largest([... | def quickselect(arr, left, right, k):
"""
Helper function to perform the Quickselect operation.
"""
if left == right:
return arr[left]
pivot_index = partition(arr, left, right)
if k == pivot_index:
return arr[k]
elif k < pivot_index:
return quickselect(arr, ... | from solution import find_kth_largest
def test_kth_largest_example1():
arr = [3, 2, 1, 5, 6, 4]
k = 2
assert find_kth_largest(arr, k) == 5
def test_kth_largest_example2():
arr = [3, 2, 1, 5, 6, 4]
k = 1
assert find_kth_largest(arr, k) == 6
def test_kth_largest_empty_list():
arr = []
k... | [
{
"docstring": "Helper function to perform the Quickselect operation.",
"function_declaration": "def quickselect(arr, left, right, k):",
"function_name": "quickselect",
"parameter_list": "(arr, left, right, k)"
},
{
"docstring": "Helper function to partition the array around the pivot.",
... | [
1,
0,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import random\n\ndef quickselect(arr, left, right, k):\n if left == right:\n return arr[left]\n \n pivot_index = random.randint(left, right)\n \n pivot_... | trial_gpt4o_9 | {
"original_instruction": "You are given an **unsorted** integer array `arr` and an integer `k`. Your task is to find the **kth largest** element in the array without sorting the entire array. Use the **Quickselect** algorithm to solve this problem. The function should return the `kth` largest element in the array.\n... | 0.657655 | Leetcode_12480 | C | [
"quickselect",
"partition",
"find_kth_largest"
] | 3 | [
[
"find_kth_largest",
"quickselect"
],
[
"quickselect",
"partition"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 0d9ed7e0c0b79c180a05248cdacd082990754344 | 0a6be3753a9c56f9c45e51c94088c4b71c03709a | |||
v1.0 | complete | Leetcode | Leetcode_12541_C | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def bst_from_preorder(nums):
""" Construct a binary search tree from a list of integers given in preorder traversal.
>>> tree_to_list_preorder(bst_from_preorder([1]))
[1]
>>> tree_to_list_... | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def insert_into_bst(root, val):
# If the root is None, we create and return a new TreeNode with the value
if root is None:
return TreeNode(val)
if val < root.val:
# Insert... | from solution import TreeNode, bst_from_preorder
def tree_to_list_preorder(root):
# Helper function to convert tree to list in preorder traversal
if root is None:
return []
return [root.val] + tree_to_list_preorder(root.left) + tree_to_list_preorder(root.right)
def test_bst_from_preorder_single_el... | [] | [
1,
1,
1,
1,
1,
0,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\ndef insert_into_bst(root, val):\n \"\"\"\n Hel... | trial_gpt4o_9 | {
"original_instruction": "Given an integer array `nums` containing unique elements, construct a binary search tree by inserting the elements in the order given by `nums`. Return the root of the binary search tree. Implement a function that will construct and return the root node of the BST, where a class `TreeNode` ... | 0.49747 | Leetcode_12541 | C | [
"insert_into_bst",
"bst_from_preorder"
] | 2 | [
[
"bst_from_preorder",
"insert_into_bst"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 5027bba4317c9364fe240f2006ab27e1983feea6 | 4583980bd1ccd33a2e85e430143532f678f12554 | |||
v1.0 | complete | Leetcode | Leetcode_12568_C | def longest_alphabetical_substring(s: str) -> int:
"""
Returns the length of the longest substring (with at most one character removed) where the remaining characters are in alphabetical order.
>>> longest_alphabetical_substring("abcde") == 5
>>> longest_alphabetical_substring("abzcde") == 5
>>> lon... | def longest_alphabetical_substring(s):
"""
Returns the length of the longest substring (with at most one character removed)
where the remaining characters are in alphabetical order.
"""
n = len(s)
if n == 0:
return 0
max_length = 0
for i in range(n):
# Check the sub... | from solution import longest_alphabetical_substring
def test_longest_alphabetical_substring_without_removal():
assert longest_alphabetical_substring("abcde") == 5 # Already in order
def test_longest_alphabetical_substring_remove_one_character():
assert longest_alphabetical_substring("abzcde") == 5 # Removin... | [
{
"docstring": "Returns the length of the longest substring (with at most one character removed) \nwhere the remaining characters are in alphabetical order.",
"function_declaration": "def longest_alphabetical_substring(s):",
"function_name": "longest_alphabetical_substring",
"parameter_list": "(s)"
... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def longest_alphabetical_substring(s):\n \"\"\"\n Returns the length of the longest substring that can be formed by \n removing at most one character from the string... | trial_gpt4o_4 | {
"original_instruction": "You are given a string `s` made up of lowercase alphabets. You need to find the longest substring that can be formed by removing at most one character from `s` such that the remaining characters are in alphabetical order. Return the length of this longest alphabetical substring.",
"prompt... | 0.732919 | Leetcode_12568 | C | [
"longest_alphabetical_substring",
"calculate_length"
] | 2 | [
[
"longest_alphabetical_substring",
"calculate_length"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d93ec3577ffc39f2add3cc74b40c679c62821227 | 1ff567e697e848bfd148ce0f7ecbb272ea93882d | |||
v1.0 | complete | Leetcode | Leetcode_12598_C | from typing import List
def is_palindrome(n: int) -> bool:
"""
Check if the given integer n is a palindrome.
>>> is_palindrome(121) == True
>>> is_palindrome(1331) == True
>>> is_palindrome(123) == False
"""
pass
def filter_palindromes(nums: List[int]) -> List[int]:
"""
Given ... | def is_palindrome(n):
"""
Check if the given integer n is a palindrome.
"""
return str(n) == str(n)[::-1]
def filter_palindromes(nums):
"""
Given a list of integers, return a list of palindromes.
"""
return [num for num in nums if is_palindrome(num)] | from solution import is_palindrome, filter_palindromes
def test_is_palindrome_true_cases():
assert is_palindrome(121) == True
assert is_palindrome(1331) == True
assert is_palindrome(1) == True
assert is_palindrome(0) == True
def test_is_palindrome_false_cases():
assert is_palindrome(123) == False
... | [
{
"docstring": "Check if the given integer n is a palindrome.",
"function_declaration": "def is_palindrome(n):",
"function_name": "is_palindrome",
"parameter_list": "(n)"
},
{
"docstring": "Given a list of integers, return a list of palindromes.",
"function_declaration": "def filter_pali... | [
1,
1,
1,
1,
1,
1,
1,
0,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_palindrome(n):\n \"\"\"\n Helper function to check if a number is a palindrome.\n \"\"\"\n return str(n) == str(n)[::-1]\n\ndef filter_palindromes(nums):\n... | trial_gpt4o_9 | {
"original_instruction": "You are given a list of integers `nums`. For each integer in the list, check if it is a palindrome. A palindrome is a number that reads the same forwards and backwards (e.g., 121 or 1331). Return a new list containing only the integers from `nums` that are palindromes.",
"prompt_id": "000... | 0.745777 | Leetcode_12598 | C | [
"is_palindrome",
"filter_palindromes"
] | 2 | [
[
"filter_palindromes",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | feb8e49258fa60f5dbd208208d80349a7f0e32eb | e1ca4d25b02eed3cd9b1347c1d619598278f8044 | |||
v1.0 | complete | Leetcode | Leetcode_12633_C | def hamming_distance(a: int, b: int) -> int:
"""
Calculate the Hamming distance between two integers.
>>> hamming_distance(1, 4)
2
>>> hamming_distance(0, 15)
4
>>> hamming_distance(0, 0)
0
>>> hamming_distance(2, 3)
1
"""
def total_hamming_distance(nums: List[int]) -> int:... | def hamming_distance(a, b):
"""
Calculate the Hamming distance between two integers.
"""
return bin(a ^ b).count('1')
def total_hamming_distance(nums):
"""
Calculate the sum of Hamming distances between all pairs of integers in the array nums.
"""
total_distance = 0
n = len(nums)
... | from solution import hamming_distance, total_hamming_distance
def test_hamming_distance():
assert hamming_distance(1, 4) == 2, "Test Case 1 Failed"
assert hamming_distance(0, 15) == 4, "Test Case 2 Failed"
assert hamming_distance(0, 0) == 0, "Test Case 3 Failed"
assert hamming_distance(2, 3) == 1, "Tes... | [
{
"docstring": "Calculate the Hamming distance between two integers.",
"function_declaration": "def hamming_distance(a, b):",
"function_name": "hamming_distance",
"parameter_list": "(a, b)"
},
{
"docstring": "Calculate the sum of Hamming distances between all pairs of integers in the array n... | [
1,
1,
0,
0,
0,
0,
0,
1,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def totalHammingDistance(nums):\n \"\"\"\n Given an integer array `nums`, returns the sum of Hamming distances between all pairs of the integers in `nums`.\n \"\"\"\... | trial_gpt4o_8 | {
"original_instruction": "Given two integers `a` and `b`, their **Hamming distance** is the number of positions at which the corresponding bits are different. Write a function that, given an integer array `nums`, returns the sum of Hamming distances between all pairs of the integers in `nums`.",
"prompt_id": "0000... | 0.771094 | Leetcode_12633 | C | [
"hamming_distance",
"total_hamming_distance"
] | 2 | [
[
"total_hamming_distance",
"hamming_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6929ce6f3f68b918d247c738a83424ee546195ae | ab45b6d4e1a60e6407d4014a2b7445efd4035432 | |||
v1.0 | complete | Leetcode | Leetcode_12699_C | def num_magic_squares_inside(grid: List[List[int]]) -> int:
""" Count all 3x3 magic squares inside the given grid.
>>> num_magic_squares_inside([
[4,3,8,4],
[9,5,1,9],
[2,7,6,2]
]) 1
>>> num_magic_squares_inside([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]) 0
"""
from... | def is_magic(square):
"""
Check if a 3x3 grid is a magic square.
"""
s = list(set([square[i][j] for i in range(3) for j in range(3)]))
if sorted(s) != list(range(1, 10)):
return False
rows = [sum(square[i]) for i in range(3)]
cols = [sum([square[i][j] for i in range(3)]) for j i... | from solution import num_magic_squares_inside
def test_no_magic_squares():
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
assert num_magic_squares_inside(grid) == 0
def test_one_magic_square():
grid = [
[4, 3, 8, 4],
[9, 5, 1, 9],
[2, 7, 6, 2]
]
asse... | [
{
"docstring": "Check if a 3x3 grid is a magic square.",
"function_declaration": "def is_magic(square):",
"function_name": "is_magic",
"parameter_list": "(square)"
},
{
"docstring": "Count all 3x3 magic squares inside the given grid.",
"function_declaration": "def num_magic_squares_insid... | [
1,
1,
0,
1,
0,
1,
0,
0,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_magic(square):\n \"\"\"\n Check if a 3x3 square is a magic square.\n \"\"\"\n # Magic square values must be from 1 to 9, and all of them distinct\n vali... | trial_gpt4o_8 | {
"original_instruction": "You are given a 2D list of integers `matrix` where the shape of the matrix is `mxn`. A **magic square** is a `3x3` grid of distinct integers from 1 to 9 where the sum of the numbers in each row, column, and diagonal is equal. Write a function to count all magic squares inside the given `m x... | 0.592196 | Leetcode_12699 | C | [
"is_magic",
"num_magic_squares_inside"
] | 2 | [
[
"num_magic_squares_inside",
"is_magic"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dfbf75f1d89a4968a3e4c7dc6b14db7be5822f3c | e60a60668f799405207ddbbb4f8b667e5f72b8c7 | |||
v1.0 | complete | Leetcode | Leetcode_12756_C | def beautiful_array(nums: List[int]) -> List[int]:
""" Rearranges elements of an array to form a beautiful array if possible.
A beautiful array is one where no index `i` exists such that `nums[i]` is divisible
by any preceding element `nums[j]` where `j < i`.
If it is not possible to form such an array... | def beautiful_array(nums):
def construct(l):
if len(l) <= 1:
return l
odds = construct(l[::2])
evens = construct(l[1::2])
return odds + evens
nums.sort()
result = construct(nums)
return result if is_beautiful(result) else []
def is_beautiful(nums):
for i... | from solution import beautiful_array, is_beautiful
def test_beautiful_array_example():
nums = [2, 3, 4, 5, 6]
result = beautiful_array(nums)
assert is_beautiful(result)
def test_beautiful_array_impossible():
nums = [1, 2]
result = beautiful_array(nums)
assert result == []
def test_beautiful_a... | [
{
"docstring": null,
"function_declaration": "def beautiful_array(nums):",
"function_name": "beautiful_array",
"parameter_list": "(nums)"
},
{
"docstring": null,
"function_declaration": "def is_beautiful(nums):",
"function_name": "is_beautiful",
"parameter_list": "(nums)"
},
... | [
1,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def beautiful_array(nums):\n def construct(l):\n if len(l) <= 1:\n return l\n odds = construct(l[::2])\n evens = construct(l[1::2])\n ... | trial_gpt4o_0 | {
"original_instruction": "You are given an integer array `nums`. An array is considered beautiful if there is no index `i` such that `nums[i]` is divisible by any preceding element `nums[j]` where `j < i`. Write a function that modifies the given array by rearranging elements to form a beautiful array if possible. I... | 0.657156 | Leetcode_12756 | C | [
"beautiful_array",
"is_beautiful"
] | 2 | [
[
"beautiful_array",
"is_beautiful"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4616cdf03219e9d4d4dbc6b6b66e253b29bddad2 | 0ac2a9f53f5ff25dbb18878f04b429e7b4e455d0 | |||
v1.0 | complete | Leetcode | Leetcode_13479_C | def can_reach_last_row(grid, m, n, row, col, prev_height):
""" Checks if it is possible to reach the last row from a given cell in the first row.
Args:
grid (List[List[int]]): 2D list representing the grid.
m (int): Number of rows in the grid.
n (int): Number of columns in the grid.
row (in... | def can_reach_last_row(grid, m, n, row, col, prev_height):
if row >= m:
return False
if grid[row][col] > prev_height:
return False
if row == m - 1:
return True
down = right_diag = left_diag = False
if row + 1 < m:
down = can_reach_last_row(grid, m, n, row + 1, col, g... | def test_can_reach_last_row():
grid = [
[4, 3, 2, 1],
[3, 2, 1, 0],
[2, 1, 0, 0],
[1, 0, 0, 0]
]
assert can_reach_last_row(grid, 4, 4, 0, 0, 4) == True
assert can_reach_last_row(grid, 4, 4, 0, 1, 3) == True
assert can_reach_last_row(grid, 4, 4, 0, 2, 2) == True
as... | [
{
"docstring": null,
"function_declaration": "def can_reach_last_row(grid, m, n, row, col, prev_height):",
"function_name": "can_reach_last_row",
"parameter_list": "(grid, m, n, row, col, prev_height)"
},
{
"docstring": null,
"function_declaration": "def max_height_to_reach_last_row(grid... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def max_start_height(grid):\n \"\"\"\n Returns the maximum height from the first row to reach the last row in the given grid.\n \"\"\"\n if not grid or not grid[0... | trial_gpt4o_5 | {
"original_instruction": "You are given a 2D grid `grid` of size `m x n` consisting of non-negative integers, where `grid[i][j]` represents the height of a point `(i, j)` in a certain area. You can start from any point in the first row and try to reach any point in the last row. At each step, you can move to the cel... | 0.575751 | Leetcode_13479 | C | [
"can_reach_last_row",
"max_height_to_reach_last_row"
] | 2 | [
[
"max_height_to_reach_last_row",
"can_reach_last_row"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | ba4d281e7563e61ab47b886f0e7279daf386b0c6 | c83d44f4fa474d755f63802d34d5473272c2d196 | |||
v1.0 | complete | Leetcode | Leetcode_13495_C | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def sorted_array_to_bst(nums):
"""
Converts a sorted array to a balanced BST.
"""
if not nums:
return None
mid = len(nums) // 2
root = Tr... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def sorted_array_to_bst(nums):
"""
Converts a sorted array to a balanced BST.
"""
if not nums:
return None
mid = len(nums) // 2
root = Tr... | from solution import TreeNode, balance_bst, inorder_traversal
def is_balanced(root):
"""
Helper function to check if a binary tree is balanced.
"""
def check(root):
if not root:
return 0, True
left_height, left_balanced = check(root.left)
right_height, right... | [] | [
1,
1,
0,
1,
0,
1,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef balanceBST(root):\... | trial_gpt4o_9 | {
"original_instruction": "Given the root of a binary search tree (BST), return a balanced BST that has the same node values. A balanced BST is defined as a binary tree in which the depth of the two subtrees of every node never differs by more than 1. If there are multiple solutions, return any of them.",
"prompt_i... | 0.671144 | Leetcode_13495 | C | [
"sorted_array_to_bst",
"inorder_traversal",
"balance_bst"
] | 3 | [
[
"balance_bst",
"inorder_traversal"
],
[
"balance_bst",
"sorted_array_to_bst"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 031442d503f2ed2be156ab4cc1880c2cbe598348 | 2d5f57ea0e7d020b4c77e5fbf8f1a952539969d8 | |||
v1.0 | complete | Leetcode | Leetcode_13654_C | def next_prime(n: int) -> int:
""" Given an integer `n`, return the smallest prime number that is greater than `n`.
>>> next_prime(1) 2
>>> next_prime(2) 3
>>> next_prime(3) 5
>>> next_prime(4) 5
>>> next_prime(5) 7
>>> next_prime(10) 11
>>> next_prime(50) 53
>>> next_prime(0) 2
... | def is_prime(num):
"""
Helper function to check if a number is prime.
"""
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return F... | from solution import next_prime
def test_next_prime_small_numbers():
assert next_prime(1) == 2
assert next_prime(2) == 3
assert next_prime(3) == 5
assert next_prime(4) == 5
assert next_prime(5) == 7
def test_next_prime_larger_numbers():
assert next_prime(10) == 11
assert next_prime(11) == ... | [
{
"docstring": "Helper function to check if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Returns the smallest prime number that is greater than n.",
"function_declaration": "def next_prime(n):... | [
1,
1,
1,
0,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Returns True if the given number is a prime number, False otherwise.\n \"\"\"\n if num <= 1:\n return False\n if num <= 3:... | trial_gpt4o_9 | {
"original_instruction": "Given an integer `n`, return the smallest prime number that is greater than `n`. \n\nTo solve the problem, you need to implement a function that efficiently checks for the next prime number beyond the given integer `n`. A prime number is a positive integer greater than 1 that has no positiv... | 0.76988 | Leetcode_13654 | C | [
"is_prime",
"next_prime"
] | 2 | [
[
"next_prime",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0906d95b7221b147a88a591d6e630bf17a250a04 | 6fe321dd4b027c0bfc91120f987d8748ce7a1785 | |||
v1.0 | complete | Leetcode | Leetcode_13785_C | def palindrome_partitions(s: str) -> List[List[str]]:
""" Given a string s containing only lowercase letters, return all possible palindrome partitions of s.
>>> palindrome_partitions("racecar")
[['r', 'a', 'c', 'e', 'c', 'a', 'r'],
['r', 'a', 'cec', 'a', 'r'],
['r', 'aceca', 'r'],
['racec... | def is_palindrome(s):
"""
Determines if a given string s is a palindrome.
"""
return s == s[::-1]
def backtrack(start, s, path, result):
"""
Uses backtracking to find all palindrome partitions from the start index.
"""
if start == len(s):
result.append(path[:])
return
... | from solution import palindrome_partitions
def test_single_character():
assert palindrome_partitions("a") == [["a"]]
def test_two_characters_palindrome():
assert palindrome_partitions("aa") == [["a", "a"], ["aa"]]
def test_two_characters_non_palindrome():
assert palindrome_partitions("ab") == [["a", "b"]... | [
{
"docstring": "Determines if a given string s is a palindrome.",
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "Uses backtracking to find all palindrome partitions from the start index.",
"function_declaratio... | [
1,
0,
1,
1,
0,
0,
1,
1,
0,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_palindrome(s):\n return s == s[::-1]\n\ndef partition(s):\n def dfs(start, path, res):\n if start >= len(s):\n res.append(path.copy())\n ... | trial_gpt4o_7 | {
"original_instruction": "Given a string `s` containing only lowercase letters, you need to find and return all possible **palindrome partitions** of `s`. A palindrome partitioning of a string is a decomposition of the string into substrings such that each substring is a palindrome. Each substring must be a contiguo... | 0.669877 | Leetcode_13785 | C | [
"is_palindrome",
"backtrack",
"palindrome_partitions"
] | 3 | [
[
"backtrack",
"is_palindrome"
],
[
"palindrome_partitions",
"backtrack"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ab74e40c8b7a22262d994ea131ff04f324d8cc41 | 723bb2e8adcccf75c4aba0963928b12d8a656683 | |||
v1.0 | complete | Leetcode | Leetcode_13787_C | from typing import List
def universal_words(words: List[str], chars: str) -> List[str]:
""" Return a list of all universal words in words.
A word is called universal if all the letters in chars appear in it at least as many times
as they appear in chars. The output list should be sorted in lexicographical... | from collections import Counter
def is_universal_word(word, chars_count):
word_count = Counter(word)
for char, count in chars_count.items():
if word_count[char] < count:
return False
return True
def universal_words(words, chars):
chars_count = Counter(chars)
universal_list = [w... | from solution import universal_words
def test_basic():
words = ["apple", "banana", "cherry", "date"]
chars = "an"
assert universal_words(words, chars) == ["banana"]
def test_multiple_universals():
words = ["apple", "banana", "ananas", "date"]
chars = "an"
assert universal_words(words, chars) =... | [
{
"docstring": null,
"function_declaration": "def is_universal_word(word, chars_count):",
"function_name": "is_universal_word",
"parameter_list": "(word, chars_count)"
},
{
"docstring": null,
"function_declaration": "def universal_words(words, chars):",
"function_name": "universal_wo... | [
1,
0,
0,
1,
1,
0,
0,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def count_characters(word):\n \"\"\"\n Returns a dictionary with character counts in the given word.\n \"\"\"\n char_count = {}\n for char in word:\n if... | trial_gpt4o_4 | {
"original_instruction": "You are given a list of strings `words` containing lowercase English letters. A word is called **universal** if all the letters in a given string `chars` appear in it at least as many times as they appear in `chars`. Return _a list of all **universal** words in_ `words`. The output list sho... | 0.645162 | Leetcode_13787 | C | [
"is_universal_word",
"universal_words"
] | 2 | [
[
"universal_words",
"is_universal_word"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ca1edadd0483e0085e5cef95a79ecef455910d3c | 50b5c8bde92b05d60bd19aea7442d12b1a75954d | |||
v1.0 | complete | Leetcode | Leetcode_13819_C | from typing import List
from collections import defaultdict
import itertools
def find_group_count(files: List[str], k: int) -> int:
""" Find the number of connected groups of similar files based on common subsequences of length `k`.
Args:
files (List[str]): List of file contents as strings.
... | from collections import defaultdict
import itertools
def find_common_subsequences(s1, s2, length):
"""
Returns True if there is at least one common subsequence of given length `length` between strings `s1` and `s2`.
"""
s1_subsequences = {s1[i:i+length] for i in range(len(s1) - length + 1)}
s2_subs... | from solution import find_group_count
def test_no_files():
assert find_group_count([], 3) == 0
def test_single_file():
assert find_group_count(["abc"], 2) == 1
def test_all_files_similar():
assert find_group_count(["abc", "bcd", "cde"], 2) == 1
def test_no_files_similar():
assert find_group_count(["... | [
{
"docstring": "Returns True if there is at least one common subsequence of given length `length` between strings `s1` and `s2`.",
"function_declaration": "def find_common_subsequences(s1, s2, length):",
"function_name": "find_common_subsequences",
"parameter_list": "(s1, s2, length)"
},
{
"... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from itertools import combinations\nfrom collections import defaultdict\n\ndef has_common_subsequence(file1, file2, k):\n \"\"\"\n Check if two files have at least one ... | trial_gpt4o_8 | {
"original_instruction": "You are given a list of `n` files where each file is represented by its path as a string in a list called `files`. Each file contains a string of lowercase alphabets. Two files are said to be **similar** if they have at least one common subsequence of length `k` (where `k` is a given positi... | 0.619347 | Leetcode_13819 | C | [
"find_common_subsequences",
"find_group_count"
] | 2 | [
[
"find_group_count",
"find_common_subsequences"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5b73b04c1cea065a568716c7d645bcbe6fbc9553 | 6e496c292ac8281578907bf001e96c027534129f | |||
v1.0 | complete | Leetcode | Leetcode_13877_C | def is_prime(num):
"""
Checks if a number is prime.
>>> is_prime(2) True
>>> is_prime(3) True
>>> is_prime(4) False
>>> is_prime(17) True
>>> is_prime(18) False
>>> is_prime(19) True
>>> is_prime(1) False
>>> is_prime(-5) False
"""
def generate_primes(n):
"""
Gen... | def is_prime(num):
"""
Checks if a number is prime.
"""
if num <= 1:
return False
if num == 2:
return True
if num % 2 == 0:
return False
p = 3
while p * p <= num:
if num % p == 0:
return False
p += 2
return True
def generate_primes... | from solution import generate_primes, is_prime
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(18) == False
assert is_prime(19) == True
assert is_prime(1) == False
assert is_prime(-5) == F... | [
{
"docstring": "Checks if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Generates a list of the first `n` prime numbers in ascending order.",
"function_declaration": "def generate_primes(n):",
... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"\n Check if a number is a prime.\n \"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2 =... | trial_gpt4o_8 | {
"original_instruction": "Given an integer `n`, generate a list of the first `n` prime numbers in ascending order.",
"prompt_id": "0000013877",
"row_id": 13877,
"seed_ids": "['59', '1100', '2133']"
} | 0.851436 | Leetcode_13877 | C | [
"is_prime",
"generate_primes"
] | 2 | [
[
"generate_primes",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ee5fc2e4b809b8190a2fba5bcc109856646e2e75 | 220cb740ae1c45d07cf0b5104d08245332af4c4a | |||
v1.0 | complete | Leetcode | Leetcode_13889_C | def minimumLatency(n: int, connections: List[Tuple[int, int, int]]) -> int:
""" Find the minimum latency required to connect all the servers in the network.
>>> minimumLatency(4, [(0, 1, 1), (1, 2, 2), (2, 3, 1), (0, 2, 2)])
4
>>> minimumLatency(2, [(0, 1, 10)])
10
>>> minimumLatency(4, [(0, 1, ... | def find(parent, i):
if parent[i] == i:
return i
else:
return find(parent, parent[i])
def union(parent, rank, x, y):
root_x = find(parent, x)
root_y = find(parent, y)
if root_x != root_y:
if rank[root_x] > rank[root_y]:
parent[root_y] = root_x
... | def test_minimumLatency_full_connectivity():
assert minimumLatency(4, [(0, 1, 1), (1, 2, 2), (2, 3, 1), (0, 2, 2)]) == 4
def test_minimumLatency_one_connection():
assert minimumLatency(2, [(0, 1, 10)]) == 10
def test_minimumLatency_no_connection():
assert minimumLatency(4, [(0, 1, 1), (2, 3, 2)]) == -1
d... | [
{
"docstring": null,
"function_declaration": "def find(parent, i):",
"function_name": "find",
"parameter_list": "(parent, i)"
},
{
"docstring": null,
"function_declaration": "def union(parent, rank, x, y):",
"function_name": "union",
"parameter_list": "(parent, rank, x, y)"
},
... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def minimumLatency(n, connections):\n \"\"\"\n Returns the minimum total latency required to connect all servers.\n \"\"\"\n # Helper function to find the parent ... | trial_gpt4o_6 | {
"original_instruction": "A company has a network that consists of a mixture of wired and wireless connections between servers. Each connection between two servers has a latency (in milliseconds). You are given a list of connections, where each connection is represented as a tuple `(server1, server2, latency)`. A ne... | 0.519371 | Leetcode_13889 | C | [
"find",
"union",
"minimumLatency"
] | 3 | [
[
"minimumLatency",
"find"
],
[
"minimumLatency",
"union"
],
[
"union",
"find"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | d9a777eeb0b0e6fe9f1597081499d70078f6cbaa | ccf7a698ed690538dc9690eec0850ff31c0f32ce | |||
v1.0 | complete | Leetcode | Leetcode_13941_C | from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def constructBST(nums: List[int]) -> List[int]:
""" Construct a binary search tree (BST) from a list of unique integers
and return its inorder traversal as a list of integ... | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def insert_into_bst(root, val):
if root is None:
return TreeNode(val)
if val < root.val:
root.left = insert_into_bst(root.left, val)
else:
root.right = insert_into_bst(... | from solution import constructBST
def test_constructBST_example():
assert constructBST([8, 5, 10, 1, 7, 12]) == [1, 5, 7, 8, 10, 12]
def test_constructBST_single_element():
assert constructBST([5]) == [5]
def test_constructBST_two_elements():
assert constructBST([5, 3]) == [3, 5]
assert constructBST(... | [] | [
1,
1,
0,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef insert_into_bst(ro... | trial_gpt4o_8 | {
"original_instruction": "You are given an integer array `nums` where each element is unique. You want to construct a binary search tree (BST) from `nums` where the following two conditions are met:\n\n* The root node is `nums[0]`.\n* If there is a node in the tree with a value `nums[j]`, then `nums[j]` appe... | 0.527252 | Leetcode_13941 | C | [
"insert_into_bst",
"inorder_traversal",
"constructBST"
] | 3 | [
[
"constructBST",
"inorder_traversal"
],
[
"constructBST",
"insert_into_bst"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | f53d192804d53985ed1b9201a0210a3cc8a7ba80 | a8ef26a5b023fb42a2f68f78d31e47535d26fbdf | |||
v1.0 | complete | Leetcode | Leetcode_13998_C | def rotate_matrix_90_degrees_clockwise(matrix):
""" Rotate the matrix 90 degrees clockwise.
>>> rotate_matrix_90_degrees_clockwise([[1, 2], [3, 4]])
[[3, 1], [4, 2]]
>>> rotate_matrix_90_degrees_clockwise([[1, 2, 3], [4, 5, 6]])
[[4, 1], [5, 2], [6, 3]]
"""
pass
def max_row_sum_after_rotati... | def rotate_matrix_90_degrees_clockwise(matrix):
"""
Rotate the matrix 90 degrees clockwise.
"""
return [list(row) for row in zip(*matrix[::-1])]
def max_row_sum_after_rotations(matrix):
"""
Return the maximum sum of the elements in any row of the matrix
after performing any number of 90 deg... | from solution import max_row_sum_after_rotations, rotate_matrix_90_degrees_clockwise
def test_rotate_matrix_90_degrees_clockwise():
assert rotate_matrix_90_degrees_clockwise([[1, 2], [3, 4]]) == [[3, 1], [4, 2]]
assert rotate_matrix_90_degrees_clockwise([[1, 2, 3], [4, 5, 6]]) == [[4, 1], [5, 2], [6, 3]]
def ... | [
{
"docstring": "Rotate the matrix 90 degrees clockwise.",
"function_declaration": "def rotate_matrix_90_degrees_clockwise(matrix):",
"function_name": "rotate_matrix_90_degrees_clockwise",
"parameter_list": "(matrix)"
},
{
"docstring": "Return the maximum sum of the elements in any row of the... | [
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def rotate_matrix_90_degrees_clockwise(matrix):\n \"\"\"\n Rotate the matrix 90 degrees clockwise.\n \"\"\"\n return [list(row) for row in zip(*matrix[::-1])]\n\n... | trial_gpt4o_0 | {
"original_instruction": "You are given a matrix `mat` of size `m x n` consisting of **positive** integers. You can **rotate** the matrix 90 degrees clockwise. Return _the **maximum** sum of the elements in any row of the matrix after performing any number of rotations._",
"prompt_id": "0000013998",
"row_id": 1... | 0.519735 | Leetcode_13998 | C | [
"rotate_matrix_90_degrees_clockwise",
"max_row_sum_after_rotations"
] | 2 | [
[
"max_row_sum_after_rotations",
"rotate_matrix_90_degrees_clockwise"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 16d5fb97cc465004a572fba1e7d366c5a5feef2e | 6d4c4ef561a2231e342fdd36f6e726c2d8400838 | |||
v1.0 | complete | Leetcode | Leetcode_14160_C | from typing import Optional, List
class TreeNode:
def __init__(self, val: int = 0, left: Optional['TreeNode'] = None, right: Optional['TreeNode'] = None):
self.val = val
self.left = left
self.right = right
def min_swaps_binary_tree(root: Optional[TreeNode]) -> int:
"""
Determine t... | def min_swaps_to_sort(arr):
"""
Helper function to count the minimum number of swaps required to
sort an array.
"""
n = len(arr)
arrpos = [(val, idx) for idx, val in enumerate(arr)]
arrpos.sort()
visited = {k: False for k in range(n)}
ans = 0
for i in range(n):
if visite... | from solution import TreeNode, min_swaps_binary_tree
def test_single_node():
root = TreeNode(1)
assert min_swaps_binary_tree(root) == 0
def test_already_sorted():
root = TreeNode(1, TreeNode(2), TreeNode(3))
assert min_swaps_binary_tree(root) == 0
def test_unsorted():
root = TreeNode(1, TreeNode(... | [] | [
0,
1,
0,
0,
0,
0,
1,
0,
0
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from collections import defaultdict, deque\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n ... | trial_gpt4o_1 | {
"original_instruction": "You are given a binary tree where each node has a value `val` from `0` to `4`. Each step, you can choose one or multiple nodes at the current level and swap their subtrees. Distance between two nodes is the number of edges along the shortest path connecting them. Your task is to determine t... | 0.56653 | Leetcode_14160 | C | [
"min_swaps_to_sort",
"level_order_traversal",
"min_swaps_binary_tree"
] | 3 | [
[
"min_swaps_binary_tree",
"level_order_traversal"
],
[
"min_swaps_binary_tree",
"min_swaps_to_sort"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | f6f0e700d767ca906a0ab7747b8212e8f4dcb294 | b0f4de8be128bf7cd7d83c3c9978fa5fbc5b07a5 | |||
v1.0 | complete | Leetcode | Leetcode_14473_C | from typing import List
def edit_distance(word1: str, word2: str) -> int:
"""
Compute the edit distance between two words.
"""
len1, len2 = len(word1), len(word2)
dp = [[0] * (len2 + 1) for _ in range(len1 + 1)]
for i in range(len1 + 1):
for j in range(len2 + 1):
if i == 0:... | def edit_distance(word1, word2):
"""
Compute the edit distance between two words.
"""
len1, len2 = len(word1), len(word2)
dp = [[0] * (len2 + 1) for _ in range(len1 + 1)]
for i in range(len1 + 1):
for j in range(len2 + 1):
if i == 0:
dp[i][j] = j
... | from solution import spell_checker
def test_word_in_dictionary():
dictionary = ["solution", "solver", "testing", "example"]
assert spell_checker(dictionary, "solution") == "solution"
assert spell_checker(dictionary, "testing") == "testing"
def test_word_not_in_dictionary():
dictionary = ["solution", "... | [
{
"docstring": "Compute the edit distance between two words.",
"function_declaration": "def edit_distance(word1, word2):",
"function_name": "edit_distance",
"parameter_list": "(word1, word2)"
},
{
"docstring": "Check the spelling of a given word against a dictionary.",
"function_declarat... | [
0,
1,
1,
0,
0,
1,
0,
1,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def edit_distance(word1, word2):\n len1, len2 = len(word1), len(word2)\n dp = [[0] * (len2 + 1) for _ in range(len1 + 1)]\n\n for i in range(len1 + 1):\n for ... | trial_gpt4o_9 | {
"original_instruction": "You have been tasked with implementing a simplified version of a spell checker. Given a list of words in a dictionary and a string containing a single word, determine whether the given word is spelled correctly. \n\nA word is considered correctly spelled if it exactly matches one of the wor... | 0.60994 | Leetcode_14473 | C | [
"edit_distance",
"spell_checker"
] | 2 | [
[
"spell_checker",
"edit_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c34c983715dc5b3d5126d17ce3702179f702fa63 | a6f529602d9a197461e5088f0210be3cf00b5ac7 | |||
v1.0 | complete | Leetcode | Leetcode_14649_C | from typing import List
def universal_strings(words1: List[str], words2: List[str]) -> List[str]:
"""
You are given two arrays `words1` and `words2`. A string `b` is a **universal string** of an array of strings `words`
if for every string `a` in `words`, every letter in `a` appears in `b` at least as man... | from collections import Counter
def is_universal(b, words):
"""
Helper function to determine if string b is a universal string for the array words.
"""
b_counter = Counter(b)
for word in words:
word_counter = Counter(word)
for char, count in word_counter.items():
if b_co... | from solution import universal_strings
def test_universal_strings_1():
words1 = ["a"]
words2 = ["a", "b", "ab", "abc"]
assert universal_strings(words1, words2) == ["a", "ab", "abc"]
def test_universal_strings_2():
words1 = ["abc"]
words2 = ["a", "b", "ab", "abc"]
assert universal_strings(words... | [
{
"docstring": "Helper function to determine if string b is a universal string for the array words.",
"function_declaration": "def is_universal(b, words):",
"function_name": "is_universal",
"parameter_list": "(b, words)"
},
{
"docstring": "Returns an array of strings in words2 that are unive... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from collections import Counter\n\ndef max_frequency(words):\n \"\"\"\n Calculate the maximum frequency of each character across all words.\n \"\"\"\n max_freq = ... | trial_gpt4o_9 | {
"original_instruction": "You are given two arrays `words1` and `words2`. A string `b` is a **universal string** of an array of strings `words` if for every string `a` in `words`, every letter in `a` appears in `b` at least as many times as it appears in `a`. For example, \"abca\" is a universal string for [\"a\", \... | 0.678616 | Leetcode_14649 | C | [
"is_universal",
"universal_strings"
] | 2 | [
[
"universal_strings",
"is_universal"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ee9124b667b2813949e387cadfe500833c46e87f | e52196903fd829ed0f52d23b21c566fbb764397d | |||
v1.0 | complete | Leetcode | Leetcode_15043_C | def kruskals_mst(n: int, connections: List[List[int]]) -> int:
""" Find the minimum spanning tree (MST) of a connected graph with `n` vertices and `m` edges.
Each edge in the graph has a weight denoted by `connections[i] = [u, v, w]` where `u` and `v`
are vertices and `w` is the weight of the edge connectin... | def find(parent, i):
if parent[i] == i:
return i
else:
return find(parent, parent[i])
def union(parent, rank, x, y):
root_x = find(parent, x)
root_y = find(parent, y)
if rank[root_x] < rank[root_y]:
parent[root_x] = root_y
elif rank[root_x] > rank[root_y]:
parent... | from solution import kruskals_mst
def test_kruskals_mst_case1():
n = 4
connections = [
[0, 1, 1],
[1, 2, 2],
[0, 2, 4],
[2, 3, 3],
[1, 3, 5]
]
expected = 6 # MST includes edges (0-1), (1-2), and (2-3)
assert kruskals_mst(n, connections) == expected
def test... | [
{
"docstring": null,
"function_declaration": "def find(parent, i):",
"function_name": "find",
"parameter_list": "(parent, i)"
},
{
"docstring": null,
"function_declaration": "def union(parent, rank, x, y):",
"function_name": "union",
"parameter_list": "(parent, rank, x, y)"
},
... | [
1,
1,
1,
0,
0,
0,
0,
0,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def find(parent, i):\n if parent[i] == i:\n return i\n else:\n return find(parent, parent[i])\n\ndef union(parent, rank, x, y):\n root_x = find(parent,... | trial_gpt4o_9 | {
"original_instruction": "You are given a connected graph with `n` vertices and `m` edges represented as an edge list `connections`. Each edge in the graph has a weight denoted by `connections[i] = [u, v, w]` where `u` and `v` are vertices and `w` is the weight of the edge connecting them. The graph is **not guarant... | 0.769491 | Leetcode_15043 | C | [
"find",
"union",
"kruskals_mst"
] | 3 | [
[
"kruskals_mst",
"find"
],
[
"kruskals_mst",
"union"
],
[
"union",
"find"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 0df29bbc6ac3f61eebecfbe801916012ca4f2e9d | 92755bcb7836adb6975cc20dbe0bdae416424782 | |||
v1.0 | complete | Leetcode | Leetcode_15098_C | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def count_paths_with_sum(root: TreeNode, targetSum: int) -> int:
"""Returns the number of distinct root-to-leaf paths in which the sum of the values
of the nodes on ... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def path_sum_helper(node, targetSum, current_sum):
if node is None:
return 0
current_sum += node.val
# If it's a leaf node and sum match... | from solution import TreeNode, count_paths_with_sum
def test_single_node_equal_to_target():
# Tree: [5]
root = TreeNode(5)
assert count_paths_with_sum(root, 5) == 1
def test_single_node_not_equal_to_target():
# Tree: [5]
root = TreeNode(5)
assert count_paths_with_sum(root, 10) == 0
def test_m... | [] | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef pathSum(root, targ... | trial_gpt4o_3 | {
"original_instruction": "Given a binary tree, root-to-leaf paths are paths from the root node to any leaf node. A leaf node is defined as a node with no children.\n\nWrite a function that returns _the number of distinct root-to-leaf paths in which the sum of the values of the nodes on the path is equal to a given t... | 0.614035 | Leetcode_15098 | C | [
"path_sum_helper",
"count_paths_with_sum"
] | 2 | [
[
"count_paths_with_sum",
"path_sum_helper"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 6843fefe367f45d21612970b337ce40217b04c77 | 264765a5f2dfeb0efe103fcefabdcd9d90be99fc | |||
v1.0 | complete | Leetcode | Leetcode_15258_C | def inorder_traversal(nums):
"""
Generates the binary tree T from the nums array and returns its in-order traversal.
Args:
nums (List[int]): List of unique integers.
Returns:
List[int]: In-order traversal of the binary tree.
"""
pass
def test_inorder_traversal_single():
as... | class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert_node(root, value):
from collections import deque
queue = deque([root])
while queue:
node = queue.popleft()
if node.left is None:
node.le... | from solution import inorder_traversal
def test_inorder_traversal_single():
assert inorder_traversal([1]) == [1]
def test_inorder_traversal_two():
assert inorder_traversal([1, 2]) == [2, 1]
def test_inorder_traversal_three():
assert inorder_traversal([1, 2, 3]) == [2, 1, 3]
def test_inorder_traversal_mu... | [] | [
0,
1,
1,
1,
1,
0,
0,
1,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef insert_into_tree(r... | trial_gpt4o_9 | {
"original_instruction": "You are given a **0-indexed** integer array `nums` of length `n` where all values are unique. A binary tree `T` is generated in the following way: \n1. Use `nums[0]` as the root node.\n2. Repeat the following steps for each `element` in `nums` following the order of the array:\n - Insert... | 0.580209 | Leetcode_15258 | C | [
"insert_node",
"build_tree",
"in_order_traversal",
"inorder_traversal"
] | 4 | [
[
"build_tree",
"insert_node"
],
[
"inorder_traversal",
"build_tree"
],
[
"inorder_traversal",
"in_order_traversal"
]
] | 3 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 62754fda04e883ea39e6f211ecffb09f239413ad | 6dd3a0d5dd9e75b20442b536ef29012dea4a3b6d | |||
v1.0 | complete | Leetcode | Leetcode_15303_C | from typing import List
def minimize_max_subarray_sum_difference(arr: List[int], m: int) -> int:
"""
Given a list of non-negative integers `arr` and an integer `m`, partition the list into
`m` non-empty contiguous subarrays such that the difference between the largest sum
of any subarray and the smalle... | def can_partition(arr, m, max_sum):
"""
Helper function to check if the array can be partitioned
into m subarrays with the given max_sum or not.
"""
current_sum = 0
count = 1 # Starting with one subarray
for num in arr:
if current_sum + num > max_sum:
count += 1
... | from solution import minimize_max_subarray_sum_difference
def test_minimize_max_subarray_sum_difference_example_1():
arr = [7, 2, 5, 10, 8]
m = 2
assert minimize_max_subarray_sum_difference(arr, m) == 18
def test_minimize_max_subarray_sum_difference_example_2():
arr = [1, 2, 3, 4, 5]
m = 2
ass... | [
{
"docstring": "Helper function to check if the array can be partitioned\ninto m subarrays with the given max_sum or not.",
"function_declaration": "def can_partition(arr, m, max_sum):",
"function_name": "can_partition",
"parameter_list": "(arr, m, max_sum)"
},
{
"docstring": "Function to pa... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def min_difference_partition(arr, m):\n \"\"\"\n Partition the list into `m` subarrays such that the difference between the largest and smallest\n sum of any subarra... | trial_gpt4o_5 | {
"original_instruction": "Given a list of non-negative integers `arr` and an integer `m`, partition the list into `m` non-empty contiguous subarrays such that the difference between the largest sum of any subarray and the smallest sum of any subarray is minimized. Return the minimum difference.",
"prompt_id": "000... | 0.76147 | Leetcode_15303 | C | [
"can_partition",
"minimize_max_subarray_sum_difference"
] | 2 | [
[
"minimize_max_subarray_sum_difference",
"can_partition"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8e80c0db10c6f81804b33be847a8102cfcd63975 | f7b815e5d328d0a5f5106a52260e35c49cc1d02d | |||
v1.0 | complete | Leetcode | Leetcode_15423_C | def split_into_palindromes(s: str, k: int) -> list[str]:
""" Given a string `s` and an integer `k`, split the string into `k` non-empty palindromic substrings.
Return a list of `k` palindromic substrings if such a split is possible, or an empty list if it is not.
A string is a palindrome if it reads the sam... | def is_palindrome(s):
return s == s[::-1]
def split_into_palindromes(s, k):
n = len(s)
result = []
def backtrack(start, cut):
if cut == 0:
if start == n:
return True
return False
for end in range(start + 1, n + 1):
sub_str = s[start:... | from solution import split_into_palindromes
def test_split_into_palindromes_basic():
assert split_into_palindromes("racecarannakayak", 3) == ["racecar", "anna", "kayak"]
def test_split_into_palindromes_one_partition():
assert split_into_palindromes("level", 1) == ["level"]
def test_split_into_palindromes_mul... | [
{
"docstring": null,
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": null,
"function_declaration": "def split_into_palindromes(s, k):",
"function_name": "split_into_palindromes",
"parameter_list": "(s, k... | [
0,
0,
0,
0,
0,
1,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_palindrome(s):\n \"\"\"\n Helper function to check if a string is a palindrome.\n \"\"\"\n return s == s[::-1]\n\ndef split_into_palindromes(s, k):\n \"... | trial_gpt4o_7 | {
"original_instruction": "Given a string `s` and an integer `k`, you need to split the string into `k` non-empty palindromic substrings. Return _a list of_ `k` _palindromic substrings if such a split is possible, or an empty list if it is not._ A string is a **palindrome** if it reads the same forward and backward."... | 0.737881 | Leetcode_15423 | C | [
"is_palindrome",
"split_into_palindromes"
] | 2 | [
[
"split_into_palindromes",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3db4edea667e53734f389d44c987b8a362a9b496 | abec8d2ccdb619a78a0bce7125cbde82ea3a08dc | |||
v1.0 | complete | Leetcode | Leetcode_15629_C | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def min_sum_covering_levels(root: TreeNode, k: int) -> int:
"""
Given a `root` of a binary tree, choose `k` nodes from the tree such that the sum of their values
... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def dfs(node, depth, nodes_by_level):
if not node:
return
if depth in nodes_by_level:
nodes_by_level[depth].append(node.val)
else:
nodes_b... | from solution import TreeNode, min_sum_covering_levels
def test_min_sum_covering_levels_single_node():
root = TreeNode(1)
assert min_sum_covering_levels(root, 1) == 1
def test_min_sum_covering_levels_two_levels():
root = TreeNode(1, TreeNode(2), TreeNode(3))
assert min_sum_covering_levels(root, 2) == ... | [] | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef minimum_sum_of_k_n... | trial_gpt4o_8 | {
"original_instruction": "Given a `root` of a binary tree, each node in the tree has a unique value. You are to choose `k` nodes from the tree such that the sum of their values is minimized and the chosen nodes cover all levels of the tree. A node is said to cover a level if there exists a path from the node to any ... | 0.613971 | Leetcode_15629 | C | [
"dfs",
"min_sum_covering_levels"
] | 2 | [
[
"min_sum_covering_levels",
"dfs"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | ff68b59dc4fbe78e3fb35f3e54eb803db5fcafe3 | 6ffde8570bb78c3c87db3e14eea653cad6eb59d4 | |||
v1.0 | complete | Leetcode | Leetcode_15670_C | from typing import List
def find_matching_words(wordlist: List[str], typed_word: str) -> List[str]:
"""Find all words in `wordlist` that are subsequences of the `typed_word`.
>>> find_matching_words(["apple", "app", "apricot", "banana", "grape"], "app")
["app"]
>>> find_matching_words(["dog", "cat... | def is_subsequence(word, typed_word):
"""
Helper function to check if `word` is a subsequence of `typed_word`.
"""
it = iter(typed_word)
return all(char in it for char in word)
def find_matching_words(wordlist, typed_word):
"""
Find all words in `wordlist` that are subsequences of the `type... | from solution import find_matching_words
def test_find_matching_words():
wordlist = ["apple", "app", "apricot", "banana", "grape"]
typed_word = "app"
assert find_matching_words(wordlist, typed_word) == ["app"]
wordlist = ["dog", "cat", "bat"]
typed_word = "dcaotg"
assert find_matching_word... | [
{
"docstring": "Helper function to check if `word` is a subsequence of `typed_word`.",
"function_declaration": "def is_subsequence(word, typed_word):",
"function_name": "is_subsequence",
"parameter_list": "(word, typed_word)"
},
{
"docstring": "Find all words in `wordlist` that are subsequen... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_subsequence(word, typed_word):\n \"\"\"\n Checks if `word` is a subsequence of `typed_word`.\n \"\"\"\n it = iter(typed_word)\n return all(char in it fo... | trial_gpt4o_9 | {
"original_instruction": "You are given a list of strings `wordlist`. A person types a word and misses out on some (possibly zero) letters, and types the remaining letters in order. A typed word qualifies to match `wordlist[i]` if and only if `wordlist[i]` is a subsequence of the typed word. Find all words in `wordl... | 0.682855 | Leetcode_15670 | C | [
"is_subsequence",
"find_matching_words"
] | 2 | [
[
"find_matching_words",
"is_subsequence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 20b0498590d4feab00237357586f6853d2a5c533 | 5b5e89063dbad87f6dcf0feb30bd3d5a191d1006 | |||
v1.0 | complete | Leetcode | Leetcode_15975_C | def explore_lake(grid, visited, i, j, elevation):
""" Helper function to explore the lake and return its size """
def largest_lake(grid):
"""
Returns the size of the largest lake in the given grid.
>>> largest_lake([[1, 2, 2, 3], [3, 2, 1, 4], [4, 4, 3, 4]])
3
>>> largest_lake([[1, 1, 1, 2, 2,... | def explore_lake(grid, visited, i, j, elevation):
""" Helper function to explore the lake and return its size """
directions = [(-1, -1), (-1, 0), (-1, 1),
(0, -1), (0, 1),
(1, -1), (1, 0), (1, 1)]
stack = [(i, j)]
lake_size = 0
while stack:
... | from solution import largest_lake
def test_lake_in_single_row():
grid = [[1, 1, 1, 2, 2, 2]]
assert largest_lake(grid) == 3
def test_lake_in_single_column():
grid = [[3], [3], [4], [4], [4]]
assert largest_lake(grid) == 3
def test_lake_in_corner():
grid = [
[1, 1, 1],
[1, 2, 1],
... | [
{
"docstring": "Helper function to explore the lake and return its size ",
"function_declaration": "def explore_lake(grid, visited, i, j, elevation):",
"function_name": "explore_lake",
"parameter_list": "(grid, visited, i, j, elevation)"
},
{
"docstring": "Returns the size of the largest lak... | [
0,
0,
0,
0,
0,
1,
1,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def largest_lake(grid):\n \"\"\"\n Returns the size of the largest lake in the grid.\n \"\"\"\n if not grid:\n return 0\n\n rows, cols = len(grid), len(... | trial_gpt4o_6 | {
"original_instruction": "You are given a **0-indexed** matrix `grid` of integers where each cell represents the elevation at that point. A lake is defined as a contiguous group of cells that are all at the same elevation. The lake is surrounded by cells of higher elevation (or the boundary of the grid). The size of... | 0.612477 | Leetcode_15975 | C | [
"explore_lake",
"largest_lake"
] | 2 | [
[
"largest_lake",
"explore_lake"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a04f12bb3d2157e9c55f29371b6c6b34c878bf74 | 58378f799c3fe96b18945aacda260f79dc2cd9d3 | |||
v1.0 | complete | Leetcode | Leetcode_16394_C | def find_valid_words(sentence: str, valid_words: List[str]) -> List[str]:
"""
Returns a list of words in `sentence` which are valid permutations found in `valid_words`.
>>> find_valid_words("god dog cat", ["dog", "cat"])
["god", "dog", "cat"]
>>> find_valid_words("fish bird", ["dog", "cat"... | def is_permutation(word, valid_word):
return sorted(word) == sorted(valid_word)
def find_valid_words(sentence, valid_words):
"""
Returns a list of words in `sentence` which are valid permutations found in `valid_words`.
"""
words = sentence.split()
result = []
for word in words:
fo... | from solution import find_valid_words
def test_find_valid_words_basic():
sentence = "god dog cat"
valid_words = ["dog", "cat"]
expected_result = ["god", "dog", "cat"]
assert find_valid_words(sentence, valid_words) == expected_result
def test_find_valid_words_no_permutations():
sentence = "fish bir... | [
{
"docstring": null,
"function_declaration": "def is_permutation(word, valid_word):",
"function_name": "is_permutation",
"parameter_list": "(word, valid_word)"
},
{
"docstring": "Returns a list of words in `sentence` which are valid permutations found in `valid_words`.",
"function_declar... | [
0,
0,
1,
1,
0,
1,
0,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from collections import Counter\n\ndef valid_permutations(sentence, valid_words):\n \"\"\"\n Returns a list of valid permutations found in the sentence.\n\n :param s... | trial_gpt4o_8 | {
"original_instruction": "A string `sentence` is given which consists of words separated by spaces. Each word is a permutation of a word found in a given list of `valid_words`. Write a function that returns a list of words in `sentence` which are valid permutations found in `valid_words`. Each word in the result lis... | 0.64886 | Leetcode_16394 | C | [
"is_permutation",
"find_valid_words"
] | 2 | [
[
"find_valid_words",
"is_permutation"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | a2bbee01a3306a66f24a2e1f08602939ac13422b | 04f2d9c526dad49aeaeb3a12cc7b0ad8e91c2a17 | |||
v1.0 | complete | Leetcode | Leetcode_16476_C | def can_form_palindrome(words: List[str]) -> bool:
""" Returns True if any subset of two words can form a palindrome upon concatenation.
>>> can_form_palindrome(["ab", "ba"]) == True
>>> can_form_palindrome(["abc", "def"]) == False
>>> can_form_palindrome(["abc", "cba"]) == True
>>> can_form_palindr... | def is_palindrome(s):
"""
Helper function to check if a string is a palindrome.
"""
return s == s[::-1]
def can_form_palindrome(words):
"""
Returns True if any subset of two words can form a palindrome upon concatenation.
"""
for i in range(len(words)):
for j in range(i + 1, le... | from solution import can_form_palindrome
def test_can_form_palindrome_true_cases():
assert can_form_palindrome(["ab", "ba"]) == True
assert can_form_palindrome(["abc", "cba"]) == True
assert can_form_palindrome(["xyz", "zyx", "abc"]) == True
def test_can_form_palindrome_false_cases():
assert can_form_... | [
{
"docstring": "Helper function to check if a string is a palindrome.",
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "Returns True if any subset of two words can form a palindrome upon concatenation.",
"funct... | [
1,
1,
0,
1,
1,
1,
0,
0,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def can_form_palindrome(words):\n \"\"\"\n Returns true if there is at least one pair of words whose concatenation is a palindrome.\n \"\"\"\n \n def is_palind... | trial_gpt4o_9 | {
"original_instruction": "You are given a list of strings `words`. Each word is in lowercase and may contain duplicate letters. You need to find out if there is any subset of two words such that their concatenation results in a palindrome. Return true if at least one such subset exists, otherwise return false.",
"... | 0.773916 | Leetcode_16476 | C | [
"is_palindrome",
"can_form_palindrome"
] | 2 | [
[
"can_form_palindrome",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 25f17584dbe89a648532a9e285efd7bde2f58c36 | a75a78344b0c880e184ddd395d38938018e89018 | |||
v1.0 | complete | Leetcode | Leetcode_16523_C | from typing import List
def is_prime(n: int) -> bool:
""" Checks if a number n is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return... | def is_prime(n):
"""
Checks if a number n is prime.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return T... | from solution import has_prime_sum_subarray
def test_no_elements():
assert not has_prime_sum_subarray([])
def test_single_prime_element():
assert has_prime_sum_subarray([3])
def test_single_non_prime_element():
assert not has_prime_sum_subarray([4])
def test_multiple_elements_with_prime_sum():
asser... | [
{
"docstring": "Checks if a number n is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Determines whether there exists a subarray in arr whose sum is prime.",
"function_declaration": "def has_prime_sum_subarray... | [
1,
0,
1,
1,
1,
1,
0,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\n\ndef is_prime(n):\n \"\"\"\n Checks if a number n is a prime number.\n \"\"\"\n if n <= 1:\n return False\n if n <= 3:\n return Tru... | trial_gpt4o_7 | {
"original_instruction": "Given an integer array `arr`, determine whether there exists a subarray, whose sum of the elements is equal to a prime number. If such a subarray exists, return `true`; otherwise, return `false`. A **subarray** is a contiguous part of an array.\n\n### Constraints:\n- The number of subarrays... | 0.804189 | Leetcode_16523 | C | [
"is_prime",
"has_prime_sum_subarray"
] | 2 | [
[
"has_prime_sum_subarray",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 552b64cd0d88e7e3feb67aaf0ba5ef054814cc20 | 930c3f435038620cd6d26416a359237587f0a2c5 | |||
v1.0 | complete | Leetcode | Leetcode_16714_C | from typing import List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def construct_tree(nums: List[int]) -> TreeNode:
""" Construct a binary tree from a list of integers representing level order traversal.
>>> ... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def construct_tree(nums):
if not nums:
return None
from collections import deque
root = TreeNode(nums[0])
queue = deque([root])
i = 1
... | from solution import reflected_level_order
def test_example_1():
nums = [1, 2, 3, -1, 5, -1, -1]
expected = [
[1],
[3, 2],
[5]
]
assert reflected_level_order(nums) == expected
def test_example_2():
nums = [1, 2, 3, 4, 5, 6, 7]
expected = [
[1],
[3, 2],
... | [] | [
0,
0,
0,
0,
1,
1,
1,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from collections import deque\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right ... | trial_gpt4o_6 | {
"original_instruction": "You are given a list of integers `nums` representing a binary tree in level order traversal. Some nodes are empty (null) and are represented by `-1`. You need to construct the binary tree and then return the level order traversal of the tree but with the levels reflected around the center.\... | 0.554704 | Leetcode_16714 | C | [
"construct_tree",
"reflect_levels",
"level_order_traversal",
"reflected_level_order"
] | 4 | [
[
"reflected_level_order",
"construct_tree"
],
[
"reflected_level_order",
"level_order_traversal"
],
[
"reflected_level_order",
"reflect_levels"
]
] | 3 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 1f02354cf4a19224dda47c7af6a54a84e02ab05d | 69e6d6554368d8b686aa82f257e6300c6343a888 | |||
v1.0 | complete | Leetcode | Leetcode_16749_C | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_subtree(root1, root2):
""" Determine if root2 is a subtree of root1.
>>> root1 = TreeNode(3)
>>> root1.left = TreeNode(4)
>>> root1.right = TreeNode(5)... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_subtree(root1, root2):
if not root2:
return True
if not root1:
return False
if is_same_tree(root1, root2):
return True
return i... | from solution import TreeNode, is_subtree
def test_is_subtree_found():
# Tree 1
root1 = TreeNode(3)
root1.left = TreeNode(4)
root1.right = TreeNode(5)
root1.left.left = TreeNode(1)
root1.left.right = TreeNode(2)
# Tree 2
root2 = TreeNode(4)
root2.left = TreeNode(1)
root2.ri... | [] | [
0,
0,
1,
1,
1,
1,
0,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is_equal(tree1, tr... | trial_gpt4o_9 | {
"original_instruction": "You are given two non-empty binary trees `root1` and `root2`. Write a function to determine if `root2` is a **subtree** of `root1`. A subtree of a binary tree `tree` is a tree that consists of a node in `tree` and all of this node's descendants. The tree `root1` could be an empty tree, in w... | 0.569184 | Leetcode_16749 | C | [
"is_subtree",
"is_same_tree"
] | 2 | [
[
"is_subtree",
"is_same_tree"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 2fe0fce950d3030f2771944ba036b88b83db6c90 | a57e2026fb5ab931ba18afa6ce1c08611bd4895b | |||
v1.0 | complete | Leetcode | Leetcode_16777_C | def is_palindrome(s):
"""
Helper function to check if a string is a palindrome.
"""
return s == s[::-1]
def palindrome_pairs(words):
"""
Given a list of unique words, return all pairs of different indices
(i, j) such that the concatenation of the two words words[i] + words[j]
is a palin... | def is_palindrome(s):
"""
Helper function to check if a string is a palindrome.
"""
return s == s[::-1]
def palindrome_pairs(words):
"""
Given a list of unique words, return all pairs of different indices
(i, j) such that the concatenation of the two words words[i] + words[j]
is a palin... | from solution import palindrome_pairs
def test_palindrome_pairs_example():
words = ["abcd", "dcba", "lls", "s", "sssll"]
result = palindrome_pairs(words)
expected = [[0, 1], [1, 0], [3, 2], [2, 4]]
assert sorted(result) == sorted(expected)
def test_palindrome_pairs_no_pairs():
words = ["abc", "def... | [
{
"docstring": "Helper function to check if a string is a palindrome.",
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "Given a list of unique words, return all pairs of different indices\n(i, j) such that the conc... | [
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_palindrome(s):\n \"\"\"\n Helper function to check if a string is a palindrome.\n \"\"\"\n return s == s[::-1]\n\ndef palindrome_pairs(words):\n \"\"\"\... | trial_gpt4o_0 | {
"original_instruction": "Given a list of unique words `words`, return _all the pairs of different indices `(i, j)` such that the concatenation of the two words `words[i] + words[j]` is a palindrome_. A string is a **palindrome** if it reads the same backward as forward.\n\nFor example, given `words = [\"abcd\", \"d... | 0.841592 | Leetcode_16777 | C | [
"is_palindrome",
"palindrome_pairs"
] | 2 | [
[
"palindrome_pairs",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 661c827e26594ca47d15ff94c0bd5d738db698e4 | a83941dabfe0117d1a5fef0b76e6f9648a51c7e9 | |||
v1.0 | complete | Leetcode | Leetcode_16940_C | def longest_concat_word(words: List[str]) -> str:
"""
Returns the longest string in the list that can be formed by concatenating other words from the list exactly once.
In case of a tie, the lexicographically smallest word is returned.
If no such string exists, returns an empty string.
>>> long... | def get_candidates(words):
# This helper function generates all possible concatenations of the given words.
candidates = set()
for i in range(len(words)):
for j in range(len(words)):
if i != j:
candidates.add(words[i] + words[j])
return candidates
def longest_concat_... | from solution import longest_concat_word
def test_example_case():
words = ["cat", "bat", "rat", "catbat"]
assert longest_concat_word(words) == "catbat"
def test_no_concatenated_words():
words = ["cat", "dog", "fish"]
assert longest_concat_word(words) == ""
def test_all_words_single_character():
w... | [
{
"docstring": null,
"function_declaration": "def get_candidates(words):",
"function_name": "get_candidates",
"parameter_list": "(words)"
},
{
"docstring": "Returns the longest string in the list that can be formed by concatenating other words from the list exactly once.\nIn case of a tie, t... | [
0,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def can_form_by_concatenation(word, words_set):\n \"\"\"\n Check if the `word` can be formed by concatenating other words from `words_set`.\n `word` should not be us... | trial_gpt4o_1 | {
"original_instruction": "You are given a list of strings, `words`, where each word consists of lowercase English letters. Find the longest string in the list that can be formed by concatenating other words from the list exactly once each (each word can be used only once). If there is a tie, return the lexicographic... | 0.764469 | Leetcode_16940 | C | [
"get_candidates",
"longest_concat_word"
] | 2 | [
[
"longest_concat_word",
"get_candidates"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 19edb7211b435bea1db7964691c99694e82e6927 | 5ea572f57240ed8a43ce266f26082ecb4eab1d81 | |||
v1.0 | complete | Leetcode | Leetcode_17051_C | def smallest_number(nums):
"""
Given a list of non-negative integers `nums`, represented as strings,
return the smallest number possible when these numbers are concatenated together.
If the result starts with zeroes (e.g., "00032"), the leading zeroes should be removed,
and only "32" should be retur... | from functools import cmp_to_key
def compare(x, y):
"""
Custom comparator function to order strings based on their concatenated result.
If 'xy' < 'yx', then 'x' should come before 'y', otherwise 'y' should come before 'x'.
"""
if x + y < y + x:
return -1
elif x + y > y + x:
retu... | from solution import smallest_number
def test_single_number():
assert smallest_number(["5"]) == "5"
assert smallest_number(["0"]) == "0"
def test_multiple_numbers():
assert smallest_number(["3", "30", "34", "5", "9"]) == "3033459"
assert smallest_number(["10", "2"]) == "102"
assert smallest_number... | [
{
"docstring": "Custom comparator function to order strings based on their concatenated result.\nIf 'xy' < 'yx', then 'x' should come before 'y', otherwise 'y' should come before 'x'.",
"function_declaration": "def compare(x, y):",
"function_name": "compare",
"parameter_list": "(x, y)"
},
{
... | [
0,
1,
0,
0,
1,
0,
0,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from functools import cmp_to_key\n\ndef compare(x, y):\n if x + y < y + x:\n return -1\n elif x + y > y + x:\n return 1\n else:\n return 0\n\nde... | trial_gpt4o_8 | {
"original_instruction": "Given a list of non-negative integers `nums`, represented as strings, return the smallest number possible when these numbers are concatenated together. If the result starts with zeroes (e.g., \"00032\"), the leading zeroes should be removed, and only \"32\" should be returned. If the final ... | 0.720325 | Leetcode_17051 | C | [
"compare",
"smallest_number"
] | 2 | [
[
"smallest_number",
"compare"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2603b0b9b2fcfa9a73d0d0380367cf0d5dae8527 | 38b27eed287c346092c420bf9f171709341cdb36 | |||
v1.0 | complete | Leetcode | Leetcode_17078_C | def is_palindrome(word):
"""
Helper function to check if a word is a palindrome.
>>> is_palindrome("level")
True
>>> is_palindrome("hello")
False
>>> is_palindrome("radar")
True
>>> is_palindrome("world")
False
"""
def palindromePairs(words):
"""
Returns the tota... | def is_palindrome(word):
"""
Helper function to check if a word is a palindrome.
"""
return word == word[::-1]
def palindromePairs(words):
"""
Returns the total number of pairs (i, j) where 0 <= i < j < words.length,
and the concatenation of words[i] + words[j] or words[j] + words[i] forms ... | from solution import palindromePairs, is_palindrome
def test_is_palindrome():
assert is_palindrome("level")
assert not is_palindrome("hello")
assert is_palindrome("radar")
assert not is_palindrome("world")
def test_palindromePairs():
assert palindromePairs(["bat", "tab", "cat"]) == 2 # "battab" a... | [
{
"docstring": "Helper function to check if a word is a palindrome.",
"function_declaration": "def is_palindrome(word):",
"function_name": "is_palindrome",
"parameter_list": "(word)"
},
{
"docstring": "Returns the total number of pairs (i, j) where 0 <= i < j < words.length,\nand the concate... | [
0,
0,
0,
0,
0,
1,
0,
1,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def palindromePairs(words):\n \"\"\"\n Returns the total number of pairs (i, j) where the concatenation of words[i] + words[j]\n or words[j] + words[i] forms a palin... | trial_gpt4o_9 | {
"original_instruction": "You are given an array of strings `words`. Each string is a word, and it consists of lowercase English letters. Return the total number of pairs `(i, j)` where `0 <= i < j < words.length`, and the concatenation of `words[i] + words[j]` or `words[j] + words[i]` forms a palindrome. \n\nFor ex... | 0.847541 | Leetcode_17078 | C | [
"is_palindrome",
"palindromePairs"
] | 2 | [
[
"palindromePairs",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 078938dbc069f89cc7b3d27914470c1d5e7e451f | 1ffb1b1db872201a38fe4bdef140a4c820f2607a | |||
v1.0 | complete | Leetcode | Leetcode_17112_C | from typing import List
def is_valid_identifier(identifier: str) -> bool:
"""
Checks if an incident identifier is valid.
A valid identifier:
- Starts with a lowercase alphabetic character
- Is at least 3 characters long
- Consists only of lowercase alphabetic characters and digits
Args:
... | def is_valid_identifier(identifier):
"""
Checks if an incident identifier is valid.
A valid identifier:
- Starts with a lowercase alphabetic character
- Is at least 3 characters long
- Consists only of lowercase alphabetic characters and digits
Args:
identifier (str): The incid... | from solution import count_valid_identifiers
def test_count_valid_identifiers():
assert count_valid_identifiers(["a123", "ab1", "1abc", "abcd", "ab"]) == 3
def test_count_no_identifiers():
assert count_valid_identifiers([]) == 0
def test_count_all_valid_identifiers():
assert count_valid_identifiers(["abc... | [
{
"docstring": "Checks if an incident identifier is valid.\n\nA valid identifier:\n- Starts with a lowercase alphabetic character\n- Is at least 3 characters long\n- Consists only of lowercase alphabetic characters and digits\n\nArgs:\nidentifier (str): The incident identifier to validate.\n\nReturns:\nbool: Tr... | [
0,
0,
0,
1,
0,
1,
0,
1,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_valid_identifier(identifier):\n \"\"\"\n Determines whether the given identifier is valid based on the criteria\n of starting with a lowercase letter and bein... | trial_gpt4o_8 | {
"original_instruction": "A company's internal case tracking system marks incidents with unique identifiers. Each identifier consists of a combination of lowercase alphabetic characters and digits. The combination always starts with a letter and must be at least 3 characters long. Any incidents that fail to meet the... | 0.602001 | Leetcode_17112 | C | [
"is_valid_identifier",
"count_valid_identifiers"
] | 2 | [
[
"count_valid_identifiers",
"is_valid_identifier"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8ce8ccb0abc1d1c0e176f2c7b81bc6933f7f9b6a | 052d07c6991149a0dd4a0bd1a150b36ad4054d8e | |||
v1.0 | complete | Leetcode | Leetcode_17179_C | def lcs_lengths(target: str, wordlist: List[str]) -> List[int]:
"""
Given a target string and a list of wordlist strings, find the longest common subsequence (LCS) between the target string and each string in the wordlist. The LCS is the longest sequence that appears in both strings in the same order, but not n... | def lcs_length(target, word):
"""
Returns the length of the longest common subsequence (LCS) between target and word.
"""
m, n = len(target), len(word)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if target[i - 1] == word... | from solution import lcs_lengths
def test_lcs_lengths():
assert lcs_lengths("abcde", ["ace", "aec", "bd"]) == [3, 2, 2]
assert lcs_lengths("abcdef", ["abc", "def", "xyz"]) == [3, 3, 0]
assert lcs_lengths("xyz", ["a", "b", "c"]) == [0, 0, 0]
assert lcs_lengths("qwerty", ["wert", "wer", "ty"]) == [4, 3, ... | [
{
"docstring": "Returns the length of the longest common subsequence (LCS) between target and word.",
"function_declaration": "def lcs_length(target, word):",
"function_name": "lcs_length",
"parameter_list": "(target, word)"
},
{
"docstring": "Returns a list where each element is the length ... | [
0,
1,
1,
1,
1,
1,
1,
0,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def lcs_length(s1, s2):\n \"\"\"\n Helper function to calculate the length of the longest common subsequence between two strings.\n \"\"\"\n m, n = len(s1), len(s... | trial_gpt4o_9 | {
"original_instruction": "Given a `target` string and a list of `wordlist` strings, find the longest common subsequence (LCS) between the `target` string and each string in the `wordlist`. The LCS is the longest sequence that appears in both strings in the same order, but not necessarily consecutively. Return an arr... | 0.668782 | Leetcode_17179 | C | [
"lcs_length",
"lcs_lengths"
] | 2 | [
[
"lcs_lengths",
"lcs_length"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 12ce3aeba4c8bfc3bcd46c08e8e47255d842c0ae | 39b52df0bc7394ce9180d7e7c133172321f74198 | |||
v1.0 | complete | Leetcode | Leetcode_17336_C | def min_operations_to_one_component(grid: List[List[int]]) -> int:
""" Return the minimum number of operations required to turn the grid into a grid with exactly one connected component of land.
>>> min_operations_to_one_component([[1, 1, 0], [1, 1, 0], [0, 0, 0]]) == 0
>>> min_operations_to_one_component([... | from collections import deque
# Define direction vectors for 4-directional movement (up, down, left, right)
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
def bfs(x, y, grid, visited):
m, n = len(grid), len(grid[0])
queue = deque([(x, y)])
visited[x][y] = True
while queue:
cx, cy = queue... | from solution import min_operations_to_one_component
def test_already_one_component():
grid = [[1, 1, 0],
[1, 1, 0],
[0, 0, 0]]
assert min_operations_to_one_component(grid) == 0
def test_no_land():
grid = [[0, 0],
[0, 0]]
assert min_operations_to_one_component(gr... | [
{
"docstring": null,
"function_declaration": "def bfs(x, y, grid, visited):",
"function_name": "bfs",
"parameter_list": "(x, y, grid, visited)"
},
{
"docstring": null,
"function_declaration": "def count_components(grid):",
"function_name": "count_components",
"parameter_list": "(... | [
0,
0,
0,
0,
0,
1,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def count_components(grid):\n \"\"\"\n Counts the number of connected components of land (1's) in the grid.\n \"\"\"\n def dfs(i, j):\n if 0 <= i < len(gri... | trial_gpt4o_6 | {
"original_instruction": "You are given a **0-indexed** 2D integer array `grid` of size `m x n` representing a grid of land and water. An entry `grid[i][j]` is `0` if it represents water, and `1` if it represents land. A **connected component** in the grid is a set of `1`s (land) connected by `4-directional` (horiz... | 0.581097 | Leetcode_17336 | C | [
"bfs",
"count_components",
"min_operations_to_one_component"
] | 3 | [
[
"count_components",
"bfs"
],
[
"min_operations_to_one_component",
"count_components"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 2280865f309dbca2e29c3c9bf9a0e6d465394221 | 927b237e9dc1d10233b807ac1a0809caf54a6fd8 | |||
v1.0 | complete | Leetcode | Leetcode_17413_C | def maxDistance(positions, m):
""" Given an array 'positions' of size 'n', where 'positions[i]' is the position of the 'i-th' ball on a number line.
Calculate the maximum possible minimum distance between any two of the 'm' placed balls.
Example:
>>> maxDistance([1, 2, 8, 4, 9], 3)
3
>>> m... | def canPlaceBalls(positions, m, minDist):
"""
Helper function to check if we can place `m` balls with at least `minDist` apart.
"""
count = 1 # place the first ball at the first position
last_position = positions[0]
for i in range(1, len(positions)):
if positions[i] - last_position... | from solution import maxDistance
def test_maxDistance():
assert maxDistance([1, 2, 8, 4, 9], 3) == 3
assert maxDistance([1, 2, 4, 8, 9], 3) == 3
assert maxDistance([1, 2, 3, 4, 5, 6], 3) == 2
assert maxDistance([1, 3, 7, 9], 2) == 8
assert maxDistance([1, 5, 9, 13], 4) == 4
assert maxDistance([... | [
{
"docstring": "Helper function to check if we can place `m` balls with at least `minDist` apart.",
"function_declaration": "def canPlaceBalls(positions, m, minDist):",
"function_name": "canPlaceBalls",
"parameter_list": "(positions, m, minDist)"
},
{
"docstring": "Returns the maximum possib... | [
1,
0,
0,
1,
0,
0,
1,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_feasible(positions, m, distance):\n \"\"\"\n Helper function to check if it's possible to place 'm' balls with at least 'distance' between any two of them.\n ... | trial_gpt4o_8 | {
"original_instruction": "Given an array `positions` of size `n`, where `positions[i]` is the position of the `i-th` ball on a number line, create a function that places `m` balls into different positions from the array such that the minimum distance between any two of the balls is maximized. Return the maximum poss... | 0.653912 | Leetcode_17413 | C | [
"canPlaceBalls",
"maxDistance"
] | 2 | [
[
"maxDistance",
"canPlaceBalls"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | eb7d4e9648c35c13118fcc31fbf025491c00aec4 | 64caac721181803e14052e939d377bdd6bfb3114 | |||
v1.0 | complete | Leetcode | Leetcode_17417_C | from typing import List
def calculate(part: List[int]) -> int:
"""
Calculate the product of non-zero elements in the part.
If the part has no non-zero elements, its product is considered to be 1.
"""
def compare_products(nums: List[int]) -> bool:
"""
Returns true if the product of non-zero... | def calculate(part):
"""
Calculate the product of non-zero elements in the part.
If the part has no non-zero elements, its product is considered to be 1.
"""
product = 1
has_non_zero = False
for num in part:
if num != 0:
product *= num
has_non_zero = True
... | from solution import calculate, compare_products
def test_calculate():
assert calculate([1, 2]) == 2
assert calculate([0, 3, 4]) == 12
assert calculate([0, 0]) == 1
assert calculate([5]) == 5
assert calculate([]) == 1
def test_compare_products():
assert compare_products([1, 2, 0, 3, 4, 0]) == ... | [
{
"docstring": "Calculate the product of non-zero elements in the part.\nIf the part has no non-zero elements, its product is considered to be 1.",
"function_declaration": "def calculate(part):",
"function_name": "calculate",
"parameter_list": "(part)"
},
{
"docstring": "Returns true if the ... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def calculate(part):\n \"\"\"\n Calculate the product of non-zero elements in the part. \n If there are no non-zero elements, return 1.\n \"\"\"\n product = 1\... | trial_gpt4o_7 | {
"original_instruction": "You are given a `0-indexed` integer array `nums` of even length `n`. Split this array into two equal parts: a left part and a right part. The left part is the first `n/2` elements of the array, and the right part is the last `n/2` elements. \n\nA function `calculate(part)` is defined to cal... | 0.63186 | Leetcode_17417 | C | [
"calculate",
"compare_products"
] | 2 | [
[
"compare_products",
"calculate"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 248d9204c3627dc4df387c038e635fc09c5b1324 | e42cb9bba5d9e7e1c8633463c7f6e94cc165ccf5 | |||
v1.0 | complete | Leetcode | Leetcode_17627_C | def is_subsequence(sub, s):
"""
Helper function to determine if 'sub' is a subsequence of 's'.
>>> is_subsequence("abc", "ahbgdc") True
>>> is_subsequence("axc", "ahbgdc") False
>>> is_subsequence("", "ahbgdc") True
>>> is_subsequence("ahbgdc", "ahbgdc") True
"""
pass
def longest_subseq... | def is_subsequence(sub, s):
"""
Helper function to determine if 'sub' is a subsequence of 's'.
"""
it = iter(s)
return all(char in it for char in sub)
def longest_subsequence_length(s, words):
"""
Returns the length of the longest string in words that is a subsequence of s.
"""
max_... | from solution import is_subsequence, longest_subsequence_length
def test_is_subsequence():
assert is_subsequence("abc", "ahbgdc") == True
assert is_subsequence("axc", "ahbgdc") == False
assert is_subsequence("", "ahbgdc") == True
assert is_subsequence("ahbgdc", "ahbgdc") == True
def test_longest_subse... | [
{
"docstring": "Helper function to determine if 'sub' is a subsequence of 's'.",
"function_declaration": "def is_subsequence(sub, s):",
"function_name": "is_subsequence",
"parameter_list": "(sub, s)"
},
{
"docstring": "Returns the length of the longest string in words that is a subsequence o... | [
1,
1,
0,
1,
1,
1,
0,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_subsequence(s, sub):\n \"\"\"\n Helper function to check if 'sub' is a subsequence of 's'.\n \"\"\"\n it = iter(s)\n return all(char in it for char in s... | trial_gpt4o_9 | {
"original_instruction": "You are given a string `s` consisting of lowercase letters, and an array of strings `words` where each string in `words` is a subsequence of `s`. A subsequence is derived from another string by deleting some or none of the characters without changing the order of the remaining characters. R... | 0.765715 | Leetcode_17627 | C | [
"is_subsequence",
"longest_subsequence_length"
] | 2 | [
[
"longest_subsequence_length",
"is_subsequence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 245bd43bc2128fad9f77f46438ac1251914e9e59 | 156aa057e0c65788278ba6e68ad2350322b27725 | |||
v1.0 | complete | Leetcode | Leetcode_17977_C | def find_timestamp_pairs(timestamps: List[str], d: int) -> List[Tuple[int, int]]:
"""
You are given a list of `n` video timestamps in the format `hours:minutes:seconds`, and a target duration `d` in seconds. Write a function to find pairs of timestamps where the absolute difference in their durations is less th... | def timestamp_to_seconds(timestamp):
hours, minutes, seconds = map(int, timestamp.split(':'))
return hours * 3600 + minutes * 60 + seconds
def find_timestamp_pairs(timestamps, d):
"""
Returns a list of tuples where each tuple contains the indices of two timestamps
with durations that differ by les... | from solution import find_timestamp_pairs
def test_find_timestamp_pairs_simple_case():
timestamps = ["00:00:05", "00:00:10", "00:00:15"]
d = 5
assert find_timestamp_pairs(timestamps, d) == [(0, 1), (1, 2)]
def test_find_timestamp_pairs_with_large_difference():
timestamps = ["01:00:00", "02:00:00", "03... | [
{
"docstring": null,
"function_declaration": "def timestamp_to_seconds(timestamp):",
"function_name": "timestamp_to_seconds",
"parameter_list": "(timestamp)"
},
{
"docstring": "Returns a list of tuples where each tuple contains the indices of two timestamps \nwith durations that differ by le... | [
1,
1,
1,
0,
1,
0,
1,
0,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef time_to_seconds(time: str) -> int:\n hours, minutes, seconds = map(int, time.split(':'))\n return hours * 3600 + minutes * 60 + se... | trial_gpt4o_8 | {
"original_instruction": "You are given a list of `n` video timestamps in the format `hours:minutes:seconds`, and a target duration `d` in seconds. Write a function to find pairs of timestamps where the absolute difference in their durations is less than or equal to `d` seconds. Return a list of tuples, where each t... | 0.613145 | Leetcode_17977 | C | [
"timestamp_to_seconds",
"find_timestamp_pairs"
] | 2 | [
[
"find_timestamp_pairs",
"timestamp_to_seconds"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 336aaf5455226aef638a4b70b99fdd3d71efea6c | a9309c2b56c106278ac8d90313d9eafb5e6b6f52 | |||
v1.0 | complete | Leetcode | Leetcode_18282_C | from typing import List
def second_minimum_spanning_tree(n: int, edges: List[List[int]]) -> int:
""" Given an undirected graph with n vertices labeled from 0 to n-1, represented by a 2D array edges where edges[i] = [u, v, w] denotes an edge between nodes u and v with weight w, find the weight of the second minimum... | import heapq
from collections import defaultdict
def find_parent(parents, node):
if parents[node] == node:
return node
parents[node] = find_parent(parents, parents[node])
return parents[node]
def union(parents, ranks, node1, node2):
root1 = find_parent(parents, node1)
root2 = find_parent(p... | from solution import second_minimum_spanning_tree
def test_no_edges():
assert second_minimum_spanning_tree(3, []) == -1
def test_single_edge():
assert second_minimum_spanning_tree(2, [[0, 1, 1]]) == -1
def test_simple_case():
assert second_minimum_spanning_tree(3, [[0, 1, 1], [1, 2, 1], [0, 2, 2]]) == 3
... | [
{
"docstring": null,
"function_declaration": "def find_parent(parents, node):",
"function_name": "find_parent",
"parameter_list": "(parents, node)"
},
{
"docstring": null,
"function_declaration": "def union(parents, ranks, node1, node2):",
"function_name": "union",
"parameter_lis... | [
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import heapq\nfrom collections import defaultdict\n\ndef find_parent(parents, node):\n if parents[node] == node:\n return node\n parents[node] = find_parent(pare... | trial_gpt4o_0 | {
"original_instruction": "Given an undirected graph with `n` vertices labeled from `0` to `n-1`, represented by a 2D array `edges` where `edges[i] = [u, v, w]` denotes an edge between nodes `u` and `v` with weight `w`, find the weight of the second minimum spanning tree (SMST). A second minimum spanning tree (SMST) ... | 0.715561 | Leetcode_18282 | C | [
"find_parent",
"union",
"kruskal",
"second_minimum_spanning_tree"
] | 4 | [
[
"kruskal",
"find_parent"
],
[
"kruskal",
"union"
],
[
"second_minimum_spanning_tree",
"kruskal"
],
[
"union",
"find_parent"
]
] | 4 | [] | false | [] | false | pytest | true | [] | true | fb139cc98c3659e9194088db6e0f0b54a1198618 | b3aacbc757dd9ef10b3c735c11f0711f79cad6b5 | |||
v1.0 | complete | Leetcode | Leetcode_18307_C | def findPalindromePairs(words: List[str]) -> List[Tuple[int, int]]:
""" Given a list of unique words, find all pairs of distinct indices (i, j) such that the concatenation of the two words words[i] + words[j] is a palindrome.
>>> findPalindromePairs(["abc", "def", "ghi"])
[]
>>> findPalindromePairs(["ba... | def is_palindrome(word):
"""
Helper function to check if a word is a palindrome.
"""
return word == word[::-1]
def findPalindromePairs(words):
"""
Returns a list of all pairs of distinct indices (i, j) such that
the concatenation of words[i] + words[j] is a palindrome.
"""
palindrom... | from solution import findPalindromePairs
def test_findPalindromePairs_no_pairs():
words = ["abc", "def", "ghi"]
assert findPalindromePairs(words) == []
def test_findPalindromePairs_single_pair():
words = ["bat", "tab", "cat"]
assert findPalindromePairs(words) == [(0, 1), (1, 0)]
def test_findPalindro... | [
{
"docstring": "Helper function to check if a word is a palindrome.",
"function_declaration": "def is_palindrome(word):",
"function_name": "is_palindrome",
"parameter_list": "(word)"
},
{
"docstring": "Returns a list of all pairs of distinct indices (i, j) such that\nthe concatenation of wor... | [
0,
0,
1,
0,
0,
1,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def findPalindromePairs(words):\n \"\"\"\n Finds all pairs of distinct indices (i, j) in the given list such that the\n concatenation of words[i] + words[j] is a pal... | trial_gpt4o_5 | {
"original_instruction": "Given a list of unique words, find all pairs of distinct indices `(i, j)` in the given list such that the concatenation of the two words `words[i] + words[j]` is a palindrome. Implement the function `findPalindromePairs` that returns a list of all such pairs `[(i, j)]`. Each pair should be ... | 0.728218 | Leetcode_18307 | C | [
"is_palindrome",
"findPalindromePairs"
] | 2 | [
[
"findPalindromePairs",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 99ecfabb2bf11d8fc18fcbc54fed3ab8850ad9fc | 779399401506f949c876316a48b2ff2683d1f5d1 | |||
v1.0 | complete | Leetcode | Leetcode_18533_C | def is_k_odd_symmetric(s: str, k: int) -> bool:
"""
Check if the string `s` is k-odd symmetric.
"""
pass
def find_k_odd_symmetric_indices(words: List[str], k: int) -> List[int]:
"""
Identify and return indices of k-odd symmetric strings in the given `words` array.
>>> find_k_odd_symmet... | def is_k_odd_symmetric(s, k):
"""
Check if the string `s` is k-odd symmetric.
"""
k_odd_str = s[::k]
return k_odd_str == k_odd_str[::-1]
def find_k_odd_symmetric_indices(words, k):
"""
Identify and return indices of k-odd symmetric strings in the given `words` array.
"""
result = []... | from solution import find_k_odd_symmetric_indices
def test_find_k_odd_symmetric_indices_general_cases():
words = ["racecar", "abcdefg", "aabbcc", "kayak"]
k = 2
assert find_k_odd_symmetric_indices(words, k) == [0, 3]
words = ["abc", "xyz", "aba", "12321", "aaxaa"]
k = 1
assert find_k_odd_s... | [
{
"docstring": "Check if the string `s` is k-odd symmetric.",
"function_declaration": "def is_k_odd_symmetric(s, k):",
"function_name": "is_k_odd_symmetric",
"parameter_list": "(s, k)"
},
{
"docstring": "Identify and return indices of k-odd symmetric strings in the given `words` array.",
... | [
0,
0,
0,
0,
1,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_k_odd_symmetric(s, k):\n \"\"\"\n Check if the string s is k-odd symmetric.\n \"\"\"\n filtered_string = s[::k]\n return filtered_string == filtered_str... | trial_gpt4o_6 | {
"original_instruction": "You are given an array of strings `words` and an integer `k`. A string `s` is called k-odd symmetric if it reads the same backward when observed every k-th character starting from the first character. For example, given the string \"abcdefg\" and k=2, the k-odd symmetric view would be \"ace... | 0.635888 | Leetcode_18533 | C | [
"is_k_odd_symmetric",
"find_k_odd_symmetric_indices"
] | 2 | [
[
"find_k_odd_symmetric_indices",
"is_k_odd_symmetric"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 29ed77711c2275baa87984edd3aaa98c1514a4f8 | 13d4f2889adaed37ce1be563b709a3ebe4adac51 | |||
v1.0 | complete | Leetcode | Leetcode_18708_C | def can_be_made_alternating(s: str) -> bool:
"""
Determines if the given string s can be made alternating with exactly one replacement.
"""
def is_alternating(s: str) -> bool:
"""
Checks if the given string s is alternating (no two adjacent characters are the same).
"""
from solution impor... | def can_be_made_alternating(s):
"""
Determines if the given string s can be made alternating with exactly one replacement.
"""
if len(s) < 2:
return True # A string of length 1 is already alternating
# Check all possible single replacements by modifying each character
for i in range(le... | from solution import can_be_made_alternating
def test_can_be_made_alternating():
# Test cases with example strings that can be solved with one replacement
assert can_be_made_alternating("AAB") == True
assert can_be_made_alternating("BCC") == True
assert can_be_made_alternating("CACA") == True
asser... | [
{
"docstring": "Determines if the given string s can be made alternating with exactly one replacement.",
"function_declaration": "def can_be_made_alternating(s):",
"function_name": "can_be_made_alternating",
"parameter_list": "(s)"
},
{
"docstring": "Checks if the given string s is alternati... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def can_make_alternating(s):\n \"\"\"\n Determines if the string can be made alternating by replacing exactly one character.\n \"\"\"\n if len(s) <= 1:\n r... | trial_gpt4o_5 | {
"original_instruction": "You are given a string `s` consisting only of characters 'A', 'B', and 'C'. You are allowed to replace exactly one character in the string with any other character ('A', 'B', or 'C'). Your task is to determine if it's possible to make the string alternating, where no two adjacent characters... | 0.599042 | Leetcode_18708 | C | [
"can_be_made_alternating",
"is_alternating"
] | 2 | [
[
"can_be_made_alternating",
"is_alternating"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b7bbf52525a6bd3cdf9898c75294c511d383c8dd | ecb382335f918d89c7bae344f092a178adee26d7 | |||
v1.0 | complete | Leetcode | Leetcode_18829_C | from typing import List
def is_valid_email(email: str) -> bool:
"""
Helper function to check if an email address is valid based on the defined rules.
"""
def filter_valid_emails(email_list: List[str]) -> List[str]:
"""
Returns a list containing all the valid email addresses from the input list.
... | import re
def is_valid_email(email):
"""
Helper function to check if an email address is valid based on the defined rules.
"""
# Regular expression pattern for validating an email
pattern = re.compile(r"^(?!.*[.]{2})(?!.*[@]{2})[A-Za-z0-9]+([._A-Za-z0-9-])*[A-Za-z0-9]+@[A-Za-z0-9]+([._A-Za-z0-9-])*... | from solution import filter_valid_emails
def test_filter_valid_emails():
assert filter_valid_emails(["valid.email@example.com",
"invalid.email..address@example.com",
".invalid.email@example.com",
"invalid.email.@examp... | [
{
"docstring": "Helper function to check if an email address is valid based on the defined rules.",
"function_declaration": "def is_valid_email(email):",
"function_name": "is_valid_email",
"parameter_list": "(email)"
},
{
"docstring": "Returns a list containing all the valid email addresses ... | [
1,
1,
0,
1,
0,
0,
1,
0,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import re\n\ndef is_valid_email(email):\n \"\"\"\n Checks if the provided email is valid based on the given rules.\n \"\"\"\n email_pattern = re.compile(\n ... | trial_gpt4o_1 | {
"original_instruction": "Given a list of strings `email_list` where each string is an email address, write a function to **filter** out all the valid email addresses. A valid email address follows these rules:\n\n- It has exactly one '@' symbol.\n- The local part (the part before the '@') does not start or end with... | 0.609276 | Leetcode_18829 | C | [
"is_valid_email",
"filter_valid_emails"
] | 2 | [
[
"filter_valid_emails",
"is_valid_email"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7f5abbd678cfda6daacfe972b1393f3ab9aaa76f | 15257045625d606e4b240fd4f9fd8b096214330b | |||
v1.0 | complete | Leetcode | Leetcode_19175_C | from typing import List
def shortest_even_sum_path(matrix: List[List[int]]) -> int:
"""
Given a matrix of size m x n filled with non-negative integers, return the length of the shortest path
from the top-left cell to the bottom-right cell, such that you can move only in the four cardinal
directions ... | from collections import deque
def is_valid(i, j, m, n):
"""
Check if the coordinates (i, j) are within the matrix bounds.
"""
return 0 <= i < m and 0 <= j < n
def shortest_even_sum_path(matrix):
"""
Returns the length of the shortest path from the top-left to the bottom-right
cell of t... | from solution import shortest_even_sum_path
def test_example_case():
matrix = [
[1, 3, 1],
[2, 8, 4],
[1, 2, 4]
]
assert shortest_even_sum_path(matrix) == 4 # 1 -> 2 -> 8 -> 4 = 15 (Odd)
def test_single_cell_even():
matrix = [
[2]
]
assert shortest_even_sum_pat... | [
{
"docstring": "Check if the coordinates (i, j) are within the matrix bounds.",
"function_declaration": "def is_valid(i, j, m, n):",
"function_name": "is_valid",
"parameter_list": "(i, j, m, n)"
},
{
"docstring": "Returns the length of the shortest path from the top-left to the bottom-right\... | [
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef is_valid_move(x, y, m, n):\n return 0 <= x < m and 0 <= y < n\n\ndef shortest_even_sum_path(matrix):\n \"\"\"\n Returns the leng... | trial_gpt4o_7 | {
"original_instruction": "Given a matrix of size `m x n` filled with non-negative integers, return the length of the **shortest path** from the top-left cell to the bottom-right cell, such that you can move only in the four cardinal directions (up, down, left, right), and the sum of all numbers along the path must b... | 0.667537 | Leetcode_19175 | C | [
"is_valid",
"shortest_even_sum_path"
] | 2 | [
[
"shortest_even_sum_path",
"is_valid"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 67b1bf020f6bccf995262c85a156675c6d8d443e | 4f33fb30a8649b083ff69b7e0d65d68f51a25a6a | |||
v1.0 | complete | Leetcode | Leetcode_19370_C | from itertools import permutations
def calculate_manhattan_distance(p1, p2):
"""
Returns the Manhattan distance between points p1 and p2.
"""
return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
def assign_bikes(workers, bikes):
"""
Assigns each worker to a bike such that the sum of the Manhattan di... | from itertools import permutations
def calculate_manhattan_distance(p1, p2):
"""
Returns the Manhattan distance between points p1 and p2.
"""
return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
def assign_bikes(workers, bikes):
"""
Assigns each worker to a bike such that the sum of the Manhattan di... | from solution import assign_bikes, calculate_manhattan_distance
def test_single_worker_bike():
workers = [(0, 0)]
bikes = [(1, 1)]
assert assign_bikes(workers, bikes) == 2
def test_two_workers_bikes():
workers = [(0, 0), (2, 2)]
bikes = [(1, 1), (3, 3)]
assert assign_bikes(workers, bikes) == 4... | [
{
"docstring": "Returns the Manhattan distance between points p1 and p2.",
"function_declaration": "def calculate_manhattan_distance(p1, p2):",
"function_name": "calculate_manhattan_distance",
"parameter_list": "(p1, p2)"
},
{
"docstring": "Assigns each worker to a bike such that the sum of ... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from itertools import permutations\n\ndef min_total_distance(workers, bikes):\n \"\"\"\n Assign workers to bikes to minimize the total Manhattan distance.\n \n Ar... | trial_gpt4o_6 | {
"original_instruction": "You are given two arrays `workers` and `bikes` of equal length, where `workers[i]` represents the `i-th` worker's location and `bikes[j]` represents the `j-th` bike's location on a grid. Your task is to assign each worker to a bike such that the sum of the Manhattan distances between each w... | 0.56639 | Leetcode_19370 | C | [
"calculate_manhattan_distance",
"assign_bikes"
] | 2 | [
[
"assign_bikes",
"calculate_manhattan_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c51a820191f07961e131ec481f34a92735832686 | d2e67768c2cc31685802ce3438192957cef2e461 | |||
v1.0 | complete | Leetcode | Leetcode_19884_C | from typing import List
def is_self_dividing(number: int) -> bool:
"""
Helper function that checks if a number is self-dividing.
"""
original_number = number
while number > 0:
digit = number % 10
if digit == 0 or original_number % digit != 0:
return False
number ... | from typing import List
def is_self_dividing(number: int) -> bool:
"""
Helper function that checks if a number is self-dividing.
"""
original_number = number
while number > 0:
digit = number % 10
if digit == 0 or original_number % digit != 0:
return False
number ... | from solution import self_dividing_numbers
def test_self_dividing_numbers_basic():
assert self_dividing_numbers(1, 22) == [
1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]
def test_self_dividing_numbers_single_digit():
assert self_dividing_numbers(1, 9) == [1, 2, 3, 4, 5, 6, 7, 8, 9]
def test_self_div... | [
{
"docstring": "Helper function that checks if a number is self-dividing.",
"function_declaration": "def is_self_dividing(number):",
"function_name": "is_self_dividing",
"parameter_list": "(number)"
},
{
"docstring": "Returns a list of all self-dividing numbers between start and end (inclusi... | [
1,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef is_self_dividing(number: int) -> bool:\n \"\"\"\n Helper function to check if a number is self-dividing.\n \"\"\"\n original_number... | trial_gpt4o_1 | {
"original_instruction": "[Question]: Given two integers `start` and `end`, return a list of all the integers within that range (inclusive) that are self-dividing. An integer is considered self-dividing if it is divisible by every digit it contains and does not contain the digit `0`. For instance, `128` is a self-di... | 0.646906 | Leetcode_19884 | C | [
"is_self_dividing",
"self_dividing_numbers"
] | 2 | [
[
"self_dividing_numbers",
"is_self_dividing"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 367daffe9f320160f87f28574ca61fa52533f954 | 2f27830cfb11189ac43b8dd7169401a90f1c38bc | |||
v1.0 | complete | Leetcode | Leetcode_19913_C | def build_max_heap(nums: List[int]) -> List[int]:
"""
Converts the input list `nums` into a max-heap.
>>> build_max_heap([9, 5, 6, 2, 3])
[9, 5, 6, 2, 3]
>>> build_max_heap([3, 9, 2, 1, 4, 5])
[9, 4, 5, 1, 3, 2]
>>> build_max_heap([])
[]
>>> build_max_heap([1])
[1]
>>> bu... | def max_heapify(nums, n, i):
"""
Ensures that the subtree rooted at index `i` in the `nums` list is a max-heap.
"""
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and nums[left] > nums[largest]:
largest = left
if right < n and nums[right] > nums[largest]:
la... | from solution import build_max_heap
def test_already_max_heap():
assert build_max_heap([9, 5, 6, 2, 3]) == [9, 5, 6, 2, 3]
def test_simple_case():
assert build_max_heap([3, 9, 2, 1, 4, 5]) == [9, 4, 5, 1, 3, 2]
def test_empty_list():
assert build_max_heap([]) == []
def test_single_element():
assert ... | [
{
"docstring": "Ensures that the subtree rooted at index `i` in the `nums` list is a max-heap.",
"function_declaration": "def max_heapify(nums, n, i):",
"function_name": "max_heapify",
"parameter_list": "(nums, n, i)"
},
{
"docstring": "Converts the input list `nums` into a max-heap.",
"... | [
1,
0,
0,
1,
1,
1,
1,
0,
0
] | 5 | medium | 0.556 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def max_heapify(nums, n, i):\n \"\"\"\n Helper function to maintain the max-heap property.\n \"\"\"\n largest = i # Initialize largest as root\n left = 2 * i ... | trial_gpt4o_6 | {
"original_instruction": "You are given a list of integers `nums` representing a heap (not necessarily balanced) and you need to implement a function to convert it into a **max-heap**. A max-heap is a complete binary tree where the value of each node is greater than or equal to the values of its children. Return the... | 0.719467 | Leetcode_19913 | C | [
"max_heapify",
"build_max_heap"
] | 2 | [
[
"build_max_heap",
"max_heapify"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ae244a3fe3653de510a023e98cf3301a7bc7d3cb | 5d8c94ba7c089e97414310af1b039027904471f0 | |||
v1.0 | complete | Leetcode | Leetcode_20010_C | def find(parent, i):
if parent[i] == i:
return i
return find(parent, parent[i])
def union(parent, rank, x, y):
root_x = find(parent, x)
root_y = find(parent, y)
if rank[root_x] < rank[root_y]:
parent[root_x] = root_y
elif rank[root_x] > rank[root_y]:
parent[root_y] = roo... | def find(parent, i):
if parent[i] == i:
return i
return find(parent, parent[i])
def union(parent, rank, x, y):
root_x = find(parent, x)
root_y = find(parent, y)
if rank[root_x] < rank[root_y]:
parent[root_x] = root_y
elif rank[root_x] > rank[root_y]:
parent[root_y] = roo... | from solution import minimum_cost
def test_example_case():
assert minimum_cost(4, [[0, 1, 1], [1, 2, 2], [2, 3, 3], [3, 0, 4], [1, 3, 5]]) == 6
def test_three_regions_two_edges():
assert minimum_cost(3, [[0, 1, 1], [1, 2, 2]]) == 3
def test_disconnected_regions():
assert minimum_cost(4, [[0, 1, 1], [2, 3... | [
{
"docstring": null,
"function_declaration": "def find(parent, i):",
"function_name": "find",
"parameter_list": "(parent, i)"
},
{
"docstring": null,
"function_declaration": "def union(parent, rank, x, y):",
"function_name": "union",
"parameter_list": "(parent, rank, x, y)"
},
... | [
0,
1,
1,
0,
0,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def minimumCost(n, edges):\n \"\"\"\n Finds the minimum cost required to ensure all regions are covered with at least a redundant server placement\n :param n: number... | trial_gpt4o_2 | {
"original_instruction": "A company is planning to structure their IT infrastructure by setting up servers across multiple regions. They have a list of potential regions where a server can be placed, and each server setup has an associated cost. However, the network setup needs to be optimized such that the total co... | 0.606836 | Leetcode_20010 | C | [
"find",
"union",
"minimum_cost"
] | 3 | [
[
"minimum_cost",
"find"
],
[
"minimum_cost",
"union"
],
[
"union",
"find"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 29a379c7a8ff3d0d599acc6496814e88ad50ac6e | 0c526abac64131484840a513798ba02adb579460 | |||
v1.0 | complete | Leetcode | Leetcode_20022_C | from typing import List
def next_permutation(nums: List[int]) -> None:
"""
Modifies nums in-place to its next lexicographical permutation.
If nums is the last permutation, sorts it to the first permutation.
"""
# Implement the function here
def kth_permutation(nums: List[int], k: int) -> List[int]... | def next_permutation(nums):
"""
Modifies nums in-place to its next lexicographical permutation.
If nums is the last permutation, sorts it to the first permutation.
"""
n = len(nums)
if n <= 1:
return
# Find the rightmost ascent in the array
i = n - 2
while i >= 0 and nums[i]... | from solution import next_permutation, kth_permutation
def test_one_step_permutation():
nums = [1, 2, 3]
next_permutation(nums)
assert nums == [1, 3, 2]
def test_reverse_permutation():
nums = [3, 2, 1]
next_permutation(nums)
assert nums == [1, 2, 3]
def test_complex_permutation():
nums = ... | [
{
"docstring": "Modifies nums in-place to its next lexicographical permutation.\nIf nums is the last permutation, sorts it to the first permutation.",
"function_declaration": "def next_permutation(nums):",
"function_name": "next_permutation",
"parameter_list": "(nums)"
},
{
"docstring": "Mod... | [
0,
0,
1,
1,
0,
1,
0,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def next_permutation(nums):\n \"\"\"\n Modifies nums in-place to the next lexicographical permutation.\n If it isn't possible, rearranges to the lowest possible orde... | trial_gpt4o_8 | {
"original_instruction": "Given an array of integers `nums` and an integer `k`, modify the array in-place such that it becomes its next lexicographical permutation. The replacement must be in-place and use only constant extra memory. If such arrangement is not possible, rearrange `nums` into its lowest possible orde... | 0.706128 | Leetcode_20022 | C | [
"next_permutation",
"kth_permutation"
] | 2 | [
[
"kth_permutation",
"next_permutation"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d752314ec53a1736b8133282bd1f043a9b6eee79 | 495da7eb1d64ee7bd25477316ed225eb9bb56135 | |||
v1.0 | complete | Leetcode | Leetcode_20249_C | from typing import List
def primes_between(x: int, y: int) -> List[int]:
"""Given two integers `x` and `y`, where `x <= y`, return an array of all the prime numbers between `x` and `y` (inclusive).
>>> primes_between(2, 11)
[2, 3, 5, 7, 11]
>>> primes_between(5, 5)
[5]
>>> primes_between(4, 4)... | def is_prime(n):
"""
Helper function to check if a number is prime.
"""
if n <= 1:
return False
elif n <= 3:
return True
elif n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
... | from solution import primes_between
def test_primes_within_small_range():
assert primes_between(2, 11) == [2, 3, 5, 7, 11]
def test_primes_within_single_number_prime():
assert primes_between(5, 5) == [5]
def test_primes_within_single_number_not_prime():
assert primes_between(4, 4) == []
def test_primes_... | [
{
"docstring": "Helper function to check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns an array of all prime numbers between x and y (inclusive).",
"function_declaration": "def primes_be... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_prime(n):\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n p = 3\n while p * p <= n:\n ... | trial_gpt4o_9 | {
"original_instruction": "Given two integers `x` and `y`, where `x <= y`, return an array of all the prime numbers between `x` and `y` (inclusive). A number is a prime number if it is greater than 1 and cannot be formed by multiplying two smaller natural numbers.",
"prompt_id": "0000020249",
"row_id": 20249,
"... | 0.667961 | Leetcode_20249 | C | [
"is_prime",
"primes_between"
] | 2 | [
[
"primes_between",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3e41d90a488515a696e87f92a279a1b25d9b040a | 72a6dece95e54995f8fd48aefbc495eb6360f8fc | |||
v1.0 | complete | Leetcode | Leetcode_20442_C | def minimum_travel_cost(n: int, m: int, roads: List[List[int]]) -> int:
""" Calculate the minimum total travel cost to ensure every city can be reached from any other city.
If it is not possible to connect all cities, return -1.
>>> minimum_travel_cost(4, 5, [[0, 1, 10], [0, 2, 6], [0, 3, 5], [1, 3, 15... | def find(parent, i):
if parent[i] == i:
return i
else:
return find(parent, parent[i])
def union(parent, rank, xroot, yroot):
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
else:
parent[yroot] = xroot
... | from solution import minimum_travel_cost
def test_minimum_travel_cost_simple():
n = 4
m = 5
roads = [
[0, 1, 10],
[0, 2, 6],
[0, 3, 5],
[1, 3, 15],
[2, 3, 4]
]
assert minimum_travel_cost(n, m, roads) == 19
def test_minimum_travel_cost_not_connected():
n ... | [
{
"docstring": null,
"function_declaration": "def find(parent, i):",
"function_name": "find",
"parameter_list": "(parent, i)"
},
{
"docstring": null,
"function_declaration": "def union(parent, rank, xroot, yroot):",
"function_name": "union",
"parameter_list": "(parent, rank, xroo... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def find(parent, i):\n if parent[i] == i:\n return i\n else:\n return find(parent, parent[i])\n\ndef union(parent, rank, x, y):\n root_x = find(parent,... | trial_gpt4o_3 | {
"original_instruction": "You are given `n` cities connected by `m` roads. Each road connects two different cities and has an associated travel cost. Your task is to ensure that every city can be reached from any other city and to minimize the total travel cost. Write a function that, given `n`, `m`, and an array `... | 0.790955 | Leetcode_20442 | C | [
"find",
"union",
"minimum_travel_cost"
] | 3 | [
[
"minimum_travel_cost",
"find"
],
[
"minimum_travel_cost",
"union"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 06595f5ea7aa453acbbf7f0cad4cc80192a5be1d | f991076ed5a2b6378fcdcbb151cf9513606ea01c | |||
v1.0 | complete | Leetcode | Leetcode_20455_C | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def pseudo_palindromic_paths(root: TreeNode) -> int:
""" Return the number of pseudo-palindromic paths in the binary tree.
A pseudo-palindromic path is a path from r... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_pseudo_palindromic(counts):
odd_count = sum(1 for count in counts.values() if count % 2 != 0)
return odd_count <= 1
def pseudo_palindromic_paths(root):
f... | from solution import TreeNode, pseudo_palindromic_paths
def test_single_node_tree():
root = TreeNode(1)
assert pseudo_palindromic_paths(root) == 1
def test_all_nodes_same_value():
root = TreeNode(2, TreeNode(2), TreeNode(2))
assert pseudo_palindromic_paths(root) == 2
def test_simple_tree():
root ... | [] | [
0,
0,
0,
0,
1,
0,
1,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\ndef pseudoPalindromi... | trial_gpt4o_6 | {
"original_instruction": "You are given a binary tree root structure. A **pseudo-palindromic path** in a binary tree is a path that starts at the root node and ends at any leaf node where it is possible to rearrange the node values to form a palindrome. Return _the number of pseudo-palindromic paths_ in the tree. Ea... | 0.621807 | Leetcode_20455 | C | [
"is_pseudo_palindromic",
"pseudo_palindromic_paths"
] | 2 | [
[
"pseudo_palindromic_paths",
"is_pseudo_palindromic"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 860149d9c63fa05d956027dfff710ea53b995236 | 5257ecd60cbb1e4adc0635df88e6952d50213b46 | |||
v1.0 | complete | Leetcode | Leetcode_20950_C | def sum_odd_length_palindromic_substrings(s: str) -> int:
""" Given a string `s` containing only digits, return the sum of all possible odd length palindromic sub-strings in `s`.
A sub-string is a contiguous sequence of characters within a string and a palindromic sub-string reads the same forwards and backward... | def is_palindrome(s):
"""
Check if the given string is palindrome.
"""
return s == s[::-1]
def sum_odd_length_palindromic_substrings(s):
"""
Given a string `s` containing only digits, return the sum of all possible odd length
palindromic substrings in `s`.
"""
total_sum = 0
n = ... | from solution import sum_odd_length_palindromic_substrings
def test_single_digit():
assert sum_odd_length_palindromic_substrings("5") == 5
assert sum_odd_length_palindromic_substrings("0") == 0
def test_two_same_digits():
assert sum_odd_length_palindromic_substrings("22") == 2 + 2 # both individual digit... | [
{
"docstring": "Check if the given string is palindrome.",
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "Given a string `s` containing only digits, return the sum of all possible odd length\npalindromic substring... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_palindrome(s):\n return s == s[::-1]\n\ndef sum_of_odd_length_palindromes(s):\n n = len(s)\n total_sum = 0\n\n for i in range(n):\n for length in ra... | trial_gpt4o_4 | {
"original_instruction": "Given a string `s` containing only digits, return the sum of all possible odd length palindromic sub-strings in `s`. A **sub-string** is a contiguous sequence of characters within a string and a **palindromic sub-string** reads the same forwards and backwards.",
"prompt_id": "0000020950",... | 0.731539 | Leetcode_20950 | C | [
"is_palindrome",
"sum_odd_length_palindromic_substrings"
] | 2 | [
[
"sum_odd_length_palindromic_substrings",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 702326f8608d7c1109c7e2f630113f9a74f0a293 | 8a2f4382be232ad0ad925abd73c86e06e9f069bb | |||
v1.0 | complete | Leetcode | Leetcode_20983_C | from typing import List
def minimizeMaxBucketSum(arr: List[int], k: int) -> int:
""" Distribute all elements in arr into k buckets such that the total sum of elements in
the bucket with the maximum sum is minimized.
Arguments:
arr -- list of integers
k -- number of buckets
Returns:
The m... | def canDistribute(arr, k, max_sum):
current_sum = 0
bucket_count = 1
for num in arr:
if current_sum + num <= max_sum:
current_sum += num
else:
bucket_count += 1
current_sum = num
if bucket_count > k:
return False
return... | from solution import minimizeMaxBucketSum
def test_single_element():
assert minimizeMaxBucketSum([10], 1) == 10
def test_two_elements_two_buckets():
assert minimizeMaxBucketSum([10, 20], 2) == 20
def test_two_elements_one_bucket():
assert minimizeMaxBucketSum([10, 20], 1) == 30
def test_multiple_element... | [
{
"docstring": null,
"function_declaration": "def canDistribute(arr, k, max_sum):",
"function_name": "canDistribute",
"parameter_list": "(arr, k, max_sum)"
},
{
"docstring": null,
"function_declaration": "def minimizeMaxBucketSum(arr, k):",
"function_name": "minimizeMaxBucketSum",
... | [
0,
0,
0,
1,
1,
1,
0,
1,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def canDistribute(arr, k, maxSum):\n current_sum = 0\n count = 1\n for num in arr:\n if current_sum + num <= maxSum:\n current_sum += num\n ... | trial_gpt4o_7 | {
"original_instruction": "Given an array of integers `arr` and an integer `k`, your task is to distribute all elements in `arr` into `k` buckets such that the total sum of elements in the bucket with the maximum sum is minimized. Return the minimized maximum bucket sum. Note that each element in `arr` must be assign... | 0.64311 | Leetcode_20983 | C | [
"canDistribute",
"minimizeMaxBucketSum"
] | 2 | [
[
"minimizeMaxBucketSum",
"canDistribute"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c058a0412884654a39f71878ce0959f44a44dd3e | c0771171a84f058d4fd67a2a3b63c3de2d49309e | |||
v1.0 | complete | Leetcode | Leetcode_21067_C | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def tree_is_balanced(n, edges):
"""
Determine if the tree is balanced. A tree is considered balanced if the height of the
two subtrees of every node never differ by more than 1. Return True ... | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def create_tree_from_edges(n, edges):
from collections import defaultdict, deque
if not edges:
return TreeNode(1) if n == 1 else None
children = defaultdict(list)
for u, ... | from solution import tree_is_balanced
def test_null_tree():
assert tree_is_balanced(0, []) == True
def test_single_node_tree():
assert tree_is_balanced(1, []) == True
def test_balanced_tree():
assert tree_is_balanced(3, [(1, 2), (1, 3)]) == True
def test_unbalanced_tree():
assert tree_is_balanced(3,... | [] | [
1,
0,
0,
0,
1,
1,
1,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n \ndef build_tree... | trial_gpt4o_8 | {
"original_instruction": "You are given a binary tree with `n` nodes, where each node is labeled from `1` to `n`. The tree is rooted at node `1`, and you are provided with an edge list representation of the tree. Each edge is represented as a tuple `(u, v)` indicating that node `u` is connected to node `v`. Write a ... | 0.737246 | Leetcode_21067 | C | [
"create_tree_from_edges",
"is_balanced",
"tree_is_balanced"
] | 3 | [
[
"tree_is_balanced",
"create_tree_from_edges"
],
[
"tree_is_balanced",
"is_balanced"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 25a96646dd278490c4877caff4ed08fd92cf7c63 | bbbde5099e81bdeb0e7a2377234ba892a1db1f2c | |||
v1.0 | complete | Leetcode | Leetcode_21470_C | def find_happy_numbers(n: int) -> List[int]:
""" Returns an array of all happy numbers in the inclusive range [1, n].
>>> find_happy_numbers(10) [1, 7, 10]
>>> find_happy_numbers(20) [1, 7, 10, 13, 19]
>>> find_happy_numbers(50) [1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49]
>>> find_happy_numbers(1) [1... | def is_happy(n):
"""
Determines if a number n is a happy number.
"""
def get_next(number):
total_sum = 0
while number > 0:
number, digit = divmod(number, 10)
total_sum += digit ** 2
return total_sum
seen = set()
while n != 1 and n not in seen:... | from solution import find_happy_numbers
def test_find_happy_numbers_up_to_10():
assert find_happy_numbers(10) == [1, 7, 10]
def test_find_happy_numbers_up_to_20():
assert find_happy_numbers(20) == [1, 7, 10, 13, 19]
def test_find_happy_numbers_up_to_50():
assert find_happy_numbers(50) == [1, 7, 10, 13, 1... | [
{
"docstring": "Determines if a number n is a happy number.",
"function_declaration": "def is_happy(n):",
"function_name": "is_happy",
"parameter_list": "(n)"
},
{
"docstring": "Returns a list of all happy numbers in the inclusive range [1, n].",
"function_declaration": "def find_happy_n... | [
1,
1,
0,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_happy(n):\n \"\"\"\n Helper function that checks if a number is a happy number.\n \"\"\"\n seen = set()\n while n != 1 and n not in seen:\n seen.... | trial_gpt4o_9 | {
"original_instruction": "A **happy number** is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1, or it loops endlessly in a cycle that does not include 1. Those numbers for whic... | 0.588591 | Leetcode_21470 | C | [
"is_happy",
"find_happy_numbers"
] | 2 | [
[
"find_happy_numbers",
"is_happy"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bae06fd4ba25793f74abbb19368216deea0b8cd5 | 66b3839c24d5b22316d908d165c3906d8595fef9 | |||
v1.0 | complete | Leetcode | Leetcode_21558_C | from typing import List
from math import gcd
def lcm(a: int, b: int) -> int:
"""
Computes the least common multiple of a and b.
"""
pass
def smallestMultiple(n: int) -> int:
"""
Suppose you are given a positive integer `n`. Your task is to determine the
smallest positive integer that is e... | from math import gcd
def lcm(a, b):
"""
Computes the least common multiple of a and b.
"""
return a * b // gcd(a, b)
def smallestMultiple(n):
"""
Returns the smallest positive integer that is evenly divisible by all integers from 1 to n.
"""
multiple = 1
for i in range(2, n + 1):
... | from solution import smallestMultiple
def test_smallest_multiple_1():
assert smallestMultiple(1) == 1
def test_smallest_multiple_2():
assert smallestMultiple(2) == 2
def test_smallest_multiple_3():
assert smallestMultiple(3) == 6
def test_smallest_multiple_4():
assert smallestMultiple(4) == 12
def ... | [
{
"docstring": "Computes the least common multiple of a and b.",
"function_declaration": "def lcm(a, b):",
"function_name": "lcm",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the smallest positive integer that is evenly divisible by all integers from 1 to n.",
"function_declara... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from math import gcd\n\ndef smallestMultiple(n):\n \"\"\"\n Returns the smallest positive integer that is evenly divisible by all integers from 1 to n.\n \"\"\"\n ... | trial_gpt4o_9 | {
"original_instruction": "Suppose you are given a positive integer `n`. Your task is to determine the smallest positive integer that is evenly divisible by all the integers from `1` to `n`. Formally, you need to find the least common multiple (LCM) of the first `n` natural numbers. Implement a function `int smallest... | 0.675174 | Leetcode_21558 | C | [
"lcm",
"smallestMultiple"
] | 2 | [
[
"smallestMultiple",
"lcm"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 307381959db59f7f975b7349708e08091a76c759 | 71d8b74dc28b975d47aa68f3aca2164f63780ba3 | |||
v1.0 | complete | Leetcode | Leetcode_21641_C | def ship_within_days(weights: List[int], days: int) -> int:
"""Find the minimum number of days required to ship all packages within the weight limit.
Each package must be shipped in the same order as they appear in the weights list.
The conveyor belt can only carry packages up to the given weight limit in a... | def can_ship(weights, days, capacity):
current_weight = 0
current_days = 1
for weight in weights:
if current_weight + weight > capacity:
current_days += 1
current_weight = 0
if current_days > days:
return False
current_weight += weight
return... | from solution import ship_within_days
def test_single_day():
assert ship_within_days([1, 2, 3, 4, 5], 1) == 15
def test_two_days():
assert ship_within_days([1, 2, 3, 4, 5], 2) == 9
def test_three_days():
assert ship_within_days([1, 2, 3, 4, 5], 3) == 6
def test_multiple_packages_single_day():
assert... | [
{
"docstring": null,
"function_declaration": "def can_ship(weights, days, capacity):",
"function_name": "can_ship",
"parameter_list": "(weights, days, capacity)"
},
{
"docstring": null,
"function_declaration": "def ship_within_days(weights, days):",
"function_name": "ship_within_days... | [
0,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def shipWithinDays(weights, capacity):\n \"\"\"\n Returns the minimum number of days required to ship all packages within the given capacity.\n \n :param weights:... | trial_gpt4o_1 | {
"original_instruction": "A conveyor belt has packages that must be shipped from one location to another within a certain timeframe. Each package has a weight represented by an integer array `weights`, where `weights[i]` denotes the weight of the `i-th` package. A conveyor belt has a weight limit represented by an i... | 0.664505 | Leetcode_21641 | C | [
"can_ship",
"ship_within_days"
] | 2 | [
[
"ship_within_days",
"can_ship"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 50049fa3687bd7a515c99ce0908e2c0d884ba4d6 | 35792ddadfccd4bed5f12eaa99f75dc172f8ccca | |||
v1.0 | complete | Leetcode | Leetcode_21840_C | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def find_difference_bst(root: TreeNode) -> int:
""" Write a function that finds the difference between the largest and smallest values in a binary search tree (BST). The ... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def find_min(node):
current = node
while current.left is not None:
current = current.left
return current.val
def find_max(node):
current = node
w... | from solution import TreeNode, find_difference_bst
def test_single_node_tree():
root = TreeNode(10)
assert find_difference_bst(root) == 0
def test_left_heavy_tree():
root = TreeNode(20)
root.left = TreeNode(10)
root.left.left = TreeNode(5)
assert find_difference_bst(root) == 15
def test_right... | [] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef find_max_min_diffe... | trial_gpt4o_8 | {
"original_instruction": "Write a function that finds the difference between the largest and smallest values in a binary search tree (BST). The BST is represented by its root node, and each node contains an integer value. Your function should return the difference as an integer. Note: A binary search tree (BST) is a... | 0.57269 | Leetcode_21840 | C | [
"find_min",
"find_max",
"find_difference_bst"
] | 3 | [
[
"find_difference_bst",
"find_max"
],
[
"find_difference_bst",
"find_min"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | cac56f5f0e545710aaeaf4e2a5ca5b53051478f1 | 831f9925115281ada2efe35253af47084adb05dc | |||
v1.0 | complete | Leetcode | Leetcode_21955_C | def remove_invalid_parentheses(s: str) -> List[str]:
"""
Removes the minimum number of parentheses to make the string valid. Returns all possible results.
>>> remove_invalid_parentheses("()())()") == {"()()()", "(())()"}
>>> remove_invalid_parentheses("(a)())()") == {"(a)()()", "(a())()"}
>>> r... | def remove_invalid_parentheses(s):
"""
Removes the minimum number of parentheses to make the string valid.
Returns all possible results.
"""
level = {s}
while True:
valid = list(filter(is_valid, level))
if valid:
return valid
# Generate all possible states
... | from solution import remove_invalid_parentheses
def test_example_1():
assert set(remove_invalid_parentheses("()())()")) == {"()()()", "(())()"}
def test_example_2():
assert set(remove_invalid_parentheses("(a)())()")) == {"(a)()()", "(a())()"}
def test_example_3():
assert set(remove_invalid_parentheses(")... | [
{
"docstring": "Removes the minimum number of parentheses to make the string valid.\nReturns all possible results.",
"function_declaration": "def remove_invalid_parentheses(s):",
"function_name": "remove_invalid_parentheses",
"parameter_list": "(s)"
},
{
"docstring": "Checks if the parenthes... | [
1,
0,
0,
1,
1,
0,
0,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def remove_invalid_parentheses(s):\n def is_valid(string):\n count = 0\n for char in string:\n if char == '(':\n count += 1\n ... | trial_gpt4o_4 | {
"original_instruction": "You are given a string `s` containing only parentheses '(' and ')'. Your task is to remove the minimum number of parentheses in any positions so that the resulting string is valid (i.e., each open parenthesis is eventually closed). Return all possible results in any order.",
"prompt_id": ... | 0.747257 | Leetcode_21955 | C | [
"remove_invalid_parentheses",
"is_valid"
] | 2 | [
[
"remove_invalid_parentheses",
"is_valid"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f16dce9b0b502e06ee7602d112dfbe31b5ec094c | 8be71ea7724884ffc70486ca47defb2592fac269 | |||
v1.0 | complete | Leetcode | Leetcode_22067_C | from typing import List
def find_smallest_diameter(points: List[List[int]]) -> List[List[int]]:
"""
Find the pair of points that forms the diameter of the smallest circle that can enclose all the given points.
>>> find_smallest_diameter([[0, 0], [0, 1], [1, 1], [1, 0]]) in [[[0, 0], [1, 1]], [[1, 1],... | import itertools
import math
def euclidean_distance(point1, point2):
"""
Calculate the Euclidean distance between two points.
"""
return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)
def find_smallest_diameter(points):
"""
Find the pair of points that forms the diamete... | from solution import find_smallest_diameter
def test_simple_case():
assert find_smallest_diameter([[0, 0], [0, 1], [1, 1], [1, 0]]) in [[[0, 0], [1, 1]], [[1, 1], [0, 0]], [[0, 1], [1, 0]], [[1, 0], [0, 1]]]
def test_single_pair():
assert find_smallest_diameter([[1, 1], [4, 5]]) == [[1, 1], [4, 5]]
def test_... | [
{
"docstring": "Calculate the Euclidean distance between two points.",
"function_declaration": "def euclidean_distance(point1, point2):",
"function_name": "euclidean_distance",
"parameter_list": "(point1, point2)"
},
{
"docstring": "Find the pair of points that forms the diameter of the smal... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\nfrom itertools import combinations\n\ndef distance(point1, point2):\n return math.sqrt((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2)\n\ndef smalles... | trial_gpt4o_9 | {
"original_instruction": "You are given a list of `points` where each `point[i] = [xi, yi]` represents the coordinates of a point in a 2D plane. The diameter of a circle is defined as the greatest distance between any two points on its perimeter. Find the pair of points that forms the diameter of the smallest circle... | 0.587342 | Leetcode_22067 | C | [
"euclidean_distance",
"find_smallest_diameter"
] | 2 | [
[
"find_smallest_diameter",
"euclidean_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1af3ac289cbd6620026092faf087867d70936264 | 2f7b650f89d6c61c721936a348d9ebffaca0a389 | |||
v1.0 | complete | Leetcode | Leetcode_22102_C | def longest_concatenated_word(words: List[str]) -> int:
""" Given an array of strings `words`, return the length of the longest string `w` in `words` such that `w` can be formed by concatenating other strings from the array. Each string in the array can be used multiple times in constructing `w`. If no such string ... | def is_composable(word, word_set):
if word in word_set:
return True
for i in range(1, len(word)):
prefix = word[:i]
suffix = word[i:]
if prefix in word_set and is_composable(suffix, word_set):
return True
return False
def longest_concatenated_word(words):
wor... | from solution import longest_concatenated_word
def test_no_composable_words():
assert longest_concatenated_word(['cat', 'dog', 'rat']) == 0
def test_single_longest_concatenated_word():
assert longest_concatenated_word(['cat', 'dog', 'catdog']) == 6
def test_multiple_concatenated_words():
assert longest_c... | [
{
"docstring": null,
"function_declaration": "def is_composable(word, word_set):",
"function_name": "is_composable",
"parameter_list": "(word, word_set)"
},
{
"docstring": null,
"function_declaration": "def longest_concatenated_word(words):",
"function_name": "longest_concatenated_wo... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def longest_concatenated_word(words):\n def can_form(word, word_dict):\n if word in memo:\n return memo[word]\n \n for i in range(1, len(wo... | trial_gpt4o_3 | {
"original_instruction": "Given an array of strings `words`, return the length of the longest string `w` in `words` such that `w` can be formed by concatenating other strings from the array. Each string in the array can be used multiple times in constructing `w`. If no such string exists, return `0`.",
"prompt_id"... | 0.749207 | Leetcode_22102 | C | [
"is_composable",
"longest_concatenated_word"
] | 2 | [
[
"longest_concatenated_word",
"is_composable"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 8ff2e1b414dce12e2de79f69f735fa530e87737d | 5202fecbbfa2674e915af031756b5a21b80892f8 | |||
v1.0 | complete | Leetcode | Leetcode_22483_C | from typing import List, Optional
class TreeNode:
def __init__(self, x: int):
self.val = x
self.left = None
self.right = None
def array_to_bst(arr: List[int]) -> Optional[TreeNode]:
"""
Converts a list representing a binary tree in level order into a BST.
"""
if not arr:
... | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def array_to_bst(arr):
"""
Converts a list representing a binary tree in level order into a BST.
"""
if not arr:
return None
root = TreeNode(arr[0])
queue = [root]
... | from solution import find_path_in_tree
def test_find_path_exists():
assert find_path_in_tree([5, 3, 8, 1, 4, 7, 10], 4) == [5, 3, 4]
def test_find_path_non_existent_target():
assert find_path_in_tree([5, 3, 8, 1, 4, 7, 10], 11) == []
def test_find_path_single_element():
assert find_path_in_tree([5], 5) =... | [] | [
1,
1,
0,
0,
1,
1,
0,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\ndef array_to_tree(array, i=0):\n if i >= len(arra... | trial_gpt4o_8 | {
"original_instruction": "You are given a binary tree with `n` nodes, where each node contains a unique integer value. Write a function that finds the path from the root node to a given target node. The path should be represented as a list of integers, corresponding to the values of the nodes in the order they are v... | 0.575662 | Leetcode_22483 | C | [
"array_to_bst",
"find_path",
"find_path_in_tree"
] | 3 | [
[
"find_path_in_tree",
"array_to_bst"
],
[
"find_path_in_tree",
"find_path"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 1af61b39c6a65d793c539fea5f67a612d142ce0a | a0792b7dc2eabd4253ed9141571e09e9b8a9b980 | |||
v1.0 | complete | Leetcode | Leetcode_22614_C | def is_subsequence(s: str, word: str) -> bool:
"""
Helper function to check if 'word' is a subsequence of 's'.
>>> is_subsequence("abcde", "ace") True
>>> is_subsequence("abcde", "aec") False
"""
def shortest_non_subsequence(s: str, words: List[str]) -> str:
"""
Given a string `s` and a list... | def is_subsequence(s, word):
"""
Helper function to check if 'word' is a subsequence of 's'.
"""
it = iter(s)
return all(char in it for char in word)
def shortest_non_subsequence(s, words):
"""
Given a string `s` and a list of words `words`, return the shortest word in `words`
that is ... | from solution import is_subsequence, shortest_non_subsequence
def test_is_subsequence():
assert is_subsequence("abcde", "ace") == True
assert is_subsequence("abcde", "aec") == False
assert is_subsequence("abcde", "abcde") == True
assert is_subsequence("abcde", "abcdef") == False
def test_shortest_non_... | [
{
"docstring": "Helper function to check if 'word' is a subsequence of 's'.",
"function_declaration": "def is_subsequence(s, word):",
"function_name": "is_subsequence",
"parameter_list": "(s, word)"
},
{
"docstring": "Given a string `s` and a list of words `words`, return the shortest word i... | [
0,
0,
1,
0,
1,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_subsequence(s, t):\n \"\"\"\n Helper function to determine if t is a subsequence of s.\n \"\"\"\n it = iter(s)\n return all(char in it for char in t)\n\... | trial_gpt4o_4 | {
"original_instruction": "Given a string `s` and a list of words `words`, where each word is a **subsequence** of `s`, find the **shortest** word in `words` that is not a subsequence of `s`. If there are multiple shortest words with the same length, return the lexicographically smallest one. If all words in `words` ... | 0.723939 | Leetcode_22614 | C | [
"is_subsequence",
"shortest_non_subsequence"
] | 2 | [
[
"shortest_non_subsequence",
"is_subsequence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c0df405396a36c12518a8d343d356fab4af275d9 | b4d92deac09825f3c4f923fa5d2e19d322d8dda2 | |||
v1.0 | complete | Leetcode | Leetcode_22617_C | def can_find_k_cities_with_threshold(n: int, graph: List[Tuple[int, int, int]], k: int, threshold: int) -> bool:
"""
Determine if there exist at least k cities such that each pair of these k cities has a path between them
with a total distance not exceeding a given threshold d.
>>> can_find_k_cities_... | import heapq
def floyd_warshall(n, graph, threshold):
# Initialize distance matrix with infinity
dist = [[float('inf')] * n for _ in range(n)]
# Distance from a node to itself is 0
for i in range(n):
dist[i][i] = 0
# Fill in the graph edges
for u, v, w in graph:
dist[u... | from solution import can_find_k_cities_with_threshold
def test_case_1():
n = 4
graph = [
(0, 1, 4),
(0, 2, 5),
(1, 2, 2),
(1, 3, 1),
(2, 3, 3)
]
k = 3
threshold = 5
assert can_find_k_cities_with_threshold(n, graph, k, threshold) == True
def test_case_2()... | [
{
"docstring": null,
"function_declaration": "def floyd_warshall(n, graph, threshold):",
"function_name": "floyd_warshall",
"parameter_list": "(n, graph, threshold)"
},
{
"docstring": null,
"function_declaration": "def can_find_k_cities_with_threshold(n, graph, k, threshold):",
"func... | [
1,
1,
1,
0,
0,
0,
0,
1,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import heapq\nimport collections\n\ndef does_k_cities_exist_within_distance(n, roads, k, d):\n \"\"\"\n Determines if there exist at least k cities such that each pair ... | trial_gpt4o_7 | {
"original_instruction": "You are given a **connected** weighted undirected graph with `n` nodes labeled from `0` to `n-1` and an integer `k`. Each node represents a city, and there is a direct road between certain pairs of cities, with a weight representing the distance of that road. Your task is to determine if th... | 0.638296 | Leetcode_22617 | C | [
"floyd_warshall",
"can_find_k_cities_with_threshold"
] | 2 | [
[
"can_find_k_cities_with_threshold",
"floyd_warshall"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b4231a00629ce3154b22d6a48e6f5f9236743537 | fa025161f13086931da43ca05dd579ed6dae3666 | |||
v1.0 | complete | Leetcode | Leetcode_22795_C | class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
def build_tree_from_list(nums):
if not nums:
return None
nodes = [TreeNode(value) if value is not None else None for value in nums]
for i in range(l... | class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
def build_tree_from_list(nums):
if not nums:
return None
nodes = [TreeNode(value) if value is not None else None for value in nums]
for i in range(l... | from solution import max_path_sum
def test_single_node_tree():
assert max_path_sum([5]) == 5
def test_complete_small_tree():
assert max_path_sum([1, 2, 3]) == 6
def test_complete_large_tree():
assert max_path_sum([-10, 9, 20, None, None, 15, 7]) == 42
def test_tree_with_negatives():
assert max_path_... | [] | [
1,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, value=0, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\ndef build_tree_f... | trial_gpt4o_0 | {
"original_instruction": "You are given a list of integers `nums` representing a binary tree in level order traversal. Write a function to find the maximum path sum. A path in the binary tree is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The p... | 0.649457 | Leetcode_22795 | C | [
"build_tree_from_list",
"max_path_sum"
] | 2 | [
[
"max_path_sum",
"build_tree_from_list"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 3cfe45b84c566279412dda9ce7066a35dd3a58ba | 861088f83dd66ce6ac56cc86d0d49e141c69722b | |||
v1.0 | complete | Leetcode | Leetcode_22968_C | from typing import List
def generate_magic_square(m: int) -> List[List[int]]:
"""
Generates an m x m magic square for odd m.
:param m: size of the magic square (must be a positive odd integer)
:return: m x m list representing the magic square, or an empty list if m is not a positive odd integer
>... | def is_odd_positive_integer(m):
return m > 0 and m % 2 == 1
def generate_magic_square(m):
"""
Generates an m x m magic square for odd m.
:param m: size of the magic square (must be a positive odd integer)
:return: m x m list representing the magic square, or an empty list if m is not a positiv... | from solution import generate_magic_square
def test_generate_magic_square_3x3():
expected = [
[8, 1, 6],
[3, 5, 7],
[4, 9, 2]
]
assert generate_magic_square(3) == expected
def test_generate_magic_square_1x1():
expected = [
[1]
]
assert generate_magic_square(1) =... | [
{
"docstring": null,
"function_declaration": "def is_odd_positive_integer(m):",
"function_name": "is_odd_positive_integer",
"parameter_list": "(m)"
},
{
"docstring": "Generates an m x m magic square for odd m.\n\n:param m: size of the magic square (must be a positive odd integer)\n:return: m... | [
1,
1,
0,
1,
0,
0,
1,
0,
1
] | 5 | medium | 0.556 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def generate_magic_square(m):\n \"\"\"\n Generates an m x m magic square.\n \n Parameters:\n m (int): The dimension of the magic square.\n \n Returns:\n ... | trial_gpt4o_9 | {
"original_instruction": "Given an integer `m`, generate an `m x m` magic square. A magic square is an arrangement of numbers in a square grid where the numbers in each row, each column, and both main diagonals all add up to the same number, known as the magic constant. In this particular problem, the magic square s... | 0.741273 | Leetcode_22968 | C | [
"is_odd_positive_integer",
"generate_magic_square"
] | 2 | [
[
"generate_magic_square",
"is_odd_positive_integer"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | aecfa8ea5980a57f8bfee58e83f949723f441264 | 2715e019d5d57841d6843b2f4ffffdf63b645255 | |||
v1.0 | complete | Leetcode | Leetcode_23505_C | from typing import List
def is_palindrome(s: str) -> bool:
""" Helper function to check if a given string is a palindrome. """
return s == s[::-1]
def longest_valid_prefix_palindrome(words: List[str]) -> List[int]:
"""
For each string in the list, identify the length of the longest "valid prefix pali... | def is_palindrome(s):
"""
Helper function to check if a given string is a palindrome.
"""
return s == s[::-1]
def longest_valid_prefix_palindrome(words):
"""
For each word in the list, find the length of the longest valid prefix palindrome.
"""
result = []
for word in words:
... | from solution import longest_valid_prefix_palindrome
def test_single_palindrome():
words = ["abba"]
assert longest_valid_prefix_palindrome(words) == [4]
def test_no_palindrome():
words = ["abc"]
assert longest_valid_prefix_palindrome(words) == [1]
def test_empty_string():
words = [""]
assert ... | [
{
"docstring": "Helper function to check if a given string is a palindrome.",
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": "For each word in the list, find the length of the longest valid prefix palindrome.",
... | [
0,
0,
0,
0,
1,
0,
0,
0,
1,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def is_palindrome(s):\n \"\"\"\n Returns True if the string s is a palindrome, else False.\n \"\"\"\n return s == s[::-1]\n\ndef longest_valid_prefix_palindrome(w... | trial_gpt4o_9 | {
"original_instruction": "You are given a list of strings `words`. Each string S in `words` is composed of lowercase English letters. We'll call a string S a \"valid prefix palindrome\" if it can be split into two parts (that may be empty), where the first part is a palindrome and the second part is any remaining po... | 0.780857 | Leetcode_23505 | C | [
"is_palindrome",
"longest_valid_prefix_palindrome"
] | 2 | [
[
"longest_valid_prefix_palindrome",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7f188a1353a03792afd343a52ee2d0447e09bf63 | e361a93a0a9517b5926c61dc103fdc81bc86b805 | |||
v1.0 | complete | Leetcode | Leetcode_23567_C | from typing import List
def largestSimilarWordsGroup(words: List[str]) -> int:
"""
You are given a `words` array containing strings of equal length `n`. Two words are considered
**similar** if they differ by at most two characters. Find the largest group of similar words
in the array. Return the size... | from collections import deque
def differByAtMostTwo(word1, word2):
"""
Return True if words differ by at most 2 characters.
"""
diff_count = 0
for c1, c2 in zip(word1, word2):
if c1 != c2:
diff_count += 1
if diff_count > 2:
return False
return True
def b... | from solution import largestSimilarWordsGroup
def test_empty_list():
assert largestSimilarWordsGroup([]) == 0
def test_single_word():
assert largestSimilarWordsGroup(["hello"]) == 1
def test_all_similar():
assert largestSimilarWordsGroup(["abcd", "abcf", "abff", "abce"]) == 4
def test_two_groups():
... | [
{
"docstring": "Return True if words differ by at most 2 characters.",
"function_declaration": "def differByAtMostTwo(word1, word2):",
"function_name": "differByAtMostTwo",
"parameter_list": "(word1, word2)"
},
{
"docstring": "Perform BFS to find the size of the connected component of simila... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def largest_group_of_similar_words(words):\n \"\"\"\n Returns the size of the largest group of similar words in the given list of words.\n \n A word is similar to... | trial_gpt4o_7 | {
"original_instruction": "You are given a `words` array containing strings of equal length `n`. Two words are considered **similar** if they differ by at most two characters. Find the largest group of similar words in the array. Return the size of this largest group. Note that for a pair of words to be considered s... | 0.73174 | Leetcode_23567 | C | [
"differByAtMostTwo",
"bfs",
"largestSimilarWordsGroup"
] | 3 | [
[
"bfs",
"differByAtMostTwo"
],
[
"largestSimilarWordsGroup",
"bfs"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e66500ca78026f2a84dc9950c03c77c420ea8ee4 | 3694dbe81c7f20af87fba1642ca3ca70bef44975 | |||
v1.0 | complete | Leetcode | Leetcode_23661_C | from typing import List, Tuple, Optional
def collinear(p1: Tuple[int, int], p2: Tuple[int, int], p3: Tuple[int, int]) -> bool:
"""
Check if points p1, p2, and p3 are collinear. Points are collinear if the area
of the triangle they form is zero.
>>> collinear((0, 0), (1, 1), (2, 2)) True
>>> colline... | from itertools import combinations
def collinear(p1, p2, p3):
"""
Check if points p1, p2, and p3 are collinear.
Points are collinear if the area of the triangle they form is zero.
The area can be calculated using the determinant of a 3x3 matrix
formed by the points.
"""
(x1, y1), (x2, y2), ... | from solution import find_triplet
def test_find_triplet_no_collinear():
points = [(0, 0), (1, 1), (2, 3), (4, 5)]
assert find_triplet(points) == None
def test_find_triplet_collinear_points():
points = [(0, 0), (1, 1), (2, 2), (-1, -1)]
assert find_triplet(points) in [(0, 1, 2), (0, 1, 3), (0, 2, 3), (... | [
{
"docstring": "Check if points p1, p2, and p3 are collinear.\nPoints are collinear if the area of the triangle they form is zero.\nThe area can be calculated using the determinant of a 3x3 matrix\nformed by the points.",
"function_declaration": "def collinear(p1, p2, p3):",
"function_name": "collinear"... | [
0,
1,
0,
1,
0,
1,
0,
1,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def points_on_same_line(points):\n \"\"\"\n Determine if there exists a straight line passing through at least three given points.\n \n Args:\n points (list of... | trial_gpt4o_8 | {
"original_instruction": "Given `n` pairs of coordinates `(x[i], y[i])`, determine if there exists a straight line that passes through at least three of these points. If such a line exists, identify the triplet of points that lie on that straight line and return their indices (0-indexed) as a tuple `(i, j, k)`. Othe... | 0.733486 | Leetcode_23661 | C | [
"collinear",
"find_triplet"
] | 2 | [
[
"find_triplet",
"collinear"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e8f02a35f9d7deb1c38289408185738d5194da46 | 7cb6ee32477265882094488b38efa79b8a145e9d | |||
v1.0 | complete | Leetcode | Leetcode_23753_C | def max_sum_subgrid(grid):
"""
Returns the maximum sum of any subgrid in the given 2D grid.
Args:
grid (list of list of int): 2D list representing the grid.
Returns:
int: The maximum sum of any rectangular subgrid within the given grid.
"""
pass
def kadane(array):
"""
... | def max_sum_subgrid(grid):
"""
Returns the maximum sum of any subgrid in the given 2D grid.
Args:
grid (list of list of int): 2D list representing the grid.
Returns:
int: The maximum sum of any rectangular subgrid within the given grid.
"""
if not grid or not grid[0]:
r... | from solution import max_sum_subgrid
def test_example_grid():
grid = [
[1, -2, 3],
[-1, 2, -1],
[3, -2, 1]
]
assert max_sum_subgrid(grid) == 4 # [1, -2, 3]
def test_all_positive_grid():
grid = [
[1, 2],
[3, 4]
]
assert max_sum_subgrid(grid) == 10 #... | [
{
"docstring": "Returns the maximum sum of any subgrid in the given 2D grid.\n\nArgs:\ngrid (list of list of int): 2D list representing the grid.\n\nReturns:\nint: The maximum sum of any rectangular subgrid within the given grid.",
"function_declaration": "def max_sum_subgrid(grid):",
"function_name": "... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def max_sum_subgrid(grid):\n \"\"\"\n Finds the largest sum of any rectangular subgrid within the given grid.\n \n Parameters:\n grid (list of list of int): 2D... | trial_gpt4o_7 | {
"original_instruction": "You are given a grid of numbers represented as a 2D array `grid`, with `n` rows and `m` columns. Your task is to find the largest sum of any rectangular subgrid within `grid`. The subgrid must be non-empty and contiguous. Return the maximum sum of any such subgrid.",
"prompt_id": "0000023... | 0.651528 | Leetcode_23753 | C | [
"max_sum_subgrid",
"kadane"
] | 2 | [
[
"max_sum_subgrid",
"kadane"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ed05d301d1bee2a9e45714eb9bf8de7ae611a396 | 0aa753d5ddd65bdbf88c09d2d56bbda3d8d0cebe | |||
v1.0 | complete | Leetcode | Leetcode_23986_C | class TreeNode:
def __init__(self, val: int):
self.val = val
self.parent = None
def build_tree(parents):
nodes = [TreeNode(i + 1) for i in range(len(parents))]
root = None
for i, parent_index in enumerate(parents):
if parent_index == -1:
root = nodes[i]
else:... | class TreeNode:
def __init__(self, val: int):
self.val = val
self.parent = None
def build_tree(parents):
nodes = [TreeNode(i + 1) for i in range(len(parents))]
root = None
for i, parent_index in enumerate(parents):
if parent_index == -1:
root = nodes[i]
else:... | from solution import lca
def test_lca():
parents = [-1, 1, 1, 2, 2, 3, 3]
assert lca(parents, 4, 5) == 2
assert lca(parents, 4, 6) == 1
assert lca(parents, 3, 4) == 1
assert lca(parents, 2, 4) == 2
# Test case with one node being the LCA of itself and another node
parents = [-1, 1, 1, 2, 3... | [] | [
0,
1,
0,
1,
1,
1,
1,
1,
1
] | 7 | easy | 0.778 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def find_lca(parents, p, q):\n \"\"\"\n Finds the lowest common ancestor (LCA) of nodes p and q in a binary tree represented by the parents array.\n \"\"\"\n # Cr... | trial_gpt4o_6 | {
"original_instruction": "You are given a **binary tree** with `n` nodes, where each node has a unique value from `1` to `n`. The tree is represented as an array `parents` where `parents[i]` is the parent of node `i+1`. The root of the tree has `parents[i]` equal to `-1`. Your task is to find the **lowest common anc... | 0.578369 | Leetcode_23986 | C | [
"build_tree",
"find_path_to_root",
"lca"
] | 3 | [
[
"lca",
"build_tree"
],
[
"lca",
"find_path_to_root"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 1c895f2f62c63ae7e1caaea6f0104bd302e95fee | 3a950f2f755e8a912c5dadbb47f77e85fedb1a81 | |||
v1.0 | complete | Leetcode | Leetcode_24129_C | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def find(root, val):
"""
Helper function to find a node with given value in BST.
"""
# Your code here
def lowest_common_ancestor(root, p, q):
"""
Ret... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def find(root, val):
"""
Helper function to find a node with given value in BST.
"""
if root is None:
return None
if val == root.val:
retu... | from solution import TreeNode, lowest_common_ancestor
def test_example():
# Construct the BST
root = TreeNode(6)
root.left = TreeNode(2)
root.right = TreeNode(8)
root.left.left = TreeNode(0)
root.left.right = TreeNode(4)
root.left.right.left = TreeNode(3)
root.left.right.right = TreeNod... | [] | [
0,
0,
0,
0,
1,
0,
1,
1,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, value=0, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\ndef find_lca(roo... | trial_gpt4o_4 | {
"original_instruction": "You are given a **binary search tree (BST)** with `n` nodes. Each node carries a unique integer value. You need to implement a function to find the **lowest common ancestor (LCA)** of two given nodes in the BST. The LCA of two nodes `p` and `q` in a BST is defined as the lowest node that ha... | 0.522684 | Leetcode_24129 | C | [
"find",
"lowest_common_ancestor"
] | 2 | [
[
"lowest_common_ancestor",
"find"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 4c67a62e5a4e5bbd5a7a46c5239ae7d9359e2a74 | 74d7b784684e00fa774aad72c283ddec7bcd5258 | |||
v1.0 | complete | Leetcode | Leetcode_24220_C | def merge_sort(nums):
"""
Given an integer array `nums`, sorts the array in ascending order using the Merge Sort algorithm and returns the sorted array.
>>> merge_sort([])
[]
>>> merge_sort([1])
[1]
>>> merge_sort([3, 1, 2])
[1, 2, 3]
>>> merge_sort([-1, -3, 2, 1])
[-3, -1, ... | def merge_sort(nums):
"""
Sorts the array in ascending order using the Merge Sort algorithm.
"""
if len(nums) <= 1:
return nums
mid = len(nums) // 2
left_half = merge_sort(nums[:mid])
right_half = merge_sort(nums[mid:])
return merge(left_half, right_half)
def merge(lef... | from solution import merge_sort
def test_empty_array():
assert merge_sort([]) == []
def test_single_element_array():
assert merge_sort([1]) == [1]
def test_multiple_elements_array():
assert merge_sort([3, 1, 2]) == [1, 2, 3]
def test_negative_numbers_array():
assert merge_sort([-1, -3, 2, 1]) == [-3... | [
{
"docstring": "Sorts the array in ascending order using the Merge Sort algorithm.",
"function_declaration": "def merge_sort(nums):",
"function_name": "merge_sort",
"parameter_list": "(nums)"
},
{
"docstring": "Merges two sorted lists into one sorted list.",
"function_declaration": "def ... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def merge_sort(nums):\n \"\"\"\n Sorts the array in ascending order using the Merge Sort algorithm.\n \"\"\"\n if len(nums) <= 1:\n return nums\n\n mid ... | trial_gpt4o_9 | {
"original_instruction": "Given an integer array `nums`, sort the array in ascending order using the Merge Sort algorithm and return the sorted array. The array can contain both positive and negative numbers. Implement the Merge Sort algorithm recursively and ensure your function can handle edge cases such as an emp... | 0.656159 | Leetcode_24220 | C | [
"merge_sort",
"merge"
] | 2 | [
[
"merge_sort",
"merge"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 20519e0a7455aa4fc45211bf73fcd30b1f56a8c8 | 163a7790de6f22b4abb4dbff83dd19c4dedfc97c | |||
v1.0 | complete | Leetcode | Leetcode_24396_C | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_subtree(s, t):
""" Check whether t is a subtree of s.
>>> s = TreeNode(3, left=TreeNode(4, left=TreeNode(1), right=TreeNode(2)), right=TreeNode(5))
>>> t ... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_subtree(s, t):
if not t:
return True
if not s:
return False
if is_same_tree(s, t):
return True
return is_subtree(s.left, t) or ... | from solution import TreeNode, is_subtree
def test_is_subtree_true():
s = TreeNode(3,
left=TreeNode(4,
left=TreeNode(1),
right=TreeNode(2)),
right=TreeNode(5))
t = TreeNode(4,
left=TreeNode(1),
... | [] | [
1,
0,
0,
1,
1,
1,
0,
1,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\ndef is_subtree(s, t):\... | trial_gpt4o_7 | {
"original_instruction": "You are given two non-empty binary trees `s` and `t`. Imagine there is a subtree of `s` that consists of all the nodes in `t`. Check whether `t` is a subtree of `s`. A subtree of a binary tree `s` is a tree `t` consisting of a node in `s` and all of this node's descendants. The tree `s` cou... | 0.558478 | Leetcode_24396 | C | [
"is_subtree",
"is_same_tree"
] | 2 | [
[
"is_subtree",
"is_same_tree"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 4b8025eb8f5a7ff577b99b0d88fab435a7d0c5e8 | 35e32a9d239a87a7f8cde5320d6a0faff6aa744a | |||
v1.0 | complete | Leetcode | Leetcode_24508_C | def is_palindrome(s: str) -> bool:
""" Check if a given string is a palindrome.
>>> is_palindrome("a") True
>>> is_palindrome("aa") True
>>> is_palindrome("abc") False
"""
def count_palindromic_substrings(s: str) -> int:
""" Given a string `s`, count the number of times a non-overlapping
... | def is_palindrome(s):
return s == s[::-1]
def count_palindromic_substrings(s):
n = len(s)
count = 0
# Iterate over all possible substring lengths
for length in range(1, n + 1):
i = 0
# Iterate over all possible substrings of length `length`
while i + length <= n:
... | from solution import count_palindromic_substrings
def test_single_character():
assert count_palindromic_substrings("a") == 1
assert count_palindromic_substrings("b") == 1
def test_all_same_characters():
assert count_palindromic_substrings("aaa") == 6
# Palindromes: "a", "a", "a", "aa", "aa", "aaa"
... | [
{
"docstring": null,
"function_declaration": "def is_palindrome(s):",
"function_name": "is_palindrome",
"parameter_list": "(s)"
},
{
"docstring": null,
"function_declaration": "def count_palindromic_substrings(s):",
"function_name": "count_palindromic_substrings",
"parameter_list... | [
0,
1,
0,
0,
0,
0,
0,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def count_non_overlapping_palindromic_substrings(s):\n \"\"\"\n Returns the number of non-overlapping palindromic substrings in the string s.\n \"\"\"\n def is_pa... | trial_gpt4o_7 | {
"original_instruction": "Given a string `s`, count the number of times a non-overlapping substring, which is a palindrome, appears in `s`. A **palindrome** is a sequence of characters that reads the same backward as forward. Two occurrences of the same substring are counted as different if they start at different p... | 0.776205 | Leetcode_24508 | C | [
"is_palindrome",
"count_palindromic_substrings"
] | 2 | [
[
"count_palindromic_substrings",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 837c1b1bcc9b94a5fd100f471376773e7e1d3974 | c3f9104b8328fa8a182b202807ef44ed1816812c | |||
v1.0 | complete | Leetcode | Leetcode_24706_C | def count_subsequences(words: List[str], s: str) -> int:
"""
You are given a list of strings `words` and a string `s`. Each string in `words` represents
a pattern of dots and dashes (`.` and `-` respectively), and the string `s` contains only
dots and dashes as well. The task is to find how many of th... | def is_subsequence(pattern, s):
"""
Helper function to check if a pattern is a subsequence of string `s`.
"""
it = iter(s)
return all(char in it for char in pattern)
def count_subsequences(words, s):
"""
Returns the count of words that are subsequences of string `s`.
"""
count = 0
... | from solution import count_subsequences
def test_example_case():
words = ["..", ".", "-."]
s = "..-."
assert count_subsequences(words, s) == 3
def test_no_match_case():
words = ["..-", "--."]
s = ".."
assert count_subsequences(words, s) == 0
def test_all_match_case():
words = [".", ".", "... | [
{
"docstring": "Helper function to check if a pattern is a subsequence of string `s`.",
"function_declaration": "def is_subsequence(pattern, s):",
"function_name": "is_subsequence",
"parameter_list": "(pattern, s)"
},
{
"docstring": "Returns the count of words that are subsequences of string... | [
0,
0,
0,
0,
0,
0,
0,
0,
1,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def isSubsequence(s, word):\n it = iter(s)\n return all(char in it for char in word)\n\ndef countSubsequences(words, s):\n \"\"\"\n Returns the number of words fr... | trial_gpt4o_8 | {
"original_instruction": "You are given a list of strings `words` and a string `s`. Each string in `words` represents a pattern of dots and dashes (`.` and `-` respectively), and the string `s` contains only dots and dashes as well. The task is to find how many of the strings in `words` can be formed as subsequences... | 0.724849 | Leetcode_24706 | C | [
"is_subsequence",
"count_subsequences"
] | 2 | [
[
"count_subsequences",
"is_subsequence"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0c8ee2b0d1548ac1cad80df683506ed2c825759e | 2b7e18add686aa4a7e684ac2cd0c09983d3a2910 | |||
v1.0 | complete | Leetcode | Leetcode_24711_C | from typing import List
def maxAreaUnderModifiedHistogram(heights: List[int]) -> int:
"""
You are given a 0-indexed integer array heights of length n representing the heights of columns in a histogram.
Each column's width is 1. Find the largest rectangle that can be formed under the histogram.
You ca... | def largestRectangleArea(heights):
"""
Returns the maximum area of the largest rectangle in the histogram.
"""
stack = []
max_area = 0
heights.append(0)
for i in range(len(heights)):
while stack and heights[stack[-1]] > heights[i]:
height = heights[stack.pop()]
... | from solution import maxAreaUnderModifiedHistogram
def test_maxAreaUnderModifiedHistogram_case1():
assert maxAreaUnderModifiedHistogram([2, 1, 5, 6, 2, 3]) == 10
def test_maxAreaUnderModifiedHistogram_case2():
assert maxAreaUnderModifiedHistogram([2, 4]) == 4
def test_maxAreaUnderModifiedHistogram_case3():
... | [
{
"docstring": "Returns the maximum area of the largest rectangle in the histogram.",
"function_declaration": "def largestRectangleArea(heights):",
"function_name": "largestRectangleArea",
"parameter_list": "(heights)"
},
{
"docstring": "Returns the maximum rectangle area that can be obtaine... | [
1,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def max_histogram_area(heights):\n \"\"\"\n Function to calculate the largest rectangle area in a histogram\n \"\"\"\n stack = []\n max_area = 0\n index = 0... | trial_gpt4o_9 | {
"original_instruction": "You are given a **0-indexed** integer array `heights` of length `n` representing the heights of columns in a histogram. Each column's width is `1`. You are asked to find the **largest rectangle** that can be formed under the histogram. You can choose to either:\n\n- Leave the array **unchan... | 0.695409 | Leetcode_24711 | C | [
"largestRectangleArea",
"maxAreaUnderModifiedHistogram"
] | 2 | [
[
"maxAreaUnderModifiedHistogram",
"largestRectangleArea"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 40e64bc8e60b3d13c17e77d3e36e7b216282ad5c | d8b9c9314c3e66d0e1b16608cd872d91128eb528 | |||
v1.0 | complete | Leetcode | Leetcode_24754_C | from typing import List
def maximalRectangle(mat: List[List[int]]) -> int:
""" Given an m x n binary matrix 'mat', return the largest rectangle containing only 1's and its area.
The function should efficiently handle a potentially large size of the matrix.
>>> maximalRectangle([
[1, 0, 1, 0, 0... | def maximalRectangle(mat):
if not mat:
return 0
max_area = 0
n = len(mat[0])
heights = [0] * n
for row in mat:
for i in range(n):
if row[i] == 0:
heights[i] = 0
else:
heights[i] += 1
max_area = max(max_are... | from solution import maximalRectangle
def test_small_matrix():
mat = [
[1, 0, 1, 0, 0],
[1, 0, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 0, 0, 1, 0]
]
assert maximalRectangle(mat) == 6
def test_empty_matrix():
mat = []
assert maximalRectangle(mat) == 0
def test_matrix_with_no... | [
{
"docstring": null,
"function_declaration": "def maximalRectangle(mat):",
"function_name": "maximalRectangle",
"parameter_list": "(mat)"
},
{
"docstring": null,
"function_declaration": "def largestRectangleArea(heights):",
"function_name": "largestRectangleArea",
"parameter_list... | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def maximalRectangle(matrix):\n \"\"\"\n Given an m x n binary matrix `matrix`, returns the area of the largest rectangle containing only 1's.\n \"\"\"\n if not m... | trial_gpt4o_9 | {
"original_instruction": "Given an `m x n` binary matrix `mat`, return the largest rectangle containing only 1's and its area. Your answer will be an integer representing the area of the largest rectangle. Implement the function `maximalRectangle(List<List<Integer>> mat)` to solve the problem. Ensure your solution e... | 0.709937 | Leetcode_24754 | C | [
"maximalRectangle",
"largestRectangleArea"
] | 2 | [
[
"maximalRectangle",
"largestRectangleArea"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 9ac2080a14401e749f567d68f48461e4a92922f7 | 9252d92b689b7194202d540d4742b41f9072fa04 | |||
v1.0 | complete | Leetcode | Leetcode_25081_C | def palindrome_pairs(words: List[str]) -> List[List[int]]:
""" Given a list of words, find all the pairs of indices (i, j) such that the concatenation of words[i] and words[j] is a palindrome.
Return the list of pairs sorted in lexicographical order according to the pair values.
>>> palindrome_pairs(["bat"... | def is_palindrome(word):
"""
Checks if a given word is a palindrome.
"""
return word == word[::-1]
def palindrome_pairs(words):
"""
Finds all pairs of indices (i, j) such that the concatenation of words[i] and words[j] is a palindrome.
Returns the list of pairs sorted in lexicographical ord... | from solution import palindrome_pairs
def test_example_case():
words = ["bat", "tab", "cat"]
assert palindrome_pairs(words) == [[0, 1], [1, 0]]
def test_no_pairs():
words = ["abc", "def", "ghi"]
assert palindrome_pairs(words) == []
def test_single_letter_words():
words = ["a", "b", "c"]
asser... | [
{
"docstring": "Checks if a given word is a palindrome.",
"function_declaration": "def is_palindrome(word):",
"function_name": "is_palindrome",
"parameter_list": "(word)"
},
{
"docstring": "Finds all pairs of indices (i, j) such that the concatenation of words[i] and words[j] is a palindrome... | [
1,
1,
0,
1,
0,
0,
0,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def find_palindrome_pairs(words):\n \"\"\"\n Returns list of pairs of indices (i, j) such that the concatenation of words[i] and words[j] is a palindrome.\n \"\"\"\n... | trial_gpt4o_9 | {
"original_instruction": "Given a list of words, create a function to find all the pairs of indices (i, j) such that the concatenation of words[i] and words[j] is a palindrome. A palindrome is a word that reads the same backward as forward. Return the list of pairs sorted in lexicographical order according to the pa... | 0.718162 | Leetcode_25081 | C | [
"is_palindrome",
"palindrome_pairs"
] | 2 | [
[
"palindrome_pairs",
"is_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 66c55c0d5d13f789a3c387a759d5d6818d11490f | 545a3d1578c1543236ca014f6d481b3119088cee | |||
v1.0 | complete | Leetcode | Leetcode_25263_C | import math
def is_perfect_square(n):
"""
Checks if the given number n is a perfect square.
"""
sqrt_n = int(math.sqrt(n))
return sqrt_n * sqrt_n == n
def subarray_has_perfect_square(arr, k):
""" Determine if there exists a subarray of length exactly k
that forms a number which is a perfec... | import math
def is_perfect_square(n):
"""
Checks if the given number n is a perfect square.
"""
sqrt_n = int(math.sqrt(n))
return sqrt_n * sqrt_n == n
def subarray_has_perfect_square(arr, k):
"""
Determines if there exists a subarray of length exactly k
that forms a number which is a p... | from solution import subarray_has_perfect_square
def test_subarray_has_perfect_square_found():
assert subarray_has_perfect_square([1, 4, 1, 5, 9], 1) == True
assert subarray_has_perfect_square([1, 4, 1, 6], 2) == True
assert subarray_has_perfect_square([4, 0, 1, 6, 1, 4], 2) == True
assert subarray_has... | [
{
"docstring": "Checks if the given number n is a perfect square.",
"function_declaration": "def is_perfect_square(n):",
"function_name": "is_perfect_square",
"parameter_list": "(n)"
},
{
"docstring": "Determines if there exists a subarray of length exactly k\nthat forms a number which is a ... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "import math\n\ndef is_perfect_square(x):\n return int(math.sqrt(x)) ** 2 == x\n\ndef find_concatenated_subarray_as_perfect_square(arr, k):\n n = len(arr)\n \n # E... | trial_gpt4o_4 | {
"original_instruction": "You are given a **0-indexed** array of integers `arr` of length `n` and an integer `k`. You need to determine if there exists a **subarray** of length exactly `k` that is a **perfect square** when considered as a whole number formed by concatenating its elements. A number is considered a pe... | 0.6781 | Leetcode_25263 | C | [
"is_perfect_square",
"subarray_has_perfect_square"
] | 2 | [
[
"subarray_has_perfect_square",
"is_perfect_square"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c14b9d2e980147df570a84a1ce0590c2b2ced967 | 2af8f178abc019a69dadf9f01f2f13e5af7b4b66 | |||
v1.0 | complete | Leetcode | Leetcode_25309_C | def minimize_max_sum(arr: List[int], k: int, x: int) -> int:
""" Divide the list into x contiguous subarrays such that the maximum sum
of the subarrays is minimized. Each subarray must contain between
k and (n - k*x + k) elements.
>>> minimize_max_sum([7, 2, 5, 10, 8], 1, 2)
18
>>> min... | def is_valid_division(arr, k, x, max_sum):
current_sum = 0
count_subarrays = 1
for num in arr:
if current_sum + num > max_sum:
count_subarrays += 1
current_sum = num
if count_subarrays > x:
return False
else:
current_sum += num
... | from solution import minimize_max_sum
def test_minimize_max_sum():
assert minimize_max_sum([7, 2, 5, 10, 8], 1, 2) == 18
assert minimize_max_sum([1, 2, 3, 4, 5], 1, 2) == 9
assert minimize_max_sum([1, 2, 3, 4, 5], 1, 3) == 6
assert minimize_max_sum([1, 4, 4], 1, 3) == 4
def test_minimize_max_sum_edge_... | [
{
"docstring": null,
"function_declaration": "def is_valid_division(arr, k, x, max_sum):",
"function_name": "is_valid_division",
"parameter_list": "(arr, k, x, max_sum)"
},
{
"docstring": null,
"function_declaration": "def minimize_max_sum(arr, k, x):",
"function_name": "minimize_max... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def minimize_max_subarray_sum(arr, k, x):\n def valid(mid):\n count = 0\n current_sum = 0\n for num in arr:\n if current_sum + num > mid:\n... | trial_gpt4o_5 | {
"original_instruction": "Given a list of integers `arr`, an integer `k`, and a positive integer `x`, divide the list into `x` contiguous subarrays such that the maximum sum of the subarrays is minimized. Each contiguous subarray must contain between `k` and `(n - k*x + k)` elements, where `n` is the length of `arr`... | 0.710907 | Leetcode_25309 | C | [
"is_valid_division",
"minimize_max_sum"
] | 2 | [
[
"minimize_max_sum",
"is_valid_division"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 24a74e9b8a8e049cdde1235fe5de3580ca5b2848 | 7fba30f976587fbd783b2914afd32e6ce22b6c95 | |||
v1.0 | complete | Leetcode | Leetcode_25364_C | from typing import List
def can_form_by_deleting(text: str, word: str) -> bool:
"""
Check if `word` can be formed by deleting some characters of `text` without reordering.
"""
def check_words_by_deleting(text: str, queries: List[str]) -> List[bool]:
"""
Check for each word in `queries` if it can b... | def can_form_by_deleting(text, word):
"""
Check if `word` can be formed by deleting some characters of `text` without reordering.
"""
it = iter(text)
return all(char in it for char in word)
def check_words_by_deleting(text, queries):
"""
Check for each word in `queries` if it can be formed ... | from solution import check_words_by_deleting
def test_check_words_by_deleting():
text = "abpcplea"
queries = ["apple", "monkey", "plea", "ale"]
expected = [True, False, True, True]
assert check_words_by_deleting(text, queries) == expected
def test_check_words_by_deleting_empty_queries():
text = "a... | [
{
"docstring": "Check if `word` can be formed by deleting some characters of `text` without reordering.",
"function_declaration": "def can_form_by_deleting(text, word):",
"function_name": "can_form_by_deleting",
"parameter_list": "(text, word)"
},
{
"docstring": "Check for each word in `quer... | [
1,
1,
0,
0,
0,
0,
1,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def can_form_by_deleting(text, queries):\n \"\"\"\n Given a string `text` and a list of words `queries`, check for each word \n in `queries` if it can be formed by d... | trial_gpt4o_6 | {
"original_instruction": "Given a string `text` and an array of words `queries`, check for each word in `queries` if it can be formed by deleting some characters of the string `text` without reordering the remaining characters. Return an array of boolean values indicating the results for each word in `queries`.",
... | 0.645697 | Leetcode_25364 | C | [
"can_form_by_deleting",
"check_words_by_deleting"
] | 2 | [
[
"check_words_by_deleting",
"can_form_by_deleting"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 33efa654461a6824154ce385a98cf927d7887a03 | d80077e3ee2e7dcd8ac4eecefc6506a653014a29 | |||
v1.0 | complete | Leetcode | Leetcode_25450_C | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def build_tree(edges):
""" Builds a binary tree from edges where each edges[i] contains [u, v, d]. """
def has_path_sum(root, k):
""" Checks if there is a path from root to any leaf with the sum ... | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def build_tree(edges):
if not edges:
return None
tree_nodes = {}
for u, v, d in edges:
if u not in tree_nodes:
tree_nodes[u] = TreeNode(u)
if v not in ... | from solution import is_path_sum
def test_is_path_sum_no_edges_tree():
assert is_path_sum([], 1) == False
def test_is_path_sum_single_path_tree():
edges = [[1, 2, 0], [2, 3, 0], [3, 4, 0]]
target_sum = 10 # 1 + 2 + 3 + 4 = 10
assert is_path_sum(edges, target_sum) == True
def test_is_path_sum_multiple... | [] | [
0,
1,
1,
0,
0,
0,
0,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, value=0, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\ndef build_tree(e... | trial_gpt4o_2 | {
"original_instruction": "You are given a binary tree with `n` nodes, where each node has a unique value from `1` to `n`. The root of the tree is always `1`. Each node has at most two children. You are also given a 2D list `edges` where each `edges[i]` contains `[u, v, d]` denoting that there is an edge between node... | 0.639341 | Leetcode_25450 | C | [
"build_tree",
"has_path_sum",
"is_path_sum"
] | 3 | [
[
"is_path_sum",
"build_tree"
],
[
"is_path_sum",
"has_path_sum"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | e6428ae132a655fbaeef4d0cf201acbdd2ff2ddd | 171b8543766f375fae4a62d40457dd80fcb85293 | |||
v1.0 | complete | Leetcode | Leetcode_25498_C | def is_palindromic_number(x: int) -> bool:
""" Helper function to check if a number is palindromic.
>>> is_palindromic_number(121) True
>>> is_palindromic_number(123) False
"""
def palindromic_numbers(n: int) -> list:
""" Returns a list of all palindromic numbers less than or equal to n.
>>... | def is_palindromic_number(x):
"""
Helper function to check if a number is palindromic.
"""
return str(x) == str(x)[::-1]
def palindromic_numbers(n):
"""
Returns a list of all palindromic numbers less than or equal to n.
"""
return [i for i in range(n + 1) if is_palindromic_number(i)] | from solution import is_palindromic_number, palindromic_numbers
def test_is_palindromic_number():
assert is_palindromic_number(121) == True
assert is_palindromic_number(123) == False
assert is_palindromic_number(0) == True # Single-digit numbers are palindromic
def test_palindromic_numbers_small_range():... | [
{
"docstring": "Helper function to check if a number is palindromic.",
"function_declaration": "def is_palindromic_number(x):",
"function_name": "is_palindromic_number",
"parameter_list": "(x)"
},
{
"docstring": "Returns a list of all palindromic numbers less than or equal to n.",
"funct... | [
0,
0,
1,
1,
1,
1,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def get_palindromic_numbers(n):\n \"\"\"\n Returns a list of palindromic numbers less than or equal to n.\n \n :param n: int - Upper limit for palindromic numbers... | trial_gpt4o_9 | {
"original_instruction": "A **palindromic number** is a number that remains the same when its digits are reversed. For example, `121` is palindromic, whereas `123` is not. Given an integer `n`, return _a list of all palindromic numbers less than or equal to `n`._ Can you optimize your solution to handle large values... | 0.753272 | Leetcode_25498 | C | [
"is_palindromic_number",
"palindromic_numbers"
] | 2 | [
[
"palindromic_numbers",
"is_palindromic_number"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3e1780093925b349ca1e74c7482169b3112cb26f | 07800c03500cec62563b0bf3983e918d213518eb | |||
v1.0 | complete | Leetcode | Leetcode_25571_C | from typing import List
def smallest_equivalent_uuids(uuids: List[str], relations: List[List[str]]) -> List[str]:
""" Given an array of UUIDs and a set of relations indicating which UUIDs are equivalent,
return the UUIDs array with each element replaced by its smallest equivalent UUID (lexicographically).
... | def find_parent(parent, u):
if parent[u] != u:
parent[u] = find_parent(parent, parent[u])
return parent[u]
def union(parent, rank, u, v):
root_u = find_parent(parent, u)
root_v = find_parent(parent, v)
if root_u != root_v:
if rank[root_u] > rank[root_v]:
parent[root_v] =... | from solution import smallest_equivalent_uuids
def test_example_case():
uuids = ["uuid1", "uuid2", "uuid3", "uuid4"]
relations = [["uuid1", "uuid2"], ["uuid3", "uuid4"], ["uuid2", "uuid3"]]
assert smallest_equivalent_uuids(uuids, relations) == ["uuid1", "uuid1", "uuid1", "uuid1"]
def test_no_relations():
... | [
{
"docstring": null,
"function_declaration": "def find_parent(parent, u):",
"function_name": "find_parent",
"parameter_list": "(parent, u)"
},
{
"docstring": null,
"function_declaration": "def union(parent, rank, u, v):",
"function_name": "union",
"parameter_list": "(parent, rank... | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def find(x, parent):\n if parent[x] != x:\n parent[x] = find(parent[x], parent)\n return parent[x]\n\ndef union(x, y, parent, rank):\n root_x = find(x, parent... | trial_gpt4o_6 | {
"original_instruction": "You are given an array of `UUIDs` represented as strings and a set of relations between different UUIDs. Each relation indicates that two UUIDs are considered equivalent (the same entity). Write a function that, given the list of relations and the UUIDs array, returns the UUIDs array with e... | 0.562019 | Leetcode_25571 | C | [
"find_parent",
"union",
"smallest_equivalent_uuids"
] | 3 | [
[
"smallest_equivalent_uuids",
"find_parent"
],
[
"smallest_equivalent_uuids",
"union"
],
[
"union",
"find_parent"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | e8feff3b5a0c0383bcdcebd14cb879d966377a50 | 08ce30f6f8ba6b5426a8f3dcdb8f7c567d3593ae | |||
v1.0 | complete | Leetcode | Leetcode_25697_C | def is_peak(grid, i, j):
"""
Check if the cell (i, j) is a peak considering all valid neighbors.
"""
def count_peaks(grid):
"""
Count the number of peaks in the given 2D grid.
>>> count_peaks([
[1, 2, 1],
[2, 3, 2],
[1, 2, 1]
]) == 1
>>> count_peaks([
[1,... | def is_peak(grid, i, j):
"""
Check if the cell (i, j) is a peak considering all valid neighbors.
"""
directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
for di, dj in directions:
ni, nj = i + di, j + dj
if 0 <= ni < len(grid) and 0 <= nj < len(grid[0])... | from solution import count_peaks
def test_count_peaks_basic():
grid = [
[1, 2, 1],
[2, 3, 2],
[1, 2, 1]
]
assert count_peaks(grid) == 1
def test_count_peaks_all_same():
grid = [
[1, 1, 1],
[1, 1, 1],
[1, 1, 1]
]
assert count_peaks(grid) == 9
def... | [
{
"docstring": "Check if the cell (i, j) is a peak considering all valid neighbors.",
"function_declaration": "def is_peak(grid, i, j):",
"function_name": "is_peak",
"parameter_list": "(grid, i, j)"
},
{
"docstring": "Count the number of peaks in the given 2D grid.",
"function_declaratio... | [
0,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def count_peaks(grid):\n \"\"\"\n Returns the number of peaks in the grid.\n \n A square is considered a \"peak\" if and only if it is greater than or equal to an... | trial_gpt4o_1 | {
"original_instruction": "You are given a 2D integer grid `grid` where each cell in the grid represents a **height above sea level**. A square is considered a **\"peak\"** if and only if it is **greater** than or **equal** to any of its 8 neighboring squares (or all the neighbors that exist, for edge and corner cell... | 0.659296 | Leetcode_25697 | C | [
"is_peak",
"count_peaks"
] | 2 | [
[
"count_peaks",
"is_peak"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 56153f17ec5f8a25808da5700469d3a4257da5f9 | b4fcf05f88b8b4411d4cdcb26de42e31907de334 | |||
v1.0 | complete | Leetcode | Leetcode_26341_C | def can_partition(arr: List[int], k: int) -> bool:
""" You are given an array of integers `arr` and an integer `k`.
You need to partition the array into exactly `k` subsets such that the sum of elements in each subset is unique.
Return `True` if such a partition exists, otherwise return `False`.
... | from itertools import combinations
def subsets_with_sum(arr, k, target_sum, used):
"""
Helper function to check if there exists a subset of `arr` (excluding used elements)
that sums up to target_sum.
"""
for i in range(len(arr)):
if not used[i] and arr[i] <= target_sum:
used[i] ... | from solution import can_partition
def test_can_partition_with_valid_partition():
arr = [4, 3, 2, 3, 5, 2, 1]
k = 4
assert can_partition(arr, k) == True
def test_can_partition_with_no_valid_partition():
arr = [1, 2, 3, 4]
k = 3
assert can_partition(arr, k) == False
def test_can_partition_all_... | [
{
"docstring": "Helper function to check if there exists a subset of `arr` (excluding used elements)\nthat sums up to target_sum.",
"function_declaration": "def subsets_with_sum(arr, k, target_sum, used):",
"function_name": "subsets_with_sum",
"parameter_list": "(arr, k, target_sum, used)"
},
{
... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from itertools import combinations\n\ndef can_partition_into_unique_subsets(arr, k):\n \"\"\"\n Check if the array can be partitioned into exactly k subsets such that t... | trial_gpt4o_4 | {
"original_instruction": "You are given an array of integers `arr` and an integer `k`. You need to partition the array into exactly `k` subsets such that the sum of elements in each subset is unique. Return `True` if such a partition exists, otherwise return `False`.",
"prompt_id": "0000026341",
"row_id": 26341,... | 0.632575 | Leetcode_26341 | C | [
"subsets_with_sum",
"can_partition"
] | 2 | [
[
"can_partition",
"subsets_with_sum"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3c661f7e2a1fa6f91a0436aa75d2743892bb129a | 0573562d154808e4d4a85b8226025e4a8b9dfd4d | |||
v1.0 | complete | Leetcode | Leetcode_26490_C | def can_form(word, words_set, memo):
""" Helper function to check if a word can be formed by concatenating other words.
"""
pass
def longest_concatenated_word(words):
""" Write a function that takes an array of strings `words`, and returns the longest word in `words` that can be constructed by concaten... | def can_form(word, words_set, memo):
if word in memo:
return memo[word]
for i in range(1, len(word)):
prefix = word[:i]
suffix = word[i:]
if prefix in words_set and (suffix in words_set or can_form(suffix, words_set, memo)):
memo[word] = True
return True
... | from solution import longest_concatenated_word
def test_example_1():
assert longest_concatenated_word(["cat", "dog", "catdog"]) == "catdog"
def test_example_2():
assert longest_concatenated_word(["cat", "dog", "catdog", "catdogcat"]) == "catdogcat"
def test_no_concatenated_word():
assert longest_concaten... | [
{
"docstring": null,
"function_declaration": "def can_form(word, words_set, memo):",
"function_name": "can_form",
"parameter_list": "(word, words_set, memo)"
},
{
"docstring": null,
"function_declaration": "def longest_concatenated_word(words):",
"function_name": "longest_concatenate... | [
0,
0,
0,
1,
1,
0,
0,
1,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def find_longest_concatenated_word(words):\n words_set = set(words)\n memo = {}\n\n def can_form(word):\n if word in memo:\n return memo[word]\n ... | trial_gpt4o_4 | {
"original_instruction": "Write a function that takes an array of strings `words`, and returns the longest word in `words` that can be constructed by concatenating other words from the array. If there is a tie for the longest word, return the word that came first in the original array. If no such word exists, return... | 0.69731 | Leetcode_26490 | C | [
"can_form",
"longest_concatenated_word"
] | 2 | [
[
"longest_concatenated_word",
"can_form"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | cbef37ede2542ad9a2a689441e305a367be9460c | b691e095a177eaaa09467f1a09daeeef89f8ec4b | |||
v1.0 | complete | Leetcode | Leetcode_26491_C | import math
import itertools
from typing import List
def is_prime(n: int) -> bool:
""" Helper function to check if a number is prime.
>>> is_prime(2)
True
>>> is_prime(3)
True
>>> is_prime(4)
False
>>> is_prime(17)
True
>>> is_prime(18)
False
"""
pass
def has_prime_... | import itertools
import math
def is_prime(n):
"""
Helper function to check if a number is prime.
"""
if n <= 1:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
def has_prime_pair(arr):
"""
Determine if there exi... | from solution import has_prime_pair, is_prime
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(17) == True
assert is_prime(18) == False
def test_has_prime_pair_exists():
assert has_prime_pair([1, 4, 6, 7]) == True # (1, 6) ... | [
{
"docstring": "Helper function to check if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Determine if there exists a pair of indices (i, j) such that\narr[i] + arr[j] is a prime number.",
"functio... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "from sympy import isprime\n\ndef has_prime_pair(arr):\n \"\"\"\n Determines if there exists a pair of distinct indices (i, j) such that arr[i] + arr[j] is a prime numbe... | trial_gpt4o_4 | {
"original_instruction": "Given a list of distinct integers `arr`, determine whether there exists a pair of indices `(i, j)` such that `arr[i]` + `arr[j]` is a prime number. Return `true` if such a pair exists, and `false` otherwise.",
"prompt_id": "0000026491",
"row_id": 26491,
"seed_ids": "['724', '216', '22... | 0.741282 | Leetcode_26491 | C | [
"is_prime",
"has_prime_pair"
] | 2 | [
[
"has_prime_pair",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1333f60c45973ddbb632aac282507a0e313889d0 | 20bca9dda3ee18230394a4d3b7c4f5f4619cd8b2 | |||
v1.0 | complete | Leetcode | Leetcode_26790_C | def minimizeMaxWorkload(tasks: List[int], k: int) -> int:
"""
Returns the minimum possible value of the maximum workload of any worker after all tasks have been assigned.
>>> minimizeMaxWorkload([10, 20, 30, 40], 2)
60
>>> minimizeMaxWorkload([1, 2, 3, 4, 5], 2)
9
>>> minimizeMaxWorkload([1... | def canDistributeWithinMax(tasks, k, maxWorkload):
"""
Helper function to determine if it's possible to distribute all tasks among k workers
without any worker exceeding the specified max workload.
"""
currentSum = 0
requiredWorkers = 1
for task in tasks:
if currentSum + task > ... | def test_minimize_max_workload_example1():
tasks = [10, 20, 30, 40]
k = 2
assert minimizeMaxWorkload(tasks, k) == 60
def test_minimize_max_workload_example2():
tasks = [1, 2, 3, 4, 5]
k = 2
assert minimizeMaxWorkload(tasks, k) == 9
def test_minimize_max_workload_example3():
tasks = [10, 20... | [
{
"docstring": "Helper function to determine if it's possible to distribute all tasks among k workers\nwithout any worker exceeding the specified max workload.",
"function_declaration": "def canDistributeWithinMax(tasks, k, maxWorkload):",
"function_name": "canDistributeWithinMax",
"parameter_list":... | [
0,
0,
1,
1,
0,
0,
0,
1,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def canCompleteInTime(mid, tasks, k):\n workers = 1\n current_load = 0\n\n for task in tasks:\n if current_load + task <= mid:\n current_load += ta... | trial_gpt4o_7 | {
"original_instruction": "You are provided with an array `tasks` where each element represents the time required to complete a task. There are `k` identical workers available, and each worker can only work on one task at a time. Your goal is to assign the tasks to the workers such that the maximum amount of time any... | 0.662507 | Leetcode_26790 | C | [
"canDistributeWithinMax",
"minimizeMaxWorkload"
] | 2 | [
[
"minimizeMaxWorkload",
"canDistributeWithinMax"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | c5e711bea125d8044b9ba9ed4421666544dd0e1b | 10d775de152ffa133b87a962f3c3121c4336a068 | |||
v1.0 | complete | Leetcode | Leetcode_26828_C | def make_shortest_palindrome(s: str) -> int:
"""
Given a string `s`, return the length of the shortest palindrome you can create by appending characters to the end of the string.
A palindrome is defined as a string that reads the same forwards and backwards.
>>> make_shortest_palindrome("")
0
... | def shortest_palindrome_length(s):
"""
Returns the length of the shortest palindrome that can be created by appending characters to the end of the string.
"""
# Find the longest palindromic prefix
n = len(s)
rev_s = s[::-1]
for i in range(n):
if s.startswith(rev_s[i:]):
... | from solution import make_shortest_palindrome
def test_shortest_palindrome_empty():
assert make_shortest_palindrome("") == 0
def test_shortest_palindrome_single_char():
assert make_shortest_palindrome("a") == 1
def test_shortest_palindrome_no_append():
assert make_shortest_palindrome("racecar") == 7
def... | [
{
"docstring": "Returns the length of the shortest palindrome that can be created by appending characters to the end of the string.",
"function_declaration": "def shortest_palindrome_length(s):",
"function_name": "shortest_palindrome_length",
"parameter_list": "(s)"
},
{
"docstring": "Return... | [
0,
1,
0,
0,
0,
1,
0,
1,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def shortest_palindrome_length(s):\n \"\"\"\n Returns the length of the shortest palindrome that can be created by appending characters to the end of the string.\n \... | trial_gpt4o_7 | {
"original_instruction": "Given a string `s`, return _the length of the shortest palindrome you can create by appending characters to the end of the string_. A palindrome is defined as a string that reads the same forwards and backwards.",
"prompt_id": "0000026828",
"row_id": 26828,
"seed_ids": "['2134', '766'... | 0.85158 | Leetcode_26828 | C | [
"shortest_palindrome_length",
"make_shortest_palindrome"
] | 2 | [
[
"make_shortest_palindrome",
"shortest_palindrome_length"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 831205aa8dac4cdfa58360f5198502533b1f97cd | 381fddb84126a5ef0fa3c0d7e9da72c0d4159ab5 | |||
v1.0 | complete | Leetcode | Leetcode_27245_C | def min_adjacent_swaps_to_sort(numbers: List[int]) -> int:
"""
Given an integer array 'numbers', determine the minimum number of adjacent swaps required to
convert the array into a non-decreasing order. An array is in a non-decreasing order if for
every i where 0 <= i < len(numbers) - 1, numbers[i] <=... | def count_inversions(numbers):
"""
Helper function to count inversions using merge sort.
An inversion indicates an out-of-order pair which needs to be swapped to sort the array.
"""
# Merge sort and count inversions
def merge_sort(arr, temp_arr, left, right):
inv_count = 0
if le... | from solution import min_adjacent_swaps_to_sort
def test_sorted_array():
assert min_adjacent_swaps_to_sort([1, 2, 3, 4, 5]) == 0
def test_reverse_sorted_array():
assert min_adjacent_swaps_to_sort([5, 4, 3, 2, 1]) == 10
def test_random_array():
assert min_adjacent_swaps_to_sort([3, 1, 2, 4, 5]) == 2
def ... | [
{
"docstring": "Helper function to count inversions using merge sort. \nAn inversion indicates an out-of-order pair which needs to be swapped to sort the array.",
"function_declaration": "def count_inversions(numbers):",
"function_name": "count_inversions",
"parameter_list": "(numbers)"
},
{
... | [
0,
0,
0,
1,
1,
0,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_50000_combined_sanitized_prepared_0_results_combined.jsonl",
"solution_code": "def min_adjacent_swaps_to_sort(numbers):\n \"\"\"\n Returns the minimum number of adjacent swaps required to sort\n the array in non-decreasing order.\n \"\"\"\n ... | trial_gpt4o_4 | {
"original_instruction": "Given an integer array `numbers`, you need to determine the **minimum** number of adjacent swaps required to convert the array into a **non-decreasing order**. An array is in a non-decreasing order if for every `i` where `0 <= i < numbers.length - 1`, `numbers[i] <= numbers[i + 1]`. Return ... | 0.707372 | Leetcode_27245 | C | [
"count_inversions",
"min_adjacent_swaps_to_sort"
] | 2 | [
[
"min_adjacent_swaps_to_sort",
"count_inversions"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 0f98313f46c5c62a9311d292f8f3a548c587c89a | d2558789d61eccfdc722d034cfa85f44165b738d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.