conversations
list
[ { "from": "user", "value": "You are given a circular **n-indexed** integer array `nums` where the index starts from `0` and ends at `n-1`. The circular aspect means the array wraps around, so the element following the last element is the first element again. Your task is to identify the length of the longes...
[ { "from": "user", "value": "### Regular String Expressions Matching\n\nYou are required to write a Python function that emulates a simplified version of a regular expression matcher. This simplified regular expression matcher should support the following special characters:\n\n1. `.` - Matches any single ch...
[ { "from": "user", "value": "def sum_face_up_cards(n, sequence):\n \"\"\"\n Returns the sum of face-up integers in the provided sequence of cards.\n\n Parameters:\n n (int): Number of cards.\n sequence (list of str): Sequence containing integers and 'X' characters.\n\n Returns:\n int: Su...
[ { "from": "user", "value": "Create a function that generates a list of prime numbers up to a given number n. The function should be efficient and use a well-known algorithm for prime number generation." }, { "from": "assistant", "value": "<think>\nOkay, I need to create a function that generates...
[ { "from": "user", "value": "Write a python function to flatten a list which can contain other lists as elements, up to a specified depth." }, { "from": "assistant", "value": "<think>\nOkay, I need to write a Python function to flatten a list that might contain other lists as elements, but only u...
[ { "from": "user", "value": "import heapq\n\nclass MedianFinder:\n \"\"\"\n A data structure that supports adding numbers and finding the median of the current numbers.\n \"\"\"\n\n def __init__(self):\n \"\"\" Initialize your data structure here. \"\"\"\n # max-heap for the first h...
[ { "from": "user", "value": "You are given a string `s` and an integer `k`. The string `s` can be broken down into `k` contiguous substrings by inserting `k-1` dividers. Return _the length of the smallest possible largest substring among these `k` substrings_. In other words, determine the minimum possible v...
[ { "from": "user", "value": "def most_frequent_element_frequency(arr: List[int]) -> int:\n \"\"\" Returns the frequency of the most frequent element in an array of integers.\n >>> most_frequent_element_frequency([1])\n 1\n >>> most_frequent_element_frequency([1, 2, 3, 4, 5])\n 1\n >>> most_...
[ { "from": "user", "value": "## Coding Challenge: Game of Numbers - Maximum Subarray Sum\n\n### Objective:\nWrite a function that takes an integer array as input and finds the contiguous subarray (containing at least one element) which has the largest sum. The function should return the sum of this subarray....
[ { "from": "user", "value": "### Coding Assessment\n\n#### Problem Statement\n\nYou are given two strings `s1` and `s2`. The string `s2` contains all distinct characters. Your task is to write a function to find the length of the longest common contiguous substring of characters in `s1` and `s2`.\n\n#### Fun...
[ { "from": "user", "value": "**Q: Writing a Python function that takes a string of mixed characters (capital letters, lowercase letters, numbers, and special characters) and returns the longest contiguous substring that contains only digits. If there are multiple substrings of maximum length, return the firs...
[ { "from": "user", "value": "Given a pair of non-negative integers, write code that outputs the lesser number without using any comparison operators like '<', '>', '==', etc." }, { "from": "assistant", "value": "<think>\nOkay, so I need to find a way to determine the lesser of two non-negative in...
[ { "from": "user", "value": "Create a function `word_break(s, wordDict)` that determines if a string `s` can be segmented into a space-separated sequence of one or more dictionary words from `wordDict`.\n\n- The first input, `s`, is a non-empty string containing only lowercase English letters.\n- The second ...
[ { "from": "user", "value": "You are given an array of strings `paths` where each path represents an absolute path to a file or directory in a file system. Each string consists of directory names and/or file names, all separated by slashes `/`. A directory or subdirectory may contain multiple files or subdir...
[ { "from": "user", "value": "class PyTorchFutureConfig:\n \"\"\" A class to configure and manage the behavior of module parameters during the conversion of models in PyTorch.\n \n >>> config = PyTorchFutureConfig()\n >>> config.set_overwrite_params(True)\n >>> config.set_swap_params(False)\n ...
[ { "from": "user", "value": "A warehouse manages its inventory using an automated system. Each product stored in the warehouse has a fixed spell duration after which it expires and must be discarded. Products can be grouped into batches, and each batch has a specific expiration duration calculated as the min...
[ { "from": "user", "value": "import heapq\nfrom typing import List\n\ndef dijkstra_shortest_paths(city: List[List[int]], start: int) -> List[int]:\n \"\"\" Calculate the shortest paths from the start vertex to all other vertices\n using Dijkstra's algorithm.\n\n :param city: 2D list representing the...
[ { "from": "user", "value": "### Matrix Column Sum\n\n#### Problem Statement\n\nYou are given a two-dimensional list (matrix) of integers. Your task is to write a function that calculates the sum of each column in the matrix and returns a list with the sums in the order of the columns.\n\nImplement a functio...
[ { "from": "user", "value": "def factorial(n):\n \"\"\"\n Calculate the factorial of a number using a for loop. The function takes one argument which is a non-negative integer. If the input is not valid, it returns \"Invalid input\".\n\n >>> factorial(5) # 5! = 5 * 4 * 3 * 2 * 1\n 120\n >>> f...
[ { "from": "user", "value": "def minimum_sum_after_split_and_reverse(T: int, test_cases: List[Tuple[int, List[int]]]) -> List[int]:\n \"\"\" \n Find the minimum sum of the elements of array A after performing \n the specified split and reverse operations once per each test case.\n \n Parameter...
[ { "from": "user", "value": "### Coding Assessment Question\n\nIn this assessment, you are required to solve a problem by implementing an efficient algorithm that calculates the minimum number of operations needed to convert one string into another.\n\n**Scenario**:\nYou are given two strings, `s1` and `s2`....
[ { "from": "user", "value": "You are given a list of integers representing the heights of buildings in a cityscape where the width of each building is 1. It is raining, and you need to determine how much water can be trapped between the buildings after it rains. Implement a function `trapRainWater(int[] heig...
[ { "from": "user", "value": "Create a function that takes a list of strings and returns the string with the highest number of unique characters. If there is a tie, return the string that appears first in the list. Additionally, if the list is empty, return an empty string." }, { "from": "assistant", ...
[ { "from": "user", "value": "def has_cycle(n: int, edges: list[tuple[int, int]]) -> bool:\n \"\"\"\n Implement Graph Cycle Detection using Disjoint Set Union (Union-Find).\n \n Args:\n - n: An integer representing the number of vertices in the graph.\n - edges: A list of tuples where each t...
[ { "from": "user", "value": "def longest_arithmetic_subarray(arr: List[int]) -> int:\n \"\"\" Returns the length of the longest subarray where the difference between every two consecutive elements is the same.\n >>> longest_arithmetic_subarray([1, 4, 7, 10, 13, 16])\n 6\n >>> longest_arithmetic_s...
[ { "from": "user", "value": "import random\n\ndef generate_random_integer() -> int:\n \"\"\"\n Returns a random integer between 1 and 10 inclusive.\n \"\"\"\n pass # Implement the function here\n\n# Unit tests\ndef test_generate_random_integer_within_range():\n for _ in range(100): # Run the ...
[ { "from": "user", "value": "A bakery is keeping track of their daily sales which are stored in a list where each element represents the number of pastries sold for each type of pastry. They want to know how many types of pastries reached or exceeded a sales target `T` for the day.\n\nWrite a function `count...
[ { "from": "user", "value": "def find_winner(n, k, array):\n \"\"\" Determines the winner of the game given the parameters.\n >>> find_winner(5, 2, [1, 2, 3, 4, 5]) \"Ben\"\n >>> find_winner(6, 3, [1, 2, 3, 4, 5, 6]) \"Susan\"\n \"\"\"\n\n# Unit Tests\ndef test_find_winner_case_1():\n assert f...
[ { "from": "user", "value": "def rearrange_items_on_shelves(n: int, items: List[int]) -> List[int]:\n \"\"\"\n Rearranges the items on the shelves so that no shelf has more items than any shelf to its right.\n \n Parameters:\n n (int): The number of shelves.\n items (list of int): The numbe...
[ { "from": "user", "value": "def max_sum_subarray(arr, k):\n \"\"\" Finds the maximum sum of any contiguous subarray of size k.\n >>> max_sum_subarray([1, 2, 3, 4, 5, 6, 7, 8], 3) 21\n >>> max_sum_subarray([5], 1) 5\n >>> max_sum_subarray([-1, -2, -3, -4, -5], 2) -3\n >>> max_sum_subarray([2, ...
[ { "from": "user", "value": "I need to write a Python function that finds the length of the longest strictly increasing subsequence in a given list of integers. Can you provide a detailed solution with an explanation?" }, { "from": "assistant", "value": "<think>\nAlright, so I have to write a Pyt...
[ { "from": "user", "value": "Given a number n, return an array containing the first n Catalan numbers. Catalan numbers form a sequence of natural numbers with significant applications in combinatorial mathematics. The n-th Catalan number can be computed using the formula:\n\n\\[ \\text{C}_n = \\frac{(2n)!}{(...
[ { "from": "user", "value": "Write a python function to create a dictionary that contains the counts of characters in a given string." }, { "from": "assistant", "value": "<think>\nOkay, so I need to write a Python function that creates a dictionary. The dictionary should count how many times each...
[ { "from": "user", "value": "Petya loves riding her bicycle. She has a new bicycle and a route she wants to take that visits exactly n landmarks. For each landmark, Petya knows the difficulty of reaching that landmark from her starting position. She can choose to visit the landmarks in any order. However, Pe...
[ { "from": "user", "value": "def find_primes_less_than(n: int) -> list:\n \"\"\" Returns a list of prime numbers less than n.\n >>> find_primes_less_than(10)\n [2, 3, 5, 7]\n >>> find_primes_less_than(20)\n [2, 3, 5, 7, 11, 13, 17, 19]\n >>> find_primes_less_than(2)\n []\n >>> find_pr...
[ { "from": "user", "value": "def is_robot_back(n: int, instructions: str) -> str:\n \"\"\"\n Determines if the robot returns to the initial starting point after completing the sequence of instructions.\n\n :param n: int, the number of instructions\n :param instructions: str, a string of length n ...
[ { "from": "user", "value": "Given a matrix of size m x n, where each cell is either '0' (empty) or '1' (occupied), your task is to find the largest square containing only '1's and return its area.\n\nExample 1:\n\nInput: \n[\n ['1', '0', '1', '0', '0'],\n ['1', '0', '1', '1', '1'],\n ['1', '1', '1', '1', '1...
[ { "from": "user", "value": "Mr. Smith is an avid coder and a puzzle enthusiast. One day, he stumbled upon a unique type of game where he needs to determine if a given sequence of brackets is valid. A sequence of brackets is considered valid if every opening bracket has a corresponding closing bracket in the...
[ { "from": "user", "value": "def calculate_teams_and_day_off(n: int) -> (int, int):\n \"\"\"\n Given a number of employees, return the number of complete teams of 3 and the number of employees left without a team.\n\n Parameters:\n n (int): Total number of employees\n\n Returns:\n tuple: A ...
[ { "from": "user", "value": "You are required to write a function called `decision_tree_classifier` that trains a Decision Tree classifier using the `sklearn` library and returns the accuracy of the model on the test data. The function should take as input a dataframe (`df`) with the last column as the targe...
[ { "from": "user", "value": "def count_distinct_identifiers(product_ids):\n \"\"\"\n Determines the number of unique product identifiers in the given list.\n \n Parameters:\n product_ids (list): A list of integers representing product identifiers.\n\n Returns:\n int: The number of distin...
[ { "from": "user", "value": "Write a program that takes a list of integers as input and returns the maximum and minimum values in the list. Your program should not use any built-in functions or methods for finding the maximum and minimum values, such as max() or min(). Instead, you should implement your own ...
[ { "from": "user", "value": "import seaborn.objects as so\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndef plot_student_performance(student_grades: pd.DataFrame):\n \"\"\" \n This function takes in a dataset of student grades and creates two line plots:\n 1. Relative performance of stude...
[ { "from": "user", "value": "def optimized_factorial_iter(n: int, mod: int = None) -> int:\n \"\"\" Calculate the factorial of a non-negative integer n iteratively.\n If mod is provided, return the factorial % mod.\n \n >>> optimized_factorial_iter(5)\n 120\n >>> optimized_factorial_iter(5,...
[ { "from": "user", "value": "Write a Python function that takes a list of integers and returns the maximum sum of a contiguous subarray within the given list. This is known as Kadane's Algorithm. Implement this function and provide a test case to verify its correctness." }, { "from": "assistant", ...
[ { "from": "user", "value": "def min_value(expression: str) -> int:\n \"\"\"Return the minimum value that can be obtained by adding parentheses in any order to the expression.\n\n >>> min_value(\"3\") == 3\n >>> min_value(\"1+2+3\") == 6\n >>> min_value(\"2*3*4\") == 24\n >>> min_value(\"2+3*4...
[ { "from": "user", "value": "def calculate_medals(t, test_cases):\n \"\"\"\n Calculate the number of Gold, Silver, and Bronze medals for each test case.\n \n Parameters:\n t (int): Number of test cases.\n test_cases (list): List of tuples, where each tuple contains three integers\n ...
[ { "from": "user", "value": "Write a function that takes a string `s` as input and returns `True` if it is a palindrome and `False` otherwise. A string is considered a palindrome if it reads the same backward as forward, ignoring spaces, capitalization, and non-alphanumeric characters.\n\nAssume: \n\n1. The ...
[ { "from": "user", "value": "class LRUCache:\n \"\"\"\n Design a Cache system that follows the Least Recently Used (LRU) policy without using any built-in libraries.\n \n A Cache is a data structure that stores a subset of elements from a larger data set, so future requests for those elements are...
[ { "from": "user", "value": "def sort_by_second_item(tuples_list):\n \"\"\"\n Sorts a list of tuples based on the second item of each tuple.\n \n Parameters:\n tuples_list (list): A list of tuples.\n \n Returns:\n list: A list of tuples sorted by the second item.\n \n >>> sort_b...
[ { "from": "user", "value": "Create a function that accepts two integers (x and y) as input and returns the sum of the numbers in their binary representations where each bit is the product of the corresponding bits of x and y. This operation is known as the bitwise AND operation before conversion." }, { ...
[ { "from": "user", "value": "#### Broadcasting Compatibility Checker\n\n**Objective:**\nThe goal of this assessment is to write a function that determines whether two tensors can be broadcast together as per PyTorch's broadcasting rules and to calculate the resulting size of the broadcasted tensors if they a...
[ { "from": "user", "value": "from typing import List, Tuple\n\ndef total_sales(sales_data: List[Tuple[int, int]], product_id: int) -> int:\n \"\"\" Returns the total quantity sold for the specified product ID.\n \n Args:\n sales_data (List[Tuple[int, int]]): The list of sales records as tuples (p...
[ { "from": "user", "value": "## Problem Description\n\nYou are given a paragraph of text which may contain a mix of alphabets, numbers, and punctuation marks. The task is to develop a Python function that extracts and returns the longest word in the given paragraph. In case there are multiple words of the sa...
[ { "from": "user", "value": "def characterReplacement(s: str, k: int) -> int:\n \"\"\"\n Returns the length of the longest substring containing the same letter you\n can achieve after performing the replacement operations.\n\n :param s: String of length n\n :param k: Maximum number of replacem...
[ { "from": "user", "value": "def total_expense(test_cases):\n \"\"\"\n Calculate the total expenses for multiple groups of friends each with different contributions.\n\n Parameters:\n test_cases (list): A list of tuples, each containing an integer (number of friends) \n and ...
[ { "from": "user", "value": "from datetime import date, time, datetime\n\ndef advanced_datetime_operations(year: int, month: int, day: int, hour: int, minute: int, second: int, usecond: int) -> dict:\n \"\"\" Perform advanced manipulations and extractions on date and time components.\n >>> result = adv...
[ { "from": "user", "value": "### Question: Develop a Simple Text Analysis Tool\n\n#### Context\nText analysis is an essential aspect of natural language processing, where words and their frequencies in a document are often analyzed to understand better the document's content. This task requires implementing ...
[ { "from": "user", "value": "from typing import List\n\ndef sumOfSubarrayMinimums(arr: List[int]) -> int:\n \"\"\"Given an array of integers arr, find the sum of all possible subarrays' minimum values.\n Return that sum modulo 10^9 + 7.\n\n >>> sumOfSubarrayMinimums([3, 1, 2, 4])\n 17\n >>> su...
[ { "from": "user", "value": "Create a function that takes a list of integers and returns a list of -1s. The function should be named \"list_of_negatives\" and should accept a parameter \"num_list\" which is the list of integers." }, { "from": "assistant", "value": "<think>\nOkay, I need to create...
[ { "from": "user", "value": "You are given a list of unique integers `nums` that contains elements ranging from `1` to `n` (both inclusive) in random order. Your task is to **reorder** the elements in `nums` such that all even-indexed positions (`0, 2, 4, ...`) contain even integers and all odd-indexed posit...
[ { "from": "user", "value": "def max_projects_completed(N: int, durations: List[int], start_times: List[int], T: int) -> int:\n \"\"\" \n Find the maximum number of projects that can be completed within the total time limit.\n\n >>> max_projects_completed(5, [2, 1, 3, 2, 2], [1, 2, 1, 3, 0], 5)\n ...
[ { "from": "user", "value": "I have created a linked list of boxes with weights. I have also created a function to find minimum weight box along with its index in the list. I need to create a function to update the minimum weight box's weight and return it along with its index. \n\nHere is the code I have so...
[ { "from": "user", "value": "class BoundingBox:\n def __init__(self, x1, y1, x2, y2):\n self.x1 = x1\n self.y1 = y1\n self.x2 = x2\n self.y2 = y2\n\n def get_area(self):\n return (self.x2 - self.x1) * (self.y2 - self.y1)\n\n def get_intersection(self, other):\n ...
[ { "from": "user", "value": "def maximum_difference(nums):\n \"\"\"\n Given a 0-indexed integer array `nums`, return the maximum difference between \n any pair of indices (i, j) such that i < j and nums[i] < nums[j]. If no such \n pair exists, return -1.\n\n >>> maximum_difference([7, 1, 5, 4]...
[ { "from": "user", "value": "Given an array of integers `nums`, return the **running sum** of `nums`. The running sum of an array is defined as `runningSum[i] = sum(nums[0]…nums[i])`. Return the array `runningSum` that contains the running sum of `nums` for each index `i`." }, { "from": "assistant", ...
[ { "from": "user", "value": "from typing import List, Tuple\n\ndef max_beauty(T: int, test_cases: List[Tuple[int, int, List[int], List[int]]]) -> List[int]:\n \"\"\"\n Determine the maximum beauty Alex can achieve without exceeding the space constraint.\n \n There are T test cases.\n For each ...
[ { "from": "user", "value": "### Longest Consecutive Subsequence in an Array\n\nGiven an unsorted array of integers, write a function to find the length of the longest consecutive elements sequence. The sequence must be consecutive and increasing, but the elements do not need to be sequentially adjacent in t...
[ { "from": "user", "value": "You are given an undirected graph with `n` nodes labeled from `0` to `n-1` represented as an edge list `edges` where `edges[i] = [u_i, v_i]` denotes an edge between nodes `u_i` and `v_i`. Additionally, you are provided with a 2D integer array `restricted` where `restricted[j]` de...
[ { "from": "user", "value": "John is an avid collector and loves to arrange his collectibles in specific patterns. Recently, he has been fascinated by the idea of mirror-image patterns. Given an integer n (1 ≤ n ≤ 100,000), he wants to form a string of length 2n that is a palindrome and consists of only the ...
[ { "from": "user", "value": "Write a python function to return True if the list is sorted, categorized into ascending and descending. A list is considered sorted if it is monotonically increasing or decreasing. A list that is not monotonic is not considered sorted." }, { "from": "assistant", "val...
[ { "from": "user", "value": "def check_sorted_books(rows):\n \"\"\"\n Determines if each row of books is sorted by height in non-decreasing order.\n\n :param rows: list of lists, each inner list contains the number of books followed by the heights of the books\n :return: list of strings \"YES\" o...
[ { "from": "user", "value": "### Scenario\nYou have been contracted by an online marketplace platform to develop a feature that helps users identify the best time to buy products based on historical price trends. The feature should analyze a list of daily prices for a product and recommend the maximum possib...
[ { "from": "user", "value": "def min_increments_to_make_unique(nums: List[int]) -> int:\n \"\"\"\n Returns the minimum number of increments needed to make all elements of the array pairwise distinct.\n >>> min_increments_to_make_unique([1, 2, 2]) == 1\n >>> min_increments_to_make_unique([3, 2, 1,...
[ { "from": "user", "value": "def highest_and_lowest_temperatures(temperatures: List[float]) -> Tuple[float, float]:\n \"\"\" Calculate the highest and lowest temperatures in a list of daily temperature readings in Celsius.\n \n Arguments:\n temperatures -- list of daily temperature readings in Ce...
[ { "from": "user", "value": "Write a code that prints the following output:\n\"Hello, world!\"\n\"Currently handling request from IP address: 192.168.1.1\"\n\"Current date and time: 2022-01-01 00:00:00\"\n(given the simulated IP address and date/time)\n\n```python\nimport socket\nfrom datetime import datetim...
[ { "from": "user", "value": "def filter_strings_starting_with_a(strings: List[str]) -> List[str]:\n \"\"\"\n Filters the list of strings and returns only the strings that start with the letter 'A'.\n \n >>> filter_strings_starting_with_a(['Apple', 'Banana', 'Avocado', 'berry']) == ['Apple', 'Avoc...
[ { "from": "user", "value": "def sum_of_squares(n: int) -> int:\n \"\"\"Create a function that takes an integer `n` as input and returns the sum of the squares of the first `n` natural numbers.\n \n >>> sum_of_squares(0) == 0\n >>> sum_of_squares(1) == 1\n >>> sum_of_squares(5) == 55\n >>> ...
[ { "from": "user", "value": "def rotate_matrix_90_clockwise(matrix):\n \"\"\"\n Rotates the given n x n matrix by 90 degrees clockwise.\n\n :param matrix: List of lists, where each inner list represents a row of the matrix.\n :return: The rotated matrix as a list of lists.\n \"\"\"\n pass\n...
[ { "from": "user", "value": "def extract_chunks(file_path: str, chunk_ids: list) -> dict:\n \"\"\"\n Reads through a file in EA IFF 85 format and extracts data from chunks with specific IDs.\n\n Args:\n - file_path (str): Path to the EA IFF 85 file.\n - chunk_ids (list): List of 4-byte chunk I...
[ { "from": "user", "value": "Write a function `is_palindrome` that checks if a given string is a palindrome.\n\n### Notes:\n\n- Return `nil` or `None` for non-string inputs.\n- Ignore case and non-alphanumeric characters while checking for palindromes.\n- Return `True` for an empty string as it is considered...
[ { "from": "user", "value": "def max_sum_subarray(arr, k):\n \"\"\"\n Calculate the maximum sum achievable by any subarray of length `k`.\n \n :param arr: List of integers\n :param k: Length of subarray for which to calculate max sum\n :return: Maximum sum of any subarray of length `k`\n ...
[ { "from": "user", "value": "You are a security expert tasked with implementing a simplified version of a secure communication protocol using the Diffie-Hellman key exchange method. Your goal is to create a Python function that performs the following:\n\n1. Generates private and public keys for two entities,...
[ { "from": "user", "value": "Write a function that takes an array of integers and an integer `n` as inputs and returns a new array which is the original array rotated to the right by `n` positions. For example, given the array `[1, 2, 3, 4, 5]` and `n = 2`, the function should return `[4, 5, 1, 2, 3]`. \n\nC...
[ { "from": "user", "value": "def countConsonants(s: str) -> int:\n \"\"\"\n Complete the function that counts the number of consonants in the given string and returns the count.\n\n Note:\n - Consider consonants to be all alphabetic characters except 'a', 'e', 'i', 'o', 'u', both uppercase and lo...
[ { "from": "user", "value": "### Context\nYou are given an array of integers that represents the heights of buildings in a row. You are required to solve a problem that involves finding special integer sequences within this array. This problem will test your ability to utilize advanced data structures and al...
[ { "from": "user", "value": "def longest_palindromic_subsequence(S: str) -> int:\n \"\"\" \n Returns the length of the longest palindromic subsequence in string S.\n >>> longest_palindromic_subsequence(\"bbbab\")\n 4\n >>> longest_palindromic_subsequence(\"cbbd\")\n 2\n \"\"\"\n\nfrom so...
[ { "from": "user", "value": "def findSecondLargest(numbers):\n \"\"\"\n Finds the second largest unique number in a given list of integers.\n If there is no such number, returns None.\n >>> findSecondLargest([1, 2, 3, 4, 5]) 4\n >>> findSecondLargest([5, 5, 5, 5, 5]) None\n >>> findSecondLa...
[ { "from": "user", "value": "You are given a rectangular n x m grid filled with non-negative integers. Each cell of the grid has a value which represents the amount of gold in that cell. A miner is to start from the top-left cell of the grid and can only move either right or down, at each step, until they re...
[ { "from": "user", "value": "def inventory_management(inventory, command, item=None):\n \"\"\"\n Manages the inventory of an online store based on the given command.\n \n Parameters:\n inventory (list): The list of items in the inventory.\n command (str): The command to execute ('add', 'upd...
[ { "from": "user", "value": "from typing import List\n\ndef maxTreesCut(n: int, heights: List[int]) -> int:\n \"\"\"\n Determines the maximum number of trees that can be cut down to make the remaining heights\n form a strictly increasing sequence.\n\n Parameters:\n n (int): The number of trees...
[ { "from": "user", "value": "def is_subsequence(str1: str, str2: str) -> bool:\n \"\"\"\n Checks if str2 is a subsequence of str1.\n\n Parameters:\n str1 (str): The original string.\n str2 (str): The string to check as a subsequence.\n\n Returns:\n bool: True if str2 is a subsequence of ...
[ { "from": "user", "value": "def is_palindrome(s: str) -> bool:\n \"\"\"\n Create a function that takes a string as input and returns True if the string is a palindrome (i.e., it reads the same forward and backward), and False otherwise. A palindrome ignores case and spaces.\n >>> is_palindrome(\"ma...
[ { "from": "user", "value": "You are given a wooden board of dimensions `w` by `h`. The board can be cut into two smaller rectangles by making one horizontal or one vertical cut. You need to determine the maximum possible area of a smaller rectangle you can get after making exactly one cut on the board.\n\nI...
[ { "from": "user", "value": "Write a python function to find the number of distinct prime factors of a given number. For example, the number 12 has prime factors 2, 2, and 3, so it has 2 distinct prime factors." }, { "from": "assistant", "value": "<think>\nOkay, I need to write a Python function ...
[ { "from": "user", "value": "Write a python function to return the maximum absolute difference between two elements in an array. The function should work for any array of integers, not just sorted arrays. What are the time and space complexity of the function?" }, { "from": "assistant", "value": ...
[ { "from": "user", "value": "Given a 2D grid of size n x m, you are initially positioned at the top-left corner (1, 1). Your goal is to reach the bottom-right corner (n, m) by moving only right or down. However, the grid has obstacles, represented by cells with a value of -1, which you cannot pass through. C...
[ { "from": "user", "value": "def find_stock_price_index(stock_data: List[tuple], target_price: float) -> int:\n \"\"\" Performs interpolation search to find the target_price in the stock_data.\n \n Parameters:\n stock_data (List[tuple]): List of tuples containing date and price, sorted by pri...
[ { "from": "user", "value": "You are given a **0-indexed** integer array `heights` representing the height of buildings in a city. The array satisfies the following properties: \n1. `heights.length` is odd.\n2. There is a unique index `i` such that `heights[i]` is the maximum height in the array.\n\nA **peak...
[ { "from": "user", "value": "Given an array of integers, write a function that checks if there are duplicate elements within a specific range `k`. More formally, given an array `nums` and an integer `k`, determine if there are two distinct indices `i` and `j` in the array such that `nums[i] == nums[j]` and t...