target
stringlengths
29
3.65k
data_source
stringclasses
12 values
prompt
listlengths
1
1
ability
stringclasses
1 value
reward_model
dict
extra_info
dict
def find_second_largest(arr): unique = list(set(arr)) if len(unique) < 2: return -1 sorted_unique = sorted(unique, reverse=True) return sorted_unique[1]
simplelr_Prefill
[ { "content": "Question:\nWrite a function to find the second largest number in an array. If the array has less than 2 unique elements, the function should return -1. How can I implement this in Python?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6500, "level": 1, "question": "Write a function to find the second largest number in an array. If the array has less than 2 unique elements, the function should return -1. How can I implement this in Python?", "split": "train" }
def bubble_sort(lst): n = len(lst) for i in range(n - 1): swapped = False for j in range(0, n - i - 1): if lst[j] > lst[j + 1]: lst[j], lst[j + 1] = lst[j + 1], lst[j] swapped = True if not swapped: break return lst # Example u...
simplelr_Filter
[ { "content": "Question:\nImplement a sorting algorithm in Python that takes a list of integers as input and outputs the list in ascending order. The algorithm should have a time complexity of O(n^2) and should not use any built-in sorting functions or libraries.\nAnswer:\nLet's think step by step.\n", "role...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6501, "level": 1, "question": "Implement a sorting algorithm in Python that takes a list of integers as input and outputs the list in ascending order. The algorithm should have a time complexity of O(n^2) and should not use any built-in sorting functions or libraries.", "split": "...
import bisect def count_distinct_chars(s, queries): # Preprocess the string to build a dictionary mapping each character to its indices char_positions = {chr(ord('a') + i): [] for i in range(26)} for idx, c in enumerate(s): char_positions[c].append(idx) result = [] for start, end in qu...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a string `s` which consists of lowercase English letters and a list of `queries`, where each query is a list containing two integers `[start, end]`. For each query, find the count of distinct characters in the substring of `s` starting from index `start` to index `end` (in...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6502, "level": 1, "question": "You are given a string `s` which consists of lowercase English letters and a list of `queries`, where each query is a list containing two integers `[start, end]`. For each query, find the count of distinct characters in the substring of `s` starting fr...
def remove_duplicates(points): """ Remove duplicates based on x-coordinate and keep the point with the smallest y-coordinate. Args: points (list): A list of tuples, where each tuple contains an x and y coordinate. Returns: list: A list of tuples, where each tuple contains an x and y co...
simplelr_Filter
[ { "content": "Question:\nI have a set of 2D points (x, y) with some of them being duplicates. I want to remove all duplicates based on their x-coordinate, keeping only the one with the smallest y-coordinate. To achieve this, I can use a dictionary where the keys are the x-coordinates and the values are the y-co...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6503, "level": 1, "question": "I have a set of 2D points (x, y) with some of them being duplicates. I want to remove all duplicates based on their x-coordinate, keeping only the one with the smallest y-coordinate. To achieve this, I can use a dictionary where the keys are the x-coor...
def generate_spiral_matrix(m, n): matrix = [[0 for _ in range(n)] for _ in range(m)] top = 0 bottom = m - 1 left = 0 right = n - 1 num = 1 while top <= bottom and left <= right: # Fill top row for i in range(left, right + 1): matrix[top][i] = num num +...
simplelr_Leetcode
[ { "content": "Question:\nGiven two integers `m` and `n`, where `1 ≤ m, n ≤ 9`, return _an m x n matrix filled with elements from 1 to m * n in spiral order_. The matrix should be filled by moving from the outermost elements towards the inner ones, spiraling inwards in a clockwise direction.\nAnswer:\nLet's thin...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6504, "level": 1, "question": "Given two integers `m` and `n`, where `1 ≤ m, n ≤ 9`, return _an m x n matrix filled with elements from 1 to m * n in spiral order_. The matrix should be filled by moving from the outermost elements towards the inner ones, spiraling inwards in a clockw...
def categorize_numbers(numbers): result = { 'low': [], 'medium': [], 'high': [] } for num in numbers: if 1 <= num <= 100: if 1 <= num <= 33: result['low'].append(num) elif 34 <= num <= 66: result['medium'].append(num) ...
simplelr_Package
[ { "content": "Question:\nYou will be writing a Python function named `categorize_numbers` that takes a list of integers and classifies them into three categories: 'low', 'medium', and 'high'. The function should return a dictionary containing three keys ('low', 'medium', 'high') with each key mapping to a list ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6505, "level": 1, "question": "You will be writing a Python function named `categorize_numbers` that takes a list of integers and classifies them into three categories: 'low', 'medium', and 'high'. The function should return a dictionary containing three keys ('low', 'medium', 'high...
def snake_game(grid, moves): # Find the initial position of the snake start = None for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 'S': start = (i, j) break if start: break snake = [start] directio...
simplelr_Package
[ { "content": "Question:\nYou are required to write a function that simulates a game of \"Snake\" on a 2D grid and returns the final length of the snake after a series of moves. In the game, the snake starts with an initial length of 1 and can grow by eating food placed on the grid.\n\n### Function Signature\n\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6506, "level": 1, "question": "You are required to write a function that simulates a game of \"Snake\" on a 2D grid and returns the final length of the snake after a series of moves. In the game, the snake starts with an initial length of 1 and can grow by eating food placed on the ...
from typing import List def trap(height: List[int]) -> int: """ Calculates the maximum amount of water that can be trapped between the bars represented by the provided elevation map. Args: height (List[int]): A list of non-negative integers representing the elevation map. Returns: ...
simplelr_Algorithm
[ { "content": "Question:\n### Task Description\nYou are required to implement a function that simulates a water retention problem in a given topography and determines the maximum amount of water that can be trapped after raining.\n\n### Problem Statement\nGiven `n` non-negative integers representing an elevation...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6507, "level": 1, "question": "### Task Description\nYou are required to implement a function that simulates a water retention problem in a given topography and determines the maximum amount of water that can be trapped after raining.\n\n### Problem Statement\nGiven `n` non-negative...
def has_consecutive_repeating_characters(s): if len(s) < 2: return False for i in range(len(s) - 1): if s[i] == s[i + 1]: return True return False
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to check if a string contains any sequence of consecutive repeating characters or not. If found, return `True` else return `False`.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6508, "level": 1, "question": "Write a python function to check if a string contains any sequence of consecutive repeating characters or not. If found, return `True` else return `False`.", "split": "train" }
def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 a, b = 0, 1 for i in range(2, n + 1): c = a + b a = b b = c return b
simplelr_Prefill
[ { "content": "Question:\nWrite a function to generate the nth Fibonacci number using an iterative approach. The function should be efficient and able to handle large values of n without running into performance issues. Additionally, consider optimizing for space complexity to minimize additional memory usage.\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6509, "level": 1, "question": "Write a function to generate the nth Fibonacci number using an iterative approach. The function should be efficient and able to handle large values of n without running into performance issues. Additionally, consider optimizing for space complexity to ...
def dict_to_nested_list(d): result = [] for key, value in d.items(): if isinstance(value, dict): value = dict_to_nested_list(value) result.append([key, value]) return result
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to convert a nested dictionary to a nested list. The function should return a list of lists, where each nested list corresponds to the keys and values of a dictionary at each level of nesting.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6510, "level": 1, "question": "Write a python function to convert a nested dictionary to a nested list. The function should return a list of lists, where each nested list corresponds to the keys and values of a dictionary at each level of nesting.", "split": "train" }
def has_triplet_with_sum_zero(nums): n = len(nums) if n < 3: return False nums.sort() for i in range(n - 2): left = i + 1 right = n - 1 while left < right: current_sum = nums[i] + nums[left] + nums[right] if current_sum == 0: return...
simplelr_Apps
[ { "content": "Question:\nGiven an array of integers, return `true` if there exists a triplet (a, b, c) such that a + b + c = 0, otherwise return `false`. The array may contain duplicate values.\n\nFor example:\n```\nInput: [-1, 0, 1, 2, -1, -4]\nOutput: true\nExplanation: The triplets (-1, 0, 1) and (-1, -1, 2)...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6511, "level": 1, "question": "Given an array of integers, return `true` if there exists a triplet (a, b, c) such that a + b + c = 0, otherwise return `false`. The array may contain duplicate values.\n\nFor example:\n```\nInput: [-1, 0, 1, 2, -1, -4]\nOutput: true\nExplanation: The ...
import ctypes from typing import List def process_integer_array(c_int_array: List[int]) -> List[int]: """ Converts an array of Python integers to a C-style array of integers, increments each element by 10, and then converts the result back to a Python list. :param c_int_array: List of Python integers ...
simplelr_Docs
[ { "content": "Question:\n**Objective**: Implement a function in Python that utilizes the C-API for integers provided in Python 3.10. The function will convert an array of C integers to Python integers and then perform some computations on them.\n\n#### Requirements:\n1. The function should create Python integer...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6512, "level": 1, "question": "**Objective**: Implement a function in Python that utilizes the C-API for integers provided in Python 3.10. The function will convert an array of C integers to Python integers and then perform some computations on them.\n\n#### Requirements:\n1. The fu...
from collections import defaultdict, namedtuple, OrderedDict from datetime import timedelta from typing import List, Dict, Any EventTuple = namedtuple('Event', ['event_name', 'start_date', 'duration']) def organize_events(events: List[Dict[str, Any]]) -> Dict[int, Dict[str, Any]]: years = defaultdict(list) ...
simplelr_Docs
[ { "content": "Question:\n### Coding Assessment: Advanced Data Handling with Collections and Datetime Modules\n\n#### Objective:\nCreate a Python program that uses the `collections` and `datetime` modules to perform detailed data manipulations and retrievals. This exercise tests your ability to handle advanced d...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6513, "level": 1, "question": "### Coding Assessment: Advanced Data Handling with Collections and Datetime Modules\n\n#### Objective:\nCreate a Python program that uses the `collections` and `datetime` modules to perform detailed data manipulations and retrievals. This exercise test...
def word_break(s, dict): if not s: return False word_set = set(dict) if not word_set: return False max_length = max(len(word) for word in word_set) n = len(s) dp = [False] * (n + 1) dp[0] = True for i in range(1, n + 1): for l in range(1, max_length + 1): ...
simplelr_Filter
[ { "content": "Question:\nGiven a string `s` consisting of lowercase English letters, determine if it can be segmented into a sequence of one or more dictionary words from a given list `dict`. Each entry of the dictionary can be used more than once in the segmentation.\nAnswer:\nLet's think step by step.\n", ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6514, "level": 1, "question": "Given a string `s` consisting of lowercase English letters, determine if it can be segmented into a sequence of one or more dictionary words from a given list `dict`. Each entry of the dictionary can be used more than once in the segmentation.", "spl...
def sort_dicts_by_key(dict_list, key): return sorted(dict_list, key=lambda x: x[key])
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a list of dictionaries in Python and returns a new list with the dictionaries sorted by a specific key in each dictionary. For example, if the given list is `[{'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 22}]` and you sort by the 'age' key, the resul...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6515, "level": 1, "question": "Create a function that takes a list of dictionaries in Python and returns a new list with the dictionaries sorted by a specific key in each dictionary. For example, if the given list is `[{'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 22}]` and y...
def capitalize_words(s): return ' '.join(word.capitalize() for word in s.split())
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a string and returns a new string where each word is capitalized.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6516, "level": 1, "question": "Create a function that takes a string and returns a new string where each word is capitalized.", "split": "train" }
def fizz_buzz(n): if n % 15 == 0: return "fizzbuzz" elif n % 3 == 0: return "fizz" elif n % 5 == 0: return "buzz" else: return str(n)
simplelr_Filter
[ { "content": "Question:\nyou are given a number. if the number is a multiple of 3, print \"fizz\". if the number is a multiple of 5, print \"buzz\". if the number is a multiple of both 3 and 5, print \"fizzbuzz\". otherwise, print the number. write a program to do this.\nAnswer:\nLet's think step by step.\n", ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6517, "level": 1, "question": "you are given a number. if the number is a multiple of 3, print \"fizz\". if the number is a multiple of 5, print \"buzz\". if the number is a multiple of both 3 and 5, print \"fizzbuzz\". otherwise, print the number. write a program to do this.", "s...
def maxSubarraySum(nums, k): current_sum = sum(nums[:k]) max_sum = current_sum for i in range(k, len(nums)): current_sum = current_sum - nums[i - k] + nums[i] if current_sum > max_sum: max_sum = current_sum return max_sum
simplelr_Taco
[ { "content": "Question:\nYou are given an integer array `nums` and an integer `k`. You want to find the maximum sum of a subarray of length `k`.\n\nA subarray is a contiguous part of an array. For example, if `nums = [1,2,3,4]` and `k = 2`, the maximum sum subarray of length `k` is `[3,4]` which sums to `7`.\n\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6518, "level": 1, "question": "You are given an integer array `nums` and an integer `k`. You want to find the maximum sum of a subarray of length `k`.\n\nA subarray is a contiguous part of an array. For example, if `nums = [1,2,3,4]` and `k = 2`, the maximum sum subarray of length `...
from typing import List def shell_sort(arr: List[int]) -> List[int]: """ Sorts a list of integers using Shell Sort with Ciura's gap sequence. Args: arr (List[int]): The list of integers to be sorted. Returns: List[int]: A new list sorted in ascending order. """ n = len(arr) if n =...
simplelr_Data_Structure
[ { "content": "Question:\n**Problem Description**:\nWrite a function to implement Shell Sort, which sorts a list of integers in ascending order. Students must use an efficient gap sequence and provide a detailed explanation of the chosen gap sequence and its complexity.\n\n**Function Signature**:\n```python\ndef...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6519, "level": 1, "question": "**Problem Description**:\nWrite a function to implement Shell Sort, which sorts a list of integers in ascending order. Students must use an efficient gap sequence and provide a detailed explanation of the chosen gap sequence and its complexity.\n\n**Fu...
from collections import defaultdict def group_and_sort_strings(strings): groups = defaultdict(list) for s in strings: key = s[0] groups[key].append(s) for key in groups: groups[key].sort() return dict(groups)
simplelr_Algorithm
[ { "content": "Question:\n### String Manipulation and Pattern Matching\n\nYou will implement a function that processes a list of strings and returns a dictionary where the keys are the first characters of the strings, and the values are lists of strings that start with that character, sorted in alphabetical orde...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6520, "level": 1, "question": "### String Manipulation and Pattern Matching\n\nYou will implement a function that processes a list of strings and returns a dictionary where the keys are the first characters of the strings, and the values are lists of strings that start with that cha...
def remove_k_digits(nums, k): stack = [] for num in nums: while stack and stack[-1] < num and k > 0: stack.pop() k -= 1 stack.append(num) # Remove remaining k digits from the end if k > 0: stack = stack[:-k] if len(stack) > k else [] # Convert to strin...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a list of non-negative integers `nums`, where each integer represents a digit (0-9). You are also provided an integer `k`. Construct the largest number possible by deleting exactly `k` digits from the list `nums`. Return the resulting number as a string. If the resulting n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6521, "level": 1, "question": "You are given a list of non-negative integers `nums`, where each integer represents a digit (0-9). You are also provided an integer `k`. Construct the largest number possible by deleting exactly `k` digits from the list `nums`. Return the resulting num...
def product_of_array(arr): if not arr: return 1 product = 1 for num in arr: product *= num return product
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes as its input an array of numbers and returns the product of all the numbers in the array.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6522, "level": 1, "question": "Create a function that takes as its input an array of numbers and returns the product of all the numbers in the array.", "split": "train" }
import importlib import importlib.resources def dynamic_import_and_read_resource(module_name: str, resource_name: str) -> str: # Dynamically import the specified module module = importlib.import_module(module_name) # Read the specified resource from within the imported module with importlib.resour...
simplelr_Docs
[ { "content": "Question:\n### Task:\nDesign a custom module importer in Python using the `importlib` package functionalities. The custom importer should:\n\n1. Dynamically import a specified module using `importlib`.\n2. Facilitate reading a specific resource (e.g., a text file) from within the imported module.\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6523, "level": 1, "question": "### Task:\nDesign a custom module importer in Python using the `importlib` package functionalities. The custom importer should:\n\n1. Dynamically import a specified module using `importlib`.\n2. Facilitate reading a specific resource (e.g., a text file...
def generate_primes(n: int) -> list: """ Generates a list of all prime numbers up to and including the given number `n`. Args: n (int): The upper limit (inclusive) up to which to generate prime numbers. Returns: list: A list of integers where each element is a prime number less than or equal t...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement:\nYou have been tasked with creating a function that generates the sequence of prime numbers up to a given number `n`. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.\n\n### Your Task:\nImplement the function...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6524, "level": 1, "question": "### Problem Statement:\nYou have been tasked with creating a function that generates the sequence of prime numbers up to a given number `n`. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.\n\n###...
import json def summarize_books(file_path: str) -> dict: with open(file_path, 'r') as f: books = json.load(f) genre_data = {} for book in books: genre = book['genre'] year = book['year'] if genre in genre_data: count, total = genre_data[genre] ge...
simplelr_Algorithm
[ { "content": "Question:\n### Question\n\nYou are tasked to write a function that reads and summarizes information from a JSON file representing a collection of books. Each book entry in the collection includes data such as title, author, genre, and year of publication. The function should group books by their g...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6525, "level": 1, "question": "### Question\n\nYou are tasked to write a function that reads and summarizes information from a JSON file representing a collection of books. Each book entry in the collection includes data such as title, author, genre, and year of publication. The fun...
def count_ways_to_decode(message: str) -> int: if not message or message[0] == '0': return 0 n = len(message) dp = [0] * (n + 1) dp[0], dp[1] = 1, 1 # Base cases for i in range(2, n + 1): one_digit = int(message[i-1:i]) two_digit = int(message[i-2:i]) ...
simplelr_Data_Structure
[ { "content": "Question:\n**Scenario**: A smart communication system uses a simple encoding scheme to transmit alphabetic messages as sequences of digits. Each letter is mapped to a numeric value ('A' -> '1', 'B' -> '2', ..., 'Z' -> '26'). When the encoded message is received, it needs to be decoded to determine...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6526, "level": 1, "question": "**Scenario**: A smart communication system uses a simple encoding scheme to transmit alphabetic messages as sequences of digits. Each letter is mapped to a numeric value ('A' -> '1', 'B' -> '2', ..., 'Z' -> '26'). When the encoded message is received, ...
def merge_dictionaries(dict1, dict2): merged_dict = {} merged_dict.update(dict1) merged_dict.update(dict2) return merged_dict # Sample dictionaries dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} # Merge the dictionaries merged = merge_dictionaries(dict1, dict2) # Output the result print("Merged di...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to merge two dictionaries. The function should take two dictionaries as arguments and return a new dictionary that contains the merged key-value pairs. If the same key exists in both dictionaries, the value from the second dictionary should overwrite the value fr...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6527, "level": 1, "question": "Write a Python function to merge two dictionaries. The function should take two dictionaries as arguments and return a new dictionary that contains the merged key-value pairs. If the same key exists in both dictionaries, the value from the second dicti...
def find_nth_digit(n): d = 1 count = 9 start = 1 while n > d * count: n -= d * count d += 1 count = 9 * (10 ** (d - 1)) start *= 10 number = start + (n - 1) // d digit_index = (n - 1) % d return int(str(number)[digit_index])
simplelr_Data_Structure
[ { "content": "Question:\n### Context\nImagine you have a sequence of all natural numbers written consecutively in order: \"123456789101112131415...\". You need to identify and return the nth digit in this sequence. This task requires accounting for the variable length of individual numbers as the sequence progr...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6528, "level": 1, "question": "### Context\nImagine you have a sequence of all natural numbers written consecutively in order: \"123456789101112131415...\". You need to identify and return the nth digit in this sequence. This task requires accounting for the variable length of indiv...
def product_except_self(nums): n = len(nums) if n == 0: return [] left = [1] * n for i in range(1, n): left[i] = left[i-1] * nums[i-1] right = [1] * n for i in range(n-2, -1, -1): right[i] = right[i+1] * nums[i+1] result = [left[i] * right[i] for i in range(n)] re...
simplelr_Filter
[ { "content": "Question:\nProvide a code which takes an array of integers and returns an array where each element is the product of all the numbers except the number at the same index\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6529, "level": 1, "question": "Provide a code which takes an array of integers and returns an array where each element is the product of all the numbers except the number at the same index", "split": "train" }
import random def generate_random_number(lower_limit): start = min(lower_limit, 100) return random.randint(start, 100)
simplelr_Filter
[ { "content": "Question:\nDefine a function called `generate_random_number` that takes one argument, `lower_limit`, and returns a random integer between `lower_limit` and 100 (inclusive).\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6530, "level": 1, "question": "Define a function called `generate_random_number` that takes one argument, `lower_limit`, and returns a random integer between `lower_limit` and 100 (inclusive).", "split": "train" }
def is_palindrome(n): if n < 0: return False original = n reversed_num = 0 while n > 0: last_digit = n % 10 reversed_num = reversed_num * 10 + last_digit n = n // 10 return original == reversed_num
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to check if a number is a palindrome. A whole number is a palindrome if the number reads the same backward as forward, such as 121 or 12321. Sorting the digits won't help. Consider all the numbers as integers (not strings).\nAnswer:\nLet's think step by step.\n",...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6531, "level": 1, "question": "Write a python function to check if a number is a palindrome. A whole number is a palindrome if the number reads the same backward as forward, such as 121 or 12321. Sorting the digits won't help. Consider all the numbers as integers (not strings).", ...
def findKthElement(nums1, nums2, k): i = j = count = 0 while count < k: if i >= len(nums1): current = nums2[j] j += 1 elif j >= len(nums2): current = nums1[i] i += 1 else: if nums1[i] < nums2[j]: current = nums1[...
simplelr_Taco
[ { "content": "Question:\nYou are given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, and an integer `k`. Find the `k-th` smallest element in the merged sorted array.\n\nConstraints:\n- The length of both arrays is between 1 and 10^4.\n- Elements of both arrays are between -10^6 and 10^...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6532, "level": 1, "question": "You are given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, and an integer `k`. Find the `k-th` smallest element in the merged sorted array.\n\nConstraints:\n- The length of both arrays is between 1 and 10^4.\n- Elements of bo...
def stutter(stack: list) -> list: length = len(stack) new_length = 2 * length new_stack = [0] * new_length # Initialize with zeros; will be overwritten for i in range(length): elem = stack[i] new_stack[2 * i] = elem new_stack[2 * i + 1] = elem return new_stack
simplelr_Data_Structure
[ { "content": "Question:\n**Problem Description:**\n\nYou are given a stack where the elements are stored in the traditional manner (LIFO - Last In, First Out). Implement a function that duplicates every element in the stack such that each element appears twice consecutively.\n\n**Function Specifications**:\n\nY...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6533, "level": 1, "question": "**Problem Description:**\n\nYou are given a stack where the elements are stored in the traditional manner (LIFO - Last In, First Out). Implement a function that duplicates every element in the stack such that each element appears twice consecutively.\n...
def group_into_triplets(nums): result = [] for i in range(0, len(nums), 3): group = nums[i:i+3] number_str = ''.join(str(d) for d in group) number = int(number_str) result.append(number) return result
simplelr_Filter
[ { "content": "Question:\nWe have a piece of code that attempts to initialize a list from given data, however, it contains some errors. Your job is to identify and fix any errors present in the code provided. You also need to write a function that will handle the initialization of list in a more generalized way....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6534, "level": 1, "question": "We have a piece of code that attempts to initialize a list from given data, however, it contains some errors. Your job is to identify and fix any errors present in the code provided. You also need to write a function that will handle the initialization...
def decode_string(s: str) -> str: stack = [] current_str = "" current_num = 0 for c in s: if c.isdigit(): current_num = current_num * 10 + int(c) elif c == '(': stack.append((current_str, current_num)) current_str = "" current_num = 0 ...
simplelr_Code_Contests
[ { "content": "Question:\nYou are given a string that consists of digits, brackets ('(' and ')'), and lowercase letters. Your task is to decode the string by following a format similar to the one used in the Decompress Run-Length Encoded List problem.\n\nThe format of the string is as follows:\n- Digits represen...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6535, "level": 1, "question": "You are given a string that consists of digits, brackets ('(' and ')'), and lowercase letters. Your task is to decode the string by following a format similar to the one used in the Decompress Run-Length Encoded List problem.\n\nThe format of the strin...
from typing import List def trap_rainwater(heights: List[int]) -> int: if not heights: return 0 n = len(heights) if n < 2: return 0 left_max = [0] * n for i in range(1, n): left_max[i] = max(left_max[i-1], heights[i-1]) right_max = [0] * n for i in range(n-...
simplelr_Taco
[ { "content": "Question:\nYou are given an array of integers representing the amount of rainwater trapped on top of each building. You need to compute the total amount of trapped rainwater.\n\nThe width of each building is 1 unit. For example, given [0,1,0,2,1,0,1,3,2,1,2,1], the amount of rainwater trapped woul...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6536, "level": 1, "question": "You are given an array of integers representing the amount of rainwater trapped on top of each building. You need to compute the total amount of trapped rainwater.\n\nThe width of each building is 1 unit. For example, given [0,1,0,2,1,0,1,3,2,1,2,1], t...
from typing import List def check_sorted(lst: List[float]) -> str: for i in range(len(lst) - 1): if lst[i] > lst[i + 1]: return "List is not sorted" return "List is sorted"
simplelr_Apps
[ { "content": "Question:\nWrite a function that accepts a list of floating point numbers and checks if the list is sorted in non-decreasing order. The function should return \"List is sorted\" if the list is sorted in non-decreasing order, and otherwise, return \"List is not sorted\".\n\nExample:\n```\nInput: [1...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6537, "level": 1, "question": "Write a function that accepts a list of floating point numbers and checks if the list is sorted in non-decreasing order. The function should return \"List is sorted\" if the list is sorted in non-decreasing order, and otherwise, return \"List is not so...
def filter_even_numbers(numbers): """Return a new list containing only the even integers from the input list.""" return [x for x in numbers if x % 2 == 0]
simplelr_Filter
[ { "content": "Question:\nCreate a Python function that takes a list of integers and returns a new list containing only the integers that are even. The function should be efficient and use list comprehension for this task. Additionally, provide a sample usage of this function and a brief explanation of how it wo...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6538, "level": 1, "question": "Create a Python function that takes a list of integers and returns a new list containing only the integers that are even. The function should be efficient and use list comprehension for this task. Additionally, provide a sample usage of this function a...
from bisect import bisect_left, bisect_right def calculate_scores(n, logs, query_intervals): if not logs: return [{} for _ in query_intervals] timestamps = [log[0] for log in logs] result = [] for s, e in query_intervals: start = bisect_left(timestamps, s) end = bisect...
simplelr_Code_Contests
[ { "content": "Question:\nA gaming company develops multiple online games, and they have a system that logs player activity data every second. Each log contains information about the player ID and the score they earned at that particular second. The company wants to analyze the data to calculate the total score ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6539, "level": 1, "question": "A gaming company develops multiple online games, and they have a system that logs player activity data every second. Each log contains information about the player ID and the score they earned at that particular second. The company wants to analyze the...
from typing import List, Tuple def range_product(nums: List[int], ranges: List[Tuple[int, int]]) -> List[int]: result = [] for (start, end) in ranges: product = 1 for i in range(start, end + 1): product *= nums[i] result.append(product) return result
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\nThe following problem involves implementing a function that computes the product of all elements in a given range within an array.\n\n### Scenario\nYou are given an array of integers, and you need to find the product of integers within given ranges multiple times....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6540, "level": 1, "question": "### Problem Statement\nThe following problem involves implementing a function that computes the product of all elements in a given range within an array.\n\n### Scenario\nYou are given an array of integers, and you need to find the product of integers ...
from typing import Tuple def convert_and_classify_temperature(temp_f: float) -> Tuple[float, str]: # Check if the temperature is within the valid range if not (-300 <= temp_f <= 300): raise ValueError("Temperature is out of range") # Convert Fahrenheit to Celsius c = (temp_f - 32) * 5 / 9 ...
simplelr_Algorithm
[ { "content": "Question:\n### Temperature Conversion and Classification\n\n**Objective**: Implement a function to convert a temperature from Fahrenheit to Celsius and classify the temperature into different categories.\n\n**Function Signature**:\n```python\ndef convert_and_classify_temperature(temp_f: float) -> ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6541, "level": 1, "question": "### Temperature Conversion and Classification\n\n**Objective**: Implement a function to convert a temperature from Fahrenheit to Celsius and classify the temperature into different categories.\n\n**Function Signature**:\n```python\ndef convert_and_clas...
def greet(name): """This function takes a name as input and returns a personalized greeting.""" return "Hello, " + name + "!" print(greet("World"))
simplelr_Filter
[ { "content": "Question:\ndef greet(name):\n \"\"\"This function takes a name as input and returns a personalized greeting.\"\"\"\n return \"Hello, \" + name + \"!\"\n\nprint(greet(\"World\"))\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6542, "level": 1, "question": "def greet(name):\n \"\"\"This function takes a name as input and returns a personalized greeting.\"\"\"\n return \"Hello, \" + name + \"!\"\n\nprint(greet(\"World\"))", "split": "train" }
def longest_unique_sequence(text: str) -> str: """ Finds the longest contiguous sequence of unique characters in the given string and returns it. Parameters: text (str): The input string to search within. Returns: str: The longest sequence of unique characters. Examples: >>> longest_u...
simplelr_Algorithm
[ { "content": "Question:\n### Task:\nYou are tasked with writing a function to find the longest sequence of unique characters in a given string. The sequence should be contiguous and should contain no repeating characters.\n\n### Function Specification:\n```python\ndef longest_unique_sequence(text: str) -> str:\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6543, "level": 1, "question": "### Task:\nYou are tasked with writing a function to find the longest sequence of unique characters in a given string. The sequence should be contiguous and should contain no repeating characters.\n\n### Function Specification:\n```python\ndef longest_...
from collections import Counter def min_deletions_to_make_anagrams(word1, word2): count1 = Counter(word1) count2 = Counter(word2) common = sum((count1 & count2).values()) return len(word1) + len(word2) - 2 * common
simplelr_Leetcode
[ { "content": "Question:\nYou are given two strings `word1` and `word2`. You want to delete the minimum number of characters from either of the two strings so that the remaining two substrings are **anagrams**. Return the minimum number of deletions required. An anagram of a string is a string that contains the ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6544, "level": 1, "question": "You are given two strings `word1` and `word2`. You want to delete the minimum number of characters from either of the two strings so that the remaining two substrings are **anagrams**. Return the minimum number of deletions required. An anagram of a st...
def factorial(n): if type(n) is not int: raise TypeError("Input must be an integer.") if n < 0: raise ValueError("Input must be a non-negative integer.") if n == 0 or n == 1: return 1 else: return n * factorial(n - 1)
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to find the factorial of a given number using recursion. The function should take an integer as an argument and return the factorial of that number. The factorial of a non-negative integer \\( n \\) is the product of all positive integers less than or equal to \\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6545, "level": 1, "question": "Write a Python function to find the factorial of a given number using recursion. The function should take an integer as an argument and return the factorial of that number. The factorial of a non-negative integer \\( n \\) is the product of all positiv...
def longest_word(sentence): words = sentence.split() if not words: return {"word": "", "length": 0} longest = max(words, key=lambda x: len(x)) return {"word": longest, "length": len(longest)}
simplelr_Filter
[ { "content": "Question:\n### Longest Word in a Sentence\nWrite a function `longest_word` that takes a sentence as an input and returns the longest word and its length in a dictionary format.\n\n### Example\nInput: `\"I love programming in python\"`\nOutput: `{\"word\": \"programming\", \"length\": 11}`\n\n### C...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6546, "level": 1, "question": "### Longest Word in a Sentence\nWrite a function `longest_word` that takes a sentence as an input and returns the longest word and its length in a dictionary format.\n\n### Example\nInput: `\"I love programming in python\"`\nOutput: `{\"word\": \"progr...
from typing import List def greatest_contiguous_sum(arr: List[int]) -> int: current_max = global_max = arr[0] for num in arr[1:]: current_max = max(num, current_max + num) if current_max > global_max: global_max = current_max return global_max
simplelr_Apps
[ { "content": "Question:\nGiven a list of integers, you are to find the greatest contiguous subarray sum. \n\nA contiguous subarray is a subarray made up of consecutive elements within the array. For example, if the input list is `[1, -2, 3, 4, -5, 8]`, the contiguous subarrays include `[1]`, `[-2]`, `[1, -2]`, ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6547, "level": 1, "question": "Given a list of integers, you are to find the greatest contiguous subarray sum. \n\nA contiguous subarray is a subarray made up of consecutive elements within the array. For example, if the input list is `[1, -2, 3, 4, -5, 8]`, the contiguous subarrays...
def remove_elements(lst): new_list = lst[::2] if len(lst) % 2 == 1: if len(new_list) % 2 == 1: mid = len(new_list) // 2 new_list.pop(mid) return new_list
simplelr_Filter
[ { "content": "Question:\nGiven a list of integers, write a python function to return a new list with every second element removed. If the length of the list is odd, remove the middle element. For example, given [1, 2, 3, 4], the output should be [1, 3].\nAnswer:\nLet's think step by step.\n", "role": "user"...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6548, "level": 1, "question": "Given a list of integers, write a python function to return a new list with every second element removed. If the length of the list is odd, remove the middle element. For example, given [1, 2, 3, 4], the output should be [1, 3].", "split": "train" }
import math def is_prime(n): if n < 2: return False if n == 2: return True if n % 2 == 0: return False max_divisor = int(math.sqrt(n)) + 1 for i in range(3, max_divisor, 2): if n % i == 0: return False return True
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to check if a number is a prime number. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. How can we write a function to determine if a given number `n` is a prime using Python?\nAnswer:\nLet's think step by ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6549, "level": 1, "question": "Write a python function to check if a number is a prime number. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. How can we write a function to determine if a given number `n` is a prime using Pyt...
def strings_to_ascii(strings): result = [] for s in strings: ascii_values = [] for char in s: ascii_values.append(ord(char)) result.append(ascii_values) return result
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to convert a list of strings into a list of their corresponding ASCII values.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6550, "level": 1, "question": "Write a python function to convert a list of strings into a list of their corresponding ASCII values.", "split": "train" }
def is_uncovered_point(rectangles: list[tuple[int, int, int, int]]) -> str: if not rectangles: return "YES" min_x1 = min(rect[0] for rect in rectangles) max_x2 = max(rect[2] for rect in rectangles) min_y1 = min(rect[1] for rect in rectangles) max_y2 = max(rect[3] for rect in rectangles)...
simplelr_Codeforces
[ { "content": "Question:\nIn a distant galaxy, the planet Zorg is protected by a series of energy shields. Each shield is represented by an axis-aligned rectangle (with edges parallel to the coordinate axes). The Zorgan Defense Council wants to ensure that there is at least one point within the boundary of Zorg ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6551, "level": 1, "question": "In a distant galaxy, the planet Zorg is protected by a series of energy shields. Each shield is represented by an axis-aligned rectangle (with edges parallel to the coordinate axes). The Zorgan Defense Council wants to ensure that there is at least one...
from typing import List def last_occurrence(array: List[int], query: int) -> int: low = 0 high = len(array) - 1 result = -1 while low <= high: mid = (low + high) // 2 if array[mid] == query: result = mid low = mid + 1 # Continue searching right half for last occ...
simplelr_Data_Structure
[ { "content": "Question:\n### Question\n\n**Scenario:** \nYou are working as a software engineer on a large-scale data analytics platform that frequently processes vast amounts of sorted numerical data. One common task is to determine the frequency of specific values within these datasets. To optimize this, you ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6552, "level": 1, "question": "### Question\n\n**Scenario:** \nYou are working as a software engineer on a large-scale data analytics platform that frequently processes vast amounts of sorted numerical data. One common task is to determine the frequency of specific values within the...
def flag_transaction(transactions: list, target: int) -> bool: seen = set() for num in transactions: complement = target - num if complement in seen: return True seen.add(num) return False
simplelr_Codeforces
[ { "content": "Question:\nYou are working for a company that processes large financial transactions. The company uses a unique algorithm to validate whether specific transactions should be flagged for review. Your task is to implement a part of this algorithm.\n\nYou need to write a function that determines whet...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6553, "level": 1, "question": "You are working for a company that processes large financial transactions. The company uses a unique algorithm to validate whether specific transactions should be flagged for review. Your task is to implement a part of this algorithm.\n\nYou need to wr...
def max_profit(prices): profit = 0 for i in range(len(prices) - 1): if prices[i+1] > prices[i]: profit += prices[i+1] - prices[i] return profit
simplelr_Apps
[ { "content": "Question:\nYou are given an input list of integers representing the stock prices of a company in chronological order. Write a function to find the maximum profit you can achieve by buying and selling one share of the stock multiple times, but you cannot hold more than one share of the stock at a t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6554, "level": 1, "question": "You are given an input list of integers representing the stock prices of a company in chronological order. Write a function to find the maximum profit you can achieve by buying and selling one share of the stock multiple times, but you cannot hold more...
def get_favorites(favorites, food_names): food_set = set(food_names) result = {} for person, foods in favorites.items(): filtered = [food for food in foods if food in food_set] result[person] = filtered return result
simplelr_Filter
[ { "content": "Question:\nIn this problem, we will be working with a dictionary where the keys are the names of people and the values are lists of their favorite foods. Create a function `get_favorites` that takes in a dictionary of people and their favorite foods, and a list of food names. It should return a di...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6555, "level": 1, "question": "In this problem, we will be working with a dictionary where the keys are the names of people and the values are lists of their favorite foods. Create a function `get_favorites` that takes in a dictionary of people and their favorite foods, and a list o...
def firstUniqueChar(s: str) -> int: count = [0] * 26 for c in s: index = ord(c) - ord('a') count[index] += 1 for i in range(len(s)): if count[ord(s[i]) - ord('a')] == 1: return i return -1
simplelr_Data_Structure
[ { "content": "Question:\n### Unique Character Finder\n\n#### Scenario\nGiven the increasing importance of text analysis in different fields such as sentiment analysis, information retrieval, and linguistics, it's essential to identify unique characters from strings efficiently. You are required to improve the s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6556, "level": 1, "question": "### Unique Character Finder\n\n#### Scenario\nGiven the increasing importance of text analysis in different fields such as sentiment analysis, information retrieval, and linguistics, it's essential to identify unique characters from strings efficiently...
def delete_all_occurrences(input_list, target): return [x for x in input_list if x != target]
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to delete all occurrences of an element in a list.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6557, "level": 1, "question": "Write a python function to delete all occurrences of an element in a list.", "split": "train" }
from typing import List def maxSumSubarray(arr: List[int], K: int) -> int: n = len(arr) if n < K: return -1 current_sum = sum(arr[:K]) max_sum = current_sum for i in range(1, n - K + 1): current_sum = current_sum - arr[i-1] + arr[i + K - 1] if current_sum > max_sum: ...
simplelr_Taco
[ { "content": "Question:\nGiven an integer array and a number K, write a function to find the maximum sum of a subarray of size K. If the input array has less than K elements, the function should return -1.\n\nExample 1:\nInput:\narr = [100, 200, 300, 400]\nK = 2\nOutput:\n700\nExplanation: The subarrays of size...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6558, "level": 1, "question": "Given an integer array and a number K, write a function to find the maximum sum of a subarray of size K. If the input array has less than K elements, the function should return -1.\n\nExample 1:\nInput:\narr = [100, 200, 300, 400]\nK = 2\nOutput:\n700\...
def rotate_array(arr, k): n = len(arr) k = k % n if n else 0 return arr[-k:] + arr[:-k] if k != 0 else arr.copy() # Example usage: arr = [1, 2, 3, 4, 5] k = 2 rotated = rotate_array(arr, k) print(rotated) # Output: [4, 5, 1, 2, 3]
simplelr_Filter
[ { "content": "Question:\nIn a programming competition, a task involves rotating an array to the right by a certain number of positions. For example, rotating the array `[1, 2, 3, 4, 5]` to the right by 2 positions should result in `[4, 5, 1, 2, 3]`. How can this be achieved efficiently?\nAnswer:\nLet's think st...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6559, "level": 1, "question": "In a programming competition, a task involves rotating an array to the right by a certain number of positions. For example, rotating the array `[1, 2, 3, 4, 5]` to the right by 2 positions should result in `[4, 5, 1, 2, 3]`. How can this be achieved ef...
def isProductEven(arr, N): for num in arr: if num % 2 == 0: return "Even" return "Odd"
simplelr_Taco
[ { "content": "Question:\nGiven an array arr[] of size N containing integers, the task is to find whether the product of all elements in the array is even or odd.\n\nExample 1:\nInput: N = 4, arr[] = {3, 5, 7, 9}\nOutput: Odd\nExplanation: The product of all elements is 3*5*7*9 = 945, which is odd.\n\nExample 2:...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6560, "level": 1, "question": "Given an array arr[] of size N containing integers, the task is to find whether the product of all elements in the array is even or odd.\n\nExample 1:\nInput: N = 4, arr[] = {3, 5, 7, 9}\nOutput: Odd\nExplanation: The product of all elements is 3*5*7*9...
def firstDuplicate(a): seen = set() for num in a: if num in seen: return num seen.add(num) return -1
simplelr_Filter
[ { "content": "Question:\nYou have been given an array of size n. Write a function to find the first duplicate in the array. \nThe first duplicate is the element that appears for the second time in the array.\n\nExample:\nInput: [2,1,3,5,3,2]\nOutput: 3\n\nInput: [2,2,3,5]\nOutput: 2\n\nInput: [2,1,3,5]\nOutput:...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6561, "level": 1, "question": "You have been given an array of size n. Write a function to find the first duplicate in the array. \nThe first duplicate is the element that appears for the second time in the array.\n\nExample:\nInput: [2,1,3,5,3,2]\nOutput: 3\n\nInput: [2,2,3,5]\nOut...
def product_except_self(lst): n = len(lst) if n == 0: return [] prefix = [1] * n for i in range(1, n): prefix[i] = prefix[i-1] * lst[i-1] suffix = [1] * n for i in range(n-2, -1, -1): suffix[i] = suffix[i+1] * lst[i+1] result = [prefix[i] * suffix[i] fo...
simplelr_Evol
[ { "content": "Question:\nIn Python, write a function that takes a list of integers and returns a list where each integer is replaced by the product of all the integers in the original list except the integer at that position. \n\nFor instance, given the list [1, 2, 3, 4], the function should return [24, 12, 8, ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6562, "level": 1, "question": "In Python, write a function that takes a list of integers and returns a list where each integer is replaced by the product of all the integers in the original list except the integer at that position. \n\nFor instance, given the list [1, 2, 3, 4], the ...
def list_intersection(list1, list2): set2 = set(list2) result = [] for element in list1: if element in set2: result.append(element) return result
simplelr_Filter
[ { "content": "Question:\nCreate a function to find the intersection of two given lists and return a new list with the common elements, keeping their original order from the first list.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6563, "level": 1, "question": "Create a function to find the intersection of two given lists and return a new list with the common elements, keeping their original order from the first list.", "split": "train" }
import csv from collections import defaultdict def process_sales_data(input_file: str, output_file: str) -> None: totals = defaultdict(float) with open(input_file, 'r') as infile: reader = csv.DictReader(infile) for row in reader: try: product = row['Product'] ...
simplelr_Docs
[ { "content": "Question:\n### CSV Data Processing\n\n**Objective:**\n\nImplement a Python function to process CSV data, demonstrating proficiency in reading, writing, and manipulating CSV files using the `csv` module.\n\n**Problem Statement:**\n\nYou are given a large CSV file containing sales records with the f...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6564, "level": 1, "question": "### CSV Data Processing\n\n**Objective:**\n\nImplement a Python function to process CSV data, demonstrating proficiency in reading, writing, and manipulating CSV files using the `csv` module.\n\n**Problem Statement:**\n\nYou are given a large CSV file ...
def primeFactors(n): if n == 1: return [] factors = set() # Handle the case for 2 separately while n % 2 == 0: factors.add(2) n = n // 2 # Now n must be odd, so start from 3 and increment by 2 i = 3 while i * i <= n: while n % i == 0: factors.add(i...
simplelr_Taco
[ { "content": "Question:\n# Task\n\n**_Given_** an **_integer n_**, *return an array of all prime factors of n in ascending order.* If n has no prime factors, return an empty list.\n___\n\n# Notes:\n\n* The number n will always be a positive integer (n > 0).\n* A prime factor is a factor of n that is a prime num...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6565, "level": 1, "question": "# Task\n\n**_Given_** an **_integer n_**, *return an array of all prime factors of n in ascending order.* If n has no prime factors, return an empty list.\n___\n\n# Notes:\n\n* The number n will always be a positive integer (n > 0).\n* A prime factor i...
import bisect def longest_increasing_subsequence(arr): tails = [] for num in arr: idx = bisect.bisect_left(tails, num) if idx == len(tails): tails.append(num) else: tails[idx] = num return len(tails)
simplelr_Filter
[ { "content": "Question:\nThe development team designed a system with limited disk space. They want to find the longest sequence of indices of a given array that contains values in strictly increasing order without duplicates. \n\nGiven an array with unique integers, implement a function `longest_increasing_subs...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6566, "level": 1, "question": "The development team designed a system with limited disk space. They want to find the longest sequence of indices of a given array that contains values in strictly increasing order without duplicates. \n\nGiven an array with unique integers, implement ...
from typing import List def generate_fibonacci_sequence(n: int) -> List[int]: if type(n) is not int or n < 0: raise TypeError("Input value must be a non-negative 'int' type.") if n == 0: return [0] elif n == 1: return [0, 1] fib = [0, 1] for i in range(2, n + 1): nex...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Question: Generate Fibonacci Sequence Up to N-th Term\n\n#### Context:\nBob is working on a project that requires generating a sequence of Fibonacci numbers. The Fibonacci sequence is defined as follows:\n- F(0) = 0\n- F(1) = 1\n- F(n) = F(n-1) + F(n-2) for n > 1\n\nYour task...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6567, "level": 1, "question": "### Coding Question: Generate Fibonacci Sequence Up to N-th Term\n\n#### Context:\nBob is working on a project that requires generating a sequence of Fibonacci numbers. The Fibonacci sequence is defined as follows:\n- F(0) = 0\n- F(1) = 1\n- F(n) = F(n...
def rotate_array(nums, k): n = len(nums) k = k % n return nums[-k:] + nums[:-k]
simplelr_Leetcode
[ { "content": "Question:\nGiven a circular array of integers `nums` of size `n`, and an integer `k`, rotate the array to the right by `k` steps, where `k` is non-negative. Return the modified array after performing the rotation. A circular array wraps around when the end is reached, so elements shifted off the r...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6568, "level": 1, "question": "Given a circular array of integers `nums` of size `n`, and an integer `k`, rotate the array to the right by `k` steps, where `k` is non-negative. Return the modified array after performing the rotation. A circular array wraps around when the end is rea...
import bisect def binary_search(nums, target): index = bisect.bisect_left(nums, target) return index if index < len(nums) and nums[index] == target else -1
simplelr_Filter
[ { "content": "Question:\nHere is a Python function that takes a sorted list and a target value as input and returns the index of the target value in the list if it's present, otherwise, returns -1.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6569, "level": 1, "question": "Here is a Python function that takes a sorted list and a target value as input and returns the index of the target value in the list if it's present, otherwise, returns -1.", "split": "train" }
def character_frequency(s): char_freq = {} for char in s: if char.isspace(): continue if char in char_freq: char_freq[char] += 1 else: char_freq[char] = 1 return char_freq
simplelr_Filter
[ { "content": "Question:\nWrite a program to compute the frequency of each character in a given string, and display the result in a dictionary format where the keys are the characters and the values are their frequencies. Ensure that the program is case-sensitive (i.e., 'A' and 'a' are considered different chara...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6570, "level": 1, "question": "Write a program to compute the frequency of each character in a given string, and display the result in a dictionary format where the keys are the characters and the values are their frequencies. Ensure that the program is case-sensitive (i.e., 'A' and...
def netProfitLoss(transactions): total = 0.0 for buy, sell in transactions: total += sell - buy return round(total, 2)
simplelr_Apps
[ { "content": "Question:\n## Story\n\nAlice likes to collect rare coins, and she keeps a detailed log of her transactions. Each entry in her log is in the format:\n\n```\n[[purchase_price, sell_price], [purchase_price, sell_price], ...]\n```\n\nEach sub array represents the price at which she purchased the coin ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6571, "level": 1, "question": "## Story\n\nAlice likes to collect rare coins, and she keeps a detailed log of her transactions. Each entry in her log is in the format:\n\n```\n[[purchase_price, sell_price], [purchase_price, sell_price], ...]\n```\n\nEach sub array represents the pri...
def min_block_swaps(n, arr): if n == 0: return 0 sorted_arr = sorted(arr) from collections import defaultdict, deque index_map = defaultdict(deque) for idx, num in enumerate(sorted_arr): index_map[num].append(idx) pos = [] for num in arr: idx = index_map[num].pople...
simplelr_Codeforces
[ { "content": "Question:\nGerald is learning about sorting algorithms and wants to experiment with a customized technique. He has a sequence of n integers arranged in an array. Gerald's goal is to sort the array in non-decreasing order using a particular operation called \"block swap\".\n\nA block swap operation...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6572, "level": 1, "question": "Gerald is learning about sorting algorithms and wants to experiment with a customized technique. He has a sequence of n integers arranged in an array. Gerald's goal is to sort the array in non-decreasing order using a particular operation called \"bloc...
from collections import deque def longest_subarray(nums, k): if not nums: return 0 max_deque = deque() min_deque = deque() left = 0 max_len = 0 for right in range(len(nums)): # Update max_deque while max_deque and nums[right] >= nums[max_deque[-1]]: ...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that returns the length of the longest continuous subarray where the difference between the maximum and minimum values is less than or equal to a given number, k.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6573, "level": 1, "question": "Create a function that returns the length of the longest continuous subarray where the difference between the maximum and minimum values is less than or equal to a given number, k.", "split": "train" }
def findPair(arr, K): if len(arr) < 2: return False seen = set() for num in arr: complement = K - num if complement in seen: return True seen.add(num) return False
simplelr_Taco
[ { "content": "Question:\nGiven an array of integers and a positive integer 'K'. The task is to determine if there are two distinct elements (i.e., elements with different indices) in the array that add up to 'K'. Return true if such a pair exists, and false otherwise.\n\nExample 1:\nInput:\narr = [10, 15, 3, 7]...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6574, "level": 1, "question": "Given an array of integers and a positive integer 'K'. The task is to determine if there are two distinct elements (i.e., elements with different indices) in the array that add up to 'K'. Return true if such a pair exists, and false otherwise.\n\nExamp...
import heapq from typing import List, Tuple def merge_sorted_logs(logs: List[List[Tuple[int, int]]]) -> List[Tuple[int, int]]: """ Merges multiple sorted lists of log entries based on their timestamps into a single sorted list. Args: logs (List[List[Tuple[int, int]]]): A list of lists where ea...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\n#### Context\nYou are developing a scaling system for a large distributed logging application. Each log entry is associated with a server's timestamp and its unique ID. An important functionality is to efficiently merge and sort logs coming from differe...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6575, "level": 1, "question": "### Coding Assessment Question\n\n#### Context\nYou are developing a scaling system for a large distributed logging application. Each log entry is associated with a server's timestamp and its unique ID. An important functionality is to efficiently merg...
def merge_intervals(intervals): if not intervals: return [] # Sort intervals based on the start time sorted_intervals = sorted(intervals, key=lambda x: x[0]) merged = [] for interval in sorted_intervals: if not merged: merged.append(interval) else: ...
simplelr_Code_Contests
[ { "content": "Question:\nGiven a collection of intervals, merge all overlapping intervals.\n\nWrite a function that takes a list of intervals, represented as pairs of integers [start, end], and returns a list of merged intervals. Each interval is guaranteed to have start <= end.\n\nInput\n\nA list of intervals,...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6576, "level": 1, "question": "Given a collection of intervals, merge all overlapping intervals.\n\nWrite a function that takes a list of intervals, represented as pairs of integers [start, end], and returns a list of merged intervals. Each interval is guaranteed to have start <= en...
def find_contiguous_subarrays(arr): subarrays = [] n = len(arr) for i in range(n): for j in range(i, n): subarrays.append(arr[i:j+1]) return subarrays
simplelr_Filter
[ { "content": "Question:\nGiven an array of integers, find all the possible contiguous subarrays within that array.\n\n\n\nExample:\n\n\nInput: `[1, 2, 3]`\n\nOutput: \n```\n[1]\n[1, 2]\n[1, 2, 3]\n[2]\n[2, 3]\n[3]\n```\n\n\n\n\n\n\n\nMy Approach:\nMy approach would be to use nested loops.\n\n Outer loop: Itera...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6577, "level": 1, "question": "Given an array of integers, find all the possible contiguous subarrays within that array.\n\n\n\nExample:\n\n\nInput: `[1, 2, 3]`\n\nOutput: \n```\n[1]\n[1, 2]\n[1, 2, 3]\n[2]\n[2, 3]\n[3]\n```\n\n\n\n\n\n\n\nMy Approach:\nMy approach would be to use ...
def contains_duplicate(nums: list[int]) -> bool: return len(set(nums)) < len(nums)
simplelr_Apps
[ { "content": "Question:\nGiven an integer array `nums`, return `True` if any value appears at least twice in the array, and return `False` if every element is distinct. Implement the function `contains_duplicate(nums: List[int]) -> bool`.\n\n## Examples\n\n```python\ncontains_duplicate([1, 2, 3, 1]) ==> ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6578, "level": 1, "question": "Given an integer array `nums`, return `True` if any value appears at least twice in the array, and return `False` if every element is distinct. Implement the function `contains_duplicate(nums: List[int]) -> bool`.\n\n## Examples\n\n```python\ncontains_...
def sum_even_numbers(numbers): """ This function takes a list of numbers and returns the sum of all the even numbers in the list. Args: numbers: A list of numbers. Returns: The sum of all the even numbers in the list. """ total_sum = 0 for number in numbers: if numb...
simplelr_Filter
[ { "content": "Question:\nThis is a problem statement:\n\n**Problem:** Your task is to create a program that takes a list of numbers as input and outputs the sum of all the even numbers in the list.\n\n**Example:**\nInput: [1, 2, 3, 4, 5, 6]\nOutput: 12\n\n**Constraints:**\n\n* The list can contain any number of...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6579, "level": 1, "question": "This is a problem statement:\n\n**Problem:** Your task is to create a program that takes a list of numbers as input and outputs the sum of all the even numbers in the list.\n\n**Example:**\nInput: [1, 2, 3, 4, 5, 6]\nOutput: 12\n\n**Constraints:**\n\n*...
import random def generate_random_integer(min_val=-100, max_val=100, seed=None): """ Generates a random integer within a specified range. Args: min_val (int): Minimum value for the random integer (default: -100) max_val (int): Maximum value for the random integer (default: 100) ...
simplelr_Filter
[ { "content": "Question:\nThis code generates random integers between -100 and 100.\n\n```python\nimport random\n\ndef generate_random_integer():\n return random.randint(-100, 100)\n\nfor _ in range(10):\n print(generate_random_integer())\n```\n\n**What could you do to modify this code to make it more versatil...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6580, "level": 1, "question": "This code generates random integers between -100 and 100.\n\n```python\nimport random\n\ndef generate_random_integer():\n return random.randint(-100, 100)\n\nfor _ in range(10):\n print(generate_random_integer())\n```\n\n**What could you do to modify...
def product_except_self(nums): n = len(nums) if n == 0: return [] prefix = [1] * n for i in range(1, n): prefix[i] = prefix[i-1] * nums[i-1] suffix = [1] * n for i in range(n-2, -1, -1): suffix[i] = suffix[i+1] * nums[i+1] result = [prefix[i] * suffix[i] for i in rang...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a list of `n` integers. Return a new list such that each element at index `i` of the new list is the product of all the numbers in the original list except the one at `i`. You must solve it **without using division** and in **O(n)** time complexity.\nAnswer:\nLet's think s...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6581, "level": 1, "question": "You are given a list of `n` integers. Return a new list such that each element at index `i` of the new list is the product of all the numbers in the original list except the one at `i`. You must solve it **without using division** and in **O(n)** time ...
def bubble_sort_descending(lst): n = len(lst) for i in range(n): swapped = False for j in range(0, n - i - 1): if lst[j] < lst[j + 1]: lst[j], lst[j + 1] = lst[j + 1], lst[j] swapped = True if not swapped: break return lst
simplelr_Filter
[ { "content": "Question:\nGiven a list of integers, write a function to sort the list from largest to smallest using the bubble sort algorithm.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6582, "level": 1, "question": "Given a list of integers, write a function to sort the list from largest to smallest using the bubble sort algorithm.", "split": "train" }
def final_position_and_orientation(instructions): x, y = 0, 0 dir_index = 0 # 0: North, 1: East, 2: South, 3: West directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] for move in instructions: if move == 'G': dx, dy = directions[dir_index] x += dx y += dy ...
simplelr_Codeforces
[ { "content": "Question:\nYou are given a robot on an infinite grid. The robot is initially located at the position (0, 0) and faces north. You will be given a sequence of instructions where each instruction corresponds to a movement or rotation:\n\n- 'G': the robot moves forward by 1 unit in the direction it is...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6583, "level": 1, "question": "You are given a robot on an infinite grid. The robot is initially located at the position (0, 0) and faces north. You will be given a sequence of instructions where each instruction corresponds to a movement or rotation:\n\n- 'G': the robot moves forwa...
from typing import List def stooge_sort(arr: List[int], l: int, h: int) -> None: if arr[l] > arr[h]: arr[l], arr[h] = arr[h], arr[l] if h - l + 1 > 2: m = (h - l + 1) // 3 stooge_sort(arr, l, h - m) stooge_sort(arr, l + m, h) stooge_sort(arr, l, h - m)
simplelr_Data_Structure
[ { "content": "Question:\n### Stooge Sort Implementation\n\n**Context**:\nStooge Sort is an interesting example of a recursive sorting algorithm. A fun fact is that its time complexity is quite poor compared to more practical algorithms like Quick Sort, Merge Sort, or even Bubble Sort. Despite this inefficiency,...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6584, "level": 1, "question": "### Stooge Sort Implementation\n\n**Context**:\nStooge Sort is an interesting example of a recursive sorting algorithm. A fun fact is that its time complexity is quite poor compared to more practical algorithms like Quick Sort, Merge Sort, or even Bubb...
def categorizeParticipants(participants): # Initialize the result dictionary with empty lists for each category result = { "fast": [], "average": [], "slow": [] } for participant in participants: time = participant['time'] name = participant['name'] i...
simplelr_Apps
[ { "content": "Question:\nWrite a function `categorizeParticipants` that takes a list of participants, where each participant is represented by a dictionary with keys \"name\" and \"time\". The function should categorize participants into three categories based on their finishing time:\n\n- \"fast\" if the time ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6585, "level": 1, "question": "Write a function `categorizeParticipants` that takes a list of participants, where each participant is represented by a dictionary with keys \"name\" and \"time\". The function should categorize participants into three categories based on their finishi...
def largestRectangleArea(heights): stack = [-1] max_area = 0 for i in range(len(heights)): while stack[-1] != -1 and heights[i] < heights[stack[-1]]: h = stack.pop() width = i - stack[-1] - 1 area = heights[h] * width if area > max_area: ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a list of non-negative integers representing the heights of bars in a histogram. Each bar has a width of `1`. Write a function to find the area of the largest rectangle that can be formed within the bounds of the histogram. \n\nFor example, given the list `[2,1,5,6,2,3]`, ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6586, "level": 1, "question": "You are given a list of non-negative integers representing the heights of bars in a histogram. Each bar has a width of `1`. Write a function to find the area of the largest rectangle that can be formed within the bounds of the histogram. \n\nFor exampl...
def count_numeric_characters(lst): count = 0 for string in lst: for char in string: if char.isdigit(): count += 1 return count
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a list of strings as input and returns the total count of numeric characters found within the list. Each string may contain any combination of letters and numbers, and the function should accurately count only the numeric characters.\nAnswer:\nLet's th...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6587, "level": 1, "question": "Write a Python function that takes a list of strings as input and returns the total count of numeric characters found within the list. Each string may contain any combination of letters and numbers, and the function should accurately count only the num...
def has_alternating_bits(n: int) -> bool: x = n ^ (n >> 1) return (x & (x + 1)) == 0
simplelr_Data_Structure
[ { "content": "Question:\n**Context:**\nIn digital systems, certain integrity checks require verification where binary signals must alternate to prevent errors. Given an integer, you are to determine if the binary representation of the number maintains an alternating pattern of bits (adjacent bits are different)...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6588, "level": 1, "question": "**Context:**\nIn digital systems, certain integrity checks require verification where binary signals must alternate to prevent errors. Given an integer, you are to determine if the binary representation of the number maintains an alternating pattern of...
def string_to_number(s): try: return int(s) except ValueError: return None
simplelr_Filter
[ { "content": "Question:\nIn this problem, you will implement a function that converts a given string into a number. The function should return the integer equivalent of the string if the conversion is successful. If the conversion is not successful, it should return None.\nAnswer:\nLet's think step by step.\n",...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6589, "level": 1, "question": "In this problem, you will implement a function that converts a given string into a number. The function should return the integer equivalent of the string if the conversion is successful. If the conversion is not successful, it should return None.", ...
def bubble_sort(lst): nums = list(lst) n = len(nums) for i in range(n - 1): swapped = False for j in range(n - 1 - i): if nums[j] > nums[j + 1]: # Swap the elements nums[j], nums[j + 1] = nums[j + 1], nums[j] swapped = True ...
simplelr_Evol
[ { "content": "Question:\nWrite a function in your programming language of choice that takes a list of integers and returns the list sorted in ascending order using the bubble sort algorithm. Additionally, provide a brief explanation of how the bubble sort algorithm works and its time complexity.\nAnswer:\nLet's...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6590, "level": 1, "question": "Write a function in your programming language of choice that takes a list of integers and returns the list sorted in ascending order using the bubble sort algorithm. Additionally, provide a brief explanation of how the bubble sort algorithm works and i...
def min_subarray_sum(arr): if not arr: return 0 # or raise ValueError("Array is empty") current_min = min_sum = arr[0] for num in arr[1:]: current_min = min(num, current_min + num) min_sum = min(min_sum, current_min) return min_sum
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the minimum sum of a contiguous subarray within a one-dimensional array of numbers.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6591, "level": 1, "question": "Write a python function to find the minimum sum of a contiguous subarray within a one-dimensional array of numbers.", "split": "train" }
def minPathSum(grid): if not grid or not grid[0]: return 0 m = len(grid) n = len(grid[0]) dp = [[0] * n for _ in range(m)] dp[0][0] = grid[0][0] for i in range(m): for j in range(n): if i == 0 and j == 0: continue if i == 0: ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a matrix of size `m x n` consisting of non-negative integers, where each cell represents the weight of the cell. Your goal is to find a path from the top-left corner to the bottom-right corner that minimizes the sum of the weights of the cells you visit. You can only move ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6592, "level": 1, "question": "You are given a matrix of size `m x n` consisting of non-negative integers, where each cell represents the weight of the cell. Your goal is to find a path from the top-left corner to the bottom-right corner that minimizes the sum of the weights of the ...
from collections import defaultdict, Counter def recommend_additional_items(past_orders, current_cart): """ Recommends additional items based on past orders. Args: past_orders (List[List[str]]): A list of past orders, each containing items purchased together. current_cart (List[str]): The ...
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question:\n\n#### Context:\nYou are developing an application for a local bakery that offers online ordering and delivery. To customize orders, the bakery wants to recommend additional items based on customers' current cart content. This requires analyzing purchase...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6593, "level": 1, "question": "### Coding Assessment Question:\n\n#### Context:\nYou are developing an application for a local bakery that offers online ordering and delivery. To customize orders, the bakery wants to recommend additional items based on customers' current cart conten...
import math def area_of_circle(r): return math.pi * r ** 2
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to calculate the area of a circle given the radius. You need to use the formula `A = πr^2` where `A` is the area and `r` is the radius. Use the `math` module for the value of `π`.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6594, "level": 1, "question": "Write a python function to calculate the area of a circle given the radius. You need to use the formula `A = πr^2` where `A` is the area and `r` is the radius. Use the `math` module for the value of `π`.", "split": "train" }
def max_points(grid): if not grid: return 0 m = len(grid) n = len(grid[0]) if m > 0 else 0 if m == 0 or n == 0: return 0 dp = [[0 for _ in range(n)] for _ in range(m)] dp[0][0] = grid[0][0] for j in range(1, n): dp[0][j] = dp[0][j-1] + grid[0][j] fo...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a `m x n` 2D integer matrix `grid` containing non-negative numbers, representing the maximum number of points that can be obtained in each cell. A robot starts at the top-left corner of the matrix and wants to reach the bottom-right corner (both corners are included in the...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6595, "level": 1, "question": "You are given a `m x n` 2D integer matrix `grid` containing non-negative numbers, representing the maximum number of points that can be obtained in each cell. A robot starts at the top-left corner of the matrix and wants to reach the bottom-right corne...
import hashlib def string_to_sha256(s): return hashlib.sha256(s.encode('utf-8')).hexdigest() # Example usage: # print(string_to_sha256("Hello, World!"))
simplelr_Filter
[ { "content": "Question:\nCould you provide a Python function that converts a string to its SHA-256 hash?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6596, "level": 1, "question": "Could you provide a Python function that converts a string to its SHA-256 hash?", "split": "train" }
def rotate_matrix(matrix): if not matrix: return [] transposed = zip(*matrix) rotated = [list(row[::-1]) for row in transposed] return rotated
simplelr_Evol
[ { "content": "Question:\nWrite a function in Python that rotates a given matrix 90 degrees clockwise. The input will be a 2D list representing the matrix, and the function should return a new 2D list representing the rotated matrix. Consider edge cases such as empty matrices, and ensure that your solution handl...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6597, "level": 1, "question": "Write a function in Python that rotates a given matrix 90 degrees clockwise. The input will be a 2D list representing the matrix, and the function should return a new 2D list representing the rotated matrix. Consider edge cases such as empty matrices, ...
def unique_paths_with_obstacles(grid): m = len(grid) if m == 0: return 0 n = len(grid[0]) if n == 0: return 0 dp = [[0 for _ in range(n)] for _ in range(m)] if grid[0][0] == 1: return 0 dp[0][0] = 1 for i in range(m): for j in range(n): ...
simplelr_Filter
[ { "content": "Question:\nI'm working on a problem where I need to find the number of unique paths in a grid with obstacles. The grid is represented as a 2D array where 0 represents a free cell and 1 represents an obstacle. The path can only move right or down. How can I solve this problem using dynamic programm...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6598, "level": 1, "question": "I'm working on a problem where I need to find the number of unique paths in a grid with obstacles. The grid is represented as a 2D array where 0 represents a free cell and 1 represents an obstacle. The path can only move right or down. How can I solve ...
def greet(name, day): """Return a personalized greeting for the given name and day of the week.""" days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] if day not in days: raise ValueError("Invalid day of the week") greeting = f"Hello {name}, happy {day}!" re...
simplelr_Filter
[ { "content": "Question:\ndef greet(name, day):\n \"\"\"Return a personalized greeting for the given name and day of the week.\"\"\"\n days = [\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"]\n if day not in days:\n raise ValueError(\"Invalid day of the ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 6599, "level": 1, "question": "def greet(name, day):\n \"\"\"Return a personalized greeting for the given name and day of the week.\"\"\"\n days = [\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"]\n if day not in days:\n rai...