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_missing_integer(arr):
n = len(arr)
expected_sum = (n + 1) * (n + 2) // 2
actual_sum = sum(arr)
return expected_sum - actual_sum | simplelr_Apps | [
{
"content": "Question:\n### Problem Statement: Find Missing Integer\n\nYou are given an array containing `n` distinct integers ranging from `1` to `n+1`. This means the array is a permutation of the numbers from `1` to `n+1` with one number missing. Write a function to find and return the missing integer.\n\nY... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2600,
"level": 1,
"question": "### Problem Statement: Find Missing Integer\n\nYou are given an array containing `n` distinct integers ranging from `1` to `n+1`. This means the array is a permutation of the numbers from `1` to `n+1` with one number missing. Write a function to find a... |
def running_total_sum(numbers):
total = 0
for number in numbers:
total += number
return total | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that finds the running total sum of a list of integers and returns the final sum.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2601,
"level": 1,
"question": "Create a function that finds the running total sum of a list of integers and returns the final sum.",
"split": "train"
} |
def sum_even_numbers(n):
if n < 0:
return 0
m = n if n % 2 == 0 else n - 1
k = m // 2
return k * (k + 1) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an integer `n` as an input and returns the sum of all the even numbers from 0 to `n` inclusive. Ensure that your function handles edge cases, such as when `n` is less than 0.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2602,
"level": 1,
"question": "Create a function that takes an integer `n` as an input and returns the sum of all the even numbers from 0 to `n` inclusive. Ensure that your function handles edge cases, such as when `n` is less than 0.",
"split": "train"
} |
def max_subarray_sum(nums):
if not nums:
return 0
current_max = global_max = nums[0]
for num in nums[1:]:
current_max = max(num, current_max + num)
if current_max > global_max:
global_max = current_max
return global_max | simplelr_Filter | [
{
"content": "Question:\nHere's a problem I'm working on:\n\n**Problem:** Given a list of integers, find the contiguous subarray with the maximum sum.\n\n**Example:**\n\n```\nInput: [-2, 1, -3, 4, -1, 2, 1, -5, 4]\nOutput: 6\n```\n\n**Explanation:**\n\nThe contiguous subarray `[4, -1, 2, 1] ` has the largest su... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2603,
"level": 1,
"question": "Here's a problem I'm working on:\n\n**Problem:** Given a list of integers, find the contiguous subarray with the maximum sum.\n\n**Example:**\n\n```\nInput: [-2, 1, -3, 4, -1, 2, 1, -5, 4]\nOutput: 6\n```\n\n**Explanation:**\n\nThe contiguous subarray ... |
def int_to_binary(n):
"""
Convert an integer to its binary representation as a string.
For positive numbers, returns the binary string without leading zeros.
For negative numbers, returns the 32-bit two's complement representation.
Args:
n (int): The integer to convert.
Returns:
... | simplelr_Filter | [
{
"content": "Question:\nWrite a function in Python to convert a given number to its binary representation and return the result as a string. The function should handle both positive and negative numbers, and for negative numbers, it should represent them in two's complement form, assuming a 32-bit integer. Ens... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2604,
"level": 1,
"question": "Write a function in Python to convert a given number to its binary representation and return the result as a string. The function should handle both positive and negative numbers, and for negative numbers, it should represent them in two's complement f... |
def filter_dict_greater(a, b):
result = {}
for key in b:
if key in a:
if b[key] > a[key]:
result[key] = b[key]
return result | simplelr_Filter | [
{
"content": "Question:\nWrite a function that takes two dictionary parameters and then returns a dictionary that contains only the key-value pairs from dictionary \"b\" if and only if the values are greater than their corresponding ones in dictionary \"a\".\nAnswer:\nLet's think step by step.\n",
"role": "... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2605,
"level": 1,
"question": "Write a function that takes two dictionary parameters and then returns a dictionary that contains only the key-value pairs from dictionary \"b\" if and only if the values are greater than their corresponding ones in dictionary \"a\".",
"split": "trai... |
def find_maximum(arr):
if not arr:
return None
return max(arr) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an array of integers as an argument and returns the maximum value among those integers. If the array is empty, the function should return `None`.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2606,
"level": 1,
"question": "Create a function that takes an array of integers as an argument and returns the maximum value among those integers. If the array is empty, the function should return `None`.",
"split": "train"
} |
def merge_sorted_arrays(arr1, arr2):
result = []
i = j = 0
while i < len(arr1) and j < len(arr2):
if arr1[i] <= arr2[j]:
result.append(arr1[i])
i += 1
else:
result.append(arr2[j])
j += 1
# Add remaining elements from arr1
while i < len(... | simplelr_Evol | [
{
"content": "Question:\nWrite a function that takes two arrays of integers, arr1 and arr2, which are both sorted in ascending order, and returns a merged array that contains all integers from both arrays in ascending order.\n\nExample:\nInput: arr1 = [1, 3, 5], arr2 = [2, 4, 6]\nOutput: [1, 2, 3, 4, 5, 6]\nAns... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2607,
"level": 1,
"question": "Write a function that takes two arrays of integers, arr1 and arr2, which are both sorted in ascending order, and returns a merged array that contains all integers from both arrays in ascending order.\n\nExample:\nInput: arr1 = [1, 3, 5], arr2 = [2, 4, ... |
def find_anagrams(word_list):
anagrams = {}
for word in word_list:
key = ''.join(sorted(word))
if key in anagrams:
anagrams[key].append(word)
else:
anagrams[key] = [word]
# Return only groups with more than one word
return [group for group in anagrams.valu... | simplelr_Filter | [
{
"content": "Question:\nI need to write a program that finds all the anagrams in a given list of words. How can I achieve this in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2608,
"level": 1,
"question": "I need to write a program that finds all the anagrams in a given list of words. How can I achieve this in Python?",
"split": "train"
} |
def rearrange_string(s, indices):
return ''.join([s[i] for i in indices]) | simplelr_Filter | [
{
"content": "Question:\nGiven a string and a list of indices, write a Python function to rearrange the characters in the string according to the order specified by the list of indices. The list of indices represents the new positions of the characters in the original string.\nAnswer:\nLet's think step by step.... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2609,
"level": 1,
"question": "Given a string and a list of indices, write a Python function to rearrange the characters in the string according to the order specified by the list of indices. The list of indices represents the new positions of the characters in the original string."... |
def nextClosestTime(time):
from itertools import product
# Split the input into hours and minutes
current_h, current_m = map(int, time.split(':'))
current_min = current_h * 60 + current_m
# Extract unique digits from the input time
digits = list(set(time.replace(':', '')))
# Generate all ... | simplelr_Taco | [
{
"content": "Question:\nYou are given the task of improving a company's digital clock system. The current system takes the current time in HH:MM format and aims to display the next closest time using the exact same digits currently present in the input time. If no valid next time can be formed within the same ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2610,
"level": 1,
"question": "You are given the task of improving a company's digital clock system. The current system takes the current time in HH:MM format and aims to display the next closest time using the exact same digits currently present in the input time. If no valid next ... |
import string
from collections import Counter
def get_most_frequent_words(file_path: str, top_n: int) -> list | None:
# Input validation
if not isinstance(file_path, str) or not file_path or not isinstance(top_n, int) or top_n <= 0:
return None
try:
with open(file_path, 'r') as file:
... | simplelr_Algorithm | [
{
"content": "Question:\n### Word Frequency Analysis Coding Challenge\n\n**Context**:\nYou are given a large text file, and you need to analyze the frequency of each word in the text. Your task is to write a function that reads the file and returns a list of the most frequent words with their counts.\n\n### Fun... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2611,
"level": 1,
"question": "### Word Frequency Analysis Coding Challenge\n\n**Context**:\nYou are given a large text file, and you need to analyze the frequency of each word in the text. Your task is to write a function that reads the file and returns a list of the most frequent ... |
def assignPrizes(scores):
n = len(scores)
if n == 0:
return []
prizes = [1] * n
# Left to right pass
for i in range(1, n):
if scores[i] > scores[i-1]:
prizes[i] = prizes[i-1] + 1
# Right to left pass
for i in range(n-2, -1, -1):
if scores[i] > sc... | simplelr_Codeforces | [
{
"content": "Question:\nIn a coding competition, there were n participants. Each participant achieved a score in the competition, represented by the array scores[], where scores[i] is the score of the i-th participant. After the competition, the organizers decided to give prizes to the participants based on th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2612,
"level": 1,
"question": "In a coding competition, there were n participants. Each participant achieved a score in the competition, represented by the array scores[], where scores[i] is the score of the i-th participant. After the competition, the organizers decided to give pri... |
import re
def contains_zipcode(s):
pattern = r'(?<!\d)\d{5}(?:-\d{4})?(?!\d)'
return bool(re.search(pattern, s))
# Example usage:
# print(check_zipcode("12345")) # Returns: True
# print(check_zipcode("12345-1234")) # Returns: True
# print(check_zipcode("1234")) # Returns: False
# print(check_zipcode("12345... | simplelr_Filter | [
{
"content": "Question:\nCreate for me a python regex that checks if a string has zipcodes in the format of 12345-1234 or 12345. It should return true if any occur and false otherwise.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2613,
"level": 1,
"question": "Create for me a python regex that checks if a string has zipcodes in the format of 12345-1234 or 12345. It should return true if any occur and false otherwise.",
"split": "train"
} |
def sort_string_by_frequency(s: str) -> str:
# Count each character's frequency and track their first occurrence
freq = {}
first_occurrence = {}
for index, char in enumerate(s):
if char not in freq:
freq[char] = 0
first_occurrence[char] = index
freq[char] += 1
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Challenge\n\n### Problem Statement\n\nWrite a Python function called `sort_string_by_frequency` that takes in a string `s` and returns a new string where the characters are sorted by their frequency in descending order. If two characters have the same frequency, they should a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2614,
"level": 1,
"question": "### Coding Challenge\n\n### Problem Statement\n\nWrite a Python function called `sort_string_by_frequency` that takes in a string `s` and returns a new string where the characters are sorted by their frequency in descending order. If two characters hav... |
def value_exists(lst, value):
return value in lst | simplelr_Filter | [
{
"content": "Question:\nHow can I write a Python function that checks if a specific value exists in a given list and returns a boolean result?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2615,
"level": 1,
"question": "How can I write a Python function that checks if a specific value exists in a given list and returns a boolean result?",
"split": "train"
} |
def int_to_binary_strings(numbers):
return [bin(num) for num in numbers] | simplelr_Apps | [
{
"content": "Question:\nWrite a function that takes a list of integers as input and returns a list of strings where each string represents the corresponding integer in binary format, prefixed with '0b'.\n\nFor example:\n\n```\n[3, 7, 10, 16] --> [\"0b11\", \"0b111\", \"0b1010\", \"0b10000\"]\n```\n\nInput will... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2616,
"level": 1,
"question": "Write a function that takes a list of integers as input and returns a list of strings where each string represents the corresponding integer in binary format, prefixed with '0b'.\n\nFor example:\n\n```\n[3, 7, 10, 16] --> [\"0b11\", \"0b111\", \"0b1010... |
def divisible_and_reversed(lst, n):
divisible = [x for x in lst if x % n == 0]
return divisible[::-1] | simplelr_Evol | [
{
"content": "Question:\nWrite a Python function that takes a list of integers and an integer `n`. The function should return a new list containing all the elements of the original list that are divisible by `n`, but with the order of elements reversed.\n\nExample:\n- Input: list = [12, 4, 9, 10, 28, 45, 30], n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2617,
"level": 1,
"question": "Write a Python function that takes a list of integers and an integer `n`. The function should return a new list containing all the elements of the original list that are divisible by `n`, but with the order of elements reversed.\n\nExample:\n- Input: l... |
def findPairs(arr, n, target):
arr.sort()
result = []
i = 0
j = n - 1
while i < j:
current_sum = arr[i] + arr[j]
if current_sum < target:
i += 1
elif current_sum > target:
j -= 1
else:
result.append([arr[i], arr[j]])
# M... | simplelr_Taco | [
{
"content": "Question:\nGiven an integer array and a target sum, find all the unique pairs of integers in the array that add up to the target sum. Each pair should be presented in ascending order, and the output should contain unique pairs (i.e., no duplicates).\n\nExample 1:\nInput: Arr[] = {1, 2, 3, 4, 5, 6}... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2618,
"level": 1,
"question": "Given an integer array and a target sum, find all the unique pairs of integers in the array that add up to the target sum. Each pair should be presented in ascending order, and the output should contain unique pairs (i.e., no duplicates).\n\nExample 1:... |
from typing import List
def calculate_total_bonus(ratings: List[int]) -> int:
bonus_map = {1: 0, 2: 0, 3: 500, 4: 1000, 5: 2000}
total = 0
for r in ratings:
total += bonus_map[r]
return total | simplelr_Apps | [
{
"content": "Question:\nA company wants to implement a simple employee bonus distribution system. Each employee is assigned a performance rating between 1 and 5 (inclusive). Based on the performance rating, employees will receive bonuses as follows:\n\n- Employees with a rating of 1 or 2 do not receive any bon... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2619,
"level": 1,
"question": "A company wants to implement a simple employee bonus distribution system. Each employee is assigned a performance rating between 1 and 5 (inclusive). Based on the performance rating, employees will receive bonuses as follows:\n\n- Employees with a rati... |
def suggest_friends(user, graph):
if user not in graph:
return []
user_interests = graph[user]
suggestions = []
for friend in graph:
if friend == user:
continue
friend_interests = graph[friend]
common_interests = user_interests & friend_interests
count... | simplelr_Algorithm | [
{
"content": "Question:\n### Social Network Friend Suggestion Based on Mutual Interests\n\nYou are tasked with implementing a function to suggest new friends to a user based on mutual interests in a simplified social network system. This problem will help assess your skills in graph traversal and algorithmic pr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2620,
"level": 1,
"question": "### Social Network Friend Suggestion Based on Mutual Interests\n\nYou are tasked with implementing a function to suggest new friends to a user based on mutual interests in a simplified social network system. This problem will help assess your skills in... |
from collections import Counter
def count_unique_words(word_list):
counts = Counter(word_list)
unique_count = sum(1 for count in counts.values() if count == 1)
return unique_count
# Example usage:
word_list = ["apple", "banana", "apple", "orange", "grape", "banana", "banana"]
print(count_unique_words(word... | simplelr_Filter | [
{
"content": "Question:\nI have a list of words, and I need to count the number of words that appear only once in the list. \nHere is the list: \n{\"apple\", \"banana\", \"apple\", \"orange\", \"grape\", \"banana\", \"banana\"}\nCan you help me write a code to solve this problem?\nAnswer:\nLet's think step by s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2621,
"level": 1,
"question": "I have a list of words, and I need to count the number of words that appear only once in the list. \nHere is the list: \n{\"apple\", \"banana\", \"apple\", \"orange\", \"grape\", \"banana\", \"banana\"}\nCan you help me write a code to solve this probl... |
def split_even_odd_indices(lst):
even = lst[::2]
odd = lst[1::2]
return (even, odd) | simplelr_Evol | [
{
"content": "Question:\nCreate a function that takes a list of integers and returns a tuple of two lists. The first list contains the even-indexed elements, while the second list contains the odd-indexed elements. If the input list is empty, return two empty lists.\n\nExample:\n\nInput:\n[10, 15, 20, 25, 30, 3... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2622,
"level": 1,
"question": "Create a function that takes a list of integers and returns a tuple of two lists. The first list contains the even-indexed elements, while the second list contains the odd-indexed elements. If the input list is empty, return two empty lists.\n\nExample... |
def compress(s):
if not s:
return ""
result = []
current_char = s[0]
count = 1
for char in s[1:]:
if char == current_char:
count += 1
else:
if count == 1:
result.append(current_char)
else:
result.append(curre... | simplelr_Taco | [
{
"content": "Question:\nYou are given a string consisting of lowercase alphabetical characters. Your task is to compress the string using the following algorithm:\n\n1. Identify sequences of consecutive characters that are the same.\n2. Replace each such sequence with the character followed by the number of ti... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2623,
"level": 1,
"question": "You are given a string consisting of lowercase alphabetical characters. Your task is to compress the string using the following algorithm:\n\n1. Identify sequences of consecutive characters that are the same.\n2. Replace each such sequence with the cha... |
def are_matrices_equal(matrix1, matrix2):
# Check if the number of rows is the same
if len(matrix1) != len(matrix2):
return False
# Iterate through each corresponding row pair
for row1, row2 in zip(matrix1, matrix2):
# Check if the number of columns in each row is the same
if len... | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that determines if two matrices are equal. Two matrices are equal if they have the same number of rows and columns and all corresponding elements are equal. The function should take two 2D lists (matrices) as input parameters and return a boolean value indicating wheth... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2624,
"level": 1,
"question": "Create a function that determines if two matrices are equal. Two matrices are equal if they have the same number of rows and columns and all corresponding elements are equal. The function should take two 2D lists (matrices) as input parameters and retu... |
def max_subarray_sum(arr):
if not arr:
return 0
max_ending_here = max_so_far = arr[0]
for num in arr[1:]:
max_ending_here = max(num, max_ending_here + num)
max_so_far = max(max_so_far, max_ending_here)
return max_so_far | simplelr_Evol | [
{
"content": "Question:\nDesign a function that takes a list of integers and returns the maximum sum of any contiguous subarray of the array. This problem is commonly referred to as the \"Maximum Subarray Problem\" or \"Kadane's Algorithm\".\n\ninput_list = [-2, 1, -3, 4, -1, 2, 1, -5, 4]\nAnswer:\nLet's think ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2625,
"level": 1,
"question": "Design a function that takes a list of integers and returns the maximum sum of any contiguous subarray of the array. This problem is commonly referred to as the \"Maximum Subarray Problem\" or \"Kadane's Algorithm\".\n\ninput_list = [-2, 1, -3, 4, -1, ... |
def count_char_occurrences(text):
"""
Counts the number of occurrences of each unique character in a string.
Args:
text: The input string.
Returns:
A dictionary where keys are unique characters in the string and values are their counts.
"""
char_counts = {}
for char in text... | simplelr_Filter | [
{
"content": "Question:\n**Objective**:\n\n* To write a Python function that takes a string as input and returns the number of occurrences of each unique character in the string.\n\n**Input**:\n\nA string\n\n**Output**:\n\nA dictionary where the keys are the unique characters in the string and the values are th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2626,
"level": 1,
"question": "**Objective**:\n\n* To write a Python function that takes a string as input and returns the number of occurrences of each unique character in the string.\n\n**Input**:\n\nA string\n\n**Output**:\n\nA dictionary where the keys are the unique characters ... |
def find_difference(lst):
if not lst:
return 0
return max(lst) - min(lst) | simplelr_Evol | [
{
"content": "Question:\nWrite a function that takes a list of integers and returns the difference between the largest and smallest numbers in the list. If the list is empty, return zero.\n\n```python\ndef find_difference(lst):\n # Your code here\n\n# Example Usage:\n# Input: [10, 2, 5, 78, 34]\n# Output: 76... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2627,
"level": 1,
"question": "Write a function that takes a list of integers and returns the difference between the largest and smallest numbers in the list. If the list is empty, return zero.\n\n```python\ndef find_difference(lst):\n # Your code here\n\n# Example Usage:\n# Inpu... |
def rearrange_string(s):
count_a = s.count('a')
count_b = len(s) - count_a
n = len(s)
if n % 2 != 0 or count_a != count_b:
return ""
half = n // 2
return 'a' * half + 'b' * half | simplelr_Leetcode | [
{
"content": "Question:\nYou are given a string `s` of even length consisting only of characters 'a' and 'b'. You need to rearrange the characters and split the string into two equal parts such that the number of 'a's in the first half is equal to the number of 'b's in the second half. Return the string after r... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2628,
"level": 1,
"question": "You are given a string `s` of even length consisting only of characters 'a' and 'b'. You need to rearrange the characters and split the string into two equal parts such that the number of 'a's in the first half is equal to the number of 'b's in the sec... |
def max_profit(prices):
if len(prices) < 2:
return 0
min_price = prices[0]
max_profit = 0
for price in prices[1:]:
if price < min_price:
min_price = price
else:
current_profit = price - min_price
if current_profit > max_profit:
... | simplelr_Evol | [
{
"content": "Question:\nImplement a function in Python that takes a list of integers representing daily stock prices and returns the maximum possible profit from a single buy-sell transaction. You may assume that you cannot buy and sell on the same day and that buying must occur before selling. The function sh... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2629,
"level": 1,
"question": "Implement a function in Python that takes a list of integers representing daily stock prices and returns the maximum possible profit from a single buy-sell transaction. You may assume that you cannot buy and sell on the same day and that buying must oc... |
import os
import json
def create_folders(data, base_path):
current_folder = os.path.join(base_path, data['name'])
os.makedirs(current_folder, exist_ok=True)
for child in data.get('children', []):
create_folders(child, current_folder)
# Example usage
if __name__ == "__main__":
# Load the JSON p... | simplelr_Filter | [
{
"content": "Question:\nI have a JSON payload that I need to create recursive folders for. Here's an example payload:\n\n```json\n{\n \"name\": \"My Folder\",\n \"children\": [\n {\n \"name\": \"Subfolder 1\",\n \"children\": [\n {\n \"name\": \"Subfolder 1.1\",\n \"chil... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2630,
"level": 1,
"question": "I have a JSON payload that I need to create recursive folders for. Here's an example payload:\n\n```json\n{\n \"name\": \"My Folder\",\n \"children\": [\n {\n \"name\": \"Subfolder 1\",\n \"children\": [\n {\n \"name\": \... |
from typing import List
def sparse_matrix_multiply(A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
# Check if the matrices can be multiplied
if not A or not B or len(A[0]) != len(B):
return []
rows_A = len(A)
cols_A = len(A[0])
cols_B = len(B[0])
# Preprocess matri... | simplelr_Data_Structure | [
{
"content": "Question:\n### Sparse Matrix Multiplication\n\n#### Problem Statement\nYou are given two sparse matrices A and B in the form of lists of lists (2D arrays). Implement a function `sparse_matrix_multiply` which multiplies matrix A with matrix B and returns the resultant matrix. Since the matrices are... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2631,
"level": 1,
"question": "### Sparse Matrix Multiplication\n\n#### Problem Statement\nYou are given two sparse matrices A and B in the form of lists of lists (2D arrays). Implement a function `sparse_matrix_multiply` which multiplies matrix A with matrix B and returns the resul... |
from collections import defaultdict
def min_window_substring(s, t):
if not t or not s:
return ""
required = defaultdict(int)
for char in t:
required[char] += 1
required_length = len(required)
window_counts = defaultdict(int)
have = 0
min_length = float('inf')
m... | simplelr_Filter | [
{
"content": "Question:\n### Minimum Window Substring\nGiven two strings `s` and `t` of lengths `m` and `n` respectively, return the minimum window in `s` which will contain all the characters in `t`. If there is no such window, return the empty string.\n\nExample 1:\n```\nInput: s = \"ADOBECODEBANC\", t = \"AB... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2632,
"level": 1,
"question": "### Minimum Window Substring\nGiven two strings `s` and `t` of lengths `m` and `n` respectively, return the minimum window in `s` which will contain all the characters in `t`. If there is no such window, return the empty string.\n\nExample 1:\n```\nInp... |
from typing import List
def product_except_self(nums: List[int]) -> List[int]:
n = len(nums)
result = [1] * n
# Left to right pass
left_product = 1
for i in range(n):
result[i] *= left_product
left_product *= nums[i]
# Right to left pass
right_product = 1
for i... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are tasked with implementing a function that takes a list of integers and returns another list where each integer is replaced by the product of all other integers in the original list except the one at that index. This is commonly known as the \"product of a... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2633,
"level": 1,
"question": "### Problem Statement\n\nYou are tasked with implementing a function that takes a list of integers and returns another list where each integer is replaced by the product of all other integers in the original list except the one at that index. This is c... |
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 [-1, -1] | simplelr_Evol | [
{
"content": "Question:\nDesign a function that takes an array of integers and a target sum as inputs. The function should find two distinct numbers in the array that add up to the target sum and return their indices. If no such pair exists, the function should return [-1, -1]. Write the function efficiently to... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2634,
"level": 1,
"question": "Design a function that takes an array of integers and a target sum as inputs. The function should find two distinct numbers in the array that add up to the target sum and return their indices. If no such pair exists, the function should return [-1, -1]... |
from typing import List, Dict, Any
import itertools
def process_data(data: List[Dict[str, Any]], key_attr: str, filter_attr: str, filter_value: Any, group_attr: str, agg_attr: str) -> List[Dict[str, Any]]:
# Sort the data based on the key_attr
sorted_data = sorted(data, key=lambda x: x[key_attr])
# Fi... | simplelr_Docs | [
{
"content": "Question:\n**Complex Data Processing with itertools**\n\nYou are provided with a dataset represented as a list of dictionaries, where each dictionary represents an item with various attributes. You need to process this dataset to generate a summary report based on specified criteria. The operation... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2635,
"level": 1,
"question": "**Complex Data Processing with itertools**\n\nYou are provided with a dataset represented as a list of dictionaries, where each dictionary represents an item with various attributes. You need to process this dataset to generate a summary report based o... |
def find_max_product_subarray(nums):
if not nums:
return 0
curr_max = nums[0]
curr_min = nums[0]
result = curr_max
for num in nums[1:]:
temp_max = curr_max
temp_min = curr_min
possible_max = max(num, num * temp_max, num * temp_min)
possible_min = min(num, num ... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function `find_max_product_subarray` that finds the maximum product of any contiguous subarray within a given array of integers. The function should take a list of integers as input and return the maximum product as an integer. Assume the input list has at least one integ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2636,
"level": 1,
"question": "Write a Python function `find_max_product_subarray` that finds the maximum product of any contiguous subarray within a given array of integers. The function should take a list of integers as input and return the maximum product as an integer. Assume th... |
from typing import List, Union
def fizz_buzz(N: int) -> List[Union[int, str]]:
if not isinstance(N, int) or N < 1:
raise ValueError("N must be a positive integer.")
result = []
for i in range(1, N + 1):
if i % 15 == 0:
result.append("FizzBuzz")
elif i % 3 == 0:
... | simplelr_Data_Structure | [
{
"content": "Question:\n### FizzBuzz Assessment\n\n#### Objective\nWrite a function to generate a list of strings and/or integers based on the classic FizzBuzz algorithm. Your implementation must return the correct results for any valid input, handle edge cases, and avoid excess resource utilization. Ensure yo... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2637,
"level": 1,
"question": "### FizzBuzz Assessment\n\n#### Objective\nWrite a function to generate a list of strings and/or integers based on the classic FizzBuzz algorithm. Your implementation must return the correct results for any valid input, handle edge cases, and avoid exc... |
def is_palindrome(s: str) -> bool:
# Filter non-alphanumeric characters and convert to lowercase
filtered = ''.join([c.lower() for c in s if c.isalnum()])
# Check if the filtered string is a palindrome
return filtered == filtered[::-1] | simplelr_Leetcode | [
{
"content": "Question:\nGiven a `string`, write a function to determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. A palindrome is a word, phrase, or sequence that reads the same backward as forward (ignoring spaces, punctuation, and capitalization). Return `true` if th... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2638,
"level": 1,
"question": "Given a `string`, write a function to determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. A palindrome is a word, phrase, or sequence that reads the same backward as forward (ignoring spaces, punctuation, and c... |
def reverse_string(s):
return s[::-1] | simplelr_Evol | [
{
"content": "Question:\nWrite a function that takes a string as input and returns the string reversed. For example, if the input is \"hello\", the function should return \"olleh\".\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2639,
"level": 1,
"question": "Write a function that takes a string as input and returns the string reversed. For example, if the input is \"hello\", the function should return \"olleh\".",
"split": "train"
} |
def binary_search(nums, target):
low = 0
high = len(nums) - 1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
return True
elif nums[mid] < target:
low = mid + 1
else:
high = mid - 1
return False | simplelr_Leetcode | [
{
"content": "Question:\nYou are given an integer array `nums` sorted in non-decreasing order. Determine if an integer `target` exists in the array by implementing a binary search algorithm. Return `true` if `target` is found in the array, and `false` otherwise.\n\nNote: Your solution should have a time complex... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2640,
"level": 1,
"question": "You are given an integer array `nums` sorted in non-decreasing order. Determine if an integer `target` exists in the array by implementing a binary search algorithm. Return `true` if `target` is found in the array, and `false` otherwise.\n\nNote: Your ... |
def remove_duplicates(input_list):
seen = set()
unique_list = []
for item in input_list:
if item not in seen:
seen.add(item)
unique_list.append(item)
return unique_list | simplelr_Filter | [
{
"content": "Question:\nGiven a list of strings, write a Python function to remove duplicates and return a list of unique strings while preserving the original order of their first occurrence. For example, if the input list is `[\"apple\", \"banana\", \"apple\", \"orange\", \"banana\", \"grape\"]`, the functio... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2641,
"level": 1,
"question": "Given a list of strings, write a Python function to remove duplicates and return a list of unique strings while preserving the original order of their first occurrence. For example, if the input list is `[\"apple\", \"banana\", \"apple\", \"orange\", \... |
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
def visualize_tips_data(df: pd.DataFrame) -> None:
"""
Function to visualize tips data using seaborn.
Parameters:
df (pd.DataFrame): DataFrame containing transaction data with columns 'day', 'total_bill', 'tip... | simplelr_Docs | [
{
"content": "Question:\nYou are provided with a dataset containing transactions from a retail store. Each transaction records the `day`, `total_bill`, `tip`, `time` (Lunch/Dinner), and whether the customer is a `smoker`. Using the seaborn library, visualize the data to extract meaningful patterns related to ti... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2642,
"level": 1,
"question": "You are provided with a dataset containing transactions from a retail store. Each transaction records the `day`, `total_bill`, `tip`, `time` (Lunch/Dinner), and whether the customer is a `smoker`. Using the seaborn library, visualize the data to extrac... |
def longest_substring_two_distinct(s):
if not s:
return ""
char_count = {}
left = 0
max_len = 0
start = 0
end = 0
for right in range(len(s)):
current_char = s[right]
char_count[current_char] = char_count.get(current_char, 0) + 1
# Shrink the... | simplelr_Filter | [
{
"content": "Question:\nGiven a string, find the longest substring that contains only two distinct characters. For example, given a string \"abcba\", the longest substring would be \"bcb\". \n\nCan you write a code that finds this substring?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2643,
"level": 1,
"question": "Given a string, find the longest substring that contains only two distinct characters. For example, given a string \"abcba\", the longest substring would be \"bcb\". \n\nCan you write a code that finds this substring?",
"split": "train"
} |
def uniqueElements(arr):
seen = set()
result = []
for num in arr:
if num not in seen:
seen.add(num)
result.append(num)
return result
| simplelr_Taco | [
{
"content": "Question:\n## Task\n\nCreate a function `uniqueElements`. This function accepts an array of numbers and returns a new array with all duplicate elements removed. The returned array should maintain the order of first appearances of each element.\n\n### Instructions:\n1. The function takes one parame... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2644,
"level": 1,
"question": "## Task\n\nCreate a function `uniqueElements`. This function accepts an array of numbers and returns a new array with all duplicate elements removed. The returned array should maintain the order of first appearances of each element.\n\n### Instructions... |
def enhanced_gnome_sort(arr: list[int]) -> tuple[list[int], int]:
arr_copy = arr.copy()
swap_count = 0
pos = 0
n = len(arr_copy)
while pos < n:
if pos == 0 or arr_copy[pos] >= arr_copy[pos - 1]:
pos += 1
else:
# Swap the elements
arr_copy[pos], arr... | simplelr_Data_Structure | [
{
"content": "Question:\n### Gnome Sort Variation Challenge\n\nGnome sort is an interesting, yet simple-to-understand sorting algorithm. Your task is to implement an enhanced version of Gnome Sort that not only sorts the list but also counts the total number of swaps made during the sorting process.\n\n#### Fun... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2645,
"level": 1,
"question": "### Gnome Sort Variation Challenge\n\nGnome sort is an interesting, yet simple-to-understand sorting algorithm. Your task is to implement an enhanced version of Gnome Sort that not only sorts the list but also counts the total number of swaps made duri... |
from collections import deque
def pathExists(grid, start, end):
if not grid:
return False
m = len(grid)
n = len(grid[0]) if m > 0 else 0
start_row, start_col = start
end_row, end_col = end
if start_row == end_row and start_col == end_col:
return True
visited = [[False for _ ... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Context\nIn graph theory, it's often necessary to determine whether a specific path exists from one node to another. Consider a grid where each cell contains a numeric value, and you can only move to adjacent cells (up, down, left, right). However, you can only move to a cel... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2646,
"level": 1,
"question": "### Problem Context\nIn graph theory, it's often necessary to determine whether a specific path exists from one node to another. Consider a grid where each cell contains a numeric value, and you can only move to adjacent cells (up, down, left, right). ... |
def first_missing_positive(nums):
if not nums:
return 1
n = len(nums)
present = [False] * (n + 2) # To cover up to n+1
for num in nums:
if 1 <= num <= n:
present[num] = True
for i in range(1, n + 2):
if not present[i]:
return i
return n + 1 # Thi... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find the first missing positive integer in an array of integers. The array may contain duplicates and negative numbers, and zeros. The function should have 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": 2647,
"level": 1,
"question": "Write a function to find the first missing positive integer in an array of integers. The array may contain duplicates and negative numbers, and zeros. The function should have a time complexity of O(n).",
"split": "train"
} |
from collections import Counter
from typing import List
def can_spell_word(word: str, characters: List[str]) -> bool:
if len(word) > len(characters):
return False
word_counts = Counter(word)
char_counts = Counter(characters)
for char, count in word_counts.items():
if char not in char_co... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nYou are given a string word. Your task is to check if the word can be spelled out using characters from a given list of allowable characters. Each character in the given list can only be used once.\n\n### Function Signature\n\n```python\ndef can_spell_word(word:... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2648,
"level": 1,
"question": "### Problem Statement\n\nYou are given a string word. Your task is to check if the word can be spelled out using characters from a given list of allowable characters. Each character in the given list can only be used once.\n\n### Function Signature\n\n... |
from typing import List
def pigeonhole_sort(arr: List[int]) -> List[int]:
if not arr:
return []
min_val = min(arr)
max_val = max(arr)
if min_val == max_val:
return arr
num_holes = max_val - min_val + 1
pigeonhole = [[] for _ in range(num_holes)]
for x in ... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are given an array of integers, and you need to sort this array using the Pigeonhole Sort algorithm. The function should closely follow the principles of the Pigeonhole Sort, ensuring efficient sorting for appropriate arrays. \n\n### Function Signature\n\n```python\ndef pigeonhole_s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2649,
"level": 1,
"question": "You are given an array of integers, and you need to sort this array using the Pigeonhole Sort algorithm. The function should closely follow the principles of the Pigeonhole Sort, ensuring efficient sorting for appropriate arrays. \n\n### Function Signa... |
def longest_substring_with_k_distinct(s: str, k: int) -> str:
if not s:
return ""
char_count = {}
start = 0
max_len = 0
max_str = ""
for end in range(len(s)):
# Add the current character to the count
char_count[s[end]] = char_count.get(s[end], 0) + 1
... | simplelr_Filter | [
{
"content": "Question:\nGiven a string `s`, find the longest substring that contains no more than `k` distinct characters. The output string should be the longest substring with no more than `k` distinct characters.\n\nHere is the example:\n```\nInput: s = \"eceba\", k = 2\nOutput: \"ece\"\n```\nHere is the wr... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2650,
"level": 1,
"question": "Given a string `s`, find the longest substring that contains no more than `k` distinct characters. The output string should be the longest substring with no more than `k` distinct characters.\n\nHere is the example:\n```\nInput: s = \"eceba\", k = 2\nO... |
def length_of_lis(nums):
if not nums:
return 0
dp = [1] * len(nums)
for i in range(1, len(nums)):
for j in range(i):
if nums[j] < nums[i]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp) | simplelr_Filter | [
{
"content": "Question:\n> **Problem:** Given an array of integers, find the length of the longest increasing sub-sequence.\n>\n> **Example:**\n>\n> Input: [1, 3, 2, 4, 5]\n>\n> Output: 4\n\n**Explanation:** The longest increasing subsequence is [1, 2, 4, 5], which has length 4.\n\nCan you provide a Python solu... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2651,
"level": 1,
"question": "> **Problem:** Given an array of integers, find the length of the longest increasing sub-sequence.\n>\n> **Example:**\n>\n> Input: [1, 3, 2, 4, 5]\n>\n> Output: 4\n\n**Explanation:** The longest increasing subsequence is [1, 2, 4, 5], which has length ... |
def calculate_total_cost(cart):
total = 0
for item in cart:
total += item[1]
return total
# Example usage:
if __name__ == "__main__":
cart = [
("apple", 1.99),
("banana", 0.50),
("orange", 1.00)
]
print("Total cost:", calculate_total(cart)) | simplelr_Filter | [
{
"content": "Question:\nCreate a Python program that calculates the total cost of a shopping cart. The program should take as input a list of tuples, each containing the name of the item and its price. The program should output the total cost of all items in the cart.\nAnswer:\nLet's think step by step.\n",
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2652,
"level": 1,
"question": "Create a Python program that calculates the total cost of a shopping cart. The program should take as input a list of tuples, each containing the name of the item and its price. The program should output the total cost of all items in the cart.",
"sp... |
import heapq
from typing import List
def merge_sorted_arrays(arrays: List[List[int]]) -> List[int]:
if not arrays:
return []
heap = []
for i, arr in enumerate(arrays):
if arr:
heapq.heappush(heap, (arr[0], i, 0))
result = []
while heap:
val, array_idx, ... | simplelr_Package | [
{
"content": "Question:\nYou are required to implement a Python function `merge_sorted_arrays` that merges multiple sorted arrays into a single sorted array. The function will:\n\n1. Take a single parameter: a list of lists `arrays`. Each sub-list contains integers sorted in ascending order.\n2. Merge all these... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2653,
"level": 1,
"question": "You are required to implement a Python function `merge_sorted_arrays` that merges multiple sorted arrays into a single sorted array. The function will:\n\n1. Take a single parameter: a list of lists `arrays`. Each sub-list contains integers sorted in a... |
def is_palindrome(s):
left = 0
right = len(s) - 1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
| simplelr_Taco | [
{
"content": "Question:\nGiven a string `s` which consists of characters `\"0\"` and `\"1\"` only, determine if the string is a palindrome without using extra space for another string.\n\n## Examples\n\n```\n\"101\" ==> true // \"101\" is the same forwards and backwards\n\"1001\" ==> true // \"1001\" is the sa... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2654,
"level": 1,
"question": "Given a string `s` which consists of characters `\"0\"` and `\"1\"` only, determine if the string is a palindrome without using extra space for another string.\n\n## Examples\n\n```\n\"101\" ==> true // \"101\" is the same forwards and backwards\n\"10... |
def maximum_of_three(a, b, c):
if a >= b and a >= c:
return a
elif b >= a and b >= c:
return b
else:
return c | simplelr_Filter | [
{
"content": "Question:\nCan you provide a Python code snippet to calculate the maximum of three numbers using a custom function?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2655,
"level": 1,
"question": "Can you provide a Python code snippet to calculate the maximum of three numbers using a custom function?",
"split": "train"
} |
import pandas as pd
def fill_missing_with_mean(dataframe, column_name):
# Create a copy of the dataframe to avoid modifying the original
df = dataframe.copy()
# Calculate the mean of the specified column
mean_value = df[column_name].mean()
# Fill missing values in the column with the calculated mea... | simplelr_Package | [
{
"content": "Question:\nWrite a function that takes a DataFrame and column name as input. The function should fill missing values in the specified column with the mean of that column.\n\nThe function should output:\n pandas.DataFrame: DataFrame with missing values filled in the specified column.\n\nYou shou... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2656,
"level": 1,
"question": "Write a function that takes a DataFrame and column name as input. The function should fill missing values in the specified column with the mean of that column.\n\nThe function should output:\n pandas.DataFrame: DataFrame with missing values filled i... |
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_Evol | [
{
"content": "Question:\nWrite a function that takes an array of integers and a target value as input and returns the indices of the two numbers that add up to the target value. The function should assume that each input would have exactly one solution and may not reuse the same element twice. Ensure the soluti... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2657,
"level": 1,
"question": "Write a function that takes an array of integers and a target value as input and returns the indices of the two numbers that add up to the target value. The function should assume that each input would have exactly one solution and may not reuse the sa... |
def intersecting_sequences(l1, l2):
return set(l1) & set(l2)
l1 = [1, 2, 3, 4, 5]
l2 = [4, 5, 6, 7, 8]
print(intersecting_sequences(l1, l2)) | simplelr_Filter | [
{
"content": "Question:\ndef intersecting_sequences(l1, l2):\n return set(l1) & set(l2)\n\nl1 = [1, 2, 3, 4, 5]\nl2 = [4, 5, 6, 7, 8]\nprint(intersecting_sequences(l1, l2))\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2658,
"level": 1,
"question": "def intersecting_sequences(l1, l2):\n return set(l1) & set(l2)\n\nl1 = [1, 2, 3, 4, 5]\nl2 = [4, 5, 6, 7, 8]\nprint(intersecting_sequences(l1, l2))",
"split": "train"
} |
def max_diff_of_zeros(binary_string):
if not binary_string:
return 0
runs = []
current_char = binary_string[0]
count = 1
for char in binary_string[1:]:
if char == current_char:
count += 1
else:
runs.append((current_char, count))
current_ch... | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function to find the maximum difference of zeros in a binary string. The function should return the length of the longest sequence of consecutive zeros that are surrounded by ones.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2659,
"level": 1,
"question": "Write a Python function to find the maximum difference of zeros in a binary string. The function should return the length of the longest sequence of consecutive zeros that are surrounded by ones.",
"split": "train"
} |
def string_to_list(s):
return list(s)
# Example usage:
print(string_to_list("hello")) # Output: ['h', 'e', 'l', 'l', 'o'] | simplelr_Filter | [
{
"content": "Question:\nHow can I convert a string to a list in Python, where each character of the string becomes an element in the list? For example, if I have the string \"hello\", I want to convert it to a list like ['h', 'e', 'l', 'l', 'o']. Can you provide a Python function for this?\nAnswer:\nLet's thin... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2660,
"level": 1,
"question": "How can I convert a string to a list in Python, where each character of the string becomes an element in the list? For example, if I have the string \"hello\", I want to convert it to a list like ['h', 'e', 'l', 'l', 'o']. Can you provide a Python func... |
def sort_dicts(dict_list):
return sorted(dict_list, key=lambda x: (-x['value'], x['id'])) | simplelr_Filter | [
{
"content": "Question:\nWrite a Python function that takes a list of dictionaries, each containing an 'id' and a 'value', and returns a new list of dictionaries sorted by the 'value' in descending order. If two items have the same 'value', they should be further sorted by their 'id' in ascending order.\nAnswer... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2661,
"level": 1,
"question": "Write a Python function that takes a list of dictionaries, each containing an 'id' and a 'value', and returns a new list of dictionaries sorted by the 'value' in descending order. If two items have the same 'value', they should be further sorted by the... |
from collections import deque
def shortest_path(maze, start, end):
m, n = len(maze), len(maze[0])
if start == end:
return 0
if maze[start[0]][start[1]] == 1 or maze[end[0]][end[1]] == 1:
return -1
queue = deque()
queue.append((start, 0))
visited = set()
visited.add((sta... | simplelr_Filter | [
{
"content": "Question:\nHere's a problem: You are building a robot that needs to navigate a maze. The maze is represented by a 2D grid where:\n\n* 0 represents an empty cell\n* 1 represents a wall\n\nThe robot starts at the top-left corner (0, 0) and needs to reach the bottom-right corner (m-1, n-1)\n\nYou can... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2662,
"level": 1,
"question": "Here's a problem: You are building a robot that needs to navigate a maze. The maze is represented by a 2D grid where:\n\n* 0 represents an empty cell\n* 1 represents a wall\n\nThe robot starts at the top-left corner (0, 0) and needs to reach the bottom... |
def count_character_occurrences(s, char):
count = 0
for c in s:
if c == char:
count += 1
return count | simplelr_Filter | [
{
"content": "Question:\nImplement a function that takes a string and a character and returns the number of times the character appears in the string.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2663,
"level": 1,
"question": "Implement a function that takes a string and a character and returns the number of times the character appears in the string.",
"split": "train"
} |
from typing import List
from collections import defaultdict
def enhanced_pigeonhole_sort(arr: List[int]) -> List[int]:
if not arr:
return []
n = len(arr)
min_val = min(arr)
max_val = max(arr)
range_size = max_val - min_val + 1
threshold = 10**6 # Threshold for switching between li... | simplelr_Data_Structure | [
{
"content": "Question:\n**Title**: Implementing Enhanced Pigeonhole Sort\n\n**Problem Description**:\nYou have been provided with an implementation of the Pigeonhole Sort algorithm. However, certain edge cases and performance issues have been noted in the current implementation. Your task is to improve and opt... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2664,
"level": 1,
"question": "**Title**: Implementing Enhanced Pigeonhole Sort\n\n**Problem Description**:\nYou have been provided with an implementation of the Pigeonhole Sort algorithm. However, certain edge cases and performance issues have been noted in the current implementati... |
def remove_duplicates(arr):
seen = set()
result = []
for num in arr:
if num not in seen:
seen.add(num)
result.append(num)
return result | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to remove duplicates from an array. The function should take an array of integers as input and return a new array with all duplicates removed. The order of the elements in the output array should be the same as their first occurrence in the input array.\nAnswer:\nLet's ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2665,
"level": 1,
"question": "Write a function to remove duplicates from an array. The function should take an array of integers as input and return a new array with all duplicates removed. The order of the elements in the output array should be the same as their first occurrence i... |
def sum_numbers(a, b):
return a + b
# Example usage:
print(sum_numbers(5, 3)) # Outputs: 8 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes two numbers as arguments and returns their sum. Can you provide an example in Python?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2666,
"level": 1,
"question": "Create a function that takes two numbers as arguments and returns their sum. Can you provide an example in Python?",
"split": "train"
} |
from typing import List, Tuple, Union
def advanced_fizzbuzz(n: int, rules: List[Tuple[int, str]]) -> List[Union[int, str]]:
if n < 1:
return []
valid_rules = [(d, s) for (d, s) in rules if d > 0 and s != ""]
result = []
for i in range(1, n + 1):
s = ""
for d, word in v... | simplelr_Data_Structure | [
{
"content": "Question:\n### FizzBuzz Alternative Challenge\n\nYou are tasked to transform the classic FizzBuzz problem into a more extensible and generalized version. \n\n**Scenario**:\nIn a kingdom, the Royal Programmer is assigned to develop an advanced version of the FizzBuzz using more diverse and extended... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2667,
"level": 1,
"question": "### FizzBuzz Alternative Challenge\n\nYou are tasked to transform the classic FizzBuzz problem into a more extensible and generalized version. \n\n**Scenario**:\nIn a kingdom, the Royal Programmer is assigned to develop an advanced version of the FizzB... |
def submatrixSum(m, n, mat, k, queries):
# Initialize the prefix sum matrix with an extra row and column of zeros
prefix = [[0] * (n + 1) for _ in range(m + 1)]
# Populate the prefix sum matrix
for i in range(1, m + 1):
for j in range(1, n + 1):
prefix[i][j] = mat[i-1][j-1] + pr... | simplelr_Taco | [
{
"content": "Question:\nYou are given a matrix `mat` of size `m x n` and an array `queries` of length `k` containing subarrays of size 4. Each subarray in `queries` is in the form of `[x1, y1, x2, y2]` representing the top-left and bottom-right corners of a submatrix. Your task is to compute the sum of the ele... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2668,
"level": 1,
"question": "You are given a matrix `mat` of size `m x n` and an array `queries` of length `k` containing subarrays of size 4. Each subarray in `queries` is in the form of `[x1, y1, x2, y2]` representing the top-left and bottom-right corners of a submatrix. Your ta... |
def min_insertions_to_form_palindrome(s):
n = len(s)
if n == 0:
return 0
dp = [[0] * n for _ in range(n)]
# All substrings of length 1
for i in range(n):
dp[i][i] = 1
# Check for substrings of length 2
for i in range(n - 1):
if s[i] == s[i + 1]:
... | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find the minimum number of insertions to form a palindrome.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2669,
"level": 1,
"question": "Write a python function to find the minimum number of insertions to form a palindrome.",
"split": "train"
} |
from collections import Counter
def top_k_frequent_words(words: list[str], k: int) -> list[str]:
count = Counter(words)
items = list(count.items())
# Sort by descending frequency, then lexicographically for ties
sorted_items = sorted(items, key=lambda x: (-x[1], x[0]))
top_words = [item[0] for item... | simplelr_Algorithm | [
{
"content": "Question:\n### Problem Statement\n\nWrite a function that takes a list of words and an integer k, and returns the k most frequent words in the list. If there is a tie for the k-th position, select words that are alphabetically smaller.\n\n**Input Format**:\n- A list of strings `words` where each s... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2670,
"level": 1,
"question": "### Problem Statement\n\nWrite a function that takes a list of words and an integer k, and returns the k most frequent words in the list. If there is a tie for the k-th position, select words that are alphabetically smaller.\n\n**Input Format**:\n- A l... |
def reverse_array(arr):
left = 0
right = len(arr) - 1
while left < right:
# Swap the elements
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
return arr
# Example usage:
arr = [1, 2, 3, 4, 5]
print(reverse_array(arr)) # Output: [5, 4, 3, 2, 1] | simplelr_Filter | [
{
"content": "Question:\nReverse the order of elements in an array without using any built-in functions or methods. The solution should have a time complexity of O(n) and should not use any additional data structures. The array should be modified in-place.\nAnswer:\nLet's think step by step.\n",
"role": "us... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2671,
"level": 1,
"question": "Reverse the order of elements in an array without using any built-in functions or methods. The solution should have a time complexity of O(n) and should not use any additional data structures. The array should be modified in-place.",
"split": "train"... |
def count_vowels(s):
return sum(1 for c in s if c.lower() in {'a', 'e', 'i', 'o', 'u'}) | simplelr_Filter | [
{
"content": "Question:\nThis is a coding task:\n\n**Task:** Implement a Python function that takes a string as an argument and returns the number of vowels (a, e, i, o, u) in that string.\n\n**Example:**\n```\ncount_vowels(\"This is a test string.\")\nAnswer:\nLet's think step by step.\n",
"role": "user"
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2672,
"level": 1,
"question": "This is a coding task:\n\n**Task:** Implement a Python function that takes a string as an argument and returns the number of vowels (a, e, i, o, u) in that string.\n\n**Example:**\n```\ncount_vowels(\"This is a test string.\")",
"split": "train"
} |
def find_target_index(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1 | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that takes an array of integers and an integer `target`. The function should return the index of the first occurrence of the `target` in the array. If the `target` is not found, the function should return -1.\nAnswer:\nLet's think step by step.\n",
"role": "user"
... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2673,
"level": 1,
"question": "Create a function that takes an array of integers and an integer `target`. The function should return the index of the first occurrence of the `target` in the array. If the `target` is not found, the function should return -1.",
"split": "train"
} |
def find_duplicates(lst):
counts = {}
for num in lst:
if num in counts:
counts[num] += 1
else:
counts[num] = 1
duplicates = [key for key, value in counts.items() if value > 1]
return duplicates | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to find duplicates in a list and return a list of duplicates.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2674,
"level": 1,
"question": "Write a function to find duplicates in a list and return a list of duplicates.",
"split": "train"
} |
def can_be_sorted_by_reversing_subarray(arr):
sorted_arr = sorted(arr)
if arr == sorted_arr:
return True
left = None
right = None
for i in range(len(arr)):
if arr[i] != sorted_arr[i]:
if left is None:
left = i
right = i
sub_a... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an array of integers `arr`, you are allowed to select a subarray (contiguous part of the array) and perform one operation: reverse the order of elements in that subarray. Only one such operation is allowed. Determine if the entire array can be sorted in non-decreasing order by usi... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2675,
"level": 1,
"question": "Given an array of integers `arr`, you are allowed to select a subarray (contiguous part of the array) and perform one operation: reverse the order of elements in that subarray. Only one such operation is allowed. Determine if the entire array can be so... |
from typing import List
def daily_temperatures(temperatures: List[int]) -> List[int]:
result = [0] * len(temperatures)
stack = []
for i in range(len(temperatures)):
while stack and temperatures[i] > temperatures[stack[-1]]:
popped = stack.pop()
result[popped] = i - popped
... | simplelr_Codeforces | [
{
"content": "Question:\nYou are given a list of integers representing the daily temperatures for a week. Write a program that processes this list and returns a new list such that, for each day in the input, the new list contains the number of days you would have to wait until a warmer temperature. If there is ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2676,
"level": 1,
"question": "You are given a list of integers representing the daily temperatures for a week. Write a program that processes this list and returns a new list such that, for each day in the input, the new list contains the number of days you would have to wait until... |
def find_substring(haystack: str, needle: str) -> int:
"""
Returns the index of the first occurrence of the substring needle in the string haystack.
If needle is not a substring of haystack, returns -1.
Args:
haystack (str): The string in which to search for the substring.
needle (str): The... | simplelr_Algorithm | [
{
"content": "Question:\n### **Implementing a Simple Text-Based Search Algorithm**\n\n**Scenario**:\nYou are tasked with developing a simple text-based search function to find the first occurrence of a substring (needle) in a longer string (haystack). This could be useful in various applications like text edito... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2677,
"level": 1,
"question": "### **Implementing a Simple Text-Based Search Algorithm**\n\n**Scenario**:\nYou are tasked with developing a simple text-based search function to find the first occurrence of a substring (needle) in a longer string (haystack). This could be useful in v... |
def find_single(arr):
res = 0
for num in arr:
res ^= num
return res
| simplelr_Taco | [
{
"content": "Question:\nGiven an integer array `arr` where every element appears exactly twice, except for one element which appears exactly once. Write a function to find and return the element that appears only once.\n\nConstraints:\n- The input array will always have an odd number of elements.\n- The array ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2678,
"level": 1,
"question": "Given an integer array `arr` where every element appears exactly twice, except for one element which appears exactly once. Write a function to find and return the element that appears only once.\n\nConstraints:\n- The input array will always have an od... |
def average(a, b):
return (a + b) / 2 | simplelr_Filter | [
{
"content": "Question:\nIn Python, how can I create a function to calculate the average of two numbers?\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2679,
"level": 1,
"question": "In Python, how can I create a function to calculate the average of two numbers?",
"split": "train"
} |
import random
def generate_random_number(start, end):
return random.randint(start, end) | simplelr_Prefill | [
{
"content": "Question:\nCreate a function that generates a random number in a given range using Python's random module. The function should take two parameters: `start` and `end`, inclusive. The function should return a random integer in the range [start, end].\nAnswer:\nLet's think step by step.\n",
"role... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2680,
"level": 1,
"question": "Create a function that generates a random number in a given range using Python's random module. The function should take two parameters: `start` and `end`, inclusive. The function should return a random integer in the range [start, end].",
"split": "... |
def largest_square_of_1s(matrix: list[list[int]]) -> int:
if not matrix or not matrix[0]:
return 0
m = len(matrix)
n = len(matrix[0])
dp = [[0] * n for _ in range(m)]
max_side = 0
for i in range(m):
for j in range(n):
if matrix[i][j] == 1:
if i == 0 or... | simplelr_Algorithm | [
{
"content": "Question:\n### Largest Square of 1s in a Binary Matrix\n\n#### Objective:\nImplement a function that finds the size of the largest square submatrix that contains only 1s within a given binary matrix.\n\n#### Context:\nDetermining the maximal square of 1s in a binary matrix is a common problem in i... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2681,
"level": 1,
"question": "### Largest Square of 1s in a Binary Matrix\n\n#### Objective:\nImplement a function that finds the size of the largest square submatrix that contains only 1s within a given binary matrix.\n\n#### Context:\nDetermining the maximal square of 1s in a bin... |
def follows_pattern(pattern: str, string: str) -> bool:
words = string.split()
if len(pattern) != len(words):
return False
pattern_to_word = {}
word_to_pattern = {}
for p, w in zip(pattern, words):
if p in pattern_to_word:
if pattern_to_word[p] != w:
ret... | simplelr_Data_Structure | [
{
"content": "Question:\n### Pattern Matching Challenge\n\nWrite a function called `follows_pattern` that checks if a given string follows a specified pattern.\n\n#### Function Signature\n```python\ndef follows_pattern(pattern: str, string: str) -> bool:\n pass\n```\n\n#### Input\n* `pattern`: A string made ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2682,
"level": 1,
"question": "### Pattern Matching Challenge\n\nWrite a function called `follows_pattern` that checks if a given string follows a specified pattern.\n\n#### Function Signature\n```python\ndef follows_pattern(pattern: str, string: str) -> bool:\n pass\n```\n\n####... |
from typing import List
def tictactoe_winner(board: List[List[str]]) -> str:
# Generate all possible winning lines
all_lines = []
# Rows
for i in range(3):
row = [(i, 0), (i, 1), (i, 2)]
all_lines.append(row)
# Columns
for j in range(3):
col = [(0, j), (1, j), (2, j)]
... | simplelr_Algorithm | [
{
"content": "Question:\n### Coding Question: Determine the Winner of a Tic-Tac-Toe Game\n\nWrite a function to determine the winner of a Tic-Tac-Toe game given a 3x3 board represented as a list of lists. Each cell is either `'X'`, `'O'`, or an empty string `''` representing an unfilled cell.\n\nYour task is to... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2683,
"level": 1,
"question": "### Coding Question: Determine the Winner of a Tic-Tac-Toe Game\n\nWrite a function to determine the winner of a Tic-Tac-Toe game given a 3x3 board represented as a list of lists. Each cell is either `'X'`, `'O'`, or an empty string `''` representing a... |
def order_string(s: str) -> str:
if len(s) % 2 == 0:
sorted_s = sorted(s, reverse=True)
else:
sorted_s = sorted(s)
return ''.join(sorted_s)
| simplelr_Taco | [
{
"content": "Question:\nGiven a string s, return a new string where the characters are in ascending order if the length of the string is odd and in descending order if the length of the string is even.\n\nFor example, in the case of `\"coding\"`, the length is even so the output should be `\"onigdc\"`, and for... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2684,
"level": 1,
"question": "Given a string s, return a new string where the characters are in ascending order if the length of the string is odd and in descending order if the length of the string is even.\n\nFor example, in the case of `\"coding\"`, the length is even so the out... |
from collections import Counter
def k_most_frequent_ids(ids, k):
count = Counter(ids)
sorted_ids = sorted(count.items(), key=lambda x: (-x[1], x[0]))
result = [id for id, cnt in sorted_ids[:k]]
return result | simplelr_Code_Contests | [
{
"content": "Question:\nYou are given a long list of integers where each integer represents an ID of a person. The IDs may contain duplicates, and your task is to determine the k most frequent IDs in the list. If there are ties in the frequency, the IDs should be returned in ascending order.\n\nWrite a functio... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2685,
"level": 1,
"question": "You are given a long list of integers where each integer represents an ID of a person. The IDs may contain duplicates, and your task is to determine the k most frequent IDs in the list. If there are ties in the frequency, the IDs should be returned in ... |
def longest_contiguous_ones(nums):
max_count = 0
current_count = 0
for num in nums:
if num == 1:
current_count += 1
else:
if current_count > max_count:
max_count = current_count
current_count = 0
if current_count > max_count:
ma... | simplelr_Leetcode | [
{
"content": "Question:\nGiven an integer array `nums`, write a function that returns the length of the longest contiguous subarray containing only `1`s. If the array contains no `1`s, return `0`. For example, for the input array `nums = [1, 1, 0, 1, 1, 1]`, the result would be `3`, as the longest contiguous su... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2686,
"level": 1,
"question": "Given an integer array `nums`, write a function that returns the length of the longest contiguous subarray containing only `1`s. If the array contains no `1`s, return `0`. For example, for the input array `nums = [1, 1, 0, 1, 1, 1]`, the result would b... |
def length_of_longest_substring(s: str) -> int:
max_length = 0
left = 0
last_seen = {}
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_length = right ... | simplelr_Code_Contests | [
{
"content": "Question:\nWrite a function that finds the length of the longest substring without repeating characters in a given string.\n\nFunction Signature:\n```python\ndef length_of_longest_substring(s: str) -> int:\n```\n\nInput\n\nThe input is a single string `s` consisting of English letters (both upperc... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2687,
"level": 1,
"question": "Write a function that finds the length of the longest substring without repeating characters in a given string.\n\nFunction Signature:\n```python\ndef length_of_longest_substring(s: str) -> int:\n```\n\nInput\n\nThe input is a single string `s` consist... |
from typing import List
def counting_sort(arr: List[int]) -> List[int]:
if not arr:
return []
min_val = min(arr)
offset = max(0, -min_val)
max_num = max(arr)
max_shifted = max_num + offset
# Initialize frequency array
frequency = [0] * (max_shifted + 1)
for num in... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are given a list of integers which may contain both positive and negative numbers. Your task is to implement the Counting Sort algorithm that can handle negative integers and sort the list in non-decreasing order.\n\n#### Function Signature\n```python\ndef counting_sort(arr: List[in... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2688,
"level": 1,
"question": "You are given a list of integers which may contain both positive and negative numbers. Your task is to implement the Counting Sort algorithm that can handle negative integers and sort the list in non-decreasing order.\n\n#### Function Signature\n```pyt... |
from typing import List
def find_missing_number(arr: List[int]) -> int:
n = len(arr)
expected_sum = n * (n + 1) // 2
actual_sum = sum(arr)
return expected_sum - actual_sum | simplelr_Algorithm | [
{
"content": "Question:\n### Missing Number Identifier\n\n**Context:**\nYou are given an array that contains `n` distinct numbers taken from the range 0 to `n`. This means there are `n + 1` numbers in the range 0 to `n`, inclusive, but one number is missing from the array. Your task is to identify the missing n... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2689,
"level": 1,
"question": "### Missing Number Identifier\n\n**Context:**\nYou are given an array that contains `n` distinct numbers taken from the range 0 to `n`. This means there are `n + 1` numbers in the range 0 to `n`, inclusive, but one number is missing from the array. You... |
def binary_search(arr, x):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == x:
return mid
elif arr[mid] > x:
high = mid - 1
else:
low = mid + 1
return -1 | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to implement a divide and conquer approach to solve a problem efficiently. For this problem, let's say we want to find the index of an element x in a sorted array using the binary search algorithm.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2690,
"level": 1,
"question": "Write a python function to implement a divide and conquer approach to solve a problem efficiently. For this problem, let's say we want to find the index of an element x in a sorted array using the binary search algorithm.",
"split": "train"
} |
def filter_even_numbers(numbers):
"""
Filter out and return the even numbers from a provided list of integers.
:param numbers: List of integers to filter.
:type numbers: list of int
:return: List of even numbers in the original order.
:rtype: list of int
"""
even_numbers = []
for nu... | simplelr_Package | [
{
"content": "Question:\nIn this problem, you are tasked with writing a function `filter_even_numbers(numbers)` which will filter out and return only the even numbers from a provided list of integers. The function should maintain the order of the provided list in the output.\n\n### Function Definition\n\n```pyt... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2691,
"level": 1,
"question": "In this problem, you are tasked with writing a function `filter_even_numbers(numbers)` which will filter out and return only the even numbers from a provided list of integers. The function should maintain the order of the provided list in the output.\n... |
def find_pair_with_sum(nums, target):
seen = set()
for num in nums:
complement = target - num
if complement in seen:
return [complement, num]
seen.add(num)
return [] | simplelr_Prefill | [
{
"content": "Question:\nWrite a python function to find two numbers from a list of integers such that their sum equals a target value. If such numbers exist, return the pair of numbers. If no such pair exists, return an empty list. The function should have a time complexity of O(n).\nAnswer:\nLet's think step ... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2692,
"level": 1,
"question": "Write a python function to find two numbers from a list of integers such that their sum equals a target value. If such numbers exist, return the pair of numbers. If no such pair exists, return an empty list. The function should have a time complexity o... |
def efficient_binomial_coefficient(n, k):
k = min(k, n - k)
result = 1
for i in range(1, k + 1):
result = result * (n - i + 1) // i
return result | simplelr_Data_Structure | [
{
"content": "Question:\n**Binomial Coefficient with Constraints**\n\nYou are working on combinatorial problems and need to compute the binomial coefficient \\( C(n, k) \\). Given the constraints of time and space, you must implement an efficient algorithm.\n\n### Problem Description\nWrite a function `efficien... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2693,
"level": 1,
"question": "**Binomial Coefficient with Constraints**\n\nYou are working on combinatorial problems and need to compute the binomial coefficient \\( C(n, k) \\). Given the constraints of time and space, you must implement an efficient algorithm.\n\n### Problem Desc... |
def is_monotonic_string(s):
if len(s) <= 1:
return True
is_increasing = True
is_decreasing = True
for i in range(len(s) - 1):
if s[i] > s[i+1]:
is_increasing = False
elif s[i] < s[i+1]:
is_decreasing = False
if not is_increasing ... | simplelr_Prefill | [
{
"content": "Question:\nWrite a function to check if a given string is a monotonically increasing or decreasing string. A string is considered monotonically increasing if each character is less than or equal to the next character and monotonically decreasing if each character is greater than or equal to the ne... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2694,
"level": 1,
"question": "Write a function to check if a given string is a monotonically increasing or decreasing string. A string is considered monotonically increasing if each character is less than or equal to the next character and monotonically decreasing if each character... |
def rotateArray(arr, k):
n = len(arr)
if n == 0:
return []
effective_k = k % n
return arr[-effective_k:] + arr[:-effective_k] | simplelr_Apps | [
{
"content": "Question:\n### Problem Statement\n\nYou are given an array of integers and a non-negative integer `k`. Your task is to rotate the array to the right by `k` steps, where `k` is non-negative.\n\n### How to rotate?\n\n- The rotate operation moves each element `k` positions to the right.\n- For exampl... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2695,
"level": 1,
"question": "### Problem Statement\n\nYou are given an array of integers and a non-negative integer `k`. Your task is to rotate the array to the right by `k` steps, where `k` is non-negative.\n\n### How to rotate?\n\n- The rotate operation moves each element `k` po... |
def third_largest_unique(nums):
unique_nums = list(set(nums))
unique_nums.sort(reverse=True)
if len(unique_nums) >= 3:
return unique_nums[2]
else:
return None | simplelr_Filter | [
{
"content": "Question:\nQuery: Given a list of numbers, write a Python program to return the third largest unique element in the list.\nAnswer:\nLet's think step by step.\n",
"role": "user"
}
] | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2696,
"level": 1,
"question": "Query: Given a list of numbers, write a Python program to return the third largest unique element in the list.",
"split": "train"
} |
def calculate_isbn10(isbn: str) -> str:
if len(isbn) != 9:
raise ValueError("ISBN length must be exactly 9 digits.")
if not isbn.isdigit():
raise ValueError("ISBN should only contain numeric digits.")
sum_products = sum((i + 1) * int(c) for i, c in enumerate(isbn))
mod = sum_product... | simplelr_Algorithm | [
{
"content": "Question:\n### Objective:\nCreate a Python function to validate and calculate the ISBN-10 check digit, ensuring proper input and output handling.\n\n### Problem Statement:\nAn ISBN-10 (International Standard Book Number) is a 10-digit code used to uniquely identify a book. The check digit is the l... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2697,
"level": 1,
"question": "### Objective:\nCreate a Python function to validate and calculate the ISBN-10 check digit, ensuring proper input and output handling.\n\n### Problem Statement:\nAn ISBN-10 (International Standard Book Number) is a 10-digit code used to uniquely identi... |
from typing import List
def optimized_exchange_sort(arr: List[int]) -> List[int]:
arr_copy = arr.copy()
n = len(arr_copy)
if n <= 1:
return arr_copy
for i in range(n):
swapped = False
for j in range(n - 1):
if arr_copy[j] > arr_copy[j + 1]:
# Swa... | simplelr_Data_Structure | [
{
"content": "Question:\n### Question: Optimized Sorting with Early Termination Check\n\nYou are working on improving the performance of a sorting algorithm for small lists. Given the inefficiency of the Exchange Sort for larger datasets, it's important to introduce optimizations for scenarios where the array m... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2698,
"level": 1,
"question": "### Question: Optimized Sorting with Early Termination Check\n\nYou are working on improving the performance of a sorting algorithm for small lists. Given the inefficiency of the Exchange Sort for larger datasets, it's important to introduce optimizati... |
def decode_ways(encoded_message: str) -> int:
n = len(encoded_message)
if n == 0:
return 0
if encoded_message[0] == '0':
return 0
dp = [0] * (n + 1)
dp[0] = 1 # Base case: one way to decode empty string
for i in range(1, n + 1):
# Check single digit
if encod... | simplelr_Data_Structure | [
{
"content": "Question:\nYou are given an encoded message containing only digits and need to determine the total number of ways to decode it using the following mapping:\n- 'A' -> 1\n- 'B' -> 2\n- ...\n- 'Z' -> 26\n\nThe encoded message will contain at most 1000 characters.\n\nImplement a function `decode_ways(... | code | {
"ground_truth": "pass",
"style": "exec"
} | {
"answer": "pass",
"index": 2699,
"level": 1,
"question": "You are given an encoded message containing only digits and need to determine the total number of ways to decode it using the following mapping:\n- 'A' -> 1\n- 'B' -> 2\n- ...\n- 'Z' -> 26\n\nThe encoded message will contain at most 1000 characters.\n\... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.