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 sum_of_even_numbers(numbers): even_numbers = [num for num in numbers if num % 2 == 0] return sum(even_numbers)
simplelr_Filter
[ { "content": "Question:\nStep 1: Write a program in Python that takes a list of numbers as input and returns the sum of all the even numbers in the list.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4700, "level": 1, "question": "Step 1: Write a program in Python that takes a list of numbers as input and returns the sum of all the even numbers in the list.", "split": "train" }
def most_common_element(lst): if not lst: return None counts = {} for index, element in enumerate(lst): if element in counts: current_count, current_index = counts[element] counts[element] = (current_count + 1, current_index) else: counts[elem...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that determines the most common element in a list. If there are multiple elements with the same highest frequency, return the one that appears first in the list. If the list is empty, return `None`. Consider both uppercase and lowercase letters as distinct elemen...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4701, "level": 1, "question": "Write a Python function that determines the most common element in a list. If there are multiple elements with the same highest frequency, return the one that appears first in the list. If the list is empty, return `None`. Consider both uppercase and l...
def num_ways_to_paint_fence(n: int, k: int) -> int: if n == 0: return 0 if n == 1: return k if n == 2: return k + k * (k - 1) prev_same = k prev_diff = k * (k - 1) for i in range(3, n + 1): current_same = prev_diff current_diff = (prev_same + pre...
simplelr_Algorithm
[ { "content": "Question:\n## Coding Challenge: Paint Fence Algorithm\n\n### Objective:\nDevelop a function that calculates the number of distinct ways to paint a fence with `n` posts using `k` different colors such that no more than two adjacent fence posts have the same color.\n\n### Problem Description:\n* You...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4702, "level": 1, "question": "## Coding Challenge: Paint Fence Algorithm\n\n### Objective:\nDevelop a function that calculates the number of distinct ways to paint a fence with `n` posts using `k` different colors such that no more than two adjacent fence posts have the same color....
import pandas as pd import matplotlib.pyplot as plt def plot_histogram(csv_file, column_name): # Read the CSV file df = pd.read_csv(csv_file) # Check if the specified column exists if column_name not in df.columns: raise ValueError(f"The column '{column_name}' does not exist in the CSV fil...
simplelr_Filter
[ { "content": "Question:\nI have a Python script that is supposed to read a CSV file and plot a histogram for a specific column. However, I am not sure how to ensure that the histogram displays the frequency of values in that column. Can you provide a Python code snippet that reads a CSV file and plots a histogr...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4703, "level": 1, "question": "I have a Python script that is supposed to read a CSV file and plot a histogram for a specific column. However, I am not sure how to ensure that the histogram displays the frequency of values in that column. Can you provide a Python code snippet that r...
def transpose(matrix): if not matrix: raise ValueError("input matrix is invalid") for row in matrix: if not row: raise ValueError("input matrix is invalid") return [list(row) for row in zip(*matrix)]
simplelr_Algorithm
[ { "content": "Question:\n### Matrix Transpose\n\n#### Context\nIn linear algebra, the transpose of a matrix is an operator which flips a matrix over its diagonal. It switches the row and column indices of the matrix by producing another matrix denoted as \\(A^T\\). Transposing a matrix can be useful in numerous...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4704, "level": 1, "question": "### Matrix Transpose\n\n#### Context\nIn linear algebra, the transpose of a matrix is an operator which flips a matrix over its diagonal. It switches the row and column indices of the matrix by producing another matrix denoted as \\(A^T\\). Transposing...
import bisect def longest_increasing_subsequence(arr): tails = [] for num in arr: idx = bisect.bisect_left(tails, num) if idx == len(tails): tails.append(num) else: tails[idx] = num return len(tails) # Example usage: # print(longest_increasing_subsequence([1...
simplelr_Evol
[ { "content": "Question:\nFormulate an algorithm that utilizes the principles of Dynamic Programming to determine the longest increasing subsequence in a given array of integers, ensuring an efficient optimization of time complexity. Provide an implementation in a programming language of your choice.\nAnswer:\nL...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4705, "level": 1, "question": "Formulate an algorithm that utilizes the principles of Dynamic Programming to determine the longest increasing subsequence in a given array of integers, ensuring an efficient optimization of time complexity. Provide an implementation in a programming l...
def modify_number(num): if num % 2 == 0: return int(str(num)[::-1]) else: return num
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a number as input and uses slicing to reverse the number if it is even. If the number is odd, no change should be made. Return the modified number.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4706, "level": 1, "question": "Create a function that takes a number as input and uses slicing to reverse the number if it is even. If the number is odd, no change should be made. Return the modified number.", "split": "train" }
def count_min_flips_to_convert(a: int, b: int) -> int: xor = a ^ b return bin(xor).count('1')
simplelr_Data_Structure
[ { "content": "Question:\n### Context\nIn data transfer and error correction, determining bit differences between sequences is crucial for diagnosing and correcting errors. This problem will assess your ability to manipulate and analyze binary data representations effectively.\n\n### Task\nImplement a function `...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4707, "level": 1, "question": "### Context\nIn data transfer and error correction, determining bit differences between sequences is crucial for diagnosing and correcting errors. This problem will assess your ability to manipulate and analyze binary data representations effectively.\...
def secondSmallest(arr, N): if N < 2: return -1 first_min = min(arr) second_min = None for num in arr: if num > first_min: if second_min is None or num < second_min: second_min = num return second_min if second_min is not None else -1
simplelr_Taco
[ { "content": "Question:\nGiven an array of integers, determine the second smallest element in the array.\n\nExample:\nInput:\nN = 6\narr[] = {23, 45, 12, 34, 25, 12}\nOutput:\n23\n\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function secondSmallest() which takes t...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4708, "level": 1, "question": "Given an array of integers, determine the second smallest element in the array.\n\nExample:\nInput:\nN = 6\narr[] = {23, 45, 12, 34, 25, 12}\nOutput:\n23\n\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the func...
import wave def process_wav_file(input_filename: str, output_filename: str) -> None: try: # Open the input WAV file in read mode with wave.open(input_filename, 'rb') as wav_in: params = wav_in.getparams() n_channels, sampwidth, framerate, n_frames, comptype, compname = param...
simplelr_Docs
[ { "content": "Question:\nYou are required to create a Python utility that reads a WAV file, processes it to double its sample rate, and writes the result to a new WAV file. The goal is to ensure that the output WAV file plays at twice the speed of the original.\n\n#### Requirements:\n\n1. **Read WAV File**: Usi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4709, "level": 1, "question": "You are required to create a Python utility that reads a WAV file, processes it to double its sample rate, and writes the result to a new WAV file. The goal is to ensure that the output WAV file plays at twice the speed of the original.\n\n#### Require...
def find_maximum(numbers): """ This function finds the maximum number in a given list of numbers. Args: numbers (list): A list of numbers. Returns: int: The maximum number in the list. """ # Check if the list is empty if not numbers: raise ValueError("T...
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to find the maximum number in a given list of numbers. Ensure your code is well-commented to explain each step.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4710, "level": 1, "question": "Write a Python function to find the maximum number in a given list of numbers. Ensure your code is well-commented to explain each step.", "split": "train" }
def decode_python_version(hex_version: int) -> dict: major = (hex_version >> 24) & 0xFF minor = (hex_version >> 16) & 0xFF micro = (hex_version >> 8) & 0xFF beta_byte = hex_version & 0xFF release_level = (beta_byte >> 4) release_serial = beta_byte & 0xF return { 'major': major, ...
simplelr_Docs
[ { "content": "Question:\nYou are tasked with implementing a function that decodes a 32-bit hexadecimal integer representing a Python version and outputs its components. This exercise will demonstrate your understanding of bitwise operations and how to manipulate bits to extract useful information.\n\n#### Funct...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4711, "level": 1, "question": "You are tasked with implementing a function that decodes a 32-bit hexadecimal integer representing a Python version and outputs its components. This exercise will demonstrate your understanding of bitwise operations and how to manipulate bits to extrac...
def kth_smallest(nums, k): if not nums or k < 1 or k > len(nums): return None k -= 1 # Convert to 0-based index left, right = 0, len(nums) - 1 while left <= right: mid = (left + right) // 2 pivot = nums[mid] # Swap the pivot with the rightmost element nums[mid], ...
simplelr_Leetcode
[ { "content": "Question:\nGiven an integer array `nums` and an integer `k`, return the _kth smallest element_ in the sorted order within `nums` using an efficient algorithm. Note that `nums` could contain duplicates, but the value we're looking for is based on sorted order, so identical values are considered for...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4712, "level": 1, "question": "Given an integer array `nums` and an integer `k`, return the _kth smallest element_ in the sorted order within `nums` using an efficient algorithm. Note that `nums` could contain duplicates, but the value we're looking for is based on sorted order, so ...
def flatten_and_unique_sort(list_of_lists): elements_set = set() for sublist in list_of_lists: for element in sublist: elements_set.add(element) return sorted(elements_set)
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to grab all the elements from a list of lists and write them into a single list, removing any duplicates. The resulting list should be sorted in ascending order.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4713, "level": 1, "question": "Write a python function to grab all the elements from a list of lists and write them into a single list, removing any duplicates. The resulting list should be sorted in ascending order.", "split": "train" }
def max_non_overlapping_tasks(tasks, timeline): # Sort tasks by their end time tasks.sort(key=lambda x: x[1]) last_end = 0 count = 0 for task in tasks: start, end = task if start >= last_end and end <= timeline: count += 1 last_end = end ret...
simplelr_Taco
[ { "content": "Question:\nImagine you are a software developer working on a project management tool. Your task is to create a function that schedules tasks in such a way that maximizes the number of completed tasks within a given timeline. Each task can start and finish within specific time intervals, and it sho...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4714, "level": 1, "question": "Imagine you are a software developer working on a project management tool. Your task is to create a function that schedules tasks in such a way that maximizes the number of completed tasks within a given timeline. Each task can start and finish within ...
def calculate_total_sales(transactions: list[str]) -> dict[str, float]: product_sales = {} for transaction in transactions: product_id, quantity, price = transaction.split(':') quantity = int(quantity) price = float(price) total = quantity * price if product_id in product...
simplelr_Algorithm
[ { "content": "Question:\n### Problem Statement\n\nYou are tasked with implementing a system that processes a list of transactions made in an online store. Each transaction is recorded as a string in the format `\"product_id:quantity:price_per_unit\"`. You need to create a function `calculate_total_sales` that c...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4715, "level": 1, "question": "### Problem Statement\n\nYou are tasked with implementing a system that processes a list of transactions made in an online store. Each transaction is recorded as a string in the format `\"product_id:quantity:price_per_unit\"`. You need to create a func...
from typing import List def longest_subarray_with_limited_diff(arr: List[int], k: int) -> int: max_length = 1 n = len(arr) for left in range(n): current_max = current_min = arr[left] for right in range(left, n): current_max = max(current_max, arr[right]) current_min ...
simplelr_Apps
[ { "content": "Question:\nGiven a list of integers, your task is to find and return the longest subarray where the absolute difference between any two elements is less than or equal to a specified integer, `k`.\n\n**Input**:\n- A list of integers `arr`.\n- An integer `k` representing the maximum allowed absolute...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4716, "level": 1, "question": "Given a list of integers, your task is to find and return the longest subarray where the absolute difference between any two elements is less than or equal to a specified integer, `k`.\n\n**Input**:\n- A list of integers `arr`.\n- An integer `k` repres...
from collections import OrderedDict def get_column(ordered_dict, column_name): """Return an OrderedDict with only the specified column name.""" result = OrderedDict() for key, value in ordered_dict.items(): if key == column_name: result[key] = value return result
simplelr_Filter
[ { "content": "Question:\nI have a Python script that takes an OrderedDict and a single column name as input, and returns a new OrderedDict where only the specified column name exists. The OrderedDict has string keys and values. Here is the example: \n\n```python\nfrom collections import OrderedDict\n\ndef get_c...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4717, "level": 1, "question": "I have a Python script that takes an OrderedDict and a single column name as input, and returns a new OrderedDict where only the specified column name exists. The OrderedDict has string keys and values. Here is the example: \n\n```python\nfrom collecti...
def get_unique_sorted_values(records, key): unique_values = set() for record in records: if key in record: unique_values.add(record[key]) return sorted(unique_values)
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes a list of dictionaries representing records and a key, then returns a list of unique values for that key. The function should be able to handle missing keys and return values in a sorted list.\nAnswer:\nLet's think step by step.\n", "role": "user" ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4718, "level": 1, "question": "Write a Python function that takes a list of dictionaries representing records and a key, then returns a list of unique values for that key. The function should be able to handle missing keys and return values in a sorted list.", "split": "train" }
def is_rotation(A: str, B: str) -> bool: if len(A) != len(B): return False if len(A) == 0: return True return B in (A + A)
simplelr_Data_Structure
[ { "content": "Question:\nYou are given two strings `A` and `B`. Determine whether `B` is a rotation of `A` using an efficient string manipulation algorithm.\n\nRotations: A rotation by `k` of `A` means moving the first `k` characters of `A` to the end.\n\nFor example:\n- `A = \"abcdef\"`, a rotation by `2` is `...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4719, "level": 1, "question": "You are given two strings `A` and `B`. Determine whether `B` is a rotation of `A` using an efficient string manipulation algorithm.\n\nRotations: A rotation by `k` of `A` means moving the first `k` characters of `A` to the end.\n\nFor example:\n- `A = ...
def is_balanced(s: str) -> bool: stack = [] for char in s: if char == '[': stack.append(char) else: if not stack: return False stack.pop() return len(stack) == 0
simplelr_Algorithm
[ { "content": "Question:\n### Coding Assessment Question\n\n#### Scenario\nYou are given a sequence of brackets that consists of only '[' and ']'. You need to determine if the brackets are balanced. A sequence of brackets is balanced if every opening '[' has a corresponding closing ']', and the sequence properly...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4720, "level": 1, "question": "### Coding Assessment Question\n\n#### Scenario\nYou are given a sequence of brackets that consists of only '[' and ']'. You need to determine if the brackets are balanced. A sequence of brackets is balanced if every opening '[' has a corresponding clo...
def delete_reoccurring_characters(s): seen = set() result = [] for char in s: if char not in seen: result.append(char) seen.add(char) return ''.join(result) # Example test cases print(delete_reoccurring_characters("abracadabra")) # Output: "abrcd" print(delete_reoccurri...
simplelr_Data_Structure
[ { "content": "Question:\n**Problem Statement:**\n\nYou are given a string `s` which may contain repeated characters. Your task is to write a Python function `delete_reoccurring_characters(s)` that removes all recurring characters and returns the resulting string while maintaining the order of their first occurr...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4721, "level": 1, "question": "**Problem Statement:**\n\nYou are given a string `s` which may contain repeated characters. Your task is to write a Python function `delete_reoccurring_characters(s)` that removes all recurring characters and returns the resulting string while maintain...
def count_characters(input_string): return len(input_string) # Example usage input_str = "Hello, World!" print(count_characters(input_str)) # Output: 13
simplelr_Filter
[ { "content": "Question:\nHow can I create a code snippet to count the number of characters in a string?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4722, "level": 1, "question": "How can I create a code snippet to count the number of characters in a string?", "split": "train" }
import os def rank_files_by_keyword(directory_path: str, keyword: str) -> list[str]: keyword = keyword.lower() file_keyword_frequency = [] for filename in os.listdir(directory_path): if filename.endswith('.txt'): try: with open(os.path.join(directory_path, filename), 'r...
simplelr_Algorithm
[ { "content": "Question:\n### Context\nIn the world of search and file management, it is often necessary to identify and rank files based on certain criteria, such as frequency of keyword occurrence. This is particularly useful in search engines, document management systems, and database queries.\n\n### Task\nYo...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4723, "level": 1, "question": "### Context\nIn the world of search and file management, it is often necessary to identify and rank files based on certain criteria, such as frequency of keyword occurrence. This is particularly useful in search engines, document management systems, an...
def find_rising_subsequence(lst): """ This function finds the longest strictly increasing subsequence in a given list. Args: lst (list): A list of integers. Returns: list: The longest strictly increasing subsequence. """ if not lst: return [] n = len(lst) d...
simplelr_Filter
[ { "content": "Question:\nI have been trying to solve this problem for hours and I just can't seem to find the right approach. \n\nI have a string of integers that represents the intensity of a signal at each point in time. For example, [1, 2, 3, 2, 1]. \n\nThe signal is considered to be in a \"rising\" phase if...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4724, "level": 1, "question": "I have been trying to solve this problem for hours and I just can't seem to find the right approach. \n\nI have a string of integers that represents the intensity of a signal at each point in time. For example, [1, 2, 3, 2, 1]. \n\nThe signal is consid...
def are_anagrams(str1, str2): # Process each string to include only lowercase alphabetic characters processed1 = [c.lower() for c in str1 if c.isalpha()] processed2 = [c.lower() for c in str2 if c.isalpha()] # Sort the processed lists and compare return sorted(processed1) == sorted(processed2)
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that takes two strings as input and returns True if they are anagrams, False otherwise. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For example, the word \"...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4725, "level": 1, "question": "Write a Python function that takes two strings as input and returns True if they are anagrams, False otherwise. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exa...
from collections import Counter def top_k_frequent_elements(numbers, k): count = Counter(numbers) sorted_numbers = sorted(count.items(), key=lambda x: (-x[1], x[0])) result = [num for num, cnt in sorted_numbers[:k]] return result
simplelr_Evol
[ { "content": "Question:\nImplement a function that returns the k most frequent elements in a given list of integers. The function should be efficient in terms of time and space complexity.\n\nExample:\n- Input: numbers = [1, 1, 1, 2, 2, 3], k = 2\n- Output: [1, 2]\n\n- Input: numbers = [4, 4, 4, 6, 6, 1, 1, 1, ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4726, "level": 1, "question": "Implement a function that returns the k most frequent elements in a given list of integers. The function should be efficient in terms of time and space complexity.\n\nExample:\n- Input: numbers = [1, 1, 1, 2, 2, 3], k = 2\n- Output: [1, 2]\n\n- Input: ...
def sum_of_integers(num_list): total_sum = 0 for num in num_list: total_sum += num return total_sum
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes in a list of integers as the variable `num_list`, and returns the sum of all the integers in the list using a for loop.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4727, "level": 1, "question": "Create a function that takes in a list of integers as the variable `num_list`, and returns the sum of all the integers in the list using a for loop.", "split": "train" }
from collections import Counter def can_form_palindrome(s): count = Counter(s) odd_counts = 0 for char, cnt in count.items(): if cnt % 2 != 0: odd_counts += 1 n = len(s) if n % 2 == 0: if odd_counts != 0: return "" else: if odd_counts != 1: ...
simplelr_Leetcode
[ { "content": "Question:\nGiven a string `s`, check if it can be rearranged to form a palindrome. If it is possible, return a palindrome that can be formed from `s`. If it is not possible to rearrange the string to form a palindrome, return an empty string. You must solve the problem with a time complexity of `O...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4728, "level": 1, "question": "Given a string `s`, check if it can be rearranged to form a palindrome. If it is possible, return a palindrome that can be formed from `s`. If it is not possible to rearrange the string to form a palindrome, return an empty string. You must solve the p...
def check_string_in_list(strings, target): target_lower = target.lower() return any(s.lower() == target_lower for s in strings)
simplelr_Filter
[ { "content": "Question:\n* **Challenge:** Design a Python function that takes two arguments:\n\n * A list of strings.\n * A single string.\n \n The function should return True if the single string is present in the list of strings, ignoring case sensitivity.\n* **Example:**\n\n ```python\n strin...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4729, "level": 1, "question": "* **Challenge:** Design a Python function that takes two arguments:\n\n * A list of strings.\n * A single string.\n \n The function should return True if the single string is present in the list of strings, ignoring case sensitivity.\n* **Exa...
def switch_pairs(stack: list) -> list: result = [] for i in range(0, len(stack), 2): pair = stack[i:i+2] if len(pair) == 2: pair = pair[::-1] # Reverse the pair result.extend(pair) return result
simplelr_Data_Structure
[ { "content": "Question:\n#### Scenario\nSuppose you are managing a software that frequently needs to modify stacks by switching successive pairs of elements. The stack could represent a wide range of ordered structures such as jobs to be processed, historical data, or even memory addresses.\n\n#### Task\nImplem...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4730, "level": 1, "question": "#### Scenario\nSuppose you are managing a software that frequently needs to modify stacks by switching successive pairs of elements. The stack could represent a wide range of ordered structures such as jobs to be processed, historical data, or even mem...
def longest_unique_substr_length(s): char_last_occurrence = {} max_length = 0 left = 0 for right in range(len(s)): char = s[right] if char in char_last_occurrence and char_last_occurrence[char] >= left: left = char_last_occurrence[char] + 1 char_last_occurrence[cha...
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the length of the longest contiguous substring with no repeating characters.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4731, "level": 1, "question": "Write a python function to find the length of the longest contiguous substring with no repeating characters.", "split": "train" }
def quick_sort(arr): if len(arr) <= 1: return arr pivot = arr[-1] left = [x for x in arr[:-1] if x <= pivot] right = [x for x in arr[:-1] if x > pivot] return quick_sort(left) + [pivot] + quick_sort(right)
simplelr_Prefill
[ { "content": "Question:\nWrite a function to sort a given array in ascending order using the quick sort algorithm in Python.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4732, "level": 1, "question": "Write a function to sort a given array in ascending order using the quick sort algorithm in Python.", "split": "train" }
def find_transaction_pairs(transactions, target): seen = {} result = [] for index, value in enumerate(transactions): complement = target - value if complement in seen: result.append((seen[complement], index)) break # Only one pair exists at most, so break after findi...
simplelr_Data_Structure
[ { "content": "Question:\nYou are a developer at a fintech company and working on a feature to monitor unusual transactions. Your task is to identify pairs of transactions within a given list of transaction amounts that sum to a specific target value.\n\n**Function**: \nWrite a function, `find_transaction_pairs(...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4733, "level": 1, "question": "You are a developer at a fintech company and working on a feature to monitor unusual transactions. Your task is to identify pairs of transactions within a given list of transaction amounts that sum to a specific target value.\n\n**Function**: \nWrite a...
def is_armstrong_number(num): if num < 0: return False original = num digits = str(num) length = len(digits) sum_of_powers = sum(int(digit) ** length for digit in digits) return sum_of_powers == original
simplelr_Filter
[ { "content": "Question:\nWhat is the code snippet to check if a number is armstrong in Python?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4734, "level": 1, "question": "What is the code snippet to check if a number is armstrong in Python?", "split": "train" }
def reverse_string(s): """ Returns the reverse of the input string. Args: s (str): The string to be reversed. Returns: str: The reversed string. Examples: >>> reverse_string("Hello") 'olleH' >>> reverse_string("") '' >>> reverse_...
simplelr_Prefill
[ { "content": "Question:\nWrite a function to reverse a string in Python. You should include a docstring that explains what the function does, and utilize the function with some test cases to verify its correctness.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4735, "level": 1, "question": "Write a function to reverse a string in Python. You should include a docstring that explains what the function does, and utilize the function with some test cases to verify its correctness.", "split": "train" }
def total_cost(products): total = 0.0 for product in products: total += product['price'] * product['quantity'] return total
simplelr_Filter
[ { "content": "Question:\n### CS50's Introduction to Computer Science\n#### Lecture 1\nLet's mimic the style of CS50, and present a problem and then walk through the solution step-by-step.\n\nHere is the problem: \n**Problem 1:**\n* Write a function called `total_cost` that takes in a list of products, where eac...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4736, "level": 1, "question": "### CS50's Introduction to Computer Science\n#### Lecture 1\nLet's mimic the style of CS50, and present a problem and then walk through the solution step-by-step.\n\nHere is the problem: \n**Problem 1:**\n* Write a function called `total_cost` that tak...
def remove_non_alpha_chars(s): return ''.join(char for char in s if char.isalpha())
simplelr_Filter
[ { "content": "Question:\nWrite a Python code that takes a string as input and returns the string with all non-alphabetic characters removed.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4737, "level": 1, "question": "Write a Python code that takes a string as input and returns the string with all non-alphabetic characters removed.", "split": "train" }
def has_increasing_subsequence(sequence): if len(sequence) < 4: return False a = b = c = d = float('inf') for num in sequence: if num < a: a = num elif num < b: b = num elif num < c: c = num elif num < d: d = num ...
simplelr_Filter
[ { "content": "Question:\n### Task: \nGiven a sequence of numbers, determine whether the sequence contains an increasing subsequence of length 4.\n\n### Example:\nInput: `[1, 2, 3, 4]`\nOutput: `True`\n\nInput: `[1, 3, 5, 7, 9]`\nOutput: `True`\n\nInput: `[1, 2, 1, 2, 3, 4]`\nOutput: `True`\n\nInput: `[1, 1, 1, ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4738, "level": 1, "question": "### Task: \nGiven a sequence of numbers, determine whether the sequence contains an increasing subsequence of length 4.\n\n### Example:\nInput: `[1, 2, 3, 4]`\nOutput: `True`\n\nInput: `[1, 3, 5, 7, 9]`\nOutput: `True`\n\nInput: `[1, 2, 1, 2, 3, 4]`\nO...
def common_elements(arr1, arr2): set1 = set(arr1) result = [] added = set() for element in arr2: if element in set1 and element not in added: result.append(element) added.add(element) return result
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes two arrays as input and returns an array containing the common elements found in both of the input arrays. The function should efficiently use data structures to minimize the time complexity.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4739, "level": 1, "question": "Create a function that takes two arrays as input and returns an array containing the common elements found in both of the input arrays. The function should efficiently use data structures to minimize the time complexity.", "split": "train" }
def find_first_repeating_char(s: str) -> str: seen = set() for c in s: if c in seen: return c seen.add(c) return None
simplelr_Algorithm
[ { "content": "Question:\n### Question: **Find the First Repeating Character**\n\n### Background\nIn many text processing tasks, it is useful to identify characters that repeat within a string. This information can help in optimizing various text analytics algorithms. For this reason, you need to develop a metho...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4740, "level": 1, "question": "### Question: **Find the First Repeating Character**\n\n### Background\nIn many text processing tasks, it is useful to identify characters that repeat within a string. This information can help in optimizing various text analytics algorithms. For this ...
def longest_increasing_subsequence(nums): """ Finds the longest increasing subsequence in a list of integers. Args: nums: A list of integers. Returns: A list containing the longest increasing subsequence. """ if not nums: return [] n = len(nums) dp = [1] * ...
simplelr_Filter
[ { "content": "Question:\nThis is the task description:\n \n You will be given a list of integers, and you need to find the longest increasing subsequence.\n\n Here are the rules and requirements:\n\n* **Longest Increasing Subsequence (LIS):**\n\nA subsequence is a sequence obtained by deleting some elements fro...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4741, "level": 1, "question": "This is the task description:\n \n You will be given a list of integers, and you need to find the longest increasing subsequence.\n\n Here are the rules and requirements:\n\n* **Longest Increasing Subsequence (LIS):**\n\nA subsequence is a sequence obt...
import heapq def find_shortest_path(flights: dict, start: str, target: str) -> int: if start == target: return 0 if start not in flights or target not in flights: return -1 distances = {city: float('infinity') for city in flights} distances[start] = 0 heap = [] heapq.heappush(...
simplelr_Algorithm
[ { "content": "Question:\n### Problem: Flight Connection Finder\n\nYou work for a company that builds an application to find the shortest flight connections between cities. You need to implement a function that calculates the shortest path from a given start city to the target city using Dijkstra's algorithm.\n\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4742, "level": 1, "question": "### Problem: Flight Connection Finder\n\nYou work for a company that builds an application to find the shortest flight connections between cities. You need to implement a function that calculates the shortest path from a given start city to the target ...
def find_max_value(lst): if not lst: return None return max(lst)
simplelr_Filter
[ { "content": "Question:\nWrite a Python function to find the maximum value in a list of integers. The function should take a list of integers as input and return the maximum value in the list. If the list is empty, the function should return None. For example, the maximum value in the list [1, 5, 3, 9, 2] is 9,...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4743, "level": 1, "question": "Write a Python function to find the maximum value in a list of integers. The function should take a list of integers as input and return the maximum value in the list. If the list is empty, the function should return None. For example, the maximum valu...
def maximalSquare(matrix): 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 j == 0: ...
simplelr_Taco
[ { "content": "Question:\nYou are given a matrix consisting of '0's and '1's. Your task is to find the size of the largest square that contains only '1's and return the area of that square. If no such square exists, return 0.\n\nExample 1:\nInput:\nmatrix = [\n [\"1\",\"0\",\"1\",\"0\",\"0\"],\n [\"1\",\"0\",\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4744, "level": 1, "question": "You are given a matrix consisting of '0's and '1's. Your task is to find the size of the largest square that contains only '1's and return the area of that square. If no such square exists, return 0.\n\nExample 1:\nInput:\nmatrix = [\n [\"1\",\"0\",\"...
def min_groups(soldiers, threshold): if not soldiers: return 0 soldiers.sort() groups = 0 start = 0 n = len(soldiers) for i in range(n): if soldiers[i] - soldiers[start] > threshold: groups += 1 start = i groups += 1 return groups
simplelr_Codeforces
[ { "content": "Question:\nYou are given an array of integers representing the strength levels of soldiers in an army. The objective is to determine the minimum number of groups that must be formed such that the difference in strength between the strongest and the weakest soldier in any group does not exceed a gi...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4745, "level": 1, "question": "You are given an array of integers representing the strength levels of soldiers in an army. The objective is to determine the minimum number of groups that must be formed such that the difference in strength between the strongest and the weakest soldie...
def max_product(nums): if len(nums) < 2: raise ValueError("The list must contain at least two elements.") sorted_nums = sorted(nums) product1 = sorted_nums[-2] * sorted_nums[-1] product2 = sorted_nums[0] * sorted_nums[1] return max(product1, product2)
simplelr_Filter
[ { "content": "Question:\nWrite a Python function that finds the maximum product of two numbers in a list. The function should handle lists with negative numbers and zero. The function should also manage lists with only one element or empty lists, raising an appropriate exception in these cases.\nAnswer:\nLet's ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4746, "level": 1, "question": "Write a Python function that finds the maximum product of two numbers in a list. The function should handle lists with negative numbers and zero. The function should also manage lists with only one element or empty lists, raising an appropriate excepti...
def is_power_of_two(n): if n <= 1: return False return (n & (n - 1)) == 0
simplelr_Prefill
[ { "content": "Question:\nWrite a function to determine if a given integer is a power of two. A power of two is an integer that can be expressed as 2 raised to an integer power. For example, 1, 2, 4, 8 are powers of two. Note that 0 and 1 are not considered powers of two in this context.\nAnswer:\nLet's think st...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4747, "level": 1, "question": "Write a function to determine if a given integer is a power of two. A power of two is an integer that can be expressed as 2 raised to an integer power. For example, 1, 2, 4, 8 are powers of two. Note that 0 and 1 are not considered powers of two in thi...
def unique_paths_with_obstacles(grid): m = len(grid) if m == 0: return 0 n = len(grid[0]) if grid[0][0] == 1 or grid[m-1][n-1] == 1: return 0 dp = [[0 for _ in range(n)] for _ in range(m)] dp[0][0] = 1 for i in range(m): for j in range(n): if i == 0 and j ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a rectangle grid with `m` rows and `n` columns represented by a 2D list `grid`. Each cell of the grid is either empty (`0`) or contains an obstacle (`1`). Starting from the top-left cell (0, 0), you want to find the number of unique paths to the bottom-right cell (m-1, n-1...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4748, "level": 1, "question": "You are given a rectangle grid with `m` rows and `n` columns represented by a 2D list `grid`. Each cell of the grid is either empty (`0`) or contains an obstacle (`1`). Starting from the top-left cell (0, 0), you want to find the number of unique paths...
import string def most_and_least_frequent(text): # Split the text into words and clean each word by stripping punctuation and converting to lowercase words = [word.strip(string.punctuation).lower() for word in text.split()] # Filter out any empty strings that may result from stripping words = [word for...
simplelr_Filter
[ { "content": "Question:\nI am working on a project that requires me to write a function to find the most and least frequent words in a given string. The function should return a tuple with the most frequent word and the least frequent word. \n\nHere is my attempt:\n\n```python\ndef most_and_least_frequent(text)...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4749, "level": 1, "question": "I am working on a project that requires me to write a function to find the most and least frequent words in a given string. The function should return a tuple with the most frequent word and the least frequent word. \n\nHere is my attempt:\n\n```python...
from collections import Counter def char_count(string): processed = string.replace(" ", "").lower() return dict(Counter(processed))
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes a string and returns the total occurrences of each character in the string. The function should ignore spaces and be case-insensitive.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4750, "level": 1, "question": "Create a function that takes a string and returns the total occurrences of each character in the string. The function should ignore spaces and be case-insensitive.", "split": "train" }
def string_to_unique_words(s): return set(s.split())
simplelr_Filter
[ { "content": "Question:\nHow can I create a Python function that converts a string to a set of unique words?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4751, "level": 1, "question": "How can I create a Python function that converts a string to a set of unique words?", "split": "train" }
def min_moves_to_equalize(num): num.sort() median = num[len(num) // 2] return sum(abs(x - median) for x in num)
simplelr_Leetcode
[ { "content": "Question:\nYou are given an array `num` of positive integers where `num[i]` represents the i-th person's amount of money. Calculate the minimum number of moves required to make all the amounts of money equal, where a move is incrementing or decrementing any amount of money by 1. Return the number ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4752, "level": 1, "question": "You are given an array `num` of positive integers where `num[i]` represents the i-th person's amount of money. Calculate the minimum number of moves required to make all the amounts of money equal, where a move is incrementing or decrementing any amoun...
def find_min_k_numbers(nums, k): if k <= 0 or not nums: return [] if k >= len(nums): return sorted(nums) sorted_nums = sorted(nums) return sorted_nums[:k]
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the minimum 'k' numbers from a given list of integers.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4753, "level": 1, "question": "Write a python function to find the minimum 'k' numbers from a given list of integers.", "split": "train" }
def insert_into_sorted_array(array, value): if not array: return [value] index = 0 while index < len(array) and array[index] <= value: index += 1 return array[:index] + [value] + array[index:]
simplelr_Prefill
[ { "content": "Question:\nWrite a function to insert a new value into a sorted array while maintaining the sorted order. Assume the array is already sorted in ascending order and you can add a new element at any position such that the new array remains sorted.\nAnswer:\nLet's think step by step.\n", "role": ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4754, "level": 1, "question": "Write a function to insert a new value into a sorted array while maintaining the sorted order. Assume the array is already sorted in ascending order and you can add a new element at any position such that the new array remains sorted.", "split": "tra...
def process_urls(filename, target_string): try: with open(filename, 'r') as file: urls = [line.strip() for line in file.readlines()] total = len(urls) matching_urls = [url for url in urls if url.startswith(target_string)] return total, matching_urls except...
simplelr_Filter
[ { "content": "Question:\nI have a text file that contains a list of URLs that I'd like to process. Each URL is on a separate line in the file. How can I use Python to read in this file, count the number of URLs, and then print a list of URLs that begin with a specific string?\nAnswer:\nLet's think step by step....
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4755, "level": 1, "question": "I have a text file that contains a list of URLs that I'd like to process. Each URL is on a separate line in the file. How can I use Python to read in this file, count the number of URLs, and then print a list of URLs that begin with a specific string?"...
def search_matrix(matrix, target): if not matrix or not matrix[0]: return [-1, -1] m, n = len(matrix), len(matrix[0]) row, col = 0, n - 1 while row < m and col >= 0: if matrix[row][col] == target: return [row, col] elif target < matrix[row][col]: col -= 1 ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given an **m x n** integer matrix `matrix` with the following rules:\n - Each row is sorted in **non-decreasing order** from left to right.\n - Each column is sorted in **non-decreasing order** from top to bottom.\n\nGiven an integer `target`, write an algorithm to find the po...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4756, "level": 1, "question": "You are given an **m x n** integer matrix `matrix` with the following rules:\n - Each row is sorted in **non-decreasing order** from left to right.\n - Each column is sorted in **non-decreasing order** from top to bottom.\n\nGiven an integer `target`...
import numpy as np from sklearn.covariance import MinCovDet def robust_covariance_estimator(data: np.ndarray) -> tuple: mcd = MinCovDet() mcd.fit(data) return (mcd.covariance_, mcd.location_)
simplelr_Docs
[ { "content": "Question:\nYou are provided with a multidimensional dataset containing potential outliers and you are tasked with performing robust covariance estimation to accurately estimate the covariance matrix while mitigating the influence of outliers. You will implement a function that uses scikit-learn's ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4757, "level": 1, "question": "You are provided with a multidimensional dataset containing potential outliers and you are tasked with performing robust covariance estimation to accurately estimate the covariance matrix while mitigating the influence of outliers. You will implement a...
def filter_people(people, city): return [person for person in people if person['age'] > 30 and person['city'] == city]
simplelr_Filter
[ { "content": "Question:\nWrite a code snippet to filter a list of dictionaries in Python based on multiple conditions. For example, consider a list of dictionaries where each dictionary represents a person with keys 'name', 'age', and 'city'. Write a function that filters this list to return only those dictiona...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4758, "level": 1, "question": "Write a code snippet to filter a list of dictionaries in Python based on multiple conditions. For example, consider a list of dictionaries where each dictionary represents a person with keys 'name', 'age', and 'city'. Write a function that filters this...
def domain_name(url: str) -> str: # Split the URL to remove the scheme split_url = url.split('://') if len(split_url) > 1: main_part = split_url[1] else: main_part = split_url[0] # Get the domain part before any '/' domain_part = main_part.split('/')[0] # Split the ...
simplelr_Data_Structure
[ { "content": "Question:\n### Domain Name Parser\n\n**Objective:**\nWrite a function that, given a URL as a string, extracts and returns the domain name as a string. Your implementation should handle various URL formats including presence or absence of \"http://\", \"https://\", and \"www.\".\n\n**Instructions:*...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4759, "level": 1, "question": "### Domain Name Parser\n\n**Objective:**\nWrite a function that, given a URL as a string, extracts and returns the domain name as a string. Your implementation should handle various URL formats including presence or absence of \"http://\", \"https://\"...
def cumulative_sum(lst): current_sum = 0 result = [] for num in lst: current_sum += num result.append(current_sum) return result
simplelr_Evol
[ { "content": "Question:\nDesign a Python function that takes in a list of integers and returns a new list where each element is the sum of itself and all previous elements in the original list. The function should utilize an efficient approach. Also, write a brief explanation of the time complexity of your solu...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4760, "level": 1, "question": "Design a Python function that takes in a list of integers and returns a new list where each element is the sum of itself and all previous elements in the original list. The function should utilize an efficient approach. Also, write a brief explanation ...
import torch def stable_batched_matrix_multiplication( batch_A: torch.Tensor, batch_B: torch.Tensor, use_tf32: bool = False, precision: str = 'fp32' ) -> torch.Tensor: """ Perform numerically stable batched matrix multiplication. Parameters: batch_A (torch.Tensor): A 3D tensor ...
simplelr_Docs
[ { "content": "Question:\n#### Objective:\nImplement a function that performs matrix multiplication on a batch of matrices in PyTorch while ensuring numerical stability and demonstrating awareness of precision issues described in the provided documentation.\n\n#### Task:\nWrite a function `stable_batched_matrix_...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4761, "level": 1, "question": "#### Objective:\nImplement a function that performs matrix multiplication on a batch of matrices in PyTorch while ensuring numerical stability and demonstrating awareness of precision issues described in the provided documentation.\n\n#### Task:\nWrite...
def two_sum_pairs(nums, target): result = [] n = len(nums) for i in range(n): for j in range(i + 1, n): if nums[i] + nums[j] == target: result.append([i, j]) return result
simplelr_Leetcode
[ { "content": "Question:\nGiven an array of integers `nums` and an integer `target`, return _an array of unique pairs of indices_ `[i, j]` _(i != j)_ from the array such that the sum of the elements at these indices equals the `target`. Ensure that the pairs are listed in ascending order of their first index, an...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4762, "level": 1, "question": "Given an array of integers `nums` and an integer `target`, return _an array of unique pairs of indices_ `[i, j]` _(i != j)_ from the array such that the sum of the elements at these indices equals the `target`. Ensure that the pairs are listed in ascen...
def replace_character(s, x, y): return s.replace(x, y)
simplelr_Prefill
[ { "content": "Question:\nWrite a function to replace all occurrences of a character 'x' in the string 's' with a new character 'y'. The function should also handle cases where 'x' and 'y' are the same character.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4763, "level": 1, "question": "Write a function to replace all occurrences of a character 'x' in the string 's' with a new character 'y'. The function should also handle cases where 'x' and 'y' are the same character.", "split": "train" }
def parse_ascii_string(s): # Replace "UFO" with the corresponding ASCII codes s = s.replace("UFO", "857079") # Split the string into valid ASCII codes codes = [] i = 0 while i < len(s): # Try to take the longest valid code (up to 3 digits) if i + 3 <= len(s): thr...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that parses input strings as ASCII character codes and converts them to corresponding uppercase letters. You need to handle a special case where the input string contains the substring \"UFO\". In this case, replace \"UFO\" with the ASCII character code for 'U' (85) fo...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4764, "level": 1, "question": "Create a function that parses input strings as ASCII character codes and converts them to corresponding uppercase letters. You need to handle a special case where the input string contains the substring \"UFO\". In this case, replace \"UFO\" with the A...
def first_missing_positive(nums): positives = set() for num in nums: if num > 0: positives.add(num) i = 1 while i in positives: i += 1 return i
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the first missing positive number in a list of integers. For example, given the array [3, 4, -1, 1], the function should return 2 because it is the first missing positive number.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4765, "level": 1, "question": "Write a python function to find the first missing positive number in a list of integers. For example, given the array [3, 4, -1, 1], the function should return 2 because it is the first missing positive number.", "split": "train" }
from collections import deque def canReach(arr, start): n = len(arr) if start < 0 or start >= n: return False if arr[start] == 0: return True visited = set() queue = deque() queue.append(start) visited.add(start) while queue: current = queue.popleft() if ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given an integer array `arr` and an integer `start`. You can move from index `i` to index `i + arr[i]` or index `i - arr[i]` where `i` is the current index. Return `true` if you can reach any index with value `0`, and `false` otherwise. \n\nNote that you cannot leap outside the ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4766, "level": 1, "question": "You are given an integer array `arr` and an integer `start`. You can move from index `i` to index `i + arr[i]` or index `i - arr[i]` where `i` is the current index. Return `true` if you can reach any index with value `0`, and `false` otherwise. \n\nNot...
def length_of_longest_substring(s): char_index = {} max_length = 0 left = 0 for right in range(len(s)): char = s[right] if char in char_index and char_index[char] >= left: left = char_index[char] + 1 char_index[char] = right current_length = right - left + 1 ...
simplelr_Filter
[ { "content": "Question:\nProblem Description:\n\nYou are given a string containing only lowercase letters. You need to find the length of the longest substring without repeating characters.\n\n Example:\n\n Input: \"abcabcbb\"\nOutput: 3\nExplanation: The longest substring without repeating characters is \"abc\...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4767, "level": 1, "question": "Problem Description:\n\nYou are given a string containing only lowercase letters. You need to find the length of the longest substring without repeating characters.\n\n Example:\n\n Input: \"abcabcbb\"\nOutput: 3\nExplanation: The longest substring wit...
def reverse_string_with_spaces(s): non_space = [c for c in s if c != ' '] non_space_reversed = non_space[::-1] result = [] reverse_index = 0 for c in s: if c == ' ': result.append(' ') else: result.append(non_space_reversed[reverse_index]) reverse_...
simplelr_Evol
[ { "content": "Question:\nWrite a Python function that takes a string as input and returns a new string that is the reverse of the original string but maintains the positions of all spaces. For example, given the string `\"a b c d\"`, the output should be `\"d c b a\"`. Handle cases where there are multiple cons...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4768, "level": 1, "question": "Write a Python function that takes a string as input and returns a new string that is the reverse of the original string but maintains the positions of all spaces. For example, given the string `\"a b c d\"`, the output should be `\"d c b a\"`. Handle ...
from collections import Counter def string_frequencies(strings): return dict(Counter(strings))
simplelr_Filter
[ { "content": "Question:\nGenerate a function in Python which takes a list of strings as input and returns a dictionary holding the frequency of each string.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4769, "level": 1, "question": "Generate a function in Python which takes a list of strings as input and returns a dictionary holding the frequency of each string.", "split": "train" }
def left_rotate_array(arr, k): n = len(arr) if n == 0 or k == 0: return arr.copy() effective_k = k % n return arr[effective_k:] + arr[:effective_k]
simplelr_Filter
[ { "content": "Question:\nCan you provide a Python function that performs a left rotation on an array? A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array becomes [3,4,5,1,2].\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4770, "level": 1, "question": "Can you provide a Python function that performs a left rotation on an array? A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5], th...
def max_meetings(meetings): # Sort the meetings by their end times meetings.sort(key=lambda x: x[1]) last_end = -1 # Initialize with a value before the earliest possible start for start, end in meetings: if start >= last_end: last_end = end else: return -1 re...
simplelr_Leetcode
[ { "content": "Question:\nYou are given a **0-indexed** 2D integer array `meetings`, where `meetings[i] = [starti, endi]` represents a meeting from `starti` to `endi` (both inclusive). You need to schedule all these meetings in a single conference room without any overlap. If scheduling is possible, return the m...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4771, "level": 1, "question": "You are given a **0-indexed** 2D integer array `meetings`, where `meetings[i] = [starti, endi]` represents a meeting from `starti` to `endi` (both inclusive). You need to schedule all these meetings in a single conference room without any overlap. If s...
def rotate_array(arr, k): if len(arr) == 0 or len(arr) == 1: return arr.copy() if arr else arr n = len(arr) k_effective = k % n if k_effective == 0: return arr.copy() part1 = arr[-k_effective:] part2 = arr[:-k_effective] return part1 + part2
simplelr_Filter
[ { "content": "Question:\nCan you write a Python function to rotate an array to the right by k steps? For example, rotating [1,2,3,4,5,6,7] by 3 steps results in [5,6,7,1,2,3,4].\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4772, "level": 1, "question": "Can you write a Python function to rotate an array to the right by k steps? For example, rotating [1,2,3,4,5,6,7] by 3 steps results in [5,6,7,1,2,3,4].", "split": "train" }
import itertools def interleave_lists(list1, list2): result = [] for a, b in zip(list1, list2): result.append(a) result.append(b) zip_length = min(len(list1), len(list2)) tail1 = list1[zip_length:] tail2 = list2[zip_length:] result.extend(itertools.chain(tail1, tail2)) retur...
simplelr_Package
[ { "content": "Question:\nYou are tasked with writing a Python function named `interleave_lists` that takes two lists of integers and returns a new list with elements of the given lists interleaved. \n\n**Function Signature:**\n```python\ndef interleave_lists(list1, list2):\n pass\n```\n\n**Requirements:**\n1...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4773, "level": 1, "question": "You are tasked with writing a Python function named `interleave_lists` that takes two lists of integers and returns a new list with elements of the given lists interleaved. \n\n**Function Signature:**\n```python\ndef interleave_lists(list1, list2):\n ...
def calculate_final_bill(total_bill): if total_bill < 50: final = total_bill elif total_bill <= 100: final = total_bill * 0.9 elif total_bill <= 200: final = total_bill * 0.8 else: final = total_bill * 0.7 return round(final, 2)
simplelr_Apps
[ { "content": "Question:\nA shop offers various discounts on products for promotional events, but the discounts are staggered based on the total bill amount. Write a function that takes in the total bill amount in dollars and returns the final amount after applying the correct discount.\n\nThe discount categorie...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4774, "level": 1, "question": "A shop offers various discounts on products for promotional events, but the discounts are staggered based on the total bill amount. Write a function that takes in the total bill amount in dollars and returns the final amount after applying the correct ...
from collections import Counter def count_constructible_words(words, target): target_freq = Counter(target) valid_words = set() for word in words: if word in valid_words: continue word_freq = Counter(word) valid = True for char, count in word_freq.items(): ...
simplelr_Leetcode
[ { "content": "Question:\nYou are given an array of strings `words` and a string `target`. Each string in `words` consists of lowercase and uppercase letters only. We want to determine the number of unique words in the list that can be formed from the characters of `target` with unlimited copies of each characte...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4775, "level": 1, "question": "You are given an array of strings `words` and a string `target`. Each string in `words` consists of lowercase and uppercase letters only. We want to determine the number of unique words in the list that can be formed from the characters of `target` wit...
def cumulative_sum(numbers): cum_sum = 0 result = [] for num in numbers: cum_sum += num result.append(cum_sum) return result # Example usage: numbers = [1, 2, 3, 4, 5] print(cumulative_sum(numbers)) # Output: [1, 3, 6, 10, 15]
simplelr_Filter
[ { "content": "Question:\nHello, I'm an AI user and I need help with a coding task. I want to calculate the cumulative sum of a list of numbers. Can you guide me on how to do this in Python?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4776, "level": 1, "question": "Hello, I'm an AI user and I need help with a coding task. I want to calculate the cumulative sum of a list of numbers. Can you guide me on how to do this in Python?", "split": "train" }
from typing import List def find_peak(nums: List[int]) -> int: return nums.index(max(nums))
simplelr_Codeforces
[ { "content": "Question:\nYou are given an array of integers which is guaranteed to have exactly one peak element. An element is a peak if it is greater than its neighbors. Your task is to find and return the index of the peak element. The array may contain multiple peaks, but you need to return the index of any...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4777, "level": 1, "question": "You are given an array of integers which is guaranteed to have exactly one peak element. An element is a peak if it is greater than its neighbors. Your task is to find and return the index of the peak element. The array may contain multiple peaks, but ...
def prime_factors(n, sort=False): if n < 2: return [] factors = [] # Handle the even factor 2 while n % 2 == 0: factors.append(2) n = n // 2 # Now check for odd factors starting from 3 i = 3 while i * i <= n: while n % i == 0: factors.append(i) ...
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes an integer as a parameter and returns a list of integers that represent the prime factors of the given integer. The function should also include an optional parameter 'sort' that defaults to False. If 'sort' is True, the list of prime factors should be retur...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4778, "level": 1, "question": "Create a function that takes an integer as a parameter and returns a list of integers that represent the prime factors of the given integer. The function should also include an optional parameter 'sort' that defaults to False. If 'sort' is True, the li...
import numpy as np def reverse_rows_and_columns(arr): """ Reverses both the rows and columns of a 2D array. Args: arr (numpy.ndarray): A 2D NumPy array. Returns: numpy.ndarray: The input array with both rows and columns reversed. """ return np.flip(arr, (0, 1))
simplelr_Prefill
[ { "content": "Question:\nWrite a function to reverse both rows and columns of a 2D array in Python. I'm currently using a simple nested loop to reverse rows, but I want to understand how to use NumPy for this task for better efficiency and readability.\nAnswer:\nLet's think step by step.\n", "role": "user" ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4779, "level": 1, "question": "Write a function to reverse both rows and columns of a 2D array in Python. I'm currently using a simple nested loop to reverse rows, but I want to understand how to use NumPy for this task for better efficiency and readability.", "split": "train" }
def sum_of_list(numbers): return sum(numbers)
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to find the sum of all numbers in a given list. Here, an example list is [1, 2, 3, 4, 5].\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4780, "level": 1, "question": "Write a python function to find the sum of all numbers in a given list. Here, an example list is [1, 2, 3, 4, 5].", "split": "train" }
def longest_subarray_with_two_distinct(nums): count = {} left = 0 max_len = 0 for right in range(len(nums)): current_num = nums[right] if current_num in count: count[current_num] += 1 else: count[current_num] = 1 # Shrink the window until it conta...
simplelr_Leetcode
[ { "content": "Question:\nGiven an array of integers `nums`, you are tasked with finding the length of the longest subarray that contains at most two distinct values. Each subarray must consist of values that appear consecutively in the original array. Return the maximum length of such a subarray.\n\n### Example...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4781, "level": 1, "question": "Given an array of integers `nums`, you are tasked with finding the length of the longest subarray that contains at most two distinct values. Each subarray must consist of values that appear consecutively in the original array. Return the maximum length...
def maxWaterContainer(heights): left = 0 right = len(heights) - 1 max_water = 0 while left < right: width = right - left current_height = min(heights[left], heights[right]) current_area = current_height * width if current_area > max_water: max_water = current_...
simplelr_Taco
[ { "content": "Question:\nGiven a list of N integers, where each integer represents the height of a vertical line drawn on a Cartesian plane at that index. The widths between each pair of adjacent lines are all the same. Write a function maxWaterContainer() to find the maximum amount of water a container formed ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4782, "level": 1, "question": "Given a list of N integers, where each integer represents the height of a vertical line drawn on a Cartesian plane at that index. The widths between each pair of adjacent lines are all the same. Write a function maxWaterContainer() to find the maximum ...
from collections import Counter def character_distribution(text): char_counts = Counter(text) return { 'total_characters': len(text), 'unique_characters': len(char_counts), 'frequency_distribution': dict(char_counts), 'most_frequent_char': char_counts.most_common(1)[0][0] }
simplelr_Algorithm
[ { "content": "Question:\nYou need to write a function that counts the number of distinct characters in a string and summarizes the character distribution. This will help in understanding the frequency and variety of characters in a given string.\n\n### Function Definition\nImplement the function `character_dist...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4783, "level": 1, "question": "You need to write a function that counts the number of distinct characters in a string and summarizes the character distribution. This will help in understanding the frequency and variety of characters in a given string.\n\n### Function Definition\nImp...
def modify_third_element_in_kth_subarrays(arr, k): for i in range(len(arr)): if i % k == 0: if len(arr[i]) >= 3: arr[i][2] += 2 return arr
simplelr_Filter
[ { "content": "Question:\nGiven an integer \\( k \\), implement a function that adds 2 to the third element of every K'th subarray (0-indexed) in a given 2D array. If the subarray doesn't contain a third element, it does nothing.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4784, "level": 1, "question": "Given an integer \\( k \\), implement a function that adds 2 to the third element of every K'th subarray (0-indexed) in a given 2D array. If the subarray doesn't contain a third element, it does nothing.", "split": "train" }
def length_of_longest_substring(s: str) -> int: char_index_map = {} max_length = 0 left = 0 for right in range(len(s)): char = s[right] if char in char_index_map: left = max(left, char_index_map[char] + 1) char_index_map[char] = right current_length = right - ...
simplelr_Filter
[ { "content": "Question:\nGiven a string `s`, find the length of the longest substring without repeating characters. How can I solve this problem efficiently using a sliding window technique?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4785, "level": 1, "question": "Given a string `s`, find the length of the longest substring without repeating characters. How can I solve this problem efficiently using a sliding window technique?", "split": "train" }
def analyze_route(traffic_lights): """ Analyze the safety and urgency of the route based on the sequence of traffic lights. :param traffic_lights: List of strings where each string is 'green', 'yellow', or 'red' :return: A string indicating the safety and urgency of the route """ if 'red' i...
simplelr_Apps
[ { "content": "Question:\nYou are working on an autonomous vehicle project and need to implement a function to analyze a route based on the color of traffic lights encountered. Each traffic light can either be green, yellow, or red. Your function should determine the safety and urgency of the route.\n\nThe funct...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4786, "level": 1, "question": "You are working on an autonomous vehicle project and need to implement a function to analyze a route based on the color of traffic lights encountered. Each traffic light can either be green, yellow, or red. Your function should determine the safety and...
def rle_encode(input_file: str, output_file: str) -> None: input_path = input_file + '.txt' output_path = output_file + '.txt' with open(input_path, 'r') as f: input_str = f.read() output = [] current_char = None current_count = 0 for char in input_str: if char.isalpha(): ...
simplelr_Package
[ { "content": "Question:\nYou are tasked with implementing a function `rle_encode(input_file: str, output_file: str) -> None` that performs Run-Length Encoding (RLE) on a given text file.\n\n- The function shall read the text from a file (input_file).\n- It should write the encoded text to another file (output_f...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4787, "level": 1, "question": "You are tasked with implementing a function `rle_encode(input_file: str, output_file: str) -> None` that performs Run-Length Encoding (RLE) on a given text file.\n\n- The function shall read the text from a file (input_file).\n- It should write the enc...
import os def remove_empty_subfolders(main_dir): for root, dirs, files in os.walk(main_dir, topdown=False): # Skip the main directory to prevent deleting it if root == main_dir: continue # Check if the directory is empty if not dirs and not files: try: ...
simplelr_Filter
[ { "content": "Question:\nI have a folder containing plenty of subfolders and files. How can I remove all empty subfolders from this folder using Python?\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4788, "level": 1, "question": "I have a folder containing plenty of subfolders and files. How can I remove all empty subfolders from this folder using Python?", "split": "train" }
from collections import defaultdict def top_k_frequent_words(words, k): counts = defaultdict(int) for word in words: counts[word] += 1 sorted_words = sorted(counts.items(), key=lambda x: (-x[1], x[0])) result = [word for word, count in sorted_words[:k]] return result
simplelr_Code_Contests
[ { "content": "Question:\nA common technique in text analysis is to highlight the most frequent words in a document. In this task, you have to implement a function to find the top k frequent words in a given list of strings.\n\nThe input to the function consists of a list of words and an integer k. Your function...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4789, "level": 1, "question": "A common technique in text analysis is to highlight the most frequent words in a document. In this task, you have to implement a function to find the top k frequent words in a given list of strings.\n\nThe input to the function consists of a list of wo...
def modify_array(arr, constant): if constant == 0: return arr.copy() modified = [num * constant for num in arr] if constant < 0: modified = modified[::-1] if isinstance(constant, float): modified = [round(num) for num in modified] return modified
simplelr_Filter
[ { "content": "Question:\nIterate through a given array and modify each element by multiplying it by a constant value. Handle the scenario where the constant value is 0 by skipping the multiplication for that element. If the constant value is negative, reverse the order of the array elements after the modificati...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4790, "level": 1, "question": "Iterate through a given array and modify each element by multiplying it by a constant value. Handle the scenario where the constant value is 0 by skipping the multiplication for that element. If the constant value is negative, reverse the order of the ...
def transform_list(numbers): """ This function transforms each integer in the input list based on its value. For each integer: - If positive, replace with its square. - If negative, replace with its cube. - If zero, remains zero. Args: numbers (list): A list of integers. ...
simplelr_Filter
[ { "content": "Question:\nDesign a Python function that can take a list of integers and return a new list where each integer is replaced with its square if it is positive, its cube if it is negative, and zero if it is zero. Make sure the function is self-contained and clearly documented. Also, test the function ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4791, "level": 1, "question": "Design a Python function that can take a list of integers and return a new list where each integer is replaced with its square if it is positive, its cube if it is negative, and zero if it is zero. Make sure the function is self-contained and clearly d...
from typing import List, Dict def pyramid_frequency_analysis(pyramid: List[List[str]]) -> List[Dict[str, int]]: result = [] for level in pyramid: level_counts = {} for string in level: for char in string: if char in level_counts: level_counts[char...
simplelr_Algorithm
[ { "content": "Question:\n### Pyramid Frequency Analysis\n\n#### Scenario\nYou are building an application that needs to analyze the occurrences of characters in various levels of a pyramid structure of strings. Each level of the pyramid contains exactly one more string than the previous level, starting with one...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4792, "level": 1, "question": "### Pyramid Frequency Analysis\n\n#### Scenario\nYou are building an application that needs to analyze the occurrences of characters in various levels of a pyramid structure of strings. Each level of the pyramid contains exactly one more string than th...
def maximum(x, y): if x == y: return "Equal" else: return max(x, y)
simplelr_Taco
[ { "content": "Question:\nIn this exercise, you will practice using functions and conditional statements in Python. Given two integers x and y, your task is to return the maximum of the two integers. If the integers are equal, return the message \"Equal\".\n\nExample 1:\nInput: x = 7, y = 5\nOutput: 7\n\nExample...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4793, "level": 1, "question": "In this exercise, you will practice using functions and conditional statements in Python. Given two integers x and y, your task is to return the maximum of the two integers. If the integers are equal, return the message \"Equal\".\n\nExample 1:\nInput:...
def count_words_starting_with(sentence, letter): target = letter.lower() words = sentence.split() count = 0 for word in words: if word: # Check if word is not empty if word[0].lower() == target: count += 1 return count
simplelr_Prefill
[ { "content": "Question:\nWrite a python function to count the number of words in a given sentence that start with a specific letter (case-insensitive). The function should take two parameters: the sentence and the letter. It should return the count of words starting with that letter.\nAnswer:\nLet's think step ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4794, "level": 1, "question": "Write a python function to count the number of words in a given sentence that start with a specific letter (case-insensitive). The function should take two parameters: the sentence and the letter. It should return the count of words starting with that ...
from collections import Counter def frequency_count(arr): return Counter(arr)
simplelr_Prefill
[ { "content": "Question:\nCreate a function that takes an array of integers as input and returns the frequency of each integer in the array. The function should be implemented using Python.\nAnswer:\nLet's think step by step.\n", "role": "user" } ]
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4795, "level": 1, "question": "Create a function that takes an array of integers as input and returns the frequency of each integer in the array. The function should be implemented using Python.", "split": "train" }
def isPalindromeAfterRemoval(S, C): left = 0 right = len(S) - 1 while left < right: # Skip all occurrences of C on the left while left < right and S[left] == C: left += 1 # Skip all occurrences of C on the right while left < right and S[right] == C: ...
simplelr_Taco
[ { "content": "Question:\nGiven a string S of lowercase alphabets, the task is to determine if the string is a palindrome after removing all occurrences of a given character C. A palindrome is a string that reads the same backward as forward.\n\nExample 1:\nInput: S = \"abccba\", C = \"c\"\nOutput: 1\nExplanatio...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4796, "level": 1, "question": "Given a string S of lowercase alphabets, the task is to determine if the string is a palindrome after removing all occurrences of a given character C. A palindrome is a string that reads the same backward as forward.\n\nExample 1:\nInput: S = \"abccba\...
def coin_change(coins, amount): # Filter out zero-value coins and duplicates coins = list(set([c for c in coins if c > 0])) if amount == 0: return 0 dp = [amount + 1] * (amount + 1) dp[0] = 0 for a in range(1, amount + 1): for c in coins: if c <= a: dp...
simplelr_Filter
[ { "content": "Question:\nThe question is to design a dynamic programming solution for the following problem:\n\nGiven an array of non-negative integers representing coins of different denominations, find the minimum number of coins required to make up a given amount. \n\nLet's say we have coins = [1, 2, 5] and ...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4797, "level": 1, "question": "The question is to design a dynamic programming solution for the following problem:\n\nGiven an array of non-negative integers representing coins of different denominations, find the minimum number of coins required to make up a given amount. \n\nLet's...
def find_pairs(arr, k): seen = set() pairs = set() for num in arr: complement = k - num if complement in seen: a, b = sorted((num, complement)) pairs.add((a, b)) seen.add(num) return sorted(pairs)
simplelr_Apps
[ { "content": "Question:\nGiven a unique set of numbers, we want to find pairs of elements that sum to a target value k. Once pairs are found, return them as a list of tuples, sorted in increasing order of the first element, and if elements of any tuple match, sort by the second element as well. \n\nExample:\n\n...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4798, "level": 1, "question": "Given a unique set of numbers, we want to find pairs of elements that sum to a target value k. Once pairs are found, return them as a list of tuples, sorted in increasing order of the first element, and if elements of any tuple match, sort by the secon...
def longestUniqueSubstring(s: str) -> int: left = 0 max_length = 0 char_index = {} for right in range(len(s)): char = s[right] if char in char_index and char_index[char] >= left: left = char_index[char] + 1 char_index[char] = right current_length = right - le...
simplelr_Apps
[ { "content": "Question:\nYou are given a string comprising lowercase letters and you are required to find the length of the longest substring that contains only unique characters. Write a function `longestUniqueSubstring()` that takes a string `s` as input and returns an integer representing the length of the l...
code
{ "ground_truth": "pass", "style": "exec" }
{ "answer": "pass", "index": 4799, "level": 1, "question": "You are given a string comprising lowercase letters and you are required to find the length of the longest substring that contains only unique characters. Write a function `longestUniqueSubstring()` that takes a string `s` as input and returns an integ...