id
stringlengths
9
23
stage
stringclasses
1 value
prompt
stringlengths
36
8.07k
answer
stringlengths
79
7.72k
test
stringlengths
153
4.03k
entry_points
listlengths
0
12
entry_declarations
listlengths
0
12
subset
stringclasses
12 values
gpt_difficulty
stringclasses
3 values
gpt_pass_percentage
float64
0.1
1
Algorithm_10008_I
test
### Problem Statement Write a function to calculate the maximum profit that can be made by performing at most `k` transactions on a list of stock prices, where each transaction consists of buying one unit of stock and selling one unit of stock on later days. You are not allowed to engage in multiple transactions simult...
def max_profit_with_k_transactions(prices, k): """ Calculate the maximum profit that can be made with at most k transactions. :param prices: List[int] - list of stock prices :param k: int - maximum number of transactions allowed :return: int - maximum profit achievable """ if not prices or ...
from solution import max_profit_with_k_transactions def test_example_case(): prices = [3, 2, 6, 5, 0, 3] k = 2 assert max_profit_with_k_transactions(prices, k) == 7 def test_no_transactions(): prices = [3, 2, 6, 5, 0, 3] k = 0 assert max_profit_with_k_transactions(prices, k) == 0 def test_emp...
[ "max_profit_with_k_transactions" ]
[ "def max_profit_with_k_transactions(prices, k):" ]
Algorithm
medium
0.556
Algorithm_10071_I
test
### Coding Problem: Maximize Stock Profits with Limited Transactions #### Context: A stock trader wants to maximize their profits from a given list of daily stock prices, but they are limited to making a fixed number of transactions (buy/sell). A transaction consists of buying one unit of stock and then later selling ...
def max_profit_with_k_transactions(prices, k): if not prices or k == 0: return 0 n = len(prices) if k >= n // 2: return sum(max(prices[i + 1] - prices[i], 0) for i in range(n - 1)) # Initialize the DP table profits = [[0] * n for _ in range(k + 1)] # Fill the DP table ...
from solution import max_profit_with_k_transactions def test_single_transaction(): prices = [3, 2, 6, 5, 0, 3] k = 1 assert max_profit_with_k_transactions(prices, k) == 4 def test_multiple_transactions(): prices = [3, 2, 6, 5, 0, 3] k = 2 assert max_profit_with_k_transactions(prices, k) == 7 ...
[ "max_profit_with_k_transactions" ]
[ "def max_profit_with_k_transactions(prices, k):" ]
Algorithm
easy
0.667
Algorithm_10154_I
test
### Problem Statement You are tasked with developing a function for an educational app aimed at teaching children basic arithmetic operations through an engaging quiz. The function should generate a series of unique arithmetic problems for addition, subtraction, and multiplication based on the given parameters. The f...
import random from typing import List def generate_arithmetic_problems(m: int) -> List[str]: if m < 1: return [] problems = [] operations = ['+', '-', '*'] base_count = m // 3 remainder = m % 3 counts = [base_count, base_count, base_count] for i in range(remainder): counts...
from solution import generate_arithmetic_problems def test_generate_arithmetic_problems_5(): problems = generate_arithmetic_problems(5) assert len(problems) == 5 assert all('+' in problem or '-' in problem or '*' in problem for problem in problems) assert sum('+' in problem for problem in problems) in ...
[ "generate_arithmetic_problems" ]
[ "def generate_arithmetic_problems(m):" ]
Algorithm
medium
0.6
Algorithm_10253_I
test
### Scenario You are developing an application where one of the features includes automatically correcting the layout of words in given paragraphs. Specifically, you need to ensure that any consecutive spaces in the text are reduced to a single space while maintaining the order and content of the words. ### Problem St...
def normalize_spacing(paragraph: str) -> str: """ Takes in a string paragraph and reduces any consecutive spaces to a single space. Leading or trailing spaces are removed if present. """ return ' '.join(paragraph.split())
def test_normalize_spacing_multiple_internal_spaces(): assert normalize_spacing("This is a sample paragraph.") == "This is a sample paragraph." def test_normalize_spacing_trailing_leading_spaces(): assert normalize_spacing(" Leading and trailing spaces are tricky. ") == "Leading and trailing space...
[ "normalize_spacing" ]
[ "def normalize_spacing(paragraph):" ]
Algorithm
easy
0.9
Algorithm_10258_I
test
### Linked List: Detect Cycle Length #### Objective You are to implement a function that detects if a linked list contains a cycle. If a cycle is found, the function should return the length of the cycle. #### Task Write a function `detect_cycle_length` that identifies a cycle in a singly linked list and returns the ...
class ListNode: def __init__(self, value=0, next=None): self.value = value self.next = next def detect_cycle_length(head: ListNode) -> int: """ Detects if a cycle exists in the linked list and returns the length of the cycle. Arguments: head: The head node of the singly lin...
def test_empty_list(): assert detect_cycle_length(None) == -1 def test_single_node_no_cycle(): node = ListNode(1) assert detect_cycle_length(node) == -1 def test_single_node_with_cycle(): node = ListNode(1) node.next = node assert detect_cycle_length(node) == 1 def test_two_nodes_no_cycle(): ...
[]
[]
Algorithm
easy
1
Algorithm_10453_I
test
### Real-Time Stock Market Data Analysis #### Scenario: You are developing a stock market analysis tool that fetches real-time stock data and computes various financial metrics required by investment analysts. The system should be able to handle multiple stock symbols and provide functionalities such as calculating mo...
import pandas as pd from typing import List class StockMarketAnalyzer: def __init__(self): self.data = {} def fetch_data(self, stock_symbols: List[str], start_date: str, end_date: str) -> None: """ Mock function to fetch stock data for the given symbols and store in self.data. ...
import pytest from solution import StockMarketAnalyzer def test_fetch_data(): analyzer = StockMarketAnalyzer() analyzer.fetch_data(["AAPL"], "2022-01-01", "2022-01-31") assert "AAPL" in analyzer.data assert len(analyzer.data["AAPL"]) == 31 def test_calculate_moving_average_invalid_symbol(): analyz...
[]
[]
Algorithm
hard
0.1
Algorithm_10506_I
test
### Minimum Window Substring #### Background You are a developer working on a text processing application. One of the features you need to implement is the ability to find the smallest substring in a given text that contains all the characters from a given pattern. This is useful for various applications, such as keyw...
from collections import Counter def min_window_substring(s, t): """ Returns the smallest substring of `s` that contains all the characters in `t`. If no such substring exists, return an empty string. """ if not t or not s: return "" dict_t = Counter(t) required = len(dict_t) ...
def test_min_window_substring(): assert min_window_substring("ADOBECODEBANC", "ABC") == "BANC" assert min_window_substring("a", "a") == "a" assert min_window_substring("a", "aa") == "" assert min_window_substring("bba", "ab") == "ba" assert min_window_substring("cabwefgewcwaefgcf", "cae") == "cwae" ...
[ "min_window_substring" ]
[ "def min_window_substring(s, t):" ]
Algorithm
hard
0.2
Algorithm_10746_I
test
### Coding Question: You are tasked with implementing a function that returns the depth of the deepest leaf node in a binary tree. The function should use a depth-first search (DFS) approach to traverse the tree and find the maximum depth. **Function Signature:** ```python class TreeNode: def __init__(self, value...
class TreeNode: def __init__(self, value=0, left=None, right=None): self.value = value self.left = left self.right = right def max_depth(root: TreeNode) -> int: if not root: return 0 left_depth = max_depth(root.left) right_depth = max_depth(root.right) retu...
from solution import TreeNode, max_depth def test_empty_tree(): assert max_depth(None) == 0 def test_single_node_tree(): assert max_depth(TreeNode(1)) == 1 def test_right_skewed_tree(): root = TreeNode(1, right=TreeNode(2, right=TreeNode(3))) assert max_depth(root) == 3 def test_balanced_tree_depth_...
[]
[]
Algorithm
easy
1
Algorithm_11028_I
test
### Maze Path Finder #### Problem Statement Given a maze represented by a 2D list, write a function to find if there is a path from the start position to the end position. The start position is always at the top-left corner of the maze (i.e., at position (0, 0)), and the end position is always at the bottom-right corn...
def find_path(maze): rows, cols = len(maze), len(maze[0]) directions = [(1, 0), (0, 1), (-1, 0), (0, -1)] def is_valid(x, y): return 0 <= x < rows and 0 <= y < cols and maze[x][y] == 'O' def dfs(x, y, visited): if (x, y) in visited: return False if (x, y) ==...
def test_find_path(): maze1 = [ ['O', 'O', 'W', 'O'], ['W', 'O', 'W', 'O'], ['O', 'O', 'O', 'O'], ['O', 'W', 'O', 'O'] ] assert find_path(maze1) == True maze2 = [ ['O', 'W', 'W', 'O'], ['W', 'W', 'W', 'O'], ['O', 'O', 'O', 'W'], ['O', 'W',...
[ "find_path", "is_valid", "dfs" ]
[ "def find_path(maze):", "def is_valid(x, y):", "def dfs(x, y, visited):" ]
Algorithm
easy
0.7
Algorithm_11135_I
test
## Scenario: Given an array of integers, you are tasked with finding the length of the longest subarray where the difference between the maximum and minimum elements is less than or equal to a given integer, \( k \). This problem is crucial in scenarios where you need to evaluate the stability or variation within speci...
def longest_stable_subarray(arr, k): """ Find the length of the longest stable subarray where the difference between the max and min elements is <= k. >>> longest_stable_subarray([1, 3, 2, 4, 5], 3) 5 >>> longest_stable_subarray([10, 1, 2, 3, 2, 5, 6], 2) 4 >>> longest_stable_subarray([...
from solution import longest_stable_subarray def test_empty_array(): assert longest_stable_subarray([], 1) == 0 def test_single_element_array(): assert longest_stable_subarray([5], 0) == 1 def test_all_elements_equal(): assert longest_stable_subarray([2, 2, 2, 2], 0) == 4 def test_no_valid_subarray(): ...
[ "longest_stable_subarray" ]
[ "def longest_stable_subarray(arr, k):" ]
Algorithm
hard
0.1
Algorithm_11150_I
test
### Question Write a Python program to implement a K-Means clustering algorithm for a given dataset. The goal is to cluster the instances in the dataset into k clusters and evaluate the clustering performance using a silhouette score. ### Requirements: - Implement the K-Means clustering using `KMeans` from the scikit-...
import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans from sklearn.datasets import make_blobs from sklearn.metrics import silhouette_score from sklearn.preprocessing import StandardScaler def load_dataset(samples: int = 300, centers: int = 3, cluster_std: float = 0.60) -> np.ndarray: ...
import pytest from solution import load_dataset, preprocess_data, kmeans_clustering def test_load_dataset(): data = load_dataset(samples=100, centers=3, cluster_std=0.60) assert data.shape == (100, 2) def test_preprocess_data(): data = np.array([[1, 2], [3, 4], [5, 6]]) processed_data = preprocess_dat...
[ "load_dataset", "preprocess_data", "kmeans_clustering", "main" ]
[ "def load_dataset(samples=300, centers=3, cluster_std=0.6):", "def preprocess_data(data):", "def kmeans_clustering(data):", "def main():" ]
Algorithm
easy
0.9
Algorithm_11347_I
test
### Advanced Problem: Finding the Missing Number in an Arithmetic Progression #### Scenario You are building a function to identify the missing number in an arithmetic progression (AP). An arithmetic progression is a sequence of numbers in which the difference of any two successive members is a constant. Given a list ...
from typing import List def find_missing_number(arr: List[int]) -> int: """ Finds the missing number in an arithmetic progression. The function uses binary search for an optimal O(log n) time complexity. """ n = len(arr) # Calculate the expected common difference total_diff = arr[-1] - arr[...
def test_find_missing_number(): assert find_missing_number([1, 3, 7, 9, 11]) == 5 assert find_missing_number([5, 10, 20, 25]) == 15 assert find_missing_number([10, 20, 30, 50, 60]) == 40 assert find_missing_number([0, 2, 4, 8, 10]) == 6 assert find_missing_number([-10, 0, 10, 30, 40]) == 20 def tes...
[ "find_missing_number" ]
[ "def find_missing_number(arr):" ]
Algorithm
hard
0.1
Algorithm_11385_I
test
### Problem Statement You are tasked with implementing a function to find the smallest substring in a given string `s` that contains all the distinct characters in `s`. The function should be efficient with respect to both time and space complexity. ### Objective Write a function `smallest_substring_with_all_chars(s: ...
def smallest_substring_with_all_chars(s: str) -> str: from collections import defaultdict, Counter # Find all distinct characters in the input string distinct_chars = set(s) num_distinct = len(distinct_chars) # Use a sliding window approach left = 0 min_len = float('inf') min_s...
from solution import smallest_substring_with_all_chars def test_example_1(): s = "abcda" result = smallest_substring_with_all_chars(s) assert result == "abcd" or result == "bcda" def test_example_2(): s = "abac" result = smallest_substring_with_all_chars(s) assert result == "abac" or result ==...
[ "smallest_substring_with_all_chars" ]
[ "def smallest_substring_with_all_chars(s):" ]
Algorithm
hard
0.2
Algorithm_11497_I
test
### Problem Statement You are tasked with implementing a function `find_arithmetic_triplet` that checks if there exists an arithmetic triplet in an array of integers. An arithmetic triplet consists of three elements (a, b, c) such that \(a\), \(b\), and \(c\) are in arithmetic sequence: \(b - a = c - b\). ### Input - ...
def find_arithmetic_triplet(nums): """ Check if there exists an arithmetic triplet in the array `nums`. An arithmetic triplet (a, b, c) satisfies the conditions: - a, b, c are distinct elements in nums - b - a == c - b Params: nums: List[int]: The input list of integers R...
def test_arithmetic_triplet_exists(): assert find_arithmetic_triplet([1, 5, 9, 3, 7]) == True def test_arithmetic_triplet_exists_multiple_triplets(): assert find_arithmetic_triplet([2, 4, 6, 8]) == True def test_arithmetic_triplet_does_not_exist(): assert find_arithmetic_triplet([1, 2, 4]) == False def t...
[ "find_arithmetic_triplet" ]
[ "def find_arithmetic_triplet(nums):" ]
Algorithm
medium
0.4
Algorithm_11520_I
test
### Finding Maximum XOR of a Pair in an Array Given an array of non-negative integers, write a function that returns the maximum XOR value of any two elements in the array. #### Function Signature ```python def find_max_xor(nums: list) -> int: pass ``` #### Input * `nums` (list of int): A list of non-negative in...
class TrieNode: def __init__(self): self.children = {} def find_max_xor(nums): # Create Trie data structure def insert(num): node = trie for bit in range(31, -1, -1): # 32 bits for a non-negative integer cur_bit = (num >> bit) & 1 if cur_bit not in node....
from solution import find_max_xor def test_example_1(): assert find_max_xor([3, 10, 5, 25, 2, 8]) == 28 def test_example_2(): assert find_max_xor([14, 70, 53, 83, 49, 91, 36, 80, 92, 51, 66, 70]) == 127 def test_example_3(): assert find_max_xor([8, 1, 2, 12, 7, 6]) == 15 def test_small_input(): asse...
[]
[]
Algorithm
medium
0.4
Algorithm_11550_I
test
### Context In numerical computing, understanding the behavior of basic operations on different data types is crucial. Floating-point numbers can sometimes lead to precision issues, and one must be cautious while performing equality checks. ### Problem Statement Write a function `approximately_equal(a: float, b: floa...
def approximately_equal(a: float, b: float, tol: float) -> bool: """ Checks if two floating-point numbers `a` and `b` are approximately equal within a given tolerance `tol`. Parameters: a (float): The first floating-point number. b (float): The second floating-point number. tol (float): The...
from solution import approximately_equal def test_approximately_equal_same_numbers(): assert approximately_equal(1.00001, 1.00001, 0.0001) == True def test_approximately_equal_close_numbers_within_tolerance(): assert approximately_equal(1.00001, 1.00002, 0.0001) == True def test_approximately_equal_numbers_o...
[ "approximately_equal" ]
[ "def approximately_equal(a, b, tol):" ]
Algorithm
easy
0.7
Algorithm_11577_I
test
You are required to define a function that formats and extracts specific details from a list of dictionary objects where each dictionary represents data about an employee. The function should also handle missing or incorrect data gracefully. 1. **Data Extraction**: - Extract the employee's full name, employee ID, ...
from typing import List, Dict def process_employee_data(employee_list: List[Dict[str, str]]) -> List[str]: formatted_employee_data = [] for employee in employee_list: try: first_name = employee["first_name"].capitalize() last_name = employee["last_name"].capitalize() ...
from solution import process_employee_data def test_process_employee_data_complete_records(): employees = [ {"first_name": "john", "last_name": "doe", "employee_id": "1234", "department": "engineering"}, {"first_name": "susan", "last_name": "ray", "employee_id": "12131", "department": "marketing"} ...
[ "process_employee_data" ]
[ "def process_employee_data(employee_list):" ]
Algorithm
medium
0.5
Algorithm_11743_I
test
**String Permutations Counter** You are tasked with creating a function that counts all the unique permutations of a given string. The function should return the number of distinct permutations that can be made from the characters of the string. ### Problem Statement Write a function `count_permutations(s: str) -> in...
from math import factorial from collections import Counter def count_permutations(s: str) -> int: """ Returns the count of unique permutations of the input string s. """ n = len(s) if n == 0: return 0 freq_count = Counter(s) denominator = 1 for count in freq_count.values(): ...
from solution import count_permutations def test_unique_characters(): assert count_permutations("abc") == 6 # 3! = 6 def test_duplicates(): assert count_permutations("aab") == 3 # 3! / (2! 1!) = 3 assert count_permutations("aaa") == 1 # 3! / 3! = 1 assert count_permutations("aabb") == 6 # 4! / (2!...
[ "count_permutations" ]
[ "def count_permutations(s):" ]
Algorithm
medium
0.6
Algorithm_11750_I
test
### Question: Employee Time Tracking System You are tasked with enhancing an existing employee time tracking system to improve its functionality and user experience. The current system tracks employee clock-in and clock-out times but lacks several key features. #### Your Task Extend the employee time tracking system ...
def track_time(clock_in: str, clock_out: str) -> dict[str, float]: from datetime import datetime def is_valid_time_format(time_str: str) -> bool: try: datetime.strptime(time_str, "%H:%M") return True except ValueError: return False if not is_valid_time_f...
import pytest from solution import track_time def test_track_time_normal_hours(): assert track_time("09:00", "17:00") == {'total_time': 8.0, 'overtime': 0.0} assert track_time("08:00", "18:30") == {'total_time': 10.5, 'overtime': 2.5} assert track_time("07:45", "19:00") == {'total_time': 11.25, 'overtime':...
[ "track_time", "is_valid_time_format" ]
[ "def track_time(clock_in, clock_out):", "def is_valid_time_format(time_str):" ]
Algorithm
medium
0.6
Algorithm_11780_I
test
### Genetic Algorithm: Optimization ### Scenario You are required to implement a simplified genetic algorithm to solve an optimization problem. The objective is to maximize a given fitness function over a binary search space. ### Task Write a Python function `genetic_algorithm` that performs a genetic algorithm to ma...
import random from typing import List, Callable, Tuple def genetic_algorithm( fitness_function: Callable[[List[int]], float], num_bits: int, population_size: int, generations: int, crossover_rate: float, mutation_rate: float ) -> Tuple[List[int], float]: def create_individual() -> List[int]...
from solution import genetic_algorithm def sample_fitness_function(individual: List[int]) -> float: return sum(individual) def test_genetic_algorithm(): num_bits = 10 population_size = 20 generations = 50 crossover_rate = 0.7 mutation_rate = 0.01 best_individual, best_fitness = genetic_al...
[ "genetic_algorithm", "create_individual", "mutate", "crossover", "tournament_selection" ]
[ "def genetic_algorithm(fitness_function, num_bits, population_size, generations, crossover_rate, mutation_rate):", "def create_individual():", "def mutate(individual, mutation_rate):", "def crossover(parent1, parent2, crossover_rate):", "def tournament_selection(population, k=3):" ]
Algorithm
medium
0.4
Algorithm_11792_I
test
### Problem Statement You are asked to implement a function that evaluates a postfix (Reverse Polish Notation) expression. A postfix expression is a mathematical notation in which every operator follows all of its operands. This format does not need any parentheses as long as operators have a fixed number of operands. ...
def evaluate_postfix(expression: str) -> float: stack = [] operators = {'+', '-', '*', '/'} if not expression: return 0 tokens = expression.split() for token in tokens: if token in operators: b = stack.pop() a = stack.pop() i...
from solution import evaluate_postfix def test_evaluate_postfix_basic(): assert evaluate_postfix("5 1 2 + 4 * + 3 -") == 14 def test_evaluate_postfix_single_operand(): assert evaluate_postfix("5") == 5 def test_evaluate_postfix_addition(): assert evaluate_postfix("3 4 +") == 7 def test_evaluate_postfix_...
[ "evaluate_postfix" ]
[ "def evaluate_postfix(expression):" ]
Algorithm
hard
0.2
Algorithm_11822_I
test
### Problem Description You are given a non-empty list of integers representing the heights of bar graphs. Write a function that computes the maximum rectangular area possible in these bar graphs, where the width of each bar is 1 unit. Each bar’s height is given in the list. ### Function Signature ```python def larges...
def largest_rectangle_area(heights: list) -> int: stack = [] max_area = 0 heights.append(0) # Append 0 to heights to flush remaining heights in stack at the end for i, h in enumerate(heights): while stack and heights[i] < heights[stack[-1]]: height = heights[stack.pop()] ...
def test_largest_rectangle_area(): assert largest_rectangle_area([2, 1, 5, 6, 2, 3]) == 10 assert largest_rectangle_area([2, 4]) == 4 assert largest_rectangle_area([6, 2, 5, 4, 5, 1, 6]) == 12 assert largest_rectangle_area([1, 3, 2, 1, 2]) == 5 assert largest_rectangle_area([2, 1, 2]) == 3 asser...
[ "largest_rectangle_area" ]
[ "def largest_rectangle_area(heights):" ]
Algorithm
medium
0.4
Algorithm_11856_I
test
### Question: Building an Interactive Command-Line To-Do Application #### Context You are asked to develop an interactive command-line to-do application in Python that allows users to manage their tasks efficiently. The application should handle adding, viewing, editing, and deleting tasks, as well as saving and loadi...
import json class ToDoApp: def __init__(self): self.tasks = [] self.next_id = 1 def add_task(self, description: str) -> None: """ Adds a new task to the list with a unique ID and given description. """ task = {"id": self.next_id, "description": descripti...
from solution import ToDoApp def test_add_task(): app = ToDoApp() app.add_task("Test task") assert len(app.tasks) == 1 assert app.tasks[0]["description"] == "Test task" def test_view_tasks_empty(): app = ToDoApp() assert app.view_tasks() == "No tasks available." def test_view_tasks():...
[]
[]
Algorithm
easy
0.889
Algorithm_11886_I
test
### Tree Traversal Verification Challenge #### Background: Tree data structures are a fundamental concept in computer science. They have numerous applications, including representing hierarchical data, managing sorted lists of data, and facilitating search operations. One particular aspect of trees is their traversal ...
def verify_traversals(in_order, pre_order, post_order): if not in_order or not pre_order or not post_order: return in_order == pre_order == post_order == [] if len(in_order) != len(pre_order) or len(in_order) != len(post_order): return False def build_tree_from_in_pre(pre_order, in_order_m...
from solution import verify_traversals def test_verify_traversals_example1(): assert verify_traversals( [4, 2, 5, 1, 6, 3, 7], [1, 2, 4, 5, 3, 6, 7], [4, 5, 2, 6, 7, 3, 1] ) == True def test_verify_traversals_example2(): assert verify_traversals( [4, 2, 5, 1, 6, 3, 7], ...
[ "verify_traversals", "build_tree_from_in_pre", "get_post_order_from_in_pre" ]
[ "def verify_traversals(in_order, pre_order, post_order):", "def build_tree_from_in_pre(pre_order, in_order_map, pre_start, pre_end, in_start, in_end):", "def get_post_order_from_in_pre(pre_order, in_order_map, pre_start, pre_end, in_start, in_end):" ]
Algorithm
hard
0.1
Algorithm_12070_I
test
### Closest Pair of Points **Problem Statement:** Given a list of `n` points on the 2D plane, where each point is represented as a tuple of two integers `(x, y)`, write a function `closest_pair_of_points(points: list[tuple[int, int]]) -> float` that finds and returns the minimum distance between any two points from t...
import math def euclidean_distance(p1, p2): return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) def closest_pair_recursive(points_sorted_by_x, points_sorted_by_y): # Base case if len(points_sorted_by_x) <= 3: min_dist = float('inf') for i in range(len(points_sorted_by_x)): ...
import pytest from solution import closest_pair_of_points def test_closest_pair_basic(): assert math.isclose(closest_pair_of_points([(0, 0), (1, 1), (4, 5), (2, 2)]), 1.4142135623730951, rel_tol=1e-9) def test_closest_pair_less_than_two_points(): with pytest.raises(ValueError, match="At least two points are r...
[ "euclidean_distance", "closest_pair_recursive", "closest_pair_of_points" ]
[ "def euclidean_distance(p1, p2):", "def closest_pair_recursive(points_sorted_by_x, points_sorted_by_y):", "def closest_pair_of_points(points):" ]
Algorithm
medium
0.6
Algorithm_12151_I
test
You are working on an inventory management system that helps businesses track their stock levels and reorder products when necessary. The system should send an email notification when the stock level of an item falls below the reorder threshold. To ensure your code sends the correct email, you should write unit tests t...
def send_email_to_supplier(recipient, subject, body): # This function would typically send an email pass def send_reorder_notification(recipient, item_name): """ Send a reorder notification email to a supplier. Args: recipient (str): The email of the recipient. item_name (str): The nam...
import pytest def fake_send_email(recipient, subject, body): """ A fake email sending function to mock sending email and return a controlled response. """ if not recipient or "@" not in recipient: return {"status": "failed", "message": "Invalid recipient email format"} if not subject: ...
[ "send_email_to_supplier", "send_reorder_notification" ]
[ "def send_email_to_supplier(recipient, subject, body):", "def send_reorder_notification(recipient, item_name):" ]
Algorithm
medium
0.5
Algorithm_12198_I
test
### Coding Assessment Question **Problem Statement**: Given an array of integers, your task is to sort the array according to the frequency of elements. The sorting should be done in such a way that the elements that have higher frequency come first. If two elements have the same frequency, the smaller element should ...
from typing import List from collections import Counter def frequency_sort(arr: List[int]) -> List[int]: """ Sorts the array according to the frequency of elements in descending order. If two elements have the same frequency, the smaller element should precede the larger one. """ # Count the freque...
from solution import frequency_sort def test_frequency_sort_example(): assert frequency_sort([4, 6, 2, 2, 6, 4, 4, 4]) == [4, 4, 4, 4, 2, 2, 6, 6] def test_frequency_sort_empty_array(): assert frequency_sort([]) == [] def test_frequency_sort_single_element(): assert frequency_sort([1]) == [1] def test_f...
[ "frequency_sort" ]
[ "def frequency_sort(arr):" ]
Algorithm
hard
0.1
Algorithm_12334_I
test
### Problem Statement **Context:** You are given a string containing a mix of digits, letters, and other characters. Your task is to identify and sum up all the "hidden" integers within the string. An integer is defined as any consecutive sequence of numerical digits within the string. The final result should be the s...
import re def sum_hidden_integers(s: str) -> int: """ Calculates the sum of hidden integers within the given string. Args: s (str): The input string potentially containing hidden integers. Returns: int: The sum of all hidden integers found within the string. """ # Find all sequences o...
from solution import sum_hidden_integers def test_no_digits(): assert sum_hidden_integers("noDigits") == 0 def test_single_number(): assert sum_hidden_integers("abc123xyz") == 123 def test_multiple_numbers(): assert sum_hidden_integers("a1b2c345") == 348 def test_mixed_with_letters(): assert sum_hid...
[ "sum_hidden_integers" ]
[ "def sum_hidden_integers(s):" ]
Algorithm
easy
1
Algorithm_12433_I
test
### Problem Statement You are developing a system for analyzing and categorizing text documents. One common task in this process is to determine the most frequently occurring words in a document after removing a set of "stop words." Stop words are common words that are often removed because they are considered unimpor...
from typing import List from collections import Counter def most_frequent_words(document: str, stop_words: List[str]) -> List[str]: # Convert document to lowercase and split into words words = document.lower().split() # Filter out the stop words filtered_words = [word for word in words if word not...
from solution import most_frequent_words def test_example_1(): document = "the quick brown fox jumps over the lazy dog" stop_words = ["the", "over"] assert most_frequent_words(document, stop_words) == ["brown", "dog", "fox", "jumps", "lazy", "quick"] def test_example_2(): document = "hello world hello...
[ "most_frequent_words" ]
[ "def most_frequent_words(document, stop_words):" ]
Algorithm
easy
0.8
Algorithm_12608_I
test
### Scenario You are responsible for developing a functionality within a text editor that allows users to perform basic find-and-replace operations on their documents. The implementation needs to handle multiple occurrences of the search string and perform the replacement efficiently. Additionally, the users should be ...
def find_and_replace(text, search, replace, case_sensitive=True): """ Replaces all occurrences of search in text with replace. Handles case-insensitive replacements based on the case_sensitive flag. """ if not text or not search: return text # Nothing to replace if case_sensitive: ...
from solution import find_and_replace def test_find_and_replace_case_sensitive(): text = "Hello World! Welcome to the world of programming." search = "world" replace = "universe" result = find_and_replace(text, search, replace) assert result == "Hello World! Welcome to the universe of programming."...
[ "find_and_replace" ]
[ "def find_and_replace(text, search, replace, case_sensitive=True):" ]
Algorithm
hard
0.1
Algorithm_12635_I
test
### Question: Implementing Depth-First Search for a Graph You need to implement the Depth-First Search (DFS) algorithm to traverse a graph. The function should explore all vertices of a graph starting from a specified source vertex and return the order of visited vertices. ### Scenario In a network analysis tool, you...
def depth_first_search(graph, start_vertex): """ Perform a Depth-First Search (DFS) on the graph starting from the given vertex. Parameters: graph (dict): A dictionary representation of an undirected graph where the keys are vertex identifiers and the values are lists of adjacent vertices. star...
def test_single_node_graph(): graph = {0: []} assert depth_first_search(graph, 0) == [0] def test_simple_connected_graph(): graph = { 0: [1, 2], 1: [0, 3, 4], 2: [0], 3: [1], 4: [1] } assert depth_first_search(graph, 0) == [0, 1, 3, 4, 2] def test_simple_con...
[ "depth_first_search" ]
[ "def depth_first_search(graph, start_vertex):" ]
Algorithm
hard
0.3
Algorithm_12773_I
test
### Problem Statement You are given an array of integers where some integers appear twice and others appear once. Your task is to implement a function that returns all the distinct integers that appear twice in the array. ### Requirements * Implement a function `find_duplicates(nums: List[int]) -> List[int]` that ret...
from typing import List def find_duplicates(nums: List[int]) -> List[int]: """ Returns a sorted list of distinct integers that appear exactly twice in the given array. """ num_count = {} # Count the occurrences of each number for num in nums: if num in num_count: num_co...
from solution import find_duplicates def test_find_duplicates(): assert find_duplicates([4, 3, 2, 7, 8, 2, 3, 1]) == [2, 3] assert find_duplicates([1, 1, 2]) == [1] assert find_duplicates([]) == [] assert find_duplicates([1, 2, 3, 4, 5]) == [] assert find_duplicates([10, 10, 20, 20, 30, 30, 30]) ==...
[ "find_duplicates" ]
[ "def find_duplicates(nums):" ]
Algorithm
hard
0.2
Algorithm_13036_I
test
### Problem Statement You are developing a software for inventory management in a warehouse. The warehouse deals with a variety of items, each of which can be categorized into different types. Write a program that: 1. Takes a list of items where each item is represented by a tuple containing `item_id`, `category`, and...
def aggregate_inventory(items): """ Aggregates the total quantity of items for each category and returns a sorted list of categories with their total quantities in descending order of quantities. Raises a ValueError if any of the quantities are non-positive. """ from collections import defa...
import pytest from solution import aggregate_inventory def test_aggregate_inventory_valid_input(): items = [ ("item_1", "electronics", 10), ("item_2", "furniture", 5), ("item_3", "electronics", 4), ("item_4", "grocery", 15), ("item_5", "furniture", 5) ] expected_outp...
[ "aggregate_inventory" ]
[ "def aggregate_inventory(items):" ]
Algorithm
easy
1
Algorithm_13074_I
test
### Scenario A library is automating the management of its book borrowing system. To better allocate the available books, the librarian wants to optimize the distribution so that the maximum number of books can be borrowed while minimizing the waiting period for the borrowers. Each borrower has a list of books they wis...
def optimize_borrowing(borrower_pref, available_books): """ Optimize the borrowing so that maximum number of borrowers get a book from their preference list. Parameters: borrower_pref (list[list[int]]): List containing the book preferences of each borrower. available_books (list[bool]): List in...
from solution import optimize_borrowing def test_optimize_borrowing_example(): borrower_pref = [[0, 1, 2], [2, 0, 1], [1, 2]] available_books = [True, False, True] assert optimize_borrowing(borrower_pref, available_books) in [[0, 2, -1], [2, 0, -1]] def test_optimize_borrowing_no_pref(): borrower_pref...
[ "optimize_borrowing" ]
[ "def optimize_borrowing(borrower_pref, available_books):" ]
Algorithm
medium
0.5
Algorithm_13075_I
test
### Binary Search Tree (BST) Level Order Traversal A Binary Search Tree (BST) is a node-based binary tree data structure where each node has at most two children referred to as the left child and the right child. For this question, you need to implement the function which performs a level-order traversal on a BST. A l...
from typing import List, Optional from collections import deque class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def insert_into_bst(root: Optional[TreeNode], val: int) -> TreeNode: if root is None: return Tree...
from solution import bst_level_order_traversal def test_bst_level_order_traversal_example1(): assert bst_level_order_traversal([10, 6, 15, 3, 8, 12, 18]) == [[10], [6, 15], [3, 8, 12, 18]] def test_bst_level_order_traversal_example2(): assert bst_level_order_traversal([7, 3, 9, 1, 4, 8, 10]) == [[7], [3, 9], ...
[]
[]
Algorithm
hard
0.3
Algorithm_13084_I
test
**Developing a Custom Sort Algorithm for Optimized Item Retrieval** You are working on a retail application that requires frequent retrieval and display of items based on various priority rules. Currently, items are fetched from a database and displayed in the order they are retrieved. To enhance user experience, the ...
from typing import List, Dict, Any def custom_sort_items(items: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """ Sort items based on custom priority rules. Parameters: - items: List[Dict[str, Any]]: A list of items, where each item is represented as a dictionary. Returns: - List[Dict[str, A...
# Assuming the custom_sort_items function is defined in the file solution.py from solution import custom_sort_items def test_custom_sort_items_varied_popularity(): items = [ {'name': 'Item1', 'popularity': 50, 'price': 30.00, 'availability': True}, {'name': 'Item2', 'popularity': 300, 'price': 20....
[ "custom_sort_items" ]
[ "def custom_sort_items(items):" ]
Algorithm
hard
0.1
Algorithm_13091_I
test
### Coding Question: Implement a Rate Limiter for an API #### Objective: Design and implement a rate limiter function for an API. The function should ensure that a given client does not exceed a specified number of requests in a given time window. If the limit is breached, the function should return an error indicatin...
import time from collections import defaultdict, deque class RateLimiter: def __init__(self): self.requests = defaultdict(deque) def rate_limiter(self, client_id: str, max_requests: int, window: int) -> bool: current_time = time.time() if client_id not in self.requests: sel...
import time from solution import RateLimiter def test_single_client_rate_limit(): limiter = RateLimiter() # Test with a max of 5 requests in 60 seconds assert limiter.rate_limiter("client_1", 5, 60) == True assert limiter.rate_limiter("client_1", 5, 60) == True assert limiter.rate_limiter("cli...
[]
[]
Algorithm
medium
0.6
Algorithm_13167_I
test
### Inventory Management System Optimization You are responsible for maintaining the backend of an inventory management system used by a large retail store. Recently, there have been issues with performance, particularly in the function that updates inventory levels after processing bulk sales transactions. Your task ...
def update_inventory_levels(inventory: dict[str, int], transactions: list[tuple[str, int]]) -> None: """ Updates the inventory levels based on a list of sales transactions. Args: inventory (dict[str, int]): The current inventory levels. transactions (list[tuple[str, int]]): The list of transact...
def test_update_inventory_levels(): inventory = { "product_001": 50, "product_002": 30, "product_003": 100 } transactions = [ ("product_001", 5), ("product_002", 3), ("product_003", 10), ("product_004", 2), ("product_001", 1) ] update_i...
[ "update_inventory_levels" ]
[ "def update_inventory_levels(inventory, transactions):" ]
Algorithm
easy
1
Algorithm_13307_I
test
### Color Palette Optimization **Context**: You are developing a software for a digital artist who frequently changes the color palette in their work. The artist wishes to have their colors sorted in a way that they transition smoothly from one hue to another to facilitate better artistic workflow. **Task**: Write a...
import math def color_distance(color1, color2): """ Helper function to calculate the Euclidean distance between two RGB colors. """ return math.sqrt((color2[0] - color1[0]) ** 2 + (color2[1] - color1[1]) ** 2 + (color2[2] - color1[2]) ** 2) def smooth_color_sort(colors): """ Sorts a list of RG...
from solution import smooth_color_sort, color_distance def test_color_distance(): assert color_distance((0, 0, 0), (0, 0, 0)) == 0 assert color_distance((0, 0, 0), (255, 255, 255)) == math.sqrt(3 * (255 ** 2)) assert color_distance((255, 0, 0), (0, 255, 0)) == math.sqrt(255 ** 2 + 255 ** 2) assert colo...
[ "color_distance", "smooth_color_sort" ]
[ "def color_distance(color1, color2):", "def smooth_color_sort(colors):" ]
Algorithm
hard
0.2
Algorithm_13317_I
test
### Question: Matrix Diagonal Sum and Trace You are provided with two individual tasks. Write two functions to achieve the following: #### Task 1: Sum of Matrix Diagonal Write a function `sum_of_diagonal(matrix: List[List[int]]) -> int` that calculates the sum of all the elements on the main diagonal of a given squar...
def sum_of_diagonal(matrix: list) -> int: if not matrix or any(len(row) != len(matrix) for row in matrix): raise ValueError("Input must be a non-empty square matrix.") return sum(matrix[i][i] for i in range(len(matrix))) def matrix_trace(matrix: list) -> int: return sum_of_diagonal(matrix)
import pytest from solution import sum_of_diagonal, matrix_trace def test_sum_of_diagonal(): assert sum_of_diagonal([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == 15 assert sum_of_diagonal([[5, 0, 0], [0, 5, 0], [0, 0, 5]]) == 15 assert sum_of_diagonal([[2, 1], [1, 2]]) == 4 def test_matrix_trace(): assert mat...
[ "sum_of_diagonal", "matrix_trace" ]
[ "def sum_of_diagonal(matrix):", "def matrix_trace(matrix):" ]
Algorithm
easy
1
Algorithm_13353_I
test
### Question #### Scenario: You are developing a system to manage a collection of files and their related operations. One essential aspect of this system is organizing the files in such a way that allows for quick retrieval, insertion, and removal. To achieve this, you decide to implement a Min-Heap data structure, wh...
def insert(heap, new_value): """ Inserts a new_value into the Min-Heap and maintains the heap property. """ heap.append(new_value) _bubble_up(heap, len(heap) - 1) def remove_min(heap): """ Removes and returns the minimum element from the Min-Heap while maintaining the heap property. """...
from solution import insert, remove_min, heapify def test_heapify(): assert heapify([15, 10, 25, 6, 14, 20, 60]) == [6, 10, 20, 15, 14, 25, 60] assert heapify([3, 1, 2]) == [1, 3, 2] assert heapify([]) == [] assert heapify([1]) == [1] def test_insert(): heap = heapify([15, 10, 25, 6, 14, 20, 60]) ...
[ "insert", "remove_min", "heapify", "_bubble_up", "_bubble_down" ]
[ "def insert(heap, new_value):", "def remove_min(heap):", "def heapify(values):", "def _bubble_up(heap, index):", "def _bubble_down(heap, index):" ]
Algorithm
medium
0.5
Algorithm_13482_I
test
### Duplicate Character Counting You are given a string consisting of lowercase and uppercase alphabets. You need to write a function that counts the number of characters that appear more than once in the string, regardless of their case (i.e., 'a' is considered the same as 'A'). ### Function Signature ```python def ...
def count_duplicate_characters(s: str) -> int: """ Returns the number of characters that appear more than once in the string s, ignoring case. """ from collections import Counter # Convert the string to lowercase s = s.lower() # Count the frequency of each character char_co...
from solution import count_duplicate_characters def test_case_insensitivity(): assert count_duplicate_characters("aA") == 1 assert count_duplicate_characters("AaBbCcDd") == 4 def test_no_duplicates(): assert count_duplicate_characters("abcdef") == 0 def test_all_same_character(): assert count_duplica...
[ "count_duplicate_characters" ]
[ "def count_duplicate_characters(s):" ]
Algorithm
medium
0.6
Algorithm_13508_I
test
### Binary Search in a Rotated Sorted Array You are building a search feature for a library catalog system. The system stores book IDs in a special format: a rotated sorted array. A rotated sorted array is an array that has been sorted in ascending order and then rotated (shifted) at a certain pivot point. For instanc...
from typing import List def search_rotated_array(nums: List[int], target: int) -> int: """ Finds the index of a target book ID in a rotated sorted array. Parameters: nums (List[int]): A list of integers representing a rotated sorted array of unique book IDs. target (int): The book ID to search...
from solution import search_rotated_array def test_search_found_at_pivot(): assert search_rotated_array([4, 5, 6, 7, 0, 1, 2], 0) == 4 def test_search_not_found(): assert search_rotated_array([4, 5, 6, 7, 0, 1, 2], 3) == -1 def test_search_single_element_found(): assert search_rotated_array([1], 1) == 0 ...
[ "search_rotated_array" ]
[ "def search_rotated_array(nums, target):" ]
Algorithm
hard
0.1
Algorithm_13609_I
test
### Scenario: You are asked to implement a system to manage a collection of social network messages. Each message has a unique ID, a timestamp, and a content string. You must provide functionality to **add** a message and **retrieve** the most recent N messages, sorted by their timestamps. ### Requirements: 1. **Add M...
from typing import List, Tuple class MessageSystem: def __init__(self): self.messages = [] def add_message(self, message_id: int, timestamp: int, content: str) -> None: import heapq heapq.heappush(self.messages, (-timestamp, message_id, content)) def get_recent_messages(self, N: i...
from solution import MessageSystem def test_add_message(): ms = MessageSystem() ms.add_message(1, 1633030123, "Hello World") assert ms.messages == [(-1633030123, 1, "Hello World")] def test_get_recent_messages(): ms = MessageSystem() ms.add_message(1, 1633030123, "Hello World") ms.add_message(...
[]
[]
Algorithm
medium
0.6
Algorithm_13681_I
test
### Problem Statement You are developing a feature for a navigation system that determines the shortest route between various landmarks in a city. The city is represented as a 2D grid, where certain cells contain obstacles that cannot be traversed. This task assesses your ability to implement pathfinding algorithms an...
from typing import List, Tuple from collections import deque def find_shortest_path(grid: List[List[int]], start: Tuple[int, int], end: Tuple[int, int]) -> int: """ Finds the shortest path from start to end in a 2D grid avoiding obstacles. Args: grid: A 2D list of integers where 0 represents an em...
def test_no_obstacles(): grid = [ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ] start = (0, 0) end = (3, 3) assert find_shortest_path(grid, start, end) == 6 def test_with_obstacles(): grid = [ [0, 0, 0, 0], [1, 1, 0, 1], [0, 0, ...
[ "find_shortest_path" ]
[ "def find_shortest_path(grid, start, end):" ]
Algorithm
easy
0.8
Algorithm_13743_I
test
### Task You are tasked with designing and implementing a function that balances a set of parentheses in a given string. The balance of parentheses is crucial in expressions to ensure their correct evaluation or functionality. ### Problem Statement **Function Signature**: ```python def balance_parentheses(expression:...
def balance_parentheses(expression: str) -> str: """ Balances the parentheses in the given expression by adding the minimum number of necessary parentheses. """ # To keep track of the open parentheses open_parentheses_count = 0 # List to build the corrected expression balanced_expression = [...
def test_balance_parentheses(): assert balance_parentheses("a + (b * c) - (d / e") == "a + (b * c) - (d / e)" assert balance_parentheses("((a+b)") == "((a+b))" assert balance_parentheses("a + b + c") == "a + b + c" assert balance_parentheses("(((a + b)))") == "(((a + b)))" assert balance_parentheses...
[ "balance_parentheses" ]
[ "def balance_parentheses(expression):" ]
Algorithm
hard
0.2
Algorithm_13828_I
test
### Context Graph traversal algorithms are fundamental to many computer science problems involving network analysis, pathfinding, and search engines. One of these algorithms is Depth-First Search (DFS), which explores as far down a branch as possible before backtracking. It is useful in scenarios requiring the full exp...
def depth_first_search(graph: dict, start_node: int) -> list: visited = [] stack = [start_node] while stack: node = stack.pop() if node not in visited: visited.append(node) # Add neighbors in reverse order to visit them in the correct sequence stack.e...
from solution import depth_first_search def test_dfs_simple_graph(): graph = { 0: [1, 2], 1: [0, 3, 4], 2: [0, 5, 6], 3: [1], 4: [1], 5: [2], 6: [2] } assert depth_first_search(graph, 0) == [0, 1, 3, 4, 2, 5, 6] def test_dfs_single_node(): graph ...
[ "depth_first_search" ]
[ "def depth_first_search(graph, start_node):" ]
Algorithm
easy
0.9
Algorithm_13984_I
test
### Coding Challenge: Detecting Cycles in a Directed Graph #### Scenario: In some complex routing networks where nodes represent junctions and directed edges represent one-way streets, it's crucial to detect if there are any cycles within the system. A cycle exists if you can start from any node and return to the same...
def detect_cycle(n: int, edges: list[tuple[int, int]]) -> bool: from collections import defaultdict def dfs(node): if visited[node] == 1: return True if visited[node] == 2: return False visited[node] = 1 for neighbor in graph[node]: if dfs(nei...
def test_detect_cycle(): # Test cases assert detect_cycle(5, [(0, 1), (1, 2), (2, 3), (3, 4), (4, 2)]) == True, "Test case 1 failed" assert detect_cycle(3, [(0, 1), (1, 2)]) == False, "Test case 2 failed" assert detect_cycle(1, [(0, 0)]) == True, "Test case 3 failed" # Self-loop assert detect_cycle...
[ "detect_cycle", "dfs" ]
[ "def detect_cycle(n, edges):", "def dfs(node):" ]
Algorithm
hard
0.3
Algorithm_14005_I
test
### Coding Assessment Question: Ordered Word List Manipulation #### Context You have been given a list of words that are initially sorted in ascending alphabetical order. You need to perform various operations on this list, including inserting new words while maintaining the order and removing specific words efficient...
import bisect class OrderedWordList: def __init__(self): """ Initializes an empty ordered word list. """ self.words = [] def add_word(self, word: str) -> None: """ Adds a new word to the list while maintaining the alphabetical order. Args: ...
from solution import OrderedWordList def test_add_word(): ol = OrderedWordList() ol.add_word("apple") ol.add_word("banana") assert str(ol) == "['apple', 'banana']" def test_add_word_insert_middle(): ol = OrderedWordList() ol.add_word("apple") ol.add_word("banana") ol.add_word("apricot"...
[]
[]
Algorithm
medium
0.6
Algorithm_14093_I
test
### Coding Assessment Question You need to assist in evaluating the performance of a research institute by analyzing the scores of research papers published by its researchers. Each paper is rated on a scale from 0 to 100. Your task is to calculate the H-index of the researchers. The H-index is defined as follows: - ...
from typing import List def calculate_h_index(citations: List[int]) -> int: """ Calculate the H-index for a list of citation counts. :param citations: List of non-negative integers representing citation counts :return: The H-index value """ # Sort citations in descending order citation...
from solution import calculate_h_index def test_calculate_h_index_example_cases(): assert calculate_h_index([6, 5, 3, 1, 0]) == 3 assert calculate_h_index([10, 8, 5, 4, 3]) == 4 def test_calculate_h_index_single_paper(): assert calculate_h_index([10]) == 1 assert calculate_h_index([0]) == 0 def test_...
[ "calculate_h_index" ]
[ "def calculate_h_index(citations):" ]
Algorithm
medium
0.6
Algorithm_14341_I
test
### Context: You have been hired by a company developing a geometric shapes library. One of the essential features they want to include is the ability to dynamically compute the area of various regular polygons given the side length and the number of sides. ### Task: Extend the `RegularPolygon` class to support dynami...
import numpy as np class RegularPolygon: def __init__(self, side_length, num_sides): self.side_length = side_length self.num_sides = num_sides def calculate_area(self): if self.num_sides <= 2: raise ValueError("Number of sides must be greater than 2") return (self.n...
import pytest from solution import RegularPolygon import numpy as np def test_triangle_area(): triangle = RegularPolygon(3, 3) assert np.isclose(triangle.calculate_area(), 3.897114317029974) def test_square_area(): square = RegularPolygon(4, 4) assert np.isclose(square.calculate_area(), 16.0) def tes...
[]
[]
Algorithm
medium
0.5
Algorithm_14402_I
test
### Scenario You are a software engineer working on a logging system for a large-scale distributed application. One of your tasks is to create a function that identifies and counts error codes that appear consecutively in the log data. This functionality helps to detect potential problems and patterns in the logs. ##...
from typing import List def count_consecutive_errors(log: List[int]) -> int: """ Counts the distinct error codes which appear consecutively in the log. """ consecutive_errors = set() previous_code = None for i in range(1, len(log)): if log[i] == log[i-1]: consecutive_er...
from solution import count_consecutive_errors def test_example_cases(): assert count_consecutive_errors([1, 1, 2, 3, 3, 3, 4, 5, 5]) == 3 assert count_consecutive_errors([7, 8, 9, 10]) == 0 assert count_consecutive_errors([4, 4, 4, 4, 4, 4]) == 1 def test_single_element(): assert count_consecutive_err...
[ "count_consecutive_errors" ]
[ "def count_consecutive_errors(log):" ]
Algorithm
medium
0.6
Algorithm_14407_I
test
## Task You are provided with a simplified version of a matrix multiplication function. Your task is to complete the `strassen_matrix_multiplication` function using Strassen's algorithm for matrix multiplication to achieve more efficient O(n^2.81) time complexity compared to conventional O(n^3) matrix multiplication. ...
import numpy as np def conventional_matrix_multiplication(A: np.ndarray, B: np.ndarray) -> np.ndarray: return np.dot(A, B) def add_matrix(A: np.ndarray, B: np.ndarray) -> np.ndarray: return A + B def subtract_matrix(A: np.ndarray, B: np.ndarray) -> np.ndarray: return A - B def split_matrix(A: np.ndarray...
import numpy as np from solution import strassen_matrix_multiplication def test_basic_case_2x2(): A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) expected_result = np.array([[19, 22], [43, 50]]) assert np.array_equal(strassen_matrix_multiplication(A, B), expected_result) def test_identit...
[ "conventional_matrix_multiplication", "add_matrix", "subtract_matrix", "split_matrix", "strassen_matrix_multiplication" ]
[ "def conventional_matrix_multiplication(A, B):", "def add_matrix(A, B):", "def subtract_matrix(A, B):", "def split_matrix(A):", "def strassen_matrix_multiplication(A, B):" ]
Algorithm
easy
0.778
Algorithm_14520_I
test
### Maximal Product Subarray #### Context You are developing a financial data analysis tool that provides insights based on historical price movements. One challenging task is to identify the period during which the product of daily returns is maximized. Given an array of daily returns, you need to find the contiguou...
from typing import List def maximal_product_subarray(arr: List[float]) -> float: if not arr: return 0 max_product = min_product = result = arr[0] for num in arr[1:]: if num < 0: max_product, min_product = min_product, max_product max_product = max(num, max...
def test_maximal_product_subarray(): assert maximal_product_subarray([2.5, -3.0, 4.0, -1.0]) == 30.0 assert maximal_product_subarray([-2.0, 0.0, -1.0]) == 0.0 assert maximal_product_subarray([0.1, 0.2, -1.0, 5.0, 2.0, -2.0, 1.0]) == 20.0 assert maximal_product_subarray([-1.0]) == -1.0 assert maximal...
[ "maximal_product_subarray" ]
[ "def maximal_product_subarray(arr):" ]
Algorithm
hard
0.1
Algorithm_14826_I
test
### Problem Statement Implement a function that finds the longest path in a matrix where each path starts at a cell containing a specific value and can move to an adjacent cell if it contains the next integer value (step size of 1). The path should only move horizontally, vertically, or diagonally. ### Input * A 2D l...
def longest_path(ROW: int, COL: int, matrix: list[list[int]], start_val: int) -> int: def dfs(r, c): if dp[r][c] != -1: return dp[r][c] max_path = 1 # Each cell is a path of length 1 for dr, dc in directions: nr, nc = r + dr, c + dc if 0 <= nr < ...
from solution import longest_path def test_longest_path_example(): matrix = [ [1, 2, 3], [6, 5, 4], [7, 8, 9] ] ROW, COL, start_val = 3, 3, 1 assert longest_path(ROW, COL, matrix, start_val) == 9 def test_longest_path_single_element(): matrix = [ [1] ] ROW, ...
[ "longest_path", "dfs" ]
[ "def longest_path(ROW, COL, matrix, start_val):", "def dfs(r, c):" ]
Algorithm
hard
0.222
Algorithm_14839_I
test
### Coding Question: Implement a Palindrome Permutation Checker **Objective**: Write a Python function that checks if any permutation of a given string can form a palindrome. To achieve this, your function should: 1. Count the frequency of each character in the input string. 2. Determine if the characters can be rea...
def can_form_palindrome(s: str) -> bool: from collections import Counter # Count the frequency of each character char_count = Counter(s) # Count the number of characters with odd frequencies odd_count = sum(1 for count in char_count.values() if count % 2 != 0) # A string can form ...
from solution import can_form_palindrome def test_can_form_palindrome_true(): assert can_form_palindrome("carrace") == True assert can_form_palindrome("aabbccdd") == True assert can_form_palindrome("aabbccdde") == True assert can_form_palindrome("racecar") == True def test_can_form_palindrome_false():...
[ "can_form_palindrome" ]
[ "def can_form_palindrome(s):" ]
Algorithm
medium
0.6
Algorithm_1483_I
test
Advanced Sorting Algorithms - Hybrid Merge-Quick Sort In this task, you are required to create an enhanced sorting algorithm that combines the best features of Merge Sort and Quick Sort. This hybrid sorting algorithm should switch from Quick Sort to Merge Sort once the recursion depth exceeds a certain threshold. This...
import math def hybrid_sort(values): """ Sorts the provided list of integers using a hybrid of Quick Sort and Merge Sort. Switches to Merge Sort when the recursion depth exceeds log(n). Parameters: - values: List[int] Returns: - List[int] """ if len(values) <= 1: r...
def test_hybrid_sort(): # Test Case 1: Already sorted list assert hybrid_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] # Test Case 2: Reverse sorted list assert hybrid_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] # Test Case 3: List with duplicates assert hybrid_sort([4, 2, 2, 3, 1, 4]) == [1, ...
[ "hybrid_sort", "quick_sort", "merge_sort", "merge" ]
[ "def hybrid_sort(values):", "def quick_sort(vals, depth):", "def merge_sort(vals):", "def merge(left, right):" ]
Algorithm
medium
0.5
Algorithm_149_I
test
**String Permutation Checker** Write a function `is_permutation` that takes two strings as input and determines whether they are permutations of each other. In other words, the function should return `True` if one string can be rearranged to form the other string, and `False` otherwise. Your function should consider ...
def is_permutation(s1: str, s2: str) -> bool: """ Determines if s1 is a permutation of s2. Parameters: s1 (str): First string. s2 (str): Second string. Returns: bool: True if s1 is a permutation of s2, False otherwise. """ # Early exit if the lengths of the strings are diff...
from solution import is_permutation def test_is_permutation_case_1(): assert is_permutation("abc", "cba") == True def test_is_permutation_case_2(): assert is_permutation("abc", "def") == False def test_is_permutation_case_3(): assert is_permutation("A man, a plan, a canal, Panama", "A man, a plan, a cana...
[ "is_permutation" ]
[ "def is_permutation(s1, s2):" ]
Algorithm
medium
0.6
Algorithm_1535_I
test
### Sparse Matrix Representation Sparse matrices are matrices that are predominantly composed of zeroes. In order to save memory, these matrices can be represented in a more efficient way. #### Objective Create a class `SparseMatrix` that supports the following operations: 1. Initialization of a sparse matrix given i...
from typing import List, Tuple class SparseMatrix: def __init__(self, dense_matrix: List[List[int]]): self.dense_matrix = dense_matrix self.csr_values = [] self.csr_columns = [] self.csr_row_pointer = [] if dense_matrix: self.rows = len(dense_matrix) ...
from solution import SparseMatrix def test_to_csr(): matrix = [ [0, 0, 3, 0], [22, 0, 0, 0], [0, 0, 0, 0], [0, 5, 0, 0] ] sparse_matrix = SparseMatrix(matrix) csr = sparse_matrix.to_csr() assert csr == ([3, 22, 5], [2, 0, 1], [0, 1, 2, 2, 3]) def test_multiply(): ...
[]
[]
Algorithm
medium
0.5
Algorithm_15403_I
test
### Problem Statement You have been provided with a number of packages, each with a weight as an integer. These packages need to be delivered using a drone that has a weight limit. Your task is to determine the minimum number of trips the drone needs to make to deliver all the packages without exceeding its weight lim...
from typing import List def minimum_trips(weights: List[int], limit: int) -> int: weights.sort(reverse=True) i, j = 0, len(weights) - 1 trips = 0 while i <= j: if i == j: # Only one package left trips += 1 break if weights[i] + weights[j] <= limit: ...
def test_minimum_trips_example1(): assert minimum_trips([1, 2, 3, 4, 5], 5) == 3 def test_minimum_trips_example2(): assert minimum_trips([9, 8, 7, 6, 2, 1], 10) == 4 def test_minimum_trips_example3(): assert minimum_trips([2, 2, 3, 3, 4, 4], 5) == 4 def test_minimum_trips_single_package(): assert min...
[ "minimum_trips" ]
[ "def minimum_trips(weights, limit):" ]
Algorithm
hard
0.1
Algorithm_15534_I
test
### Question: Scheduling Tasks with Priority and Time Constraints **Context**: A company has a set of tasks that need to be completed by certain deadlines. Each task has a start time, an end time (deadline), and a priority level. The goal is to maximize the total priority of completed tasks within the given time const...
from typing import List class Task: def __init__(self, name: str, start_time: int, end_time: int, priority: int): self.name = name self.start_time = start_time self.end_time = end_time self.priority = priority def schedule_tasks(tasks: List[Task]) -> List[Task]: # Sort tasks by...
from solution import Task, schedule_tasks def test_schedule_tasks_no_overlap(): tasks = [ Task("Task A", 1, 3, 50), Task("Task B", 4, 6, 60), Task("Task C", 7, 9, 70), ] scheduled_tasks = schedule_tasks(tasks) assert [task.name for task in scheduled_tasks] == ["Task A", "Task B"...
[]
[]
Algorithm
hard
0.1
Algorithm_15589_I
test
### Problem Statement You are given an array of integers `nums` and an integer `target`. Your task is to determine whether there is a pair of integers in the array whose sum is equal to the given `target`. If such a pair exists, return the indices of the two integers in the form of a list `[index1, index2]`. The indice...
def find_pair_with_sum(nums: list[int], target: int) -> list[int]: """ Returns a list of two indices whose values in the input array sum up to the target. If no such pair exists, returns an empty list. """ # Dictionary to store the complement and its index complement_map = {} for index,...
from solution import find_pair_with_sum def test_find_pair_with_sum_example1(): assert find_pair_with_sum([2, 7, 11, 15], 9) == [0, 1] def test_find_pair_with_sum_example2(): assert find_pair_with_sum([1, 2, 3, 4], 7) == [2, 3] def test_find_pair_with_sum_example3(): assert find_pair_with_sum([3, 2, 4], ...
[ "find_pair_with_sum" ]
[ "def find_pair_with_sum(nums, target):" ]
Algorithm
hard
0.2
Algorithm_15776_I
test
### Database Schema Design: Bookstore Inventory Your task is to design a relational database schema for managing a bookstore's inventory. Similar to the provided example for managing a library system, you will define tables, fields, and relationships to effectively store and organize data about books, authors, and pub...
def create_bookstore_schema(): schema_script = """ -- Create table for publishers CREATE TABLE publishers ( publisher_id INT PRIMARY KEY, name VARCHAR(255) NOT NULL, address VARCHAR(255), phone VARCHAR(15), email VARCHAR(100) ); -- Create table for authors ...
from solution import create_bookstore_schema def test_create_bookstore_schema(): schema_script = create_bookstore_schema() assert 'CREATE TABLE publishers (' in schema_script assert 'CREATE TABLE authors (' in schema_script assert 'CREATE TABLE books (' in schema_script assert 'CREATE TABLE book_au...
[ "create_bookstore_schema" ]
[ "def create_bookstore_schema():" ]
Algorithm
hard
0.2
Algorithm_15783_I
test
### Coding Assessment Question E-commerce platforms frequently need to recommend products to users based on various criteria, including purchase history and product ratings. To streamline this, data structures can facilitate quick and efficient product lookups. ### Problem Context: You are managing an e-commerce data...
def filter_products_by_rating(reviews, min_avg_rating): """ Returns a list of product IDs that meet or exceed the specified minimum average rating. :param reviews: dict where keys are product IDs and values are lists of integers representing ratings. :param min_avg_rating: float representing the mi...
def test_filter_products_by_rating(): reviews = { "p1": [5, 4, 4, 5], "p2": [3, 2, 4], "p3": [5, 5, 5], "p4": [1, 1, 1, 1] } assert filter_products_by_rating(reviews, 4.0) == ["p1", "p3"] reviews = { "a34": [2, 3, 4], "b56": [4, 4, 4], "c78": ...
[ "filter_products_by_rating" ]
[ "def filter_products_by_rating(reviews, min_avg_rating):" ]
Algorithm
medium
0.6
Algorithm_15810_I
test
### Coding Assessment Question #### Context: You are required to implement an algorithm that sorts a list of strings based on their lengths. In case of a tie where two strings have the same length, the strings should maintain their relative order from the original list. This sorting approach is a stable sort. #### Ta...
def stable_length_sort(strings): """ Sorts a list of strings based on their lengths in ascending order. If two strings have the same length, their relative order is preserved. Args: strings (List[str]): List of strings to be sorted. Returns: List[str]: List of strings sorted by the...
from solution import stable_length_sort def test_stable_length_sort_basic(): assert stable_length_sort(["word", "longest", "a", "verylongword", "mid"]) == ["a", "mid", "word", "longest", "verylongword"] def test_stable_length_sort_same_length(): assert stable_length_sort(["bb", "aa", "cc"]) == ["bb", "aa", "c...
[ "stable_length_sort" ]
[ "def stable_length_sort(strings):" ]
Algorithm
easy
0.9
Algorithm_15937_I
test
### Coding Problem: Longest Subsequence by Sum #### Context: In data analysis and algorithm development, it is often necessary to find subsequences within sequences that satisfy specific criteria. One common problem is identifying the longest subsequence of numbers within an array that has a sum less than or equal to ...
def longest_subsequence_by_sum(arr, target_sum): """ Finds the longest subsequence within the array `arr` such that the sum of its elements is less than or equal to `target_sum`. Args: arr (list[int]): The input array. target_sum (int): The target sum. Returns: tuple: A tuple c...
from solution import longest_subsequence_by_sum def test_example_case(): arr = [5, 1, 3, 2, 5, 7, 3, 9] target_sum = 10 assert longest_subsequence_by_sum(arr, target_sum) == (3, [5, 1, 3]) def test_empty_array(): arr = [] target_sum = 10 assert longest_subsequence_by_sum(arr, target_sum) == (0...
[ "longest_subsequence_by_sum" ]
[ "def longest_subsequence_by_sum(arr, target_sum):" ]
Algorithm
hard
0.1
Algorithm_15945_I
test
### Question: Implement a Moving Average Filter for Time Series Data You are tasked with implementing a moving average filter for a time series dataset. The moving average filter is commonly used in signal processing and time series analysis to smooth out short-term fluctuations and highlight longer-term trends or cyc...
import numpy as np def moving_average_filter(data: np.ndarray, window_size: int) -> np.ndarray: """ Implements the moving average filter on a time series dataset. Parameters: data (ndarray): A numpy array of numeric values representing the time series data. window_size (int): The size of t...
import numpy as np from solution import moving_average_filter def test_moving_average_filter_basic(): data = np.array([1, 2, 3, 4, 5]) window_size = 3 expected_output = np.array([1.0, 1.5, 2.0, 3.0, 4.0]) assert np.allclose(moving_average_filter(data, window_size), expected_output) def test_moving_ave...
[ "moving_average_filter" ]
[ "def moving_average_filter(data, window_size):" ]
Algorithm
hard
0.3
Algorithm_16131_I
test
### Question: Multi-threaded Matrix Multiplication You are tasked with implementing a multi-threaded approach to matrix multiplication. Matrix multiplication involves computing the product of two matrices, where each element of the resulting matrix is the dot product of a row from the first matrix and a column from th...
import threading def multi_threaded_matrix_multiplication(A, B): """ Multiplies two matrices A and B using multiple threads. """ if not A or not B: return [] # Get the dimensions of the matrices num_rows_A, num_cols_A = len(A), len(A[0]) num_rows_B, num_cols_B = len(B), len(B[0...
import pytest from solution import multi_threaded_matrix_multiplication def test_multiplication_basic(): A = [ [1, 2], [3, 4] ] B = [ [5, 6], [7, 8] ] assert multi_threaded_matrix_multiplication(A, B) == [[19, 22], [43, 50]] def test_multiplication_single_element():...
[ "multi_threaded_matrix_multiplication", "calculate_element" ]
[ "def multi_threaded_matrix_multiplication(A, B):", "def calculate_element(i, j):" ]
Algorithm
medium
0.5
Algorithm_16145_I
test
### FizzBuzz with a Twist You are tasked with creating a modified version of the classic FizzBuzz problem. Your function should print numbers from 1 to a given integer `n`. However, for multiples of a given divisor `x`, print "Fizz" instead of the number, for multiples of another given divisor `y`, print "Buzz", and f...
def is_prime(num): """Helper function to check if a number is prime.""" if num <= 1: return False if num <= 3: return True if num % 2 == 0 or num % 3 == 0: return False i = 5 while i * i <= num: if num % i == 0 or num % (i + 2) == 0: return False ...
import pytest from solution import fizz_buzz_prime def test_fizz_buzz_prime_basic(): assert fizz_buzz_prime(15, 3, 5) == None # Expected output # 1 # Prime # Fizz # Prime # Buzz # Fizz # 7 # Prime # Fizz # Buzz # 11 # Fizz # Prime # 14 # FizzBuzz def...
[ "is_prime", "fizz_buzz_prime" ]
[ "def is_prime(num):", "def fizz_buzz_prime(n, x, y):" ]
Algorithm
hard
0.1
Algorithm_16292_I
test
### Problem Statement You are managing a team of developers, and one of their tasks involves parsing a collection of log entries from a system. Each entry consists of a timestamp in "YYYY-MM-DD HH:MM:SS" format, followed by a log message. Your team needs a function to extract specific information for analytics. Your ...
def extract_logs(logs, date): """ Extracts log messages from logs that match the given date. Args: logs (list of str): List of log entries in the format "YYYY-MM-DD HH:MM:SS - <message>" date (str): A specific date in "YYYY-MM-DD" format Returns: list of str: List of log messages that ...
def test_extract_logs_single_entry_matching_date(): logs = ["2023-01-01 12:00:00 - System rebooted"] date = "2023-01-01" assert extract_logs(logs, date) == ["System rebooted"] def test_extract_logs_multiple_entries_matching_date(): logs = [ "2023-01-01 12:00:00 - System rebooted", "2023...
[ "extract_logs" ]
[ "def extract_logs(logs, date):" ]
Algorithm
easy
1
Algorithm_16320_I
test
### Coding Assessment Question #### Task You are required to write a Python program that processes data from a CSV file containing information about various books and their attributes, and calculates specific metrics based on the data. #### Function Specifications Write a function `analyze_books(csv_filepath: str) ->...
import csv from collections import defaultdict def analyze_books(csv_filepath: str) -> dict: try: with open(csv_filepath, mode='r', encoding='utf-8') as file: reader = csv.DictReader(file) total_books = 0 total_ratings = 0 highest_rating = -float('inf') ...
import pytest import os from solution import analyze_books def write_csv(file_path, content): with open(file_path, mode='w', encoding='utf-8') as file: file.write(content) def test_analyze_books(): test_csv_content = """title,author,genre,rating The Great Gatsby,F. Scott Fitzgerald,Fiction,4.5 To Kill...
[ "analyze_books" ]
[ "def analyze_books(csv_filepath):" ]
Algorithm
medium
0.6
Algorithm_16328_I
test
**Context:** You are asked to develop a utility that computes the sum of elements in a given range of an integer array. This problem frequently arises in the context of competitive programming and performance-critical applications where efficient data retrieval is crucial. ### Task: Write a class-based solution using ...
class SegmentTree: def build(self, arr): """ Constructs the Segment Tree from the given array. """ self.n = len(arr) self.tree = [0] * (2 * self.n) # Build the segment tree # Initialize leaves for i in range(self.n): self.tree[self.n + i] =...
def test_segment_tree_operations(): seg_tree = SegmentTree() arr = [1, 3, 5, 7, 9, 11] seg_tree.build(arr) assert seg_tree.range_sum(1, 3) == 15 # 3 + 5 + 7 seg_tree.update(1, 10) assert seg_tree.range_sum(1, 3) == 22 # 10 + 5 + 7 seg_tree.update(2, 0) assert seg_tree.ra...
[]
[]
Algorithm
easy
0.8
Algorithm_16391_I
test
### Matrix Transposer You are assigned the task of creating a method in the `MatrixOperations` class to transpose a given 2D numpy array. **Task**: Add the following method to the `MatrixOperations` class: ```python def transpose_matrix(self): """ Transpose the given matrix. :return: Transposed matrix ...
import numpy as np class MatrixOperations: def __init__(self, matrix): self.matrix = matrix def transpose_matrix(self): """ Transpose the given matrix. :return: Transposed matrix """ return self.matrix.T
from solution import MatrixOperations import numpy as np def test_transpose_square_matrix(): matrix = np.array([[1, 2], [3, 4]]) expected = np.array([[1, 3], [2, 4]]) mop = MatrixOperations(matrix) result = mop.transpose_matrix() np.testing.assert_array_equal(result, expected) def test_transpose_r...
[]
[]
Algorithm
medium
0.5
Algorithm_16468_I
test
## Problem Statement ### Count Distinct Primes in Range You are given two positive integers `a` and `b`. Your task is to implement a function `count_distinct_primes(a: int, b: int) -> int` that returns the count of distinct prime numbers between `a` and `b` (inclusive). ### Input - **a**: A positive integer such tha...
def count_distinct_primes(a, b): """ Returns the count of distinct prime numbers between a and b (inclusive). """ def sieve_of_eratosthenes(limit): sieve = [True] * (limit + 1) sieve[0] = sieve[1] = False p = 2 while p * p <= limit: if sieve[p]: ...
from solution import count_distinct_primes def test_count_distinct_primes_small_range(): assert count_distinct_primes(10, 20) == 4 # primes: 11, 13, 17, 19 assert count_distinct_primes(1, 10) == 4 # primes: 2, 3, 5, 7 def test_count_distinct_primes_single_prime(): assert count_distinct_primes(2, 2) == ...
[ "count_distinct_primes", "sieve_of_eratosthenes" ]
[ "def count_distinct_primes(a, b):", "def sieve_of_eratosthenes(limit):" ]
Algorithm
medium
0.5
Algorithm_16499_I
test
### Question: Managing Employee Hierarchies In a company, employees are arranged in a hierarchy. Each employee reports to exactly one manager, and the hierarchy forms a tree structure with the CEO at the root. The goal is to write a function that computes the total number of direct and indirect reports for each employ...
from typing import List, Tuple, Dict from collections import defaultdict def compute_employee_reports(employee_hierarchy: List[Tuple[int, int]]) -> Dict[int, int]: # Build the graph adjacency list and a dictionary to hold the counts graph = defaultdict(list) report_counts = defaultdict(int) for employ...
from solution import compute_employee_reports def test_example_scenario(): assert compute_employee_reports([(2, 1), (3, 1), (4, 2), (5, 2), (6, 3)]) == {1: 5, 2: 2, 3: 1, 4: 0, 5: 0, 6: 0} def test_single_relationship(): assert compute_employee_reports([(2, 1)]) == {1: 1, 2: 0} def test_no_reports(): ass...
[ "compute_employee_reports", "dfs" ]
[ "def compute_employee_reports(employee_hierarchy):", "def dfs(employee):" ]
Algorithm
hard
0.3
Algorithm_16699_I
test
### Problem Scenario You are asked to design an inventory management system for a bookstore. The system needs to track the stock levels of various books and ensure no book goes out of stock without triggering a restocking alert. Each time a sale is made, the stock level should be updated accordingly, and if the stock ...
from typing import Dict, List class BookInventory: def __init__(self, initial_stock: Dict[str, int], restock_threshold: int): self.stock = initial_stock self.restock_threshold = restock_threshold def sell_book(self, book_title: str, quantity: int) -> bool: if book_title not in self...
from solution import BookInventory def test_initial_stock(): inventory = BookInventory({"Book A": 50, "Book B": 20, "Book C": 5}, restock_threshold=10) assert inventory.stock == {"Book A": 50, "Book B": 20, "Book C": 5} assert inventory.restock_threshold == 10 def test_sell_book_successful(): inventor...
[]
[]
Algorithm
medium
0.5
Algorithm_16708_I
test
### Pathfinding in a Grid with Obstacles You are implementing a robot's navigation system to find the shortest path from a starting position to a destination within a grid environment. The grid consists of `0`s (walkable cells) and `1`s (obstacles). The robot can move up, down, left, or right but cannot move diagonall...
from collections import deque def shortest_path(grid, start, end): if not grid or start == end: return [start] if start == end and grid[start[0]][start[1]] == 0 else [] rows, cols = len(grid), len(grid[0]) directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] queue = deque([(start, [start])]) vi...
from solution import shortest_path def test_no_obstacles(): grid = [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ] start = (0, 0) end = (2, 2) assert shortest_path(grid, start, end) == [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)] def test_with_obstacles(): grid = [ [0, 1, 0], ...
[ "shortest_path" ]
[ "def shortest_path(grid, start, end):" ]
Algorithm
hard
0.1
Algorithm_17014_I
test
### Problem: Binary Tree Zigzag Level Order Traversal As a software developer, you are tasked with implementing a function to perform a zigzag level order traversal of a binary tree. The zigzag traversal implies that alternate levels are traversed from right to left and left to right, respectively. #### Instructions:...
from collections import deque class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def zigzag_level_order(root: TreeNode): if not root: return [] results = [] current_level = deque([root]) left_to_...
def test_zigzag_level_order(): # Create example binary tree: # 3 # / \ # 9 20 # / \ # 15 7 root = TreeNode(3) root.left = TreeNode(9) root.right = TreeNode(20) root.right.left = TreeNode(15) root.right.right = TreeNode(7) assert zigzag_level_order(ro...
[]
[]
Algorithm
easy
1
Algorithm_17069_I
test
### Coding Task: Matrix Zigzag Traversal You are given a 2D matrix. Implement a function to return a list of all the elements of the matrix in zigzag order. The traversal should start from the top-left corner of the matrix and proceed to the top-right corner, then move to the bottom-left corner, and finish at the bott...
def zigzag_traversal(matrix): """ Returns the elements of the 2D matrix in zigzag order. :param matrix: a list of lists of integers representing the 2D matrix. :return: a list of integers representing the matrix elements in zigzag order. """ rows = len(matrix) cols = len(matrix[0]) ...
def test_zigzag_3x3_matrix(): matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] assert zigzag_traversal(matrix) == [1, 2, 4, 7, 5, 3, 6, 8, 9] def test_zigzag_2x2_matrix(): matrix = [ [1, 2], [3, 4] ] assert zigzag_traversal(matrix) == [1, 2, 3, 4] def test_z...
[ "zigzag_traversal" ]
[ "def zigzag_traversal(matrix):" ]
Algorithm
medium
0.4
Algorithm_17073_I
test
Binary Search Tree (BST) Implementation and Range Sum Calculation You are required to implement a Binary Search Tree (BST) and provide functions to insert elements and calculate the range sum of values within a specified range. Implement the following functions: 1. **insert** - To insert a new value into the BST. 2. ...
class TreeNode: def __init__(self, value: int): self.value = value self.left = None self.right = None def insert(root: TreeNode, value: int) -> TreeNode: """ Insert a value into the BST. Args: - root (TreeNode): The root node of the BST. - value (int): The value to be in...
from solution import TreeNode, insert, find_range_sum def test_insert(): root = TreeNode(4) insert(root, 2) insert(root, 6) insert(root, 1) insert(root, 3) insert(root, 5) insert(root, 7) assert root.left.value == 2 assert root.right.value == 6 assert root.left.left.value =...
[]
[]
Algorithm
easy
0.778
Algorithm_17118_I
test
### Coding Assessment Question #### Context You are developing a simple text editor with a feature that automatically formats text into paragraphs of a given maximum width. Each word should be separated by a single space, and lines should be left-justified. #### Objective Write a function that formats a given list of...
def format_paragraph(words: list[str], max_width: int) -> list[str]: """ Formats a list of words into a paragraph of lines, each with a maximum width of max_width. Args: words (list of str): The list of words to format. max_width (int): The maximum width of each line. Returns: list...
def test_format_paragraph_basic_usage(): assert format_paragraph( ["This", "is", "a", "sample", "paragraph", "formatted", "into", "multiple", "lines"], 10 ) == ["This is a", "sample", "paragraph", "formatted", "into", "multiple", "lines"] def test_format_paragraph_different_width(): assert format_p...
[ "format_paragraph" ]
[ "def format_paragraph(words, max_width):" ]
Algorithm
hard
0.111
Algorithm_17296_I
test
### Scenario In this task, you will design a command-line tool that processes a log file and generates a summary report. The log file contains entries of different events, with each line consisting of a timestamp, a log level (INFO, WARNING, ERROR), and a message. ### Objective Create a script that processes the log f...
import re from collections import defaultdict, Counter from datetime import datetime LOG_PATTERN = re.compile( r'(?P<date>\d{4}-\d{2}-\d{2}) (?P<time>\d{2}:\d{2}:\d{2}) \[(?P<level>INFO|WARNING|ERROR)\] (?P<message>.+)' ) def process_log_file(log_file_path): level_counts = Counter() hourly_counts = Counte...
import os from solution import process_log_file, filter_log_by_date def create_test_log_file(file_path, content): with open(file_path, 'w') as f: f.write(content) def remove_test_log_file(file_path): if os.path.exists(file_path): os.remove(file_path) def test_process_log_file_with_example_log...
[ "process_log_file", "filter_log_by_date" ]
[ "def process_log_file(log_file_path):", "def filter_log_by_date(log_file_path, date_str):" ]
Algorithm
medium
0.4
Algorithm_17318_I
test
### Problem Statement: Prime Number Rotation A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. A number is considered to be a "rotatable prime" if each rotation of its digits forms a valid prime number. For example, 197 is a rotatable prime because rot...
def is_prime(n): """ Checks if a number is prime. """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def ...
from solution import is_rotatable_prime def test_single_digit_primes(): assert is_rotatable_prime(2) == True assert is_rotatable_prime(3) == True assert is_rotatable_prime(5) == True assert is_rotatable_prime(7) == True def test_non_prime_single_digits(): assert is_rotatable_prime(1) == False ...
[ "is_prime", "get_rotations", "is_rotatable_prime" ]
[ "def is_prime(n):", "def get_rotations(number):", "def is_rotatable_prime(number):" ]
Algorithm
hard
0.1
Algorithm_17404_I
test
### K-Means Clustering and Elbow Method Implementation In this assessment, you are required to implement functions for K-Means Clustering and the Elbow Method. Your implementation should include appropriate error handling and optimizations as outlined. The functions should strictly follow the operational steps and req...
import numpy as np from scipy.spatial.distance import cdist from sklearn.cluster import KMeans from typing import Union def k_means_clustering(features: np.ndarray, clusters: int) -> np.ndarray: """ K-Means Clustering. Parameters: * features: The features extracted from the dataset (numpy arra...
import numpy as np import pytest from solution import k_means_clustering, elbow_method def test_k_means_clustering_valid_input(): features = np.array([[1, 2], [1, 3], [4, 5], [6, 8], [6, 9]]) clusters = 2 labels = k_means_clustering(features, clusters) assert len(labels) == len(features) assert set...
[ "k_means_clustering", "elbow_method" ]
[ "def k_means_clustering(features, clusters):", "def elbow_method(features, max_clusters):" ]
Algorithm
medium
0.6
Algorithm_17445_I
test
### Problem: Counting Island Perimeters in a Grid You are tasked with calculating the total perimeter of the connected island cells in a grid. ### Function Signature ```python def island_perimeters(grid: list[list[int]]) -> int: """ Parameters: - grid : list of lists of integers : a 2D list representing t...
def island_perimeters(grid: list[list[int]]) -> int: """ Calculates the total perimeter of islands in the given grid. Parameters: - grid: list of lists of integers, where 0 represents water and 1 represents land Returns: - int: the total perimeter of all islands """ def is_wate...
from solution import island_perimeters def test_single_cell_island(): grid = [ [0, 0, 0], [0, 1, 0], [0, 0, 0] ] assert island_perimeters(grid) == 4 def test_multiple_cells_island(): grid = [ [0, 1, 0], [1, 1, 1], [0, 1, 0] ] assert island_perime...
[ "island_perimeters", "is_water" ]
[ "def island_perimeters(grid):", "def is_water(i, j):" ]
Algorithm
medium
0.5
Algorithm_1762_I
test
### Coding Assessment Question #### Scenario You are given a matrix representing the layout of a garden where each cell contains an integer representing the height of a plant in that cell. Your task is to find the highest possible sum of the heights of plants in any rectangular submatrix of the garden. #### Problem S...
from typing import List def max_sum_submatrix(matrix: List[List[int]]) -> int: """ Returns the highest possible sum of the heights of plants in any rectangular submatrix. Args: matrix (List[List[int]]): The 2D matrix of integers representing plant heights. Returns: int: The highest possib...
import pytest from solution import max_sum_submatrix def test_max_sum_submatrix_example_1(): matrix = [ [1, 2, -1, -4, -20], [-8, -3, 4, 2, 1], [3, 8, 10, 1, 3], [-4, -1, 1, 7, -6], ] assert max_sum_submatrix(matrix) == 29 def test_max_sum_submatrix_example_2(): matrix ...
[ "max_sum_submatrix", "max_sum_subarray" ]
[ "def max_sum_submatrix(matrix):", "def max_sum_subarray(arr):" ]
Algorithm
medium
0.4
Algorithm_1764_I
test
**Question**: Design a **LRU Cache** class that supports `get` and `put` operations with constant average time complexity. ### Context Your task is to implement a Least Recently Used (LRU) cache. The LRU cache should evict the least recently used item when it reaches its capacity. This type of cache is widely used for...
class LRUCache: class Node: def __init__(self, key: int, value: int): self.key = key self.value = value self.prev = None self.next = None def __init__(self, capacity: int): self.capacity = capacity self.cache = {} self.head = self...
import pytest from solution import LRUCache def test_lru_cache_usage_example(): cache = LRUCache(2) cache.put(1, 1) cache.put(2, 2) assert cache.get(1) == 1 cache.put(3, 3) assert cache.get(2) == -1 cache.put(4, 4) assert cache.get(1) == -1 assert cache.get(3) == 3 ...
[]
[]
Algorithm
easy
1
Algorithm_17702_I
test
### Implement a Simple Database using Dictionary You are tasked with implementing a simple in-memory database that supports basic CRUD (Create, Read, Update, Delete) operations. The database will store record objects and allow the user to manipulate records identified by unique IDs. #### Tasks: 1. **Database Class I...
class Record: def __init__(self, attributes): """ Initialize a record with attributes, which are stored in a dictionary. """ self.attributes = attributes class Database: def __init__(self): """ Initialize with an empty dictionary to hold records. """ ...
from solution import Record, Database def test_create_and_read_record(): db = Database() record1 = Record({'name': 'Alice', 'age': '30', 'city': 'New York'}) db.create('001', record1) assert db.read('001').attributes == {'name': 'Alice', 'age': '30', 'city': 'New York'} assert db.read('002') i...
[]
[]
Algorithm
easy
0.9
Algorithm_17718_I
test
### Binary Search Tree (BST) Operations and Depth Calculation #### Context You are tasked with implementing and enhancing a Binary Search Tree (BST) data structure that supports standard insertion, search, and deletion operations, as well as calculating the depth of the tree. This will help ensure comprehension of tre...
class TreeNode: def __init__(self, key: int): self.key = key self.left = None self.right = None class BinarySearchTree: def __init__(self): self.root = None def insert(self, key: int): self.root = self._insert(self.root, key) def _insert(self, node: TreeNode, k...
from solution import BinarySearchTree, tree_depth, process_operations def test_insert_and_search(): bst = BinarySearchTree() bst.insert(5) bst.insert(3) bst.insert(7) assert bst.search(5) == True assert bst.search(3) == True assert bst.search(7) == True assert bst.search(4) == False de...
[]
[]
Algorithm
medium
0.5
Algorithm_17727_I
test
### Question: Implement a Tic-Tac-Toe Game Judge #### Context: Tic-Tac-Toe is a classic two-player game also known as Naughts and Crosses. The game is played on a 3x3 grid, where players take turns to place their mark, either 'X' or 'O', in an empty cell. The player who succeeds in placing three of their marks in a h...
def tic_tac_toe_judge(board: list) -> str: # Check rows and columns for i in range(3): if board[i][0] != '' and board[i][0] == board[i][1] and board[i][1] == board[i][2]: return board[i][0] if board[0][i] != '' and board[0][i] == board[1][i] and board[1][i] == board[2][i]: ...
from solution import tic_tac_toe_judge def test_X_wins_horizontal(): board = [ ['X', 'X', 'X'], ['O', '', 'O'], ['', '', 'O'] ] assert tic_tac_toe_judge(board) == 'X' def test_O_wins_vertical(): board = [ ['X', 'O', 'X'], ['X', 'O', ''], ['', 'O', ''] ...
[ "tic_tac_toe_judge" ]
[ "def tic_tac_toe_judge(board):" ]
Algorithm
hard
0.1
Algorithm_17746_I
test
Sorting Strings by Character Frequency #### Problem Statement You are given a function `sort_by_frequency` that sorts an array of strings based on the frequency of a specified character within each string. Your task is to implement this function. #### Function Signature ```python def sort_by_frequency(strings: list,...
def sort_by_frequency(strings, char): """ Sorts strings by the frequency of the specified character in descending order. """ return sorted(strings, key=lambda s: s.count(char), reverse=True)
def test_sort_by_frequency_with_varied_frequencies(): assert sort_by_frequency(["apple", "banana", "cherry", "date"], 'a') == ['banana', 'apple', 'date', 'cherry'] def test_sort_by_frequency_with_no_target_char(): assert sort_by_frequency(["apple", "banana", "cherry", "date"], 'x') == ['apple', 'banana', 'cher...
[ "sort_by_frequency" ]
[ "def sort_by_frequency(strings, char):" ]
Algorithm
hard
0.1
Algorithm_18245_I
test
### Question: Reversing a Linked List You are given a singly linked list where each node contains an integer value and a pointer to the next node. The task is to reverse the linked list, such that the last node becomes the first node and now its `next` pointer points to the previous node, and so on. Implement the fol...
class ListNode: def __init__(self, value: int = 0, next_node: 'ListNode' = None): self.value = value self.next = next_node def reverse_linked_list(head: 'ListNode') -> 'ListNode': """ Reverses the given linked list. Args: head (ListNode): The head node of the singly linked list. ...
def test_reverse_linked_list_empty(): assert reverse_linked_list(None) is None def test_reverse_linked_list_single_node(): head = ListNode(1, None) new_head = reverse_linked_list(head) assert new_head.value == 1 assert new_head.next is None def test_reverse_linked_list_multiple_nodes(): head =...
[]
[]
Algorithm
easy
1
Algorithm_183_I
test
### Problem Statement You are tasked with implementing a function that returns the number of subarrays with a sum equal to a given target integer `t` within a given list of integers. ### Function Signature ```python def count_subarrays_with_sum(arr: list, t: int) -> int: """ Returns the number of subarrays tha...
def count_subarrays_with_sum(arr, t): """ Returns the number of subarrays that sum up to t within the given list arr. """ count = 0 current_sum = 0 sum_dict = {0: 1} # Initialize with 0 sum having one count for edge cases. for num in arr: current_sum += num if current_sum ...
def test_count_subarrays_with_sum(): assert count_subarrays_with_sum([1, 2, 3], 3) == 2 assert count_subarrays_with_sum([1, -1, 1], 1) == 3 assert count_subarrays_with_sum([1, 2, 3], 6) == 1 assert count_subarrays_with_sum([-1, -1, 1], 0) == 1 assert count_subarrays_with_sum([], 0) == 0 assert c...
[ "count_subarrays_with_sum" ]
[ "def count_subarrays_with_sum(arr, t):" ]
Algorithm
hard
0.2
Algorithm_18529_I
test
### Coding Question You are asked to create a function that predicts the next most likely value in a numeric sequence using a simple Linear Regression model. The model should be able to handle a sequence of numbers, fit a line to the sequence using least squares method, and then predict the next value following the la...
def predict_next_value(sequence): """ Predict the next value in the given numeric sequence using Linear Regression. Arguments: sequence -- a list of numeric values representing the sequence Returns: A single numeric value representing the predicted next value. """ N = len(seque...
from solution import predict_next_value def test_predict_next_value_increasing_sequence(): assert predict_next_value([1, 2, 3, 4, 5]) == 6.0 def test_predict_next_value_decreasing_sequence(): assert predict_next_value([5, 4, 3, 2, 1]) == 0.0 def test_predict_next_value_mixed_sequence(): assert predict_ne...
[ "predict_next_value" ]
[ "def predict_next_value(sequence):" ]
Algorithm
medium
0.6
Algorithm_18777_I
test
### Number of Occurrences Challenge Given a list of integers, write a function that returns a dictionary where each key is an integer from the list, and the corresponding value is the number of times that integer appears in the list. ### Function Signature ```python def count_occurrences(numbers: list[int]) -> dict[i...
def count_occurrences(numbers: list[int]) -> dict[int, int]: """ Returns a dictionary with the counts of each integer in the input list. """ occurrence_dict = {} for number in numbers: if number in occurrence_dict: occurrence_dict[number] += 1 else: occurrence...
from solution import count_occurrences def test_empty_list(): assert count_occurrences([]) == {} def test_single_element(): assert count_occurrences([1]) == {1: 1} def test_multiple_occurrences(): assert count_occurrences([1, 2, 2, 3, 1, 1, 4]) == {1: 3, 2: 2, 3: 1, 4: 1} def test_identical_elements(): ...
[ "count_occurrences" ]
[ "def count_occurrences(numbers):" ]
Algorithm
easy
1
Algorithm_18952_I
test
### Question #### Objective Your task is to implement a function to evaluate the Infix expression and convert it into its equivalent Postfix expression using the Shunting Yard algorithm. The Shunting Yard algorithm converts an infix expression (i.e., human-readable mathematical notation) into a postfix expression (i.e....
def infix_to_postfix(expression: str) -> str: """ Convert infix expression to postfix using Shunting Yard algorithm. """ # Define operator precedence precedence = {'+': 1, '-': 1, '*': 2, '/': 2} # Define the stack and postfix list stack = [] postfix = [] # Remove all spaces fro...
from solution import infix_to_postfix def test_simple_expression(): assert infix_to_postfix("3 + 5") == "3 5 +" def test_with_parentheses(): assert infix_to_postfix("( 1 + 2 ) * 3") == "1 2 + 3 *" def test_mixed_operators(): assert infix_to_postfix("10 + 2 * 6") == "10 2 6 * +" def test_more_complex_exp...
[ "infix_to_postfix" ]
[ "def infix_to_postfix(expression):" ]
Algorithm
medium
0.6
Algorithm_18973_I
test
### Coding Assessment Question #### Scenario You are tasked with developing a feature for an event planning application. Users should be able to input events with a start and end time, and you will need to determine whether any new event conflicts with the existing ones. #### Task 1. **Function Implementation**: Im...
from typing import List, Tuple def check_conflict(new_event: Tuple[int, int], current_events: List[Tuple[int, int]]) -> bool: """ Checks if the new_event conflicts with any of the current_events. Args: new_event (tuple): A tuple representing the start and end times of the proposed event. current_e...
from solution import check_conflict def test_no_current_events(): assert check_conflict((3, 7), []) == False def test_no_overlap(): current_events = [(1, 5), (6, 10), (12, 15)] new_event = (16, 18) assert check_conflict(new_event, current_events) == False def test_overlap_start(): current_events ...
[ "check_conflict" ]
[ "def check_conflict(new_event, current_events):" ]
Algorithm
easy
0.7
Algorithm_19112_I
test
### Recursive Fibonacci Sequence You are tasked with implementing the Fibonacci sequence in Python using a recursive approach. The function should take a single integer as the input and return the nth Fibonacci number. #### Function Signature ```python def fibonacci(n: int) -> int: ``` #### Parameters: - `n` (int): ...
def fibonacci(n: int) -> int: """ Returns the nth Fibonacci number using a recursive approach. Parameters: n (int): The position in the Fibonacci sequence (0-indexed) to compute the Fibonacci number for. Returns: int: The nth Fibonacci number. """ if n == 0: return 0 ...
from solution import fibonacci def test_fibonacci_base_cases(): assert fibonacci(0) == 0 assert fibonacci(1) == 1 def test_fibonacci_small_values(): assert fibonacci(2) == 1 assert fibonacci(3) == 2 assert fibonacci(4) == 3 assert fibonacci(5) == 5 def test_fibonacci_medium_values(): asse...
[ "fibonacci" ]
[ "def fibonacci(n):" ]
Algorithm
easy
1
Algorithm_19224_I
test
### Problem Statement Design a function `find_common_elements(matrix)` that finds all the common elements present in each row of a given matrix. ### Function Signature ```python def find_common_elements(matrix: list[list[int]]) -> list[int]: pass ``` ### Input - `matrix`: A list of lists of integers where each i...
def find_common_elements(matrix: list[list[int]]) -> list[int]: if not matrix: return [] # Initialize the common elements set with the first row's elements common_elements = set(matrix[0]) # Iterate through the rest of the rows and perform intersection for row in matrix[1:]: co...
from solution import find_common_elements def test_example_cases(): matrix1 = [ [1, 2, 3, 4, 5], [2, 3, 5, 8, 10], [2, 3, 6, 7, 9] ] assert sorted(find_common_elements(matrix1)) == [2, 3] matrix2 = [ [10, 15, 20, 25], [15, 20, 35, 40, 50], [5, 15, 20, 30...
[ "find_common_elements" ]
[ "def find_common_elements(matrix):" ]
Algorithm
easy
1
Algorithm_19288_I
test
### Problem Statement: Longest Word with Given Letters Given a list of words and a set of letters, write a function `longest_word_with_letters(words, letters)` that returns the longest word from the list that can be formed using the given set of letters. Each letter in the set can only be used as many times as it appe...
from typing import List from collections import Counter def longest_word_with_letters(words: List[str], letters: str) -> str: letter_count = Counter(letters) # Helper function to determine if a word can be formed with given letters def can_form_word(word): word_count = Counter(word) fo...
from solution import longest_word_with_letters def test_longest_word_with_letters_example1(): assert longest_word_with_letters(["apple", "banana", "cherry"], "aabnnnaa") == "banana" def test_longest_word_with_letters_example2(): assert longest_word_with_letters(["hello", "world"], "ehllloh") == "hello" def t...
[ "longest_word_with_letters", "can_form_word" ]
[ "def longest_word_with_letters(words, letters):", "def can_form_word(word):" ]
Algorithm
medium
0.625