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 | Codeforces | Codeforces_110_C | def minimize_max_fatigue(n: int, k: int, r: List[int]) -> int:
"""
This function assigns each robot a day such that the maximum fatigue is minimized.
The assignment minimizes |d_i - r_i| for given n robots and k days.
Args:
- n (int): The number of robots.
- k (int): The number of consecuti... | def minimize_max_fatigue(n, k, r):
"""
This function assigns each robot a day such that the maximum fatigue is minimized.
The assignment minimizes |d_i - r_i| for given n robots and k days.
Args:
- n (int): The number of robots.
- k (int): The number of consecutive days.
- r (list): Lis... | from solution import minimize_max_fatigue
def test_simple_case():
assert minimize_max_fatigue(5, 5, [1, 2, 3, 4, 5]) == 0
def test_no_optimal_match():
assert minimize_max_fatigue(3, 3, [1, 1, 3]) == 1
def test_equal_optimal_days():
assert minimize_max_fatigue(3, 3, [2, 2, 2]) == 1
def test_large_case():... | [
{
"docstring": "This function assigns each robot a day such that the maximum fatigue is minimized.\nThe assignment minimizes |d_i - r_i| for given n robots and k days.\n\nArgs:\n- n (int): The number of robots.\n- k (int): The number of consecutive days.\n- r (list): List of integers where r[i] is the optimal d... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def minimize_maximum_fatigue(n, k, r):\n \"\"\"\n Returns minimum possible maximum fatigue experienced by any robot.\n \"\"\"\n \n # Step 1: So... | trial_gpt4o_7 | {
"original_instruction": "Marcus is organizing a robot race event. Each robot participates in a race on a different day. Robot races are held over $$$k$$$ consecutive days. Marcus wants to ensure there's enough charging time for all the robots and minimize the maximum fatigue any robot can experience.\n\nThe fatigue... | 0.625006 | Codeforces_110 | C | [
"minimize_max_fatigue",
"can_assign_days"
] | 2 | [
[
"minimize_max_fatigue",
"can_assign_days"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 5199c7104633b10aa480b74a840092d7b55bb20e | 6975dc06bc6bdbd8ded35e544497751fb0c65b92 | |||
v1.0 | complete | Codeforces | Codeforces_318_C | def solve(grid: List[List[int]]) -> str:
""" Find the shortest path from the top-left corner to the bottom-right corner (only moving right or down) such that the sum of the integers along the path is minimized. Return the minimum sum and the sequence of coordinates of the path.
>>> solve([
... [1, 3... | def min_path_sum(grid):
n = len(grid)
m = len(grid[0])
# Initialize DP table and path tracker
dp = [[float('inf')] * m for _ in range(n)]
dp[0][0] = grid[0][0]
path = [[[] for _ in range(m)] for _ in range(n)]
path[0][0] = [(0, 0)]
for i in range(n):
for j in range(m):
... | from solution import solve
def test_case_1():
grid = [
[1, 3, 1],
[1, 5, 1],
[4, 2, 1]
]
result = solve(grid)
expected = "7\n(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)"
assert result == expected
def test_case_2():
grid = [
[1, 2],
[1, 1]
]
result = s... | [
{
"docstring": null,
"function_declaration": "def min_path_sum(grid):",
"function_name": "min_path_sum",
"parameter_list": "(grid)"
},
{
"docstring": null,
"function_declaration": "def solve(grid):",
"function_name": "solve",
"parameter_list": "(grid)"
}
] | [
0,
0,
0,
1,
0,
1,
0,
0,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def min_path_sum(grid):\n n = len(grid)\n m = len(grid[0])\n \n dp = [[0] * m for _ in range(n)]\n dp[0][0] = grid[0][0]\n \n for i in ra... | trial_gpt4o_5 | {
"original_instruction": "You are given a grid of size $$$n \\times m$$$, filled with non-negative integers. Your task is to find the shortest path from the top-left corner (0, 0) to the bottom-right corner (n-1, m-1) such that the sum of the integers along the path is minimized. You can only move right or down at e... | 0.693727 | Codeforces_318 | C | [
"min_path_sum",
"solve"
] | 2 | [
[
"solve",
"min_path_sum"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | feccf3c2b0bcc17bc55de8886f9f0e7a981db261 | c952f09ecfc7fadedf46708c1d2f5e53a3a6b9c3 | |||
v1.0 | complete | Codeforces | Codeforces_420_C | from typing import List
def is_harmonious_sequence(sequence: List[int]) -> bool:
"""
Determines if the sequence can become harmonious by repeatedly replacing
each element with the sum of its digits.
>>> is_harmonious_sequence([123, 456, 789])
True
>>> is_harmonious_sequence([555])
True
... | from typing import List
def sum_of_digits(n: int) -> int:
"""
Calculates the sum of the digits of an integer n.
"""
return sum(int(digit) for digit in str(n))
def all_elements_equal(lst: List[int]) -> bool:
"""
Checks if all elements in the list are equal.
"""
return all(x == lst[0] fo... | from solution import is_harmonious_sequence
def test_harmonious_sequence_example():
sequence = [123, 456, 789]
assert is_harmonious_sequence(sequence) == True
def test_single_element_sequence():
sequence = [555]
assert is_harmonious_sequence(sequence) == True
def test_unequal_initially_becomes_equal(... | [
{
"docstring": "Calculates the sum of the digits of an integer n.",
"function_declaration": "def sum_of_digits(n):",
"function_name": "sum_of_digits",
"parameter_list": "(n)"
},
{
"docstring": "Checks if all elements in the list are equal.",
"function_declaration": "def all_elements_equa... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef sum_of_digits(n: int) -> int:\n return sum(int(digit) for digit in str(n))\n\ndef is_harmonious_sequence(sequence: List[int]... | trial_gpt4o_4 | {
"original_instruction": "You are given a sequence of integers, and you are tasked with creating a new sequence where each element is derived from the sum of the digits of the corresponding element in the original sequence. The goal is to determine if the resulting sequence eventually reaches a point where all eleme... | 0.565987 | Codeforces_420 | C | [
"sum_of_digits",
"all_elements_equal",
"is_harmonious_sequence"
] | 3 | [
[
"is_harmonious_sequence",
"all_elements_equal"
],
[
"is_harmonious_sequence",
"sum_of_digits"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | daac0625e2521f5120aaa504f411f0ff8ca0a915 | da9e83c0e9018b6467b7136601e8505869f53859 | |||
v1.0 | complete | Codeforces | Codeforces_531_C | from collections import defaultdict, deque
def find_order_of_alphabet(species_names: List[str]) -> str:
"""
Determine a valid permutation of the alphabet letters such that the given species names
are sorted in lexicographical order based on this permutation. If such an order does not
exist, return "Imp... | from collections import defaultdict, deque
def find_order_of_alphabet(species_names):
"""
Determine a valid permutation of the alphabet letters such that the given species names
are sorted in lexicographical order based on this permutation. If such an order does not
exist, return "Impossible".
"""
... | from solution import solve
def test_possible_order():
input_text = """4
bunny
bear
banana
cat"""
output = solve(input_text)
assert output != "Impossible"
def test_no_possible_order():
input_text = """3
abc
ab"""
output = solve(input_text)
assert output == "Impossible"
def test_single_species_... | [
{
"docstring": "Determine a valid permutation of the alphabet letters such that the given species names\nare sorted in lexicographical order based on this permutation. If such an order does not\nexist, return \"Impossible\".",
"function_declaration": "def find_order_of_alphabet(species_names):",
"functi... | [
0,
0,
0,
1,
0,
0,
0,
0,
1
] | 2 | hard | 0.222 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque, defaultdict\n\ndef find_order(words):\n \"\"\"\n Determines a valid custom order of the alphabet given a list of words so... | trial_gpt4o_3 | {
"original_instruction": "ZooKeeper at the Wonderland Zoo is tasked with organizing the feeding schedule for different animals. The zoo has different species of animals, and each species has a name that must be sorted in a specific lexicographical order. However, some species names can conflict with the traditional ... | 0.615 | Codeforces_531 | C | [
"find_order_of_alphabet",
"solve"
] | 2 | [
[
"solve",
"find_order_of_alphabet"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7f0bfc50506d7c4ca4017755632389b37b64d48c | 5069d352d3c34d18c508fc31103ef0292dd370a6 | |||
v1.0 | complete | Codeforces | Codeforces_170_C | def find_treasure_path(n: int, corridors: List[Tuple[int, int]]) -> Union[int, Tuple[int, List[int]]]:
"""
A treasure hunter is exploring a haunted mansion where each room is connected by corridors.
The mansion consists of `n` rooms, and each pair of rooms is connected by a corridor that
can either b... | from collections import deque
def bfs_minimum_corridors(n, adj_list):
"""
Apply BFS to find the minimum path from room 1 to room n.
"""
# This will store the minimum number of corridors from room 1 to room i.
distances = [-1] * (n + 1)
distances[1] = 0
# This will store the path to ... | from solution import find_treasure_path
def test_no_corridors():
assert find_treasure_path(3, []) == -1
def test_simple_case():
n = 6
corridors = [(1, 2), (2, 3), (3, 6)]
assert find_treasure_path(n, corridors) == (3, [1, 2, 3, 6])
def test_more_complex_case():
n = 6
corridors = [(1, 2), (1, ... | [
{
"docstring": "Apply BFS to find the minimum path from room 1 to room n.",
"function_declaration": "def bfs_minimum_corridors(n, adj_list):",
"function_name": "bfs_minimum_corridors",
"parameter_list": "(n, adj_list)"
},
{
"docstring": "Find the shortest path from room 1 to room n in the ha... | [
0,
1,
0,
1,
0,
1,
1,
0,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque, defaultdict\n\ndef find_treasure_path(n, m, corridors):\n if n == 2 and not corridors:\n print(\"-1\")\n retur... | trial_gpt4o_8 | {
"original_instruction": "A treasure hunter is exploring a haunted mansion where each room is connected by corridors. The mansion consists of $$$n$$$ rooms, and each pair of rooms is connected by a corridor that can either be open or closed. The entrance to the mansion is at room $$$1$$$, and the treasure is located... | 0.698001 | Codeforces_170 | C | [
"bfs_minimum_corridors",
"find_treasure_path"
] | 2 | [
[
"find_treasure_path",
"bfs_minimum_corridors"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | c0dc9e2b5b8019f77839a04bd1570a4d45d5df01 | f92556f152cdba408accf89dc26f8d23e71358f3 | |||
v1.0 | complete | Codeforces | Codeforces_619_C | def connected_queries(n: int, edges: List[Tuple[int, int]], queries: List[Tuple[int, int]]) -> List[str]:
""" Determine if two friends can be connected through a series of tag requests.
Parameters:
- n: the number of friends
- edges: list of tuples representing directed tag requests
- queries: list ... | def find_connected_components(n, edges):
from collections import defaultdict, deque
graph = defaultdict(list)
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
visited = [-1] * (n + 1)
component_id = 0
def bfs(start):
queue = deque([start])
v... | def test_connected_queries():
n = 5
edges = [
(1, 2),
(2, 3),
(3, 4),
(4, 5)
]
queries = [
(1, 5),
(2, 4),
(1, 3)
]
expected_output = ["YES", "YES", "YES"]
assert connected_queries(n, edges, queries) == expected_output
def test_disconn... | [
{
"docstring": null,
"function_declaration": "def find_connected_components(n, edges):",
"function_name": "find_connected_components",
"parameter_list": "(n, edges)"
},
{
"docstring": null,
"function_declaration": "def connected_queries(n, edges, queries):",
"function_name": "connect... | [
0,
1,
1,
1,
1,
1,
1,
1,
0
] | 7 | easy | 0.778 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import defaultdict, deque\n\ndef solve_connectedness(n, m, connections, q, queries):\n def bfs(start, graph, reached):\n queue = de... | trial_gpt4o_7 | {
"original_instruction": "Konatsu is designing a new social media app that allows users to tag their friends in posts.\n\nEvery post can have multiple friends tagged, and tagging can only be done if the friend accepts the tag request.\n\nThe tagging system can be represented as a directed graph where each vertex rep... | 0.560753 | Codeforces_619 | C | [
"find_connected_components",
"connected_queries"
] | 2 | [
[
"connected_queries",
"find_connected_components"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 36aac16a379e174cb61f04145a990fde2e9f288f | dd8ef0a655d81a6559cb2fb8dd0a1c0a15451100 | |||
v1.0 | complete | Codeforces | Codeforces_585_C | from typing import List, Tuple
def parse_time(time: str) -> int:
"""Converts time from HH:MM format to minutes since the start of the day."""
pass
def parse_event(event: str) -> Tuple[int, int]:
"""Parses an event string in the format 'HH:MM-HH:MM' to a tuple of start and end time in minutes."""
pass
... | from typing import List, Tuple
def parse_time(time: str) -> int:
"""Converts time from HH:MM format to minutes since the start of the day."""
hours, minutes = map(int, time.split(':'))
return hours * 60 + minutes
def parse_event(event: str) -> Tuple[int, int]:
"""Parses an event string in the format '... | from solution import max_events
def test_max_events_example():
assert max_events(["09:00-10:30", "10:15-11:30", "11:00-12:00"]) == 2
def test_max_events_no_overlap():
assert max_events(["09:00-10:00", "10:00-11:00", "11:00-12:00"]) == 3
def test_max_events_all_overlap():
assert max_events(["09:00-11:00",... | [
{
"docstring": "Converts time from HH:MM format to minutes since the start of the day.",
"function_declaration": "def parse_time(time):",
"function_name": "parse_time",
"parameter_list": "(time)"
},
{
"docstring": "Parses an event string in the format 'HH:MM-HH:MM' to a tuple of start and en... | [
0,
0,
0,
1,
0,
1,
1,
1,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def to_minutes(time_str):\n hours, minutes = map(int, time_str.split(':'))\n return hours * 60 + minutes\n\ndef can_attend_all(events):\n events.sort... | trial_gpt4o_7 | {
"original_instruction": "You are given a series of events in a calendar, where each event is represented by a start time and an end time. The times are given in 24-hour format (e.g., 13:00 for 1 PM). Your task is to find the maximum number of events you can attend if you can only attend one event at a time. Two eve... | 0.552336 | Codeforces_585 | C | [
"parse_time",
"parse_event",
"max_events"
] | 3 | [
[
"max_events",
"parse_event"
],
[
"parse_event",
"parse_time"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | ba794c4a0450b1cb18ce53e92edea964af751764 | e0990e5d65914ab8f811550a4c587bac1febc551 | |||
v1.0 | complete | Codeforces | Codeforces_460_C | from typing import List
def largest_concatenated_number(arr: List[int]) -> str:
"""
Takes a list of non-negative integers and returns the largest integer
that can be formed by concatenating their string representations.
>>> largest_concatenated_number([3, 30, 34, 5, 9])
'9534330'
>>> larg... | from functools import cmp_to_key
def compare(x, y):
"""
Custom comparator function to determine the order of two strings
x and y by comparing their concatenated results in both possible orders.
"""
if x + y > y + x:
return -1
elif x + y < y + x:
return 1
else:
retur... | from solution import largest_concatenated_number
def test_example():
assert largest_concatenated_number([3, 30, 34, 5, 9]) == '9534330'
def test_single_element():
assert largest_concatenated_number([1]) == '1'
def test_multiple_zeros():
assert largest_concatenated_number([0, 0, 0]) == '0'
def test_l... | [
{
"docstring": "Custom comparator function to determine the order of two strings \nx and y by comparing their concatenated results in both possible orders.",
"function_declaration": "def compare(x, y):",
"function_name": "compare",
"parameter_list": "(x, y)"
},
{
"docstring": "Takes a list o... | [
0,
0,
0,
1,
0,
0,
0,
1,
1,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from functools import cmp_to_key\n\ndef largest_concatenated_number(nums):\n \"\"\"\n Returns the largest concatenated number that can be formed by the ... | trial_gpt4o_9 | {
"original_instruction": "You are given a list of integers, and you want to form the maximum possible number by concatenating them. Write a function that takes a list of non-negative integers and returns the largest integer that can be formed by concatenating their string representations. The input integers can rang... | 0.689103 | Codeforces_460 | C | [
"compare",
"largest_concatenated_number"
] | 2 | [
[
"largest_concatenated_number",
"compare"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 696ff6d0b7c3389a2222bee347d90a56bd259828 | 3b22a29d9439d8abdc82a0e4254fd3fdd258f60b | |||
v1.0 | complete | Codeforces | Codeforces_669_C | def preprocess_sum(arr):
"""
Preprocesses the input array to create a prefix sum array.
This helps in computing range sums efficiently.
Args:
arr (list of int): The input list of integers.
Returns:
list of int: The prefix sum array.
"""
def range_sum(prefix_sums, l, r):
"""
... | def preprocess_sum(arr):
"""
Preprocesses the input array to create a prefix sum array.
This helps in computing range sums efficiently.
Args:
arr (list of int): The input list of integers.
Returns:
list of int: The prefix sum array.
"""
prefix_sums = [0] * (len(arr) + 1)
fo... | from solution import preprocess_sum, range_sum, process_queries
def test_preprocess_sum():
arr = [1, 2, 3, 4, 5]
expected_prefix_sums = [0, 1, 3, 6, 10, 15]
assert preprocess_sum(arr) == expected_prefix_sums
def test_range_sum():
prefix_sums = [0, 1, 3, 6, 10, 15]
assert range_sum(prefix_sums, 1, ... | [
{
"docstring": "Preprocesses the input array to create a prefix sum array.\nThis helps in computing range sums efficiently.\n\nArgs:\narr (list of int): The input list of integers.\n\nReturns:\nlist of int: The prefix sum array.",
"function_declaration": "def preprocess_sum(arr):",
"function_name": "pre... | [
0,
1,
1,
1,
1,
1,
1,
1,
1
] | 8 | easy | 0.889 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def preprocess_prefix_sums(arr):\n \"\"\"\n Preprocess the input array to compute prefix sums.\n \n Args:\n arr (list): The list of integers.\n... | trial_gpt4o_9 | {
"original_instruction": "Given a list of integer intervals, you are required to write a program that can efficiently answer multiple range sum queries performed on this list. \n\nThe program will receive an initial list of n integers and q queries. Each query will specify a range (l, r) and your task is to compute ... | 0.67452 | Codeforces_669 | C | [
"preprocess_sum",
"range_sum",
"process_queries"
] | 3 | [
[
"process_queries",
"preprocess_sum"
],
[
"process_queries",
"range_sum"
]
] | 2 | [
"process_queries"
] | false | [] | false | pytest | true | [] | true | dfe5c7c82bf5ac7b05ac02bbbf13728fa8e4a6fc | b77743ce3931750cbe6e2745ca217fb670ceaf29 | |||
v1.0 | complete | Codeforces | Codeforces_908_C | def count_matching_words(dictionary: List[str], fragment: str) -> int:
"""
Counts how many words from the dictionary can match the fragmented sequence by replacing underscores.
>>> count_matching_words(["alpha", "beta", "gamma"], "a__ha") == 1
>>> count_matching_words(["alpha", "beta", "gamma"], "____a"... | def count_matching_words(dictionary, fragment):
"""
Counts how many words from the dictionary can match the fragmented sequence by replacing underscores.
"""
def matches(word, fragment):
if len(word) != len(fragment):
return False
for w_char, f_char in zip(word, fragment):
... | def test_single_word_match():
dictionary = ["alpha", "beta", "gamma"]
fragment = "a__ha"
result = count_matching_words(dictionary, fragment)
assert result == 1
def test_multiple_word_match():
dictionary = ["alpha", "beta", "gamma"]
fragment = "____a"
result = count_matching_words(dictionary... | [
{
"docstring": "Counts how many words from the dictionary can match the fragmented sequence by replacing underscores.",
"function_declaration": "def count_matching_words(dictionary, fragment):",
"function_name": "count_matching_words",
"parameter_list": "(dictionary, fragment)"
},
{
"docstri... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def count_possible_words(dictionary, sequences):\n def match(sequence, word):\n if len(sequence) != len(word):\n return False\n fo... | trial_gpt4o_3 | {
"original_instruction": "In an ancient city, the local historian has discovered a fragmented set of inscriptions on stone tablets. Each tablet contains a sequence of lowercase English letters, but some characters are missing and replaced with the \"_\" symbol. The historian believes that by inserting letters in pla... | 0.610665 | Codeforces_908 | C | [
"count_matching_words",
"solve"
] | 2 | [
[
"solve",
"count_matching_words"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 13661fa6cf0bd4f2f40af3c46e4cf03069ad5262 | 6410457a885e3a6626d2b2bf99a805f0e280a791 | |||
v1.0 | complete | Codeforces | Codeforces_890_C | from typing import List
def smallest_or_next_lexicographical_order(arr: List[int]) -> List[int]:
"""
Given an array of integers, rearrange the elements to form the lexicographically
smallest possible array. If the input array is already the smallest possible
lexicographical order, return the next lexic... | def next_permutation(arr):
"""
Generate the next lexicographical permutation for the list `arr`.
Args:
arr (list): The list of integers.
Returns:
list: The next lexicographical permutation of the list.
"""
# 1. Find the largest index k such that arr[k] < arr[k + 1]. If no such ... | def test_smallest_order():
assert smallest_or_next_lexicographical_order([3, 1, 4, 2]) == [1, 2, 3, 4]
assert smallest_or_next_lexicographical_order([2, 2, 1]) == [1, 2, 2]
def test_next_permutation():
assert smallest_or_next_lexicographical_order([1, 2, 3, 4, 5]) == [1, 2, 3, 5, 4]
assert smallest_or_... | [
{
"docstring": "Generate the next lexicographical permutation for the list `arr`.\n\nArgs:\narr (list): The list of integers.\n\nReturns:\nlist: The next lexicographical permutation of the list.",
"function_declaration": "def next_permutation(arr):",
"function_name": "next_permutation",
"parameter_l... | [
1,
1,
1,
1,
1,
0,
0,
0,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def next_permutation(nums):\n \"\"\"\n Modifies list 'nums' to its next lexicographical permutation in-place.\n Returns True if the permutation is th... | trial_gpt4o_9 | {
"original_instruction": "Given an array of integers, your task is to rearrange the elements in such a way that they form the lexicographically smallest possible array. If the input array is already the smallest possible lexicographical order, then the next lexicographical permutation should be used instead.\n\nFor ... | 0.732734 | Codeforces_890 | C | [
"next_permutation",
"smallest_or_next_lexicographical_order"
] | 2 | [
[
"smallest_or_next_lexicographical_order",
"next_permutation"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 5346b4af68e9f7a87aecd90fba0c8eb3cc1d3f74 | fa9f43bc823f10ea46e8acff1ad3e7c008825822 | |||
v1.0 | complete | Codeforces | Codeforces_1002_C | from typing import List, Tuple
def is_prime(num: int) -> bool:
""" Check if a number is prime """
pass
def is_power_of_two(num: int) -> bool:
""" Check if a number is a power of two """
pass
def max_checkpoints(n: int) -> Tuple[int, List[int]]:
""" Determine the maximum number of checkpoints and ... | def is_prime(num):
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 False
i += 6
return True
def is_power_of_two(num):
... | from solution import max_checkpoints
def test_one_runner():
assert max_checkpoints(1) == (1, [1])
def test_two_runners():
assert max_checkpoints(2) == (1, [2])
def test_three_runners():
assert max_checkpoints(3) == (1, [3])
def test_four_runners():
assert max_checkpoints(4) == (1, [4])
def test_mul... | [
{
"docstring": null,
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def is_power_of_two(num):",
"function_name": "is_power_of_two",
"parameter_list": "(num)"
},
{
"docst... | [
0,
1,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n \"\"\"Check if a number is prime.\"\"\"\n if num <= 1:\n return False\n if num <= 3:\n return True\n if num % 2... | trial_gpt4o_1 | {
"original_instruction": "Lea is organizing a charity marathon event. She wants to assign a set of runners to each checkpoint. Each checkpoint must have at least one runner and each runner must participate in exactly one checkpoint. However, the total number of runners at every checkpoint must either be a prime numb... | 0.531226 | Codeforces_1002 | C | [
"is_prime",
"is_power_of_two",
"max_checkpoints"
] | 3 | [
[
"max_checkpoints",
"is_power_of_two"
],
[
"max_checkpoints",
"is_prime"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 13004257185fb4f76ed49d65ed9009cc616adbe9 | 51ce00ea396efeea0f6afd50b6e724786b8d6f76 | |||
v1.0 | complete | Codeforces | Codeforces_1007_C | def make_consistent_log(n: int, operations: List[str]) -> List[str]:
""" Fixes the log by adding the minimum number of operations to make it consistent.
Args:
n (int): The number of operations left in Alice's log.
operations (List[str]): The list of operations in the format as described.
R... | def make_consistent_log(n, operations):
table = set()
result = []
for operation in operations:
op = operation.split()
if op[0] == "insert":
x = int(op[1])
if x not in table:
table.add(x)
result.append(operation)
elif op[0] ... | from solution import make_consistent_log
def test_sample_input_1():
operations = ["delete 3", "insert 4", "contains 4"]
expected_output = ["insert 3", "delete 3", "insert 4", "contains 4"]
assert make_consistent_log(3, operations) == expected_output
def test_sample_input_2():
operations = ["contains 1... | [
{
"docstring": null,
"function_declaration": "def make_consistent_log(n, operations):",
"function_name": "make_consistent_log",
"parameter_list": "(n, operations)"
},
{
"docstring": null,
"function_declaration": "def solve(n, operations):",
"function_name": "solve",
"parameter_li... | [
1,
1,
0,
0,
0,
0,
1,
0,
0
] | 3 | medium | 0.333 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class HashTable:\n def __init__(self, size=100000):\n self.size = size\n self.table = [None] * size\n self.deleted = set()\n \n... | trial_gpt4o_6 | {
"original_instruction": "Alice has recently learned about hash tables.\n\nShe has a hash table that uses open addressing with linear probing to resolve collisions. This hash table supports the following operations:\n\n1. `insert x`: Inserts integer `x` into the hash table. If `x` is already in the hash table, it ig... | 0.528471 | Codeforces_1007 | C | [
"make_consistent_log",
"solve"
] | 2 | [
[
"solve",
"make_consistent_log"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7bd5cfa23ecc682e2a96bb8eb347a517b99a1b3e | a848c5ba8e745b8f7e6c8011f307c14d0f522367 | |||
v1.0 | complete | Codeforces | Codeforces_875_C | from typing import List
def minimum_travel_time(k: int, n: int, road_list: List[str]) -> int:
""" Determine the minimum total travel time required to connect all the castles.
Return "IMPOSSIBLE" if it is not possible to connect all the castles.
Args:
k (int): Number of castles.
n (int): Number... | 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_y] = root_x
elif rank[root_x] < rank[root_y]:
parent[root_x] ... | def test_minimum_travel_time():
k = 4
n = 5
road_list = [
"1 2 3",
"2 3 4",
"3 4 5",
"4 1 6",
"2 4 2",
]
assert minimum_travel_time(k, n, road_list) == 9
def test_only_one_road():
k = 2
n = 1
road_list = [
"1 2 1000",
]
assert mini... | [
{
"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,
1,
0,
0,
1,
0,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def kruskal_minimum_spanning_tree(k, n, roads):\n # Helper function to find the root of a set using path compression\n def find(parent, i):\n if ... | trial_gpt4o_6 | {
"original_instruction": "In a fictional kingdom, there are k castles connected by n bidirectional roads. Each road connects two distinct castles and can be traversed in both directions. The king wants to ensure that his troops can defend the entire kingdom efficiently by installing communication lines. However, the... | 0.642316 | Codeforces_875 | C | [
"find",
"union",
"kruskal_minimum_spanning_tree",
"minimum_travel_time"
] | 4 | [
[
"kruskal_minimum_spanning_tree",
"find"
],
[
"kruskal_minimum_spanning_tree",
"union"
],
[
"minimum_travel_time",
"kruskal_minimum_spanning_tree"
],
[
"union",
"find"
]
] | 4 | [] | false | [] | false | pytest | false | [] | true | ff5a10616d74528e99e237b4d9d40331a5333629 | 7978210cba088e034017ed29d1edfbce034dc6bf | |||
v1.0 | complete | Codeforces | Codeforces_1376_C | from typing import Union, List
def max_beauty(input_data: Union[str, List[str]]) -> Union[str, int]:
"""
Create a function that calculates the 'beauty' of a string. The beauty of a character is defined as its position in the English alphabet (A is 1, B is 2, ..., Z is 26). The beauty of a string is the sum of ... | def char_beauty(c):
"""
Returns the beauty of a single character.
"""
return ord(c) - ord('A') + 1
def string_beauty(s):
"""
Returns the beauty of a string.
"""
return sum(char_beauty(c) for c in s)
def max_beauty(input_data):
"""
If input_data is a single string, returns its b... | from solution import max_beauty
def test_single_string():
assert max_beauty("ZEBRA") == 52
assert max_beauty("ABCDE") == 15
assert max_beauty("XYZ") == 75
def test_list_of_strings():
assert max_beauty(["APPLE", "ORANGE", "BANANA"]) == "ORANGE"
assert max_beauty(["ABC", "XYZ", "MNO"]) == "XYZ"
... | [
{
"docstring": "Returns the beauty of a single character.",
"function_declaration": "def char_beauty(c):",
"function_name": "char_beauty",
"parameter_list": "(c)"
},
{
"docstring": "Returns the beauty of a string.",
"function_declaration": "def string_beauty(s):",
"function_name": "s... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def calculate_beauty(char):\n \"\"\"\n Calculate the beauty of a single character.\n \"\"\"\n return ord(char) - ord('A') + 1\n\ndef beauty_of_str... | trial_gpt4o_3 | {
"original_instruction": "Create a function that calculates the 'beauty' of a string. The beauty of a character is defined as its position in the English alphabet (A is 1, B is 2, ..., Z is 26). The beauty of a string is the sum of the beauties of its characters.\n\nThe function should also be able to take a list of... | 0.654963 | Codeforces_1376 | C | [
"char_beauty",
"string_beauty",
"max_beauty"
] | 3 | [
[
"max_beauty",
"string_beauty"
],
[
"string_beauty",
"char_beauty"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 06e4a352d48d6875fa692a56ec79ec067ba24733 | 9011d08fa75469a21bc4235378e7ae7ddd06d6b7 | |||
v1.0 | complete | Codeforces | Codeforces_1038_C | def minimumHeaviestLoad(n: int, m: int, a: List[int], b: List[int]) -> int:
"""
Return the minimum possible weight the heaviest loaded shelf can hold.
Parameters:
n (int): Number of shelves.
m (int): Number of books.
a (list): List of maximum number of books each shelf can hold.
b (list): L... | def canPlaceBooks(maxWeight, shelves, books):
""" Helper function to check if all books can be placed such that no shelf exceeds maxWeight."""
shelf_capacities = shelves[:]
current_shelf = 0
current_weight = 0
for book in books:
if current_weight + book <= maxWeight:
current... | from solution import minimumHeaviestLoad
def test_case_1():
assert minimumHeaviestLoad(3, 5, [3, 2, 1], [4, 3, 2, 7, 1]) == 7
def test_case_2():
assert minimumHeaviestLoad(1, 3, [1], [1, 1, 1]) == 3
def test_case_3():
assert minimumHeaviestLoad(4, 5, [2, 2, 2, 2], [2, 2, 2, 2, 2]) == 4
def test_case... | [
{
"docstring": "Helper function to check if all books can be placed such that no shelf exceeds maxWeight.",
"function_declaration": "def canPlaceBooks(maxWeight, shelves, books):",
"function_name": "canPlaceBooks",
"parameter_list": "(maxWeight, shelves, books)"
},
{
"docstring": "Return the... | [
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def canDistribute(books, shelves, mid):\n # List to capture the current weights on each shelf.\n current_shelves = [0] * len(shelves)\n\n for book in... | trial_gpt4o_5 | {
"original_instruction": "You are given a series of shelves, each of which can hold a certain number of books. Each shelf can hold at most a[ind] books. You have several books to place into the shelves, and your goal is to fit all the books into the shelves while balancing the total weight evenly across the shelves ... | 0.620414 | Codeforces_1038 | C | [
"canPlaceBooks",
"minimumHeaviestLoad"
] | 2 | [
[
"minimumHeaviestLoad",
"canPlaceBooks"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7d6b3214f904e8c609427871476a8f4c7d2b04be | d7abf9f01b24a45884b17cebea077a99b9626c7f | |||
v1.0 | complete | Codeforces | Codeforces_1360_C | from typing import List
def find_anagram_groups(words: List[str]) -> List[str]:
"""
Given a list of words, find all anagram groups within the list.
If no anagram groups are found, return ["No anagrams found"].
>>> find_anagram_groups(["listen", "silent", "enlist", "inlets", "google"])
['listen... | def find_anagram_groups(words):
"""
Given a list of words, find all anagram groups within the list.
"""
from collections import defaultdict
anagrams = defaultdict(list)
for word in words:
sorted_word = ''.join(sorted(word))
anagrams[sorted_word].append(word)
... | from solution import find_anagram_groups, solve
def test_find_anagram_groups_with_anagrams():
words = ["listen", "silent", "enlist", "inlets", "google"]
result = find_anagram_groups(words)
assert result == ["listen silent enlist inlets"]
def test_find_anagram_groups_without_anagrams():
words = ["apple... | [
{
"docstring": "Given a list of words, find all anagram groups within the list.",
"function_declaration": "def find_anagram_groups(words):",
"function_name": "find_anagram_groups",
"parameter_list": "(words)"
},
{
"docstring": null,
"function_declaration": "def solve(n, word_list):",
... | [
1,
1,
1,
1,
0,
0,
0,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_anagram_groups(words):\n from collections import defaultdict\n \n anagram_dict = defaultdict(list)\n \n # Group words by sorted tuple ... | trial_gpt4o_9 | {
"original_instruction": "Given a list of words, find all anagram groups within the list. An anagram is a word formed by rearranging the letters of another, such as \"listen\" and \"silent\".\n\nThe first line contains a single integer n (1 ≤ n ≤ 10000) — the total number of words in the list.\n\nThe next n lines ea... | 0.597647 | Codeforces_1360 | C | [
"find_anagram_groups",
"solve"
] | 2 | [
[
"solve",
"find_anagram_groups"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 10c07332263574234093eb38dca4782a9ad2fef4 | fd547f7b89de3e83d8f22cbe8dc8b24bcc8f5cfa | |||
v1.0 | complete | Codeforces | Codeforces_1509_C | def is_power_of_two(n: int) -> bool:
""" Check if a number is power of two.
>>> is_power_of_two(128)
True
>>> is_power_of_two(123)
False
"""
def can_form_power_of_two(x: int) -> str:
""" Check if it's possible to rearrange the digits of a number to form a power of two.
>>> can_form_... | from itertools import permutations
def is_power_of_two(n):
# n is a single number
return n > 0 and (n & (n - 1)) == 0
def can_form_power_of_two(x):
x_str = str(x)
perm = set(permutations(x_str)) # get all permutations of x_str
for p in perm:
num = int(''.join(p))
if is_power_of_tw... | from solution import check_power_of_two_rearrangement, can_form_power_of_two
def test_example_1(capsys):
check_power_of_two_rearrangement(128)
captured = capsys.readouterr()
assert captured.out.strip() == "YES"
def test_example_2(capsys):
check_power_of_two_rearrangement(123)
captured = capsys.rea... | [
{
"docstring": null,
"function_declaration": "def is_power_of_two(n):",
"function_name": "is_power_of_two",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def can_form_power_of_two(x):",
"function_name": "can_form_power_of_two",
"parameter_list": "(x)"
... | [
1,
1,
0,
0,
0,
0,
1,
0,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from itertools import permutations\n\ndef is_power_of_two(n):\n \"\"\"\n Check if the given number n is a power of two.\n \"\"\"\n return (n > 0) ... | trial_gpt4o_9 | {
"original_instruction": "Given a non-negative integer `x`, determine whether it is possible to rearrange its digits such that they form a power of 2. \n\nThe first line contains an integer `x` (0 ≤ x ≤ 10^9).\n\nIn a single line, print \"YES\" if it is possible to rearrange the digits of `x` to form a power of 2, o... | 0.665481 | Codeforces_1509 | C | [
"is_power_of_two",
"can_form_power_of_two",
"check_power_of_two_rearrangement"
] | 3 | [
[
"can_form_power_of_two",
"is_power_of_two"
],
[
"check_power_of_two_rearrangement",
"can_form_power_of_two"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 1c9625fb8931edb12ae2dd5c6358fdcf7919681d | ed509be53a2d38145e2a399a870b9a4bb00f7c11 | |||
v1.0 | complete | Codeforces | Codeforces_1518_C | from typing import Tuple, Union
def sieve(n: int) -> list:
""" Implement Sieve of Eratosthenes to generate all prime numbers up to n.
>>> sieve(10)
[2, 3, 5, 7]
"""
is_prime = [True] * (n + 1)
p = 2
while p * p <= n:
if is_prime[p]:
for i in range(p * p, n + 1, p):
... | def sieve(n):
""" Implement Sieve of Eratosthenes to generate all prime numbers up to n. """
is_prime = [True] * (n + 1)
p = 2
while p * p <= n:
if is_prime[p]:
for i in range(p * p, n + 1, p):
is_prime[i] = False
p += 1
primes = [p for p in range(2, n + 1... | from solution import find_prime_pair
def test_smallest_valid_prime_pair():
assert find_prime_pair(4) == (2, 2)
def test_example_case():
assert find_prime_pair(26) == (3, 23)
def test_no_possible_pair():
# This case assumes the input will always guarantee at least one valid pair
pass
def test_lar... | [
{
"docstring": "Implement Sieve of Eratosthenes to generate all prime numbers up to n. ",
"function_declaration": "def sieve(n):",
"function_name": "sieve",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def find_prime_pair(n):",
"function_name": "find_prime... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n if num <= 1:\n return False\n if num == 2:\n return True\n if num % 2 == 0:\n return False\n for i in ra... | trial_gpt4o_3 | {
"original_instruction": "Ella has recently become interested in prime numbers and their properties. To challenge herself, she came up with a new game involving prime sums. The game is defined as follows:\n\nGiven an integer n, find two distinct positive prime numbers p and q such that their sum equals n (i.e., p + ... | 0.710634 | Codeforces_1518 | C | [
"sieve",
"find_prime_pair"
] | 2 | [
[
"find_prime_pair",
"sieve"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f2867ca6f48f94e6d07b2746f6857c5a435cef31 | be012d64b5c23b17d3764b08e91467980a6c19bf | |||
v1.0 | complete | Codeforces | Codeforces_1438_C | from typing import List, Tuple
def max_decommissioned_paths(n: int, m: int, k: int, connections: List[Tuple[int, int, int]], secure_paths: List[Tuple[int, int]]) -> int:
""" Determine the maximum number of secure paths which can be decommissioned without increasing the shortest latency from the central module to a... | from heapq import heappop, heappush
from collections import defaultdict
import sys
def min_latencies(n, adj):
dist = [float('inf')] * (n + 1)
dist[1] = 0
pq = [(0, 1)]
while pq:
d, u = heappop(pq)
if d > dist[u]:
continue
for v, w in adj[u]:
if dist[... | from solution import max_decommissioned_paths
def test_max_decommissioned_paths():
n, m, k = 5, 6, 3
connections = [
(1, 2, 1),
(1, 3, 3),
(2, 4, 4),
(3, 4, 2),
(4, 5, 2),
(3, 5, 8)
]
secure_paths = [
(2, 1),
(4, 3),
(5, 10)
]
... | [
{
"docstring": null,
"function_declaration": "def min_latencies(n, adj):",
"function_name": "min_latencies",
"parameter_list": "(n, adj)"
},
{
"docstring": null,
"function_declaration": "def max_decommissioned_paths(n, m, k, connections, secure_paths):",
"function_name": "max_decommi... | [
0,
0,
0,
0,
0,
0,
1,
1,
0,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\n\ndef maximum_decommissioned_paths(n, m, k, connections, secure_paths):\n # Step 1: Build the adjacency list for general connections\n adj... | trial_gpt4o_6 | {
"original_instruction": "Katrina is managing a new software system which consists of n modules numbered from 1 to n. Module 1 is the central module. Additionally, there are m directed connections between the modules. One can go from module ui to module vi using the i-th connection, with a latency of xi milliseconds... | 0.594087 | Codeforces_1438 | C | [
"min_latencies",
"max_decommissioned_paths"
] | 2 | [
[
"max_decommissioned_paths",
"min_latencies"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bf63efffeab7f1c1d821ed3f2441ca074db7d1ca | ef042cc272de2363967b0bb761e17710ed7fee05 | |||
v1.0 | complete | Codeforces | Codeforces_1494_C | def maximalRectangle(matrix: List[List[int]]) -> int:
"""
Given a grid of 0s and 1s, find the largest rectangle containing only 1s.
>>> maximalRectangle([
[1, 0, 1, 0, 0],
[1, 0, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 0, 0, 1, 0]
]) == 6
>>> maximalRectangle([
[1, 1, ... | def largestRectangleArea(heights):
"""
Helper function to find the largest rectangle in a histogram.
"""
stack = []
max_area = 0
index = 0
while index < len(heights):
if not stack or heights[index] >= heights[stack[-1]]:
stack.append(index)
index += 1
... | from solution import maximalRectangle
def test_example_case():
input_grid = [
[1, 0, 1, 0, 0],
[1, 0, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 0, 0, 1, 0]
]
assert maximalRectangle(input_grid) == 6
def test_all_ones():
input_grid = [
[1, 1, 1],
[1, 1, 1],
... | [
{
"docstring": "Helper function to find the largest rectangle in a histogram.",
"function_declaration": "def largestRectangleArea(heights):",
"function_name": "largestRectangleArea",
"parameter_list": "(heights)"
},
{
"docstring": "Given a grid of 0s and 1s, finds the largest rectangle conta... | [
0,
1,
1,
0,
1,
0,
1,
0,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def largest_rectangle_area(matrix):\n \"\"\"\n Returns the area of the largest rectangle containing only 1s in the given grid.\n \"\"\"\n if not m... | trial_gpt4o_2 | {
"original_instruction": "Given a grid with N rows and M columns, you need to find the largest rectangle (sub-grid) containing only 1s.\n\nYou are given N x M grid of 0s and 1s. Your task is to write a program that calculates the area of the largest rectangle (sub-grid) in the grid that contains only 1s.\n\n**Input:... | 0.71209 | Codeforces_1494 | C | [
"largestRectangleArea",
"maximalRectangle"
] | 2 | [
[
"maximalRectangle",
"largestRectangleArea"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 3a6e54a208f55c5508ffb90040f81276a910d3ba | 5c4adf140e8104f0242fbce952d17fb7f6072d50 | |||
v1.0 | complete | Codeforces | Codeforces_2053_C | def get_word_weight(word: str) -> int:
"""
Calculates the weight of a given word.
>>> get_word_weight("apple") 50
>>> get_word_weight("dog") 26
"""
# Your code here
def highest_weight_word(words: str) -> str:
"""
Returns the word with the highest weight from a space-separated list of wo... | def get_word_weight(word):
"""
Calculates the weight of a given word.
"""
return sum(ord(char) - ord('a') + 1 for char in word)
def highest_weight_word(words):
"""
Returns the word with the highest weight. In case of a tie, returns the lexicographically first word.
"""
word_list = words... | from solution import highest_weight_word
def test_highest_weight_word_single_word():
assert highest_weight_word("apple") == "apple"
def test_highest_weight_word_multiple_words():
assert highest_weight_word("dog cat zebra apple") == "zebra"
def test_highest_weight_word_tie():
assert highest_weight... | [
{
"docstring": "Calculates the weight of a given word.",
"function_declaration": "def get_word_weight(word):",
"function_name": "get_word_weight",
"parameter_list": "(word)"
},
{
"docstring": "Returns the word with the highest weight. In case of a tie, returns the lexicographically first wor... | [
0,
0,
1,
1,
1,
1,
0,
0,
1,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def word_weight(word):\n \"\"\"\n Computes the weight of a word based on the sum of positions of its characters in the alphabet.\n \n :param word:... | trial_gpt4o_8 | {
"original_instruction": "Create a program that computes the \"weight\" of a word, where the weight of a word is defined as the sum of the positions of its characters in the alphabet (a = 1, b = 2, ..., z = 26).\n\nYour task is to write a function that takes in a list of words and returns the word with the highest w... | 0.682778 | Codeforces_2053 | C | [
"get_word_weight",
"highest_weight_word"
] | 2 | [
[
"highest_weight_word",
"get_word_weight"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | eafc1c60b63347ab88892cbb655bf14e633db446 | e8ba562faa605631fa45a47109ecb6bc1ac543cf | |||
v1.0 | complete | Codeforces | Codeforces_1585_C | def maximal_rectangle(matrix: List[List[str]]) -> int:
""" Find the largest rectangle containing only 1's and return its area.
>>> maximal_rectangle([
... ['1', '0', '1', '0', '0'],
... ['1', '0', '1', '1', '1'],
... ['1', '1', '1', '1', '1'],
... ['1', '0', '0', '1', '0']
...]) 6
>... | def maximal_rectangle(matrix):
if not matrix:
return 0
n = len(matrix)
m = len(matrix[0])
heights = [0] * m
max_area = 0
for row in matrix:
for i in range(m):
if row[i] == '1':
heights[i] += 1
else:
heights[i] = 0
... | import pytest
from solution import maximal_rectangle
def test_example_case():
matrix = [
['1', '0', '1', '0', '0'],
['1', '0', '1', '1', '1'],
['1', '1', '1', '1', '1'],
['1', '0', '0', '1', '0']
]
assert maximal_rectangle(matrix) == 6
def test_empty_matrix():
matrix = ... | [
{
"docstring": null,
"function_declaration": "def maximal_rectangle(matrix):",
"function_name": "maximal_rectangle",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def largest_rectangle_area(heights):",
"function_name": "largest_rectangle_area",
"pa... | [
1,
1,
1,
0,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def maximalRectangle(matrix):\n if not matrix:\n return 0\n\n max_area = 0\n n = len(matrix)\n m = len(matrix[0])\n heights = [0] * m\n\... | trial_gpt4o_8 | {
"original_instruction": "A rectangular matrix is given with $$$n$$$ rows and $$$m$$$ columns. The matrix contains only binary values (0 or 1). \n\nYour task is to find the largest rectangle containing only 1's and return its area.\n\n### Input format\n- The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1... | 0.741168 | Codeforces_1585 | C | [
"maximal_rectangle",
"largest_rectangle_area"
] | 2 | [
[
"maximal_rectangle",
"largest_rectangle_area"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e5d12ee00539a218a25de2d6b2a57a0846f70308 | 40be436b6ef406bdbae9a0fa5cdae33b9e5ea63a | |||
v1.0 | complete | Codeforces | Codeforces_1481_C | from typing import List
def ruler_of_forest(n: int, m: int, creatures: List[List[int]], abilities: List[int]) -> int:
"""
Determine the creature who would become the ruler of the forest after n duels.
Parameters:
n (int): Number of creatures in the forest.
m (int): Number of different abiliti... | def find_ruler(n, m, creatures, abilities):
current_creatures = list(range(n)) # index of creatures still in the forest
for ability in abilities:
ability -= 1 # converting to 0-based index
# Perform duels for the current ability
new_creatures = []
while len(current_creatures... | def test_ruler_example():
n = 4
m = 2
creatures = [
[10, 15],
[20, 5],
[25, 30],
[10, 40]
]
abilities = [1, 2, 2, 1]
assert ruler_of_forest(n, m, creatures, abilities) == 3
def test_ruler_different_abilities():
n = 3
m = 3
creatures = [
[5, 15... | [
{
"docstring": null,
"function_declaration": "def find_ruler(n, m, creatures, abilities):",
"function_name": "find_ruler",
"parameter_list": "(n, m, creatures, abilities)"
},
{
"docstring": null,
"function_declaration": "def ruler_of_forest(n, m, creatures, abilities):",
"function_na... | [
1,
1,
0,
0,
0,
0,
0,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_ruler(num_creatures, num_abilities, creatures, order_of_duels):\n remaining_creatures = list(range(num_creatures))\n \n for ability in order... | trial_gpt4o_9 | {
"original_instruction": "In an ancient forest, there are several magical creatures each with unique abilities. Abilities can be either physical (strength, agility) or elemental (fire, water). Every day, two creatures engage in a duel in a particular ability chosen by the forest's elder. The creature with the higher... | 0.520159 | Codeforces_1481 | C | [
"find_ruler",
"ruler_of_forest"
] | 2 | [
[
"ruler_of_forest",
"find_ruler"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 48ac34f8b9c4453b84288e6c7fd024299da631aa | 19e6918f84b032ca32aa2dd3a52da3d695aeadc9 | |||
v1.0 | complete | Codeforces | Codeforces_1510_C | def merge_sort(arr: List[str]) -> List[str]:
"""Implement Merge Sort algorithm to sort an array of strings in ascending lexicographical order"""
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def me... | def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left, right):
merged = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
... | from solution import sort_strings
def test_sort_strings():
assert sort_strings(5, ["apple", "banana", "orange", "grape", "mango"]) == ["apple", "banana", "grape", "mango", "orange"]
assert sort_strings(3, ["zebra", "apple", "yellow"]) == ["apple", "yellow", "zebra"]
assert sort_strings(4, ["mango", "banana... | [
{
"docstring": null,
"function_declaration": "def merge_sort(arr):",
"function_name": "merge_sort",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def merge(left, right):",
"function_name": "merge",
"parameter_list": "(left, right)"
},
{
"docst... | [
1,
1,
1,
1,
1,
1,
0,
0,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def merge_sort(arr):\n if len(arr) > 1:\n mid = len(arr) // 2\n left_half = arr[:mid]\n right_half = arr[mid:]\n\n merge_sort(l... | trial_gpt4o_9 | {
"original_instruction": "Kiran has been learning about different sorting algorithms, and he is particularly interested in the Merge Sort algorithm. He understands how Merge Sort works, but he wants to see its specific application on an array of strings.\n\nKiran has an array of n strings, and he needs to sort the a... | 0.675945 | Codeforces_1510 | C | [
"merge_sort",
"merge",
"sort_strings"
] | 3 | [
[
"merge_sort",
"merge"
],
[
"sort_strings",
"merge_sort"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 80e906ef6f423399347255e551decf5d10b89770 | 0573fca7c12e3f49f288e6e0c05a3c9d058d2656 | |||
v1.0 | complete | Codeforces | Codeforces_1224_C | def count_unique_books(logbook):
"""
Returns a dictionary where keys are customer ids and values are
the number of unique books read by that customer.
:param logbook: List of tuples, each tuple contains a customer id and a book id.
:return: Dictionary with customer id as keys and number of uniq... | def count_unique_books(logbook):
"""
Returns a dictionary where keys are customer ids and values are
the number of unique books read by that customer.
:param logbook: List of tuples, each tuple contains a customer id and a book id.
:return: Dictionary with customer id as keys and number of uniq... | from solution import process_logbook
def test_single_customer_multiple_books():
entries = [
"5",
"1 10",
"1 20",
"1 30",
"1 40",
"1 10"
]
assert process_logbook(entries) == {1: 4}
def test_multiple_customers():
entries = [
"6",
"1 10",
... | [
{
"docstring": "Returns a dictionary where keys are customer ids and values are\nthe number of unique books read by that customer.\n\n:param logbook: List of tuples, each tuple contains a customer id and a book id.\n:return: Dictionary with customer id as keys and number of unique books as values.",
"functi... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def count_unique_books(logbook):\n from collections import defaultdict\n\n customer_books = defaultdict(set)\n\n for customer_id, book_id in logbook:... | trial_gpt4o_9 | {
"original_instruction": "An online bookstore keeps track of the books its customers read. Each time a customer reads a book, the bookstore logs the reading activity. The system stores all customers' reading activities in a logbook, which is a list of entries. Each entry contains a customer id and book id.\n\nBased ... | 0.535201 | Codeforces_1224 | C | [
"count_unique_books",
"process_logbook"
] | 2 | [
[
"process_logbook",
"count_unique_books"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e19b14539eb58b379ebcff099ff64e12f2fcbe1f | b0acf08f79cec2d13a2c76bc2f7d79868eeac342 | |||
v1.0 | complete | Codeforces | Codeforces_2098_C | def gcd(x, y):
"""
Calculate the Greatest Common Divisor (GCD) of x and y.
"""
while y:
x, y = y, x % y
return x
def lcm(a, b):
"""
Returns the Least Common Multiple (LCM) of a and b.
>>> lcm(4, 6) == 12
>>> lcm(5, 10) == 10
>>> lcm(7, 7) == 7
>>> lcm(7, 13) == 91
... | def gcd(x, y):
"""
Calculate the Greatest Common Divisor (GCD) of x and y.
"""
while y:
x, y = y, x % y
return x
def lcm(a, b):
"""
Returns the Least Common Multiple (LCM) of a and b.
"""
return abs(a * b) // gcd(a, b) | from solution import lcm
def test_lcm_example1():
assert lcm(4, 6) == 12
def test_lcm_example2():
assert lcm(5, 10) == 10
def test_lcm_same_numbers():
assert lcm(7, 7) == 7
def test_lcm_prime_numbers():
assert lcm(7, 13) == 91
def test_lcm_one():
assert lcm(1, 10) == 10
assert lcm(1, 1) == ... | [
{
"docstring": "Calculate the Greatest Common Divisor (GCD) of x and y.",
"function_declaration": "def gcd(x, y):",
"function_name": "gcd",
"parameter_list": "(x, y)"
},
{
"docstring": "Returns the Least Common Multiple (LCM) of a and b.",
"function_declaration": "def lcm(a, b):",
"f... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef lcm(a, b):\n \"\"\"\n Returns the least common multiple (LCM) of two integers a and b.\n \"\"\"\n return abs(a*b) // math.gcd(a... | trial_gpt4o_9 | {
"original_instruction": "You are given two integers \\(a\\) and \\(b\\) (1 ≤ a, b ≤ 100). You need to determine the smallest integer \\(c\\) such that both \\(a\\) and \\(b\\) are divisors of \\(c\\).\n\nA number \\(x\\) is said to be a divisor of \\(y\\) if there exists an integer \\(k\\) such that \\(y = k \\time... | 0.831475 | Codeforces_2098 | C | [
"gcd",
"lcm"
] | 2 | [
[
"lcm",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 98fd427a930c68aaa04e5ca6c6ab64cb4b7039bf | 5f952c6f084acf098214bfc65f557a536f47d5c1 | |||
v1.0 | complete | Codeforces | Codeforces_919_C | def determine_point_status(n: int, vertices: List[Tuple[int, int]], point: Tuple[int, int]) -> str:
""" Determine if a given point lies inside, on the boundary, or outside a convex polygon.
:param n: Number of vertices of the polygon
:param vertices: List of (x, y) coordinates of the polygon vertices in cl... | def is_point_in_polygon(vertices, point):
def on_segment(p, q, r):
"""Check if point q lies on segment pr"""
if (q[0] <= max(p[0], r[0]) and q[0] >= min(p[0], r[0]) and
q[1] <= max(p[1], r[1]) and q[1] >= min(p[1], r[1])):
return True
return False
def orientation... | from solution import determine_point_status
def test_inside():
assert determine_point_status(5, [(0,0),(4,0),(4,4),(0,4),(-1,2)], (2,2)) == "INSIDE"
def test_outside():
assert determine_point_status(4, [(1,1),(3,1),(3,3),(1,3)], (4,4)) == "OUTSIDE"
def test_boundary():
assert determine_point_status(4, [(... | [
{
"docstring": null,
"function_declaration": "def is_point_in_polygon(vertices, point):",
"function_name": "is_point_in_polygon",
"parameter_list": "(vertices, point)"
},
{
"docstring": null,
"function_declaration": "def determine_point_status(n, vertices, point):",
"function_name": ... | [
1,
0,
0,
1,
1,
1,
1,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_point_in_polygon(n, vertices, px, py):\n def is_on_segment(p, q, r):\n # Check if point r is on segment pq\n return (q[0] <= max(p[0],... | trial_gpt4o_8 | {
"original_instruction": "You are given a convex polygon with n vertices. A convex polygon is defined as a polygon where all interior angles are less than 180 degrees, and each line segment between two vertices is inside or on the boundary of the polygon. The vertices are given in clockwise order. Your task is to de... | 0.589799 | Codeforces_919 | C | [
"is_point_in_polygon",
"determine_point_status"
] | 2 | [
[
"determine_point_status",
"is_point_in_polygon"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 467d399f0ae0978cb0fc31cce4325a463dfac10a | cfc408b2b7866c2477133c7eef3c7195f7c40506 | |||
v1.0 | complete | Codeforces | Codeforces_1433_C | from typing import List, Tuple
def can_attend_meetings(meetings: List[Tuple[str, str]]) -> bool:
"""
Determine if a person can attend all meetings without overlaps.
Args:
meetings (List[Tuple[str, str]]): A list of tuples where each tuple represents the start and end time of a meeting in "HH:MM" ... | from typing import List, Tuple
def time_to_minutes(t: str) -> int:
"""
Convert a time string in the format 'HH:MM' to the number of minutes since 00:00.
"""
hours, minutes = map(int, t.split(':'))
return hours * 60 + minutes
def can_attend_meetings(meetings: List[Tuple[str, str]]) -> bool:
"""... | from solution import can_attend_meetings
def test_no_overlap():
meetings = [("09:00", "10:30"), ("11:00", "12:00"), ("12:30", "14:00")]
assert can_attend_meetings(meetings) == True
def test_with_overlap():
meetings = [("09:00", "10:30"), ("10:15", "11:00"), ("11:00", "12:00")]
assert can_attend_meetin... | [
{
"docstring": "Convert a time string in the format 'HH:MM' to the number of minutes since 00:00.",
"function_declaration": "def time_to_minutes(t):",
"function_name": "time_to_minutes",
"parameter_list": "(t)"
},
{
"docstring": "Determines if a person can attend all meetings without overlap... | [
1,
1,
1,
1,
1,
1,
0,
1,
1,
0
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple\n\ndef can_attend_meetings(meetings: List[Tuple[str, str]]) -> bool:\n # Convert time from \"HH:MM\" string format to intege... | trial_gpt4o_8 | {
"original_instruction": "Write a function that takes a list of tuples as input, each containing start and end times of meetings (in the format (start_time, end_time)), and determines whether a person can attend all the meetings without overlap. The times are given as 24-hour format strings (e.g., \"09:00\").\n\nThe... | 0.608885 | Codeforces_1433 | C | [
"time_to_minutes",
"can_attend_meetings"
] | 2 | [
[
"can_attend_meetings",
"time_to_minutes"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b44b2319df26836618564bb62cac6f1be78ce0ef | 6775a621e5627221c0b98e23a7140eb944bda28a | |||
v1.0 | complete | Codeforces | Codeforces_1656_C | import math
from itertools import combinations
from typing import List, Tuple
def calculate_distance(p1: Tuple[int, int], p2: Tuple[int, int]) -> float:
"""
Computes the Euclidean distance between two points p1 and p2.
"""
return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
def min_largest_d... | import math
from itertools import combinations
def calculate_distance(p1, p2):
"""
Computes the Euclidean distance between two points p1 and p2.
"""
return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
def min_largest_distance(n, k, coordinates):
"""
Returns the minimum possible value... | from solution import min_largest_distance
def test_min_largest_distance_case1():
n = 4
k = 2
coordinates = [(0, 0), (3, 4), (6, 8), (9, 12)]
assert min_largest_distance(n, k, coordinates) == 5.0
def test_min_largest_distance_case2():
n = 3
k = 2
coordinates = [(1, 1), (4, 5), (7, 9)]
a... | [
{
"docstring": "Computes the Euclidean distance between two points p1 and p2.",
"function_declaration": "def calculate_distance(p1, p2):",
"function_name": "calculate_distance",
"parameter_list": "(p1, p2)"
},
{
"docstring": "Returns the minimum possible value of the largest distance any fri... | [
0,
0,
1,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom itertools import combinations\n\ndef distance(p1, p2):\n \"\"\"\n Calculates the Euclidean distance between two points p1 and p2.\n ... | trial_gpt4o_2 | {
"original_instruction": "A group of friends are planning a trip. They want to visit exactly k islands out of n available islands. Each friend can have only one visit per island, but multiple friends can visit an island simultaneously. They can start from any island and move to any other island. They want to minimiz... | 0.640806 | Codeforces_1656 | C | [
"calculate_distance",
"min_largest_distance"
] | 2 | [
[
"min_largest_distance",
"calculate_distance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 444252247ea08f0fc1fbb8d1ecd5bc4f33cebe3e | 04733948ef98eedf3479f5c226dbc0c716c072ce | |||
v1.0 | complete | Codeforces | Codeforces_2383_C | def largest_rectangular_area_of_empty_cells(grid: List[List[str]], R: int, C: int) -> int:
""" Determine the largest rectangle of empty cells ('.') within a given grid.
>>> largest_rectangular_area_of_empty_cells([
... ['.', '.', '.', '.', '.'],
... ['.', '.', '#', '.', '.'],
... ['.', '.', '.', '.'... | def max_histogram_area(heights):
stack = []
max_area = 0
index = 0
while index < len(heights):
if not stack or heights[stack[-1]] <= heights[index]:
stack.append(index)
index += 1
else:
top_of_stack = stack.pop()
area = (heights[top_of_sta... | from solution import largest_rectangular_area_of_empty_cells
def test_no_blockers():
grid = [
['.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.']
]
assert largest_rectangular_area_of_empty_cells(grid, 4, 5) == 20
def te... | [
{
"docstring": null,
"function_declaration": "def max_histogram_area(heights):",
"function_name": "max_histogram_area",
"parameter_list": "(heights)"
},
{
"docstring": null,
"function_declaration": "def largest_rectangular_area_of_empty_cells(grid, R, C):",
"function_name": "largest_... | [
0,
0,
0,
0,
0,
0,
1,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def max_histogram_area(histogram):\n stack = []\n max_area = 0\n index = 0\n\n while index < len(histogram):\n if not stack or histogram[st... | trial_gpt4o_6 | {
"original_instruction": "You are given a rectangular grid of cells with R rows and C columns. Each cell in the grid can either be empty ('.') or blocked ('#'). Your task is to determine the largest rectangle of empty cells ('.') within this grid. Note that the rectangle has to be contiguous and its sides should be ... | 0.65508 | Codeforces_2383 | C | [
"max_histogram_area",
"largest_rectangular_area_of_empty_cells"
] | 2 | [
[
"largest_rectangular_area_of_empty_cells",
"max_histogram_area"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f772452b02494be200240b01bc69a4354d140a27 | eccbbb85cee6e2d299f45d8afab68a04d8ca444d | |||
v1.0 | complete | Codeforces | Codeforces_2193_C | from typing import List
def min_days_to_bloom(n: int, growth_times: List[int]) -> int:
""" Determine the minimum number of days required from any starting day to achieve the goal where all flower types bloom on the same day.
>>> min_days_to_bloom(3, [5, 10, 15])
30
>>> min_days_to_bloom(1, [4])
... | import math
from functools import reduce
def lcm(a, b):
return abs(a * b) // math.gcd(a, b)
def lcm_multiple(numbers):
return reduce(lcm, numbers)
def min_days_to_bloom(n, growth_times):
return lcm_multiple(growth_times) | from solution import min_days_to_bloom
def test_example_case():
assert min_days_to_bloom(3, [5, 10, 15]) == 30
def test_single_seed_type():
assert min_days_to_bloom(1, [4]) == 4
def test_two_seed_types():
assert min_days_to_bloom(2, [6, 8]) == 24
def test_multiple_seed_types():
assert min_days_to_bl... | [
{
"docstring": null,
"function_declaration": "def lcm(a, b):",
"function_name": "lcm",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def lcm_multiple(numbers):",
"function_name": "lcm_multiple",
"parameter_list": "(numbers)"
},
{
"docstring":... | [
1,
1,
1,
1,
1,
1,
1,
0,
1
] | 8 | easy | 0.889 | {
"trial_gpt4o_0": null,
"trial_gpt4o_1": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared1_results_combined.jsonl",
"solution_code": "import math\nfrom functools import reduce\n\ndef lcm(x, y):\n return x * y // math.gcd(x, y)\n\ndef min_days_to_bloom(n, growth_ti... | trial_gpt4o_9 | {
"original_instruction": "Alice is an avid gardener who loves to grow a wide variety of flowers. She recently came across a collection of n different types of seeds, each with a respective growth time. From these seeds, she wants to plan her garden such that all grown flowers bloom at the same time in order to maxim... | 0.573937 | Codeforces_2193 | C | [
"lcm",
"lcm_multiple",
"min_days_to_bloom"
] | 3 | [
[
"lcm_multiple",
"lcm"
],
[
"min_days_to_bloom",
"lcm_multiple"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6de0008f4bb2a9c02e568082a0a547094329453d | da0526971a246ec5fd29bc178476590a91d52acd | |||
v1.0 | complete | Codeforces | Codeforces_1676_C | from typing import List, Tuple
def generate_difficulties(l: int, b1: int, v: int, w: int, m: int) -> List[int]:
""" Generate the sequence of difficulties for a participant.
>>> generate_difficulties(2, 5, 3, 2, 100)
[5, 11]
>>> generate_difficulties(2, 4, 1, 5, 50)
[4, 9]
"""
pass
def mini... | def generate_difficulties(l, b1, v, w, m):
difficulties = [b1]
for j in range(1, l):
next_difficulty = (difficulties[-1] + v * w) % m
difficulties.append(next_difficulty)
return difficulties
def minimize_difficult_transitions(n, participants):
all_problems = []
for i, (l, b1, v, w, ... | from solution import generate_difficulties, minimize_difficult_transitions, solve
def test_generate_difficulties():
assert generate_difficulties(2, 5, 3, 2, 100) == [5, 11]
assert generate_difficulties(2, 4, 1, 5, 50) == [4, 9]
assert generate_difficulties(3, 1, 2, 2, 10) == [1, 5, 9]
def test_minimize_di... | [
{
"docstring": null,
"function_declaration": "def generate_difficulties(l, b1, v, w, m):",
"function_name": "generate_difficulties",
"parameter_list": "(l, b1, v, w, m)"
},
{
"docstring": null,
"function_declaration": "def minimize_difficult_transitions(n, participants):",
"function_... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def generate_difficulties(n, participants):\n difficulties = []\n \n for i in range(n):\n li, b1, vi, wj, mi = participants[i]\n b = [b... | trial_gpt4o_9 | {
"original_instruction": "You are organizing a coding competition and you have received the registration forms from n participants, numbered from 1 to n. Each participant has provided a schedule of coding problems they will solve, which needs to be followed in a strict sequential order. \n\nEach problem provided by ... | 0.678886 | Codeforces_1676 | C | [
"generate_difficulties",
"minimize_difficult_transitions",
"solve"
] | 3 | [
[
"minimize_difficult_transitions",
"generate_difficulties"
],
[
"solve",
"minimize_difficult_transitions"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 655cea050792aa7524cc15bf079b4bfbb0465f90 | 4ef40c229cd7dd7fa3b6fe1d578cf52298674d68 | |||
v1.0 | complete | Codeforces | Codeforces_1800_C | from typing import List
def is_prime(n: int) -> bool:
""" Helper function to determine if a number is prime. """
pass
def prime_sort(arr: List[int]) -> List[int]:
"""
Returns a new list containing only the prime numbers from the input list,
sorted in ascending order.
>>> prime_sort([2, 4... | from typing import List
def is_prime(n: int) -> bool:
"""
Helper function to determine if a number is prime.
"""
if n <= 1:
return False
if n == 2:
return True # Special case for 2, which is prime
if n % 2 == 0:
return False # No even number larger than 2 is prime
... | from solution import prime_sort
def test_prime_sort_basic():
assert prime_sort([2, 4, 3, 1, 7, 0]) == [2, 3, 7]
def test_prime_sort_with_negatives_and_non_primes():
assert prime_sort([-1, -2, 16, 17, 9]) == [17]
def test_prime_sort_mixed_values():
assert prime_sort([10, 11, 10, 0, 5]) == [5, 11]
def tes... | [
{
"docstring": "Helper function to determine if a number is prime.",
"function_declaration": "def is_prime(n):",
"function_name": "is_prime",
"parameter_list": "(n)"
},
{
"docstring": "Returns a new list containing only the prime numbers from the input list,\nsorted in ascending order.",
... | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 10 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef is_prime(n: int) -> bool:\n \"\"\"Returns True if n is a prime number, else False.\"\"\"\n if n <= 1:\n return Fal... | trial_gpt4o_9 | {
"original_instruction": "Design and implement a function that takes an integer array as input, and returns a new array which contains only the prime numbers from the input array, sorted in ascending order. Note that zero and negative numbers should not be considered prime. Your function should have the following si... | 0.746083 | Codeforces_1800 | C | [
"is_prime",
"prime_sort"
] | 2 | [
[
"prime_sort",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | bab02ce458813fa05cfce1b2768f651ff47eafb0 | e4526475632f078dccf34b76e71e5f4e3e44c24e | |||
v1.0 | complete | Codeforces | Codeforces_2445_C | def calculate_parallel_resistance(res_list):
# Calculate the parallel resistance of a list of resistors
pass
def find_closest_resistance(n, R, resistances):
""" Find the minimum absolute difference between the target resistance R and the closest achievable resistance using any combination of the n resistor... | from itertools import combinations
import math
def calculate_parallel_resistance(res_list):
# Return infinity if the list is empty to avoid division by zero
if not res_list:
return float('inf')
inverse_sum = sum(1/r for r in res_list)
if inverse_sum == 0:
return float('inf')
return ... | from solution import find_closest_resistance
def test_single_resistor():
assert find_closest_resistance(1, 10, [10]) == 0
def test_series_and_parallel():
assert find_closest_resistance(3, 4, [1, 2, 3]) == 1
def test_exact_match():
assert find_closest_resistance(2, 10, [10, 15]) == 0
def test_parallel_re... | [
{
"docstring": null,
"function_declaration": "def calculate_parallel_resistance(res_list):",
"function_name": "calculate_parallel_resistance",
"parameter_list": "(res_list)"
},
{
"docstring": null,
"function_declaration": "def find_closest_resistance(n, R, resistances):",
"function_n... | [
0,
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import itertools\nimport math\n\ndef closest_resistance(n, R, resistances):\n optimal_diff = float('inf')\n best_combination = ()\n\n for i in range(... | trial_gpt4o_7 | {
"original_instruction": "Bob likes to tinker with electronic circuits in his home workshop.\n\nHe has n resistors, each with a resistance value. Bob wants to create a circuit where the total resistance is as close as possible to a target resistance R. He can arrange the resistors in series or parallel, or even leav... | 0.485347 | Codeforces_2445 | C | [
"calculate_parallel_resistance",
"find_closest_resistance"
] | 2 | [
[
"find_closest_resistance",
"calculate_parallel_resistance"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 2388f28d8aca5a99e6519951f24222b0518e7e9d | 3a02592e5e5007b626138f4f8b0d513865b4904e | |||
v1.0 | complete | Codeforces | Codeforces_2344_C | from typing import List, Tuple
from math import sqrt
def number_of_clusters(n: int, t: int, points: List[Tuple[int, int]]) -> int:
""" Finds the number of unique clusters based on the given coordinates and distance threshold.
>>> number_of_clusters(5, 3, [(0, 0), (3, 0), (6, 0), (10, 0), (0, 4)]) # 3
>>> ... | from math import sqrt
from collections import deque
def euclidean_distance(x1, y1, x2, y2):
return sqrt((x1 - x2)**2 + (y1 - y2)**2)
def find_clusters(n, t, coordinates):
visited = [False] * n
clusters = 0
def bfs(start):
queue = deque([start])
visited[start] = True
while queu... | from solution import number_of_clusters
def test_example_input():
n = 5
t = 3
points = [(0, 0), (3, 0), (6, 0), (10, 0), (0, 4)]
assert number_of_clusters(n, t, points) == 3
def test_single_point():
n = 1
t = 3
points = [(0, 0)]
assert number_of_clusters(n, t, points) == 1
def test_al... | [
{
"docstring": null,
"function_declaration": "def euclidean_distance(x1, y1, x2, y2):",
"function_name": "euclidean_distance",
"parameter_list": "(x1, y1, x2, y2)"
},
{
"docstring": null,
"function_declaration": "def find_clusters(n, t, coordinates):",
"function_name": "find_clusters... | [
1,
0,
0,
1,
0,
1,
0,
1,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\n\ndef find_clusters(n, t, places):\n def euclidean_distance(p1, p2):\n return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)\n ... | trial_gpt4o_9 | {
"original_instruction": "A travel company is developing an itinerary application that helps users plan their trips. One of the features of the application is to group nearby places of interest into clusters so that users can visit multiple places in one trip. You are given a list of places, each represented by thei... | 0.68612 | Codeforces_2344 | C | [
"euclidean_distance",
"find_clusters",
"number_of_clusters"
] | 3 | [
[
"find_clusters",
"euclidean_distance"
],
[
"number_of_clusters",
"find_clusters"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e904e8b98203a76ec349020c1d4a1f4e47894c53 | f3319202c7a92400aab7b5f016fb4246460cb27f | |||
v1.0 | complete | Codeforces | Codeforces_1964_C | from typing import List, Tuple
def preprocess_matrix(matrix: List[List[int]]) -> List[List[int]]:
"""
Preprocess the matrix to create a prefix sum matrix.
:param matrix: 2D list of integers
:return: 2D prefix sum matrix
"""
# your code here
def sum_submatrix(prefix_sum: List[List[int]], r1: in... | def preprocess_matrix(matrix):
"""
Preprocess the matrix to create a prefix sum matrix.
:param matrix: 2D list of integers
:return: 2D prefix sum matrix
"""
n = len(matrix)
m = len(matrix[0])
prefix_sum = [[0] * (m+1) for _ in range(n+1)]
for i in range(1, n+1):
for j in... | from solution import preprocess_matrix, sum_submatrix, solve
def test_sum_submatrix():
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
prefix_sum = preprocess_matrix(matrix)
assert sum_submatrix(prefix_sum, 1, 1, 2, 2) == 12 # Sum of submatrix (1, 1) to (2, 2)
assert sum_subma... | [
{
"docstring": "Preprocess the matrix to create a prefix sum matrix.\n:param matrix: 2D list of integers\n:return: 2D prefix sum matrix",
"function_declaration": "def preprocess_matrix(matrix):",
"function_name": "preprocess_matrix",
"parameter_list": "(matrix)"
},
{
"docstring": "Calculate ... | [
1,
1,
1,
1,
1,
0,
1,
1,
1,
0
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def preprocess_matrix(matrix):\n \"\"\"\n Preprocess the given matrix to calculate the prefix sum matrix.\n \"\"\"\n n = len(matrix)\n m = len(... | trial_gpt4o_8 | {
"original_instruction": "You are given a matrix of size $$$n \\times m$$$ containing integers. Your task is to perform multiple queries on this matrix, where each query will ask you to calculate the sum of integers in a submatrix defined by its top-left and bottom-right coordinates.\n\nThe first line of input conta... | 0.574516 | Codeforces_1964 | C | [
"preprocess_matrix",
"sum_submatrix",
"solve"
] | 3 | [
[
"solve",
"preprocess_matrix"
],
[
"solve",
"sum_submatrix"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | e47e650dddef4145696ed18c1f1b6dac6f595a71 | fad9ddd5ca614bae8839e9f0220c6c73ecd14397 | |||
v1.0 | complete | Codeforces | Codeforces_1527_C | from typing import List
def find_subsets(nums: List[int]) -> List[List[int]]:
"""
Returns all possible non-empty subsets of nums.
:param nums: List of integers to find the subsets of.
:return: List of all non-empty subsets.
"""
pass
def unique_subsets(nums: List[int]) -> List[List[int]]:
... | import itertools
def find_subsets(nums):
"""
Returns all possible non-empty subsets of nums.
"""
subsets = []
for i in range(1, len(nums) + 1):
subsets.extend(itertools.combinations(nums, i))
return subsets
def unique_subsets(nums):
"""
Returns all non-empty unique subsets of n... | from solution import find_subsets, unique_subsets
def test_find_subsets():
assert sorted(find_subsets([1, 2, 2])) == sorted([
(1,), (2,), (2,),
(1, 2), (1, 2),
(2, 2),
(1, 2, 2)
])
def test_unique_subsets():
assert unique_subsets([1, 2, 2]) == [[1], [1, 2], [1, 2, 2], [2... | [
{
"docstring": "Returns all possible non-empty subsets of nums.",
"function_declaration": "def find_subsets(nums):",
"function_name": "find_subsets",
"parameter_list": "(nums)"
},
{
"docstring": "Returns all non-empty unique subsets of nums, sorted in lexicographical order.",
"function_d... | [
1,
0,
0,
0,
1,
1,
1,
1,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from itertools import combinations\n\ndef find_subsets(nums):\n \"\"\"\n Returns all non-empty subsets of the input list in non-descending order.\n \... | trial_gpt4o_8 | {
"original_instruction": "Write a function `find_subsets` that takes a list of n integers and returns all possible non-empty subsets of the list. Each subset should be presented in non-descending order of their elements. \n\nIn addition, create a function `unique_subsets` that ensures subsets with the same elements,... | 0.588607 | Codeforces_1527 | C | [
"find_subsets",
"unique_subsets"
] | 2 | [
[
"unique_subsets",
"find_subsets"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 27032eed54daae0989d6f35f21aa23c77d271323 | c25ce5d21382621384d07310ca972b32bcac3140 | |||
v1.0 | complete | Codeforces | Codeforces_1958_C | from typing import List
def count_good_subarrays(arr: List[int]) -> int:
""" Calculate the number of 'good' subarrays.
A subarray is defined as 'good' if it contains at least one element which is the sum of any two elements within that subarray.
Args:
arr (List[int]): The array of integers.
... | def count_good_subarrays(arr):
n = len(arr)
good_count = 0
for i in range(n):
for j in range(i, n):
seen_sums = set()
is_good = False
for k in range(i, j + 1):
for l in range(i, j + 1):
if k != l:
if... | from solution import number_of_good_subarrays
def test_small_array():
assert number_of_good_subarrays(3, [1, 2, 3]) == 3
assert number_of_good_subarrays(4, [1, 1, 1, 1]) == 6
assert number_of_good_subarrays(2, [1, 2]) == 1
def test_single_element():
assert number_of_good_subarrays(1, [5]) == 0
def te... | [
{
"docstring": null,
"function_declaration": "def count_good_subarrays(arr):",
"function_name": "count_good_subarrays",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def number_of_good_subarrays(n, arr):",
"function_name": "number_of_good_subarrays",
... | [
0,
0,
1,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def count_good_subarrays(arr):\n n = len(arr)\n good_subarray_count = 0\n\n for start in range(n):\n found_sums = set()\n for end in ra... | trial_gpt4o_2 | {
"original_instruction": "You are given an integer array $$$arr$$$ of size $$$n$$$. Let's define a subarray $$$arr[l:r]$$$ (where $$$1 \\leq l \\leq r \\leq n$$$) as *good* if it contains at least one element which is the sum of any two elements within that subarray. \n\nCalculate the number of *good* subarrays.\n\n... | 0.701572 | Codeforces_1958 | C | [
"count_good_subarrays",
"number_of_good_subarrays"
] | 2 | [
[
"number_of_good_subarrays",
"count_good_subarrays"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 6f17e8e174430fa5b57e807a79f8538ec816277f | 26edd34647c2ce4313cb19e549f9a07be55e4f9a | |||
v1.0 | complete | Codeforces | Codeforces_2360_C | from typing import List
def earliest_celebration_year(n: int, k: int, life_cycles: List[int]) -> int:
""" Determine the earliest year after the initial year (year 0) when all n types
of creatures can gather for the celebration, given that year is also a multiple of k.
>>> earliest_celebration_year(2, 12, [... | import math
from functools import reduce
def lcm(a, b):
return abs(a*b) // math.gcd(a, b)
def earliest_celebration_year(n, k, life_cycles):
# Finding the LCM of all life cycle lengths
lcm_all = reduce(lcm, life_cycles)
# Find the first year that is multiple of both lcm_all and k
if lcm_all % ... | from solution import earliest_celebration_year
def test_case_1():
assert earliest_celebration_year(2, 12, [3, 4]) == 12
def test_case_2():
assert earliest_celebration_year(3, 6, [2, 3, 4]) == 12
def test_case_3():
assert earliest_celebration_year(4, 15, [3, 5, 10, 15]) == 30
def test_case_4():
asser... | [
{
"docstring": null,
"function_declaration": "def lcm(a, b):",
"function_name": "lcm",
"parameter_list": "(a, b)"
},
{
"docstring": null,
"function_declaration": "def earliest_celebration_year(n, k, life_cycles):",
"function_name": "earliest_celebration_year",
"parameter_list": "... | [
0,
0,
0,
0,
0,
0,
1,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import math\nfrom functools import reduce\n\ndef lcm(a, b):\n \"\"\"Calculate the Least Common Multiple of two integers.\"\"\"\n return a * b // math.gc... | trial_gpt4o_7 | {
"original_instruction": "In a magical forest, there are n different types of mythical creatures. Each type of creature has its own characteristic length of life cycle. The life cycle length of the i-th type of creature is denoted by li. Every creature type starts its life cycle at the beginning of the year and live... | 0.550633 | Codeforces_2360 | C | [
"lcm",
"earliest_celebration_year"
] | 2 | [
[
"earliest_celebration_year",
"lcm"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ee5e85d8d9cd9a6da2e6868d8d3e9ac7173af100 | 43e0fb508ff201969529e733f9ec7fe5664669a5 | |||
v1.0 | complete | Codeforces | Codeforces_2827_C | def can_make_identical(a, b):
""" Determines if two arrays `a` and `b` can be made identical by multiplying elements by any prime number any number of times.
>>> can_make_identical([6, 4, 3, 9], [18, 4, 27, 3])
'YES'
>>> can_make_identical([2, 3, 5], [4, 9, 10])
'NO'
""" | def prime_factors(number):
"""
Returns the set of prime factors of a given number.
"""
i = 2
factors = set()
while i * i <= number:
while (number % i) == 0:
factors.add(i)
number //= i
i += 1
if number > 1:
factors.add(number)
return factor... | from solution import can_make_identical
def test_identical_arrays():
assert can_make_identical([1], [1]) == "YES"
assert can_make_identical([6, 4, 3, 9], [18, 4, 27, 3]) == "YES"
def test_different_arrays():
assert can_make_identical([2, 3, 5], [4, 9, 10]) == "NO"
def test_single_element_arrays()... | [
{
"docstring": "Returns the set of prime factors of a given number.",
"function_declaration": "def prime_factors(number):",
"function_name": "prime_factors",
"parameter_list": "(number)"
},
{
"docstring": "Determines if two arrays `a` and `b` can be made identical by multiplying elements by ... | [
0,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from math import gcd\n\ndef gcd_list(numbers):\n \"\"\"\n Computes the GCD of a list of numbers.\n \"\"\"\n current_gcd = numbers[0]\n for num ... | trial_gpt4o_1 | {
"original_instruction": "You are given two arrays of integers `a` and `b` of the same length `n`. You should determine if you can make the arrays identical by performing the following allowed operations any number of times:\n\n1. Select any index `i` in array `a` and multiply `a[i]` by any prime number.\n2. Select ... | 0.578984 | Codeforces_2827 | C | [
"prime_factors",
"can_make_identical"
] | 2 | [
[
"can_make_identical",
"prime_factors"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ec13460a5c39a4260aeb2acdbc865583044d5499 | 6f1a8792c99fb4d49be6e51fae4200c7810f3d09 | |||
v1.0 | complete | Codeforces | Codeforces_2845_C | def count_inversions(arr: List[int]) -> int:
""" Count the number of inversions in a sequence of integers.
An inversion is a pair of indices (i, j) such that i < j and arr[i] > arr[j].
>>> count_inversions([2, 3, 8, 6, 1])
5
>>> count_inversions([1, 2, 3, 4, 5])
0
>>> count_inversions([... | def merge_and_count(arr, temp_arr, left, mid, right):
i = left # Starting index for left subarray
j = mid + 1 # Starting index for right subarray
k = left # Starting index to be sorted
inv_count = 0
# Conditions are checked to ensure that i doesn't exceed mid and j doesn't exceed right
wh... | from solution import count_inversions
def test_single_element():
assert count_inversions([1]) == 0
def test_sorted_array():
assert count_inversions([1, 2, 3, 4, 5]) == 0
def test_reverse_sorted_array():
assert count_inversions([5, 4, 3, 2, 1]) == 10
def test_mixed_array():
assert count_inversions([2... | [
{
"docstring": null,
"function_declaration": "def merge_and_count(arr, temp_arr, left, mid, right):",
"function_name": "merge_and_count",
"parameter_list": "(arr, temp_arr, left, mid, right)"
},
{
"docstring": null,
"function_declaration": "def merge_sort_and_count(arr, temp_arr, left, r... | [
1,
1,
1,
0,
1,
0,
0,
1,
0,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def count_inversions(arr):\n \"\"\"\n Returns the number of inversions in the array `arr`.\n \"\"\"\n if not arr:\n return 0\n \n # A... | trial_gpt4o_9 | {
"original_instruction": "You are given a sequence of integers and you need to determine the number of inversions in the sequence. An inversion is a pair of indices (i, j) such that i < j and ai > aj. This is a common task in computer science and is often used to measure how far a given sequence is from being sorted... | 0.844885 | Codeforces_2845 | C | [
"merge_and_count",
"merge_sort_and_count",
"count_inversions"
] | 3 | [
[
"count_inversions",
"merge_sort_and_count"
],
[
"merge_sort_and_count",
"merge_and_count"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 6741f2ce42272eb40a03c58d48c13470dc785f03 | 44cd622d1e17eafea2e05c18cbb60493acbfd46d | |||
v1.0 | complete | Codeforces | Codeforces_2449_C | def level_order_traversal(arr: List[int]) -> List[List[int]]:
""" Reconstruct the binary tree from the given compressed form and perform a level-order traversal.
>>> level_order_traversal([1, 2, 3, -1, 4, 5, 6, -1, -1, 7, -1, -1]) [[1], [2, 3], [4, 5, 6], [7]]
>>> level_order_traversal([1, -1, 2, -1, 3, -1,... | from collections import deque
from typing import List, Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def buildTree(arr: List[int]) -> Optional[TreeNode]:
if not arr or arr[0] == -1:
return None
... | import pytest
from solution import level_order_traversal
def test_single_node():
arr = [1]
assert level_order_traversal(arr) == [[1]]
def test_complete_tree():
arr = [1, 2, 3, 4, 5, 6, 7]
assert level_order_traversal(arr) == [[1], [2, 3], [4, 5, 6, 7]]
def test_right_heavy_tree():
arr = [1, -1, 2... | [] | [
0,
1,
1,
1,
0,
0,
0,
0,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Optional\n\nclass TreeNode:\n def __init__(self, val=0):\n self.val = val\n self.left = None\n self.right = N... | trial_gpt4o_8 | {
"original_instruction": "You are given an array of integers where the array represents a binary tree in a compressed form. The root of the tree starts at the first element of the array, and each subsequent element either extends the current node or starts a new level in the tree.\n\nAn element at index i may have o... | 0.537493 | Codeforces_2449 | C | [
"buildTree",
"level_order_traversal"
] | 2 | [
[
"level_order_traversal",
"buildTree"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | a4cc5241a6506809c431e4f5e8115a071e929e3d | 02a981ab1a7bdce3a4d59ee31ea83b526df8d581 | |||
v1.0 | complete | Codeforces | Codeforces_2411_C | from typing import List
def update_difficulties(difficulties: List[int], i: int, d: int) -> None:
"""
Updates the difficulty of the i-th problem to d.
>>> diff = [4, 1, 7, 3, 2]
>>> update_difficulties(diff, 2, 6)
>>> diff
[4, 1, 6, 3, 2]
"""
pass
def minimum_difficulty_range(difficul... | def update_difficulties(difficulties, i, d):
"""
Updates the difficulty of the i-th problem to d.
"""
difficulties[i] = d
def minimum_difficulty_range(difficulties, k):
"""
Finds the minimum possible difficulty range for any subset of exactly k problems.
"""
# Sort the list of difficult... | import pytest
from solution import update_difficulties, minimum_difficulty_range, handle_queries
def test_update_difficulties():
difficulties = [4, 1, 7, 3, 2]
update_difficulties(difficulties, 2, 6)
assert difficulties == [4, 1, 6, 3, 2]
def test_minimum_difficulty_range():
difficulties = [4, 1, 7, 3... | [
{
"docstring": "Updates the difficulty of the i-th problem to d.",
"function_declaration": "def update_difficulties(difficulties, i, d):",
"function_name": "update_difficulties",
"parameter_list": "(difficulties, i, d)"
},
{
"docstring": "Finds the minimum possible difficulty range for any s... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from bisect import bisect_left, bisect_right, insort_left\n\ndef min_difficulty_range(n, q, initial_difficulties, queries):\n difficulties = sorted(initial... | trial_gpt4o_3 | {
"original_instruction": "You are organizing a programming competition, and you have a collection of $$$n$$$ problems. Each problem has a difficulty level associated with it, which is any integer between $$$1$$$ and $$$10^6$$$. \n\nYou want to create the most balanced problem set for the competition. A balanced prob... | 0.594754 | Codeforces_2411 | C | [
"update_difficulties",
"minimum_difficulty_range",
"handle_queries"
] | 3 | [
[
"handle_queries",
"minimum_difficulty_range"
],
[
"handle_queries",
"update_difficulties"
]
] | 2 | [
"handle_queries"
] | false | [] | false | pytest | true | [] | true | 510e598b2f7c1a8cc34b59d1205248214ffce90d | fe63faa21fae074de6381a061b99738f33d9cd30 | |||
v1.0 | complete | Codeforces | Codeforces_2254_C | def minimum_spanning_tree_cost(n: int, m: int, edge_list: List[Tuple[int, int, int]]) -> int:
""" Given an undirected graph with `n` nodes and `m` edges, where each edge has a weight of either 1 or 2,
find the minimum cost to connect all nodes in the graph using these edges (construct the Minimum Spanning Tree)... | class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [1] * n
def find(self, u):
if self.parent[u] != u:
self.parent[u] = self.find(self.parent[u])
return self.parent[u]
def union(self, u, v):
root_u = self.find(u)
root... | def test_case_1():
n, m = 4, 5
edges = [
(1, 2, 1),
(1, 3, 2),
(2, 3, 1),
(2, 4, 2),
(3, 4, 1)
]
assert minimum_spanning_tree_cost(n, m, edges) == 3
def test_case_2():
n, m = 3, 3
edges = [
(1, 2, 1),
(2, 3, 2),
(1, 3, 1)
]
... | [] | [
1,
1,
1,
1,
1,
1,
0,
0,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find(parent, x):\n if parent[x] != x:\n parent[x] = find(parent, parent[x])\n return parent[x]\n\ndef union(parent, rank, x, y):\n rootX =... | trial_gpt4o_8 | {
"original_instruction": "Given an undirected graph with $$$n$$$ nodes (numbered from 1 to $$$n$$$) and $$$m$$$ edges, each edge has a certain weight. The weight of an edge can be either 1 or 2. You are required to find the minimum cost to connect all nodes in the graph using these edges (construct the Minimum Spann... | 0.804053 | Codeforces_2254 | C | [
"find_minimum_spanning_tree",
"minimum_spanning_tree_cost"
] | 2 | [
[
"minimum_spanning_tree_cost",
"find_minimum_spanning_tree"
]
] | 1 | [] | false | [
"UnionFind"
] | true | pytest | false | [] | true | 26c4980a7a3369d418eedbe894e4762c88340a47 | 568eca1d85caab859270b6ee90be58cbc1312cb3 | |||
v1.0 | complete | Codeforces | Codeforces_2178_C | def minimum_toll_cost(n: int, m: int, roads: List[Tuple[int, int, int]]) -> int:
"""Compute the minimum total toll cost required to connect all cities to the capital (city with index 1) using a Minimum Spanning Tree (MST) approach.
Parameters:
n (int): number of cities
m (int): number of roads
... | 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]:
p... | def test_example_case():
n, m = 5, 7
roads = [
(1, 2, 3),
(1, 3, 4),
(2, 3, 2),
(2, 4, 5),
(3, 4, 1),
(3, 5, 6),
(4, 5, 2)
]
assert minimum_toll_cost(n, m, roads) == 8
def test_single_city():
n, m = 1, 0
roads = []
assert minimum_toll_... | [
{
"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,
1,
0,
0,
0,
0,
1,
0
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_mst_cost(n, m, roads):\n \"\"\"\n Returns the minimum total toll cost to connect all cities in the kingdom.\n \"\"\"\n # Implementing Kru... | trial_gpt4o_8 | {
"original_instruction": "In a kingdom, there are multiple cities connected by bidirectional roads. Each road is associated with a toll cost. The kingdom's government decided to build a new road network such that the total toll cost from one specific city, the capital, to all other cities is minimized. They plan to ... | 0.679759 | Codeforces_2178 | C | [
"find",
"union",
"minimum_toll_cost"
] | 3 | [
[
"minimum_toll_cost",
"find"
],
[
"minimum_toll_cost",
"union"
],
[
"union",
"find"
]
] | 3 | [] | false | [] | false | pytest | false | [] | true | 412f2b2810abd2f3800f5a30a77bfbd65fb3c038 | dcdf5735adcc044fef97926a6fd9c885eaf55e83 | |||
v1.0 | complete | Codeforces | Codeforces_2792_C | def max_path_sum(n: int, values: List[int], edges: List[Tuple[int, int]]) -> int:
""" Find the maximum path sum in a binary tree defined by values and edges.
>>> max_path_sum(5, [-10, 9, 20, 15, 7], [(1, 2), (1, 3), (3, 4), (3, 5)])
42
>>> max_path_sum(1, [5], [])
5
>>> max_path_sum(3, [-1, -2, ... | from typing import List, Tuple
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def build_tree(n: int, values: List[int], edges: List[Tuple[int, int]]) -> TreeNode:
if not n:
return None
nodes = {i... | from solution import max_path_sum
def test_example_case():
n = 5
values = [-10, 9, 20, 15, 7]
edges = [(1, 2), (1, 3), (3, 4), (3, 5)]
assert max_path_sum(n, values, edges) == 42
def test_single_node():
n = 1
values = [5]
edges = []
assert max_path_sum(n, values, edges) == 5
def test_... | [] | [
0,
0,
1,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List, Tuple, Dict\nimport sys\n\nclass TreeNode:\n def __init__(self, value):\n self.value = value\n self.left = None\n ... | trial_gpt4o_2 | {
"original_instruction": "You are given a binary tree where each node contains an integer value. Write a function to find the maximum path sum. The path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and ... | 0.69986 | Codeforces_2792 | C | [
"build_tree",
"max_path_sum"
] | 2 | [
[
"max_path_sum",
"build_tree"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 6dd2e54d4b2d0bead699ce5eca49e7f259114bc6 | c1cd1371cb484638ca74a6cb706b60c4943a8482 | |||
v1.0 | complete | Codeforces | Codeforces_1895_C | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def build_tree(nodes):
if not nodes:
return None
n = len(nodes)
node_dict = {i: TreeNode(val=nodes[i-1][0]) for i in range(1, n+1)}
for i in... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def build_tree(nodes):
if not nodes:
return None
n = len(nodes)
node_dict = {i: TreeNode(val=nodes[i-1][0]) for i in range(1, n+1)}
for i in... | def test_balanced_tree():
n = 5
nodes = [
(0, 2, 3),
(1, 4, 0),
(2, 0, 5),
(3, 0, 0),
(2, 0, 0)
]
assert plant_balance(n, nodes) == "Balanced"
def test_not_balanced_tree():
n = 3
nodes = [
(0, 2, 3),
(2, 0, 0),
(5, 0, 0)
]... | [] | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\ndef build_tree(nodes):\n ... | trial_gpt4o_3 | {
"original_instruction": "Bob is a botanist studying a unique type of plant with an unusual growth pattern. The plant is represented as a binary tree where each node corresponds to a part of the plant. Each node has a value representing the number of days since that part of the plant started growing. Bob wants to un... | 0.602749 | Codeforces_1895 | C | [
"build_tree",
"subtree_info",
"average_subtree",
"check_balanced",
"plant_balance"
] | 5 | [
[
"average_subtree",
"subtree_info"
],
[
"check_balanced",
"average_subtree"
],
[
"check_balanced",
"build_tree"
],
[
"plant_balance",
"check_balanced"
]
] | 4 | [] | false | [
"TreeNode"
] | true | pytest | false | [] | true | 03138f96b093caabd9e783535571a8c9f4fc1791 | fc43ccb57111fed65c73fa69a088c9c7cd106480 | |||
v1.0 | complete | Codeforces | Codeforces_2282_C | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def build_tree(values, edges):
""" Build a binary tree from given values and edges.
"""
nodes = [TreeNode(val) for val in values]
for a, b in edges:
a... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def build_tree(values, edges):
nodes = [TreeNode(val) for val in values]
for a, b in edges:
a -= 1
b -= 1
connect(nodes[a], nodes[b])
retu... | from solution import TreeNode, build_tree, maxPathSum
def test_maxPathSum_single_node():
root = TreeNode(val=5)
assert maxPathSum(root) == 5
def test_maxPathSum_two_nodes():
root = TreeNode(val=1)
root.left = TreeNode(val=2)
assert maxPathSum(root) == 3
def test_maxPathSum_three_nodes():
root... | [] | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, value=0):\n self.value = value\n self.left = None\n self.right = None\n\ndef maxPathSum(root):\n ... | trial_gpt4o_3 | {
"original_instruction": "You are given a binary tree with $$$n$$$ nodes. Each node in the tree has a value associated with it. Your task is to find the maximum sum of values from any path in the binary tree. A path is defined as a sequence of nodes where each pair of adjacent nodes in the sequence has an edge conne... | 0.640579 | Codeforces_2282 | C | [
"build_tree",
"connect",
"maxPathSum"
] | 3 | [
[
"build_tree",
"connect"
]
] | 1 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 9efe3bab5497b5e5c2468238353d630a5ad13518 | be20edd3eafc83ae06da3d0db4df3c9db153b7d3 | |||
v1.0 | complete | Codeforces | Codeforces_2258_C | def is_prime(num):
"""
Utility function to check if a number is prime.
"""
# Implementation here
def prime_matrix(n):
"""
Generate an n x n matrix filled with prime numbers in increasing order.
Args:
n (int): The size of the matrix.
Returns:
List[List[int]]: A 2D list ... | def is_prime(num):
"""
Utility function to check if a number is prime.
"""
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
def prime_matrix(n):
"""
Generate an n x n matrix filled with prime numbers in ... | from solution import is_prime, prime_matrix
def test_is_prime():
assert is_prime(2) == True
assert is_prime(3) == True
assert is_prime(4) == False
assert is_prime(11) == True
assert is_prime(1) == False
def test_prime_matrix_1x1():
expected = [[2]]
assert prime_matrix(1) == expected
def t... | [
{
"docstring": "Utility function to check if a number is prime.",
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": "Generate an n x n matrix filled with prime numbers in increasing order.",
"function_declaration": "def... | [
1,
0,
1,
1,
1,
1,
1,
1,
1,
0
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_prime(num):\n if num <= 1:\n return False\n if num == 2:\n return True\n if num % 2 == 0:\n return False\n for i in ra... | trial_gpt4o_7 | {
"original_instruction": "Emma is learning about prime numbers and wants to generate a prime matrix. A prime matrix is a matrix where all the elements are prime numbers.\n\nEmma wants you to help her generate a prime matrix of size n x n with prime numbers increasing row-wise and column-wise.\n\nYour task is to writ... | 0.722756 | Codeforces_2258 | C | [
"is_prime",
"prime_matrix"
] | 2 | [
[
"prime_matrix",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 009869ab13f212508311aab25fb81e80eb61fc51 | e553ba8da04662cff5df436ecc9ef77bf233599b | |||
v1.0 | complete | Codeforces | Codeforces_2943_C | def count_paths(grid: List[str]) -> int:
""" Calculate the number of different paths from the top-left corner to the bottom-right corner in a grid.
The input grid is a list of strings, where '.' indicates an open cell and '#' indicates a blocked cell.
You can only move right or down to an adjacent cell if i... | MOD = 1000000007
def count_paths(grid):
n = len(grid)
m = len(grid[0])
if grid[0][0] == '#' or grid[n-1][m-1] == '#':
return 0
dp = [[0] * m for _ in range(n)]
dp[0][0] = 1
for i in range(n):
for j in range(m):
if grid[i][j] == '#':
dp[... | from solution import number_of_paths_from_input
def test_case_1():
input_string = "3 3\n...\n.#.\n..."
assert number_of_paths_from_input(input_string) == 2
def test_case_2():
input_string = "3 3\n###\n###\n###"
assert number_of_paths_from_input(input_string) == 0
def test_case_3():
input_string =... | [
{
"docstring": null,
"function_declaration": "def count_paths(grid):",
"function_name": "count_paths",
"parameter_list": "(grid)"
},
{
"docstring": null,
"function_declaration": "def number_of_paths_from_input(input_string):",
"function_name": "number_of_paths_from_input",
"param... | [
0,
0,
0,
0,
1,
0,
0,
0,
1,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def num_paths(n, m, grid):\n MOD = 1000000007\n \n if grid[0][0] == '#' or grid[n-1][m-1] == '#':\n return 0\n\n dp = [[0] * m for _ in ran... | trial_gpt4o_9 | {
"original_instruction": "Consider a rectangular grid of cells with n rows and m columns. Each cell in the grid is either open (.) or blocked (#). You start from the top-left corner of the grid and want to reach the bottom-right corner. From your current cell, you can move to a directly adjacent cell to the right or... | 0.728355 | Codeforces_2943 | C | [
"count_paths",
"number_of_paths_from_input"
] | 2 | [
[
"number_of_paths_from_input",
"count_paths"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7f73d50a7f15405443b682bddfb56cc28a44aeae | 1ce65010a5be2bc6452436ce019cc1e38e7853d2 | |||
v1.0 | complete | Codeforces | Codeforces_1484_C | from typing import List, Tuple
def graph_path_exists(n: int, m: int, k: int, edges: List[Tuple[int, int, int]]) -> str:
"""
Determine if there exists a path between any two vertices such that the sum of weights along the path equals k.
Parameters:
n (int): Number of vertices
m (int): Number o... | import collections
from itertools import product
def does_path_exist(n, m, k, edges):
"""
Returns "YES" if there exists any path between any two vertices such that the sum of weights
along the path equals k. Otherwise, returns "NO".
"""
graph = collections.defaultdict(list)
for u, v, w in ... | from solution import graph_path_exists
def test_case_1():
n = 5
m = 6
k = 7
edges = [(1, 2, 3),
(2, 3, 4),
(1, 3, 5),
(3, 4, 2),
(2, 5, 1),
(4, 5, -1)]
assert graph_path_exists(n, m, k, edges) == "YES"
def test_case_2():
n = 3
... | [
{
"docstring": "Returns \"YES\" if there exists any path between any two vertices such that the sum of weights\nalong the path equals k. Otherwise, returns \"NO\".",
"function_declaration": "def does_path_exist(n, m, k, edges):",
"function_name": "does_path_exist",
"parameter_list": "(n, m, k, edges... | [
0,
1,
0,
0,
0,
0,
0,
0,
0,
1
] | 2 | hard | 0.2 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import defaultdict, deque\n\ndef has_path_with_sum(n, m, k, edges):\n \"\"\"\n Determine if there exists any path between any two verti... | trial_gpt4o_9 | {
"original_instruction": "You are given an undirected graph with $$$n$$$ vertices and $$$m$$$ edges. Each edge has a weight associated with it. Your task is to determine if there exists a path between any two vertices such that the sum of weights along the path equals $$$k$$$.\n\nInput:\n- The first line contains th... | 0.687322 | Codeforces_1484 | C | [
"does_path_exist",
"graph_path_exists"
] | 2 | [
[
"graph_path_exists",
"does_path_exist"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | b4cc503e70f2c5c6fa5d010864f5b9a80b01de12 | 0143d633bc998d5e8e93135e62b76f7219b04fa9 | |||
v1.0 | complete | Codeforces | Codeforces_1458_C | from typing import List
def shortest_path_matrix(n: int, matrix: List[List[int]]) -> List[List[int]]:
"""
Computes the length of the shortest path between every pair of clearings.
:param n: The number of clearings.
:param matrix: The adjacency matrix representing path lengths.
:return: A matri... | def floyd_warshall(n, graph):
"""
Uses Floyd-Warshall algorithm to find the shortest paths between all pairs of clearings.
:param n: Number of clearings.
:param graph: Adjacency matrix representing path lengths.
:return: Matrix of shortest paths between all pairs of clearings.
"""
# Ini... | from solution import shortest_path_matrix
def test_shortest_path_example():
input_matrix = [
[0, 3, -1, 7],
[3, 0, 2, 8],
[-1, 2, 0, 1],
[7, 8, 1, 0]
]
expected_output = [
[0, 3, 5, 6],
[3, 0, 2, 3],
[5, 2, 0, 1],
[6, 3, 1, 0]
]
assert... | [
{
"docstring": "Uses Floyd-Warshall algorithm to find the shortest paths between all pairs of clearings.\n\n:param n: Number of clearings.\n:param graph: Adjacency matrix representing path lengths.\n:return: Matrix of shortest paths between all pairs of clearings.",
"function_declaration": "def floyd_warsha... | [
1,
0,
1,
0,
1,
0,
1,
0,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def floyd_warshall(n, graph):\n # Prepare the distance matrix, using float('inf') for non-existent paths\n dist = [[float('inf')] * n for _ in range(n)]... | trial_gpt4o_9 | {
"original_instruction": "A forest has several clearings, connected by surprisingly straight paths. Adventurers traveling from one point to another often encounter multiple possible routes between the same pair of clearings. However, thick forest growth and active wildlife make travel between clearings difficult, so... | 0.66173 | Codeforces_1458 | C | [
"floyd_warshall",
"shortest_path_matrix"
] | 2 | [
[
"shortest_path_matrix",
"floyd_warshall"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | fd501230fba23a2ead114d7c9f4708bc12778364 | a1054df49ce6ad08342a9b69ee95e022d91960d2 | |||
v1.0 | complete | Codeforces | Codeforces_3119_C | from typing import List, Tuple
def find_pairs(N: int) -> List[Tuple[int, int]]:
"""
Returns the number of distinct pairs (a, b) such that a * b = N,
and the pairs themselves in ascending order based on the value of a.
>>> find_pairs(12)
[(1, 12), (2, 6), (3, 4)]
>>> find_pairs(25)
[(1, 25)... | def find_pairs(N):
"""
Returns the number of distinct pairs (a, b) such that a * b = N,
and the pairs themselves in ascending order based on the value of a.
"""
pairs = []
for a in range(1, int(N**0.5) + 1):
if N % a == 0:
b = N // a
pairs.append((a, b))
retu... | from solution import find_pairs, distinct_pairs
def test_find_pairs_12():
assert find_pairs(12) == [(1, 12), (2, 6), (3, 4)]
def test_find_pairs_25():
assert find_pairs(25) == [(1, 25), (5, 5)]
def test_find_pairs_1():
assert find_pairs(1) == [(1, 1)]
def test_find_pairs_100():
assert find_pairs(100... | [
{
"docstring": "Returns the number of distinct pairs (a, b) such that a * b = N, \nand the pairs themselves in ascending order based on the value of a.",
"function_declaration": "def find_pairs(N):",
"function_name": "find_pairs",
"parameter_list": "(N)"
},
{
"docstring": null,
"function... | [
1,
1,
0,
1,
0,
0,
0,
0,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_pairs(N):\n \"\"\"\n Returns the number of distinct pairs (a, b) such that a * b = N, \n and the pairs themselves sorted in ascending order ... | trial_gpt4o_9 | {
"original_instruction": "You are given a positive integer N (1 ≤ N ≤ 1000). Your task is to determine how many distinct pairs of positive integers (a, b) satisfy the condition:\n\na * b = N\n\nThe format of the input and output should be as follows:\n\n**Input:**\nThe input contains a single integer N.\n\n**Output:... | 0.653709 | Codeforces_3119 | C | [
"find_pairs",
"distinct_pairs"
] | 2 | [
[
"distinct_pairs",
"find_pairs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | dd7897b5dc4c4fd3042bee72bb8a8be7a07a8b1b | 1a8878da8f74d1d51104c8a34145b63e405f1e36 | |||
v1.0 | complete | Codeforces | Codeforces_2967_C | def count_connected_components(t: int, test_cases: List[Tuple[int, int, List[Tuple[int, int]]]]) -> List[int]:
"""
Given an undirected graph, determine the number of connected components in the graph.
A connected component is a maximal set of vertices such that there is a path between any two vertices in t... | def dfs(node, graph, visited):
"""
Depth-First Search (DFS) to traverse the graph and mark all nodes in the same connected component.
"""
stack = [node]
while stack:
current = stack.pop()
for neighbor in graph[current]:
if not visited[neighbor]:
visited[ne... | from solution import count_connected_components
def test_single_node():
assert count_connected_components(1, [(1, 0, [])]) == [1]
def test_no_edges():
assert count_connected_components(1, [(4, 0, [])]) == [4]
def test_connected_graph():
assert count_connected_components(1, [(5, 4, [(1, 2), (2, 3), (3, 4)... | [
{
"docstring": "Depth-First Search (DFS) to traverse the graph and mark all nodes in the same connected component.",
"function_declaration": "def dfs(node, graph, visited):",
"function_name": "dfs",
"parameter_list": "(node, graph, visited)"
},
{
"docstring": null,
"function_declaration"... | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_connected_components(t, test_cases):\n def dfs(node, visited, adj_list):\n stack = [node]\n while stack:\n current = stac... | trial_gpt4o_9 | {
"original_instruction": "Given an undirected graph, we want to determine the number of connected components in the graph. A connected component is a maximal set of vertices such that there is a path between any two vertices in this set.\n\nYou are provided with multiple test cases to analyze. Each test case consist... | 0.668762 | Codeforces_2967 | C | [
"dfs",
"count_connected_components"
] | 2 | [
[
"count_connected_components",
"dfs"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 4bf2a0825825067e8b71f6319e9125e9228fea14 | 97b327757eeba6e88c76d63866f2b986a64b655c | |||
v1.0 | complete | Codeforces | Codeforces_1868_C | def preprocess(arr):
""" Preprocess the array to compute prefix products modulo 1000000007.
Args:
arr (List[int]): The input array.
Returns:
List[int]: The prefix products array.
"""
pass
def product_query(prefix_prod, l, r):
""" Compute the product of elements in the subarray arr[... | MOD = 1000000007
def preprocess(arr):
n = len(arr)
prefix_prod = [1] * (n + 1)
for i in range(1, n + 1):
prefix_prod[i] = (prefix_prod[i - 1] * arr[i - 1]) % MOD
return prefix_prod
def product_query(prefix_prod, l, r):
if l == 1:
return prefix_prod[r]
return (prefix_prod[r] *... | from solution import preprocess, product_query, process_queries
def test_preprocess():
arr = [1, 2, 3, 4, 5]
expected = [1, 1, 2, 6, 24, 120]
assert preprocess(arr) == expected
def test_product_query():
prefix_prod = preprocess([1, 2, 3, 4, 5])
assert product_query(prefix_prod, 1, 3) == 6
asse... | [
{
"docstring": null,
"function_declaration": "def preprocess(arr):",
"function_name": "preprocess",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def product_query(prefix_prod, l, r):",
"function_name": "product_query",
"parameter_list": "(prefix_prod... | [
0,
0,
0,
1,
0,
1,
0,
0,
0,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "MOD = 1000000007\n\ndef product_subarray(arr, queries):\n n = len(arr)\n prefix_prods = [1] * (n + 1)\n \n for i in range(1, n + 1):\n pref... | trial_gpt4o_9 | {
"original_instruction": "You are given an array of integers `arr` of length `n` (1 ≤ n ≤ 100,000). You need to process `q` queries. Each query is described by integers `l` and `r` (1 ≤ l ≤ r ≤ n). For each query, you have to return the product of all elements in the subarray `arr[l:r]` modulo `1000000007`.\n\nThe f... | 0.601419 | Codeforces_1868 | C | [
"preprocess",
"product_query",
"process_queries"
] | 3 | [
[
"process_queries",
"preprocess"
],
[
"process_queries",
"product_query"
]
] | 2 | [
"process_queries"
] | false | [] | false | pytest | true | [] | true | b46619fa86e123a75310bf25089b6c2e86877633 | a3ce2042904cb682478d992e75d0650f2aa85b27 | |||
v1.0 | complete | Codeforces | Codeforces_3167_C | def min_max_distance(N: int, K: int, roads: List[Tuple[int, int]]) -> int:
""" Determine the minimum possible maximum distance between any city and the closest castle in Treeland.
>>> min_max_distance(7, 2, [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7)])
3
>>> min_max_distance(1, 1, [])
0
>>> ... | from collections import deque, defaultdict
def bfs_longest(node, adjacency_list):
queue = deque([(node, 0)])
visited = set()
visited.add(node)
farthest_node = node
max_distance = 0
while queue:
current, distance = queue.popleft()
for neighbor in adjacency_list[current]:
... | import pytest
from solution import min_max_distance
def test_example_case():
N = 7
K = 2
roads = [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7)]
assert min_max_distance(N, K, roads) == 3
def test_single_city():
N = 1
K = 1
roads = []
assert min_max_distance(N, K, roads) == 0
def test... | [
{
"docstring": null,
"function_declaration": "def bfs_longest(node, adjacency_list):",
"function_name": "bfs_longest",
"parameter_list": "(node, adjacency_list)"
},
{
"docstring": null,
"function_declaration": "def min_max_distance(N, K, roads):",
"function_name": "min_max_distance",... | [
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque, defaultdict\n\ndef bfs_longest(node, adjacency_list):\n queue = deque([(node, 0)])\n visited = set()\n visited.add(nod... | trial_gpt4o_0 | {
"original_instruction": "The ancient kingdom of Treeland is composed of $$$N$$$ cities connected by $$$N-1$$$ roads, forming a tree structure. The king wants to fortify Treeland by placing castles in some of the cities. To ensure efficient administration, the king requires each castle to control a segment of cities... | 0.633302 | Codeforces_3167 | C | [
"bfs_longest",
"min_max_distance",
"can_place_castles"
] | 3 | [
[
"min_max_distance",
"bfs_longest"
],
[
"min_max_distance",
"can_place_castles"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | f2b46205545163d370571d90a47c2ebd093cb97f | fa7d58ae45309dbc5cf3fe83e4bc1f1de5d9b700 | |||
v1.0 | complete | Codeforces | Codeforces_2314_C | def min_max_toll(n: int, m: int, roads: List[Tuple[int, int, int]]) -> int:
""" In a mysterious land, there are n cities and multiple bidirectional roads connecting pairs of these cities. Each road has a certain toll cost. The king of the land wants to travel from his capital city to all other cities. He demands to... | def can_travel_with_max_toll(n, roads, max_toll):
from collections import deque, defaultdict
graph = defaultdict(list)
for u, v, w in roads:
if w <= max_toll:
graph[u].append(v)
graph[v].append(u)
visited = set()
queue = deque([1])
visited.add(1)... | from solution import min_max_toll
def test_case_1():
n, m = 3, 3
roads = [(1, 2, 4), (2, 3, 3), (1, 3, 5)]
assert min_max_toll(n, m, roads) == 4
def test_case_2():
n, m = 4, 4
roads = [(1, 2, 1), (1, 3, 4), (3, 4, 2), (2, 4, 3)]
assert min_max_toll(n, m, roads) == 3
def test_case_3():
n, ... | [
{
"docstring": null,
"function_declaration": "def can_travel_with_max_toll(n, roads, max_toll):",
"function_name": "can_travel_with_max_toll",
"parameter_list": "(n, roads, max_toll)"
},
{
"docstring": null,
"function_declaration": "def min_max_toll(n, m, roads):",
"function_name": "... | [
0,
0,
1,
0,
1,
1,
0,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class UnionFind:\n def __init__(self, n):\n self.parent = list(range(n))\n self.rank = [1] * n\n\n def find(self, p):\n if self.par... | trial_gpt4o_4 | {
"original_instruction": "In a mysterious land, there are n cities and multiple bidirectional roads connecting pairs of these cities. Each road has a certain toll cost. The king of the land wants to travel from his capital city to all other cities. He demands to find the path that minimizes the maximum toll cost he ... | 0.728979 | Codeforces_2314 | C | [
"can_travel_with_max_toll",
"min_max_toll"
] | 2 | [
[
"min_max_toll",
"can_travel_with_max_toll"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | f93de723424848fbf1b33839138e872d451d027d | 5b4124fe78a0f9cccff22daa65a5daa596e20005 | |||
v1.0 | complete | Codeforces | Codeforces_3513_C | def count_k_palindromes(s: str, k: int) -> int:
"""
Count the number of substrings in `s` that are k-palindromes.
A k-palindrome is a substring that can be transformed into a palindrome by changing at most `k` characters.
:param s: The input string consisting of lowercase English letters.
:param k... | def is_k_palindrome(sub, k):
"""
Check if the substring `sub` can be converted to a palindrome by changing at most `k` characters.
"""
l = len(sub)
mismatch_count = 0
for i in range(l // 2):
if sub[i] != sub[l - 1 - i]:
mismatch_count += 1
if mismatch_count >... | from solution import count_k_palindromes
def test_single_character():
assert count_k_palindromes("a", 0) == 1
assert count_k_palindromes("a", 1) == 1
def test_multiple_characters():
assert count_k_palindromes("ab", 0) == 2
assert count_k_palindromes("ab", 1) == 3
def test_example_case():
assert c... | [
{
"docstring": "Check if the substring `sub` can be converted to a palindrome by changing at most `k` characters.",
"function_declaration": "def is_k_palindrome(sub, k):",
"function_name": "is_k_palindrome",
"parameter_list": "(sub, k)"
},
{
"docstring": "Count the number of substrings in `s... | [
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_k_palindrome(sub, k):\n \"\"\"\n Check if the substring `sub` can be converted to a palindrome by changing at most `k` characters.\n \"\"\"\n ... | trial_gpt4o_0 | {
"original_instruction": "You are given a string s, which consists of lowercase English characters only. A substring of s is defined as any contiguous sequence of characters within s. A k-palindrome is a substring that can be transformed into a palindrome by changing at most k characters.\n\nYour task is to find the... | 0.746312 | Codeforces_3513 | C | [
"is_k_palindrome",
"count_k_palindromes"
] | 2 | [
[
"count_k_palindromes",
"is_k_palindrome"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 809bb93ef40fe5f1e2684df16a4c2bed681a456c | 0520ee4e5c616963d724c6cf4c042df0dc41e83d | |||
v1.0 | complete | Codeforces | Codeforces_2496_C | def longest_palindromic_prime_subsequence(n: int, arr: List[int]) -> int:
""" Finds the length of the longest sub-sequence of a given list of integers that forms a palindromic prime sequence.
>>> longest_palindromic_prime_subsequence(6, [2, 3, 5, 7, 11, 13]) == 0
>>> longest_palindromic_prime_subsequence(7,... | def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i != 0:
continue
return False
return True
def longest_palindromic_prime_subsequence(n, arr):
primes = [num for num in arr if is_prime(num)]
if not primes:
re... | from solution import longest_palindromic_prime_subsequence
def test_no_primes():
assert longest_palindromic_prime_subsequence(6, [4, 6, 8, 9, 10, 12]) == 0
def test_no_palindrome_with_primes():
assert longest_palindromic_prime_subsequence(6, [2, 3, 5, 7, 11, 13]) == 1
def test_single_prime_sequence():
as... | [
{
"docstring": null,
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def longest_palindromic_prime_subsequence(n, arr):",
"function_name": "longest_palindromic_prime_subsequence",
... | [
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_palindrome(s):\n return s == s[::-1]\n\ndef is_prime(num):\n if num <= 1:\n return False\n for i in range(2, int(num**0.5) + 1):\n ... | trial_gpt4o_4 | {
"original_instruction": "Sarah loves prime numbers and palindrome sequences. She recently came across a sequence of positive integers and wondered if she could extract a sub-sequence from it that is both a prime sequence and a palindrome.\n\nA sub-sequence is a sequence that can be derived from another sequence by ... | 0.695512 | Codeforces_2496 | C | [
"is_prime",
"longest_palindromic_prime_subsequence"
] | 2 | [
[
"longest_palindromic_prime_subsequence",
"is_prime"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 863bfa0a2f652fdb2e0c1dc4e085d79e2f9ede02 | 0a800a7a4e1fd2a786cb743fc930a65220480bca | |||
v1.0 | complete | Codeforces | Codeforces_3580_C | def gcd(a: int, b: int) -> int:
"""
Returns the greatest common divisor of a and b using the Euclidean algorithm.
"""
pass
def euler_totient(n: int) -> int:
"""
Returns the value of Euler's Totient function φ(n), which counts the number
of positive integers up to n that are relatively prim... | def gcd(a, b):
"""
Returns the greatest common divisor of a and b using the Euclidean algorithm.
"""
while b != 0:
a, b = b, a % b
return a
def euler_totient(n):
"""
Returns the value of Euler's Totient function φ(n), which counts the number
of positive integers up to n that ar... | from solution import euler_totient
def test_euler_totient_1():
assert euler_totient(1) == 1
def test_euler_totient_10():
assert euler_totient(10) == 4
def test_euler_totient_2():
assert euler_totient(2) == 1
def test_euler_totient_3():
assert euler_totient(3) == 2
def test_euler_totient_4():
as... | [
{
"docstring": "Returns the greatest common divisor of a and b using the Euclidean algorithm.",
"function_declaration": "def gcd(a, b):",
"function_name": "gcd",
"parameter_list": "(a, b)"
},
{
"docstring": "Returns the value of Euler's Totient function φ(n), which counts the number \nof pos... | [
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def euler_totient(n):\n \"\"\"\n Computes the value of Euler's Totient function φ(n).\n \"\"\"\n if n == 1:\n return 1\n \n result = ... | trial_gpt4o_9 | {
"original_instruction": "Anastasia is a brilliant mathematician who recently started exploring number theory. She has become fascinated with the concept of prime numbers and their properties. Recently, she came across Euler's Totient function, φ(n), which counts the number of positive integers up to n that are rela... | 0.730113 | Codeforces_3580 | C | [
"gcd",
"euler_totient"
] | 2 | [
[
"euler_totient",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 500feeb8b8ac1cdee885ed311c17b7a15dd8873c | deec4e5614229605e9e5cb541848ed118bfc7a3b | |||
v1.0 | complete | Codeforces | Codeforces_3387_C | class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def build_tree(nodes):
node_dict = {}
root = None
for value, left, right in nodes:
if value not in node_dict:
node_dict[value] = TreeNode(value)
if left ... | class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def build_tree(nodes):
node_dict = {}
root = None
for value, left, right in nodes:
if value not in node_dict:
node_dict[value] = TreeNode(value)
if left ... | import pytest
from solution import find_tree_depth
def test_tree_depth_1():
n = 5
node_data = [
"1 2 3",
"2 4 5",
"3 0 0",
"4 0 0",
"5 0 0"
]
assert find_tree_depth(n, node_data) == 3
def test_tree_depth_2():
n = 1
node_data = ["1 0 0"]
assert find_t... | [] | [
1,
1,
1,
0,
0,
1,
1,
0,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_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 bu... | trial_gpt4o_6 | {
"original_instruction": "Your friend Bob loves learning about binary trees. However, he is struggling with understanding how to calculate the depth of a binary tree. Can you help him out by writing a function to determine the depth of a given binary tree?\n\nIn this problem, the depth (or height) of a binary tree i... | 0.598963 | Codeforces_3387 | C | [
"build_tree",
"tree_depth",
"find_tree_depth"
] | 3 | [
[
"find_tree_depth",
"build_tree"
],
[
"find_tree_depth",
"tree_depth"
]
] | 2 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | f3b5d5c644fe95c921990837d2120140799f2b04 | c08f738be78de760e6ddc5dcdd6b033e6998af8d | |||
v1.0 | complete | Codeforces | Codeforces_3881_C | def is_star_possible(n: int, k: int) -> str:
"""
Determines if a non-degenerate star can be drawn using all vertices exactly once,
and returns the sequence of vertices if possible.
>>> is_star_possible(5, 2)
'YES\n1 3 5 2 4'
>>> is_star_possible(6, 2)
'NO'
>>> is_star_possible(7, 3)... | def is_star_possible(n, k):
"""
Determines if a non-degenerate star can be drawn using all vertices exactly once,
and returns the sequence of vertices if possible.
"""
if n % k == 0 or gcd(n, k) != 1:
return "NO"
sequence = []
current_vertex = 0
for _ in range(n):
s... | from solution import is_star_possible
def test_example_1():
assert is_star_possible(5, 2) == "YES\n1 3 5 2 4"
def test_example_2():
assert is_star_possible(6, 2) == "NO"
def test_prime_number_sides():
assert is_star_possible(7, 3) == "YES\n1 4 7 3 6 2 5"
def test_small_polygon():
assert is_star_... | [
{
"docstring": "Determines if a non-degenerate star can be drawn using all vertices exactly once, \nand returns the sequence of vertices if possible.",
"function_declaration": "def is_star_possible(n, k):",
"function_name": "is_star_possible",
"parameter_list": "(n, k)"
},
{
"docstring": "Re... | [
0,
1,
0,
0,
1,
0,
0,
1,
1,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_star_possible(n, k):\n \"\"\"\n Determines if a non-degenerate star can be drawn using all vertices exactly once. \n If possible, it returns \... | trial_gpt4o_7 | {
"original_instruction": "Petya is also fond of different shapes and today he is playing with an n-sided regular polygon. He wants to draw a star within the polygon by connecting some of its vertices in a specific sequence. The sequence rules are as follows:\n\n1. You start at vertex 1, then move to vertex k, then t... | 0.559901 | Codeforces_3881 | C | [
"is_star_possible",
"gcd"
] | 2 | [
[
"is_star_possible",
"gcd"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | e35191f11f6626e648b64dfed7b507d93ddcb465 | 62d861364cb34d092a080df9ff0ca0479b160362 | |||
v1.0 | complete | Codeforces | Codeforces_2958_C | def is_peak(arr: List[int], x: int) -> str:
"""
Determine if a given integer x is a peak element of the array.
The array first strictly increases, then strictly decreases.
A peak element is defined as an element that is greater than its immediate neighbors.
>>> is_peak([1, 3, 8, 12, 4, 2, 1], 1... | def find_peak_index(arr):
"""
Utility function to find the peak index in a mountain array.
"""
left, right = 0, len(arr) - 1
while left < right:
mid = (left + right) // 2
if arr[mid] < arr[mid + 1]:
left = mid + 1
else:
right = mid
return left
def... | from solution import is_peak
def test_peak_element():
arr = [1, 3, 8, 12, 4, 2, 1]
assert is_peak(arr, 12) == "YES"
assert is_peak(arr, 3) == "NO"
assert is_peak(arr, 5) == "NO"
def test_no_peak():
arr = [1, 2, 3, 2, 1]
assert is_peak(arr, 4) == "NO"
assert is_peak(arr, 1) == "NO"
def tes... | [
{
"docstring": "Utility function to find the peak index in a mountain array.",
"function_declaration": "def find_peak_index(arr):",
"function_name": "find_peak_index",
"parameter_list": "(arr)"
},
{
"docstring": "Returns \"YES\" if x is a peak element in the mountain array arr, otherwise \"N... | [
1,
1,
1,
1,
1,
1,
0,
0,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_peak(n, array, queries):\n peaks = []\n\n for i in range(1, n - 1):\n if array[i - 1] < array[i] > array[i + 1]:\n peaks.appe... | trial_gpt4o_8 | {
"original_instruction": "You are given an array consisting of $$$n$$$ integers. The array follows a specific pattern: it first strictly increases, then strictly decreases. Your task is to efficiently answer multiple queries regarding the given array. Each query asks you to determine if a given integer $$$x$$$ is a ... | 0.66149 | Codeforces_2958 | C | [
"find_peak_index",
"is_peak"
] | 2 | [
[
"is_peak",
"find_peak_index"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 24d87916678f0ff576188ea7043225266907f40c | 0c52ba4113a7fae835c8942a98150fac084a0b9e | |||
v1.0 | complete | Codeforces | Codeforces_3280_C | from typing import List, Tuple
def prefix_sums(arr: List[int]) -> List[int]:
"""
This function returns the prefix sums array for a given input array.
>>> prefix_sums([3, 2, 4, 5, 1, 6]) == [0, 3, 5, 9, 14, 15, 21]
>>> prefix_sums([1, 2, 3]) == [0, 1, 3, 6]
"""
pass
def range_sum(prefix: List[i... | def prefix_sums(arr):
"""
This function returns the prefix sums array for a given input array.
"""
n = len(arr)
prefix = [0] * (n + 1)
for i in range(1, n + 1):
prefix[i] = prefix[i - 1] + arr[i - 1]
return prefix
def range_sum(prefix, i, j):
"""
This function returns the su... | from solution import prefix_sums, range_sum, solve
def test_prefix_sums():
assert prefix_sums([3, 2, 4, 5, 1, 6]) == [0, 3, 5, 9, 14, 15, 21]
assert prefix_sums([1, 2, 3]) == [0, 1, 3, 6]
def test_range_sum():
prefix = prefix_sums([3, 2, 4, 5, 1, 6])
assert range_sum(prefix, 1, 3) == 9
assert rang... | [
{
"docstring": "This function returns the prefix sums array for a given input array.",
"function_declaration": "def prefix_sums(arr):",
"function_name": "prefix_sums",
"parameter_list": "(arr)"
},
{
"docstring": "This function returns the sum of the elements from index i to j (inclusive)\nus... | [
1,
1,
1,
1,
1,
1,
1,
0,
1,
0
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def cumulative_sum(n, q, array, queries):\n prefix_sum = [0] * (n + 1)\n \n # Calculating prefix sums\n for i in range(1, n + 1):\n prefix_... | trial_gpt4o_8 | {
"original_instruction": "Given a list of n integers and q queries, each query asks about the sum of all integers between indices i and j in the list. Your task is to output these sums for each query.\n\nThe first line contains two integers n and q (1 ≤ n, q ≤ 100,000), the number of elements in the list and the num... | 0.650864 | Codeforces_3280 | C | [
"prefix_sums",
"range_sum",
"solve"
] | 3 | [
[
"solve",
"prefix_sums"
],
[
"solve",
"range_sum"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | cddcb5d8d529ab21227b6755d2485379a766e4b9 | ddad86cc21e2a4fd397cc09ab0d5a3d714a28192 | |||
v1.0 | complete | Codeforces | Codeforces_1985_C | def min_train_routes(n: int, m: int, p: int, edges: List[Tuple[int, int, int]]) -> Union[List[Tuple[int, int, int]], str]:
""" In a country called Arithmus, determine if it is possible to add at most p new train routes to achieve full connectivity
between all n cities. If possible, return the roads used; other... | def find_connected_components(n, edges):
from collections import defaultdict, deque
graph = defaultdict(list)
for u, v, l in edges:
graph[u].append(v)
graph[v].append(u)
visited = [False] * (n + 1)
components = []
def bfs(start):
queue = deque([start])
... | def test_min_train_routes():
input_data = "4 4 1\n1 2 5\n2 3 3\n3 4 7\n4 1 2\n"
expected_result = "1 2 5\n2 3 3\n3 4 7\n4 1 2"
assert solve(input_data) == expected_result
def test_min_train_routes_impossible():
input_data = "4 2 0\n1 2 5\n3 4 7\n"
expected_result = "IMPOSSIBLE"
assert solve(inp... | [
{
"docstring": null,
"function_declaration": "def find_connected_components(n, edges):",
"function_name": "find_connected_components",
"parameter_list": "(n, edges)"
},
{
"docstring": null,
"function_declaration": "def min_train_routes(n, m, p, edges):",
"function_name": "min_train_r... | [
0,
0,
0,
0,
1,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_connected_components(n, edges):\n parent = list(range(n))\n\n def find(x):\n if parent[x] != x:\n parent[x] = find(parent[x])... | trial_gpt4o_4 | {
"original_instruction": "In a country called Arithmus, there are n cities (numbered from 1 to n) connected by m directed roads, where each road has a certain length. Additionally, each road connects two different cities. The road network is currently represented as a directed graph with n vertices and m edges.\n\nT... | 0.710123 | Codeforces_1985 | C | [
"find_connected_components",
"min_train_routes",
"solve"
] | 3 | [
[
"min_train_routes",
"find_connected_components"
],
[
"solve",
"min_train_routes"
]
] | 2 | [] | false | [] | false | pytest | false | [] | true | 95e2967a03186c7df39570507b17e3664c3d9081 | a26a630eadd00d5d74e6403e4b567b5cbe2ec61f | |||
v1.0 | complete | Codeforces | Codeforces_4124_C | def get_max_product_of_subarray(n: int, array: List[int]) -> int:
""" Computes the maximum product of any subarray.
Args:
n (int): Number of elements in the array.
array (List[int]): List of positive integers.
Returns:
int: The maximum product of any subarray.
>>> get_max_prod... | def max_product_subarray(arr):
"""
Computes the maximum product of any subarray.
"""
n = len(arr)
if n == 0:
return 0
max_product = arr[0]
min_product = arr[0]
result = arr[0]
for i in range(1, n):
if arr[i] < 0:
max_product, min_product = min_pr... | from solution import get_max_product_of_subarray
def test_example_1():
assert get_max_product_of_subarray(5, [1, 2, 3, 4, 5]) == 120
def test_example_2():
assert get_max_product_of_subarray(4, [6, 2, 1, 8]) == 96
def test_single_element():
assert get_max_product_of_subarray(1, [10]) == 10
assert get_... | [
{
"docstring": "Computes the maximum product of any subarray.",
"function_declaration": "def max_product_subarray(arr):",
"function_name": "max_product_subarray",
"parameter_list": "(arr)"
},
{
"docstring": null,
"function_declaration": "def get_max_product_of_subarray(n, array):",
"... | [
0,
0,
1,
0,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def max_subarray_product(arr):\n \"\"\"\n Returns the maximum product of any subarray in the given array.\n \"\"\"\n # Initialize the variables fo... | trial_gpt4o_2 | {
"original_instruction": "You are given an array of $$n$$ positive integers. A subarray is a contiguous part of the original array. We define the product of a subarray as the product of all its elements.\n\nWe want to find the largest product of any subarray of the given array.\n\nYour task is to output the maximum ... | 0.80728 | Codeforces_4124 | C | [
"max_product_subarray",
"get_max_product_of_subarray"
] | 2 | [
[
"get_max_product_of_subarray",
"max_product_subarray"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 38997381873aaf9109f96fcec6aec91c71c184b1 | adde5d40f2657e9b618f0351ca272ee5fef70edd | |||
v1.0 | complete | Codeforces | Codeforces_3452_C | def min_operations_from_input(n: int, m: int, grid_values: List[int]) -> int:
""" Determine the minimum number of operations required to reduce all values in the grid to zero.
Args:
n (int): number of rows in the grid
m (int): number of columns in the grid
grid_values (List[int]): flattened 2D ... | def min_operations(grid):
n = len(grid)
m = len(grid[0])
operations = 0
max_value = max(max(row) for row in grid)
return max_value
def min_operations_from_input(n, m, grid_values):
grid = [list(map(int, grid_values[i * m : (i + 1) * m])) for i in range(n)]
return min_operations(grid) | def test_min_operations():
assert min_operations_from_input(2, 3, [1, 2, 1, 0, 1, 1]) == 2
assert min_operations_from_input(1, 1, [5]) == 5
assert min_operations_from_input(3, 3, [3, 3, 3, 3, 3, 3, 3, 3, 3]) == 3
assert min_operations_from_input(2, 2, [0, 0, 0, 0]) == 0
assert min_operations_from_in... | [
{
"docstring": null,
"function_declaration": "def min_operations(grid):",
"function_name": "min_operations",
"parameter_list": "(grid)"
},
{
"docstring": null,
"function_declaration": "def min_operations_from_input(n, m, grid_values):",
"function_name": "min_operations_from_input",
... | [
0,
0,
1,
1,
1,
1,
0,
0,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def minimum_operations(grid):\n n = len(grid)\n m = len(grid[0])\n operations = 0\n\n # First, handle row-wise reductions\n for row in grid:\n ... | trial_gpt4o_5 | {
"original_instruction": "You are given a two-dimensional grid of size $$$n \\times m$$$ where each cell contains a non-negative integer. You need to perform a set of operations to reduce the positive value in each cell to zero. In one operation, you can select a subrectangle of the grid (comprising of a contiguous ... | 0.613541 | Codeforces_3452 | C | [
"min_operations",
"min_operations_from_input"
] | 2 | [
[
"min_operations_from_input",
"min_operations"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | f565c16b53a26d4fafd62eabbea955710761f32a | d9c2d7998ec808c0c4dbad16b5a85b2b7cdd589d | |||
v1.0 | complete | Codeforces | Codeforces_3721_C | from typing import List
def min_transfer_times(n: int, G: List[List[int]], s: int) -> List[int]:
"""
Calculate the minimum time required to transfer data from server s to all other servers using the network paths.
Args:
n: int - number of servers
G: List[List[int]] - adjacency matrix where G[i... | from heapq import heappop, heappush
import sys
def dijkstra(n, G, s):
dist = [float('inf')] * n
dist[s] = 0
pq = [(0, s)] # priority queue of (cost, node)
while pq:
cur_dist, u = heappop(pq)
if cur_dist > dist[u]:
continue
for v in range(n):
... | from solution import min_transfer_times
def test_example():
n = 4
G = [
[0, 3, -1, -1],
[3, 0, 1, -1],
[-1, 1, 0, 2],
[-1, -1, 2, 0]
]
s = 0
assert min_transfer_times(n, G, s) == [0, 3, 4, 6]
def test_unreachable_server():
n = 3
G = [
[0, 1, -1],
... | [
{
"docstring": null,
"function_declaration": "def dijkstra(n, G, s):",
"function_name": "dijkstra",
"parameter_list": "(n, G, s)"
},
{
"docstring": null,
"function_declaration": "def min_transfer_times(n, G, s):",
"function_name": "min_transfer_times",
"parameter_list": "(n, G, s... | [
1,
1,
0,
1,
0,
1,
1,
0,
0
] | 5 | medium | 0.556 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\n\ndef network_transfer_time(n, G, s):\n \"\"\"\n Determines the minimum time required to transfer data from server `s` to all other server... | trial_gpt4o_1 | {
"original_instruction": "A company has a network of servers represented by a matrix $$$n \\times n$$$ matrix $$$G$$$, where each cell $$$G[i][j]$$$ represents the time it takes to transfer data from server $$$i$$$ to server $$$j$$$. Given a specific server node $$$s$$$, determine the minimum time required to transf... | 0.568203 | Codeforces_3721 | C | [
"dijkstra",
"min_transfer_times"
] | 2 | [
[
"min_transfer_times",
"dijkstra"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7954942d9bdf523f8c4486944cabdbade572adad | 5e38d8664cbc6695c8f4a1929eec250fdd64030d | |||
v1.0 | complete | Codeforces | Codeforces_3286_C | def min_cost_to_connect_islands(n: int, m: int, t: int, ferries: List[Tuple[int, int, int]], express: List[Tuple[int, int]]) -> int:
"""
Determine the minimum cost required to connect all the islands using the provided ferry routes and express ferry routes.
Args:
n : int : number of islands
m : in... | import heapq
def find(parent, i):
if parent[i] == i:
return i
else:
parent[i] = find(parent, parent[i])
return 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]:
... | from solution import min_cost_to_connect_islands
def test_min_cost_to_connect_islands():
n, m, t = 4, 2, 1
ferries = [(1, 2, 4), (3, 4, 2)]
express = [(2, 3)]
assert min_cost_to_connect_islands(n, m, t, ferries, express) == 6
def test_case_with_only_express_routes():
n, m, t = 4, 0, 3
ferries ... | [
{
"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,
0,
0,
1,
0,
0,
1,
0,
0,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_min_cost_to_connect_islands(n, m, t, ferry_routes, express_routes):\n \"\"\"\n Calculates the minimum cost to connect all islands using provide... | trial_gpt4o_6 | {
"original_instruction": "You are given a tree with n nodes, but initially, it is not connected. There are m edges given in advance, which can be used only once in any order to connect the nodes. Each node represents an island, and each edge represents a ferry route between two islands. You need to determine the min... | 0.70357 | Codeforces_3286 | C | [
"find",
"union",
"min_cost_to_connect_islands"
] | 3 | [
[
"min_cost_to_connect_islands",
"find"
],
[
"min_cost_to_connect_islands",
"union"
],
[
"union",
"find"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 4ea0abe03e9309254e45bd0a19506a135d7207f7 | 111fc8a89a3732856741dc0616d664c5d103c0b0 | |||
v1.0 | complete | Codeforces | Codeforces_3256_C | from typing import List, Tuple
def dijkstra(graph: List[List[Tuple[int, int]]], start: int) -> List[int]:
""" Implements Dijkstra's algorithm to find the shortest path from the start node to all other nodes in
the graph.
"""
pass
def shortest_paths(n: int, m: int, edges: List[Tuple[int, int, int]], q:... | import heapq
def dijkstra(graph, start):
n = len(graph)
distances = [float('inf')] * n
distances[start] = 0
priority_queue = [(0, start)]
while priority_queue:
current_distance, current_node = heapq.heappop(priority_queue)
if current_distance > distances[current_node]:... | def test_shortest_paths():
n = 5
m = 6
edges = [
(1, 2, 4),
(1, 3, 2),
(2, 3, 1),
(2, 4, 7),
(3, 5, 5),
(4, 5, 1)
]
q = 3
queries = [
(1, 5),
(1, 4),
(3, 4)
]
expected_output = ['7', '8', '6']
assert shortest_pat... | [
{
"docstring": null,
"function_declaration": "def dijkstra(graph, start):",
"function_name": "dijkstra",
"parameter_list": "(graph, start)"
},
{
"docstring": null,
"function_declaration": "def shortest_paths(n, m, edges, q, queries):",
"function_name": "shortest_paths",
"paramete... | [
0,
1,
0,
1,
0,
1,
0,
0
] | 3 | medium | 0.375 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\n\ndef dijkstra(n, roads, start):\n dist = [float('inf')] * (n + 1)\n adj = [[] for _ in range(n + 1)]\n \n for u, v, w in roads:\n ... | trial_gpt4o_7 | {
"original_instruction": "A travel agency uses a mobile app to help tourists find the shortest path between two landmarks in a city. The city is represented by an undirected graph where landmarks are nodes, and roads are edges with positive integer weights representing the travel time. Given a list of queries, each ... | 0.750364 | Codeforces_3256 | C | [
"dijkstra",
"shortest_paths"
] | 2 | [
[
"shortest_paths",
"dijkstra"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | a513aeb1d7f11bdee5814b46c025f7c2dcf5b5d8 | a829c07c6f81c1071eea058458000bfb0aa3e3c1 | |||
v1.0 | complete | Codeforces | Codeforces_3225_C | def game_outcome(n: int, m: int, k: int, initial_grid: List[str], q: int, moves: List[tuple]) -> str:
""" Determine the outcome of the board game given the initial configuration and sequence of moves.
>>> game_outcome(3, 3, 3, ["...", "...", "..."], 9, [('A', 1, 1), ('B', 1, 2), ('A', 1, 3), ('B', 2, 1), (... | def check_winner(grid, n, m, k):
# Helper function to check if a sequence of k in a list is the same and not '.'
def is_winner(sequence, player):
return sequence == [player] * k
# Check rows
for r in range(n):
for c in range(m - k + 1):
if is_winner(grid[r][c:c+k], 'A'):
... | import pytest
from solution import game_outcome
def test_game_alice_wins_by_row():
assert game_outcome(
3, 3, 3,
["...", "...", "..."],
9,
[('A', 1, 1), ('B', 1, 2), ('A', 1, 3), ('B', 2, 1), ('A', 2, 2), ('B', 2, 3), ('A', 3, 1), ('B', 3, 2), ('A', 3, 3)]
) == "Alice wins"
... | [
{
"docstring": null,
"function_declaration": "def check_winner(grid, n, m, k):",
"function_name": "check_winner",
"parameter_list": "(grid, n, m, k)"
},
{
"docstring": null,
"function_declaration": "def game_outcome(n, m, k, initial_grid, q, moves):",
"function_name": "game_outcome",... | [
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def check_winner(grid, player, k):\n def check_line(line, player, k):\n count = 0\n for cell in line:\n if cell == player:\n ... | trial_gpt4o_9 | {
"original_instruction": "A game company is developing a new board game, and they need your help to simulate a specific game scenario. The game takes place on an n x m grid, and players place their tokens on the grid according to certain rules. Two players, Alice and Bob, take turns placing their tokens on the grid.... | 0.638862 | Codeforces_3225 | C | [
"check_winner",
"game_outcome"
] | 2 | [
[
"game_outcome",
"check_winner"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | df0f24435f52ddf467833f386ca2757a88e2f90c | 9f9544938dc0a3c4cb124e90a5ca7355a118b845 | |||
v1.0 | complete | Codeforces | Codeforces_4109_C | def is_valid_username(username):
"""
Validates a single username based on the given rules:
1. The username must start with an uppercase letter.
2. The username must be at least 6 characters long and no more than 12 characters long.
3. The username must contain at least one digit.
4. The usernam... | import re
def is_valid_username(username):
"""
Validates a single username based on the given rules.
"""
if len(username) < 6 or len(username) > 12:
return False
if not username[0].isupper():
return False
if not any(char.isdigit() for char in username):
return False
... | from solution import is_valid_username, validate_usernames
def test_is_valid_username():
assert is_valid_username("A1b234") == True
assert is_valid_username("Zebra2020") == True
assert is_valid_username("helloWorld") == False
assert is_valid_username("Short1") == True
assert is_valid_username("TooL... | [
{
"docstring": "Validates a single username based on the given rules.",
"function_declaration": "def is_valid_username(username):",
"function_name": "is_valid_username",
"parameter_list": "(username)"
},
{
"docstring": "Given a number of test cases t, and a list of usernames, returns a list ... | [
0,
1,
0,
0,
1,
0,
0,
1,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def validate_username(username):\n \"\"\"\n Validate if the username meets the required guidelines:\n - The username must start with an uppercase let... | trial_gpt4o_1 | {
"original_instruction": "A company is hosting a coding competition, and they want to ensure that the competitors' usernames follow specific guidelines to avoid any conflicts or inappropriate names. The username must adhere to the following rules:\n\n1. The username must start with an uppercase letter.\n2. The usern... | 0.537603 | Codeforces_4109 | C | [
"is_valid_username",
"validate_usernames"
] | 2 | [
[
"validate_usernames",
"is_valid_username"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 63296ee09ea9c69c13be8a543d92fe2eb1b6cf33 | 46dc24152eaa609bbf5ffd0d698c5bb6be57bd65 | |||
v1.0 | complete | Codeforces | Codeforces_3953_C | from typing import List
def replace_primes(arr: List[int]) -> List[int]:
""" Given an array A of n integers, return an array of all the prime numbers
in the same relative order as they appear in A. Additionally, for each prime number found, replace its occurrence
with the smallest integer greater than th... | from typing import List
def is_prime(num: int) -> bool:
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
def smallest_composite_greater_than(n: int) -> int:
candidatate = n + 1
while True:
if not is_prime(... | from solution import replace_primes
def test_replace_primes_with_primes():
assert replace_primes([2, 3, 5, 7]) == [4, 4, 6, 8]
def test_replace_primes_with_mixed():
assert replace_primes([2, 3, 4, 5, 10, 15]) == [4, 4, 4, 6, 10, 15]
def test_replace_primes_no_primes():
assert replace_primes([1, 4, 6,... | [
{
"docstring": null,
"function_declaration": "def is_prime(num):",
"function_name": "is_prime",
"parameter_list": "(num)"
},
{
"docstring": null,
"function_declaration": "def smallest_composite_greater_than(n):",
"function_name": "smallest_composite_greater_than",
"parameter_list... | [
0,
1,
1,
1,
1,
1,
0,
0,
0,
0
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from typing import List\n\ndef is_prime(num: int) -> bool:\n if num <= 1:\n return False\n if num == 2:\n return True\n if num % 2 == 0... | trial_gpt4o_4 | {
"original_instruction": "Given an array A of n integers, return an array of all the prime numbers in the same relative order as they appear in A. Additionally, for each prime number found, replace its occurrence with the smallest integer greater than the prime number but not a prime itself (a composite number).\n\n... | 0.67474 | Codeforces_3953 | C | [
"is_prime",
"smallest_composite_greater_than",
"replace_primes"
] | 3 | [
[
"replace_primes",
"is_prime"
],
[
"replace_primes",
"smallest_composite_greater_than"
],
[
"smallest_composite_greater_than",
"is_prime"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 9edc3182a13080352958dbfa31dc7856ce00314a | 051c915c9a6d6f2a72a68ff6c0ba2389b1627b4b | |||
v1.0 | complete | Codeforces | Codeforces_4410_C | from functools import cmp_to_key
def largest_number(arr):
"""
Returns the largest number that can be formed by concatenating the array elements.
>>> largest_number([54, 546, 548]) '54854654'
>>> largest_number([1, 34, 3, 98]) '983431'
>>> largest_number([0, 0, 0, 0]) '0'
>>> largest_number([71]... | from functools import cmp_to_key
def compare(x, y):
if x + y > y + x:
return -1
elif x + y < y + x:
return 1
else:
return 0
def largest_number(arr):
"""
Returns the largest number that can be formed by concatenating the array elements.
"""
# Convert all numbers to s... | from solution import largest_number
def test_example_1():
assert largest_number([54, 546, 548]) == '54854654'
def test_example_2():
assert largest_number([1, 34, 3, 98]) == '983431'
def test_all_zeros():
assert largest_number([0, 0, 0, 0]) == '0'
def test_single_element():
assert largest_number(... | [
{
"docstring": null,
"function_declaration": "def compare(x, y):",
"function_name": "compare",
"parameter_list": "(x, y)"
},
{
"docstring": "Returns the largest number that can be formed by concatenating the array elements.",
"function_declaration": "def largest_number(arr):",
"funct... | [
0,
0,
1,
1,
0,
1,
0,
0,
1
] | 4 | medium | 0.444 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from functools import cmp_to_key\n\ndef largest_number(arr):\n \"\"\"\n Given a list of non-negative integers, arrange them such that they form the larg... | trial_gpt4o_6 | {
"original_instruction": "You are given an array of non-negative integers. Imagine placing each number in the array one after another to form the largest possible number.\n\nYour task is to write a function that takes the array as input and returns a string representing the largest number that can be formed by conca... | 0.736247 | Codeforces_4410 | C | [
"compare",
"largest_number"
] | 2 | [
[
"largest_number",
"compare"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ffd443ac2d10fb2d158fbbbac90a5371ffba5ce2 | a18604ef7d24ad03594e8b891620d306656f0967 | |||
v1.0 | complete | Codeforces | Codeforces_3725_C | def min_edges_to_connect_graph(n: int, m: int, edges: List[Tuple[int, int]]) -> int:
"""
Determine the minimum number of edges that need to be added to make the graph connected.
:param n: Number of vertices
:param m: Number of edges
:param edges: List of tuples representing the edges (u, v)
... | def find(parent, i):
if parent[i] == i:
return i
return find(parent, parent[i])
def union(parent, x, y):
root_x = find(parent, x)
root_y = find(parent, y)
if root_x != root_y:
parent[root_x] = root_y
def min_edges_to_connect_graph(n, m, edges):
parent = list(range(n + 1))
... | from solution import min_edges_to_connect_graph
def test_single_node():
assert min_edges_to_connect_graph(1, 0, []) == 0
def test_already_connected_graph():
assert min_edges_to_connect_graph(4, 4, [(1, 2), (2, 3), (3, 4), (4, 1)]) == 0
def test_disconnected_graph():
assert min_edges_to_connect_graph(4, 2... | [
{
"docstring": null,
"function_declaration": "def find(parent, i):",
"function_name": "find",
"parameter_list": "(parent, i)"
},
{
"docstring": null,
"function_declaration": "def union(parent, x, y):",
"function_name": "union",
"parameter_list": "(parent, x, y)"
},
{
"doc... | [
1,
1,
1,
1,
1,
0,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find(parent, i):\n if parent[i] == i:\n return i\n else:\n parent[i] = find(parent, parent[i])\n return parent[i]\n\ndef union(... | trial_gpt4o_8 | {
"original_instruction": "You are given an undirected graph with vertices numbered from 1 to n. Your task is to determine the minimum number of edges that need to be added to make the graph connected. A graph is connected if there is a path between any pair of vertices.\n\nThe first line contains two integers n and ... | 0.685281 | Codeforces_3725 | C | [
"find",
"union",
"min_edges_to_connect_graph"
] | 3 | [
[
"min_edges_to_connect_graph",
"find"
],
[
"min_edges_to_connect_graph",
"union"
],
[
"union",
"find"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | 973f67ee407e1059a3afa8c210c268e26e756b14 | 1afff2e6d804acb6220a443728542cc558e4cec5 | |||
v1.0 | complete | Codeforces | Codeforces_4022_C | def get_largest_square_size(n: int, m: int, grid_data: str) -> int:
""" Find the size of the largest square sub-grid where all the numbers are the same.
Args:
n: An integer representing the number of rows in the grid.
m: An integer representing the number of columns in the grid.
grid_data: A string ... | def largest_square_subgrid_same_numbers(grid):
n = len(grid)
m = len(grid[0])
dp = [[0] * m for _ in range(n)]
max_side = 0
for i in range(n):
for j in range(m):
if i == 0 or j == 0:
dp[i][j] = 1
else:
if grid[i][j] == grid[i-1][j]... | from solution import get_largest_square_size
def test_example_case():
n = 4
m = 5
grid_data = "1 2 3 4 5\n1 1 1 2 2\n1 1 1 2 2\n1 1 1 2 2"
assert get_largest_square_size(n, m, grid_data) == 3
def test_single_cell_grid():
n = 1
m = 1
grid_data = "7"
assert get_largest_square_size(n, m, ... | [
{
"docstring": null,
"function_declaration": "def largest_square_subgrid_same_numbers(grid):",
"function_name": "largest_square_subgrid_same_numbers",
"parameter_list": "(grid)"
},
{
"docstring": null,
"function_declaration": "def get_largest_square_size(n, m, grid_data):",
"function... | [
1,
1,
1,
0,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def largest_square_subgrid(grid, n, m):\n if n == 0 or m == 0:\n return 0\n dp = [[0] * m for _ in range(n)]\n max_side_length = 0\n\n for ... | trial_gpt4o_9 | {
"original_instruction": "You are given a grid with n rows and m columns, consisting of cells filled with non-negative integers. Your task is to find the size of the largest square sub-grid where all the numbers are the same. The size of a square sub-grid is defined by the length of its side.\n\nThe first line of th... | 0.642826 | Codeforces_4022 | C | [
"largest_square_subgrid_same_numbers",
"get_largest_square_size"
] | 2 | [
[
"get_largest_square_size",
"largest_square_subgrid_same_numbers"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 1ca8b2b33cee80e3122ce01f309b2b6c8faab61b | 52daa01a0b53210da3eef56b7452ea0216e30080 | |||
v1.0 | complete | Codeforces | Codeforces_3649_C | def balloon_collisions(n: int, input_data: List[str]) -> List[Tuple[int, int]]:
""" Determine the sequence of combinations of balloons that end up with a single balloon.
Each balloon has rings and initial velocity, and if two balloons collide, they combine.
Args:
n (int): The number of balloons.
... | import heapq
def combine_balloons(n, balloons):
# Priority queue for keeping track of smallest lexicographic pairs
pq = [(i, balloons[i]) for i in range(n)]
heapq.heapify(pq)
result = []
while len(pq) > 1:
# Get the two balloons with the smallest indices
a_idx, a = heapq.heappo... | from solution import balloon_collisions
def test_single_balloon():
input_data = ["1 500"]
expected = []
assert balloon_collisions(1, input_data) == expected
def test_two_balloons():
input_data = ["4 6", "7 1"]
expected = [(0, 1)]
assert balloon_collisions(2, input_data) == expected
def test_t... | [
{
"docstring": null,
"function_declaration": "def combine_balloons(n, balloons):",
"function_name": "combine_balloons",
"parameter_list": "(n, balloons)"
},
{
"docstring": null,
"function_declaration": "def balloon_collisions(n, input_data):",
"function_name": "balloon_collisions",
... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def combine_balloons(initial_balloons):\n from heapq import heappop, heappush\n import heapq\n \n n = len(initial_balloons)\n events = []\n ... | trial_gpt4o_3 | {
"original_instruction": "You are given a number of balloons, each with a number of rings attached to it. Each balloon floats upwards with a certain initial velocity. If two balloons collide, they combine into one, maintaining a single ring count which is the sum of the original two. The velocity of the combined bal... | 0.548448 | Codeforces_3649 | C | [
"combine_balloons",
"balloon_collisions"
] | 2 | [
[
"balloon_collisions",
"combine_balloons"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ae56c90b31ee0569b2881ee4612957b53d3a0868 | 3f790a766ba5a380344da4551cb61aee609ddb1e | |||
v1.0 | complete | Codeforces | Codeforces_2009_C | def get_shortest_paths(n: int, m: int, bridges: List[Tuple[int, int]]) -> List[List[Union[int, str]]]:
"""
Determine the minimal number of bridges that need to be traversed to travel from one island to another. If two islands are not directly connected or reachable through any series of bridges, the distance b... | def floyd_warshall(n, edges):
INF = float('inf')
dist = [[INF] * n for _ in range(n)]
for i in range(n):
dist[i][i] = 0
for u, v in edges:
dist[u - 1][v - 1] = 1
dist[v - 1][u - 1] = 1
for k in range(n):
for i in range(n):
for j in r... | from solution import get_shortest_paths
def test_example_case_1():
n = 4
m = 4
bridges = [(1, 2), (2, 3), (3, 4), (4, 1)]
expected = [
[0, 1, 2, 1],
[1, 0, 1, 2],
[2, 1, 0, 1],
[1, 2, 1, 0]
]
assert get_shortest_paths(n, m, bridges) == expected
def test_no_path_... | [
{
"docstring": null,
"function_declaration": "def floyd_warshall(n, edges):",
"function_name": "floyd_warshall",
"parameter_list": "(n, edges)"
},
{
"docstring": null,
"function_declaration": "def get_shortest_paths(n, m, bridges):",
"function_name": "get_shortest_paths",
"parame... | [
0,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def shortest_path_between_islands(n, m, connections):\n inf = float('inf')\n distance = [[inf] * n for _ in range(n)]\n \n for i in range(n):\n ... | trial_gpt4o_9 | {
"original_instruction": "In a coastal city, the local government has decided to construct a series of interconnected sea bridges and islands to boost maritime navigation. Each bridge connects exactly two islands and there is no more than one bridge directly connecting any pair of islands. The mayor, being a fan of ... | 0.75996 | Codeforces_2009 | C | [
"floyd_warshall",
"get_shortest_paths"
] | 2 | [
[
"get_shortest_paths",
"floyd_warshall"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 7d04a41823758058f9f6ba0a6e7e8a2e2c1611e2 | 86aaacaebe253e1e9083ffa6e5f3d455601e1a83 | |||
v1.0 | complete | Codeforces | Codeforces_2525_C | def prefix_sums(arr):
"""
Compute the prefix sum array of the given array.
"""
prefix = [0] * (len(arr) + 1)
for i in range(1, len(prefix)):
prefix[i] = prefix[i-1] + arr[i-1]
return prefix
def query_sums(prefix, l, r):
"""
Query the sum for a sublist from l to r (inclusive, 1-b... | def prefix_sums(arr):
"""
Compute the prefix sum array of the given array.
"""
prefix = [0] * (len(arr) + 1)
for i in range(1, len(prefix)):
prefix[i] = prefix[i-1] + arr[i-1]
return prefix
def query_sums(prefix, l, r):
"""
Query the sum for a sublist from l to r (inclusive, 1-b... | from solution import process_queries
def test_example_case():
n = 5
q = 3
arr = [1, 2, 3, 4, 5]
queries = [(1, 3), (2, 4), (1, 5)]
assert process_queries(n, q, arr, queries) == ["even", "odd", "odd"]
def test_all_even_numbers():
n = 4
q = 2
arr = [2, 4, 6, 8]
queries = [(1, 2), (1,... | [
{
"docstring": "Compute the prefix sum array of the given array.",
"function_declaration": "def prefix_sums(arr):",
"function_name": "prefix_sums",
"parameter_list": "(arr)"
},
{
"docstring": "Query the sum for a sublist from l to r (inclusive, 1-based index).\nCheck if the sum is even or od... | [
0,
0,
0,
0,
1,
1,
1,
0,
1,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def odd_or_even(n, q, numbers, queries):\n \"\"\"\n Determines if the sum of elements in specified sublists is odd or even.\n\n Parameters:\n n (i... | trial_gpt4o_8 | {
"original_instruction": "You have a list of $$$n$$$ integers and you are required to answer $$$q$$$ queries. Each query provides two integers $$$l$$$ and $$$r$$$ and requires you to output whether the sum of the sublist from index $$$l$$$ to index $$$r$$$ (inclusive, 1-based indices) is odd or even.\n\nThe first li... | 0.659034 | Codeforces_2525 | C | [
"prefix_sums",
"query_sums",
"process_queries"
] | 3 | [
[
"process_queries",
"prefix_sums"
],
[
"process_queries",
"query_sums"
]
] | 2 | [
"process_queries"
] | false | [] | false | pytest | true | [] | true | f3d3dd6e3c7a34b77e6a44dbdad6eb4637cee488 | 277489dff831d4bd208058198e62c4c63f73c72b | |||
v1.0 | complete | Codeforces | Codeforces_2996_C | from datetime import datetime, timedelta
from typing import List
def total_working_time(n: int, logs: List[str]) -> List[str]:
""" Calculate the total working time for each employee from the logs.
>>> total_working_time(6, [
... "2023-05-01 emp1 start:09:00 stop:12:30",
... "2023-05-01 emp1 break_start... | from datetime import datetime, timedelta
def parse_time(time_str):
return datetime.strptime(time_str, "%H:%M")
def total_working_time(n, logs):
work_times = {}
break_times = {}
for log in logs:
parts = log.split()
date = parts[0]
employee_id = parts[1]
time_type = part... | def test_total_working_time():
logs = [
"2023-05-01 emp1 start:09:00 stop:12:30",
"2023-05-01 emp1 break_start:10:00 break_stop:10:15",
"2023-05-01 emp2 start:08:00 stop:16:00",
"2023-05-01 emp2 break_start:12:00 break_stop:13:00",
"2023-05-01 emp2 break_start:15:00 break_sto... | [
{
"docstring": null,
"function_declaration": "def parse_time(time_str):",
"function_name": "parse_time",
"parameter_list": "(time_str)"
},
{
"docstring": null,
"function_declaration": "def total_working_time(n, logs):",
"function_name": "total_working_time",
"parameter_list": "(n... | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import defaultdict\nfrom datetime import datetime, timedelta\n\ndef parse_time(time_str):\n \"\"\"Parses a time string in HH:MM format and... | trial_gpt4o_3 | {
"original_instruction": "A company wants to increase the productivity of their employees, so they decided to introduce a system where employees can log their working hours and breaks in a structured format. They need a program that can analyze these logs and compute the total working time for each employee, excludi... | 0.645149 | Codeforces_2996 | C | [
"parse_time",
"total_working_time"
] | 2 | [
[
"total_working_time",
"parse_time"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | bf882326aacb7debfe0aaa026d6a0c53d911498d | 18773e0be19b8a933239a01b390f45bfa7ac3ebc | |||
v1.0 | complete | Codeforces | Codeforces_3226_C | def simulate_farmland(initial_fields: List[List[int]], K: int) -> List[List[int]]:
"""
In a faraway land, there is a unique type of farmland management system where fields are arranged in a grid of size M x N. Each cell in this grid represents a specific field.
All fields are either planted with crops or l... | from typing import List
def count_crops_neighbors(fields: List[List[int]], x: int, y: int) -> int:
"""
Count the number of neighboring cells with crops around the cell at (x, y).
"""
count = 0
rows = len(fields)
cols = len(fields[0])
for dx in [-1, 0, 1]:
for dy in [-1, 0, 1]:
... | from solution import simulate_farmland
def test_simulate_farmland_initial_example():
initial_fields = [
[0, 1, 0],
[0, 0, 1],
[1, 1, 1]
]
K = 1
expected = [
[0, 0, 0],
[1, 0, 1],
[0, 1, 1]
]
assert simulate_farmland(initial_fields, K) == expected
... | [
{
"docstring": "Count the number of neighboring cells with crops around the cell at (x, y).",
"function_declaration": "def count_crops_neighbors(fields, x, y):",
"function_name": "count_crops_neighbors",
"parameter_list": "(fields, x, y)"
},
{
"docstring": "Simulate the changes in the farmla... | [
0,
0,
0,
1,
1,
1,
1,
0,
0,
0
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def simulate_farmland(initial_fields, K):\n def get_neighbor_count(fields, i, j):\n count = 0\n directions = [(-1, -1), (-1, 0), (-1, 1), (0,... | trial_gpt4o_6 | {
"original_instruction": "In a faraway land, there is a unique type of farmland management system where fields are arranged in a grid of size M x N. Each cell in this grid represents a specific field. All fields are either planted with crops or left barren.\n\nEvery month, fields undergo changes based on certain rul... | 0.519678 | Codeforces_3226 | C | [
"count_crops_neighbors",
"simulate_farmland"
] | 2 | [
[
"simulate_farmland",
"count_crops_neighbors"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 01e4c75edff8734f9d3c224ac332854f2e27d396 | e2b40c9c7bb635c45146073b9493dba744142657 | |||
v1.0 | complete | Codeforces | Codeforces_4227_C | def can_distribute(tasks, max_load, k):
current_load = 0
servers_used = 1
for task in tasks:
if current_load + task > max_load:
servers_used += 1
current_load = task
if servers_used > k:
return False
else:
current_load += t... | def can_distribute(tasks, max_load, k):
current_load = 0
servers_used = 1
for task in tasks:
if current_load + task > max_load:
servers_used += 1
current_load = task
if servers_used > k:
return False
else:
current_load += t... | def test_minimize_max_load_single_task():
assert minimize_max_load([5], 1) == 5
def test_minimize_max_load_all_equal_tasks():
assert minimize_max_load([10, 10, 10, 10], 2) == 20
def test_minimize_max_load_varied_tasks():
assert minimize_max_load([10, 20, 30, 40, 50], 3) == 60
def test_minimize_max_load_s... | [
{
"docstring": null,
"function_declaration": "def can_distribute(tasks, max_load, k):",
"function_name": "can_distribute",
"parameter_list": "(tasks, max_load, k)"
},
{
"docstring": null,
"function_declaration": "def minimize_max_load(tasks, k):",
"function_name": "minimize_max_load"... | [
1,
0,
1,
0,
1,
0,
0,
0,
0,
1
] | 4 | medium | 0.4 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def canDistribute(tasks, k, max_load):\n servers = [0] * k\n for task in tasks:\n if task > max_load:\n return False\n for i in... | trial_gpt4o_9 | {
"original_instruction": "You are managing a set of servers and each server has a limited processing capacity. Occasionally, you need to distribute a set of tasks to these servers efficiently to minimize the maximum load among all servers. This is a classic load balancing problem.\n\nYou are given two things:\n1. An... | 0.63866 | Codeforces_4227 | C | [
"can_distribute",
"minimize_max_load"
] | 2 | [
[
"minimize_max_load",
"can_distribute"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 209851cfd18929f28e01bc648a1cc3863ec14e34 | 61cc08a84c551f2ca7114a85c57be09343894324 | |||
v1.0 | complete | Codeforces | Codeforces_4142_C | def get_shortest_path(n: int, m: int, roads_data: List[str], a: int, b: int) -> Union[int, str]:
""" In a given city, there are several intersections connected by roads.
Each road has an associated length. A traveler wants to determine the shortest
possible distance between two specific intersections using ... | import heapq
def dijkstra(n, roads, start, end):
"""
Returns the shortest path from start to end using Dijkstra's algorithm.
Args:
n (int): Number of intersections.
roads (list of tuples): Roads between intersections (u, v, w).
start (int): Starting intersection.
end (int): Ending inte... | def test_get_shortest_path_basic():
n = 4
m = 4
roads_data = [
"1 2 5",
"1 3 9",
"2 3 2",
"3 4 6"
]
a, b = 1, 4
assert get_shortest_path(n, m, roads_data, a, b) == 13
def test_get_shortest_path_no_path():
n = 4
m = 2
roads_data = [
"1 2 5",
... | [
{
"docstring": "Returns the shortest path from start to end using Dijkstra's algorithm.\n\nArgs:\nn (int): Number of intersections.\nroads (list of tuples): Roads between intersections (u, v, w).\nstart (int): Starting intersection.\nend (int): Ending intersection.\n\nReturns:\nint or str: The shortest path len... | [
1,
0,
1,
1,
1,
0,
0,
1,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\n\ndef dijkstra(n, adj_list, start, end):\n \"\"\"\n Function to find the shortest path using Dijkstra's algorithm.\n \"\"\"\n distan... | trial_gpt4o_8 | {
"original_instruction": "In a given city, there are several intersections connected by roads. Each road has an associated length. A traveler wants to determine the shortest possible distance between two specific intersections using the available roads. Implement an algorithm to help the traveler find this shortest ... | 0.723863 | Codeforces_4142 | C | [
"dijkstra",
"get_shortest_path"
] | 2 | [
[
"get_shortest_path",
"dijkstra"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 582b005b32b0252d35be69a8e3a24157e365a189 | b14dbc4a7ae93aa5a3a905dbf5042cecaafb1fea | |||
v1.0 | complete | Codeforces | Codeforces_3986_C | class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insert_into_bst(root, val):
"""Inserts a value into the BST and returns the root node."""
# Your code goes here
def bst_height(root):
"""Calculates the height of the BST."""
# You... | class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insert_into_bst(root, val):
if not root:
return TreeNode(val)
if val < root.val:
root.left = insert_into_bst(root.left, val)
else:
root.right = insert_into_bst(... | from solution import solve, TreeNode, insert_into_bst, bst_height, bst_from_array_height
def test_example_case():
test_cases = [(5, [3, 2, 1, 5, 4]), (3, [10, 8, 12])]
assert solve(test_cases) == [2, 1]
def test_single_element():
test_cases = [(1, [4])]
assert solve(test_cases) == [0]
def test_increa... | [] | [
0,
1,
1,
1,
1,
1,
1,
0,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, key):\n self.left = None\n self.right = None\n self.val = key\n\ndef insert(root, key):\n if r... | trial_gpt4o_9 | {
"original_instruction": "Given an array of distinct integers, you need to construct a binary search tree (BST) by inserting the elements of the array one by one in the order they appear in the array. Your task is to determine the height of this BST. The height of a BST is defined as the number of edges in the longe... | 0.528182 | Codeforces_3986 | C | [
"insert_into_bst",
"bst_height",
"bst_from_array_height",
"solve"
] | 4 | [
[
"bst_from_array_height",
"bst_height"
],
[
"bst_from_array_height",
"insert_into_bst"
],
[
"solve",
"bst_from_array_height"
]
] | 3 | [] | false | [
"TreeNode"
] | true | pytest | true | [] | true | 71fcd06b37cc89b41f5ea29a23c7bb225ab9d5bb | c3db3048dacc5be35afbf0d965d6c38b619b4f42 | |||
v1.0 | complete | Codeforces | Codeforces_4612_C | import random
from typing import List, Tuple
def manipulate_data(n: int) -> int:
primes = [2, 3, 5, 7]
prime = random.choice(primes)
if random.choice([True, False]) and n % prime == 0:
return n // prime
else:
return n * prime
def detect_primes(n: int) -> List[Tuple[int, str]]:
""" ... | import random
from typing import List, Tuple
# Assuming we have the definition of manipulate_data function
def manipulate_data(n: int) -> int:
primes = [2, 3, 5, 7]
prime = random.choice(primes)
if random.choice([True, False]) and n % prime == 0:
return n // prime
else:
return n * prime... | def test_detect_primes_single_multiply():
original_value = 10
# Mocking manipulate_data for specific behavior
result = detect_primes(original_value)
assert all(op in ['multiply', 'divide'] for prime, op in result)
assert len(result) <= 3
assert all(prime in [2, 3, 5, 7] for prime, op in result)
... | [
{
"docstring": null,
"function_declaration": "def manipulate_data(n):",
"function_name": "manipulate_data",
"parameter_list": "(n)"
},
{
"docstring": null,
"function_declaration": "def detect_primes(n):",
"function_name": "detect_primes",
"parameter_list": "(n)"
}
] | [
0,
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import random\nfrom typing import List, Tuple\n\ndef manipulate_data(n: int) -> int:\n primes = [2, 3, 5, 7]\n prime = random.choice(primes)\n operat... | trial_gpt4o_3 | {
"original_instruction": "You are given a function `manipulate_data` that takes an integer `n` and performs one of two actions: either multiplying `n` by a fixed prime number (2, 3, 5, or 7) or dividing `n` by it (if divisible). The function could apply different primes in different calls randomly but at most three ... | 0.669536 | Codeforces_4612 | C | [
"manipulate_data",
"detect_primes"
] | 2 | [
[
"detect_primes",
"manipulate_data"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | f7073a415490570bacc778525da9659b23a2947f | 08a4658acb56f9bb2c16847895aa59e459e672ee | |||
v1.0 | complete | Codeforces | Codeforces_4718_C | def add_road_without_cycle(input_str: str) -> str:
"""
Determines whether it is possible to add one road between two cities without creating a cycle.
:param input_str: String representation of the input, where the first line contains
the number of cities (n) and roads (m), followed by... | def is_possible_to_add_road(n, roads):
"""
Determines whether it is possible to add one road between two cities without creating a cycle.
:param n: Number of cities
:param roads: List of tuples (u, v) representing the current roads
:return: "NO" if it is not possible to add any road without cre... | from solution import add_road_without_cycle
def test_add_road_without_cycle_case1():
input_data = "5 4\n1 2\n1 3\n2 4\n3 4"
expected_output = "YES\n"
output = add_road_without_cycle(input_data)
assert output.startswith("YES")
a, b = map(int, output.split()[1:])
assert 1 <= a <= 5 and 1 <= b <= ... | [
{
"docstring": "Determines whether it is possible to add one road between two cities without creating a cycle.\n\n:param n: Number of cities\n:param roads: List of tuples (u, v) representing the current roads\n:return: \"NO\" if it is not possible to add any road without creating a cycle,\n otherwise \"... | [
1,
0,
0,
1,
0,
0,
0,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def find_road_to_add(n, roads):\n \"\"\"\n Determine if there is a road that can be added without creating a cycle.\n \n Args:\n n: Number of c... | trial_gpt4o_3 | {
"original_instruction": "In a faraway land, there is a kingdom with n cities connected by a network of roads. The King wants to build a new road system such that there is exactly one additional road that directly connects two different cities, in order to improve the connectivity of the kingdom. The cities are numb... | 0.647047 | Codeforces_4718 | C | [
"is_possible_to_add_road",
"add_road_without_cycle"
] | 2 | [
[
"add_road_without_cycle",
"is_possible_to_add_road"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 70a7edfc2bf76975081891a72711c80f32a3de8d | 06746a3f22114ae9463c8512b4c02a7ececa5147 | |||
v1.0 | complete | Codeforces | Codeforces_3891_C | from typing import List, Tuple
def solve_network_routing(N: int, M: int, K: int, edges: List[Tuple[int, int, int]], S: int, D: int) -> int:
"""
Determine the minimum number of times a packet must be forwarded to move from the source router to the destination router,
or output -1 if the destination router... | import heapq
from collections import defaultdict
def dijkstra(N, edges, S, D):
graph = defaultdict(list)
for u, v, w in edges:
graph[u].append((v, w))
graph[v].append((u, w))
min_heap = [(0, S)]
min_times = {i: float('inf') for i in range(1, N + 1)}
min_times[S] = 0
... | from solution import solve_network_routing
def test_case_1():
N, M, K = 5, 6, 100
edges = [
(1, 2, 4),
(1, 3, 2),
(2, 3, 1),
(2, 4, 5),
(3, 4, 3),
(3, 5, 10)
]
S, D = 1, 5
assert solve_network_routing(N, M, K, edges, S, D) == 12
def test_case_2():
... | [
{
"docstring": null,
"function_declaration": "def dijkstra(N, edges, S, D):",
"function_name": "dijkstra",
"parameter_list": "(N, edges, S, D)"
},
{
"docstring": null,
"function_declaration": "def solve_network_routing(N, M, K, edges, S, D):",
"function_name": "solve_network_routing"... | [
1,
1,
1,
1,
1,
0,
0,
1,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "import heapq\nimport sys\n\ndef minimum_forwarding(N, M, K, edges, S, D):\n # Create adjacency list\n graph = {i: [] for i in range(1, N+1)}\n for u,... | trial_gpt4o_9 | {
"original_instruction": "A software company has designed a new network routing protocol. Each router in the network can send packets to its neighboring routers. The routers are connected in an undirected graph, where each node represents a router and each edge represents a direct communication link between two rout... | 0.641395 | Codeforces_3891 | C | [
"dijkstra",
"solve_network_routing"
] | 2 | [
[
"solve_network_routing",
"dijkstra"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | ed63a5d2f6e1417ac413a7414e762c20c8620fd1 | 58ddb64a60628030dee6947765707ea320dfcec8 | |||
v1.0 | complete | Codeforces | Codeforces_4535_C | def min_total_maintenance_cost(B: int, P: int, bridges: List[Tuple[int, int, int]]) -> int:
""" Find the minimum possible total maintenance cost required to ensure all buildings are connected.
Args:
B : int : number of buildings
P : int : number of possible bridges
bridges : List[Tuple[int, int... | def find(parent, i):
if parent[i] == i:
return i
else:
return find(parent, parent[i])
def union(parent, rank, x, y):
xroot = find(parent, x)
yroot = find(parent, y)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yr... | from solution import min_total_maintenance_cost
def test_min_total_maintenance_cost_example1():
B = 4
P = 5
bridges = [
(1, 2, 10),
(2, 3, 15),
(3, 4, 4),
(1, 4, 6),
(1, 3, 5)
]
assert min_total_maintenance_cost(B, P, bridges) == 19
def test_min_total_mainte... | [
{
"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,
0,
0,
1,
0,
0,
1,
0
] | 3 | medium | 0.375 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_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_... | trial_gpt4o_7 | {
"original_instruction": "A company is building a new office compound, which will consist of several connected buildings. Each building will be connected to exactly one other building, and this connection will be represented by bridges. The company's goal is to select the bridges in such a way that the overall maint... | 0.621439 | Codeforces_4535 | C | [
"find",
"union",
"min_total_maintenance_cost"
] | 3 | [
[
"min_total_maintenance_cost",
"find"
],
[
"min_total_maintenance_cost",
"union"
],
[
"union",
"find"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | cb43972ea12ccb0213973e1d73c6b66d35378a13 | b4dc68d8ae2c05bb6a923ecd58bf3a756a4692b0 | |||
v1.0 | complete | Codeforces | Codeforces_4264_C | from collections import defaultdict, deque
from typing import List, Tuple
def update_value(node_values: List[int], node: int, value: int) -> None:
""" Updates the value of a node in the node_values list.
>>> node_values = [0, 10, 20, 30, 40, 50]
>>> update_value(node_values, 3, 0)
>>> node_values[3]
... | from collections import defaultdict, deque
def update_value(node_values, node, value):
node_values[node] = value
def reachable_sum(graph, node_values, node):
visited = set()
queue = deque([node])
total_sum = 0
while queue:
current = queue.popleft()
if current not in visited:
... | from solution import update_value, reachable_sum, process_queries
def test_update_value():
node_values = [0, 10, 20, 30, 40, 50]
update_value(node_values, 3, 0)
assert node_values[3] == 0
def test_reachable_sum():
graph = defaultdict(list, {1: [2, 3], 2: [], 3: [4], 4: [5]})
node_values = [0, 10, ... | [
{
"docstring": null,
"function_declaration": "def update_value(node_values, node, value):",
"function_name": "update_value",
"parameter_list": "(node_values, node, value)"
},
{
"docstring": null,
"function_declaration": "def reachable_sum(graph, node_values, node):",
"function_name":... | [
0,
0,
0,
1,
0,
0,
0,
0,
1,
1
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import defaultdict, deque\n\nclass DAGWithQueries:\n def __init__(self, n, node_values, edges):\n self.n = n\n self.node_val... | trial_gpt4o_8 | {
"original_instruction": "You are given a directed acyclic graph (DAG) with `n` nodes and `m` edges. Each node has a non-negative integer value assigned to it. You need to answer multiple queries about the graph.\n\nThe DAG is represented as follows:\n- **First line**: Two integers `n` and `m` (1 ≤ n ≤ 10^5, 0 ≤ m ≤... | 0.581397 | Codeforces_4264 | C | [
"update_value",
"reachable_sum",
"process_queries"
] | 3 | [
[
"process_queries",
"reachable_sum"
],
[
"process_queries",
"update_value"
]
] | 2 | [
"process_queries"
] | false | [] | false | pytest | true | [] | true | 1fe1585463baa0127932599d1acb7e78726837fa | 130ca1ea08c08f538a2c43236a7e99cf7fb0f9f7 | |||
v1.0 | complete | Codeforces | Codeforces_3647_C | def contains_cycle(N: int, M: int, edges: List[Tuple[int, int]]) -> str:
"""
Given an undirected graph with N vertices and M edges, determine whether
the graph contains any cycles. A cycle in a graph is a path that starts
and ends at the same vertex and contains at least one other vertex.
Arg... | def has_cycle(graph, n):
visited = [False] * n
parent = [-1] * n
def dfs(v):
visited[v] = True
for u in graph[v]:
if not visited[u]:
parent[u] = v
if dfs(u):
return True
elif parent[v] != u:
return T... | from solution import contains_cycle
def test_contains_cycle_case1():
N, M = 6, 6
edges = [(1, 2), (2, 3), (3, 4), (4, 1), (2, 5), (5, 6)]
assert contains_cycle(N, M, edges) == "YES"
def test_contains_cycle_case2():
N, M = 4, 3
edges = [(1, 2), (2, 3), (3, 4)]
assert contains_cycle(N, M, edges)... | [
{
"docstring": null,
"function_declaration": "def has_cycle(graph, n):",
"function_name": "has_cycle",
"parameter_list": "(graph, n)"
},
{
"docstring": null,
"function_declaration": "def contains_cycle(N, M, edges):",
"function_name": "contains_cycle",
"parameter_list": "(N, M, e... | [
1,
1,
1,
1,
1,
1,
0,
0,
1,
1
] | 8 | easy | 0.8 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def has_cycle_dfs(graph, visited, parent, vertex):\n visited[vertex] = True\n for neighbor in graph[vertex]:\n if not visited[neighbor]:\n ... | trial_gpt4o_8 | {
"original_instruction": "Given an undirected graph with `N` vertices and edges, you need to determine whether the graph contains any cycles. A cycle in a graph is a path that starts and ends at the same vertex and contains at least one other vertex.\n\nThe first line contains an integer `N` (1 ≤ N ≤ 1000) — the num... | 0.663458 | Codeforces_3647 | C | [
"has_cycle",
"contains_cycle"
] | 2 | [
[
"contains_cycle",
"has_cycle"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | adc03a2cb0b0d0009079c67fbf3e54ab53dd201b | 1134937ffbb87d0a564e7e0b6f87d6c97a30e678 | |||
v1.0 | complete | Codeforces | Codeforces_4723_C | def is_magic_square(matrix):
"""
Check if a given NxN matrix is a magic square.
>>> is_magic_square([
... [2, 7, 6],
... [9, 5, 1],
... [4, 3, 8]
... ]) == "YES"
>>> is_magic_square([
... [1, 2, 3],
... [4, 5, 6],
... [7, 8, 9]
... ]) == "NO"
"... | def is_magic_square(matrix):
"""
Check if a given NxN matrix is a magic square.
"""
n = len(matrix)
if n == 0:
return "NO"
magic_sum = sum(matrix[0])
# Check sums of each row
for row in matrix:
if sum(row) != magic_sum:
return "NO"
# Ch... | def test_is_magic_square():
assert is_magic_square([
[2, 7, 6],
[9, 5, 1],
[4, 3, 8]
]) == "YES"
assert is_magic_square([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]) == "NO"
assert is_magic_square([
[2, 7, 6],
[9, 5, 1],
[4, 3, 9]
... | [
{
"docstring": "Check if a given NxN matrix is a magic square.",
"function_declaration": "def is_magic_square(matrix):",
"function_name": "is_magic_square",
"parameter_list": "(matrix)"
},
{
"docstring": null,
"function_declaration": "def read_input_and_check_magic_square():",
"funct... | [
0,
0,
1,
1,
0,
1,
1,
1,
1,
1
] | 7 | easy | 0.7 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def is_magic_square(matrix):\n n = len(matrix)\n \n # Calculate the target sum using the first row\n target_sum = sum(matrix[0])\n \n # Chec... | trial_gpt4o_2 | {
"original_instruction": "Develop a function that takes a square matrix of integers as input and determines if it is a magic square. A magic square is a matrix in which the sum of every row, the sum of every column, and the sum of both main diagonals are all the same. The matrix is guaranteed to be square (i.e., it ... | 0.649644 | Codeforces_4723 | C | [
"is_magic_square",
"read_input_and_check_magic_square"
] | 2 | [
[
"read_input_and_check_magic_square",
"is_magic_square"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 541799b2c29f0656bda9b7b8fcfffeb050722b88 | 14a96ce4b6b7c7916748206cdf7335be47ea1a1d | |||
v1.0 | complete | Codeforces | Codeforces_5066_C | from typing import List
def num_decodings_message(n: int, s: str) -> int:
""" Determine the number of distinct ways to decode a given encoded message.
Args:
n: An integer representing the length of the encoded message.
s: A string of n digits representing the encoded message.
Returns:
... | def num_decodings(s: str) -> int:
if not s or s[0] == '0':
return 0
n = len(s)
dp = [0] * (n + 1)
dp[0] = 1
dp[1] = 1
for i in range(2, n + 1):
if s[i - 1] != '0':
dp[i] += dp[i - 1]
if 10 <= int(s[i - 2:i]) <= 26:
dp[i] += dp[i - 2]
return ... | from solution import num_decodings_message
def test_num_decodings_example():
assert num_decodings_message(5, "12321") == 6
def test_num_decodings_single_digit():
assert num_decodings_message(1, "1") == 1
assert num_decodings_message(1, "0") == 0
def test_num_decodings_with_zeroes():
assert num_decodi... | [
{
"docstring": null,
"function_declaration": "def num_decodings(s):",
"function_name": "num_decodings",
"parameter_list": "(s)"
},
{
"docstring": null,
"function_declaration": "def num_decodings_message(n, s):",
"function_name": "num_decodings_message",
"parameter_list": "(n, s)"... | [
0,
1,
1,
0,
0,
1,
1,
0,
0,
1
] | 5 | medium | 0.5 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def num_decodings(encoded_message):\n n = len(encoded_message)\n if n == 0 or encoded_message[0] == '0':\n return 0\n \n dp = [0] * (n + 1)... | trial_gpt4o_9 | {
"original_instruction": "You are given an encoded message consisting of digits. A letter can be encoded to digits in the range '1' to '26', mapped to the letters 'A' to 'Z', respectively (i.e., 'A' -> 1, 'B' -> 2, ..., 'Z' -> 26). The message can be decoded in multiple ways. Your task is to write a program to deter... | 0.63161 | Codeforces_5066 | C | [
"num_decodings",
"num_decodings_message"
] | 2 | [
[
"num_decodings_message",
"num_decodings"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | 189430de2ee9056675f20f164dfdc3604a0cd1f9 | 4eb50592314b126a48e431a89c2cc3f41f7fe4e4 | |||
v1.0 | complete | Codeforces | Codeforces_4004_C | def preprocess_sum_array(arr):
"""
Preprocess the original array to create a prefix sum array.
"""
pass
def query_sum(prefix_sum, i, j):
"""
Returns the sum from index i to j using the prefix sum array.
"""
pass
def process_queries(n, q, arr, queries):
"""
Process all the queri... | def preprocess_sum_array(arr):
"""
Preprocess the original array to create a prefix sum array.
"""
prefix_sum = [0] * (len(arr) + 1)
for idx in range(len(arr)):
prefix_sum[idx + 1] = prefix_sum[idx] + arr[idx]
return prefix_sum
def query_sum(prefix_sum, i, j):
"""
Returns the su... | from solution import preprocess_sum_array, query_sum, process_queries
def test_preprocess_sum_array():
arr = [1, 2, 3, 4, 5]
expected_prefix_sum = [0, 1, 3, 6, 10, 15]
assert preprocess_sum_array(arr) == expected_prefix_sum
def test_query_sum():
prefix_sum = [0, 1, 3, 6, 10, 15]
assert query_sum(p... | [
{
"docstring": "Preprocess the original array to create a prefix sum array.",
"function_declaration": "def preprocess_sum_array(arr):",
"function_name": "preprocess_sum_array",
"parameter_list": "(arr)"
},
{
"docstring": "Returns the sum from index i to j using the prefix sum array.",
"f... | [
1,
0,
1,
1,
1,
1,
1,
1,
1,
1
] | 9 | easy | 0.9 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def range_sum(arr, queries):\n \"\"\"\n Given an array of integers `arr` and a list of queries. Each query contains two integers i and j.\n This func... | trial_gpt4o_9 | {
"original_instruction": "You are given an array A of n integers and q queries. Each query is of the form i j which means find the sum of integers from the i-th to the j-th index (both inclusive) in the array.\n\nOutput the result of each query.\n\nThe first line contains two integers n, q (1 ≤ n ≤ 105, 1 ≤ q ≤ 50,0... | 0.544884 | Codeforces_4004 | C | [
"preprocess_sum_array",
"query_sum",
"process_queries"
] | 3 | [
[
"process_queries",
"preprocess_sum_array"
],
[
"process_queries",
"query_sum"
]
] | 2 | [
"process_queries"
] | false | [] | false | pytest | true | [] | true | 120882f32ac7d2a76237ee2e6e3208407c9852aa | 45d913bde0c628ec20c202f7fa49045db639ad5b | |||
v1.0 | complete | Codeforces | Codeforces_5372_C | from typing import List
def min_moves_from_input(input_str: str) -> str:
"""
Determines the minimum number of moves required to traverse from the top-left corner to the bottom-right corner
of the grid. The arm can only move right or down, and certain cells are blocked and cannot be traversed.
>>... | from collections import deque
def min_moves(grid):
"""
Returns the minimum number of moves required to traverse from the top-left corner to the bottom-right corner of the grid.
If it is impossible, return "impossible".
"""
m, n = len(grid), len(grid[0])
if grid[0][0] == 'X' or grid[m-1][n-1] ==... | from solution import min_moves_from_input
def test_min_moves_sample_1():
input_str = "3 3\n...\n.X.\n..."
assert min_moves_from_input(input_str) == 4
def test_min_moves_sample_2():
input_str = "2 2\n.X\nX."
assert min_moves_from_input(input_str) == "impossible"
def test_min_moves_single_cell():
i... | [
{
"docstring": "Returns the minimum number of moves required to traverse from the top-left corner to the bottom-right corner of the grid.\nIf it is impossible, return \"impossible\".",
"function_declaration": "def min_moves(grid):",
"function_name": "min_moves",
"parameter_list": "(grid)"
},
{
... | [
0,
0,
0,
0,
1,
1,
0,
0,
1,
0
] | 3 | hard | 0.3 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "from collections import deque\n\ndef minimum_moves(m, n, grid):\n \"\"\"\n Returns the minimum number of moves required to traverse from the\n top-le... | trial_gpt4o_8 | {
"original_instruction": "To help a mechanical arm navigate a grid, you need to write a program that determines the minimum number of moves required to traverse from the top-left corner to the bottom-right corner of the grid. The arm can only move right or down, and certain cells are blocked and cannot be traversed.... | 0.640496 | Codeforces_5372 | C | [
"min_moves",
"parse_input",
"min_moves_from_input"
] | 3 | [
[
"min_moves_from_input",
"min_moves"
],
[
"min_moves_from_input",
"parse_input"
]
] | 2 | [
"parse_input"
] | false | [] | false | pytest | true | [] | true | 9edfe6c1c23e1845142661cceaf0a356e38aa408 | 064b7486169bfa390e802053c236dced3fcfea4b | |||
v1.0 | complete | Codeforces | Codeforces_5007_C | def minimum_cost_to_connect_all_castles(n: int, m: int, roads: List[Tuple[int, int, int]]) -> int:
""" Determine the minimum total construction cost to connect all the castles with roads.
>>> minimum_cost_to_connect_all_castles(4, 5, [(1, 2, 1), (2, 3, 4), (3, 4, 3), (4, 1, 2), (1, 3, 3)])
6
>>> minimum... | 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
elif r... | from solution import minimum_cost_to_connect_all_castles
def test_basic_example():
assert minimum_cost_to_connect_all_castles(4, 5, [(1, 2, 1), (2, 3, 4), (3, 4, 3), (4, 1, 2), (1, 3, 3)]) == 6
def test_no_possible_connection():
assert minimum_cost_to_connect_all_castles(4, 2, [(1, 2, 5), (3, 4, 10)]) == -1
... | [
{
"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,
0,
1,
1,
0,
1,
0,
0,
1,
1
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def minimum_cost_to_connect_castles(n, m, roads):\n parent = list(range(n+1))\n \n def find(x):\n if parent[x] != x:\n parent[x] = ... | trial_gpt4o_9 | {
"original_instruction": "In an ancient kingdom, there are various castles that need to be connected by roads. The kingdom has `n` castles connected by `m` potential roads. Each road has a cost associated with its construction. The kingdom's goal is to build a network of roads such that any castle can be reached fro... | 0.630484 | Codeforces_5007 | C | [
"find",
"union",
"minimum_cost_to_connect_all_castles"
] | 3 | [
[
"minimum_cost_to_connect_all_castles",
"find"
],
[
"minimum_cost_to_connect_all_castles",
"union"
],
[
"union",
"find"
]
] | 3 | [] | false | [] | false | pytest | true | [] | true | d337067b8d62297fc71853295ddc5341df152643 | 245f4c4db8959a16a66ea77a73698141ecac9324 | |||
v1.0 | complete | Codeforces | Codeforces_4816_C | def find_road(grid: List[str], n: int) -> List[Union[str, Tuple[int, int]]]:
""" Determine if it is possible to construct a road from the northwest corner to the southeast corner
of a square-shaped grid of size n x n, and find a valid sequence of coordinates if possible.
>>> find_road([
"EEEEB",... | def find_road(grid, n):
def is_valid(x, y, visited):
return 0 <= x < n and 0 <= y < n and grid[x][y] == 'E' and (x, y) not in visited
def backtrack(x, y, path):
if (x, y) == (n - 1, n - 1):
return True
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
for ... | def test_example_case():
n = 5
grid = [
"EEEEB",
"BBBEE",
"EEEEE",
"BEEEE",
"EBEEE"
]
output = find_road(grid, n)
assert output[0] == "Possible"
def test_no_possible_path_case():
n = 4
grid = [
"EEEE",
"BBBB",
"EEEE",
"... | [
{
"docstring": null,
"function_declaration": "def find_road(grid, n):",
"function_name": "find_road",
"parameter_list": "(grid, n)"
},
{
"docstring": null,
"function_declaration": "def solve(n, grid):",
"function_name": "solve",
"parameter_list": "(n, grid)"
},
{
"docstri... | [
0,
0,
0,
0,
0,
1,
0,
0,
0,
0
] | 1 | hard | 0.1 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def dfs(city_grid, x, y, n, path, visited):\n if not (0 <= x < n and 0 <= y < n) or city_grid[x][y] == 'B' or visited[x][y]:\n return False\n pat... | trial_gpt4o_5 | {
"original_instruction": "In an ancient city, there is a square-shaped grid of size $$$n \\times n$$$, where each cell can be either a building (**B**) or an empty plot (**E**). The city council plans to build a new road from the northwest corner (i.e., cell (1,1)) to the southeast corner (i.e., cell (n,n)) of the g... | 0.646177 | Codeforces_4816 | C | [
"find_road",
"solve"
] | 2 | [
[
"solve",
"find_road"
]
] | 1 | [] | false | [] | false | pytest | false | [] | true | 74378068166fcb75c718b2215bfec3c0f508e000 | 9086336b7f16b8d808f6c680733cedd3ff223ffd | |||
v1.0 | complete | Codeforces | Codeforces_5050_C | def preprocess_accesses(access_counts: List[int]) -> List[int]:
"""
Preprocess the access counts to create a prefix sum array.
"""
# Implement the function
def query_sum(prefix_sum: List[int], l: int, r: int) -> int:
"""
Return the sum of accesses in the range [l, r].
"""
# Implement th... | def preprocess_accesses(access_counts):
"""
Preprocess the access counts to create a prefix sum array.
"""
n = len(access_counts)
prefix_sum = [0] * (n + 1)
for i in range(n):
prefix_sum[i + 1] = prefix_sum[i] + access_counts[i]
return prefix_sum
def query_sum(prefix_sum, l, r):
... | from solution import preprocess_accesses, query_sum, process_document_accesses
def test_preprocess_accesses():
access_counts = [3, 2, 1, 4, 5]
prefix_sum = preprocess_accesses(access_counts)
assert prefix_sum == [0, 3, 5, 6, 10, 15]
def test_query_sum():
prefix_sum = [0, 3, 5, 6, 10, 15]
assert qu... | [
{
"docstring": "Preprocess the access counts to create a prefix sum array.",
"function_declaration": "def preprocess_accesses(access_counts):",
"function_name": "preprocess_accesses",
"parameter_list": "(access_counts)"
},
{
"docstring": "Return the sum of accesses in the range [l, r].",
... | [
1,
1,
1,
1,
1,
1,
0
] | 6 | easy | 0.857 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def process_requests(n, accesses, q, queries):\n \"\"\"\n n: int - number of documents\n accesses: List[int] - list of document accesses\n q: int ... | trial_gpt4o_8 | {
"original_instruction": "A large company has a server system that stores several documents. Each document is represented by a unique number from 1 to n. The server receives multiple requests, and each request indicates a range of documents that need to be processed.\n\nYou are required to write a program that will ... | 0.447896 | Codeforces_5050 | C | [
"preprocess_accesses",
"query_sum",
"process_document_accesses"
] | 3 | [
[
"process_document_accesses",
"preprocess_accesses"
],
[
"process_document_accesses",
"query_sum"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 43b1a7359d93f217942a87fe47ec60d1b2b817ca | d10c20e2e1bba17934bc575af1e6761a621f2551 | |||
v1.0 | complete | Codeforces | Codeforces_4751_C | def game_result(N: int, M: int, moves: List[Tuple[int, int, str]]) -> str:
""" Simulates the game and determines the result after all moves have been made.
Prints "X wins" or "O wins" if either player wins, else prints "Draw".
>>> game_result(3, 6, [(1, 1, 'X'), (1, 2, 'O'), (2, 1, 'X'), (2, 2, 'O'), (3, 1,... | def check_winner(grid, N):
"""
Checks for a winner in the grid.
"""
lines = []
# Rows and Columns
for i in range(N):
lines.append(grid[i]) # row
lines.append([grid[j][i] for j in range(N)]) # column
# Diagonals
lines.append([grid[i][i] for i in range(N)]) # main diag... | from solution import game_result
def test_game_result_X_wins():
N = 3
M = 6
moves = [
(1, 1, 'X'),
(1, 2, 'O'),
(2, 1, 'X'),
(2, 2, 'O'),
(3, 1, 'X'),
(3, 2, 'O')
]
assert game_result(N, M, moves) == "X wins"
def test_game_result_O_wins():
N = 3
... | [
{
"docstring": "Checks for a winner in the grid.",
"function_declaration": "def check_winner(grid, N):",
"function_name": "check_winner",
"parameter_list": "(grid, N)"
},
{
"docstring": "Simulates the game and returns the result.",
"function_declaration": "def game_result(N, M, moves):",... | [
1,
1,
1,
0,
1,
1,
0,
0,
1,
0
] | 6 | medium | 0.6 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "def check_winner(grid, N):\n # Check rows and columns\n for i in range(N):\n if all(grid[i][j] == 'X' for j in range(N)) or all(grid[j][i] == 'X'... | trial_gpt4o_8 | {
"original_instruction": "Imagine you're working on a simple game involving a grid of size N x N. The game begins with each cell of the grid being empty, represented by a '.'. Players take turns to place their symbol ('X' or 'O') on the grid in one of the empty cells. The player who successfully places three of thei... | 0.706959 | Codeforces_4751 | C | [
"check_winner",
"game_result"
] | 2 | [
[
"game_result",
"check_winner"
]
] | 1 | [] | false | [] | false | pytest | true | [] | true | d7b398241f2cf59baa78542fd583546cc22e7011 | 82eff4b4ba2cd02b721b4a3b756d8bb4d388fabf | |||
v1.0 | complete | Codeforces | Codeforces_4097_C | def update_value(values, u, v):
"""
Update the value of node u to v.
Args:
values (dict): A dictionary containing the values of the nodes.
u (int): The node to update.
v (int): The new value.
"""
pass
def query_max_value(tree, values, u):
"""
Determine the maximum value in the ... | def update_value(values, u, v):
"""
Update the value of node u to v.
Args:
values (dict): A dictionary containing the values of the nodes.
u (int): The node to update.
v (int): The new value.
"""
values[u] = v
def query_max_value(tree, values, u):
"""
Determine the maximum ... | import pytest
from solution import update_value, query_max_value, process_operations
def test_update_value():
values = {1: 1, 2: 5, 3: 3}
update_value(values, 3, 10)
assert values[3] == 10
def test_query_max_value():
tree = {1: [2], 2: [1, 3], 3: [2, 4, 5], 4: [3], 5: [3]}
values = {1: 1, 2: 5, 3:... | [
{
"docstring": "Update the value of node u to v.\n\nArgs:\nvalues (dict): A dictionary containing the values of the nodes.\nu (int): The node to update.\nv (int): The new value.",
"function_declaration": "def update_value(values, u, v):",
"function_name": "update_value",
"parameter_list": "(values, ... | [
0,
0,
1,
0,
0,
0,
0,
0,
0
] | 1 | hard | 0.111 | {
"trial_gpt4o_0": {
"file_source": "CodeGen_instruction_codeforces-i2i_20000_1739005417_sanitized_prepared0_results_combined.jsonl",
"solution_code": "class TreeNode:\n def __init__(self, value):\n self.value = value\n self.children = []\n self.max_value = value\n\nclass Tree:\n de... | trial_gpt4o_2 | {
"original_instruction": "You are given a tree with `n` nodes rooted at node `1`. Each node has a value assigned to it. Your task is to support the following two types of operations:\n\n1. **Update Operation**:\n - `1 u v`: Assign the value `v` to the node `u`.\n \n2. **Query Operation**:\n - `2 u`: Determine... | 0.552656 | Codeforces_4097 | C | [
"update_value",
"query_max_value",
"process_operations"
] | 3 | [
[
"process_operations",
"query_max_value"
],
[
"process_operations",
"update_value"
]
] | 2 | [] | false | [] | false | pytest | true | [] | true | 4ddae83ffc18aa6f82b08f8c6fe24cf8797874df | 4fe2695e315ac8ef7f78e6085a73af90788048ee |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.