target stringlengths 29 3.65k | data_source stringclasses 12
values | prompt listlengths 1 1 | ability stringclasses 1
value | reward_model dict | extra_info dict |
|---|---|---|---|---|---|
import collections
def k_most_common_elements(lst, k):
if not lst:
return []
counts = collections.Counter(lst)
count_list = list(counts.items())
count_list.sort(key=lambda x: (-x[1], x[0]))
result = [element for element, _ in count_list[:k]]
return result | simplelr_Filter | [
{
"content": "Question:\nGiven a list of integers and a positive integer k, write a Python function that returns the k most common elements in the list. If there are multiple elements with the same frequency, return them in ascending order. Ensure your function handles edge cases and is optimized for large data... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1100,
"level": 1,
"question": "Given a list of integers and a positive integer k, write a Python function that returns the k most common elements in the list. If there are multiple elements with the same frequency, return them in ascending order. Ensure your function handles edge ca... |
def swap_cases(s):
return s.swapcase()
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes a string consisting of lowercase and uppercase characters, and returns a string where each uppercase letter is replaced by its lowercase counterpart and each lowercase letter is replaced by its uppercase counterpart. For example, given the input \"aBcdE\", th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1101,
"level": 1,
"question": "Write a function that takes a string consisting of lowercase and uppercase characters, and returns a string where each uppercase letter is replaced by its lowercase counterpart and each lowercase letter is replaced by its uppercase counterpart. For exa... |
import heapq
from collections import defaultdict
def top_k_frequent(nums, k):
if k == 0:
return []
freq = defaultdict(int)
for num in nums:
freq[num] += 1
heap = []
for key in freq:
current_freq = freq[key]
if len(heap) < k:
heapq.heappush(heap,... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Context\nIn a data processing pipeline, it’s often necessary to find the k most frequent elements in a dataset. This operation should be optimized for both time and space efficiency, especially when dealing with large datasets where the number of e... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1102,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Context\nIn a data processing pipeline, it’s often necessary to find the k most frequent elements in a dataset. This operation should be optimized for both time and space efficiency, especially when dealing with l... |
def shortest_path(graph, start_node, end_node):
if start_node == end_node:
return [start_node]
if start_node not in graph or end_node not in graph:
return []
# Initialize distances and predecessors
nodes = graph.keys()
distances = {node: float('infinity') for node in nodes}... | simplelr_Package | [
{
"content": "Question:\nIn computational graph theory, finding the shortest path between nodes in a weighted graph is a common problem. A well-known algorithm for this task is Dijkstra's algorithm. In this problem, you will implement a function named `shortest_path` that calculates the shortest path from a sta... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1103,
"level": 1,
"question": "In computational graph theory, finding the shortest path between nodes in a weighted graph is a common problem. A well-known algorithm for this task is Dijkstra's algorithm. In this problem, you will implement a function named `shortest_path` that calc... |
def binary_to_decimal(binary):
result = 0
for char in binary:
result = result * 2 + int(char)
return result
| simplelr_Taco | [
{
"content": "Question:\nGiven a string of numbers representing a binary number, return the decimal value of the number without converting the entire string to an integer. You are only allowed to perform binary operations to calculate the decimal value directly from the binary string.\n\nThe binary number strin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1104,
"level": 1,
"question": "Given a string of numbers representing a binary number, return the decimal value of the number without converting the entire string to an integer. You are only allowed to perform binary operations to calculate the decimal value directly from the binary... |
def print_odd_numbers(numbers):
odds = [x for x in numbers if x % 2 != 0]
if not odds:
print("No odd numbers found.")
else:
print(*odds, sep='\n') | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function `print_odd_numbers` that prints all odd numbers in a given list. If the list does not contain any odd numbers, the function should print \"No odd numbers found.\" Use tuple unpacking and iterating techniques to accomplish this task.\nAnswer:\nLet's think step by ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1105,
"level": 1,
"question": "Write a Python function `print_odd_numbers` that prints all odd numbers in a given list. If the list does not contain any odd numbers, the function should print \"No odd numbers found.\" Use tuple unpacking and iterating techniques to accomplish this t... |
def get_top_student(students):
top_average = None
top_student = None
for student in students:
grades = student['grades']
avg = sum(grades.values()) / len(grades)
if top_average is None or avg > top_average:
top_average = avg
top_student = student['name']
r... | simplelr_Evol | [
{
"content": "Question:\nIn Python, you have a list of dictionaries representing students and their respective grades in several subjects. Each dictionary has the following format:\n```python\n{\n 'name': 'Student Name',\n 'grades': {\n 'math': 85,\n 'english': 78,\n 'science': 90,\n ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1106,
"level": 1,
"question": "In Python, you have a list of dictionaries representing students and their respective grades in several subjects. Each dictionary has the following format:\n```python\n{\n 'name': 'Student Name',\n 'grades': {\n 'math': 85,\n 'engli... |
import pandas as pd
import numpy as np
def log_transform_and_scale(csv_file_path: str) -> pd.DataFrame:
df = pd.read_csv(csv_file_path)
for col in df.columns:
if pd.api.types.is_numeric_dtype(df[col]):
# Apply natural logarithm
df[col] = np.log(df[col])
# Standa... | simplelr_Package | [
{
"content": "Question:\nYou are required to write a Python function named `log_transform_and_scale` which uses the `numpy` and `pandas` libraries to perform the following tasks:\n\n1. Load a dataset from a specified CSV file into a pandas DataFrame.\n2. Apply a natural logarithm transformation to all numeric c... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1107,
"level": 1,
"question": "You are required to write a Python function named `log_transform_and_scale` which uses the `numpy` and `pandas` libraries to perform the following tasks:\n\n1. Load a dataset from a specified CSV file into a pandas DataFrame.\n2. Apply a natural logari... |
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1) | simplelr_Filter | [
{
"content": "Question:\nExplain, in programming, what a recursive function is and provide an example in a code snippet. Additionally, identify and correct any mistakes in the following erroneous code snippet provided below, which is an attempt to implement a recursive function to calculate factorial values.\nA... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1108,
"level": 1,
"question": "Explain, in programming, what a recursive function is and provide an example in a code snippet. Additionally, identify and correct any mistakes in the following erroneous code snippet provided below, which is an attempt to implement a recursive functio... |
def find_longest_increasing_subsequence(arr):
if not arr:
return {0: []}
n = len(arr)
dp = [1] * n
prev = [-1] * n
for i in range(1, n):
for j in range(i):
if arr[i] > arr[j] and dp[i] < dp[j] + 1:
dp[i] = dp[j] + 1
prev[i] = j
... | simplelr_Package | [
{
"content": "Question:\nGiven a list of integers, write a function that returns a dictionary with the longest increasing subsequence (LIS) in the list. The dictionary should have the length of the LIS as the key and the LIS itself as the value.\nThe function should output:\n - a dictionary where the key is ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1109,
"level": 1,
"question": "Given a list of integers, write a function that returns a dictionary with the longest increasing subsequence (LIS) in the list. The dictionary should have the length of the LIS as the key and the LIS itself as the value.\nThe function should output:\n ... |
def list_compression(nums):
if not nums:
return []
result = []
current = nums[0]
count = 1
for num in nums[1:]:
if num == current:
count += 1
else:
if count == 1:
result.append(current)
else:
result... | simplelr_Taco | [
{
"content": "Question:\nIn this problem, you need to complete the function `list_compression`. \n\nYou will be given a list of integers, `nums`, as the function's only argument. Your task is to compress the list by summing any consecutive sequences of the same integer and replacing them with a single instance ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1110,
"level": 1,
"question": "In this problem, you need to complete the function `list_compression`. \n\nYou will be given a list of integers, `nums`, as the function's only argument. Your task is to compress the list by summing any consecutive sequences of the same integer and rep... |
def second_smallest(nums):
if len(nums) < 2:
return None
unique_nums = list(set(nums))
if len(unique_nums) < 2:
return None
sorted_unique = sorted(unique_nums)
return sorted_unique[1] | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to find the second smallest number in a list of integers. The function should take a list of integers as input and return the second smallest number in the list. If the list contains less than two elements, the function should return None. If the list contains tw... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1111,
"level": 1,
"question": "Write a Python function to find the second smallest number in a list of integers. The function should take a list of integers as input and return the second smallest number in the list. If the list contains less than two elements, the function should r... |
def generate_even_number_list(n):
even_numbers = [i * 2 for i in range(n)]
print(even_numbers)
try:
with open('even_numbers.txt', 'w') as f:
for num in even_numbers:
f.write(f"{num}\n")
except OSError as e:
print(f"Error writing to file: {e}") | simplelr_Package | [
{
"content": "Question:\nYou are required to write a Python function called `generate_even_number_list(n)` that generates a list of the first `n` even numbers. This function should perform the following tasks:\n\n1. Generate a list `even_numbers` containing the first `n` even numbers starting from 0.\n2. Print ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1112,
"level": 1,
"question": "You are required to write a Python function called `generate_even_number_list(n)` that generates a list of the first `n` even numbers. This function should perform the following tasks:\n\n1. Generate a list `even_numbers` containing the first `n` even ... |
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]
result = [0] * n
suffix = 1
for i in range(n-1, -1, -1):
result[i] = prefix[i] * suffix
suffix *= nums[i]
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `nums` of length `n`. Your task is to rearrange `nums` such that every `nums[i]` is equal to the product of all elements in `nums` except `nums[i]`. Return the modified array. You must solve it without using division and in O(n) time complexity.\nAnswer:\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1113,
"level": 1,
"question": "You are given an integer array `nums` of length `n`. Your task is to rearrange `nums` such that every `nums[i]` is equal to the product of all elements in `nums` except `nums[i]`. Return the modified array. You must solve it without using division and ... |
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1) | simplelr_Filter | [
{
"content": "Question:\ncan you describe a recursive function in Python, and provide an example of such a function?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1114,
"level": 1,
"question": "can you describe a recursive function in Python, and provide an example of such a function?",
"split": "train"
} |
def closest_three_sum(arr, target):
arr.sort()
n = len(arr)
best_sum = None
best_diff = float('inf')
for i in range(n - 2):
left = i + 1
right = n - 1
while left < right:
current_sum = arr[i] + arr[left] + arr[right]
current_diff = abs(current_sum... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `arr` and an integer `target`, return _the closest possible sum of any three distinct elements in `arr` that is closest to the `target`_. If there are multiple such sums, return the smallest sum. The array may contain both positive and negative integers.\nAnswer:\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1115,
"level": 1,
"question": "Given an integer array `arr` and an integer `target`, return _the closest possible sum of any three distinct elements in `arr` that is closest to the `target`_. If there are multiple such sums, return the smallest sum. The array may contain both positi... |
def find_nth_digit(n):
digits = 1
count = 9
start = 1
while n > digits * count:
n -= digits * count
digits += 1
count *= 10
start *= 10
number = start + (n - 1) // digits
digit_index = (n - 1) % digits
return int(str(number)[digit_index]) | simplelr_Data_Structure | [
{
"content": "Question:\n### Scenario\nYou are helping a mathematical research group to analyze sequences of natural numbers. They've come up with a challenge where they need to find specific digits in a long concatenated sequence of positive integers. For example, in the sequence \"123456789101112...\" (and so... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1116,
"level": 1,
"question": "### Scenario\nYou are helping a mathematical research group to analyze sequences of natural numbers. They've come up with a challenge where they need to find specific digits in a long concatenated sequence of positive integers. For example, in the sequ... |
def is_palindrome_number(num):
if num < 0:
return False
if num == 0:
return True
if num % 10 == 0:
return False
reversed_num = 0
original_num = num
while num > 0:
remainder = num % 10
reversed_num = reversed_num * 10 + remainder
num = num // 10
... | simplelr_Filter | [
{
"content": "Question:\nWrite a program to check if a given number is a palindrome or not. The program should work for both positive and negative numbers, and it should not convert the number to a string at any point. Use Python for the implementation.\nAnswer:\nLet's think step by step.\n",
"role": "user"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1117,
"level": 1,
"question": "Write a program to check if a given number is a palindrome or not. The program should work for both positive and negative numbers, and it should not convert the number to a string at any point. Use Python for the implementation.",
"split": "train"
} |
def is_palindrome_permutation(s: str) -> bool:
freq = {}
for char in s:
if char.isalpha():
lower_char = char.lower()
if lower_char in freq:
freq[lower_char] += 1
else:
freq[lower_char] = 1
odd_count = 0
for count in freq.va... | simplelr_Package | [
{
"content": "Question:\nGiven a string containing both lowercase and uppercase letters, write a function `is_palindrome_permutation(s: str) -> bool` that checks if the string is a permutation of a palindrome. A permutation of a palindrome has the same characters with the same frequencies, but the characters ca... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1118,
"level": 1,
"question": "Given a string containing both lowercase and uppercase letters, write a function `is_palindrome_permutation(s: str) -> bool` that checks if the string is a permutation of a palindrome. A permutation of a palindrome has the same characters with the same... |
from collections import defaultdict
def is_valid_k_ary_tree(edges: list, k: int) -> bool:
if not edges:
return True
parents = set()
children = set()
for p, c in edges:
parents.add(p)
children.add(c)
all_nodes = parents.union(children)
n = len(all_nodes)
... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nA `k-ary` tree is a tree in which each node has no more than `k` children. Given an array `edges` where `edges[i]` is of the format `[parent, child]` representing a directed edge from `parent` to `child` in the tree, write a function to determine if the given ed... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1119,
"level": 1,
"question": "### Problem Statement\n\nA `k-ary` tree is a tree in which each node has no more than `k` children. Given an array `edges` where `edges[i]` is of the format `[parent, child]` representing a directed edge from `parent` to `child` in the tree, write a fu... |
import math
def is_good_array(nums):
if not nums:
return False # Assuming the function should return False for empty arrays
current_gcd = nums[0]
for num in nums[1:]:
current_gcd = math.gcd(current_gcd, num)
if current_gcd == 1:
return True
return current_gcd == 1 | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `nums`. A \"good\" array is defined as an array where the greatest common divisor (GCD) of all its elements is 1. Return `true` if the given array is a good array, and `false` otherwise. For example, the array `[12, 5, 7, 23]` is a good array because t... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1120,
"level": 1,
"question": "You are given an array of integers `nums`. A \"good\" array is defined as an array where the greatest common divisor (GCD) of all its elements is 1. Return `true` if the given array is a good array, and `false` otherwise. For example, the array `[12, 5... |
def unique_characters(s: str) -> str:
seen = set()
result = []
for char in s:
if char not in seen:
result.append(char)
seen.add(char)
return ''.join(result) | simplelr_Data_Structure | [
{
"content": "Question:\n### Scenario\n\nYou are developing a text processing tool and one of the requirements is to simplify strings by removing duplicate characters while maintaining the original order. Your task is to implement a function that processes the strings as per the requirement.\n\n### Task\n\nWrit... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1121,
"level": 1,
"question": "### Scenario\n\nYou are developing a text processing tool and one of the requirements is to simplify strings by removing duplicate characters while maintaining the original order. Your task is to implement a function that processes the strings as per t... |
def convert_to_roman(n: int) -> str:
roman_numerals = [
(1000, 'M'), (900, 'CM'),
(500, 'D'), (400, 'CD'),
(100, 'C'), (90, 'XC'),
(50, 'L'), (40, 'XL'),
(10, 'X'), (9, 'IX'),
(5, 'V'), (4, 'IV'), (1, 'I')
]
result = ''
for value, numeral in roman_numerals... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Integer to Roman Numeral Conversion\n\nGiven an integer, convert it into its corresponding Roman numeral. Your function should be able to handle integers in the range from 1 to 3999 inclusive. \n\n### Requirements:\n* Implement the function `convert_to_roman(n: int) -> str... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1122,
"level": 1,
"question": "### Question: Integer to Roman Numeral Conversion\n\nGiven an integer, convert it into its corresponding Roman numeral. Your function should be able to handle integers in the range from 1 to 3999 inclusive. \n\n### Requirements:\n* Implement the functi... |
def longest_substring_without_repeating_characters(s):
"""
This function finds the longest substring without repeating characters using the sliding window technique.
Args:
s: The input string
Returns:
The longest substring without repeating characters.
"""
char_map = {}
max... | simplelr_Filter | [
{
"content": "Question:\nGiven a string, find the longest substring that contains only unique characters.\n\n Example:\n ```\n Input: \"abcabcbb\"\n Output: \"abc\"\n ```\n\n Explanation:\n\nThe longest substring without repeating characters in \"abcabcbb\" is \"abc\", which has a length of 3.\n\n### My... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1123,
"level": 1,
"question": "Given a string, find the longest substring that contains only unique characters.\n\n Example:\n ```\n Input: \"abcabcbb\"\n Output: \"abc\"\n ```\n\n Explanation:\n\nThe longest substring without repeating characters in \"abcabcbb\" is \"abc\",... |
from collections import deque
def influenced_count(start: str, network: dict) -> int:
if start not in network:
return 0
visited = set()
queue = deque([start])
visited.add(start)
count = 0
while queue:
current = queue.popleft()
for neighbor in network[current]:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question\n\n#### Scenario:\nYou have been assigned to create a function that helps to analyze the relationships between people in terms of social influence from recommendations. Given a network where each person can recommend a product to other people, the objectiv... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1124,
"level": 1,
"question": "### Coding Assessment Question\n\n#### Scenario:\nYou have been assigned to create a function that helps to analyze the relationships between people in terms of social influence from recommendations. Given a network where each person can recommend a pr... |
def reverse_words_in_sentence(s):
words = s.split()
reversed_words = words[::-1]
return ' '.join(reversed_words) | simplelr_Filter | [
{
"content": "Question:\nI need help with a Python function to manipulate a string. Specifically, I want to reverse the order of words in a sentence while maintaining the order of characters within each word. How can I achieve this?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1125,
"level": 1,
"question": "I need help with a Python function to manipulate a string. Specifically, I want to reverse the order of words in a sentence while maintaining the order of characters within each word. How can I achieve this?",
"split": "train"
} |
import bisect
def max_subarray_cost(nums, budget):
prefix_sum = [0]
sorted_prefix = [0]
max_total = 0
for num in nums:
current_sum = prefix_sum[-1] + num
prefix_sum.append(current_sum)
target = current_sum - budget
# Find the first index in sorted_prefix >= target
... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a **0-indexed** integer array `nums` of length `n` representing the cost of different items in a shop, and an integer `budget` representing the amount of money you have. You want to buy a contiguous subarray of items such that the total cost is as close to the `budget` as ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1126,
"level": 1,
"question": "You are given a **0-indexed** integer array `nums` of length `n` representing the cost of different items in a shop, and an integer `budget` representing the amount of money you have. You want to buy a contiguous subarray of items such that the total c... |
def can_form_by_deletion(source: str, s: str) -> bool:
if len(s) > len(source):
return False
i = j = 0
n, m = len(source), len(s)
while i < n and j < m:
if source[i] == s[j]:
j += 1
i += 1
return j == m | simplelr_Algorithm | [
{
"content": "Question:\n## Question\nYou need to write a Python function `can_form_by_deletion` that determines if a string `s` can be formed from another string `source` by deleting some or none of the characters from `source` without changing the order of the remaining characters.\n\n### Function Signature\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1127,
"level": 1,
"question": "## Question\nYou need to write a Python function `can_form_by_deletion` that determines if a string `s` can be formed from another string `source` by deleting some or none of the characters from `source` without changing the order of the remaining char... |
def compress_image_rle(grid: list[list[int]]) -> list[list[tuple[int, int]]]:
compressed = []
for row in grid:
if not row:
compressed.append([])
continue
current_value = row[0]
count = 1
compressed_row = []
for pixel in row[1:]:
if pixe... | simplelr_Algorithm | [
{
"content": "Question:\n### Image Compression with RLE\n\n**Problem Statement**:\nYou need to compress a given image represented as a 2D grid of pixels using the Run-Length Encoding (RLE) algorithm. RLE is a simple form of data compression in which consecutive occurrences of the same value are stored as a sing... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1128,
"level": 1,
"question": "### Image Compression with RLE\n\n**Problem Statement**:\nYou need to compress a given image represented as a 2D grid of pixels using the Run-Length Encoding (RLE) algorithm. RLE is a simple form of data compression in which consecutive occurrences of ... |
from collections import defaultdict, Counter
def min_window(s: str, t: str) -> str:
if not t:
return ""
if len(t) > len(s):
return ""
required = Counter(t)
window_counts = defaultdict(int)
have = 0
need = len(required)
min_length = float('inf')
result = ""
... | simplelr_Apps | [
{
"content": "Question:\nYou are given two strings s and t. Return the minimum window in s which will contain all the characters in t, including duplicates. If there is no such window in s that covers all characters in t, return the empty string \"\".\n\nNote:\n- If there is a tie, return the window which appea... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1129,
"level": 1,
"question": "You are given two strings s and t. Return the minimum window in s which will contain all the characters in t, including duplicates. If there is no such window in s that covers all characters in t, return the empty string \"\".\n\nNote:\n- If there is a... |
def max_subarray_sum(nums: list[int]) -> int:
if not nums:
return 0 # Though the problem states nums is non-empty, this handles edge cases gracefully.
max_current = max_global = nums[0]
for num in nums[1:]:
max_current = max(num, max_current + num)
if max_current > max_global:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Question: Efficient Subarray Sum\n\n**Context**:\nYou need to calculate the sum of contiguous subarrays within an array of integers efficiently. Given the constraints of the system, the goal is to implement a solution that computes the sum in optimal time.\n\n**Task**:\nImple... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1130,
"level": 1,
"question": "### Coding Question: Efficient Subarray Sum\n\n**Context**:\nYou need to calculate the sum of contiguous subarrays within an array of integers efficiently. Given the constraints of the system, the goal is to implement a solution that computes the sum i... |
def custom_sort(nums):
evens = []
odds = []
for num in nums:
if num % 2 == 0:
evens.append(num)
else:
odds.append(num)
evens_sorted = sorted(evens)
odds_sorted = sorted(odds, reverse=True)
return evens_sorted + odds_sorted | simplelr_Apps | [
{
"content": "Question:\nCreate a function that takes an array of integers and returns an array of the same integers but sorted in such a way that the even numbers are sorted in ascending order and placed at the beginning, followed by the odd numbers sorted in descending order. For example:\n\n```\n[5, 3, 2, 8,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1131,
"level": 1,
"question": "Create a function that takes an array of integers and returns an array of the same integers but sorted in such a way that the even numbers are sorted in ascending order and placed at the beginning, followed by the odd numbers sorted in descending order... |
def max_product_subarray(arr):
if not arr:
return 0
current_max = current_min = overall_max = arr[0]
for num in arr[1:]:
temp_max = current_max * num
temp_min = current_min * num
current_max = max(num, temp_max, temp_min)
current_min = min(num, temp_min, temp_max)
... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to find the maximum product of a subarray within a given array of integers. The array can contain positive, negative, and zero values.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1132,
"level": 1,
"question": "Write a Python function to find the maximum product of a subarray within a given array of integers. The array can contain positive, negative, and zero values.",
"split": "train"
} |
def find_missing(sequence: list) -> int:
n = len(sequence)
d = (sequence[-1] - sequence[0]) // n
for i in range(n - 1):
if sequence[i + 1] - sequence[i] != d:
return sequence[i] + d
return sequence[0] + d | simplelr_Algorithm | [
{
"content": "Question:\n### Question: Find the Missing Number in a Sequence\n\n#### Context:\nYou are tasked with developing a function to find a single missing number from an arithmetic sequence. An arithmetic sequence or arithmetic progression is a sequence of numbers in which the difference between consecut... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1133,
"level": 1,
"question": "### Question: Find the Missing Number in a Sequence\n\n#### Context:\nYou are tasked with developing a function to find a single missing number from an arithmetic sequence. An arithmetic sequence or arithmetic progression is a sequence of numbers in wh... |
def index_multiply_sum(arr):
return sum(x * i for i, x in enumerate(arr)) | simplelr_Filter | [
{
"content": "Question:\nLet's write a Python function that multiplies each element of an array by its index position and returns the sum of the results. For example, given an array `[3, 0, -2, 7]`, the function should calculate `3*0 + 0*1 + -2*2 + 7*3`, which equals `17`. Can you code this function? Make sure ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1134,
"level": 1,
"question": "Let's write a Python function that multiplies each element of an array by its index position and returns the sum of the results. For example, given an array `[3, 0, -2, 7]`, the function should calculate `3*0 + 0*1 + -2*2 + 7*3`, which equals `17`. Can... |
def find_max_non_adjacent_subset(arr):
return (len(arr) + 1) // 2 | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the maximum number of elements that can be included in a subset of an array such that no two elements in the subset are adjacent in the original array.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1135,
"level": 1,
"question": "Write a python function to find the maximum number of elements that can be included in a subset of an array such that no two elements in the subset are adjacent in the original array.",
"split": "train"
} |
def max_product_of_three(nums):
"""
Finds the maximum product of three numbers in an array.
Args:
nums: A list of integers.
Returns:
The maximum product of three numbers from the list.
"""
nums.sort()
product1 = nums[-1] * nums[-2] * nums[-3]
product2 = nums[0] * nums[1... | simplelr_Filter | [
{
"content": "Question:\nThis is a coding challenge I'm struggling with. Here's the prompt:\n\n**Challenge:**\n\nYou are given an array of integers. Your task is to find the maximum product that can be achieved by multiplying three numbers from the array.\n\n**Input:**\n\nAn array of integers.\n\n**Output:**\n\... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1136,
"level": 1,
"question": "This is a coding challenge I'm struggling with. Here's the prompt:\n\n**Challenge:**\n\nYou are given an array of integers. Your task is to find the maximum product that can be achieved by multiplying three numbers from the array.\n\n**Input:**\n\nAn a... |
def common_elements(list_a, list_b):
set_b = set(list_b)
return [x for x in list_a if x in set_b] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the common elements in two lists using list comprehension.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1137,
"level": 1,
"question": "Write a python function to find the common elements in two lists using list comprehension.",
"split": "train"
} |
def format_string(template, values):
return template.format(**values) | simplelr_Filter | [
{
"content": "Question:\nHey Qwen, can you help me with some Python code? I'm trying to create a function that can format a string by applying a given template. For example, if I have a template \"Hello, my name is {name} and I am {age} years old.\", and I provide the function with a dictionary like {'name': 'A... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1138,
"level": 1,
"question": "Hey Qwen, can you help me with some Python code? I'm trying to create a function that can format a string by applying a given template. For example, if I have a template \"Hello, my name is {name} and I am {age} years old.\", and I provide the function... |
def extract_values(dict_list, key):
return [d.get(key) for d in dict_list] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of dictionaries and returns a list of the values for a specified key.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1139,
"level": 1,
"question": "Create a function that takes a list of dictionaries and returns a list of the values for a specified key.",
"split": "train"
} |
def is_palindrome(s: str) -> bool:
cleaned = [c.lower() for c in s if c.isalnum()]
cleaned_str = ''.join(cleaned)
return cleaned_str == cleaned_str[::-1] | simplelr_Filter | [
{
"content": "Question:\nGiven the Python programming language, how can I implement a function that efficiently checks if a given string is a palindrome, considering case sensitivity and ignoring any non-alphanumeric characters? For example, \"A man, a plan, a canal: Panama\" should be considered a palindrome, ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1140,
"level": 1,
"question": "Given the Python programming language, how can I implement a function that efficiently checks if a given string is a palindrome, considering case sensitivity and ignoring any non-alphanumeric characters? For example, \"A man, a plan, a canal: Panama\" ... |
from typing import List
def unique_substrings(s: str, length: int) -> List[str]:
"""
Extracts all unique substrings of a given length from the provided string.
Args:
s (str): The input string from which substrings will be extracted.
length (int): The length of each substring to be extracted.
... | simplelr_Algorithm | [
{
"content": "Question:\nYou need to implement a function that identifies and extracts all unique substrings of a given length from a provided string. This function must be efficient and handle various edge cases, including those involving overlapping substrings.\n\n### Task\nImplement a function that extracts ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1141,
"level": 1,
"question": "You need to implement a function that identifies and extracts all unique substrings of a given length from a provided string. This function must be efficient and handle various edge cases, including those involving overlapping substrings.\n\n### Task\n... |
def find_anagrams(s, p):
len_p = len(p)
len_s = len(s)
result = []
if len_p == 0 or len_p > len_s:
return result
# Initialize frequency counts for p and the first window of s
p_count = [0] * 26
for c in p:
p_count[ord(c) - ord('a')] += 1
s_count = [0] * 26
... | simplelr_Leetcode | [
{
"content": "Question:\nImplement a function to identify all the starting indices of substrings in a given string `s` that are anagrams of a given string `p`. Both strings consist of lowercase English letters. The output should be a list of all starting indices in `s` where the substring is an anagram of `p`. ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1142,
"level": 1,
"question": "Implement a function to identify all the starting indices of substrings in a given string `s` that are anagrams of a given string `p`. Both strings consist of lowercase English letters. The output should be a list of all starting indices in `s` where t... |
def rotate_matrix(matrix: list) -> None:
"""
Rotates the given N x N matrix 90 degrees clockwise in-place.
Examples:
>>> matrix = [
... [1, 2, 3],
... [4, 5, 6],
... [7, 8, 9]]
>>> rotate_matrix(matrix)
>>> matrix
[[7, 4, 1],
[8, 5, 2],
[9, 6, 3]]
... | simplelr_Algorithm | [
{
"content": "Question:\n### Matrix Rotation Challenge\n\n#### Background\nYou are working on a graphics rendering application that frequently requires rotating images represented as 2D matrices. Rotation operations are computationally intensive and must be optimized to handle high-resolution images efficiently... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1143,
"level": 1,
"question": "### Matrix Rotation Challenge\n\n#### Background\nYou are working on a graphics rendering application that frequently requires rotating images represented as 2D matrices. Rotation operations are computationally intensive and must be optimized to handle... |
def get_even_numbers(input_list):
return [num for num in input_list if num % 2 == 0] | simplelr_Filter | [
{
"content": "Question:\nWrite a python function that gets as input a list and returns a new list that contains only the even numbers in the input list\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1144,
"level": 1,
"question": "Write a python function that gets as input a list and returns a new list that contains only the even numbers in the input list",
"split": "train"
} |
import cmath
def analyze_complex_numbers(numbers):
result = {}
for num in numbers:
modulus, phase = cmath.polar(num)
polar = (modulus, phase)
exp = cmath.exp(num)
log = cmath.log(num)
sqrt = cmath.sqrt(num)
sin = cmath.sin(num)
cos = cmath.cos(num)
... | simplelr_Docs | [
{
"content": "Question:\n### Complex Number Analyzer\n\nYou are tasked with creating a function called `analyze_complex_numbers` that takes a list of complex numbers and performs a series of operations to extract various mathematical properties and transformations. Specifically, this function should:\n\n1. Conv... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1145,
"level": 1,
"question": "### Complex Number Analyzer\n\nYou are tasked with creating a function called `analyze_complex_numbers` that takes a list of complex numbers and performs a series of operations to extract various mathematical properties and transformations. Specificall... |
def two_sum(nums, target):
seen = {}
for index, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], index]
seen[num] = index
return [] | simplelr_Filter | [
{
"content": "Question:\nYou're given an array of integers 'nums' and an integer 'target'.\n\nYour task is to return indices of the two numbers in 'nums' such that they add up to 'target'.\n\nYou may assume that each input would have exactly one solution, and you may not use the same element twice.\n\n**Example... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1146,
"level": 1,
"question": "You're given an array of integers 'nums' and an integer 'target'.\n\nYour task is to return indices of the two numbers in 'nums' such that they add up to 'target'.\n\nYou may assume that each input would have exactly one solution, and you may not use t... |
def is_palindrome(s: str) -> bool:
"""
This function determines if a given string is a palindrome.
Args:
s (str): The input string to be checked.
Returns:
bool: True if the string is a palindrome, False otherwise.
"""
if s is None:
return False
left = 0
right = len... | simplelr_Filter | [
{
"content": "Question:\nTo determine if a string is a palindrome, we compare characters from the beginning and end, working our way towards the center. If all pairs of characters match, then the string is a palindrome.\n# Task\nThe string \"radar\" is a palindrome, but the string \"python\" is not. Write a fun... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1147,
"level": 1,
"question": "To determine if a string is a palindrome, we compare characters from the beginning and end, working our way towards the center. If all pairs of characters match, then the string is a palindrome.\n# Task\nThe string \"radar\" is a palindrome, but the st... |
import collections
def word_frequency(s):
words = s.split()
return dict(collections.Counter(words)) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to calculate the frequency of each word in a given string and return the result as a dictionary.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1148,
"level": 1,
"question": "Write a python function to calculate the frequency of each word in a given string and return the result as a dictionary.",
"split": "train"
} |
def find_unique(nums):
result = 0
for num in nums:
result ^= num
return result | simplelr_Data_Structure | [
{
"content": "Question:\nYou are given a list of integers where each integer except one appears exactly twice. Your task is to implement a function `find_unique(nums)` that finds and returns the single number that does not appear in pairs.\n\n### Input\n- A list `nums` of integers (1 ≤ len(nums) ≤ 10^6)\n- Each... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1149,
"level": 1,
"question": "You are given a list of integers where each integer except one appears exactly twice. Your task is to implement a function `find_unique(nums)` that finds and returns the single number that does not appear in pairs.\n\n### Input\n- A list `nums` of inte... |
from urllib.parse import urlparse
def extract_url_components(url):
parsed_url = urlparse(url)
protocol = parsed_url.scheme
domain = parsed_url.netloc.split(':')[0]
path = parsed_url.path
return {
'protocol': protocol,
'domain': domain,
'path': path
} | simplelr_Filter | [
{
"content": "Question:\nCan you help me with a Python function that can extract the protocol, domain, and path from a given URL? For example, if I have the URL `https://www.example.com/path/to/resource`, I want to get the protocol `https`, the domain `www.example.com`, and the path `/path/to/resource` as separ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1150,
"level": 1,
"question": "Can you help me with a Python function that can extract the protocol, domain, and path from a given URL? For example, if I have the URL `https://www.example.com/path/to/resource`, I want to get the protocol `https`, the domain `www.example.com`, and th... |
def process_transaction(
initial_balance: float,
transactions: list[float],
min_threshold: float,
) -> float:
"""
Processes a list of transactions starting from an initial balance and ensures the balance never drops below a specified minimum threshold.
Args:
initial_balance (float): The... | simplelr_Algorithm | [
{
"content": "Question:\nYou are tasked with creating a function `process_transaction` to simulate a simple banking application. This function will process a list of transactions (deposits and withdrawals) and return the final account balance. Additionally, you need to add checks to ensure the account never goe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1151,
"level": 1,
"question": "You are tasked with creating a function `process_transaction` to simulate a simple banking application. This function will process a list of transactions (deposits and withdrawals) and return the final account balance. Additionally, you need to add che... |
def final_position(start_x, start_y, instructions):
current_x = start_x
current_y = start_y
for c in instructions:
if c == 'U':
current_y += 1
elif c == 'D':
current_y -= 1
elif c == 'R':
current_x += 1
elif c == 'L':
current_x ... | simplelr_Apps | [
{
"content": "Question:\nOn a rectangular grid, you are given a starting point (start_x, start_y) and a list of instructions. Each instruction is a character that signifies a direction to move from the current point: 'U' (up), 'D' (down), 'L' (left), 'R' (right). Calculate the final coordinates of the point aft... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1152,
"level": 1,
"question": "On a rectangular grid, you are given a starting point (start_x, start_y) and a list of instructions. Each instruction is a character that signifies a direction to move from the current point: 'U' (up), 'D' (down), 'L' (left), 'R' (right). Calculate the... |
def vecsum(v):
if len(v) == 1:
return v[0]
else:
return v[0] + vecsum(v[1:]) | simplelr_Filter | [
{
"content": "Question:\nTranslate this into Python: function x = vecsum(v) if length(v) == 1 x = v; else x = v(1) + vecsum(v(2:end)); end end\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1153,
"level": 1,
"question": "Translate this into Python: function x = vecsum(v) if length(v) == 1 x = v; else x = v(1) + vecsum(v(2:end)); end end",
"split": "train"
} |
def linear_search(arr, target):
"""
Searches for a target value in a list using the linear search algorithm.
Args:
arr (list): The list to search in.
target: The value to search for.
Returns:
int: The index of the target if found; -1 otherwise.
"""
for index, va... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to implement the linear search algorithm in Python. Linear search is a simple search algorithm that checks each element in a list one by one until the desired element is found or the list is exhausted. It is not suitable for large lists, but it is efficient for small li... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1154,
"level": 1,
"question": "Write a function to implement the linear search algorithm in Python. Linear search is a simple search algorithm that checks each element in a list one by one until the desired element is found or the list is exhausted. It is not suitable for large list... |
from collections import Counter
def can_construct(ransomNote, magazine):
mag_counts = Counter(magazine)
ransom_counts = Counter(ransomNote)
for char, count in ransom_counts.items():
if mag_counts.get(char, 0) < count:
return False
return True | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to solve the赎金信(ransom note) problem. The function should take two inputs: ransomNote and magazine, and it should return True if the ransomNote can be constructed from the letters in the magazine, otherwise return False.\nAnswer:\nLet's think step by step.\n",
"role... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1155,
"level": 1,
"question": "Write a function to solve the赎金信(ransom note) problem. The function should take two inputs: ransomNote and magazine, and it should return True if the ransomNote can be constructed from the letters in the magazine, otherwise return False.",
"split": "... |
def find_pair_with_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return (seen[complement], i)
seen[num] = i
return None
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes in a list of integers and a target sum. The function should return a tuple of two indices of the list such that the values at these indices add up to the target sum. If no such pair exists, return `None`.\n\nExamples:\n\n```python\nfind_pair_with_sum([2, 7, 1... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1156,
"level": 1,
"question": "Write a function that takes in a list of integers and a target sum. The function should return a tuple of two indices of the list such that the values at these indices add up to the target sum. If no such pair exists, return `None`.\n\nExamples:\n\n```... |
def insert_index(sorted_list: list, num: int) -> int:
left = 0
right = len(sorted_list)
while left < right:
mid = (left + right) // 2
if sorted_list[mid] < num:
left = mid + 1
else:
right = mid
return left | simplelr_Data_Structure | [
{
"content": "Question:\n**Context**:\nYou are developing an application that handles sorted lists of integers. One critical operation in this application is to insert a new number in the correct position to maintain the list's sorted order. To do this efficiently, you need to determine the correct index at whi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1157,
"level": 1,
"question": "**Context**:\nYou are developing an application that handles sorted lists of integers. One critical operation in this application is to insert a new number in the correct position to maintain the list's sorted order. To do this efficiently, you need to... |
def contains_duplicates(lst):
return len(lst) != len(set(lst)) | simplelr_Filter | [
{
"content": "Question:\nIn Python, how to write a function that checks if a given list of integers contains any duplicates?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1158,
"level": 1,
"question": "In Python, how to write a function that checks if a given list of integers contains any duplicates?",
"split": "train"
} |
def calculate_bonus(employees_scores):
bonuses = {}
for employee, scores in employees_scores.items():
total = 0
for score in scores:
if score >= 90:
total += 100
elif score >= 80:
total += 50
elif score >= 70:
to... | simplelr_Taco | [
{
"content": "Question:\nA company's employees are given scores based on their performance in different projects. Each employee has taken part in some number of projects, and their scores for each project are listed in an array.\n\nYour task is to write a function `calculate_bonus` that accepts a dictionary whe... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1159,
"level": 1,
"question": "A company's employees are given scores based on their performance in different projects. Each employee has taken part in some number of projects, and their scores for each project are listed in an array.\n\nYour task is to write a function `calculate_b... |
def longest_mountain(arr):
n = len(arr)
if n < 3:
return 0
left = [1] * n
for i in range(1, n):
if arr[i] > arr[i-1]:
left[i] = left[i-1] + 1
else:
left[i] = 1
right = [1] * n
for i in range(n-2, -1, -1):
if arr[i] > arr[i+1]:
... | simplelr_Apps | [
{
"content": "Question:\nGiven an array of distinct integers arr, a \"mountain\" is defined as a subarray that:\n- Has a length of at least 3.\n- There exists some index i (0 < i < subarray.length - 1) such that:\n - arr[0] < arr[1] < ... < arr[i]\n - arr[i] > arr[i + 1] > ... > arr[subarray.length - 1]\n\nWr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1160,
"level": 1,
"question": "Given an array of distinct integers arr, a \"mountain\" is defined as a subarray that:\n- Has a length of at least 3.\n- There exists some index i (0 < i < subarray.length - 1) such that:\n - arr[0] < arr[1] < ... < arr[i]\n - arr[i] > arr[i + 1] > .... |
def rotate_matrix(matrix):
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for row in matrix:
row.reverse() | simplelr_Algorithm | [
{
"content": "Question:\n### Matrix Rotation\n\nYou are given an n x n matrix that represents a 2D image. You need to rotate the matrix 90 degrees clockwise in place. Implement a function that performs this rotation without using any extra memory for another matrix.\n\n### Input\n1. **matrix**: A 2D list repres... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1161,
"level": 1,
"question": "### Matrix Rotation\n\nYou are given an n x n matrix that represents a 2D image. You need to rotate the matrix 90 degrees clockwise in place. Implement a function that performs this rotation without using any extra memory for another matrix.\n\n### Inp... |
def is_drone_back(moves: str) -> bool:
left = right = up = down = 0
for move in moves:
if move == 'R':
right += 1
elif move == 'L':
left += 1
elif move == 'U':
up += 1
elif move == 'D':
down += 1
return left == right and up == d... | simplelr_Data_Structure | [
{
"content": "Question:\nA delivery drone moves in a 2-dimensional plane starting from the origin (0, 0). The movements of the drone are represented by a string consisting of the characters 'R' (Right), 'L' (Left), 'U' (Up), and 'D' (Down). \n\nYour task is to write a function `is_drone_back(moves: str) -> bool... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1162,
"level": 1,
"question": "A delivery drone moves in a 2-dimensional plane starting from the origin (0, 0). The movements of the drone are represented by a string consisting of the characters 'R' (Right), 'L' (Left), 'U' (Up), and 'D' (Down). \n\nYour task is to write a function... |
def max_consecutive_vowels(s):
vowels = {'a', 'e', 'i', 'o', 'u'}
max_count = 0
current_count = 0
for char in s:
if char.lower() in vowels:
current_count += 1
if current_count > max_count:
max_count = current_count
else:
current_count =... | simplelr_Evol | [
{
"content": "Question:\nGiven a string, write a function in Python that calculates the maximum number of consecutive vowels in the string. For this problem, consider vowels as 'a', 'e', 'i', 'o', and 'u'.\n\nExample:\n```python\ns = \"earthquake\"\n```\nThe function should return:\n```python\n3\n```\nExplanati... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1163,
"level": 1,
"question": "Given a string, write a function in Python that calculates the maximum number of consecutive vowels in the string. For this problem, consider vowels as 'a', 'e', 'i', 'o', and 'u'.\n\nExample:\n```python\ns = \"earthquake\"\n```\nThe function should re... |
def filter_even_numbers(numbers):
"""
Returns a new list containing only the even numbers from the provided list of integers.
Args:
numbers (list): A list of integers.
Returns:
list: A new list containing only the even integers from the input list.
Example:
>>> filter_even... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python script that takes a list of integers and returns a new list containing only the even numbers from the original list. Ensure the script is well-documented, including a brief description of the function, parameters, and return value.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1164,
"level": 1,
"question": "Write a Python script that takes a list of integers and returns a new list containing only the even numbers from the original list. Ensure the script is well-documented, including a brief description of the function, parameters, and return value.",
"... |
def sum_of_n_natural_numbers(n):
return n * (n + 1) // 2 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an integer `n` as input and returns the sum of the first `n` natural numbers. The function should be efficient and work for large values of `n`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1165,
"level": 1,
"question": "Create a function that takes an integer `n` as input and returns the sum of the first `n` natural numbers. The function should be efficient and work for large values of `n`.",
"split": "train"
} |
def create_dict():
"""
Create dictionary d and dictionary e, where e's value for key 'pi'
is the value for key 'pi' in d.
"""
d = {"pi": 3.14}
e = {"pi": d["pi"]} # Using dictionary d to set the value for key 'pi' in e
return d, e
# Test the function
d, e = create_dict()
assert d["pi"] ==... | simplelr_Filter | [
{
"content": "Question:\n### Task\nCreate a `Dictionary` with one key-value pair.\nUse the dictionary to lookup the value. \n\n### Test Case\nThe unit test will create a dictionary named `d`. The key will be the string `\"pi\"` and the value will be `3.14`. Use the dictionary `d` to create another dictionary `e... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1166,
"level": 1,
"question": "### Task\nCreate a `Dictionary` with one key-value pair.\nUse the dictionary to lookup the value. \n\n### Test Case\nThe unit test will create a dictionary named `d`. The key will be the string `\"pi\"` and the value will be `3.14`. Use the dictionary ... |
def find_max_value(lst):
if not lst:
raise ValueError("No data points to compare.")
values = [next(iter(d.values())) for d in lst]
return max(values) | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the maximum value in a list of dictionaries, where each dictionary has a single key-value pair. The key is a string, and the value is a numeric type (either integer or float). The function should return the maximum numeric value among the keys. If the lis... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1167,
"level": 1,
"question": "Write a python function to find the maximum value in a list of dictionaries, where each dictionary has a single key-value pair. The key is a string, and the value is a numeric type (either integer or float). The function should return the maximum numer... |
def remove_duplicates(lst):
seen = set()
result = []
for num in lst:
if num not in seen:
seen.add(num)
result.append(num)
return result | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to remove duplicates from a list of integers. The solution should be as efficient as possible and also consider the case where the list may contain negative numbers and zeros. How would you approach this problem?\nAnswer:\nLet's think step by step.\n",
"role"... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1168,
"level": 1,
"question": "Write a python function to remove duplicates from a list of integers. The solution should be as efficient as possible and also consider the case where the list may contain negative numbers and zeros. How would you approach this problem?",
"split": "t... |
def max_teams(scores, k):
scores.sort()
count = 0
i = 0
n = len(scores)
while i < n - 1:
if scores[i+1] - scores[i] <= k:
count += 1
i += 2
else:
i += 1
return count | simplelr_Leetcode | [
{
"content": "Question:\nGiven a **0-indexed** integer array `scores` representing the scores of players in a game. Each player can form a team with another player. A team is considered valid if the **absolute difference** between the scores of the two players in the team is **at most** a given integer `k`. Ret... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1169,
"level": 1,
"question": "Given a **0-indexed** integer array `scores` representing the scores of players in a game. Each player can form a team with another player. A team is considered valid if the **absolute difference** between the scores of the two players in the team is *... |
def longestWord(text):
words = text.split()
max_length = 0
result = ''
for word in words:
# Trim leading non-letters
start = 0
while start < len(word) and not word[start].isalpha():
start += 1
# Trim trailing non-letters
end = len(word) - 1
whi... | simplelr_Taco | [
{
"content": "Question:\nWrite a function `longestWord` that takes a string of text and returns the longest word in that text. If there are two or more words that are the same length, return the word that appears first in the text. For the purposes of this function, a \"word\" is defined as a sequence of non-sp... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1170,
"level": 1,
"question": "Write a function `longestWord` that takes a string of text and returns the longest word in that text. If there are two or more words that are the same length, return the word that appears first in the text. For the purposes of this function, a \"word\"... |
def rotate_array(arr, k):
n = len(arr)
if n == 0 or k == 0:
return arr
effective_k = k % n
if effective_k == 0:
return arr
return arr[-effective_k:] + arr[:-effective_k] | simplelr_Filter | [
{
"content": "Question:\nYour Task:\nYou are given an array of integers. Rotate the array to the right by k steps, where k is non-negative.\n\n Example:\nInput: [1,2,3,4,5,6,7] and k = 3\nOutput: [5,6,7,1,2,3,4]\n\nExplanation:\nrotate 1 steps to the right: [7,1,2,3,4,5,6]\nrotate 2 steps to the right: [6,7,1,2... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1171,
"level": 1,
"question": "Your Task:\nYou are given an array of integers. Rotate the array to the right by k steps, where k is non-negative.\n\n Example:\nInput: [1,2,3,4,5,6,7] and k = 3\nOutput: [5,6,7,1,2,3,4]\n\nExplanation:\nrotate 1 steps to the right: [7,1,2,3,4,5,6]\nro... |
def char_frequency(s):
frequency = {}
for char in s:
if char.isalpha():
lower_char = char.lower()
if lower_char in frequency:
frequency[lower_char] += 1
else:
frequency[lower_char] = 1
return frequency
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that takes a string of text and returns a dictionary with the frequency of each character in the string. The function should ignore case (i.e., 'A' and 'a' should be counted as the same character) and ignore non-alphabetic characters.\n\nFor example:\n```python\nchar_fr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1172,
"level": 1,
"question": "Write a function that takes a string of text and returns a dictionary with the frequency of each character in the string. The function should ignore case (i.e., 'A' and 'a' should be counted as the same character) and ignore non-alphabetic characters.\... |
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
a, b = 0, 1
for i in range(2, n + 1):
current = a + b
a = b
b = current
return b
| simplelr_Taco | [
{
"content": "Question:\nA Fibonacci sequence is one where every number after the first two is the sum of the two preceding ones. Typically, it starts with `0` and `1`. The sequence often starts as `0, 1, 1, 2, 3, 5, 8, …`. \n\nWrite a function `fibonacci(n)` that returns the `n`-th Fibonacci number where `n` i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1173,
"level": 1,
"question": "A Fibonacci sequence is one where every number after the first two is the sum of the two preceding ones. Typically, it starts with `0` and `1`. The sequence often starts as `0, 1, 1, 2, 3, 5, 8, …`. \n\nWrite a function `fibonacci(n)` that returns the ... |
def count_vowels_and_digits(string: str) -> tuple:
vowels = sum(1 for c in string if c in {'a', 'e', 'i', 'o', 'u'})
digits = sum(1 for c in string if c.isdigit())
return (vowels, digits) | simplelr_Codeforces | [
{
"content": "Question:\nYou are given a string consisting of lowercase alphabets and digits. Write a function that counts the number of vowels (a, e, i, o, u) and the number of digits in the string, and returns them as a tuple (number_of_vowels, number_of_digits).\n\nThe function should be implemented as follo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1174,
"level": 1,
"question": "You are given a string consisting of lowercase alphabets and digits. Write a function that counts the number of vowels (a, e, i, o, u) and the number of digits in the string, and returns them as a tuple (number_of_vowels, number_of_digits).\n\nThe func... |
def remove_consecutive_duplicates(text: str) -> str:
words = text.split()
if not words:
return ""
result = [words[0]]
for word in words[1:]:
if word != result[-1]:
result.append(word)
return ' '.join(result) | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nCreate a function that identifies and removes consecutive duplicate words in a given text. The function should also ensure that the resulting text has only single spaces between words and no leading or trailing spaces.\n\n### Function Signature\n```python\ndef r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1175,
"level": 1,
"question": "### Problem Statement\n\nCreate a function that identifies and removes consecutive duplicate words in a given text. The function should also ensure that the resulting text has only single spaces between words and no leading or trailing spaces.\n\n### F... |
def countUniqueWithDuplicates(A, N):
freq = {}
for num in A:
if num in freq:
freq[num] += 1
else:
freq[num] = 1
count = 0
for key in freq:
if freq[key] >= 2:
count += 1
return count
| simplelr_Taco | [
{
"content": "Question:\nGiven an array A of size N containing integers, your task is to return the number of unique elements in the array that have at least one duplicate element also present in the array.\n\nExample 1:\nInput:\nN = 7\nA[] = {1, 2, 3, 2, 1, 4, 5}\nOutput: 2\nExplanation: The elements '1' and '... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1176,
"level": 1,
"question": "Given an array A of size N containing integers, your task is to return the number of unique elements in the array that have at least one duplicate element also present in the array.\n\nExample 1:\nInput:\nN = 7\nA[] = {1, 2, 3, 2, 1, 4, 5}\nOutput: 2\n... |
def min_operations_to_equal_elements(nums: list[int]) -> int:
if not nums:
return 0
n = len(nums)
if n == 1:
return 0
sum_nums = sum(nums)
max_a = max(nums)
mod = n - 1
target_mod = sum_nums % mod
b_list = [sum_nums - a_i * mod for a_i in nums]
max_b = max(b_list)
... | simplelr_Algorithm | [
{
"content": "Question:\n### Minimum Operations to Make Array Elements Equal\n\n#### Context:\nYou are tasked with writing a function to determine the minimum number of operations required to make all elements of an array equal. The only operation allowed is incrementing `n-1` elements of the array by 1.\n\n###... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1177,
"level": 1,
"question": "### Minimum Operations to Make Array Elements Equal\n\n#### Context:\nYou are tasked with writing a function to determine the minimum number of operations required to make all elements of an array equal. The only operation allowed is incrementing `n-1`... |
def longestConsecutive(nums):
if not nums:
return 0
longest_streak = 0
num_set = set(nums)
for num in num_set:
if (num - 1) not in num_set:
current_num = num
current_streak = 1
while (current_num + 1) in num_set:
current_num += 1
... | simplelr_Filter | [
{
"content": "Question:\nThis is an example of a problem I would like to solve:\n\nGiven an array of integers, find the length of the longest consecutive sequence.\n\nFor example,\n\nInput: nums = [100, 4, 200, 1, 3, 2]\nOutput: 4\nExplanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1178,
"level": 1,
"question": "This is an example of a problem I would like to solve:\n\nGiven an array of integers, find the length of the longest consecutive sequence.\n\nFor example,\n\nInput: nums = [100, 4, 200, 1, 3, 2]\nOutput: 4\nExplanation: The longest consecutive element... |
def minCoins(denominations, amount):
if amount == 0:
return 0
dp = [float('inf')] * (amount + 1)
dp[0] = 0 # Base case: 0 coins needed to make 0 amount
for i in range(1, amount + 1):
for coin in denominations:
if coin <= i:
dp[i] = min(dp[i], dp[i -... | simplelr_Apps | [
{
"content": "Question:\nImplement a function to determine the minimum number of coins required to make a given amount of money. You are given an array of distinct positive integer denominations of the coins, and a target amount. Assume that there is an infinite supply of each type of coin. If it is not possibl... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1179,
"level": 1,
"question": "Implement a function to determine the minimum number of coins required to make a given amount of money. You are given an array of distinct positive integer denominations of the coins, and a target amount. Assume that there is an infinite supply of each... |
def max_subarray_sum(numbers):
if not numbers:
return 0
max_ending_here = max_so_far = numbers[0]
for number in numbers[1:]:
max_ending_here = max(number, max_ending_here + number)
max_so_far = max(max_so_far, max_ending_here)
return max_so_far | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes a list of numbers as input and returns the maximum sum of a contiguous subarray. This function should be efficient, preferably using Kadane's algorithm, which has a time complexity of O(n).\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1180,
"level": 1,
"question": "Create a function that takes a list of numbers as input and returns the maximum sum of a contiguous subarray. This function should be efficient, preferably using Kadane's algorithm, which has a time complexity of O(n).",
"split": "train"
} |
def find_duplicates(nums):
sorted_nums = sorted(nums)
result = set()
for i in range(len(sorted_nums) - 1):
if sorted_nums[i] == sorted_nums[i + 1]:
result.add(sorted_nums[i])
return list(result) | simplelr_Filter | [
{
"content": "Question:\ndef find_duplicates(nums):\n nums.sort()\n result = set()\n for i in range(len(nums) - 1):\n if nums[i] == nums[i + 1]:\n result.add(nums[i])\n return list(result)\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1181,
"level": 1,
"question": "def find_duplicates(nums):\n nums.sort()\n result = set()\n for i in range(len(nums) - 1):\n if nums[i] == nums[i + 1]:\n result.add(nums[i])\n return list(result)",
"split": "train"
} |
def product_except_self(nums, k):
count_zero = nums.count(0)
P = 1
for num in nums:
if num != 0:
P *= num
if count_zero >= 2:
sum_result = 0
elif count_zero == 1:
sum_result = P
else:
sum_result = 0
for num in nums:
sum_result ... | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an array of integers `nums` and an integer `k`. Construct a new array `result` such that each element at index `i` of `result` is the product of all the elements in `nums` except `nums[i]`, and ensure that the sum of all elements in `result` is less than or equal to `k`. R... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1182,
"level": 1,
"question": "You are given an array of integers `nums` and an integer `k`. Construct a new array `result` such that each element at index `i` of `result` is the product of all the elements in `nums` except `nums[i]`, and ensure that the sum of all elements in `resu... |
def truncate_array(arr, k):
counts = {}
result = []
for num in arr:
if counts.get(num, 0) < k:
result.append(num)
counts[num] = counts.get(num, 0) + 1
return result | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `arr` and an integer `k`, truncate the array such that each element appears at most `k` times in the final array. Return the truncated array while maintaining the order of first occurrences.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1183,
"level": 1,
"question": "Given an array of integers `arr` and an integer `k`, truncate the array such that each element appears at most `k` times in the final array. Return the truncated array while maintaining the order of first occurrences.",
"split": "train"
} |
import random
def generate_random_point(grid_width, grid_height):
"""
Generates a random point within the grid, not on the border.
Args:
grid_width (int): The width of the grid.
grid_height (int): The height of the grid.
Returns:
tuple: A tuple containing the x and y coordinates of the ra... | simplelr_Filter | [
{
"content": "Question:\nI am trying to make a project that has objectives, and I want to make the objectives appear at random points on a grid. To do that, I need a function that can generate a random point on a grid given the grid's dimensions. \n\nHere is what I have so far:\n```python\nimport random\n\ndef... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1184,
"level": 1,
"question": "I am trying to make a project that has objectives, and I want to make the objectives appear at random points on a grid. To do that, I need a function that can generate a random point on a grid given the grid's dimensions. \n\nHere is what I have so fa... |
from typing import List, Tuple
def get_maximum_value(items: List[Tuple[int, int]], capacity: int) -> int:
if capacity == 0 or not items:
return 0
dp = [0] * (capacity + 1)
for value, weight in items:
for j in range(capacity, weight - 1, -1):
dp[j] = max(dp[j], dp[j - w... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are given a knapsack that can hold a maximum weight of `capacity`. You are also given a list of items, each defined by its `value` and `weight`. You need to determine the maximum summed value of items that can be packed into the knapsack without exceeding the weight limit. Each item... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1185,
"level": 1,
"question": "You are given a knapsack that can hold a maximum weight of `capacity`. You are also given a list of items, each defined by its `value` and `weight`. You need to determine the maximum summed value of items that can be packed into the knapsack without ex... |
def remove_duplicates(input_list):
seen = set()
unique_list = []
for element in input_list:
if element not in seen:
seen.add(element)
unique_list.append(element)
return unique_list | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to remove duplicates from the given list and return the list of unique elements in the same order as their first occurrence.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1186,
"level": 1,
"question": "Write a python function to remove duplicates from the given list and return the list of unique elements in the same order as their first occurrence.",
"split": "train"
} |
def int_list_to_str_list(nums):
return [str(num) for num in nums] | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in a list of integers and returns a new list where all the integers are converted to their string representation. You should use list comprehension for this task.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1187,
"level": 1,
"question": "Create a function that takes in a list of integers and returns a new list where all the integers are converted to their string representation. You should use list comprehension for this task.",
"split": "train"
} |
def parse_name_value_pairs(pairs):
result = {}
for pair in pairs:
name, value = pair.split('=', 1)
if name in result:
result[name].append(value)
else:
result[name] = [value]
return result
| simplelr_Taco | [
{
"content": "Question:\nYou are given a list of items which represents a collection of name-value pairs in the format \"name=value\". Your task is to write a function that will parse this list and return a dictionary where each key is the name and each corresponding value is a list of values associated with th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1188,
"level": 1,
"question": "You are given a list of items which represents a collection of name-value pairs in the format \"name=value\". Your task is to write a function that will parse this list and return a dictionary where each key is the name and each corresponding value is ... |
def rotate_list(nums: list[int], k: int) -> list[int]:
if not nums:
return []
n = len(nums)
k %= n
if k == 0:
return list(nums)
return nums[-k:] + nums[:-k] | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Assessment Question: Rotate a List by K Positions\n\nYou have been provided with a list of integers `nums` and an integer `k`. Write a function `rotate_list(nums: list[int], k: int) -> list[int]` that rotates the list to the right by `k` positions. Rotation means that the ele... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1189,
"level": 1,
"question": "### Coding Assessment Question: Rotate a List by K Positions\n\nYou have been provided with a list of integers `nums` and an integer `k`. Write a function `rotate_list(nums: list[int], k: int) -> list[int]` that rotates the list to the right by `k` pos... |
def common_elements(arr1, arr2):
set1 = set(arr1)
set2 = set(arr2)
common = set1 & set2
return sorted(common) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes in two arrays: `arr1` and `arr2`. The function should return a list containing all the elements that are common to both arrays, without any duplicates. Additionally, the returned list should be sorted in ascending order.\nAnswer:\nLet's think step by step.\n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1190,
"level": 1,
"question": "Create a function that takes in two arrays: `arr1` and `arr2`. The function should return a list containing all the elements that are common to both arrays, without any duplicates. Additionally, the returned list should be sorted in ascending order.",
... |
def longest_unique_substring(s):
last_seen = {}
left = 0
max_len = 0
start = 0
for right in range(len(s)):
char = s[right]
if char in last_seen and last_seen[char] >= left:
left = last_seen[char] + 1
last_seen[char] = right
current_len = right - left + 1
... | simplelr_Filter | [
{
"content": "Question:\nGiven a string input, return the longest substring without repeating characters. If there are multiple substrings of the same maximum length, return the first occurring one.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1191,
"level": 1,
"question": "Given a string input, return the longest substring without repeating characters. If there are multiple substrings of the same maximum length, return the first occurring one.",
"split": "train"
} |
def max_subarray_sum(nums, k):
"""
Given an array of integers, find the maximum sum of a subarray with a size of k.
Args:
nums (list): A list of integers.
k (int): The size of the subarray.
Returns:
int: The maximum sum of a subarray with a size of k.
"""
n = len(nums)
current_... | simplelr_Filter | [
{
"content": "Question:\nGiven an array of integers, find the maximum sum of a subarray with a size of k.\n\nExample 1:\nInput: nums = [1,2,3,4,5], k = 3\nOutput: 12\nExplanation: [3,4,5] is the subarray with the maximum sum.\n\nExample 2:\nInput: nums = [-1,-2,-3,-4,-5], k = 3\nOutput: -6\nExplanation: [-1,-2,... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1192,
"level": 1,
"question": "Given an array of integers, find the maximum sum of a subarray with a size of k.\n\nExample 1:\nInput: nums = [1,2,3,4,5], k = 3\nOutput: 12\nExplanation: [3,4,5] is the subarray with the maximum sum.\n\nExample 2:\nInput: nums = [-1,-2,-3,-4,-5], k = ... |
def next_greater_element(arr):
stack = []
result = []
for num in reversed(arr):
while stack and stack[-1] <= num:
stack.pop()
if stack:
result.append(stack[-1])
else:
result.append(-1)
stack.append(num)
return result[::-1]
| simplelr_Taco | [
{
"content": "Question:\nWrite a function that accepts a list of integers and returns a new list containing the **next greater element** for each corresponding element in the input list. The **next greater element** for an element `x` is the first greater element that comes after `x` in the input list; if no su... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1193,
"level": 1,
"question": "Write a function that accepts a list of integers and returns a new list containing the **next greater element** for each corresponding element in the input list. The **next greater element** for an element `x` is the first greater element that comes af... |
def max_subarray_len(nums, k):
sum_indices = {0: -1}
current_sum = 0
max_len = 0
for i, num in enumerate(nums):
current_sum += num
target = current_sum - k
if target in sum_indices:
length = i - sum_indices[target]
if length > max_len:
max_... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers nums and an integer k, return the maximum length of a subarray that sums to k. If no such subarray exists, return 0. A subarray is a contiguous part of an array.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1194,
"level": 1,
"question": "Given an array of integers nums and an integer k, return the maximum length of a subarray that sums to k. If no such subarray exists, return 0. A subarray is a contiguous part of an array.",
"split": "train"
} |
def extended_anagram(s1: str, s2: str) -> bool:
# Check if lengths are different
if len(s1) != len(s2):
return False
# Handle case when both strings are empty
if len(s1) == 0:
return True
# Initialize frequency arrays for each string
arr1 = [0] * 95
arr2 = [0] * 95
... | simplelr_Data_Structure | [
{
"content": "Question:\n**Anagram Checker with Extended Character Set**\n\nGiven two strings, determine if they are anagrams of each other. The strings may contain any printable ASCII characters, and the check should be case-insensitive. You must handle all edge cases, including empty strings and strings with ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1195,
"level": 1,
"question": "**Anagram Checker with Extended Character Set**\n\nGiven two strings, determine if they are anagrams of each other. The strings may contain any printable ASCII characters, and the check should be case-insensitive. You must handle all edge cases, includ... |
from typing import List
def max_gold(A: List[int]) -> int:
if not A:
return 0
n = len(A)
if n == 1:
return A[0]
prev_prev = 0
prev = A[0]
for i in range(1, n):
current = max(prev, prev_prev + A[i])
prev_prev, prev = prev, current
return prev
| simplelr_Taco | [
{
"content": "Question:\nIn a remote village, there are N unique houses aligned in a straight row from left to right numbered from 1 to N. Each house has varying amounts of gold inside it. Two thieves decide to rob the village but they have a peculiar problem: these thieves have an agreement that they will neve... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1196,
"level": 1,
"question": "In a remote village, there are N unique houses aligned in a straight row from left to right numbered from 1 to N. Each house has varying amounts of gold inside it. Two thieves decide to rob the village but they have a peculiar problem: these thieves ha... |
def is_palindrome(s):
cleaned = ''.join([c for c in s if c.isalnum()]).lower()
return cleaned == cleaned[::-1] | simplelr_Filter | [
{
"content": "Question:\nAre there any built-in functions in Python that can be used to determine if a given string is a palindrome? If not, how can I write a function to check if a string is a palindrome?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1197,
"level": 1,
"question": "Are there any built-in functions in Python that can be used to determine if a given string is a palindrome? If not, how can I write a function to check if a string is a palindrome?",
"split": "train"
} |
def bitwise_multiply(a, b):
if a == 0 or b == 0:
return 0
sign = -1 if (a < 0) ^ (b < 0) else 1
a = abs(a)
b = abs(b)
result = 0
while b != 0:
if b & 1:
result += a
a = a << 1 # a = a * 2
b = b >> 1 # b = b // 2
return sign * result | simplelr_Filter | [
{
"content": "Question:\nI need to create a Python function that calculates the product of two integers using only bitwise operations and addition. The function should be able to handle both positive and negative integers. Can you help me with that?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1198,
"level": 1,
"question": "I need to create a Python function that calculates the product of two integers using only bitwise operations and addition. The function should be able to handle both positive and negative integers. Can you help me with that?",
"split": "train"
} |
def is_valid_parentheses(s):
stack = []
mapping = { '(': ')', '{': '}', '[': ']' }
for char in s:
if char in mapping:
stack.append(mapping[char])
else:
if not stack:
return False
if stack.pop() != char:
return False
retu... | simplelr_Filter | [
{
"content": "Question:\nThis is a fun and challenging coding problem that tests your understanding of recursion, loops, and data structures.\n\n **Problem:** Given a string containing only parentheses, write a function to check if the string is valid.\n\n **A valid string of parentheses must meet the following... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 1199,
"level": 1,
"question": "This is a fun and challenging coding problem that tests your understanding of recursion, loops, and data structures.\n\n **Problem:** Given a string containing only parentheses, write a function to check if the string is valid.\n\n **A valid string of ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.