{"name": "reverse_words_preserve_spaces", "topic": "string manipulation", "prompt": "def reverse_words_preserve_spaces(text: str) -> str:\n \"\"\"\n Reverses the order of words in a string while preserving the exact position and quantity of all whitespace characters.\n\n A 'word' is defined as a contiguous sequence of non-whitespace characters.\n Whitespace characters are defined by str.isspace().\n\n For example:\n - reverse_words_preserve_spaces(\"Hello World\") == \"World Hello\"\n - reverse_words_preserve_spaces(\" leading spaces \") == \" spaces leading \"\n - reverse_words_preserve_spaces(\"multiple spaces between\") == \"between spaces multiple\"\n - reverse_words_preserve_spaces(\"singleword\") == \"singleword\"\n - reverse_words_preserve_spaces(\"\") == \"\"\n - reverse_words_preserve_spaces(\" \") == \" \"\n \"\"\"", "solution": "def reverse_words_preserve_spaces(text: str) -> str:\n if not text:\n return \"\"\n\n words = []\n whitespaces = []\n current_word = []\n current_whitespace = []\n\n for char in text:\n if char.isspace():\n if current_word:\n words.append(\"\".join(current_word))\n current_word = []\n current_whitespace.append(char)\n else:\n if current_whitespace:\n whitespaces.append(\"\".join(current_whitespace))\n current_whitespace = []\n current_word.append(char)\n\n if current_word:\n words.append(\"\".join(current_word))\n if current_whitespace:\n whitespaces.append(\"\".join(current_whitespace))\n \n # Handle cases where the string starts/ends with whitespace or words\n # The key is to correctly interleave reversed words and original whitespaces\n \n reversed_words = words[::-1]\n result_parts = []\n \n word_idx = 0\n whitespace_idx = 0\n \n # Determine if text starts with a word or whitespace\n starts_with_word = bool(words) and text.strip() and text.find(words[0]) == 0\n\n while word_idx < len(reversed_words) or whitespace_idx < len(whitespaces):\n if starts_with_word:\n if word_idx < len(reversed_words):\n result_parts.append(reversed_words[word_idx])\n word_idx += 1\n if whitespace_idx < len(whitespaces):\n result_parts.append(whitespaces[whitespace_idx])\n whitespace_idx += 1\n else: # Starts with whitespace\n if whitespace_idx < len(whitespaces):\n result_parts.append(whitespaces[whitespace_idx])\n whitespace_idx += 1\n if word_idx < len(reversed_words):\n result_parts.append(reversed_words[word_idx])\n word_idx += 1\n \n return \"\".join(result_parts)", "tests": ["assert reverse_words_preserve_spaces(\"Hello World\") == \"World Hello\"", "assert reverse_words_preserve_spaces(\" leading spaces \") == \" spaces leading \"", "assert reverse_words_preserve_spaces(\"multiple spaces between\") == \"between spaces multiple\"", "assert reverse_words_preserve_spaces(\"singleword\") == \"singleword\"", "assert reverse_words_preserve_spaces(\"\") == \"\"", "assert reverse_words_preserve_spaces(\" \") == \" \"", "assert reverse_words_preserve_spaces(\" a b c \") == \" c b a \"", "assert reverse_words_preserve_spaces(\"a b c\") == \"c b a\""]} {"name": "decode_run_length_string", "topic": "string manipulation", "prompt": "def decode_run_length_string(encoded_string: str) -> str:\n \"\"\"\n Decodes a run-length encoded string. The encoded string consists of alternating\n numbers (representing the count) and characters. For example, '3a2b1c' decodes to 'aaabbc'.\n \n Assumptions:\n - The input string will always be valid, following the 'number-character' pattern.\n - Numbers will be positive integers.\n - The string will not be empty.\n - Numbers and characters will alternate, starting with a number.\n - The characters will be single ASCII letters.\n \n Args:\n encoded_string: The run-length encoded string.\n\n Returns:\n The decoded string.\n \"\"\"", "solution": "def decode_run_length_string(encoded_string: str) -> str:\n decoded_parts = []\n i = 0\n n = len(encoded_string)\n while i < n:\n count_str = ''\n while i < n and encoded_string[i].isdigit():\n count_str += encoded_string[i]\n i += 1\n \n if count_str:\n count = int(count_str)\n if i < n and not encoded_string[i].isdigit(): # Ensure it's a character\n char = encoded_string[i]\n decoded_parts.append(char * count)\n i += 1\n # If it's a digit here, it's an error in parsing, but per assumptions, this won't happen.\n # If count_str is empty, it means we started with a character, which is against assumptions.\n\n return ''.join(decoded_parts)", "tests": ["assert decode_run_length_string('3a2b1c') == 'aaabbc'", "assert decode_run_length_string('10z') == 'zzzzzzzzzz'", "assert decode_run_length_string('1a1b1c1d1e') == 'abcde'", "assert decode_run_length_string('2x3y1z') == 'xxyyyz'", "assert decode_run_length_string('5A') == 'AAAAA'", "assert decode_run_length_string('1P2Q3R4S') == 'PQQRRRSSSS'"]} {"name": "decode_run_length", "topic": "string manipulation", "prompt": "def decode_run_length(encoded_string: str) -> str:\n \"\"\"\n Decodes a run-length encoded string. The encoding format is 'count_char', where 'count'\n is a positive integer representing the number of times 'char' appears consecutively.\n Counts can be multi-digit. The input string will always be valid, consisting of alternating\n numbers and single characters. There will be no empty counts or zero counts.\n\n For example:\n '3A2B1C' decodes to 'AAABBC'\n '10X' decodes to 'XXXXXXXXXX'\n '1A1B1C' decodes to 'ABC'\n \"\"\"", "solution": "def decode_run_length(encoded_string: str) -> str:\n decoded_parts = []\n current_number = []\n\n for char in encoded_string:\n if char.isdigit():\n current_number.append(char)\n else:\n if current_number:\n count = int(\"\".join(current_number))\n decoded_parts.append(char * count)\n current_number = []\n return \"\".join(decoded_parts)", "tests": ["assert decode_run_length('3A2B1C') == 'AAABBC'", "assert decode_run_length('10X') == 'XXXXXXXXXX'", "assert decode_run_length('1A1B1C') == 'ABC'", "assert decode_run_length('5Z') == 'ZZZZZ'", "assert decode_run_length('12A3B') == 'AAAAAAAAAAAABBB'", "assert decode_run_length('1H1E1L1L1O') == 'HELLO'"]} {"name": "decode_run_length_918", "topic": "string manipulation", "prompt": "def decode_run_length(encoded_string: str) -> str:\n \"\"\"\n Decodes a run-length encoded string. The encoding format is a sequence of\n 'count' followed by 'character'. 'count' is a digit or sequence of digits\n representing the number of times 'character' should be repeated.\n 'character' is a single non-digit character.\n\n For example:\n '3A2B1C' decodes to 'AAABB C'\n '10Z' decodes to 'ZZZZZZZZZZ'\n '1A1B1C' decodes to 'ABC'\n '2X3Y' decodes to 'XXYYY'\n '5@' decodes to '@@@@@'\n\n Assumptions:\n - The input string will always be valid run-length encoding.\n - Counts will always be positive integers.\n - Characters will always be single non-digit characters.\n - The input string will not be empty.\n \"\"\"", "solution": "def decode_run_length(encoded_string: str) -> str:\n decoded_parts = []\n i = 0\n while i < len(encoded_string):\n count_str = \"\"\n while encoded_string[i].isdigit():\n count_str += encoded_string[i]\n i += 1\n count = int(count_str)\n char = encoded_string[i]\n decoded_parts.append(char * count)\n i += 1\n return \"\".join(decoded_parts)", "tests": ["assert decode_run_length('3A2B1C') == 'AAABBC'", "assert decode_run_length('10Z') == 'ZZZZZZZZZZ'", "assert decode_run_length('1A1B1C') == 'ABC'", "assert decode_run_length('2X3Y') == 'XXYYY'", "assert decode_run_length('5@') == '@@@@@'", "assert decode_run_length('1P2Q3R4S') == 'PQQRRRSSSS'"]} {"name": "reverse_words_preserve_spaces_358", "topic": "string manipulation", "prompt": "def reverse_words_preserve_spaces(text: str) -> str:\n \"\"\"\n Reverses the order of words in a string while preserving the exact position\n and sequence of all whitespace characters.\n\n A 'word' is defined as a contiguous sequence of non-whitespace characters.\n Multiple spaces between words should remain exactly as they are. Leading,\n trailing, and internal multiple spaces should also be preserved.\n\n For example:\n - reverse_words_preserve_spaces(\"Hello World\") == \"World Hello\"\n - reverse_words_preserve_spaces(\" Python is fun \") == \" fun is Python \"\n - reverse_words_preserve_spaces(\"SingleWord\") == \"SingleWord\"\n - reverse_words_preserve_spaces(\" \") == \" \"\n - reverse_words_preserve_spaces(\"\") == \"\"\n \"\"\"", "solution": "def reverse_words_preserve_spaces(text: str) -> str:\n if not text:\n return \"\"\n\n words = []\n spaces = []\n current_word = []\n current_space = []\n\n for char in text:\n if char.isspace():\n if current_word:\n words.append(\"\".join(current_word))\n current_word = []\n current_space.append(char)\n else:\n if current_space:\n spaces.append(\"\".join(current_space))\n current_space = []\n current_word.append(char)\n \n if current_word:\n words.append(\"\".join(current_word))\n if current_space:\n spaces.append(\"\".join(current_space))\n\n if not words and spaces:\n return text\n if not words and not spaces:\n return \"\"\n\n words.reverse()\n\n result = []\n word_idx = 0\n space_idx = 0\n \n # Determine if text starts with word or space\n starts_with_space = False\n if text and text[0].isspace():\n starts_with_space = True\n\n if starts_with_space:\n # Start with a space block\n if space_idx < len(spaces): \n result.append(spaces[space_idx])\n space_idx += 1\n\n while word_idx < len(words) or space_idx < len(spaces):\n if word_idx < len(words):\n result.append(words[word_idx])\n word_idx += 1\n \n if space_idx < len(spaces):\n result.append(spaces[space_idx])\n space_idx += 1\n \n # Special handling for cases like \"word\" (no spaces) or \" \" (only spaces)\n if not spaces and len(words) == 1 and not text[0].isspace():\n return text\n \n return \"\".join(result)", "tests": ["assert reverse_words_preserve_spaces(\"Hello World\") == \"World Hello\"", "assert reverse_words_preserve_spaces(\" Python is fun \") == \" fun is Python \"", "assert reverse_words_preserve_spaces(\"SingleWord\") == \"SingleWord\"", "assert reverse_words_preserve_spaces(\" \") == \" \"", "assert reverse_words_preserve_spaces(\"\") == \"\"", "assert reverse_words_preserve_spaces(\" one two three \") == \" three two one \"", "assert reverse_words_preserve_spaces(\" a b c \") == \" c b a \""]} {"name": "reverse_words_preserve_spaces_433", "topic": "string manipulation", "prompt": "def reverse_words_preserve_spaces(text: str) -> str:\n \"\"\"\n Reverses the order of words in a string while preserving all whitespace characters\n (including leading, trailing, and multiple consecutive spaces) in their original positions.\n\n A 'word' is defined as any sequence of non-whitespace characters.\n Whitespace characters are defined by str.isspace().\n\n For example:\n - reverse_words_preserve_spaces(\"Hello World\") == \"World Hello\"\n - reverse_words_preserve_spaces(\" leading spaces \") == \" spaces leading \"\n - reverse_words_preserve_spaces(\"one two three\") == \"three two one\"\n - reverse_words_preserve_spaces(\" singleword \") == \" singleword \"\n - reverse_words_preserve_spaces(\"\") == \"\"\n - reverse_words_preserve_spaces(\" \") == \" \"\n \"\"\"", "solution": "def reverse_words_preserve_spaces(text: str) -> str:\n if not text:\n return \"\"\n\n # Split the string into words and space sequences\n parts = []\n current_part = []\n is_in_word = False\n\n for char in text:\n if char.isspace():\n if is_in_word:\n parts.append(\"\".join(current_part))\n current_part = []\n is_in_word = False\n current_part.append(char)\n else:\n if not is_in_word:\n if current_part:\n parts.append(\"\".join(current_part))\n current_part = []\n is_in_word = True\n current_part.append(char)\n \n if current_part:\n parts.append(\"\".join(current_part))\n\n words = []\n spaces = []\n \n for part in parts:\n if part and part[0].isspace():\n spaces.append(part)\n else:\n words.append(part)\n \n words.reverse()\n \n result_parts = []\n word_idx = 0\n space_idx = 0\n \n for part in parts:\n if part and part[0].isspace():\n result_parts.append(spaces[space_idx])\n space_idx += 1\n else:\n result_parts.append(words[word_idx])\n word_idx += 1\n \n return \"\".join(result_parts)", "tests": ["assert reverse_words_preserve_spaces(\"Hello World\") == \"World Hello\"", "assert reverse_words_preserve_spaces(\" leading spaces \") == \" spaces leading \"", "assert reverse_words_preserve_spaces(\"one two three\") == \"three two one\"", "assert reverse_words_preserve_spaces(\" singleword \") == \" singleword \"", "assert reverse_words_preserve_spaces(\"\") == \"\"", "assert reverse_words_preserve_spaces(\" \") == \" \"", "assert reverse_words_preserve_spaces(\"A B C D\") == \"D C B A\"", "assert reverse_words_preserve_spaces(\" a b c \") == \" c b a \""]} {"name": "rot13_cipher", "topic": "string manipulation", "prompt": "def rot13_cipher(text: str) -> str:\n \"\"\"\n Applies the ROT13 substitution cipher to the input string. \n \n ROT13 (\"rotate by 13 places\") is a simple letter substitution cipher that \n replaces a letter with the 13th letter after it in the alphabet. \n \n - Uppercase letters remain uppercase, and lowercase letters remain lowercase.\n - Non-alphabetic characters (numbers, symbols, spaces, etc.) are left unchanged.\n - The alphabet wraps around (e.g., 'A' becomes 'N', 'M' becomes 'Z', 'a' becomes 'n', 'm' becomes 'z').\n \n Examples:\n rot13_cipher(\"Hello, World!\") == \"Uryyb, Jbeyq!\"\n rot13_cipher(\"Python 3.9\") == \"Clguba 3.9\"\n rot13_cipher(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\") == \"NOPQRSTUVWXYZABCDEFGHIJKLM\"\n rot13_cipher(\"abcdefghijklmnopqrstuvwxyz\") == \"nopqrstuvwxyzabcdefghijklm\"\n \"\"\"", "solution": "def rot13_cipher(text: str) -> str:\n result = []\n for char in text:\n if 'a' <= char <= 'z':\n rotated_char = chr(((ord(char) - ord('a') + 13) % 26) + ord('a'))\n result.append(rotated_char)\n elif 'A' <= char <= 'Z':\n rotated_char = chr(((ord(char) - ord('A') + 13) % 26) + ord('A'))\n result.append(rotated_char)\n else:\n result.append(char)\n return ''.join(result)", "tests": ["assert rot13_cipher(\"Hello, World!\") == \"Uryyb, Jbeyq!\"", "assert rot13_cipher(\"Python 3.9 is fun!\") == \"Clguba 3.9 vf sha!\"", "assert rot13_cipher(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\") == \"NOPQRSTUVWXYZABCDEFGHIJKLM\"", "assert rot13_cipher(\"abcdefghijklmnopqrstuvwxyz\") == \"nopqrstuvwxyzabcdefghijklm\"", "assert rot13_cipher(\"123!@#$\") == \"123!@#$\"", "assert rot13_cipher(\"GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.\") == \"THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.\""]} {"name": "reverse_words_and_case", "topic": "string manipulation", "prompt": "def reverse_words_and_case(text: str) -> str:\n \"\"\"\n Reverses the order of words in a sentence and inverts the case of each character within each word.\n Words are separated by single spaces. Punctuation attached to words should be treated as part of the word.\n\n For example:\n - \"Hello World\" becomes \"wORLD hELLO\"\n - \"Python is FUN\" becomes \"fun IS pYTHON\"\n - \"Apples, are good.\" becomes \"GOOD. ARE aPPLES,\"\n - \"\" becomes \"\"\n - \"SingleWord\" becomes \"sINGLEwORD\"\n \"\"\"", "solution": "def reverse_words_and_case(text: str) -> str:\n if not text:\n return \"\"\n\n words = text.split(' ')\n reversed_words = []\n\n for word in words:\n reversed_words.append(word.swapcase())\n\n return ' '.join(reversed_words[::-1])", "tests": ["assert reverse_words_and_case(\"Hello World\") == \"wORLD hELLO\"", "assert reverse_words_and_case(\"Python is FUN\") == \"fun IS pYTHON\"", "assert reverse_words_and_case(\"Apples, are good.\") == \"GOOD. ARE aPPLES,\"", "assert reverse_words_and_case(\"\") == \"\"", "assert reverse_words_and_case(\"SingleWord\") == \"sINGLEwORD\"", "assert reverse_words_and_case(\"ONE two THREE\") == \"three TWO one\""]} {"name": "reverse_words_preserve_spaces_302", "topic": "string manipulation", "prompt": "def reverse_words_preserve_spaces(text: str) -> str:\n \"\"\"\n Reverses the order of words in a string while preserving the exact original spacing\n between words. Leading, trailing, and multiple internal spaces should remain as they are.\n\n A 'word' is defined as any sequence of non-space characters.\n\n For example:\n reverse_words_preserve_spaces(\" hello world \") == \" world hello \"\n reverse_words_preserve_spaces(\"one two three\") == \"three two one\"\n reverse_words_preserve_spaces(\"a\") == \"a\"\n reverse_words_preserve_spaces(\" \") == \" \"\n \"\"\"", "solution": "def reverse_words_preserve_spaces(text: str) -> str:\n if not text:\n return \"\"\n\n parts = []\n current_part = []\n is_space = text[0].isspace()\n\n for char in text:\n if char.isspace() == is_space:\n current_part.append(char)\n else:\n parts.append(\"\".join(current_part))\n current_part = [char]\n is_space = not is_space\n parts.append(\"\".join(current_part))\n\n result = []\n words = []\n spaces = []\n\n for part in parts:\n if part[0].isspace():\n spaces.append(part)\n else:\n words.append(part)\n\n words.reverse()\n\n word_idx = 0\n space_idx = 0\n\n if text[0].isspace():\n # Starts with space\n while space_idx < len(spaces) or word_idx < len(words):\n if space_idx < len(spaces):\n result.append(spaces[space_idx])\n space_idx += 1\n if word_idx < len(words):\n result.append(words[word_idx])\n word_idx += 1\n else:\n # Starts with word\n while word_idx < len(words) or space_idx < len(spaces):\n if word_idx < len(words):\n result.append(words[word_idx])\n word_idx += 1\n if space_idx < len(spaces):\n result.append(spaces[space_idx])\n space_idx += 1\n\n return \"\".join(result)", "tests": ["assert reverse_words_preserve_spaces(\" hello world \") == \" world hello \"", "assert reverse_words_preserve_spaces(\"one two three\") == \"three two one\"", "assert reverse_words_preserve_spaces(\"a\") == \"a\"", "assert reverse_words_preserve_spaces(\" \") == \" \"", "assert reverse_words_preserve_spaces(\"\") == \"\"", "assert reverse_words_preserve_spaces(\"first second third\") == \"third second first\"", "assert reverse_words_preserve_spaces(\" leading and trailing \") == \" trailing and leading \""]} {"name": "find_peak_elements", "topic": "list/array processing", "prompt": "def find_peak_elements(arr):\n \"\"\"\n Given a list of integers `arr`, find all \"peak\" elements and return them in a new list.\n A peak element is an element that is strictly greater than its neighbors.\n For elements at the boundaries (first or last), they only need to be greater than their single neighbor.\n\n An empty list should return an empty list.\n A list with one element should consider that element a peak.\n\n Examples:\n find_peak_elements([1, 2, 3, 2, 1]) == [3]\n find_peak_elements([1, 5, 2, 8, 3]) == [5, 8]\n find_peak_elements([10]) == [10]\n find_peak_elements([]) == []\n find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]\n \"\"\"", "solution": "def find_peak_elements(arr):\n if not arr:\n return []\n if len(arr) == 1:\n return [arr[0]]\n\n peaks = []\n n = len(arr)\n\n # Check first element\n if arr[0] > arr[1]:\n peaks.append(arr[0])\n\n # Check middle elements\n for i in range(1, n - 1):\n if arr[i] > arr[i-1] and arr[i] > arr[i+1]:\n peaks.append(arr[i])\n\n # Check last element\n if arr[n-1] > arr[n-2]:\n peaks.append(arr[n-1])\n\n return peaks", "tests": ["assert find_peak_elements([1, 2, 3, 2, 1]) == [3]", "assert find_peak_elements([1, 5, 2, 8, 3]) == [5, 8]", "assert find_peak_elements([10]) == [10]", "assert find_peak_elements([]) == []", "assert find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]", "assert find_peak_elements([5, 4, 3, 2, 1]) == [5]", "assert find_peak_elements([1, 2, 3, 4, 5]) == [5]"]} {"name": "find_peak_elements_346", "topic": "list/array processing", "prompt": "def find_peak_elements(nums: list[int]) -> list[int]:\n \"\"\"\n A peak element is an element that is strictly greater than its neighbors.\n Given an input list 'nums' of integers, return a list of all peak elements found in 'nums'.\n \n For elements at the boundaries (first or last element), consider only their single neighbor.\n If the list has only one element, that element is considered a peak.\n The returned list should maintain the order of appearance of the peak elements in 'nums'.\n\n Examples:\n find_peak_elements([1, 2, 3, 1]) == [3]\n find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]\n find_peak_elements([1]) == [1]\n find_peak_elements([5, 4, 3, 2, 1]) == [5]\n find_peak_elements([1, 2, 3, 4, 5]) == [5]\n \"\"\"", "solution": "def find_peak_elements(nums: list[int]) -> list[int]:\n peaks = []\n n = len(nums)\n\n if n == 0:\n return []\n if n == 1:\n return [nums[0]]\n\n for i in range(n):\n is_peak = False\n if i == 0: # First element\n if nums[i] > nums[i+1]:\n is_peak = True\n elif i == n - 1: # Last element\n if nums[i] > nums[i-1]:\n is_peak = True\n else: # Middle elements\n if nums[i] > nums[i-1] and nums[i] > nums[i+1]:\n is_peak = True\n \n if is_peak:\n peaks.append(nums[i])\n \n return peaks", "tests": ["assert find_peak_elements([1, 2, 3, 1]) == [3]", "assert find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]", "assert find_peak_elements([1]) == [1]", "assert find_peak_elements([5, 4, 3, 2, 1]) == [5]", "assert find_peak_elements([1, 2, 3, 4, 5]) == [5]", "assert find_peak_elements([]) == []", "assert find_peak_elements([10, 20, 15, 2, 23, 90, 67]) == [20, 90]", "assert find_peak_elements([7, 7, 7, 7, 7]) == []"]} {"name": "find_peak_elements_297", "topic": "list/array processing", "prompt": "def find_peak_elements(nums):\n \"\"\"\n Finds all 'peak elements' in a list of integers. A peak element is an element\n that is strictly greater than its neighbors. For elements at the ends of the list,\n only one neighbor needs to be considered. If an element has no neighbors (list of size 1),\n it is considered a peak.\n\n The function should return a list of peak elements in the order they appear in the input list.\n\n Args:\n nums: A list of integers.\n\n Returns:\n A list of integers representing the peak elements.\n\n Examples:\n find_peak_elements([1, 2, 3, 1]) == [3]\n find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]\n find_peak_elements([1]) == [1]\n find_peak_elements([]) == []\n find_peak_elements([5, 4, 3, 2, 1]) == [5]\n find_peak_elements([1, 2, 3, 4, 5]) == [5]\n \"\"\"", "solution": "def find_peak_elements(nums):\n \"\"\"\n Finds all 'peak elements' in a list of integers. A peak element is an element\n that is strictly greater than its neighbors. For elements at the ends of the list,\n only one neighbor needs to be considered. If an element has no neighbors (list of size 1),\n it is considered a peak.\n\n The function should return a list of peak elements in the order they appear in the input list.\n\n Args:\n nums: A list of integers.\n\n Returns:\n A list of integers representing the peak elements.\n\n Examples:\n find_peak_elements([1, 2, 3, 1]) == [3]\n find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]\n find_peak_elements([1]) == [1]\n find_peak_elements([]) == []\n find_peak_elements([5, 4, 3, 2, 1]) == [5]\n find_peak_elements([1, 2, 3, 4, 5]) == [5]\n \"\"\"\n n = len(nums)\n if n == 0:\n return []\n if n == 1:\n return [nums[0]]\n\n peaks = []\n\n # Check first element\n if nums[0] > nums[1]:\n peaks.append(nums[0])\n\n # Check middle elements\n for i in range(1, n - 1):\n if nums[i] > nums[i - 1] and nums[i] > nums[i + 1]:\n peaks.append(nums[i])\n\n # Check last element\n if nums[n - 1] > nums[n - 2]:\n peaks.append(nums[n - 1])\n\n return peaks", "tests": ["assert find_peak_elements([1, 2, 3, 1]) == [3]", "assert find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]", "assert find_peak_elements([1]) == [1]", "assert find_peak_elements([]) == []", "assert find_peak_elements([5, 4, 3, 2, 1]) == [5]", "assert find_peak_elements([1, 2, 3, 4, 5]) == [5]", "assert find_peak_elements([3, 2, 1, 2, 3]) == [3, 3]", "assert find_peak_elements([10, 20, 15, 2, 23, 90, 67]) == [20, 90]"]} {"name": "find_peak_elements_942", "topic": "list/array processing", "prompt": "def find_peak_elements(nums):\n \"\"\"\n Given a list of integers 'nums', find all 'peak elements' and return their indices.\n\n A peak element is an element that is greater than its neighbors. If an element has\n only one neighbor (i.e., it's at an end of the list), it is considered a peak if\n it's greater than that single neighbor.\n\n For example:\n - In [1, 2, 3, 1], 3 is a peak element (index 2).\n - In [1, 5, 2, 6, 3], 5 (index 1) and 6 (index 3) are peak elements.\n - In [3, 2, 1], 3 is a peak element (index 0).\n - In [1, 2, 3], 3 is a peak element (index 2).\n\n The input list 'nums' will contain at least one element.\n Duplicate values are possible, but a peak must be strictly greater than its neighbors.\n\n Args:\n nums (list[int]): The input list of integers.\n\n Returns:\n list[int]: A list of indices of all peak elements, in ascending order.\n \"\"\"", "solution": "def find_peak_elements(nums):\n \"\"\"\n Given a list of integers 'nums', find all 'peak elements' and return their indices.\n\n A peak element is an element that is greater than its neighbors. If an element has\n only one neighbor (i.e., it's at an end of the list), it is considered a peak if\n it's greater than that single neighbor.\n\n For example:\n - In [1, 2, 3, 1], 3 is a peak element (index 2).\n - In [1, 5, 2, 6, 3], 5 (index 1) and 6 (index 3) are peak elements.\n - In [3, 2, 1], 3 is a peak element (index 0).\n - In [1, 2, 3], 3 is a peak element (index 2).\n\n The input list 'nums' will contain at least one element.\n Duplicate values are possible, but a peak must be strictly greater than its neighbors.\n\n Args:\n nums (list[int]): The input list of integers.\n\n Returns:\n list[int]: A list of indices of all peak elements, in ascending order.\n \"\"\"\n n = len(nums)\n if n == 1:\n return [0]\n\n peak_indices = []\n\n for i in range(n):\n is_peak = False\n if i == 0: # First element\n if nums[i] > nums[i+1]:\n is_peak = True\n elif i == n - 1: # Last element\n if nums[i] > nums[i-1]:\n is_peak = True\n else: # Middle elements\n if nums[i] > nums[i-1] and nums[i] > nums[i+1]:\n is_peak = True\n \n if is_peak:\n peak_indices.append(i)\n \n return peak_indices", "tests": ["assert find_peak_elements([1, 2, 3, 1]) == [2]", "assert find_peak_elements([1, 5, 2, 6, 3]) == [1, 3]", "assert find_peak_elements([3, 2, 1]) == [0]", "assert find_peak_elements([1, 2, 3]) == [2]", "assert find_peak_elements([5]) == [0]", "assert find_peak_elements([1, 1, 1, 1]) == []", "assert find_peak_elements([1, 3, 2, 5, 4, 6, 0]) == [1, 3, 5]", "assert find_peak_elements([7, 6, 5, 4, 3, 2, 1]) == [0]", "assert find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [1, 5]"]} {"name": "find_kth_smallest_in_merged_sorted_lists", "topic": "list/array processing", "prompt": "def find_kth_smallest_in_merged_sorted_lists(list1: list[int], list2: list[int], k: int) -> int:\n \"\"\"\n Given two sorted lists of integers, `list1` and `list2`, and an integer `k`,\n find the k-th smallest element in the merged sorted list of `list1` and `list2`.\n\n You can assume that both `list1` and `list2` are already sorted in ascending order.\n The value of `k` will always be valid, meaning 1 <= k <= len(list1) + len(list2).\n\n Examples:\n find_kth_smallest_in_merged_sorted_lists([1, 3, 5], [2, 4, 6], 3) == 3\n find_kth_smallest_in_merged_sorted_lists([10, 20], [1, 5, 15], 1) == 1\n find_kth_smallest_in_merged_sorted_lists([1, 2], [3, 4], 4) == 4\n find_kth_smallest_in_merged_sorted_lists([], [7, 8, 9], 2) == 8\n \"\"\"", "solution": "def find_kth_smallest_in_merged_sorted_lists(list1: list[int], list2: list[int], k: int) -> int:\n p1, p2 = 0, 0\n current_val = 0\n\n while k > 0:\n if p1 < len(list1) and (p2 >= len(list2) or list1[p1] <= list2[p2]):\n current_val = list1[p1]\n p1 += 1\n elif p2 < len(list2) and (p1 >= len(list1) or list2[p2] < list1[p1]):\n current_val = list2[p2]\n p2 += 1\n k -= 1\n return current_val", "tests": ["assert find_kth_smallest_in_merged_sorted_lists([1, 3, 5], [2, 4, 6], 3) == 3", "assert find_kth_smallest_in_merged_sorted_lists([10, 20], [1, 5, 15], 1) == 1", "assert find_kth_smallest_in_merged_sorted_lists([1, 2], [3, 4], 4) == 4", "assert find_kth_smallest_in_merged_sorted_lists([], [7, 8, 9], 2) == 8", "assert find_kth_smallest_in_merged_sorted_lists([1, 2, 3, 4, 5], [], 5) == 5", "assert find_kth_smallest_in_merged_sorted_lists([1, 1, 1], [1, 1, 1], 6) == 1"]} {"name": "sort_by_frequency", "topic": "list/array processing", "prompt": "def sort_by_frequency(arr: list) -> list:\n \"\"\"\n Given a list of numbers, sort the list in increasing order of the frequency of each number.\n If two numbers have the same frequency, the one with the smaller value should come first.\n\n For example:\n sort_by_frequency([1, 1, 2, 2, 2, 3]) == [3, 1, 1, 2, 2, 2]\n Explanation: '3' appears once, '1' appears twice, '2' appears thrice.\n\n sort_by_frequency([2, 3, 1, 3, 2]) == [1, 2, 2, 3, 3]\n Explanation: '1' appears once. '2' appears twice. '3' appears twice. Since 2 < 3, '2' comes before '3'.\n\n The input list can be empty. If empty, return an empty list.\n \"\"\"", "solution": "from collections import Counter\n\ndef sort_by_frequency(arr: list) -> list:\n if not arr:\n return []\n\n counts = Counter(arr)\n\n # Sort based on frequency (primary key) and then value (secondary key)\n # The key for sorting is a tuple: (frequency, value)\n # Python's sort is stable, but we define the full ordering explicitly.\n sorted_arr = sorted(arr, key=lambda x: (counts[x], x))\n return sorted_arr", "tests": ["assert sort_by_frequency([1, 1, 2, 2, 2, 3]) == [3, 1, 1, 2, 2, 2]", "assert sort_by_frequency([2, 3, 1, 3, 2]) == [1, 2, 2, 3, 3]", "assert sort_by_frequency([5, 5, 5, 2, 2, 1, 1, 1, 1, 4]) == [4, 2, 2, 5, 5, 5, 1, 1, 1, 1]", "assert sort_by_frequency([]) == []", "assert sort_by_frequency([7]) == [7]", "assert sort_by_frequency([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]", "assert sort_by_frequency([9, 9, 8, 8, 7, 7, 7, 6]) == [6, 8, 8, 9, 9, 7, 7, 7]"]} {"name": "find_peak_elements_217", "topic": "list/array processing", "prompt": "def find_peak_elements(nums):\n \"\"\"\n Given a 0-indexed integer array 'nums', find all the peak elements and return their values\n in a list, sorted in ascending order. A peak element is an element that is strictly greater\n than its neighbors. If an element has only one neighbor (i.e., it's an edge element),\n it is considered a peak if it is strictly greater than its single neighbor.\n\n The array 'nums' can contain duplicate numbers, but the peak condition still requires\n strict inequality. An empty input array should return an empty list.\n\n Examples:\n find_peak_elements([1,2,3,1]) == [3]\n find_peak_elements([1,2,1,3,5,6,4]) == [2, 6]\n find_peak_elements([5]) == [5]\n find_peak_elements([1,1,1]) == []\n find_peak_elements([3,2,1]) == [3]\n find_peak_elements([1,2,3]) == [3]\n \"\"\"", "solution": "def find_peak_elements(nums):\n \"\"\"\n Given a 0-indexed integer array 'nums', find all the peak elements and return their values\n in a list, sorted in ascending order. A peak element is an element that is strictly greater\n than its neighbors. If an element has only one neighbor (i.e., it's an edge element),\n it is considered a peak if it is strictly greater than its single neighbor.\n\n The array 'nums' can contain duplicate numbers, but the peak condition still requires\n strict inequality. An empty input array should return an empty list.\n\n Examples:\n find_peak_elements([1,2,3,1]) == [3]\n find_peak_elements([1,2,1,3,5,6,4]) == [2, 6]\n find_peak_elements([5]) == [5]\n find_peak_elements([1,1,1]) == []\n find_peak_elements([3,2,1]) == [3]\n find_peak_elements([1,2,3]) == [3]\n \"\"\"\n if not nums:\n return []\n\n peaks = []\n n = len(nums)\n\n if n == 1:\n return [nums[0]]\n\n # Check first element\n if nums[0] > nums[1]:\n peaks.append(nums[0])\n\n # Check middle elements\n for i in range(1, n - 1):\n if nums[i] > nums[i-1] and nums[i] > nums[i+1]:\n peaks.append(nums[i])\n\n # Check last element\n if nums[n-1] > nums[n-2]:\n peaks.append(nums[n-1])\n\n return sorted(peaks)", "tests": ["assert find_peak_elements([1,2,3,1]) == [3]", "assert find_peak_elements([1,2,1,3,5,6,4]) == [2, 6]", "assert find_peak_elements([5]) == [5]", "assert find_peak_elements([1,1,1]) == []", "assert find_peak_elements([3,2,1]) == [3]", "assert find_peak_elements([1,2,3]) == [3]", "assert find_peak_elements([]) == []", "assert find_peak_elements([10,20,15,2,23,90,67]) == [20, 90]"]} {"name": "find_peak_elements_399", "topic": "list/array processing", "prompt": "def find_peak_elements(arr):\n \"\"\"\n Finds all 'peak' elements in a list of numbers. An element is considered a peak\n if it is strictly greater than its immediate neighbors. For elements at the\n boundaries, it only needs to be strictly greater than its single neighbor.\n If the list contains only one element, that element is considered a peak.\n\n The function should return a list of all peak elements in the order they\n appear in the input array. If no peaks are found, return an empty list.\n\n Args:\n arr (list): A list of integers or floats.\n\n Returns:\n list: A list containing all peak elements.\n\n Examples:\n >>> find_peak_elements([1, 2, 3, 2, 1])\n [3]\n >>> find_peak_elements([1, 5, 2, 8, 3])\n [5, 8]\n >>> find_peak_elements([10])\n [10]\n >>> find_peak_elements([5, 4, 3, 2, 1])\n [5]\n >>> find_peak_elements([1, 2, 3, 4, 5])\n [5]\n >>> find_peak_elements([])\n []\n >>> find_peak_elements([3, 1, 4, 1, 5, 9, 2, 6])\n [3, 4, 9, 6]\n \"\"\"", "solution": "def find_peak_elements(arr):\n \"\"\"\n Finds all 'peak' elements in a list of numbers. An element is considered a peak\n if it is strictly greater than its immediate neighbors. For elements at the\n boundaries, it only needs to be strictly greater than its single neighbor.\n If the list contains only one element, that element is considered a peak.\n\n The function should return a list of all peak elements in the order they\n appear in the input array. If no peaks are found, return an empty list.\n\n Args:\n arr (list): A list of integers or floats.\n\n Returns:\n list: A list containing all peak elements.\n\n Examples:\n >>> find_peak_elements([1, 2, 3, 2, 1])\n [3]\n >>> find_peak_elements([1, 5, 2, 8, 3])\n [5, 8]\n >>> find_peak_elements([10])\n [10]\n >>> find_peak_elements([5, 4, 3, 2, 1])\n [5]\n >>> find_peak_elements([1, 2, 3, 4, 5])\n [5]\n >>> find_peak_elements([])\n []\n >>> find_peak_elements([3, 1, 4, 1, 5, 9, 2, 6])\n [3, 4, 9, 6]\n \"\"\"\n n = len(arr)\n if n == 0:\n return []\n if n == 1:\n return [arr[0]]\n\n peaks = []\n\n # Check first element\n if arr[0] > arr[1]:\n peaks.append(arr[0])\n\n # Check middle elements\n for i in range(1, n - 1):\n if arr[i] > arr[i-1] and arr[i] > arr[i+1]:\n peaks.append(arr[i])\n\n # Check last element\n if arr[n-1] > arr[n-2]:\n peaks.append(arr[n-1])\n\n return peaks", "tests": ["assert find_peak_elements([1, 2, 3, 2, 1]) == [3]", "assert find_peak_elements([1, 5, 2, 8, 3]) == [5, 8]", "assert find_peak_elements([10]) == [10]", "assert find_peak_elements([5, 4, 3, 2, 1]) == [5]", "assert find_peak_elements([1, 2, 3, 4, 5]) == [5]", "assert find_peak_elements([]) == []", "assert find_peak_elements([3, 1, 4, 1, 5, 9, 2, 6]) == [3, 4, 9, 6]", "assert find_peak_elements([1,1,1,1,1]) == []", "assert find_peak_elements([0.5, 1.2, 0.8, 2.1, 1.5]) == [1.2, 2.1]"]} {"name": "find_peak_elements_587", "topic": "list/array processing", "prompt": "def find_peak_elements(nums):\n \"\"\"\n Finds all 'peak elements' in a list of integers. A peak element is an element\n that is strictly greater than its neighbors. For elements at the boundaries,\n only one neighbor needs to be considered. If the list is empty, return an empty list.\n If the list has only one element, that element is considered a peak.\n\n Args:\n nums (list[int]): A list of integers.\n\n Returns:\n list[int]: A list of peak elements, in the order they appear in the input list.\n\n Examples:\n >>> find_peak_elements([1, 2, 3, 1])\n [3]\n >>> find_peak_elements([1, 2, 1, 3, 5, 6, 4])\n [2, 6]\n >>> find_peak_elements([1])\n [1]\n >>> find_peak_elements([])\n []\n >>> find_peak_elements([5, 4, 3, 2, 1])\n [5]\n >>> find_peak_elements([1, 2, 3, 4, 5])\n [5]\n \"\"\"", "solution": "def find_peak_elements(nums):\n \"\"\"\n Finds all 'peak elements' in a list of integers. A peak element is an element\n that is strictly greater than its neighbors. For elements at the boundaries,\n only one neighbor needs to be considered. If the list is empty, return an empty list.\n If the list has only one element, that element is considered a peak.\n\n Args:\n nums (list[int]): A list of integers.\n\n Returns:\n list[int]: A list of peak elements, in the order they appear in the input list.\n\n Examples:\n >>> find_peak_elements([1, 2, 3, 1])\n [3]\n >>> find_peak_elements([1, 2, 1, 3, 5, 6, 4])\n [2, 6]\n >>> find_peak_elements([1])\n [1]\n >>> find_peak_elements([])\n []\n >>> find_peak_elements([5, 4, 3, 2, 1])\n [5]\n >>> find_peak_elements([1, 2, 3, 4, 5])\n [5]\n \"\"\"\n n = len(nums)\n if n == 0:\n return []\n if n == 1:\n return [nums[0]]\n\n peaks = []\n for i in range(n):\n is_peak = True\n # Check left neighbor\n if i > 0 and nums[i] <= nums[i - 1]:\n is_peak = False\n # Check right neighbor\n if i < n - 1 and nums[i] <= nums[i + 1]:\n is_peak = False\n\n if is_peak:\n peaks.append(nums[i])\n return peaks", "tests": ["assert find_peak_elements([1, 2, 3, 1]) == [3]", "assert find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]", "assert find_peak_elements([1]) == [1]", "assert find_peak_elements([]) == []", "assert find_peak_elements([5, 4, 3, 2, 1]) == [5]", "assert find_peak_elements([1, 2, 3, 4, 5]) == [5]", "assert find_peak_elements([3, 2, 1, 2, 3]) == [3, 3]", "assert find_peak_elements([10, 20, 15, 2, 23, 90, 67]) == [20, 90]"]} {"name": "find_peak_elements_671", "topic": "list/array processing", "prompt": "def find_peak_elements(nums):\n \"\"\"\n Finds all 'peak' elements in a list of integers. A peak element is an element that is\n greater than or equal to its neighbors. For elements at the ends of the list,\n only one neighbor needs to be considered. An empty list has no peaks.\n A list with a single element has that element as a peak.\n\n Args:\n nums (list[int]): A list of integers.\n\n Returns:\n list[int]: A list of all peak elements, in the order they appear in the input list.\n If no peaks are found, an empty list is returned.\n\n Examples:\n find_peak_elements([1, 2, 3, 2, 1]) == [3]\n find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]\n find_peak_elements([5]) == [5]\n find_peak_elements([]) == []\n find_peak_elements([1, 1, 1]) == [1, 1, 1]\n find_peak_elements([10, 20, 15, 2, 23, 90, 67]) == [20, 90]\n \"\"\"\n", "solution": "def find_peak_elements(nums):\n \"\"\"\n Finds all 'peak' elements in a list of integers. A peak element is an element that is\n greater than or equal to its neighbors. For elements at the ends of the list,\n only one neighbor needs to be considered. An empty list has no peaks.\n A list with a single element has that element as a peak.\n\n Args:\n nums (list[int]): A list of integers.\n\n Returns:\n list[int]: A list of all peak elements, in the order they appear in the input list.\n If no peaks are found, an empty list is returned.\n\n Examples:\n find_peak_elements([1, 2, 3, 2, 1]) == [3]\n find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]\n find_peak_elements([5]) == [5]\n find_peak_elements([]) == []\n find_peak_elements([1, 1, 1]) == [1, 1, 1]\n find_peak_elements([10, 20, 15, 2, 23, 90, 67]) == [20, 90]\n \"\"\"\n n = len(nums)\n if n == 0:\n return []\n if n == 1:\n return [nums[0]]\n\n peaks = []\n for i in range(n):\n is_peak = True\n # Check left neighbor\n if i > 0 and nums[i] < nums[i - 1]:\n is_peak = False\n # Check right neighbor\n if i < n - 1 and nums[i] < nums[i + 1]:\n is_peak = False\n\n if is_peak:\n peaks.append(nums[i])\n\n return peaks", "tests": ["assert find_peak_elements([1, 2, 3, 2, 1]) == [3]", "assert find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]", "assert find_peak_elements([5]) == [5]", "assert find_peak_elements([]) == []", "assert find_peak_elements([1, 1, 1]) == [1, 1, 1]", "assert find_peak_elements([10, 20, 15, 2, 23, 90, 67]) == [20, 90]", "assert find_peak_elements([3, 2, 1]) == [3]", "assert find_peak_elements([1, 2, 3]) == [3]"]} {"name": "find_peak_elements_726", "topic": "list/array processing", "prompt": "def find_peak_elements(nums: list[int]) -> list[int]:\n \"\"\"\n Given an integer array 'nums', find all the peak elements and return a list of their values.\n\n A peak element is an element that is strictly greater than its neighbors.\n For an element at an index 'i', its neighbors are at 'i-1' and 'i+1'.\n\n - If an element is at the first index (index 0), it only has one neighbor at index 1.\n It is a peak if nums[0] > nums[1].\n - If an element is at the last index (index len(nums)-1), it only has one neighbor at index len(nums)-2.\n It is a peak if nums[len(nums)-1] > nums[len(nums)-2].\n - If the array has only one element, that element is considered a peak.\n - If the array is empty, return an empty list.\n\n The returned list should contain the values of the peak elements, in the order they appear in the input array.\n\n Example:\n find_peak_elements([1,2,3,1]) == [3]\n find_peak_elements([1,2,1,3,5,6,4]) == [2, 6]\n find_peak_elements([3,2,1]) == [3]\n find_peak_elements([1,2,3]) == [3]\n \"\"\"", "solution": "def find_peak_elements(nums: list[int]) -> list[int]:\n if not nums:\n return []\n if len(nums) == 1:\n return [nums[0]]\n\n peaks = []\n n = len(nums)\n\n # Check first element\n if nums[0] > nums[1]:\n peaks.append(nums[0])\n\n # Check middle elements\n for i in range(1, n - 1):\n if nums[i] > nums[i-1] and nums[i] > nums[i+1]:\n peaks.append(nums[i])\n\n # Check last element\n if nums[n-1] > nums[n-2]:\n peaks.append(nums[n-1])\n\n return peaks", "tests": ["assert find_peak_elements([1,2,3,1]) == [3]", "assert find_peak_elements([1,2,1,3,5,6,4]) == [2, 6]", "assert find_peak_elements([3,2,1]) == [3]", "assert find_peak_elements([1,2,3]) == [3]", "assert find_peak_elements([5]) == [5]", "assert find_peak_elements([]) == []", "assert find_peak_elements([1,1,1]) == []", "assert find_peak_elements([1,5,2,8,3,9,4]) == [5, 8, 9]"]} {"name": "find_peak_elements_343", "topic": "list/array processing", "prompt": "def find_peak_elements(nums):\n \"\"\"\n Finds all peak elements in a list of integers. A peak element is an element\n that is strictly greater than its neighbors. If an element is at an edge,\n it only needs to be greater than its single neighbor.\n\n For example:\n - In [1, 2, 3, 1], 3 is a peak element.\n - In [1, 5, 1, 3, 6, 7, 6, 5], 5, 7 are peak elements.\n\n Args:\n nums: A list of integers.\n\n Returns:\n A list of peak elements, in the order they appear in the input list.\n If no peak elements are found, an empty list is returned.\n \"\"\"", "solution": "def find_peak_elements(nums):\n \"\"\"\n Finds all peak elements in a list of integers. A peak element is an element\n that is strictly greater than its neighbors. If an element is at an edge,\n it only needs to be greater than its single neighbor.\n\n For example:\n - In [1, 2, 3, 1], 3 is a peak element.\n - In [1, 5, 1, 3, 6, 7, 6, 5], 5, 7 are peak elements.\n\n Args:\n nums: A list of integers.\n\n Returns:\n A list of peak elements, in the order they appear in the input list.\n If no peak elements are found, an empty list is returned.\n \"\"\"\n if not nums:\n return []\n if len(nums) == 1:\n return [nums[0]]\n\n peak_elements = []\n n = len(nums)\n\n # Check first element\n if nums[0] > nums[1]:\n peak_elements.append(nums[0])\n\n # Check middle elements\n for i in range(1, n - 1):\n if nums[i] > nums[i - 1] and nums[i] > nums[i + 1]:\n peak_elements.append(nums[i])\n\n # Check last element\n if nums[n - 1] > nums[n - 2]:\n peak_elements.append(nums[n - 1])\n\n return peak_elements", "tests": ["assert find_peak_elements([1, 2, 3, 1]) == [3]", "assert find_peak_elements([1, 5, 1, 3, 6, 7, 6, 5]) == [5, 7]", "assert find_peak_elements([3, 2, 1]) == [3]", "assert find_peak_elements([1, 2, 3]) == [3]", "assert find_peak_elements([]) == []", "assert find_peak_elements([5]) == [5]", "assert find_peak_elements([1, 1, 1, 1]) == []", "assert find_peak_elements([1, 2, 1, 2, 1]) == [2, 2]"]} {"name": "find_peak_elements_248", "topic": "list/array processing", "prompt": "def find_peak_elements(arr):\n \"\"\"\n Finds all 'peak' elements in a given list of numbers.\n\n A peak element is defined as an element that is strictly greater than its neighbors.\n For elements at the beginning or end of the list, only one neighbor needs to be considered.\n - The first element is a peak if it's greater than the second element (if it exists).\n - The last element is a peak if it's greater than the second to last element (if it exists).\n - An intermediate element is a peak if it's greater than both its left and right neighbors.\n\n The input list 'arr' will contain only integers. It can be empty or have one element.\n If the list is empty, return an empty list.\n If the list has one element, that element is considered a peak.\n\n Args:\n arr (list[int]): The input list of integers.\n\n Returns:\n list[int]: A list containing all peak elements found in the order they appear in the input list.\n\n Examples:\n >>> find_peak_elements([1, 2, 1, 3, 5, 6, 4])\n [2, 6]\n >>> find_peak_elements([1, 2, 3, 4, 5])\n [5]\n >>> find_peak_elements([5, 4, 3, 2, 1])\n [5]\n >>> find_peak_elements([10])\n [10]\n >>> find_peak_elements([])\n []\n >>> find_peak_elements([3, 1, 4, 1, 5, 9, 2, 6])\n [3, 4, 9, 6]\n \"\"\"", "solution": "def find_peak_elements(arr):\n if not arr:\n return []\n if len(arr) == 1:\n return [arr[0]]\n\n peaks = []\n n = len(arr)\n\n # Check the first element\n if arr[0] > arr[1]:\n peaks.append(arr[0])\n\n # Check intermediate elements\n for i in range(1, n - 1):\n if arr[i] > arr[i-1] and arr[i] > arr[i+1]:\n peaks.append(arr[i])\n\n # Check the last element\n if arr[n-1] > arr[n-2]:\n peaks.append(arr[n-1])\n\n return peaks", "tests": ["assert find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]", "assert find_peak_elements([1, 2, 3, 4, 5]) == [5]", "assert find_peak_elements([5, 4, 3, 2, 1]) == [5]", "assert find_peak_elements([10]) == [10]", "assert find_peak_elements([]) == []", "assert find_peak_elements([3, 1, 4, 1, 5, 9, 2, 6]) == [3, 4, 9, 6]", "assert find_peak_elements([1, 2, 3, 2, 1]) == [3]", "assert find_peak_elements([7, 8, 9, 10, 5, 6, 4]) == [10, 6]"]} {"name": "find_peak_elements_669", "topic": "list/array processing", "prompt": "def find_peak_elements(nums):\n \"\"\"\n Finds all 'peak' elements in a list of integers. A peak element is an element\n that is strictly greater than its neighbors. For elements at the ends of the list,\n only one neighbor needs to be considered. If the list has only one element, that\n element is considered a peak.\n\n Args:\n nums (list[int]): A list of integers.\n\n Returns:\n list[int]: A list of all peak elements found in the input list, in the order\n they appear. Returns an empty list if no peaks are found or if the\n input list is empty.\n\n Examples:\n find_peak_elements([1, 2, 3, 1]) == [3]\n find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]\n find_peak_elements([5]) == [5]\n find_peak_elements([]) == []\n find_peak_elements([1, 1, 1]) == []\n \"\"\"", "solution": "def find_peak_elements(nums):\n \"\"\"\n Finds all 'peak' elements in a list of integers. A peak element is an element\n that is strictly greater than its neighbors. For elements at the ends of the list,\n only one neighbor needs to be considered. If the list has only one element, that\n element is considered a peak.\n\n Args:\n nums (list[int]): A list of integers.\n\n Returns:\n list[int]: A list of all peak elements found in the input list, in the order\n they appear. Returns an empty list if no peaks are found or if the\n input list is empty.\n\n Examples:\n find_peak_elements([1, 2, 3, 1]) == [3]\n find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]\n find_peak_elements([5]) == [5]\n find_peak_elements([]) == []\n find_peak_elements([1, 1, 1]) == []\n \"\"\"\n if not nums:\n return []\n if len(nums) == 1:\n return [nums[0]]\n\n peaks = []\n n = len(nums)\n\n for i in range(n):\n is_peak = True\n # Check left neighbor\n if i > 0 and nums[i] <= nums[i - 1]:\n is_peak = False\n # Check right neighbor\n if i < n - 1 and nums[i] <= nums[i + 1]:\n is_peak = False\n\n if is_peak:\n peaks.append(nums[i])\n\n return peaks", "tests": ["assert find_peak_elements([1, 2, 3, 1]) == [3]", "assert find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]", "assert find_peak_elements([5]) == [5]", "assert find_peak_elements([]) == []", "assert find_peak_elements([1, 1, 1]) == []", "assert find_peak_elements([10, 20, 15, 2, 23, 90, 67]) == [20, 90]", "assert find_peak_elements([3, 2, 1]) == [3]", "assert find_peak_elements([1, 2, 3]) == [3]"]} {"name": "find_peak_elements_745", "topic": "list/array processing", "prompt": "def find_peak_elements(arr):\n \"\"\"\n Finds all 'peak' elements in a given list of numbers.\n\n A peak element is defined as an element that is strictly greater\n than its immediate neighbors. For elements at the boundaries (first\n or last), they are considered a peak if they are strictly greater\n than their single immediate neighbor.\n\n The function should return a new list containing all peak elements\n in the order they appear in the original list.\n\n An empty list or a list with a single element has no peaks.\n\n Args:\n arr (list[int | float]): The input list of numbers.\n\n Returns:\n list[int | float]: A list of all peak elements.\n\n Examples:\n >>> find_peak_elements([1, 2, 1])\n [2]\n >>> find_peak_elements([1, 2, 3, 2, 1])\n [3]\n >>> find_peak_elements([1, 5, 2, 8, 3])\n [5, 8]\n >>> find_peak_elements([5, 1, 2, 8, 3, 9])\n [5, 8, 9]\n >>> find_peak_elements([])\n []\n >>> find_peak_elements([7])\n []\n \"\"\"", "solution": "def find_peak_elements(arr):\n \"\"\"\n Finds all 'peak' elements in a given list of numbers.\n\n A peak element is defined as an element that is strictly greater\n than its immediate neighbors. For elements at the boundaries (first\n or last), they are considered a peak if they are strictly greater\n than their single immediate neighbor.\n\n The function should return a new list containing all peak elements\n in the order they appear in the original list.\n\n An empty list or a list with a single element has no peaks.\n\n Args:\n arr (list[int | float]): The input list of numbers.\n\n Returns:\n list[int | float]: A list of all peak elements.\n\n Examples:\n >>> find_peak_elements([1, 2, 1])\n [2]\n >>> find_peak_elements([1, 2, 3, 2, 1])\n [3]\n >>> find_peak_elements([1, 5, 2, 8, 3])\n [5, 8]\n >>> find_peak_elements([5, 1, 2, 8, 3, 9])\n [5, 8, 9]\n >>> find_peak_elements([])\n []\n >>> find_peak_elements([7])\n []\n \"\"\"\n n = len(arr)\n if n <= 1:\n return []\n\n peaks = []\n\n # Check first element\n if n > 1 and arr[0] > arr[1]:\n peaks.append(arr[0])\n\n # Check middle elements\n for i in range(1, n - 1):\n if arr[i] > arr[i - 1] and arr[i] > arr[i + 1]:\n peaks.append(arr[i])\n\n # Check last element\n if n > 1 and arr[n - 1] > arr[n - 2]:\n peaks.append(arr[n - 1])\n\n return peaks", "tests": ["assert find_peak_elements([1, 2, 1]) == [2]", "assert find_peak_elements([1, 2, 3, 2, 1]) == [3]", "assert find_peak_elements([1, 5, 2, 8, 3]) == [5, 8]", "assert find_peak_elements([5, 1, 2, 8, 3, 9]) == [5, 8, 9]", "assert find_peak_elements([]) == []", "assert find_peak_elements([7]) == []", "assert find_peak_elements([1, 2, 3, 4, 5]) == [5]", "assert find_peak_elements([5, 4, 3, 2, 1]) == [5]", "assert find_peak_elements([1, 1, 1, 1, 1]) == []", "assert find_peak_elements([10, 20, 15, 2, 23, 90, 67]) == [20, 90]", "assert find_peak_elements([3.0, 1.5, 4.0, 2.0, 5.5]) == [3.0, 4.0, 5.5]"]} {"name": "find_peak_elements_776", "topic": "list/array processing", "prompt": "def find_peak_elements(nums: list[int]) -> list[int]:\n \"\"\"\n A peak element is an element that is strictly greater than its neighbors. An array may contain\n multiple peak elements. The function should return a list of all peak elements found in the input array `nums`.\n The returned list should maintain the order in which the peak elements appear in `nums`.\n\n For elements at the boundaries:\n - The first element is a peak if it's strictly greater than its only right neighbor.\n - The last element is a peak if it's strictly greater than its only left neighbor.\n\n An empty input list should return an empty list.\n An input list with a single element should return a list containing that single element.\n\n Examples:\n find_peak_elements([1, 2, 3, 1]) == [3]\n find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]\n find_peak_elements([3, 2, 1]) == [3]\n find_peak_elements([1, 3, 2]) == [3]\n find_peak_elements([1]) == [1]\n find_peak_elements([]) == []\n find_peak_elements([5, 5, 5]) == []\n find_peak_elements([1, 2, 2, 1]) == []\n \"\"\"", "solution": "def find_peak_elements(nums: list[int]) -> list[int]:\n \"\"\"\n A peak element is an element that is strictly greater than its neighbors. An array may contain\n multiple peak elements. The function should return a list of all peak elements found in the input array `nums`.\n The returned list should maintain the order in which the peak elements appear in `nums`.\n\n For elements at the boundaries:\n - The first element is a peak if it's strictly greater than its only right neighbor.\n - The last element is a peak if it's strictly greater than its only left neighbor.\n\n An empty input list should return an empty list.\n An input list with a single element should return a list containing that single element.\n\n Examples:\n find_peak_elements([1, 2, 3, 1]) == [3]\n find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]\n find_peak_elements([3, 2, 1]) == [3]\n find_peak_elements([1, 3, 2]) == [3]\n find_peak_elements([1]) == [1]\n find_peak_elements([]) == []\n find_peak_elements([5, 5, 5]) == []\n find_peak_elements([1, 2, 2, 1]) == []\n \"\"\"\n n = len(nums)\n if n == 0:\n return []\n if n == 1:\n return [nums[0]]\n\n peaks = []\n for i in range(n):\n # Check first element\n if i == 0:\n if nums[i] > nums[i+1]:\n peaks.append(nums[i])\n # Check last element\n elif i == n - 1:\n if nums[i] > nums[i-1]:\n peaks.append(nums[i])\n # Check middle elements\n else:\n if nums[i] > nums[i-1] and nums[i] > nums[i+1]:\n peaks.append(nums[i])\n return peaks", "tests": ["assert find_peak_elements([1, 2, 3, 1]) == [3]", "assert find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]", "assert find_peak_elements([3, 2, 1]) == [3]", "assert find_peak_elements([1]) == [1]", "assert find_peak_elements([]) == []", "assert find_peak_elements([5, 5, 5]) == []", "assert find_peak_elements([1, 3, 2, 4, 1, 5, 0]) == [3, 4, 5]"]} {"name": "find_peak_elements_612", "topic": "list/array processing", "prompt": "def find_peak_elements(nums):\n \"\"\"\n Given an integer array 'nums', find all the peak elements. A peak element is an element\n that is strictly greater than its neighbors. If an element has only one neighbor (e.g.,\n the first or last element in the array), it is considered a peak if it is strictly\n greater than that single neighbor.\n\n Return a list of all peak elements found in the order they appear in the input array.\n\n The array 'nums' will have at least one element.\n\n Examples:\n find_peak_elements([1,2,3,1]) == [3]\n find_peak_elements([1,2,1,3,5,6,4]) == [2, 6]\n find_peak_elements([5]) == [5]\n find_peak_elements([1,2]) == [2]\n find_peak_elements([2,1]) == [2]\n \"\"\"", "solution": "def find_peak_elements(nums):\n peaks = []\n n = len(nums)\n\n if n == 1:\n return [nums[0]]\n\n for i in range(n):\n is_peak = False\n if i == 0:\n # First element: check only right neighbor\n if nums[i] > nums[i+1]:\n is_peak = True\n elif i == n - 1:\n # Last element: check only left neighbor\n if nums[i] > nums[i-1]:\n is_peak = True\n else:\n # Middle element: check both neighbors\n if nums[i] > nums[i-1] and nums[i] > nums[i+1]:\n is_peak = True\n\n if is_peak:\n peaks.append(nums[i])\n\n return peaks", "tests": ["assert find_peak_elements([1,2,3,1]) == [3]", "assert find_peak_elements([1,2,1,3,5,6,4]) == [2, 6]", "assert find_peak_elements([5]) == [5]", "assert find_peak_elements([1,2]) == [2]", "assert find_peak_elements([2,1]) == [2]", "assert find_peak_elements([1,1,1,1]) == []", "assert find_peak_elements([10,20,15,2,23,90,67]) == [20, 90]", "assert find_peak_elements([3,2,1]) == [3]"]} {"name": "find_peak_elements_102", "topic": "list/array processing", "prompt": "def find_peak_elements(nums):\n \"\"\"\n Given a 0-indexed integer array `nums`, find all peak elements and return a list of their indices.\n \n A peak element is an element that is strictly greater than its neighbors. \n \n For an element at index `i`:\n - If `i` is 0, it's a peak if `nums[0] > nums[1]`.\n - If `i` is len(nums) - 1, it's a peak if `nums[len(nums) - 1] > nums[len(nums) - 2]`.\n - If `i` is in between, it's a peak if `nums[i] > nums[i-1]` and `nums[i] > nums[i+1]`.\n \n If the array contains fewer than 2 elements, there are no peak elements.\n\n The returned list should contain the indices of all peak elements, in ascending order.\n\n Examples:\n find_peak_elements([1,2,3,1]) == [2] (nums[2] = 3 is greater than its neighbors 2 and 1)\n find_peak_elements([1,2,1,3,5,6,4]) == [1, 5] (nums[1]=2 is >1 and >1, nums[5]=6 is >5 and >4)\n find_peak_elements([3,2,1]) == [0]\n find_peak_elements([1,2,3]) == [2]\n find_peak_elements([]) == []\n find_peak_elements([5]) == []\n find_peak_elements([1,1,1]) == []\n \"\"\"", "solution": "def find_peak_elements(nums):\n if len(nums) < 2:\n return []\n\n peak_indices = []\n n = len(nums)\n\n # Check first element\n if n > 1 and nums[0] > nums[1]:\n peak_indices.append(0)\n\n # Check middle elements\n for i in range(1, n - 1):\n if nums[i] > nums[i - 1] and nums[i] > nums[i + 1]:\n peak_indices.append(i)\n\n # Check last element\n if n > 1 and nums[n - 1] > nums[n - 2]:\n peak_indices.append(n - 1)\n\n return peak_indices", "tests": ["assert find_peak_elements([1,2,3,1]) == [2]", "assert find_peak_elements([1,2,1,3,5,6,4]) == [1, 5]", "assert find_peak_elements([3,2,1]) == [0]", "assert find_peak_elements([1,2,3]) == [2]", "assert find_peak_elements([]) == []", "assert find_peak_elements([5]) == []", "assert find_peak_elements([1,1,1]) == []", "assert find_peak_elements([1,5,2,8,3,9,4]) == [1,3,5]", "assert find_peak_elements([10, 20, 15, 2, 23, 90, 67]) == [1, 5]"]} {"name": "find_peak_elements_971", "topic": "list/array processing", "prompt": "def find_peak_elements(nums):\n \"\"\"\n Finds all peak elements in a list of integers.\n\n A peak element is an element that is strictly greater than its neighbors.\n For elements at the ends of the list, only one neighbor needs to be considered.\n If the list contains only one element, that element is considered a peak.\n\n Args:\n nums: A list of integers.\n\n Returns:\n A list of peak elements, in the order they appear in the input list.\n Returns an empty list if no peak elements are found.\n\n Examples:\n find_peak_elements([1, 2, 3, 1]) == [3]\n find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]\n find_peak_elements([5]) == [5]\n find_peak_elements([]) == []\n find_peak_elements([1, 1, 1]) == []\n find_peak_elements([1, 5, 2, 8, 3]) == [5, 8]\n \"\"\"", "solution": "def find_peak_elements(nums):\n \"\"\"\n Finds all peak elements in a list of integers.\n\n A peak element is an element that is strictly greater than its neighbors.\n For elements at the ends of the list, only one neighbor needs to be considered.\n If the list contains only one element, that element is considered a peak.\n\n Args:\n nums: A list of integers.\n\n Returns:\n A list of peak elements, in the order they appear in the input list.\n Returns an empty list if no peak elements are found.\n\n Examples:\n find_peak_elements([1, 2, 3, 1]) == [3]\n find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]\n find_peak_elements([5]) == [5]\n find_peak_elements([]) == []\n find_peak_elements([1, 1, 1]) == []\n find_peak_elements([1, 5, 2, 8, 3]) == [5, 8]\n \"\"\"\n n = len(nums)\n if n == 0:\n return []\n if n == 1:\n return [nums[0]]\n\n peaks = []\n for i in range(n):\n is_peak = True\n # Check left neighbor\n if i > 0 and nums[i] <= nums[i - 1]:\n is_peak = False\n # Check right neighbor\n if i < n - 1 and nums[i] <= nums[i + 1]:\n is_peak = False\n\n if is_peak:\n peaks.append(nums[i])\n\n return peaks", "tests": ["assert find_peak_elements([1, 2, 3, 1]) == [3]", "assert find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]", "assert find_peak_elements([5]) == [5]", "assert find_peak_elements([]) == []", "assert find_peak_elements([1, 1, 1]) == []", "assert find_peak_elements([1, 5, 2, 8, 3]) == [5, 8]", "assert find_peak_elements([1, 2, 3, 4, 5]) == [5]", "assert find_peak_elements([5, 4, 3, 2, 1]) == [5]"]} {"name": "find_peak_elements_386", "topic": "list/array processing", "prompt": "def find_peak_elements(arr):\n \"\"\"\n Given a 0-indexed integer array 'arr', find all peak elements and return their indices in a list.\n\n A peak element is an element that is strictly greater than its neighbors.\n If an element has only one neighbor (e.g., the first or last element), it is considered\n a peak if it is strictly greater than its single neighbor.\n\n For example:\n - In [1, 2, 3, 1], 3 is a peak element because 3 > 2 and 3 > 1. Its index is 2.\n - In [1, 2, 1, 3, 5, 6, 4], 2 is a peak (index 1), 6 is a peak (index 5).\n\n The returned list of indices should be sorted in ascending order.\n If no peak elements are found, return an empty list.\n\n Args:\n arr (list[int]): A list of integers.\n\n Returns:\n list[int]: A list of indices of all peak elements, sorted in ascending order.\n \"\"\"", "solution": "def find_peak_elements(arr):\n \"\"\"\n Given a 0-indexed integer array 'arr', find all peak elements and return their indices in a list.\n\n A peak element is an element that is strictly greater than its neighbors.\n If an element has only one neighbor (e.g., the first or last element), it is considered\n a peak if it is strictly greater than its single neighbor.\n\n For example:\n - In [1, 2, 3, 1], 3 is a peak element because 3 > 2 and 3 > 1. Its index is 2.\n - In [1, 2, 1, 3, 5, 6, 4], 2 is a peak (index 1), 6 is a peak (index 5).\n\n The returned list of indices should be sorted in ascending order.\n If no peak elements are found, return an empty list.\n\n Args:\n arr (list[int]): A list of integers.\n\n Returns:\n list[int]: A list of indices of all peak elements, sorted in ascending order.\n \"\"\"\n n = len(arr)\n if n == 0:\n return []\n if n == 1:\n return [0] # A single element array is always a peak\n\n peaks = []\n for i in range(n):\n is_peak = False\n if i == 0: # First element\n if arr[i] > arr[i+1]:\n is_peak = True\n elif i == n - 1: # Last element\n if arr[i] > arr[i-1]:\n is_peak = True\n else: # Middle elements\n if arr[i] > arr[i-1] and arr[i] > arr[i+1]:\n is_peak = True\n \n if is_peak:\n peaks.append(i)\n \n return peaks", "tests": ["assert find_peak_elements([1, 2, 3, 1]) == [2]", "assert find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [1, 5]", "assert find_peak_elements([1, 2, 3, 4, 5]) == [4]", "assert find_peak_elements([5, 4, 3, 2, 1]) == [0]", "assert find_peak_elements([1, 1, 1, 1]) == []", "assert find_peak_elements([]) == []", "assert find_peak_elements([7]) == [0]", "assert find_peak_elements([1, 3, 2, 4, 1, 5, 2]) == [1, 3, 5]"]} {"name": "find_peak_elements_129", "topic": "list/array processing", "prompt": "def find_peak_elements(nums):\n \"\"\"\n Given an integer array 'nums', find all the peak elements and return a list of their indices.\n A peak element is an element that is strictly greater than its neighbors.\n For an array of length 1, the single element is considered a peak.\n For elements at the boundaries, only one neighbor needs to be considered (e.g., nums[0] > nums[1]).\n\n Examples:\n find_peak_elements([1,2,3,1]) == [2] (nums[2] is 3, greater than 2 and 1)\n find_peak_elements([1,2,1,3,5,6,4]) == [1, 5] (nums[1] is 2, nums[5] is 6)\n find_peak_elements([5]) == [0]\n find_peak_elements([1,2]) == [1]\n find_peak_elements([2,1]) == [0]\n find_peak_elements([]) == []\n \"\"\"", "solution": "def find_peak_elements(nums):\n if not nums:\n return []\n if len(nums) == 1:\n return [0]\n\n peaks = []\n n = len(nums)\n\n # Check first element\n if nums[0] > nums[1]:\n peaks.append(0)\n\n # Check middle elements\n for i in range(1, n - 1):\n if nums[i] > nums[i - 1] and nums[i] > nums[i + 1]:\n peaks.append(i)\n\n # Check last element\n if nums[n - 1] > nums[n - 2]:\n peaks.append(n - 1)\n\n return peaks", "tests": ["assert find_peak_elements([1,2,3,1]) == [2]", "assert find_peak_elements([1,2,1,3,5,6,4]) == [1, 5]", "assert find_peak_elements([5]) == [0]", "assert find_peak_elements([]) == []", "assert find_peak_elements([1,2]) == [1]", "assert find_peak_elements([2,1]) == [0]", "assert find_peak_elements([3,2,1]) == [0]", "assert find_peak_elements([1,2,3,4,5]) == [4]", "assert find_peak_elements([5,4,3,2,1]) == [0]", "assert find_peak_elements([1,3,2,4,1,5,0]) == [1, 3, 5]"]} {"name": "find_peak_elements_955", "topic": "list/array processing", "prompt": "def find_peak_elements(arr):\n \"\"\"\n Given a 0-indexed integer array arr, find all peak elements and return a list of their indices.\n\n A peak element is an element that is strictly greater than its neighbors.\n If an element has only one neighbor (i.e., it's at an end of the array),\n it is considered a peak if it is strictly greater than its single neighbor.\n\n The array can contain duplicate numbers, but the peak condition still requires strict inequality.\n\n Example:\n find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [1, 5]\n # Explanation:\n # - arr[0] = 1 (not a peak, 1 < 2)\n # - arr[1] = 2 (peak, 1 < 2 > 1)\n # - arr[2] = 1 (not a peak, 2 > 1 < 3)\n # - arr[3] = 3 (not a peak, 1 < 3 < 5)\n # - arr[4] = 5 (not a peak, 3 < 5 < 6)\n # - arr[5] = 6 (peak, 5 < 6 > 4)\n # - arr[6] = 4 (not a peak, 6 > 4)\n\n find_peak_elements([1, 2, 3, 4, 5]) == [4]\n # Explanation:\n # - arr[4] = 5 (peak, only neighbor 4 < 5)\n\n find_peak_elements([5, 4, 3, 2, 1]) == [0]\n # Explanation:\n # - arr[0] = 5 (peak, only neighbor 4 < 5)\n\n find_peak_elements([1, 1, 1]) == []\n # Explanation: No element is strictly greater than its neighbors.\n\n :param arr: A list of integers.\n :return: A list of indices of all peak elements.\n \"\"\"\n pass", "solution": "def find_peak_elements(arr):\n \"\"\"\n Given a 0-indexed integer array arr, find all peak elements and return a list of their indices.\n\n A peak element is an element that is strictly greater than its neighbors.\n If an element has only one neighbor (i.e., it's at an end of the array),\n it is considered a peak if it is strictly greater than its single neighbor.\n\n The array can contain duplicate numbers, but the peak condition still requires strict inequality.\n\n Example:\n find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [1, 5]\n # Explanation:\n # - arr[0] = 1 (not a peak, 1 < 2)\n # - arr[1] = 2 (peak, 1 < 2 > 1)\n # - arr[2] = 1 (not a peak, 2 > 1 < 3)\n # - arr[3] = 3 (not a peak, 1 < 3 < 5)\n # - arr[4] = 5 (not a peak, 3 < 5 < 6)\n # - arr[5] = 6 (peak, 5 < 6 > 4)\n # - arr[6] = 4 (not a peak, 6 > 4)\n\n find_peak_elements([1, 2, 3, 4, 5]) == [4]\n # Explanation:\n # - arr[4] = 5 (peak, only neighbor 4 < 5)\n\n find_peak_elements([5, 4, 3, 2, 1]) == [0]\n # Explanation:\n # - arr[0] = 5 (peak, only neighbor 4 < 5)\n\n find_peak_elements([1, 1, 1]) == []\n # Explanation: No element is strictly greater than its neighbors.\n\n :param arr: A list of integers.\n :return: A list of indices of all peak elements.\n \"\"\"\n n = len(arr)\n if n == 0:\n return []\n if n == 1:\n return [0]\n\n peak_indices = []\n for i in range(n):\n is_peak = True\n # Check left neighbor\n if i > 0 and arr[i] <= arr[i-1]:\n is_peak = False\n # Check right neighbor\n if i < n - 1 and arr[i] <= arr[i+1]:\n is_peak = False\n\n if is_peak:\n peak_indices.append(i)\n\n return peak_indices", "tests": ["assert find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [1, 5]", "assert find_peak_elements([1, 2, 3, 4, 5]) == [4]", "assert find_peak_elements([5, 4, 3, 2, 1]) == [0]", "assert find_peak_elements([1, 1, 1]) == []", "assert find_peak_elements([10]) == [0]", "assert find_peak_elements([]) == []", "assert find_peak_elements([3, 2, 3, 4, 3, 5, 4, 6, 7, 6, 5]) == [0, 3, 5, 8]"]} {"name": "find_peak_elements_609", "topic": "list/array processing", "prompt": "def find_peak_elements(arr):\n \"\"\"\n Given a 0-indexed integer array arr, find all its 'peak elements'.\n A peak element is an element that is strictly greater than its neighbors.\n For elements at the boundaries:\n - The first element is a peak if it's strictly greater than the second element.\n - The last element is a peak if it's strictly greater than the second to last element.\n If the array has only one element, that element is considered a peak.\n \n Return a list of all peak elements in the order they appear in the input array.\n \n Examples:\n find_peak_elements([1, 2, 3, 1]) == [3]\n find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]\n find_peak_elements([3, 2, 1]) == [3]\n find_peak_elements([1, 2, 3]) == [3]\n find_peak_elements([5]) == [5]\n find_peak_elements([]) == []\n find_peak_elements([1, 1, 1]) == []\n \"\"\"", "solution": "def find_peak_elements(arr):\n \"\"\"\n Given a 0-indexed integer array arr, find all its 'peak elements'.\n A peak element is an element that is strictly greater than its neighbors.\n For elements at the boundaries:\n - The first element is a peak if it's strictly greater than the second element.\n - The last element is a peak if it's strictly greater than the second to last element.\n If the array has only one element, that element is considered a peak.\n \n Return a list of all peak elements in the order they appear in the input array.\n \n Examples:\n find_peak_elements([1, 2, 3, 1]) == [3]\n find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]\n find_peak_elements([3, 2, 1]) == [3]\n find_peak_elements([1, 2, 3]) == [3]\n find_peak_elements([5]) == [5]\n find_peak_elements([]) == []\n find_peak_elements([1, 1, 1]) == []\n \"\"\"\n n = len(arr)\n if n == 0:\n return []\n if n == 1:\n return [arr[0]]\n\n peaks = []\n\n # Check first element\n if arr[0] > arr[1]:\n peaks.append(arr[0])\n\n # Check middle elements\n for i in range(1, n - 1):\n if arr[i] > arr[i - 1] and arr[i] > arr[i + 1]:\n peaks.append(arr[i])\n\n # Check last element\n if arr[n - 1] > arr[n - 2]:\n peaks.append(arr[n - 1])\n\n return peaks", "tests": ["assert find_peak_elements([1, 2, 3, 1]) == [3]", "assert find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]", "assert find_peak_elements([3, 2, 1]) == [3]", "assert find_peak_elements([1, 2, 3]) == [3]", "assert find_peak_elements([5]) == [5]", "assert find_peak_elements([]) == []", "assert find_peak_elements([1, 1, 1]) == []", "assert find_peak_elements([10, 20, 15, 2, 23, 90, 67]) == [20, 90]", "assert find_peak_elements([7, 6, 5, 4, 3, 2, 1]) == [7]", "assert find_peak_elements([1, 2, 3, 4, 5, 6, 7]) == [7]"]} {"name": "find_peak_elements_276", "topic": "list/array processing", "prompt": "def find_peak_elements(nums):\n \"\"\"\n Find all 'peak' elements in a list of numbers. A peak element is an element\n that is strictly greater than its neighbors. For elements at the boundaries\n (first and last), only one neighbor needs to be considered.\n\n If the list is empty, return an empty list.\n If the list has one element, that element is considered a peak.\n\n Args:\n nums (list[int]): A list of integers.\n\n Returns:\n list[int]: A list of all peak elements found in the input list, in their original order.\n \"\"\"", "solution": "def find_peak_elements(nums):\n if not nums:\n return []\n if len(nums) == 1:\n return [nums[0]]\n\n peaks = []\n n = len(nums)\n\n # Check first element\n if nums[0] > nums[1]:\n peaks.append(nums[0])\n\n # Check middle elements\n for i in range(1, n - 1):\n if nums[i] > nums[i-1] and nums[i] > nums[i+1]:\n peaks.append(nums[i])\n\n # Check last element\n if nums[n-1] > nums[n-2]:\n peaks.append(nums[n-1])\n\n return peaks", "tests": ["assert find_peak_elements([1, 2, 3, 2, 1]) == [3]", "assert find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]", "assert find_peak_elements([1, 2, 3, 4, 5]) == [5]", "assert find_peak_elements([5, 4, 3, 2, 1]) == [5]", "assert find_peak_elements([]) == []", "assert find_peak_elements([7]) == [7]", "assert find_peak_elements([1,1,1,1,1]) == []", "assert find_peak_elements([1, 5, 2, 8, 3, 9, 4]) == [5, 8, 9]"]} {"name": "find_peak_elements_911", "topic": "list/array processing", "prompt": "def find_peak_elements(nums):\n \"\"\"\n Finds all 'peak elements' in a list of numbers. A peak element is an element\n that is strictly greater than its neighbors. For elements at the ends of the list,\n we only consider one neighbor. If the list is empty, return an empty list.\n If the list has only one element, that element is considered a peak.\n\n Args:\n nums (list[int]): A list of integers.\n\n Returns:\n list[int]: A list of peak elements, in the order they appear in the input list.\n\n Examples:\n find_peak_elements([1, 2, 3, 4, 5]) == [5]\n find_peak_elements([5, 4, 3, 2, 1]) == [5]\n find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]\n find_peak_elements([10]) == [10]\n find_peak_elements([]) == []\n find_peak_elements([1,1,1]) == []\n \"\"\"", "solution": "def find_peak_elements(nums):\n if not nums:\n return []\n if len(nums) == 1:\n return [nums[0]]\n\n peaks = []\n n = len(nums)\n\n # Check first element\n if nums[0] > nums[1]:\n peaks.append(nums[0])\n\n # Check middle elements\n for i in range(1, n - 1):\n if nums[i] > nums[i - 1] and nums[i] > nums[i + 1]:\n peaks.append(nums[i])\n\n # Check last element\n if nums[n - 1] > nums[n - 2]:\n peaks.append(nums[n - 1])\n\n return peaks", "tests": ["assert find_peak_elements([1, 2, 3, 4, 5]) == [5]", "assert find_peak_elements([5, 4, 3, 2, 1]) == [5]", "assert find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [2, 6]", "assert find_peak_elements([10]) == [10]", "assert find_peak_elements([]) == []", "assert find_peak_elements([1, 1, 1]) == []", "assert find_peak_elements([3, 2, 1, 2, 3]) == [3, 3]", "assert find_peak_elements([1, 2, 3, 2, 1]) == [3]"]} {"name": "find_peak_elements_932", "topic": "list/array processing", "prompt": "def find_peak_elements(nums):\n \"\"\"\n Given a 0-indexed integer array 'nums', find all the 'peak elements' and return their indices\n in a list, sorted in ascending order. A peak element is an element that is strictly greater\n than its neighbors. If an element has only one neighbor (i.e., it's at an end of the array),\n it only needs to be strictly greater than that single neighbor.\n\n For example:\n - In [1,2,3,1], 3 is a peak element because it's > 2 and > 1. Its index is 2.\n - In [1,2,1,3,5,6,4], 2 is a peak element (index 1), 6 is a peak element (index 5).\n\n The array 'nums' will have at least one element.\n Duplicate values are possible but will not form a 'peak' unless strictly greater.\n\n Args:\n nums (list[int]): A list of integers.\n\n Returns:\n list[int]: A list of indices of all peak elements, sorted in ascending order.\n \"\"\"", "solution": "def find_peak_elements(nums):\n peak_indices = []\n n = len(nums)\n\n if n == 1:\n return [0]\n\n for i in range(n):\n is_peak = False\n if i == 0: # First element\n if nums[i] > nums[i+1]:\n is_peak = True\n elif i == n - 1: # Last element\n if nums[i] > nums[i-1]:\n is_peak = True\n else: # Middle elements\n if nums[i] > nums[i-1] and nums[i] > nums[i+1]:\n is_peak = True\n \n if is_peak:\n peak_indices.append(i)\n \n return peak_indices", "tests": ["assert find_peak_elements([1, 2, 3, 1]) == [2]", "assert find_peak_elements([1, 2, 1, 3, 5, 6, 4]) == [1, 5]", "assert find_peak_elements([3, 2, 1]) == [0]", "assert find_peak_elements([1, 2, 3, 4, 5]) == [4]", "assert find_peak_elements([5, 4, 3, 2, 1]) == [0]", "assert find_peak_elements([1]) == [0]", "assert find_peak_elements([1,1,1,1]) == []", "assert find_peak_elements([1,5,1,5,1]) == [1,3]"]} {"name": "count_common_elements", "topic": "dictionaries and counting", "prompt": "def count_common_elements(list_of_dictionaries: list[dict[str, list[str]]]) -> dict[str, int]:\n \"\"\"\n Counts the occurrences of common string elements across lists within dictionaries.\n\n Given a list of dictionaries, where each dictionary's values are lists of strings,\n this function should return a new dictionary. The keys of this new dictionary\n will be the unique string elements that appear in at least two *different* \n lists (regardless of which dictionary those lists belong to). The values will be\n the total count of how many *times* that common element appears across all lists.\n\n An element is considered 'common' if it exists in at least two distinct lists.\n The counting should be cumulative across all lists in all dictionaries.\n\n Example:\n list_of_dictionaries = [\n {'a': ['apple', 'banana'], 'b': ['orange', 'apple']},\n {'c': ['grape', 'banana', 'kiwi'], 'd': ['apple', 'grape']}\n ]\n \n 'apple' appears in ['apple', 'banana'], ['orange', 'apple'], ['apple', 'grape'].\n 'banana' appears in ['apple', 'banana'], ['grape', 'banana', 'kiwi'].\n 'grape' appears in ['grape', 'banana', 'kiwi'], ['apple', 'grape'].\n\n Expected output for the example: {'apple': 3, 'banana': 2, 'grape': 2}\n (Note: 'kiwi' and 'orange' are not common, as they only appear once each.)\n \"\"\"", "solution": "def count_common_elements(list_of_dictionaries: list[dict[str, list[str]]]) -> dict[str, int]:\n all_elements_counts = {}\n all_lists = []\n\n # Collect all lists and count individual element occurrences\n for d in list_of_dictionaries:\n for key in d:\n current_list = d[key]\n all_lists.append(current_list)\n for item in current_list:\n all_elements_counts[item] = all_elements_counts.get(item, 0) + 1\n\n # Determine which elements are common (appear in at least two different lists)\n element_to_list_set = {}\n for i, current_list in enumerate(all_lists):\n for item in set(current_list): # Use set to count unique occurrences within a single list\n if item not in element_to_list_set:\n element_to_list_set[item] = set()\n element_to_list_set[item].add(i)\n \n common_elements_result = {}\n for element, list_indices in element_to_list_set.items():\n if len(list_indices) >= 2:\n common_elements_result[element] = all_elements_counts[element]\n \n return common_elements_result", "tests": ["assert count_common_elements([\n {'a': ['apple', 'banana'], 'b': ['orange', 'apple']},\n {'c': ['grape', 'banana', 'kiwi'], 'd': ['apple', 'grape']}\n ]) == {'apple': 3, 'banana': 2, 'grape': 2}", "assert count_common_elements([\n {'x': ['a', 'b', 'c']},\n {'y': ['b', 'd'], 'z': ['c', 'e']}\n ]) == {'b': 2, 'c': 2}", "assert count_common_elements([\n {'p': ['hello']},\n {'q': ['world']}\n ]) == {}", "assert count_common_elements([\n {'k1': ['foo', 'bar']},\n {'k2': ['bar', 'baz']},\n {'k3': ['foo', 'baz', 'qux']}\n ]) == {'foo': 2, 'bar': 2, 'baz': 2}", "assert count_common_elements([]) == {}", "assert count_common_elements([\n {'single': ['unique']}\n ]) == {}"]} {"name": "count_word_frequencies", "topic": "dictionaries and counting", "prompt": "def count_word_frequencies(text: str) -> dict[str, int]:\n \"\"\"\n Counts the frequency of each word in a given text. Words are case-insensitive and\n punctuation marks (periods, commas, exclamation points, question marks, semicolons,\n colons) should be removed. The result should be a dictionary where keys are\n lowercase words and values are their counts.\n\n Example:\n count_word_frequencies(\"Hello world! This is a test, hello again.\")\n should return:\n {'hello': 2, 'world': 1, 'this': 1, 'is': 1, 'a': 1, 'test': 1, 'again': 1}\n \"\"\"", "solution": "def count_word_frequencies(text: str) -> dict[str, int]:\n \"\"\"\n Counts the frequency of each word in a given text. Words are case-insensitive and\n punctuation marks (periods, commas, exclamation points, question marks, semicolons,\n colons) should be removed. The result should be a dictionary where keys are\n lowercase words and values are their counts.\n\n Example:\n count_word_frequencies(\"Hello world! This is a test, hello again.\")\n should return:\n {'hello': 2, 'world': 1, 'this': 1, 'is': 1, 'a': 1, 'test': 1, 'again': 1}\n \"\"\"\n punctuation = \".!?,;:'\"\n cleaned_text = text.lower()\n for punc_char in punctuation:\n cleaned_text = cleaned_text.replace(punc_char, '')\n \n words = cleaned_text.split()\n \n word_counts = {}\n for word in words:\n word_counts[word] = word_counts.get(word, 0) + 1\n \n return word_counts", "tests": ["assert count_word_frequencies(\"Hello world! This is a test, hello again.\") == {'hello': 2, 'world': 1, 'this': 1, 'is': 1, 'a': 1, 'test': 1, 'again': 1}", "assert count_word_frequencies(\"Python is fun. Python is powerful! Is it?\") == {'python': 2, 'is': 3, 'fun': 1, 'powerful': 1, 'it': 1}", "assert count_word_frequencies(\"A B C A B C\") == {'a': 2, 'b': 2, 'c': 2}", "assert count_word_frequencies(\"One word only.\") == {'one': 1, 'word': 1, 'only': 1}", "assert count_word_frequencies(\"\") == {}", "assert count_word_frequencies(\"Multiple spaces between words, and! punc: tuation;\") == {'multiple': 1, 'spaces': 1, 'between': 1, 'words': 1, 'and': 1, 'punc': 1, 'tuation': 1}"]} {"name": "most_frequent_words", "topic": "dictionaries and counting", "prompt": "def most_frequent_words(text: str, k: int) -> list[str]:\n \"\"\"\n Given a string `text` and an integer `k`, return a list of the `k` most frequent words in the text.\n If there are ties in frequency, words should be sorted alphabetically. If there are fewer than `k`\n unique words, return all unique words sorted by frequency (and then alphabetically).\n\n Words are case-insensitive. Punctuation (anything not a letter or space) should be ignored.\n Empty strings or strings containing only punctuation/spaces should result in an empty list.\n\n Examples:\n most_frequent_words(\"The quick brown fox jumps over the lazy fox.\", 2) == [\"fox\", \"the\"]\n most_frequent_words(\"apple banana apple cherry banana\", 3) == [\"apple\", \"banana\", \"cherry\"]\n most_frequent_words(\"A, B. C! D? A@ B#\", 1) == [\"a\"]\n most_frequent_words(\"\", 5) == []\n most_frequent_words(\"Hello world, hello!\", 1) == [\"hello\"]\n \"\"\"", "solution": "import re\nfrom collections import Counter\n\ndef most_frequent_words(text: str, k: int) -> list[str]:\n if not text:\n return []\n\n # Normalize text: convert to lowercase and remove non-alphanumeric characters\n cleaned_text = re.sub(r'[^a-zA-Z\\s]', '', text).lower()\n \n # Split into words and filter out empty strings\n words = [word for word in cleaned_text.split() if word]\n\n if not words:\n return []\n\n # Count word frequencies\n word_counts = Counter(words)\n\n # Sort words: first by frequency (descending), then alphabetically (ascending)\n # We create a list of (word, frequency) tuples to sort.\n sorted_words = sorted(\n word_counts.items(),\n key=lambda item: (-item[1], item[0])\n )\n\n # Extract the top k words\n result = [word for word, count in sorted_words[:k]]\n\n return result", "tests": ["assert most_frequent_words(\"The quick brown fox jumps over the lazy fox.\", 2) == [\"fox\", \"the\"]", "assert most_frequent_words(\"apple banana apple cherry banana\", 3) == [\"apple\", \"banana\", \"cherry\"]", "assert most_frequent_words(\"A, B. C! D? A@ B#\", 1) == [\"a\"]", "assert most_frequent_words(\"\", 5) == []", "assert most_frequent_words(\"Hello world, hello!\", 1) == [\"hello\"]", "assert most_frequent_words(\" test TEST tEsT, again and again. \", 2) == [\"test\", \"again\"]", "assert most_frequent_words(\"one two three four five\", 10) == [\"five\", \"four\", \"one\", \"three\", \"two\"]"]} {"name": "count_word_frequencies_295", "topic": "dictionaries and counting", "prompt": "def count_word_frequencies(text: str) -> dict[str, int]:\n \"\"\"\n Counts the frequency of each word in a given text. Words are case-insensitive\n and the function should return frequencies in lowercase. Punctuation marks\n (periods, commas, exclamation points, question marks, semicolons, colons)\n should be removed from words before counting. Words are separated by spaces.\n\n For example:\n count_word_frequencies(\"Hello world! This is a test. Hello again.\")\n should return:\n {'hello': 2, 'world': 1, 'this': 1, 'is': 1, 'a': 1, 'test': 1, 'again': 1}\n \"\"\"", "solution": "def count_word_frequencies(text: str) -> dict[str, int]:\n word_counts = {}\n punctuation = \".!,?;:\"\n \n # Remove punctuation and split into words\n for p in punctuation:\n text = text.replace(p, \"\")\n \n words = text.lower().split()\n \n for word in words:\n word_counts[word] = word_counts.get(word, 0) + 1\n \n return word_counts", "tests": ["assert count_word_frequencies(\"Hello world! This is a test. Hello again.\") == {'hello': 2, 'world': 1, 'this': 1, 'is': 1, 'a': 1, 'test': 1, 'again': 1}", "assert count_word_frequencies(\"Python is fun. Python is powerful!\") == {'python': 2, 'is': 2, 'fun': 1, 'powerful': 1}", "assert count_word_frequencies(\"A B C a b c.\") == {'a': 2, 'b': 2, 'c': 2}", "assert count_word_frequencies(\"SingleWord\") == {'singleword': 1}", "assert count_word_frequencies(\"\") == {}", "assert count_word_frequencies(\" Multiple spaces here! \") == {'multiple': 1, 'spaces': 1, 'here': 1}"]} {"name": "count_word_frequencies_619", "topic": "dictionaries and counting", "prompt": "def count_word_frequencies(text: str) -> dict[str, int]:\n \"\"\"\n Counts the frequency of each word in a given text, ignoring case and punctuation.\n \n Words are defined as sequences of alphabetic characters. All words should be\n converted to lowercase before counting. Punctuation and spaces should be\n treated as delimiters. Empty strings or strings with only non-alphabetic characters\n should result in an empty dictionary.\n\n Args:\n text: The input string.\n\n Returns:\n A dictionary where keys are lowercase words and values are their frequencies.\n\n Examples:\n >>> count_word_frequencies(\"Hello world, hello!\")\n {'hello': 2, 'world': 1}\n >>> count_word_frequencies(\"A quick brown fox jumped over the lazy dog.\")\n {'a': 1, 'quick': 1, 'brown': 1, 'fox': 1, 'jumped': 1, 'over': 1, 'the': 1, 'lazy': 1, 'dog': 1}\n >>> count_word_frequencies(\"Python is fun. Is Python easy?\")\n {'python': 2, 'is': 2, 'fun': 1, 'easy': 1}\n >>> count_word_frequencies(\" \")\n {}\n >>> count_word_frequencies(\"123 !@#\")\n {}\n \"\"\"", "solution": "import re\n\ndef count_word_frequencies(text: str) -> dict[str, int]:\n \"\"\"\n Counts the frequency of each word in a given text, ignoring case and punctuation.\n \n Words are defined as sequences of alphabetic characters. All words should be\n converted to lowercase before counting. Punctuation and spaces should be\n treated as delimiters. Empty strings or strings with only non-alphabetic characters\n should result in an empty dictionary.\n\n Args:\n text: The input string.\n\n Returns:\n A dictionary where keys are lowercase words and values are their frequencies.\n\n Examples:\n >>> count_word_frequencies(\"Hello world, hello!\")\n {'hello': 2, 'world': 1}\n >>> count_word_frequencies(\"A quick brown fox jumped over the lazy dog.\")\n {'a': 1, 'quick': 1, 'brown': 1, 'fox': 1, 'jumped': 1, 'over': 1, 'the': 1, 'lazy': 1, 'dog': 1}\n >>> count_word_frequencies(\"Python is fun. Is Python easy?\")\n {'python': 2, 'is': 2, 'fun': 1, 'easy': 1}\n >>> count_word_frequencies(\" \")\n {}\n >>> count_word_frequencies(\"123 !@#\")\n {}\n \"\"\"\n frequencies = {}\n # Use re.findall to find all sequences of alphabetic characters\n # Convert to lowercase immediately\n words = [word.lower() for word in re.findall(r'[a-zA-Z]+', text)]\n \n for word in words:\n frequencies[word] = frequencies.get(word, 0) + 1\n \n return frequencies", "tests": ["assert count_word_frequencies(\"Hello world, hello!\") == {'hello': 2, 'world': 1}", "assert count_word_frequencies(\"A quick brown fox jumped over the lazy dog.\") == {'a': 1, 'quick': 1, 'brown': 1, 'fox': 1, 'jumped': 1, 'over': 1, 'the': 1, 'lazy': 1, 'dog': 1}", "assert count_word_frequencies(\"Python is fun. Is Python easy?\") == {'python': 2, 'is': 2, 'fun': 1, 'easy': 1}", "assert count_word_frequencies(\" \") == {}", "assert count_word_frequencies(\"123 !@#\") == {}", "assert count_word_frequencies(\"ONE, two. One more time! TWO\") == {'one': 2, 'two': 2, 'more': 1, 'time': 1}"]} {"name": "count_anagram_groups", "topic": "dictionaries and counting", "prompt": "def count_anagram_groups(words: list[str]) -> int:\n \"\"\"\n Given a list of words, return the number of unique anagram groups.\n\n An anagram group is a set of words where all words in the set are anagrams\n of each other. Two words are anagrams if they contain the same characters\n with the same frequencies, regardless of order or case.\n\n For example:\n - ['listen', 'silent', 'inlets'] form one anagram group.\n - ['Hello', 'olleh', 'world'] form two groups: ['Hello', 'olleh'] and ['world'].\n - ['a', 'A'] are considered anagrams.\n\n All input words will consist of alphabetic characters only.\n The list of words can be empty.\n \"\"\"", "solution": "def count_anagram_groups(words: list[str]) -> int:\n \"\"\"\n Given a list of words, return the number of unique anagram groups.\n\n An anagram group is a set of words where all words in the set are anagrams\n of each other. Two words are anagrams if they contain the same characters\n with the same frequencies, regardless of order or case.\n\n For example:\n - ['listen', 'silent', 'inlets'] form one anagram group.\n - ['Hello', 'olleh', 'world'] form two groups: ['Hello', 'olleh'] and ['world'].\n - ['a', 'A'] are considered anagrams.\n\n All input words will consist of alphabetic characters only.\n The list of words can be empty.\n \"\"\"\n if not words:\n return 0\n\n anagram_map = {}\n for word in words:\n # Normalize word: convert to lowercase and sort characters\n normalized_word = ''.join(sorted(word.lower()))\n anagram_map[normalized_word] = anagram_map.get(normalized_word, 0) + 1\n\n return len(anagram_map)", "tests": ["assert count_anagram_groups(['listen', 'silent', 'inlets', 'hello', 'olleh', 'world']) == 3", "assert count_anagram_groups(['a', 'A', 'b', 'B', 'c']) == 3", "assert count_anagram_groups(['cat', 'act', 'tac']) == 1", "assert count_anagram_groups(['apple', 'banana', 'orange']) == 3", "assert count_anagram_groups(['tar', 'rat', 'art', 'star', 'rats']) == 2", "assert count_anagram_groups([]) == 0", "assert count_anagram_groups(['single']) == 1"]} {"name": "count_unique_elements_in_lists", "topic": "dictionaries and counting", "prompt": "def count_unique_elements_in_lists(list_of_lists: list[list]) -> dict[int, int]:\n \"\"\"\n Given a list of lists of integers, return a dictionary where keys are the unique integers\n found across all inner lists, and values are the total count of occurrences for each integer.\n\n The order of keys in the output dictionary does not matter.\n\n For example:\n count_unique_elements_in_lists([[1, 2, 1], [3, 2], [1, 4]])\n should return {1: 3, 2: 2, 3: 1, 4: 1}\n\n count_unique_elements_in_lists([[], [5, 5], [6]])\n should return {5: 2, 6: 1}\n\n count_unique_elements_in_lists([[]])\n should return {}\n \"\"\"", "solution": "def count_unique_elements_in_lists(list_of_lists: list[list]) -> dict[int, int]:\n counts = {}\n for inner_list in list_of_lists:\n for item in inner_list:\n counts[item] = counts.get(item, 0) + 1\n return counts", "tests": ["assert count_unique_elements_in_lists([[1, 2, 1], [3, 2], [1, 4]]) == {1: 3, 2: 2, 3: 1, 4: 1}", "assert count_unique_elements_in_lists([[], [5, 5], [6]]) == {5: 2, 6: 1}", "assert count_unique_elements_in_lists([[]]) == {}", "assert count_unique_elements_in_lists([[10, 20], [30, 40], [10, 30, 50]]) == {10: 2, 20: 1, 30: 2, 40: 1, 50: 1}", "assert count_unique_elements_in_lists([[7, 7, 7], [7]]) == {7: 4}", "assert count_unique_elements_in_lists([[-1, 0], [0, 1]]) == {-1: 1, 0: 2, 1: 1}"]} {"name": "count_word_frequencies_955", "topic": "dictionaries and counting", "prompt": "def count_word_frequencies(text: str) -> dict[str, int]:\n \"\"\"\n Counts the frequency of each word in the given text.\n\n Words are case-insensitive and should be converted to lowercase.\n Punctuation (any character that is not a letter or a number) should be removed.\n The function should return a dictionary where keys are words (strings) and values are their counts (inteppers).\n\n Args:\n text: The input string.\n\n Returns:\n A dictionary with word frequencies.\n\n Examples:\n >>> count_word_frequencies(\"Hello world! Hello Python.\")\n {'hello': 2, 'world': 1, 'python': 1}\n >>> count_word_frequencies(\"This is a test. Is this fun?\")\n {'this': 2, 'is': 2, 'a': 1, 'test': 1, 'fun': 1}\n >>> count_word_frequencies(\"One, Two, One Two Three!\")\n {'one': 2, 'two': 2, 'three': 1}\n \"\"\"", "solution": "import re\n\ndef count_word_frequencies(text: str) -> dict[str, int]:\n \"\"\"\n Counts the frequency of each word in the given text.\n\n Words are case-insensitive and should be converted to lowercase.\n Punctuation (any character that is not a letter or a number) should be removed.\n The function should return a dictionary where keys are words (strings) and values are their counts (integers).\n\n Args:\n text: The input string.\n\n Returns:\n A dictionary with word frequencies.\n \"\"\"\n # Convert to lowercase and replace non-alphanumeric characters with spaces\n cleaned_text = re.sub(r'[^a-z0-9]+', ' ', text.lower())\n words = cleaned_text.split()\n\n word_counts = {}\n for word in words:\n if word:\n word_counts[word] = word_counts.get(word, 0) + 1\n\n return word_counts", "tests": ["assert count_word_frequencies(\"Hello world! Hello Python.\") == {'hello': 2, 'world': 1, 'python': 1}", "assert count_word_frequencies(\"This is a test. Is this fun?\") == {'this': 2, 'is': 2, 'a': 1, 'test': 1, 'fun': 1}", "assert count_word_frequencies(\"One, Two, One Two Three!\") == {'one': 2, 'two': 2, 'three': 1}", "assert count_word_frequencies(\"A B C A B A\") == {'a': 3, 'b': 2, 'c': 1}", "assert count_word_frequencies(\"\") == {}", "assert count_word_frequencies(\" Multiple spaces between words. \") == {'multiple': 1, 'spaces': 1, 'between': 1, 'words': 1}", "assert count_word_frequencies(\"Python, python, PYTHON! Version 3.9\") == {'python': 3, 'version': 1, '3': 1, '9': 1}"]} {"name": "count_word_frequencies_497", "topic": "dictionaries and counting", "prompt": "def count_word_frequencies(text_data: str) -> dict[str, int]:\n \"\"\"\n Counts the frequency of each unique word in a given string.\n\n Words are case-insensitive. Punctuation (periods, commas, exclamation marks, question marks,\n colons, semicolons) should be stripped from words before counting. The function should\n return a dictionary where keys are lowercase words and values are their frequencies.\n\n Args:\n text_data: A string containing one or more sentences.\n\n Returns:\n A dictionary mapping lowercase words to their counts.\n\n Examples:\n >>> count_word_frequencies(\"Hello world! Hello there.\")\n {'hello': 2, 'world': 1, 'there': 1}\n >>> count_word_frequencies(\"Python is fun, python is powerful.\")\n {'python': 2, 'is': 2, 'fun': 1, 'powerful': 1}\n \"\"\"", "solution": "import string\n\ndef count_word_frequencies(text_data: str) -> dict[str, int]:\n word_counts = {}\n # Create a translation table to remove punctuation\n translator = str.maketrans('', '', string.punctuation)\n \n # Split the text into words, convert to lowercase, and strip punctuation\n words = text_data.lower().split()\n \n for word in words:\n cleaned_word = word.translate(translator)\n if cleaned_word: # Ensure we don't count empty strings if punctuation was the only character\n word_counts[cleaned_word] = word_counts.get(cleaned_word, 0) + 1\n \n return word_counts", "tests": ["assert count_word_frequencies(\"Hello world! Hello there.\") == {'hello': 2, 'world': 1, 'there': 1}", "assert count_word_frequencies(\"Python is fun, python is powerful.\") == {'python': 2, 'is': 2, 'fun': 1, 'powerful': 1}", "assert count_word_frequencies(\"A quick brown fox jumps over the lazy dog. The dog barks.\") == {'a': 1, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'the': 2, 'lazy': 1, 'dog': 2, 'barks': 1}", "assert count_word_frequencies(\"One, two, three. One, two.\") == {'one': 2, 'two': 2, 'three': 1}", "assert count_word_frequencies(\"\") == {}", "assert count_word_frequencies(\"!!!???...\" ) == {}"]} {"name": "count_word_frequencies_287", "topic": "dictionaries and counting", "prompt": "def count_word_frequencies(text: str) -> dict[str, int]:\n \"\"\"\n Counts the frequency of each word in a given text, ignoring case and punctuation.\n \n Words are defined as sequences of alphabetic characters. All words should be\n converted to lowercase before counting. Punctuation and whitespace should\n be treated as word separators.\n \n Args:\n text: The input string containing words and potentially punctuation.\n \n Returns:\n A dictionary where keys are lowercase words and values are their\n corresponding frequencies.\n \n Examples:\n >>> count_word_frequencies(\"Hello world! Hello there.\")\n {'hello': 2, 'world': 1, 'there': 1}\n >>> count_word_frequencies(\"A B a b C\")\n {'a': 2, 'b': 2, 'c': 1}\n >>> count_word_frequencies(\"One-two three, four.\")\n {'one': 1, 'two': 1, 'three': 1, 'four': 1}\n >>> count_word_frequencies(\"\")\n {}\n >>> count_word_frequencies(\" Hello World!!! \")\n {'hello': 1, 'world': 1}\n \"\"\"", "solution": "import re\n\ndef count_word_frequencies(text: str) -> dict[str, int]:\n \"\"\"\n Counts the frequency of each word in a given text, ignoring case and punctuation.\n \n Words are defined as sequences of alphabetic characters. All words should be\n converted to lowercase before counting. Punctuation and whitespace should\n be treated as word separators.\n \n Args:\n text: The input string containing words and potentially punctuation.\n \n Returns:\n A dictionary where keys are lowercase words and values are their\n corresponding frequencies.\n \n Examples:\n >>> count_word_frequencies(\"Hello world! Hello there.\")\n {'hello': 2, 'world': 1, 'there': 1}\n >>> count_word_frequencies(\"A B a b C\")\n {'a': 2, 'b': 2, 'c': 1}\n >>> count_word_frequencies(\"One-two three, four.\")\n {'one': 1, 'two': 1, 'three': 1, 'four': 1}\n >>> count_word_frequencies(\"\")\n {}\n >>> count_word_frequencies(\" Hello World!!! \")\n {'hello': 1, 'world': 1}\n \"\"\"\n frequencies = {}\n # Use re.findall to get all sequences of alphabetic characters\n # re.IGNORECASE makes the match case-insensitive for the extraction\n # but we will convert to lowercase explicitly for the dictionary key\n words = re.findall(r'[a-zA-Z]+', text)\n \n for word in words:\n lower_word = word.lower()\n frequencies[lower_word] = frequencies.get(lower_word, 0) + 1\n \n return frequencies", "tests": ["assert count_word_frequencies(\"Hello world! Hello there.\") == {'hello': 2, 'world': 1, 'there': 1}", "assert count_word_frequencies(\"A B a b C\") == {'a': 2, 'b': 2, 'c': 1}", "assert count_word_frequencies(\"One-two three, four.\") == {'one': 1, 'two': 1, 'three': 1, 'four': 1}", "assert count_word_frequencies(\"\") == {}", "assert count_word_frequencies(\" Hello World!!! \") == {'hello': 1, 'world': 1}", "assert count_word_frequencies(\"Python is fun. Python is great! PYTHON.\") == {'python': 3, 'is': 2, 'fun': 1, 'great': 1}"]} {"name": "most_frequent_words_439", "topic": "dictionaries and counting", "prompt": "def most_frequent_words(text: str, k: int) -> list[str]:\n \"\"\"\n Given a string of text and an integer k, return a list of the k most frequent words.\n \n Words should be case-insensitive, and the returned list should contain lowercase words.\n Punctuation (anything not an alphanumeric character or a space) should be removed.\n \n If multiple words have the same frequency and would tie for a spot within the top k,\n they should be sorted alphabetically.\n \n If there are fewer than k unique words, return all unique words sorted alphabetically.\n\n The returned list should be sorted by frequency (most frequent first).\n Words with the same frequency should be sorted alphabetically.\n\n Example:\n most_frequent_words(\"Hello world! Hello Python. Python is great.\", 2) == ['hello', 'python']\n most_frequent_words(\"apple banana apple orange banana\", 1) == ['apple']\n \"\"\"", "solution": "import re\nfrom collections import Counter\n\ndef most_frequent_words(text: str, k: int) -> list[str]:\n if not text:\n return []\n\n # Remove punctuation and convert to lowercase\n cleaned_text = re.sub(r'[^a-zA-Z0-9\\s]', '', text).lower()\n words = cleaned_text.split()\n\n if not words:\n return []\n\n word_counts = Counter(words)\n\n # Sort by frequency (descending) then alphabetically (ascending)\n sorted_words = sorted(\n word_counts.items(),\n key=lambda item: (-item[1], item[0])\n )\n\n result = [word for word, count in sorted_words[:k]]\n return result", "tests": ["assert most_frequent_words(\"Hello world! Hello Python. Python is great.\", 2) == ['hello', 'python']", "assert most_frequent_words(\"Apple banana apple Orange banana\", 1) == ['apple']", "assert most_frequent_words(\"The quick brown fox jumps over the lazy dog. The fox is quick.\", 3) == ['the', 'fox', 'quick']", "assert most_frequent_words(\"A B A C B D\", 5) == ['a', 'b', 'c', 'd']", "assert most_frequent_words(\"one two three one two\", 1) == ['one']", "assert most_frequent_words(\"\", 3) == []", "assert most_frequent_words(\"Just one word.\", 5) == ['just', 'one', 'word']", "assert most_frequent_words(\"Apple APPLE apple\", 1) == ['apple']", "assert most_frequent_words(\"a b c a b c d e f g h i j k l m n o p q r s t u v w x y z\", 26) == ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']", "assert most_frequent_words(\"Cat Dog cat dog\", 2) == ['cat', 'dog']"]} {"name": "count_word_frequencies_429", "topic": "dictionaries and counting", "prompt": "def count_word_frequencies(text: str) -> dict[str, int]:\n \"\"\"\n Counts the frequency of each word in a given text. Words are case-insensitive\n and should be converted to lowercase. Punctuation (periods, commas, question marks,\n exclamation marks, colons, semicolons) should be removed from words before counting.\n \n For example:\n count_word_frequencies(\"Hello world! This is a test. Hello again.\")\n should return:\n {'hello': 2, 'world': 1, 'this': 1, 'is': 1, 'a': 1, 'test': 1, 'again': 1}\n \"\"\"\n", "solution": "def count_word_frequencies(text: str) -> dict[str, int]:\n \"\"\"\n Counts the frequency of each word in a given text. Words are case-insensitive\n and should be converted to lowercase. Punctuation (periods, commas, question marks,\n exclamation marks, colons, semicolons) should be removed from words before counting.\n \n For example:\n count_word_frequencies(\"Hello world! This is a test. Hello again.\")\n should return:\n {'hello': 2, 'world': 1, 'this': 1, 'is': 1, 'a': 1, 'test': 1, 'again': 1}\n \"\"\"\n frequencies = {}\n punctuation_to_remove = \".!?,:;\"\n \n # Replace punctuation with spaces to ensure word splitting works correctly\n for char in punctuation_to_remove:\n text = text.replace(char, ' ')\n \n words = text.lower().split()\n \n for word in words:\n # After splitting, there might still be empty strings if multiple punctuation marks were together\n if word:\n frequencies[word] = frequencies.get(word, 0) + 1\n \n return frequencies\n", "tests": ["assert count_word_frequencies(\"Hello world! This is a test. Hello again.\") == {'hello': 2, 'world': 1, 'this': 1, 'is': 1, 'a': 1, 'test': 1, 'again': 1}", "assert count_word_frequencies(\"Python is fun. Python is great!\") == {'python': 2, 'is': 2, 'fun': 1, 'great': 1}", "assert count_word_frequencies(\"One, two; three four five. One... two!!!\") == {'one': 2, 'two': 2, 'three': 1, 'four': 1, 'five': 1}", "assert count_word_frequencies(\"A B C a b c.\") == {'a': 2, 'b': 2, 'c': 2}", "assert count_word_frequencies(\" leading and trailing spaces \") == {'leading': 1, 'and': 1, 'trailing': 1, 'spaces': 1}", "assert count_word_frequencies(\"\") == {}"]} {"name": "count_word_frequencies_220", "topic": "dictionaries and counting", "prompt": "def count_word_frequencies(text_corpus: list[str]) -> dict[str, int]:\n \"\"\"\n Counts the frequency of each unique word across a list of text documents.\n\n The function should process a list of strings, where each string represents a document.\n Words should be case-insensitive (e.g., \"The\" and \"the\" count as the same word).\n Punctuation (e.g., periods, commas, exclamation marks, question marks, colons, semicolons)\n should be removed from words before counting. Hyphenated words (e.g., \"self-contained\")\n should be treated as two separate words if the hyphen is surrounded by letters,\n otherwise the hyphen should be removed (e.g., \"end-.\" becomes \"end\").\n Numbers should also be treated as words.\n\n Args:\n text_corpus: A list of strings, where each string is a document.\n\n Returns:\n A dictionary where keys are lowercase words and values are their total counts\n across all documents.\n\n Examples:\n >>> count_word_frequencies([\"Hello world.\", \"World is great!\"])\n {'hello': 1, 'world': 2, 'is': 1, 'great': 1}\n >>> count_word_frequencies([\"One, two-three.\", \"Two (two) again.\"])\n {'one': 1, 'two': 3, 'three': 1, 'again': 1}\n >>> count_word_frequencies([\"Python is fun-tastic.\", \"Fun-tastic is it?\"])\n {'python': 1, 'is': 2, 'fun': 2, 'tastic': 2, 'it': 1}\n \"\"\"", "solution": "import re\n\ndef count_word_frequencies(text_corpus: list[str]) -> dict[str, int]:\n word_counts = {}\n for document in text_corpus:\n # Normalize hyphens: replace 'a-b' with 'a b', remove other hyphens\n processed_doc = re.sub(r'([a-zA-Z])-(?=[a-zA-Z])', r'\\1 ', document)\n processed_doc = re.sub(r'-', '', processed_doc)\n\n # Remove punctuation except spaces and letters/numbers\n # Then split by whitespace\n words = re.findall(r'\\b[a-zA-Z0-9]+\\b', processed_doc.lower())\n for word in words:\n word_counts[word] = word_counts.get(word, 0) + 1\n return word_counts", "tests": ["assert count_word_frequencies([\"Hello world.\", \"World is great!\"]) == {'hello': 1, 'world': 2, 'is': 1, 'great': 1}", "assert count_word_frequencies([\"One, two-three.\", \"Two (two) again.\"]) == {'one': 1, 'two': 3, 'three': 1, 'again': 1}", "assert count_word_frequencies([\"Python is fun-tastic.\", \"Fun-tastic is it?\"]) == {'python': 1, 'is': 2, 'fun': 2, 'tastic': 2, 'it': 1}", "assert count_word_frequencies([\"A B C. D-E-F.\", \"GHI! JKL? MNO; PQR: STU, VWX.\"]) == {'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'ghi': 1, 'jkl': 1, 'mno': 1, 'pqr': 1, 'stu': 1, 'vwx': 1}", "assert count_word_frequencies([\"123 test 456.\", \"Test 123 again.\"]) == {'123': 2, 'test': 2, '456': 1, 'again': 1}", "assert count_word_frequencies([\"\", \" \", \" \", \"!@#$\"]) == {}"]} {"name": "most_frequent_words_189", "topic": "dictionaries and counting", "prompt": "def most_frequent_words(text: str, k: int) -> list[str]:\n \"\"\"\n Given a string `text` and an integer `k`, return a list of the `k` most frequent words in the text.\n Words should be case-insensitive and treated as sequences of alphabetic characters.\n Non-alphabetic characters act as word delimiters. Words must contain at least one alphabetic character.\n \n If multiple words have the same frequency and would tie for the k-th position, \n prioritize them alphabetically (case-insensitive).\n The returned list of words should also be sorted alphabetically (case-insensitive) if they have the same frequency,\n and then by frequency in descending order.\n \n Example:\n text = \"The quick brown fox jumps over the lazy dog. Fox jumps high.\"\n k = 2\n # Word counts: {'the': 2, 'fox': 2, 'jumps': 2, 'quick': 1, 'brown': 1, 'over': 1, 'lazy': 1, 'dog': 1, 'high': 1}\n # Sorted by frequency (desc), then alphabetically (asc):\n # [('fox', 2), ('jumps', 2), ('the', 2), ('brown', 1), ...]\n # Top 2: ['fox', 'jumps'] (alphabetical tie-break for equal frequency)\n \n Args:\n text: The input string.\n k: The number of most frequent words to return.\n\n Returns:\n A list of the `k` most frequent words, sorted as described above.\n If `k` is greater than the number of unique words, return all unique words \n sorted by frequency (desc) then alphabetically (asc).\n \"\"\"", "solution": "import re\nfrom collections import Counter\n\ndef most_frequent_words(text: str, k: int) -> list[str]:\n words = re.findall(r'[a-zA-Z]+', text.lower())\n \n word_counts = Counter(words)\n \n # Sort by: \n # 1. Frequency (descending)\n # 2. Word (alphabetical, ascending)\n sorted_words = sorted(\n word_counts.items(), \n key=lambda item: (-item[1], item[0])\n )\n \n result = [word for word, count in sorted_words[:k]]\n \n return result", "tests": ["assert most_frequent_words(\"The quick brown fox jumps over the lazy dog. Fox jumps high.\", 2) == [\"fox\", \"jumps\"]", "assert most_frequent_words(\"Apple Banana apple Orange BANANA apple\", 3) == [\"apple\", \"banana\", \"orange\"]", "assert most_frequent_words(\"a b c a b c a b c\", 1) == [\"a\"]", "assert most_frequent_words(\"Hello world! hello Python. World is great.\", 5) == [\"hello\", \"world\", \"great\", \"is\", \"python\"]", "assert most_frequent_words(\"one two three four five six seven eight nine ten\", 10) == [\"eight\", \"five\", \"four\", \"nine\", \"one\", \"seven\", \"six\", \"ten\", \"three\", \"two\"]", "assert most_frequent_words(\"\", 1) == []", "assert most_frequent_words(\"123 test 456 another test!\", 2) == [\"test\", \"another\"]"]} {"name": "count_unique_elements_in_lists_664", "topic": "dictionaries and counting", "prompt": "def count_unique_elements_in_lists(list_of_lists: list[list[str]]) -> dict[str, int]:\n \"\"\"\n Counts the occurrences of each unique string element across all inner lists.\n\n Given a list of lists, where each inner list contains string elements,\n this function should return a dictionary where keys are the unique string\n elements found in any inner list, and values are their total counts\n across all inner lists.\n\n For example:\n count_unique_elements_in_lists([['a', 'b'], ['b', 'c', 'a']])\n should return {'a': 2, 'b': 2, 'c': 1}\n\n count_unique_elements_in_lists([['apple', 'banana'], ['apple', 'orange'], ['grape']])\n should return {'apple': 2, 'banana': 1, 'orange': 1, 'grape': 1}\n\n The input list_of_lists can be empty, or contain empty inner lists.\n Elements within inner lists can be duplicated.\n \"\"\"", "solution": "def count_unique_elements_in_lists(list_of_lists: list[list[str]]) -> dict[str, int]:\n counts = {}\n for inner_list in list_of_lists:\n for item in inner_list:\n counts[item] = counts.get(item, 0) + 1\n return counts", "tests": ["assert count_unique_elements_in_lists([['a', 'b'], ['b', 'c', 'a']]) == {'a': 2, 'b': 2, 'c': 1}", "assert count_unique_elements_in_lists([['apple', 'banana'], ['apple', 'orange'], ['grape']]) == {'apple': 2, 'banana': 1, 'orange': 1, 'grape': 1}", "assert count_unique_elements_in_lists([['x', 'y', 'x'], ['y', 'z']]) == {'x': 2, 'y': 2, 'z': 1}", "assert count_unique_elements_in_lists([]) == {}", "assert count_unique_elements_in_lists([[], ['test'], []]) == {'test': 1}", "assert count_unique_elements_in_lists([['one', 'one', 'two'], ['two', 'three']]) == {'one': 2, 'two': 2, 'three': 1}"]} {"name": "count_word_frequencies_897", "topic": "dictionaries and counting", "prompt": "def count_word_frequencies(text: str) -> dict[str, int]:\n \"\"\"\n Counts the frequency of each word in a given text. Words are case-insensitive\n and the function should return all words in lowercase. Punctuation marks\n (periods, commas, exclamation marks, question marks, semicolons, colons)\n should be removed from words before counting. Hyphenated words should be\n treated as a single word (e.g., \"self-contained\" is one word).\n Empty strings or strings with only punctuation should result in an empty dictionary.\n\n Args:\n text: The input string containing words.\n\n Returns:\n A dictionary where keys are lowercase words and values are their frequencies.\n\n Examples:\n >>> count_word_frequencies(\"Hello world, hello there!\")\n {'hello': 2, 'world': 1, 'there': 1}\n >>> count_word_frequencies(\"Python is fun. Is it not?\")\n {'python': 1, 'is': 2, 'fun': 1, 'it': 1, 'not': 1}\n >>> count_word_frequencies(\"Self-contained function.\")\n {'self-contained': 1, 'function': 1}\n >>> count_word_frequencies(\" \")\n {}\n >>> count_word_frequencies(\"!!!\")\n {}\n \"\"\"", "solution": "def count_word_frequencies(text: str) -> dict[str, int]:\n if not text.strip():\n return {}\n\n # Define punctuation to remove, but keep hyphens for now\n punctuation_to_remove = str.maketrans('', '', '.,!?;:')\n \n # Remove punctuation, convert to lowercase, and split into words\n # We first remove specific punctuation, then split by space\n # and then clean up individual words more carefully.\n \n cleaned_text = text.translate(punctuation_to_remove).lower()\n words = cleaned_text.split()\n \n word_counts = {}\n for word in words:\n # Further clean each word, specifically handling cases where\n # punctuation might have been adjacent to a hyphen or at the start/end\n # after initial removal. A simple regex or more robust parsing could be used\n # but for this specific problem, splitting and then stripping is sufficient\n # given the defined punctuation and hyphen rule.\n \n # We need to be careful not to strip hyphens if they are part of a word.\n # The prompt implies hyphens within words are kept.\n # The initial translate should handle most cases. If a word is just a hyphen,\n # or starts/ends with one after initial cleaning, it should be ignored if not part of a valid word.\n \n # A more robust way: use regex to split, or carefully strip non-alphanumeric\n # but preserve internal hyphens.\n \n # Given the prompt's simplicity, the current approach of removing specific\n # punctuation and then splitting by space is largely effective. \n # Words like '---hello---' would become 'hello' after stripping, but 'self-contained' \n # remains 'self-contained'.\n \n # A simpler interpretation of 'remove punctuation' could be: strip non-alphanumeric\n # characters from the start and end of each word, but only specific ones.\n \n # Let's refine the word cleaning slightly for potential edge cases.\n # The current `translate` already removes the specified punctuation.\n # The remaining issue could be if a word ends up being empty after cleaning.\n \n if word:\n word_counts[word] = word_counts.get(word, 0) + 1\n \n return word_counts", "tests": ["assert count_word_frequencies(\"Hello world, hello there!\") == {'hello': 2, 'world': 1, 'there': 1}", "assert count_word_frequencies(\"Python is fun. Is it not?\") == {'python': 1, 'is': 2, 'fun': 1, 'it': 1, 'not': 1}", "assert count_word_frequencies(\"Self-contained function: easy, self-contained.\") == {'self-contained': 2, 'function': 1, 'easy': 1}", "assert count_word_frequencies(\"A B a b. C!\") == {'a': 2, 'b': 2, 'c': 1}", "assert count_word_frequencies(\" \") == {}", "assert count_word_frequencies(\"!!! ???\") == {}"]} {"name": "most_frequent_words_366", "topic": "dictionaries and counting", "prompt": "def most_frequent_words(text: str, k: int) -> list[str]:\n \"\"\"\n Given a string of text and an integer k, return a list of the k most frequent words.\n \n Words should be case-insensitive, and the returned list should contain lowercase words.\n Punctuation should be ignored. Words are separated by spaces.\n \n If there are ties in frequency, words should be sorted alphabetically.\n If k is greater than the number of unique words, return all unique words sorted by frequency\n (and then alphabetically for ties).\n \n Example:\n most_frequent_words(\"The quick brown fox jumps over the lazy fox.\", 2) == [\"fox\", \"the\"]\n most_frequent_words(\"Apple Banana apple Cherry cherry Banana\", 2) == [\"apple\", \"banana\"]\n most_frequent_words(\"A B C A B A\", 3) == [\"a\", \"b\", \"c\"]\n \"\"\"", "solution": "import collections\nimport re\n\ndef most_frequent_words(text: str, k: int) -> list[str]:\n if not text.strip():\n return []\n\n # Normalize text: convert to lowercase and remove punctuation\n normalized_text = re.sub(r'[\\W_]+', ' ', text.lower())\n words = normalized_text.split()\n\n if not words:\n return []\n\n # Count word frequencies\n word_counts = collections.Counter(words)\n\n # Sort words by frequency (descending) then alphabetically (ascending)\n # The key for sorting is a tuple: (-frequency, word)\n sorted_words = sorted(\n word_counts.items(),\n key=lambda item: (-item[1], item[0])\n )\n\n # Extract the top k words\n result = [word for word, count in sorted_words[:k]]\n\n return result", "tests": ["assert most_frequent_words(\"The quick brown fox jumps over the lazy fox.\", 2) == [\"fox\", \"the\"]", "assert most_frequent_words(\"Apple Banana apple Cherry cherry Banana\", 2) == [\"apple\", \"banana\"]", "assert most_frequent_words(\"A B C A B A\", 3) == [\"a\", \"b\", \"c\"]", "assert most_frequent_words(\"Hello world hello there world!\", 1) == [\"hello\"]", "assert most_frequent_words(\"One two three four five.\", 10) == [\"five\", \"four\", \"one\", \"three\", \"two\"]", "assert most_frequent_words(\"\", 5) == []", "assert most_frequent_words(\"a, b. c! a? b;\", 2) == [\"a\", \"b\"]", "assert most_frequent_words(\"Test test TEST\", 1) == [\"test\"]"]} {"name": "count_unique_elements_in_lists_646", "topic": "dictionaries and counting", "prompt": "def count_unique_elements_in_lists(list_of_lists: list[list]) -> dict[int, int]:\n \"\"\"\n Counts the frequency of each unique element across all sublists in a given list of lists.\n \n The function should return a dictionary where keys are the unique elements encountered\n (which are guaranteed to be integers) and values are their total counts across all sublists.\n If the input list_of_lists is empty, an empty dictionary should be returned.\n\n Args:\n list_of_lists: A list where each element is itself a list of integers.\n\n Returns:\n A dictionary mapping each unique integer element to its total count across all sublists.\n\n Examples:\n >>> count_unique_elements_in_lists([[1, 2], [2, 3, 1]])\n {1: 2, 2: 2, 3: 1}\n >>> count_unique_elements_in_lists([[], [5, 5], [1]])\n {5: 2, 1: 1}\n >>> count_unique_elements_in_lists([])\n {}\n \"\"\"", "solution": "def count_unique_elements_in_lists(list_of_lists: list[list]) -> dict[int, int]:\n counts = {}\n for sublist in list_of_lists:\n for element in sublist:\n counts[element] = counts.get(element, 0) + 1\n return counts", "tests": ["assert count_unique_elements_in_lists([[1, 2], [2, 3, 1]]) == {1: 2, 2: 2, 3: 1}", "assert count_unique_elements_in_lists([[], [5, 5], [1]]) == {5: 2, 1: 1}", "assert count_unique_elements_in_lists([]) == {}", "assert count_unique_elements_in_lists([[-1, 0, -1], [0, 0]]) == {-1: 2, 0: 3}", "assert count_unique_elements_in_lists([[10, 20, 10], [30, 40], [10]]) == {10: 3, 20: 1, 30: 1, 40: 1}", "assert count_unique_elements_in_lists([[1,1,1,1]]) == {1: 4}"]} {"name": "sum_of_divisors", "topic": "basic math and number theory", "prompt": "def sum_of_divisors(n: int) -> int:\n \"\"\"\n Calculates the sum of all positive divisors of a given positive integer n.\n A divisor of n is an integer that divides n without leaving a remainder.\n For example, the divisors of 6 are 1, 2, 3, and 6, and their sum is 1 + 2 + 3 + 6 = 12.\n\n The input n will always be a positive integer (n >= 1).\n \n Args:\n n: A positive integer.\n\n Returns:\n The sum of all positive divisors of n.\n \"\"\"", "solution": "def sum_of_divisors(n: int) -> int:\n if n == 1:\n return 1\n total_sum = 0\n for i in range(1, int(n**0.5) + 1):\n if n % i == 0:\n total_sum += i\n if i * i != n:\n total_sum += n // i\n return total_sum", "tests": ["assert sum_of_divisors(1) == 1", "assert sum_of_divisors(6) == 12", "assert sum_of_divisors(7) == 8", "assert sum_of_divisors(10) == 18", "assert sum_of_divisors(28) == 56", "assert sum_of_divisors(100) == 217"]} {"name": "sum_of_divisors_580", "topic": "basic math and number theory", "prompt": "def sum_of_divisors(n: int) -> int:\n \"\"\"\n Calculates the sum of all positive divisors of a given positive integer n.\n A divisor of n is an integer that divides n evenly, leaving no remainder.\n For example, the divisors of 6 are 1, 2, 3, and 6. Their sum is 1 + 2 + 3 + 6 = 12.\n\n The input n will always be a positive integer (n >= 1).\n \n Args:\n n: A positive integer.\n\n Returns:\n The sum of all positive divisors of n.\n \"\"\"", "solution": "def sum_of_divisors(n: int) -> int:\n if n == 1:\n return 1\n total_sum = 0\n for i in range(1, int(n**0.5) + 1):\n if n % i == 0:\n total_sum += i\n if i * i != n:\n total_sum += n // i\n return total_sum", "tests": ["assert sum_of_divisors(1) == 1", "assert sum_of_divisors(6) == 12", "assert sum_of_divisors(7) == 8", "assert sum_of_divisors(10) == 18", "assert sum_of_divisors(12) == 28", "assert sum_of_divisors(100) == 217"]} {"name": "is_prime_factorable", "topic": "basic math and number theory", "prompt": "def is_prime_factorable(n, prime_factors):\n \"\"\"\n Checks if a positive integer 'n' can be formed by multiplying only the given 'prime_factors'.\n Each prime factor in 'prime_factors' can be used multiple times.\n If 'n' is 1, it is considered factorable if 'prime_factors' is not empty (representing the empty product).\n If 'n' is 1 and 'prime_factors' is empty, it returns False.\n\n Args:\n n (int): The positive integer to check (n >= 1).\n prime_factors (list): A list of unique prime numbers (integers > 1) allowed for factorization.\n The list may be empty.\n\n Returns:\n bool: True if 'n' can be formed by multiplying elements from 'prime_factors', False otherwise.\n Returns False if any element in 'prime_factors' is not prime.\n Returns False if any element in 'prime_factors' is not unique.\n \"\"\"", "solution": "import math\n\ndef is_prime_factorable(n, prime_factors):\n if n < 1:\n return False\n\n if not isinstance(prime_factors, list):\n return False\n\n if n == 1:\n return bool(prime_factors) # If n is 1, it's factorable if there are any factors to form an empty product\n\n if not prime_factors:\n return False # If n > 1 and no prime factors are provided, it cannot be factorable\n\n # Validate prime_factors: uniqueness and primality\n seen_factors = set()\n for p in prime_factors:\n if not isinstance(p, int) or p <= 1:\n return False # Not a valid prime number\n if p in seen_factors:\n return False # Duplicate prime factor\n if not is_prime(p):\n return False # Not a prime number\n seen_factors.add(p)\n\n # Sort prime_factors to simplify division logic\n sorted_factors = sorted(list(seen_factors))\n\n temp_n = n\n for p in sorted_factors:\n while temp_n % p == 0:\n temp_n //= p\n \n return temp_n == 1\n\ndef is_prime(num):\n if num < 2:\n return False\n for i in range(2, int(math.sqrt(num)) + 1):\n if num % i == 0:\n return False\n return True", "tests": ["assert is_prime_factorable(12, [2, 3]) == True", "assert is_prime_factorable(30, [2, 3, 5]) == True", "assert is_prime_factorable(7, [2, 3]) == False", "assert is_prime_factorable(1, [2, 3]) == True", "assert is_prime_factorable(1, []) == False", "assert is_prime_factorable(10, [2, 5, 5]) == False", "assert is_prime_factorable(10, [2, 5]) == True", "assert is_prime_factorable(12, [2, 3, 7]) == True", "assert is_prime_factorable(35, [5, 7]) == True", "assert is_prime_factorable(36, [2, 3]) == True", "assert is_prime_factorable(36, [2]) == False", "assert is_prime_factorable(27, [3]) == True", "assert is_prime_factorable(27, [2, 3]) == True", "assert is_prime_factorable(100, [2, 5]) == True", "assert is_prime_factorable(100, [2, 3, 5]) == True", "assert is_prime_factorable(100, [3, 5]) == False", "assert is_prime_factorable(4, [2]) == True", "assert is_prime_factorable(4, [2, 2]) == False", "assert is_prime_factorable(13, [2, 3, 5, 7, 11]) == False", "assert is_prime_factorable(0, [2]) == False", "assert is_prime_factorable(10, [2, 4]) == False", "assert is_prime_factorable(10, [2, -5]) == False", "assert is_prime_factorable(10, [2, 1]) == False", "assert is_prime_factorable(10, [2, 3, 5, 7]) == True"]} {"name": "sum_of_divisors_309", "topic": "basic math and number theory", "prompt": "def sum_of_divisors(n: int) -> int:\n \"\"\"\n Calculates the sum of all positive divisors of a given positive integer n.\n A divisor of n is an integer that divides n without leaving a remainder.\n This includes 1 and n itself.\n\n For example:\n sum_of_divisors(1) == 1 (divisors: {1})\n sum_of_divisors(6) == 12 (divisors: {1, 2, 3, 6})\n sum_of_divisors(7) == 8 (divisors: {1, 7})\n\n Args:\n n: A positive integer (n >= 1).\n\n Returns:\n The sum of all positive divisors of n.\n \"\"\"", "solution": "def sum_of_divisors(n: int) -> int:\n if n < 1:\n raise ValueError(\"Input must be a positive integer.\")\n \n total_sum = 0\n for i in range(1, int(n**0.5) + 1):\n if n % i == 0:\n total_sum += i\n if i * i != n:\n total_sum += n // i\n return total_sum", "tests": ["assert sum_of_divisors(1) == 1", "assert sum_of_divisors(6) == 12", "assert sum_of_divisors(7) == 8", "assert sum_of_divisors(10) == 18", "assert sum_of_divisors(28) == 56", "assert sum_of_divisors(100) == 217"]} {"name": "sum_of_divisors_331", "topic": "basic math and number theory", "prompt": "def sum_of_divisors(n: int) -> int:\n \"\"\"\n Calculates the sum of all positive divisors of a given positive integer n.\n A divisor of n is an integer that divides n without leaving a remainder.\n For example, the divisors of 6 are 1, 2, 3, and 6, and their sum is 1 + 2 + 3 + 6 = 12.\n\n Args:\n n: A positive integer.\n\n Returns:\n The sum of all positive divisors of n.\n\n Raises:\n ValueError: If n is not a positive integer.\n \"\"\"", "solution": "def sum_of_divisors(n: int) -> int:\n if not isinstance(n, int) or n <= 0:\n raise ValueError(\"n must be a positive integer.\")\n\n total_sum = 0\n for i in range(1, int(n**0.5) + 1):\n if n % i == 0:\n total_sum += i\n if i * i != n:\n total_sum += n // i\n return total_sum", "tests": ["assert sum_of_divisors(1) == 1", "assert sum_of_divisors(6) == 12", "assert sum_of_divisors(10) == 18", "assert sum_of_divisors(28) == 56", "assert sum_of_divisors(97) == 98", "assert sum_of_divisors(100) == 217"]} {"name": "sum_of_divisors_296", "topic": "basic math and number theory", "prompt": "def sum_of_divisors(n: int) -> int:\n \"\"\"\n Calculates the sum of all positive divisors of a given positive integer n, \n including 1 and n itself.\n\n For example:\n sum_of_divisors(1) == 1 (divisors: 1)\n sum_of_divisors(6) == 12 (divisors: 1, 2, 3, 6)\n sum_of_divisors(10) == 18 (divisors: 1, 2, 5, 10)\n\n Args:\n n: A positive integer.\n\n Returns:\n The sum of its positive divisors.\n\n Raises:\n ValueError: If n is not a positive integer.\n \"\"\"", "solution": "def sum_of_divisors(n: int) -> int:\n if not isinstance(n, int) or n <= 0:\n raise ValueError(\"Input must be a positive integer.\")\n\n if n == 1:\n return 1\n\n total_sum = 0\n for i in range(1, int(n**0.5) + 1):\n if n % i == 0:\n total_sum += i\n if i * i != n:\n total_sum += n // i\n return total_sum", "tests": ["assert sum_of_divisors(1) == 1", "assert sum_of_divisors(6) == 12", "assert sum_of_divisors(10) == 18", "assert sum_of_divisors(7) == 8", "assert sum_of_divisors(12) == 28", "assert sum_of_divisors(100) == 217"]} {"name": "sum_of_divisors_173", "topic": "basic math and number theory", "prompt": "def sum_of_divisors(n: int) -> int:\n \"\"\"\n Calculates the sum of all positive divisors of a given positive integer n.\n A divisor includes 1 and n itself.\n\n For example:\n sum_of_divisors(1) == 1 (divisors: 1)\n sum_of_divisors(6) == 12 (divisors: 1, 2, 3, 6)\n sum_of_divisors(7) == 8 (divisors: 1, 7)\n\n Args:\n n: A positive integer.\n\n Returns:\n The sum of its positive divisors.\n \n Raises:\n ValueError: If n is not a positive integer.\n \"\"\"", "solution": "def sum_of_divisors(n: int) -> int:\n if not isinstance(n, int) or n <= 0:\n raise ValueError(\"Input n must be a positive integer.\")\n\n if n == 1:\n return 1\n\n total_sum = 0\n for i in range(1, int(n**0.5) + 1):\n if n % i == 0:\n total_sum += i\n if i * i != n:\n total_sum += n // i\n return total_sum", "tests": ["assert sum_of_divisors(1) == 1", "assert sum_of_divisors(6) == 12", "assert sum_of_divisors(7) == 8", "assert sum_of_divisors(10) == 18", "assert sum_of_divisors(12) == 28", "assert sum_of_divisors(100) == 217"]} {"name": "sum_of_divisors_182", "topic": "basic math and number theory", "prompt": "def sum_of_divisors(n: int) -> int:\n \"\"\"\n Calculates the sum of all positive divisors of a given positive integer n.\n A divisor of n is an integer that divides n without leaving a remainder.\n For example, the divisors of 6 are 1, 2, 3, and 6, so their sum is 1 + 2 + 3 + 6 = 12.\n\n Args:\n n: A positive integer (n >= 1).\n\n Returns:\n The sum of all positive divisors of n.\n\n Examples:\n sum_of_divisors(1) == 1\n sum_of_divisors(6) == 12\n sum_of_divisors(7) == 8\n \"\"\"", "solution": "def sum_of_divisors(n: int) -> int:\n if n < 1:\n raise ValueError(\"Input must be a positive integer.\")\n \n total_sum = 0\n for i in range(1, int(n**0.5) + 1):\n if n % i == 0:\n total_sum += i\n if i * i != n:\n total_sum += n // i\n return total_sum", "tests": ["assert sum_of_divisors(1) == 1", "assert sum_of_divisors(6) == 12", "assert sum_of_divisors(7) == 8", "assert sum_of_divisors(10) == 18", "assert sum_of_divisors(28) == 56", "assert sum_of_divisors(100) == 217"]} {"name": "sum_of_divisors_965", "topic": "basic math and number theory", "prompt": "def sum_of_divisors(n: int) -> int:\n \"\"\"\n Calculates the sum of all positive divisors of a given positive integer n.\n A divisor of n is an integer that divides n without leaving a remainder.\n For example, the divisors of 6 are 1, 2, 3, and 6, and their sum is 1 + 2 + 3 + 6 = 12.\n\n The input n is guaranteed to be a positive integer (n >= 1).\n\n Args:\n n: A positive integer.\n\n Returns:\n The sum of all positive divisors of n.\n \"\"\"", "solution": "def sum_of_divisors(n: int) -> int:\n if n == 1:\n return 1\n\n total_sum = 0\n for i in range(1, int(n**0.5) + 1):\n if n % i == 0:\n total_sum += i\n if i * i != n:\n total_sum += n // i\n return total_sum", "tests": ["assert sum_of_divisors(1) == 1", "assert sum_of_divisors(6) == 12", "assert sum_of_divisors(7) == 8", "assert sum_of_divisors(10) == 18", "assert sum_of_divisors(28) == 56", "assert sum_of_divisors(100) == 217"]} {"name": "is_prime_factorable_304", "topic": "basic math and number theory", "prompt": "def is_prime_factorable(n, prime_factors):\n \"\"\"\n Checks if a positive integer 'n' can be formed by multiplying only the given 'prime_factors'.\n The prime_factors list contains distinct prime numbers. 'n' must be greater than 0.\n If 'n' is 1, it's considered factorable by an empty product (or any set of prime factors).\n\n Args:\n n (int): The positive integer to check (n > 0).\n prime_factors (list): A list of distinct prime numbers.\n\n Returns:\n bool: True if 'n' can be formed by multiplying only the given prime_factors, False otherwise.\n \"\"\"\n", "solution": "def is_prime_factorable(n, prime_factors):\n if n == 1:\n return True\n if n <= 0:\n raise ValueError(\"n must be a positive integer.\")\n\n temp_n = n\n for p in sorted(prime_factors):\n while temp_n % p == 0:\n temp_n //= p\n\n return temp_n == 1", "tests": ["assert is_prime_factorable(12, [2, 3]) == True", "assert is_prime_factorable(30, [2, 3, 5]) == True", "assert is_prime_factorable(15, [2, 3, 5]) == True", "assert is_prime_factorable(14, [2, 3, 5]) == False", "assert is_prime_factorable(1, [2, 3]) == True", "assert is_prime_factorable(7, [2, 3, 5]) == False", "assert is_prime_factorable(16, [2]) == True", "assert is_prime_factorable(12, [3, 2]) == True"]} {"name": "sum_of_divisors_813", "topic": "basic math and number theory", "prompt": "def sum_of_divisors(n: int) -> int:\n \"\"\"\n Calculates the sum of all positive divisors of a given positive integer n.\n A divisor of n is an integer that divides n without leaving a remainder.\n For example, the divisors of 6 are 1, 2, 3, and 6, so their sum is 1 + 2 + 3 + 6 = 12.\n\n The function should work for n up to 10^6.\n\n Args:\n n: A positive integer.\n\n Returns:\n The sum of all positive divisors of n.\n\n Raises:\n ValueError: If n is not a positive integer.\n \"\"\"", "solution": "def sum_of_divisors(n: int) -> int:\n if not isinstance(n, int) or n <= 0:\n raise ValueError(\"n must be a positive integer.\")\n\n if n == 1:\n return 1\n\n total_sum = 0\n i = 1\n while i * i <= n:\n if n % i == 0:\n total_sum += i\n if i * i != n:\n total_sum += n // i\n i += 1\n return total_sum", "tests": ["assert sum_of_divisors(1) == 1", "assert sum_of_divisors(6) == 12", "assert sum_of_divisors(10) == 18", "assert sum_of_divisors(12) == 28", "assert sum_of_divisors(7) == 8", "assert sum_of_divisors(100) == 217"]} {"name": "sum_of_divisors_673", "topic": "basic math and number theory", "prompt": "def sum_of_divisors(n: int) -> int:\n \"\"\"\n Calculates the sum of all positive divisors of a given positive integer n.\n A divisor of n is an integer that divides n without leaving a remainder.\n\n For example, the divisors of 6 are 1, 2, 3, and 6. Their sum is 1 + 2 + 3 + 6 = 12.\n\n Args:\n n: A positive integer (n >= 1).\n\n Returns:\n The sum of all positive divisors of n.\n \"\"\"", "solution": "def sum_of_divisors(n: int) -> int:\n if n < 1:\n raise ValueError(\"n must be a positive integer\")\n\n total_sum = 0\n for i in range(1, int(n**0.5) + 1):\n if n % i == 0:\n total_sum += i\n if i * i != n:\n total_sum += n // i\n return total_sum", "tests": ["assert sum_of_divisors(1) == 1", "assert sum_of_divisors(6) == 12", "assert sum_of_divisors(7) == 8", "assert sum_of_divisors(10) == 18", "assert sum_of_divisors(12) == 28", "assert sum_of_divisors(100) == 217"]} {"name": "sum_of_divisors_548", "topic": "basic math and number theory", "prompt": "def sum_of_divisors(n: int) -> int:\n \"\"\"\n Calculate the sum of all positive divisors of a given positive integer n.\n A divisor of n is an integer that divides n without leaving a remainder.\n\n For example:\n - If n = 1, divisors are {1}, sum = 1.\n - If n = 6, divisors are {1, 2, 3, 6}, sum = 1 + 2 + 3 + 6 = 12.\n - If n = 7, divisors are {1, 7}, sum = 1 + 7 = 8.\n\n Args:\n n: A positive integer.\n\n Returns:\n The sum of all positive divisors of n.\n\n Raises:\n ValueError: If n is not a positive integer.\n \"\"\"", "solution": "def sum_of_divisors(n: int) -> int:\n \"\"\"\n Calculate the sum of all positive divisors of a given positive integer n.\n A divisor of n is an integer that divides n without leaving a remainder.\n\n For example:\n - If n = 1, divisors are {1}, sum = 1.\n - If n = 6, divisors are {1, 2, 3, 6}, sum = 1 + 2 + 3 + 6 = 12.\n - If n = 7, divisors are {1, 7}, sum = 1 + 7 = 8.\n\n Args:\n n: A positive integer.\n\n Returns:\n The sum of all positive divisors of n.\n\n Raises:\n ValueError: If n is not a positive integer.\n \"\"\"\n if not isinstance(n, int) or n <= 0:\n raise ValueError(\"n must be a positive integer.\")\n\n if n == 1:\n return 1\n\n total_sum = 0\n for i in range(1, int(n**0.5) + 1):\n if n % i == 0:\n total_sum += i\n if i * i != n:\n total_sum += n // i\n return total_sum", "tests": ["assert sum_of_divisors(1) == 1", "assert sum_of_divisors(6) == 12", "assert sum_of_divisors(7) == 8", "assert sum_of_divisors(12) == 28", "assert sum_of_divisors(30) == 72", "assert sum_of_divisors(100) == 217"]} {"name": "sum_of_prime_factors", "topic": "basic math and number theory", "prompt": "def sum_of_prime_factors(n: int) -> int:\n \"\"\"\n Calculates the sum of unique prime factors of a given positive integer n.\n If n is 1, the sum is 0 (as 1 has no prime factors).\n If n is a prime number, the sum is n itself.\n\n For example:\n sum_of_prime_factors(1) == 0\n sum_of_prime_factors(2) == 2\n sum_of_prime_factors(10) == 7 (prime factors are 2, 5; sum = 2+5)\n sum_of_prime_factors(12) == 5 (prime factors are 2, 3; sum = 2+3)\n sum_of_prime_factors(77) == 18 (prime factors are 7, 11; sum = 7+11)\n sum_of_prime_factors(99) == 14 (prime factors are 3, 11; sum = 3+11)\n\n Args:\n n: A positive integer.\n\n Returns:\n The sum of the unique prime factors of n.\n \"\"\"", "solution": "def sum_of_prime_factors(n: int) -> int:\n if n <= 1:\n return 0\n\n sum_factors = 0\n temp_n = n\n factor = 2\n unique_factors = set()\n\n while factor * factor <= temp_n:\n if temp_n % factor == 0:\n unique_factors.add(factor)\n while temp_n % factor == 0:\n temp_n //= factor\n factor += 1\n\n if temp_n > 1:\n unique_factors.add(temp_n)\n\n return sum(unique_factors)", "tests": ["assert sum_of_prime_factors(1) == 0", "assert sum_of_prime_factors(2) == 2", "assert sum_of_prime_factors(10) == 7", "assert sum_of_prime_factors(12) == 5", "assert sum_of_prime_factors(77) == 18", "assert sum_of_prime_factors(99) == 14", "assert sum_of_prime_factors(100) == 7", "assert sum_of_prime_factors(221) == 30"]} {"name": "is_prime_and_sum_digits", "topic": "basic math and number theory", "prompt": "def is_prime_and_sum_digits(n: int) -> tuple[bool, int]:\n \"\"\"Checks if a given integer n is a prime number and also returns the sum of its digits.\n\n A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.\n The sum of digits is calculated for the absolute value of n.\n\n Args:\n n: An integer.\n\n Returns:\n A tuple where the first element is a boolean indicating if n is prime (True) or not (False).\n The second element is an integer representing the sum of the absolute value of n's digits.\n For n <= 1, the first element (is_prime) should be False.\n If n is negative, its primality is determined by its absolute value.\n\n Examples:\n is_prime_and_sum_digits(7) == (True, 7)\n is_prime_and_sum_digits(10) == (False, 1)\n is_prime_and_sum_digits(13) == (True, 4)\n is_prime_and_sum_digits(-17) == (True, 8)\n is_prime_and_sum_digits(1) == (False, 1)\n is_prime_and_sum_digits(0) == (False, 0)\n is_prime_and_sum_digits(2) == (True, 2)\n \"\"\"", "solution": "import math\n\ndef is_prime_and_sum_digits(n: int) -> tuple[bool, int]:\n \"\"\"Checks if a given integer n is a prime number and also returns the sum of its digits.\n\n A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.\n The sum of digits is calculated for the absolute value of n.\n\n Args:\n n: An integer.\n\n Returns:\n A tuple where the first element is a boolean indicating if n is prime (True) or not (False).\n The second element is an integer representing the sum of the absolute value of n's digits.\n For n <= 1, the first element (is_prime) should be False.\n If n is negative, its primality is determined by its absolute value.\n\n Examples:\n is_prime_and_sum_digits(7) == (True, 7)\n is_prime_and_sum_digits(10) == (False, 1)\n is_prime_and_sum_digits(13) == (True, 4)\n is_prime_and_sum_digits(-17) == (True, 8)\n is_prime_and_sum_digits(1) == (False, 1)\n is_prime_and_sum_digits(0) == (False, 0)\n is_prime_and_sum_digits(2) == (True, 2)\n \"\"\"\n abs_n = abs(n)\n\n # Calculate sum of digits\n sum_digits = 0\n temp_n = abs_n\n if temp_n == 0:\n sum_digits = 0\n else:\n while temp_n > 0:\n sum_digits += temp_n % 10\n temp_n //= 10\n\n # Check for primality\n is_prime = True\n if abs_n <= 1:\n is_prime = False\n elif abs_n == 2:\n is_prime = True\n elif abs_n % 2 == 0:\n is_prime = False\n else:\n for i in range(3, int(math.sqrt(abs_n)) + 1, 2):\n if abs_n % i == 0:\n is_prime = False\n break\n\n return is_prime, sum_digits", "tests": ["assert is_prime_and_sum_digits(7) == (True, 7)", "assert is_prime_and_sum_digits(10) == (False, 1)", "assert is_prime_and_sum_digits(13) == (True, 4)", "assert is_prime_and_sum_digits(-17) == (True, 8)", "assert is_prime_and_sum_digits(1) == (False, 1)", "assert is_prime_and_sum_digits(0) == (False, 0)", "assert is_prime_and_sum_digits(2) == (True, 2)", "assert is_prime_and_sum_digits(23) == (True, 5)", "assert is_prime_and_sum_digits(25) == (False, 7)", "assert is_prime_and_sum_digits(-1) == (False, 1)", "assert is_prime_and_sum_digits(97) == (True, 16)"]} {"name": "sum_of_divisors_709", "topic": "basic math and number theory", "prompt": "def sum_of_divisors(n: int) -> int:\n \"\"\"\n Calculates the sum of all positive divisors of a given positive integer n.\n\n A divisor of n is an integer that divides n without leaving a remainder.\n For example, the divisors of 6 are 1, 2, 3, and 6, and their sum is 1 + 2 + 3 + 6 = 12.\n\n The input n will always be a positive integer (n >= 1).\n\n Args:\n n: A positive integer.\n\n Returns:\n The sum of all positive divisors of n.\n \"\"\"", "solution": "def sum_of_divisors(n: int) -> int:\n if n == 1:\n return 1\n\n total_sum = 0\n for i in range(1, int(n**0.5) + 1):\n if n % i == 0:\n total_sum += i\n if i * i != n:\n total_sum += n // i\n return total_sum", "tests": ["assert sum_of_divisors(1) == 1", "assert sum_of_divisors(6) == 12", "assert sum_of_divisors(7) == 8", "assert sum_of_divisors(10) == 18", "assert sum_of_divisors(28) == 56", "assert sum_of_divisors(100) == 217"]} {"name": "sum_of_divisors_821", "topic": "basic math and number theory", "prompt": "def sum_of_divisors(n: int) -> int:\n \"\"\"\n Calculates the sum of all positive divisors of a given positive integer n.\n A divisor of n is an integer that divides n without leaving a remainder.\n For example, the divisors of 6 are 1, 2, 3, and 6. Their sum is 1 + 2 + 3 + 6 = 12.\n\n Args:\n n: A positive integer (n >= 1).\n\n Returns:\n The sum of all positive divisors of n.\n\n Examples:\n sum_of_divisors(1) == 1\n sum_of_divisors(6) == 12\n sum_of_divisors(7) == 8\n \"\"\"", "solution": "def sum_of_divisors(n: int) -> int:\n if n < 1:\n raise ValueError(\"Input must be a positive integer.\")\n \n total_sum = 0\n for i in range(1, int(n**0.5) + 1):\n if n % i == 0:\n total_sum += i\n if i * i != n:\n total_sum += n // i\n return total_sum", "tests": ["assert sum_of_divisors(1) == 1", "assert sum_of_divisors(6) == 12", "assert sum_of_divisors(7) == 8", "assert sum_of_divisors(10) == 18", "assert sum_of_divisors(12) == 28", "assert sum_of_divisors(100) == 217"]} {"name": "sum_of_divisors_651", "topic": "basic math and number theory", "prompt": "def sum_of_divisors(n: int) -> int:\n \"\"\"\n Calculates the sum of all positive divisors of a given positive integer n.\n\n A divisor of n is an integer that divides n without leaving a remainder.\n For example, the divisors of 6 are 1, 2, 3, and 6. Their sum is 1 + 2 + 3 + 6 = 12.\n\n The function should work efficiently for moderately large n.\n\n Args:\n n: A positive integer (n >= 1).\n\n Returns:\n The sum of all positive divisors of n.\n\n Examples:\n sum_of_divisors(1) == 1\n sum_of_divisors(6) == 12\n sum_of_divisors(10) == 18\n \"\"\"", "solution": "def sum_of_divisors(n: int) -> int:\n if n == 1:\n return 1\n\n total_sum = 0\n i = 1\n while i * i <= n:\n if n % i == 0:\n total_sum += i\n if i * i != n:\n total_sum += n // i\n i += 1\n return total_sum", "tests": ["assert sum_of_divisors(1) == 1", "assert sum_of_divisors(6) == 12", "assert sum_of_divisors(10) == 18", "assert sum_of_divisors(12) == 28", "assert sum_of_divisors(25) == 31", "assert sum_of_divisors(100) == 217", "assert sum_of_divisors(997) == 998"]} {"name": "sum_of_divisors_178", "topic": "basic math and number theory", "prompt": "def sum_of_divisors(n: int) -> int:\n \"\"\"\n Calculates the sum of all positive divisors of a given positive integer n.\n A divisor of n is an integer that divides n without leaving a remainder.\n For example, the divisors of 6 are 1, 2, 3, and 6, and their sum is 1 + 2 + 3 + 6 = 12.\n\n The input n will always be a positive integer (n >= 1).\n\n Args:\n n: A positive integer.\n\n Returns:\n The sum of all positive divisors of n.\n \"\"\"", "solution": "def sum_of_divisors(n: int) -> int:\n if n == 1:\n return 1\n \n total_sum = 0\n for i in range(1, int(n**0.5) + 1):\n if n % i == 0:\n total_sum += i\n if i * i != n:\n total_sum += n // i\n return total_sum", "tests": ["assert sum_of_divisors(1) == 1", "assert sum_of_divisors(6) == 12", "assert sum_of_divisors(10) == 18", "assert sum_of_divisors(7) == 8", "assert sum_of_divisors(12) == 28", "assert sum_of_divisors(100) == 217"]} {"name": "sum_of_divisors_202", "topic": "basic math and number theory", "prompt": "def sum_of_divisors(n: int) -> int:\n \"\"\"\n Calculates the sum of all positive divisors of a given positive integer n.\n A divisor of n is an integer that divides n without leaving a remainder.\n For example, the divisors of 6 are 1, 2, 3, and 6. Their sum is 1 + 2 + 3 + 6 = 12.\n\n The input n will always be a positive integer (n >= 1).\n\n Args:\n n: A positive integer.\n\n Returns:\n The sum of all positive divisors of n.\n \"\"\"", "solution": "def sum_of_divisors(n: int) -> int:\n if n == 1:\n return 1\n \n total_sum = 0\n for i in range(1, int(n**0.5) + 1):\n if n % i == 0:\n total_sum += i\n if i * i != n:\n total_sum += n // i\n return total_sum", "tests": ["assert sum_of_divisors(1) == 1", "assert sum_of_divisors(6) == 12", "assert sum_of_divisors(7) == 8", "assert sum_of_divisors(10) == 18", "assert sum_of_divisors(12) == 28", "assert sum_of_divisors(100) == 217"]} {"name": "is_prime", "topic": "basic math and number theory", "prompt": "def is_prime(n: int) -> bool:\n \"\"\"\n Check if a given positive integer n is a prime number.\n\n A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.\n\n Examples:\n is_prime(2) == True\n is_prime(1) == False\n is_prime(4) == False\n is_prime(17) == True\n \"\"\"", "solution": "def is_prime(n: int) -> bool:\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n return False\n i = 5\n while i * i <= n:\n if n % i == 0 or n % (i + 2) == 0:\n return False\n i += 6\n return True", "tests": ["assert is_prime(2) == True", "assert is_prime(1) == False", "assert is_prime(4) == False", "assert is_prime(17) == True", "assert is_prime(23) == True", "assert is_prime(997) == True", "assert is_prime(999) == False", "assert is_prime(0) == False"]} {"name": "sum_of_divisors_959", "topic": "basic math and number theory", "prompt": "def sum_of_divisors(n: int) -> int:\n \"\"\"\n Calculates the sum of all positive divisors of a given positive integer n.\n A divisor of n is an integer that divides n without leaving a remainder.\n For example, the divisors of 6 are 1, 2, 3, and 6, and their sum is 1 + 2 + 3 + 6 = 12.\n\n The input n will always be a positive integer (n >= 1).\n\n Args:\n n: A positive integer.\n\n Returns:\n The sum of all positive divisors of n.\n \"\"\"", "solution": "def sum_of_divisors(n: int) -> int:\n if n == 1:\n return 1\n \n total_sum = 0\n for i in range(1, int(n**0.5) + 1):\n if n % i == 0:\n total_sum += i\n if i * i != n:\n total_sum += n // i\n return total_sum", "tests": ["assert sum_of_divisors(1) == 1", "assert sum_of_divisors(6) == 12", "assert sum_of_divisors(7) == 8", "assert sum_of_divisors(10) == 18", "assert sum_of_divisors(12) == 28", "assert sum_of_divisors(100) == 217"]} {"name": "sum_of_divisors_920", "topic": "basic math and number theory", "prompt": "def sum_of_divisors(n: int) -> int:\n \"\"\"\n Calculates the sum of all positive divisors of a given positive integer n.\n A divisor of n is an integer that divides n without leaving a remainder.\n For example, the divisors of 6 are 1, 2, 3, and 6, so their sum is 1 + 2 + 3 + 6 = 12.\n\n The input n will always be a positive integer (n >= 1).\n\n Args:\n n: A positive integer.\n\n Returns:\n The sum of all positive divisors of n.\n \"\"\"", "solution": "def sum_of_divisors(n: int) -> int:\n if n == 1:\n return 1\n\n total_sum = 0\n for i in range(1, int(n**0.5) + 1):\n if n % i == 0:\n total_sum += i\n if i * i != n:\n total_sum += n // i\n return total_sum", "tests": ["assert sum_of_divisors(1) == 1", "assert sum_of_divisors(6) == 12", "assert sum_of_divisors(7) == 8", "assert sum_of_divisors(10) == 18", "assert sum_of_divisors(28) == 56", "assert sum_of_divisors(100) == 217"]} {"name": "sum_of_divisors_824", "topic": "basic math and number theory", "prompt": "def sum_of_divisors(n: int) -> int:\n \"\"\"Calculates the sum of all positive divisors of a given positive integer n.\n A divisor of n is an integer that divides n without leaving a remainder.\n For example, the divisors of 6 are 1, 2, 3, and 6, and their sum is 1 + 2 + 3 + 6 = 12.\n\n Args:\n n: A positive integer.\n\n Returns:\n The sum of all positive divisors of n.\n\n Raises:\n ValueError: If n is not a positive integer.\n \"\"\"", "solution": "def sum_of_divisors(n: int) -> int:\n if not isinstance(n, int) or n <= 0:\n raise ValueError(\"n must be a positive integer.\")\n\n if n == 1:\n return 1\n\n total_sum = 0\n for i in range(1, int(n**0.5) + 1):\n if n % i == 0:\n total_sum += i\n if i * i != n:\n total_sum += n // i\n return total_sum", "tests": ["assert sum_of_divisors(1) == 1", "assert sum_of_divisors(6) == 12", "assert sum_of_divisors(7) == 8", "assert sum_of_divisors(12) == 28", "assert sum_of_divisors(100) == 217", "assert sum_of_divisors(30) == 72"]} {"name": "sum_of_divisors_857", "topic": "basic math and number theory", "prompt": "def sum_of_divisors(n: int) -> int:\n \"\"\"\n Calculates the sum of all positive divisors of a given integer n.\n A divisor of n is an integer that divides n without leaving a remainder.\n For example, the divisors of 6 are 1, 2, 3, and 6, and their sum is 1 + 2 + 3 + 6 = 12.\n\n The input n will always be a positive integer (n >= 1).\n\n Args:\n n: A positive integer.\n\n Returns:\n The sum of all positive divisors of n.\n \"\"\"", "solution": "def sum_of_divisors(n: int) -> int:\n if n == 1:\n return 1\n \n total_sum = 0\n for i in range(1, int(n**0.5) + 1):\n if n % i == 0:\n total_sum += i\n if i * i != n:\n total_sum += n // i\n return total_sum", "tests": ["assert sum_of_divisors(1) == 1", "assert sum_of_divisors(6) == 12", "assert sum_of_divisors(7) == 8", "assert sum_of_divisors(12) == 28", "assert sum_of_divisors(100) == 217", "assert sum_of_divisors(28) == 56"]} {"name": "sum_of_divisors_317", "topic": "basic math and number theory", "prompt": "def sum_of_divisors(n: int) -> int:\n \"\"\"\n Calculates the sum of all positive divisors of a given positive integer n.\n A divisor of n is an integer that divides n without leaving a remainder.\n The divisors include 1 and n itself.\n\n For example:\n sum_of_divisors(1) == 1 (divisors: 1)\n sum_of_divisors(6) == 1 + 2 + 3 + 6 == 12 (divisors: 1, 2, 3, 6)\n sum_of_divisors(7) == 1 + 7 == 8 (divisors: 1, 7)\n\n Args:\n n: A positive integer.\n\n Returns:\n The sum of all positive divisors of n.\n\n Raises:\n ValueError: If n is not a positive integer.\n \"\"\"", "solution": "def sum_of_divisors(n: int) -> int:\n if not isinstance(n, int) or n <= 0:\n raise ValueError(\"n must be a positive integer.\")\n\n if n == 1:\n return 1\n\n total_sum = 0\n for i in range(1, int(n**0.5) + 1):\n if n % i == 0:\n total_sum += i\n if i * i != n:\n total_sum += n // i\n return total_sum", "tests": ["assert sum_of_divisors(1) == 1", "assert sum_of_divisors(6) == 12", "assert sum_of_divisors(7) == 8", "assert sum_of_divisors(12) == 28", "assert sum_of_divisors(100) == 217", "assert sum_of_divisors(36) == 91"]} {"name": "sum_of_divisors_860", "topic": "basic math and number theory", "prompt": "def sum_of_divisors(n: int) -> int:\n \"\"\"\n Calculate the sum of all positive divisors of a given positive integer n.\n A divisor of n is an integer d such that n/d is an integer.\n For example, the divisors of 6 are 1, 2, 3, and 6. Their sum is 1 + 2 + 3 + 6 = 12.\n\n The input n will always be a positive integer (n >= 1).\n \"\"\"", "solution": "def sum_of_divisors(n: int) -> int:\n if n == 1:\n return 1\n total_sum = 0\n for i in range(1, int(n**0.5) + 1):\n if n % i == 0:\n total_sum += i\n if i * i != n:\n total_sum += (n // i)\n return total_sum", "tests": ["assert sum_of_divisors(1) == 1", "assert sum_of_divisors(6) == 12", "assert sum_of_divisors(7) == 8", "assert sum_of_divisors(10) == 18", "assert sum_of_divisors(28) == 56", "assert sum_of_divisors(100) == 217"]} {"name": "flatten_nested_list", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a nested list of integers into a single, flat list of integers.\n The input list can contain integers or other lists, which in turn can contain integers or lists, and so on.\n\n For example:\n flatten_nested_list([1, [2, 3], [[4], 5]]) == [1, 2, 3, 4, 5]\n flatten_nested_list([1, 2, 3]) == [1, 2, 3]\n flatten_nested_list([]) == []\n flatten_nested_list([[], [1]]) == [1]\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n flat_list = []\n for item in nested_list:\n if isinstance(item, list):\n flat_list.extend(flatten_nested_list(item))\n else:\n flat_list.append(item)\n return flat_list", "tests": ["assert flatten_nested_list([1, [2, 3], [[4], 5]]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([1, 2, 3]) == [1, 2, 3]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([[], [1]]) == [1]", "assert flatten_nested_list([[[[[1]]]]]) == [1]", "assert flatten_nested_list([1, [2, [3, [4, 5], 6], 7], 8]) == [1, 2, 3, 4, 5, 6, 7, 8]"]} {"name": "flatten_nested_list_436", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a nested list of integers into a single, one-dimensional list.\n\n The input `nested_list` can contain integers directly or other lists.\n These inner lists can in turn contain integers or further nested lists, and so on.\n Empty lists should be ignored.\n\n For example:\n flatten_nested_list([1, [2, 3], [[4], 5]]) should return [1, 2, 3, 4, 5]\n flatten_nested_list([1, [], [2, [3, []]]]) should return [1, 2, 3]\n flatten_nested_list([]) should return []\n \"\"\"\n", "solution": "def flatten_nested_list(nested_list):\n flat_list = []\n for item in nested_list:\n if isinstance(item, list):\n flat_list.extend(flatten_nested_list(item))\n else:\n flat_list.append(item)\n return flat_list", "tests": ["assert flatten_nested_list([1, [2, 3], [[4], 5]]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([1, [], [2, [3, []]]]) == [1, 2, 3]", "assert flatten_nested_list([[[1, 2], 3], [4]]) == [1, 2, 3, 4]", "assert flatten_nested_list([7]) == [7]", "assert flatten_nested_list([[], [[], []], [1, [2, []]], [[[]]], 3]) == [1, 2, 3]"]} {"name": "flatten_nested_list_970", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a nested list of integers into a single, flat list of integers.\n The input list can contain integers or other lists, which in turn can contain integers or lists, and so on.\n\n For example:\n flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]\n flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]\n flatten_nested_list([]) == []\n flatten_nested_list([1, [], [2, [3]]]) == [1, 2, 3]\n\n Args:\n nested_list: A list containing integers or other lists.\n\n Returns:\n A new list containing all integers from the nested_list in a flattened order.\n \"\"\"\n", "solution": "def flatten_nested_list(nested_list):\n flattened = []\n for item in nested_list:\n if isinstance(item, list):\n flattened.extend(flatten_nested_list(item))\n else:\n flattened.append(item)\n return flattened", "tests": ["assert flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]", "assert flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([1, [], [2, [3]]]) == [1, 2, 3]", "assert flatten_nested_list([[[1, 2], 3], [4, [5]]]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([7]) == [7]"]} {"name": "flatten_nested_list_189", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"\n Flattens a deeply nested list of integers into a single, one-dimensional list of integers.\n \n The input list can contain integers or other lists (which can in turn contain integers or lists, and so on).\n The order of elements in the flattened list should be the same as their appearance in the original nested list.\n \n For example:\n flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]\n flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]\n flatten_nested_list([]) == []\n flatten_nested_list([[[1, 2], [3]], 4, [5]]) == [1, 2, 3, 4, 5]\n \n Args:\n nested_list: A list that can contain integers or other lists.\n \n Returns:\n A new list containing all integers from the nested_list in a flattened, one-dimensional structure.\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n flattened = []\n for element in nested_list:\n if isinstance(element, list):\n flattened.extend(flatten_nested_list(element))\n else:\n flattened.append(element)\n return flattened", "tests": ["assert flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]", "assert flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([[[1, 2], [3]], 4, [5]]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([1, 2, 3]) == [1, 2, 3]", "assert flatten_nested_list([[], [1, []], [[2], [3, [4]]]]) == [1, 2, 3, 4]"]} {"name": "flatten_nested_list_197", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a nested list of integers into a single, flat list of integers.\n The input list can contain integers or other lists, which in turn can contain integers or lists, and so on.\n\n For example:\n flatten_nested_list([1, [2, 3], [[4], 5]]) == [1, 2, 3, 4, 5]\n flatten_nested_list([]) == []\n flatten_nested_list([1, 2, 3]) == [1, 2, 3]\n flatten_nested_list([[1], [[2]]]) == [1, 2]\n\n Args:\n nested_list: A list potentially containing integers or other lists.\n\n Returns:\n A new list containing all integers from the nested_list in the order they appear when flattened.\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n flattened = []\n for item in nested_list:\n if isinstance(item, list):\n flattened.extend(flatten_nested_list(item))\n else:\n flattened.append(item)\n return flattened", "tests": ["assert flatten_nested_list([1, [2, 3], [[4], 5]]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([1, 2, 3]) == [1, 2, 3]", "assert flatten_nested_list([[1], [[2]]]) == [1, 2]", "assert flatten_nested_list([[[[100]]], 200, [300, [400]]]) == [100, 200, 300, 400]", "assert flatten_nested_list([5]) == [5]"]} {"name": "flatten_nested_list_690", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a nested list of integers into a single, non-nested list.\n \n The input `nested_list` can contain integers or other lists.\n Each inner list can also contain integers or further nested lists, and so on.\n The order of elements in the flattened list should be the same as their\n appearance in a depth-first traversal of the nested structure.\n\n For example:\n flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]\n flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]\n flatten_nested_list([]) == []\n flatten_nested_list([1, [], [2, [3]]]) == [1, 2, 3]\n\n Args:\n nested_list (list): A list potentially containing integers and other lists.\n\n Returns:\n list: A new list containing all integers from the nested_list in flattened order.\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n flattened = []\n for item in nested_list:\n if isinstance(item, list):\n flattened.extend(flatten_nested_list(item))\n else:\n flattened.append(item)\n return flattened", "tests": ["assert flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]", "assert flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([1, [], [2, [3]]]) == [1, 2, 3]", "assert flatten_nested_list([[[1, 2]], [3], [[4, [5]]]]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([7]) == [7]", "assert flatten_nested_list([[], [[]], [1, [], 2]]) == [1, 2]"]} {"name": "flatten_nested_list_572", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a nested list of integers into a single, non-nested list.\n \n The input `nested_list` can contain integers or other lists (which themselves\n can contain integers or other lists, and so on). Empty lists should be ignored.\n\n For example:\n flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]\n flatten_nested_list([1, [], [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]\n flatten_nested_list([]) == []\n flatten_nested_list([[[1, 2], 3], [4]]) == [1, 2, 3, 4]\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n flattened = []\n for item in nested_list:\n if isinstance(item, list):\n flattened.extend(flatten_nested_list(item))\n else:\n flattened.append(item)\n return flattened", "tests": ["assert flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]", "assert flatten_nested_list([1, [], [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([[[1, 2], 3], [4]]) == [1, 2, 3, 4]", "assert flatten_nested_list([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([[[[[[]]]]]]) == []"]} {"name": "flatten_nested_list_947", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a nested list of integers into a single, non-nested list of integers.\n The input list can contain integers or other lists (which in turn can contain integers or lists, and so on).\n\n For example:\n flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]\n flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]\n flatten_nested_list([]) == []\n flatten_nested_list([1, 2, 3]) == [1, 2, 3]\n flatten_nested_list([[]]) == []\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n flattened = []\n for item in nested_list:\n if isinstance(item, list):\n flattened.extend(flatten_nested_list(item))\n else:\n flattened.append(item)\n return flattened", "tests": ["assert flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]", "assert flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([1, 2, 3]) == [1, 2, 3]", "assert flatten_nested_list([[], [1, []], [[2, 3], 4]]) == [1, 2, 3, 4]", "assert flatten_nested_list([[[[[1]]]]]) == [1]"]} {"name": "flatten_nested_list_181", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a nested list of integers into a single, one-dimensional list.\n\n The input `nested_list` can contain integers directly or other lists.\n These inner lists can in turn contain integers or further nested lists, and so on.\n Empty lists should be ignored.\n\n For example:\n flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]\n flatten_nested_list([1, [], [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]\n flatten_nested_list([]) == []\n flatten_nested_list([1, 2, 3]) == [1, 2, 3]\n flatten_nested_list([[[1]], [2, [3]]]) == [1, 2, 3]\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n flat_list = []\n for item in nested_list:\n if isinstance(item, list):\n flat_list.extend(flatten_nested_list(item))\n else:\n flat_list.append(item)\n return flat_list", "tests": ["assert flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]", "assert flatten_nested_list([1, [], [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([1, 2, 3]) == [1, 2, 3]", "assert flatten_nested_list([[[1]], [2, [3]]]) == [1, 2, 3]", "assert flatten_nested_list([[[[[], 1]]], [2, [3, []], 4], 5]) == [1, 2, 3, 4, 5]"]} {"name": "flatten_nested_list_900", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"Flattens a deeply nested list of integers into a single flat list.\n\n The input list can contain integers or other lists, which in turn can contain\n integers or other lists, and so on. The function should return a new list\n containing all integers in their original order, without any nesting.\n\n For example:\n flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]\n flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]\n flatten_nested_list([]) == []\n flatten_nested_list([[[1, 2], 3], [4]]) == [1, 2, 3, 4]\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n flat_list = []\n for item in nested_list:\n if isinstance(item, list):\n flat_list.extend(flatten_nested_list(item))\n else:\n flat_list.append(item)\n return flat_list", "tests": ["assert flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]", "assert flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([[[1, 2], 3], [4]]) == [1, 2, 3, 4]", "assert flatten_nested_list([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([[], [1, []], [[2]]]) == [1, 2]"]} {"name": "flatten_nested_list_903", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a nested list of integers into a single, non-nested list.\n \n The input `nested_list` can contain integers or other lists (which in turn\n can contain integers or other lists, and so on).\n\n Example:\n flatten_nested_list([1, [2, 3], [[4], 5]]) == [1, 2, 3, 4, 5]\n flatten_nested_list([]) == []\n flatten_nested_list([1, 2, 3]) == [1, 2, 3]\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n result = []\n for item in nested_list:\n if isinstance(item, list):\n result.extend(flatten_nested_list(item))\n else:\n result.append(item)\n return result", "tests": ["assert flatten_nested_list([1, [2, 3], [[4], 5]]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([1, 2, 3]) == [1, 2, 3]", "assert flatten_nested_list([[[1]], [[2], [3, 4]], 5]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([7, [8, [9, [10]]]]) == [7, 8, 9, 10]", "assert flatten_nested_list([[], [[]], [[[]]]]) == []"]} {"name": "flatten_nested_list_650", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a nested list of integers into a single, non-nested list of integers.\n The order of elements should be preserved.\n\n For example:\n flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]\n flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]\n flatten_nested_list([]) == []\n flatten_nested_list([1, 2, 3]) == [1, 2, 3]\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n flat_list = []\n for item in nested_list:\n if isinstance(item, list):\n flat_list.extend(flatten_nested_list(item))\n else:\n flat_list.append(item)\n return flat_list", "tests": ["assert flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]", "assert flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([1, 2, 3]) == [1, 2, 3]", "assert flatten_nested_list([[[1, 2], [3]], 4, [5, [6]]]) == [1, 2, 3, 4, 5, 6]", "assert flatten_nested_list([[[[]]], [1, []], [[2]]]) == [1, 2]"]} {"name": "flatten_nested_list_209", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a nested list of integers into a single, one-dimensional list.\n\n The input `nested_list` can contain integers or other lists. These inner lists\n can in turn contain integers or further nested lists, and so on.\n\n Example:\n flatten_nested_list([1, [2, 3], [[4], 5]]) == [1, 2, 3, 4, 5]\n flatten_nested_list([]) == []\n flatten_nested_list([1, 2, 3]) == [1, 2, 3]\n flatten_nested_list([[1], [[2, 3]], [[4, [5]]]]) == [1, 2, 3, 4, 5]\n\n Args:\n nested_list: A list potentially containing integers and other lists.\n\n Returns:\n A new list containing all integers from the nested_list, in the order\n they appear when flattened from left to right.\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n flattened = []\n for item in nested_list:\n if isinstance(item, list):\n flattened.extend(flatten_nested_list(item))\n else:\n flattened.append(item)\n return flattened", "tests": ["assert flatten_nested_list([1, [2, 3], [[4], 5]]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([1, 2, 3]) == [1, 2, 3]", "assert flatten_nested_list([[1], [[2, 3]], [[4, [5]]]]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([[[[1]]]]) == [1]", "assert flatten_nested_list([[], [1, []], [[2, [3, []]]]]) == [1, 2, 3]"]} {"name": "flatten_nested_list_378", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"Flattens a deeply nested list of integers into a single, one-dimensional list.\n\n The input list can contain integers or other lists, which in turn can contain\n integers or other lists, and so on. Empty lists or lists containing only empty\n lists should result in an empty flattened list.\n\n Args:\n nested_list: A list potentially containing integers and other lists.\n\n Returns:\n A new list containing all integers from the nested_list in the order they\n appear, but without any nested structure.\n\n Examples:\n flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]\n flatten_nested_list([1, [2, [3, 4], 5], 6]) == [1, 2, 3, 4, 5, 6]\n flatten_nested_list([]) == []\n flatten_nested_list([[], [[]]]) == []\n flatten_nested_list([1, [], [2, [3]], 4]) == [1, 2, 3, 4]\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n flattened = []\n for item in nested_list:\n if isinstance(item, list):\n flattened.extend(flatten_nested_list(item))\n else:\n flattened.append(item)\n return flattened", "tests": ["assert flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]", "assert flatten_nested_list([1, [2, [3, 4], 5], 6]) == [1, 2, 3, 4, 5, 6]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([[], [[]], 7, [[8, []]], 9]) == [7, 8, 9]", "assert flatten_nested_list([[[[1]]], 2, [3, [4, [5]]]]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([10]) == [10]"]} {"name": "flatten_nested_list_555", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a nested list of integers into a single, non-nested list of integers.\n The order of elements should be preserved.\n\n For example:\n flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]\n flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]\n flatten_nested_list([]) == []\n flatten_nested_list([1, 2, 3]) == [1, 2, 3]\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n flattened = []\n for item in nested_list:\n if isinstance(item, list):\n flattened.extend(flatten_nested_list(item))\n else:\n flattened.append(item)\n return flattened", "tests": ["assert flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]", "assert flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([1, 2, 3]) == [1, 2, 3]", "assert flatten_nested_list([[], [1, [2]], [[3]]]) == [1, 2, 3]", "assert flatten_nested_list([[[[1]]]]) == [1]"]} {"name": "flatten_nested_list_742", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a nested list of integers into a single, flat list of integers.\n\n The input `nested_list` can contain integers or other lists. Each inner list\n can also contain integers or further nested lists, and so on.\n\n For example:\n flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]\n flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]\n flatten_nested_list([]) == []\n flatten_nested_list([1, [], [2, [3]]]) == [1, 2, 3]\n\n Args:\n nested_list: A list that may contain integers or other lists (nested arbitrarily deep).\n\n Returns:\n A new list containing all integers from the nested_list in the order they appear,\n but without any nesting.\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a nested list of integers into a single, flat list of integers.\n\n The input `nested_list` can contain integers or other lists. Each inner list\n can also contain integers or further nested lists, and so on.\n\n For example:\n flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]\n flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]\n flatten_nested_list([]) == []\n flatten_nested_list([1, [], [2, [3]]]) == [1, 2, 3]\n\n Args:\n nested_list: A list that may contain integers or other lists (nested arbitrarily deep).\n\n Returns:\n A new list containing all integers from the nested_list in the order they appear,\n but without any nesting.\n \"\"\"\n flat_list = []\n for item in nested_list:\n if isinstance(item, list):\n flat_list.extend(flatten_nested_list(item))\n else:\n flat_list.append(item)\n return flat_list", "tests": ["assert flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]", "assert flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([1, [], [2, [3]]]) == [1, 2, 3]", "assert flatten_nested_list([[[1]], 2, [3, [4, 5], 6], 7]) == [1, 2, 3, 4, 5, 6, 7]", "assert flatten_nested_list([[[[[[]]]]]]) == []"]} {"name": "flatten_nested_list_895", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"Flatten a potentially deeply nested list of integers into a single flat list of integers.\n\n The input `nested_list` can contain integers or other lists. These inner lists can also\n contain integers or further nested lists, and so on.\n\n Args:\n nested_list: A list potentially containing integers and other lists.\n\n Returns:\n A new list containing all integers from the input list, flattened into a single dimension.\n\n Examples:\n >>> flatten_nested_list([1, [2, 3], 4])\n [1, 2, 3, 4]\n >>> flatten_nested_list([1, [2, [3, 4]], 5])\n [1, 2, 3, 4, 5]\n >>> flatten_nested_list([])\n []\n >>> flatten_nested_list([[[[1]]]])\n [1]\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n flat_list = []\n for item in nested_list:\n if isinstance(item, list):\n flat_list.extend(flatten_nested_list(item))\n else:\n flat_list.append(item)\n return flat_list", "tests": ["assert flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]", "assert flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([[[[1]]]]) == [1]", "assert flatten_nested_list([1, 2, 3]) == [1, 2, 3]", "assert flatten_nested_list([1, [], [2, [3, []]], 4]) == [1, 2, 3, 4]"]} {"name": "flatten_nested_list_665", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a nested list of integers into a single, non-nested list of integers.\n The order of elements should be preserved.\n\n For example:\n flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]\n flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]\n flatten_nested_list([]) == []\n flatten_nested_list([[]]) == []\n flatten_nested_list([1, [], [2, 3]]) == [1, 2, 3]\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a nested list of integers into a single, non-nested list of integers.\n The order of elements should be preserved.\n\n For example:\n flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]\n flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]\n flatten_nested_list([]) == []\n flatten_nested_list([[]]) == []\n flatten_nested_list([1, [], [2, 3]]) == [1, 2, 3]\n \"\"\"\n flat_list = []\n for element in nested_list:\n if isinstance(element, list):\n flat_list.extend(flatten_nested_list(element))\n else:\n flat_list.append(element)\n return flat_list", "tests": ["assert flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]", "assert flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([[], [[]], 6]) == [6]", "assert flatten_nested_list([[[[1]]], 2, [3, []]]) == [1, 2, 3]", "assert flatten_nested_list([1, 2, 3, 4]) == [1, 2, 3, 4]"]} {"name": "flatten_nested_list_224", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a nested list of integers into a single, non-nested list of integers.\n \n The input `nested_list` can contain integers or other lists. These inner lists\n can in turn contain integers or further nested lists, and so on.\n \n For example:\n flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]\n flatten_nested_list([1, [2, [3, 4], 5], 6]) == [1, 2, 3, 4, 5, 6]\n flatten_list([]) == []\n flatten_list([1, 2, 3]) == [1, 2, 3]\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n flattened = []\n for item in nested_list:\n if isinstance(item, list):\n flattened.extend(flatten_nested_list(item))\n else:\n flattened.append(item)\n return flattened", "tests": ["assert flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]", "assert flatten_nested_list([1, [2, [3, 4], 5], 6]) == [1, 2, 3, 4, 5, 6]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([1, 2, 3]) == [1, 2, 3]", "assert flatten_nested_list([[[1]], [2, [3]], 4]) == [1, 2, 3, 4]", "assert flatten_nested_list([[], [[]], [1, []]]) == [1]"]} {"name": "flatten_nested_list_459", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a nested list of integers into a single, flat list of integers.\n\n The input `nested_list` can contain integers or other lists. These inner lists\n can in turn contain integers or further nested lists, and so on.\n Empty lists should be ignored.\n\n For example:\n flatten_nested_list([1, [2, 3], [[4], 5]]) == [1, 2, 3, 4, 5]\n flatten_nested_list([1, [], [2, [3, []]], 4]) == [1, 2, 3, 4]\n flatten_nested_list([]) == []\n flatten_nested_list([[[[1]]]]) == [1]\n\n Args:\n nested_list (list): A list potentially containing integers and other lists.\n\n Returns:\n list: A new list containing all integers from the nested_list in order.\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a nested list of integers into a single, flat list of integers.\n\n The input `nested_list` can contain integers or other lists. These inner lists\n can in turn contain integers or further nested lists, and so on.\n Empty lists should be ignored.\n\n For example:\n flatten_nested_list([1, [2, 3], [[4], 5]]) == [1, 2, 3, 4, 5]\n flatten_nested_list([1, [], [2, [3, []]], 4]) == [1, 2, 3, 4]\n flatten_nested_list([]) == []\n flatten_nested_list([[[[1]]]]) == [1]\n\n Args:\n nested_list (list): A list potentially containing integers and other lists.\n\n Returns:\n list: A new list containing all integers from the nested_list in order.\n \"\"\"\n flat_list = []\n for item in nested_list:\n if isinstance(item, list):\n flat_list.extend(flatten_nested_list(item))\n else:\n flat_list.append(item)\n return flat_list", "tests": ["assert flatten_nested_list([1, [2, 3], [[4], 5]]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([1, [], [2, [3, []]], 4]) == [1, 2, 3, 4]", "assert flatten_nested_list([[[[1]]]]) == [1]", "assert flatten_nested_list([1, 2, 3]) == [1, 2, 3]", "assert flatten_nested_list([[], [[]], [[], [1, [2]]]]) == [1, 2]"]} {"name": "flatten_nested_list_642", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a nested list of integers into a single, non-nested list of integers.\n The input list can contain integers directly or other lists which may contain integers or further nested lists.\n\n For example:\n flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]\n flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]\n flatten_nested_list([]) == []\n flatten_nested_list([1, [], [2, []]]) == [1, 2]\n\n Args:\n nested_list: A list that can contain integers or other lists.\n\n Returns:\n A new list containing all integers from the nested_list in the order they appear,\n without any nesting.\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n flattened = []\n for item in nested_list:\n if isinstance(item, list):\n flattened.extend(flatten_nested_list(item))\n else:\n flattened.append(item)\n return flattened", "tests": ["assert flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]", "assert flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([1, [], [2, []], [[3]]]) == [1, 2, 3]", "assert flatten_nested_list([[1], [2, [3, [4, 5]]], 6]) == [1, 2, 3, 4, 5, 6]", "assert flatten_nested_list([7]) == [7]"]} {"name": "flatten_nested_list_157", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a nested list of integers into a single, flat list of integers.\n The input list can contain integers or other lists, which in turn can contain integers or other lists, and so on.\n An empty list should return an empty list.\n\n For example:\n flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]\n flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]\n flatten_nested_list([]) == []\n flatten_nested_list([[[1, 2]], [3, [4]]]) == [1, 2, 3, 4]\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n flattened = []\n for item in nested_list:\n if isinstance(item, list):\n flattened.extend(flatten_nested_list(item))\n else:\n flattened.append(item)\n return flattened", "tests": ["assert flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]", "assert flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([[[1, 2]], [3, [4]]]) == [1, 2, 3, 4]", "assert flatten_nested_list([1, [], [2, [3, []], 4], 5]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([[[[]]]]) == []"]} {"name": "flatten_nested_list_948", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"Flatten a nested list of integers into a single flat list.\n\n The input `nested_list` can contain integers or other lists.\n Sub-lists can be nested to any depth.\n An empty list or a list containing only empty lists should return an empty list.\n\n Args:\n nested_list: A list potentially containing integers and other lists.\n\n Returns:\n A new list containing all integers from the nested_list in the order they appear.\n\n Examples:\n >>> flatten_nested_list([1, [2, 3], 4])\n [1, 2, 3, 4]\n >>> flatten_nested_list([1, [2, [3, 4]], 5])\n [1, 2, 3, 4, 5]\n >>> flatten_nested_list([])\n []\n >>> flatten_nested_list([[], [[]]])\n []\n >>> flatten_nested_list([1, [], [2, [3, []]], 4])\n [1, 2, 3, 4]\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n flat_list = []\n for item in nested_list:\n if isinstance(item, list):\n flat_list.extend(flatten_nested_list(item))\n else:\n flat_list.append(item)\n return flat_list", "tests": ["assert flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]", "assert flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([[], [[]]]) == []", "assert flatten_nested_list([1, [], [2, [3, []]], 4]) == [1, 2, 3, 4]", "assert flatten_nested_list([[[1]], 2, [3, [4, [5]]]]) == [1, 2, 3, 4, 5]"]} {"name": "flatten_nested_list_963", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a nested list of integers into a single, non-nested list of integers.\n The order of elements in the flattened list should be the same as they appear\n when traversing the nested list from left to right.\n\n An empty list or a list containing only empty lists should result in an empty list.\n\n Args:\n nested_list: A list that can contain integers or other lists.\n These inner lists can also contain integers or other lists, and so on.\n\n Returns:\n A new list containing all integers from the nested_list in a flattened order.\n\n Examples:\n flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]\n flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]\n flatten_nested_list([]) == []\n flatten_nested_list([[], [1]]) == [1]\n flatten_nested_list([[[[1, 2]]], 3]) == [1, 2, 3]\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n flattened = []\n for item in nested_list:\n if isinstance(item, list):\n flattened.extend(flatten_nested_list(item))\n else:\n flattened.append(item)\n return flattened", "tests": ["assert flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]", "assert flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([[], [1]]) == [1]", "assert flatten_nested_list([[[[1, 2]]], 3]) == [1, 2, 3]", "assert flatten_nested_list([[], [[], []], [7]]) == [7]", "assert flatten_nested_list([0, [1, [2, [3, [4, 5]]], 6], 7]) == [0, 1, 2, 3, 4, 5, 6, 7]"]} {"name": "flatten_nested_list_890", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a nested list of integers into a single, non-nested list of integers.\n The order of elements should be preserved.\n\n For example:\n flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]\n flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]\n flatten_nested_list([]) == []\n flatten_nested_list([1, 2, 3]) == [1, 2, 3]\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n result = []\n for item in nested_list:\n if isinstance(item, list):\n result.extend(flatten_nested_list(item))\n else:\n result.append(item)\n return result", "tests": ["assert flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]", "assert flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([1, 2, 3]) == [1, 2, 3]", "assert flatten_nested_list([[[1, 2], 3], [4, [5]]]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([0, [], [1, [2, []]], 3]) == [0, 1, 2, 3]"]} {"name": "flatten_nested_list_513", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a nested list of integers into a single, non-nested list of integers.\n \n The input `nested_list` can contain integers or other lists (which in turn can contain\n integers or other lists, and so on). Empty lists should be ignored.\n \n For example:\n flatten_nested_list([1, [2, 3], [[4], 5]]) == [1, 2, 3, 4, 5]\n flatten_nested_list([]) == []\n flatten_nested_list([1, [], [2, []]]) == [1, 2]\n \n Args:\n nested_list: A list that may contain integers or other lists.\n \n Returns:\n A new list containing all integers from the nested_list in the order they appear.\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n flat_list = []\n for item in nested_list:\n if isinstance(item, list):\n flat_list.extend(flatten_nested_list(item))\n else:\n flat_list.append(item)\n return flat_list", "tests": ["assert flatten_nested_list([1, [2, 3], [[4], 5]]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([1, [], [2, []]]) == [1, 2]", "assert flatten_nested_list([[[1]], 2, [3, [4, 5]], 6]) == [1, 2, 3, 4, 5, 6]", "assert flatten_nested_list([[[[[[1]]]]]]) == [1]", "assert flatten_nested_list([[], [], []]) == []"]} {"name": "flatten_nested_list_869", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"Flattens a list that can contain other lists as elements, recursively.\n\n The function should take a nested list and return a single, flat list\n containing all non-list elements in the order they appear when traversed\n from left to right, depth-first.\n\n For example:\n flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]\n flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]\n flatten_nested_list([]) == []\n flatten_nested_list([[]]) == []\n flatten_nested_list([1, [], [2, []]]) == [1, 2]\n\n Args:\n nested_list: A list that may contain integers or other lists.\n\n Returns:\n A flat list containing all non-list elements from the input list.\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n flat_list = []\n for item in nested_list:\n if isinstance(item, list):\n flat_list.extend(flatten_nested_list(item))\n else:\n flat_list.append(item)\n return flat_list", "tests": ["assert flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]", "assert flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([[]]) == []", "assert flatten_nested_list([1, [], [2, []]]) == [1, 2]", "assert flatten_nested_list([[[1, 2], 3], [4, [5, 6]]]) == [1, 2, 3, 4, 5, 6]", "assert flatten_nested_list([1, 2, 3]) == [1, 2, 3]"]} {"name": "flatten_nested_list_696", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a nested list of integers into a single, flat list of integers.\n The input list can contain integers directly or other lists of integers (which can also be nested).\n\n For example:\n flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]\n flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]\n flatten_nested_list([]) == []\n flatten_nested_list([[], [1]]) == [1]\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n flat_list = []\n for item in nested_list:\n if isinstance(item, list):\n flat_list.extend(flatten_nested_list(item))\n else:\n flat_list.append(item)\n return flat_list", "tests": ["assert flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]", "assert flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([[], [1]]) == [1]", "assert flatten_nested_list([[[[1]]], 2, [3, [4, 5], 6], 7]) == [1, 2, 3, 4, 5, 6, 7]", "assert flatten_nested_list([1, 2, 3]) == [1, 2, 3]"]} {"name": "flatten_nested_list_recursive", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a arbitrarily nested list of integers into a single flat list of integers.\n The order of elements in the flattened list should be the same as their appearance in the nested list.\n\n For example:\n flatten_nested_list([1, [2, 3], [[4], 5]]) == [1, 2, 3, 4, 5]\n flatten_nested_list([1, [], [2, [3, []]]]) == [1, 2, 3]\n flatten_nested_list([]) == []\n\n Args:\n nested_list: A list that can contain integers or other lists (which can in turn contain integers or lists).\n\n Returns:\n A new list containing all integers from the nested_list in a flat structure.\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n flattened = []\n for item in nested_list:\n if isinstance(item, list):\n flattened.extend(flatten_nested_list(item))\n else:\n flattened.append(item)\n return flattened", "tests": ["assert flatten_nested_list([1, [2, 3], [[4], 5]]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([1, 2, 3]) == [1, 2, 3]", "assert flatten_nested_list([1, [], [2, [3, []]]]) == [1, 2, 3]", "assert flatten_nested_list([[1, [2]], [[3, 4], 5], 6]) == [1, 2, 3, 4, 5, 6]", "assert flatten_nested_list([[[[[1]]]]]) == [1]"]} {"name": "flatten_nested_list_720", "topic": "recursion", "prompt": "def flatten_nested_list(nested_list):\n \"\"\"\n Recursively flattens a nested list of integers into a single, flat list of integers.\n The input list can contain integers or other lists, which in turn can contain integers or lists, and so on.\n\n For example:\n flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]\n flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]\n flatten_nested_list([]) == []\n flatten_nested_list([1, 2, 3]) == [1, 2, 3]\n flatten_nested_list([[], [1, []], 2]) == [1, 2]\n\n Args:\n nested_list: A list that can contain integers or other lists.\n\n Returns:\n A new list containing all integers from the nested_list in the order they appear,\n but without any nesting.\n \"\"\"", "solution": "def flatten_nested_list(nested_list):\n flattened = []\n for item in nested_list:\n if isinstance(item, list):\n flattened.extend(flatten_nested_list(item))\n else:\n flattened.append(item)\n return flattened", "tests": ["assert flatten_nested_list([1, [2, 3], 4]) == [1, 2, 3, 4]", "assert flatten_nested_list([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]", "assert flatten_nested_list([]) == []", "assert flatten_nested_list([1, 2, 3]) == [1, 2, 3]", "assert flatten_nested_list([[], [1, []], 2]) == [1, 2]", "assert flatten_nested_list([[[[1]]], 2, [3, []]]) == [1, 2, 3]"]} {"name": "sort_and_find_median_kth", "topic": "sorting and searching", "prompt": "def sort_and_find_median_kth(data: list[int], k: int) -> int:\n \"\"\"\n Given a list of integers `data` and an integer `k`,\n first sort the list in ascending order, then return the k-th smallest element.\n If `k` is 1, return the smallest element. If `k` is len(data), return the largest.\n The list `data` is guaranteed to have at least one element.\n `k` is guaranteed to be within the valid range [1, len(data)].\n\n Example:\n sort_and_find_median_kth([3, 1, 4, 1, 5, 9, 2, 6], 3) == 2\n (Sorted list: [1, 1, 2, 3, 4, 5, 6, 9], 3rd element is 2)\n sort_and_find_median_kth([7, 2, 5], 1) == 2\n sort_and_find_median_kth([7, 2, 5], 3) == 7\n \"\"\"", "solution": "def sort_and_find_median_kth(data: list[int], k: int) -> int:\n \"\"\"\n Given a list of integers `data` and an integer `k`,\n first sort the list in ascending order, then return the k-th smallest element.\n If `k` is 1, return the smallest element. If `k` is len(data), return the largest.\n The list `data` is guaranteed to have at least one element.\n `k` is guaranteed to be within the valid range [1, len(data)].\n\n Example:\n sort_and_find_median_kth([3, 1, 4, 1, 5, 9, 2, 6], 3) == 2\n (Sorted list: [1, 1, 2, 3, 4, 5, 6, 9], 3rd element is 2)\n sort_and_find_median_kth([7, 2, 5], 1) == 2\n sort_and_find_median_kth([7, 2, 5], 3) == 7\n \"\"\"\n sorted_data = sorted(data)\n return sorted_data[k - 1]", "tests": ["assert sort_and_find_median_kth([3, 1, 4, 1, 5, 9, 2, 6], 3) == 2", "assert sort_and_find_median_kth([7, 2, 5], 1) == 2", "assert sort_and_find_median_kth([7, 2, 5], 3) == 7", "assert sort_and_find_median_kth([10], 1) == 10", "assert sort_and_find_median_kth([-5, 0, 5, -10], 2) == -5", "assert sort_and_find_median_kth([1, 2, 3, 4, 5], 5) == 5"]} {"name": "sort_and_find_median", "topic": "sorting and searching", "prompt": "def sort_and_find_median(numbers: list[int]) -> float:\n \"\"\"\n Sorts a list of integers in ascending order and returns its median.\n \n The median of a finite list of numbers is the 'middle' number when those numbers\n are listed in order. If the list has an odd number of elements, the median is the\n middle element. If the list has an even number of elements, the median is\n typically defined as the average of the two middle elements.\n \n The input list 'numbers' will not be empty.\n \n Args:\n numbers: A list of integers.\n \n Returns:\n The median of the sorted list as a float.\n \n Examples:\n >>> sort_and_find_median([1, 2, 3])\n 2.0\n >>> sort_and_find_median([3, 1, 2, 4])\n 2.5\n >>> sort_and_find_median([5])\n 5.0\n >>> sort_and_find_median([10, 20, 30, 40, 50])\n 30.0\n >>> sort_and_find_median([1, 100])\n 50.5\n \"\"\"", "solution": "def sort_and_find_median(numbers: list[int]) -> float:\n \"\"\"\n Sorts a list of integers in ascending order and returns its median.\n \n The median of a finite list of numbers is the 'middle' number when those numbers\n are listed in order. If the list has an odd number of elements, the median is the\n middle element. If the list has an even number of elements, the median is\n typically defined as the average of the two middle elements.\n \n The input list 'numbers' will not be empty.\n \n Args:\n numbers: A list of integers.\n \n Returns:\n The median of the sorted list as a float.\n \n Examples:\n >>> sort_and_find_median([1, 2, 3])\n 2.0\n >>> sort_and_find_median([3, 1, 2, 4])\n 2.5\n >>> sort_and_find_median([5])\n 5.0\n >>> sort_and_find_median([10, 20, 30, 40, 50])\n 30.0\n >>> sort_and_find_median([1, 100])\n 50.5\n \"\"\"\n sorted_numbers = sorted(numbers)\n n = len(sorted_numbers)\n \n if n % 2 == 1:\n # Odd number of elements\n return float(sorted_numbers[n // 2])\n else:\n # Even number of elements\n mid1 = sorted_numbers[n // 2 - 1]\n mid2 = sorted_numbers[n // 2]\n return (mid1 + mid2) / 2.0", "tests": ["assert sort_and_find_median([1, 2, 3]) == 2.0", "assert sort_and_find_median([3, 1, 2, 4]) == 2.5", "assert sort_and_find_median([5]) == 5.0", "assert sort_and_find_median([10, 20, 30, 40, 50]) == 30.0", "assert sort_and_find_median([1, 100]) == 50.5", "assert sort_and_find_median([-5, 0, 5, 10]) == 2.5", "assert sort_and_find_median([7, 2, 9, 1, 5, 3, 8]) == 5.0"]} {"name": "find_median_sorted_arrays", "topic": "sorting and searching", "prompt": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n \"\"\"\n Given two sorted arrays nums1 and nums2 of size m and n respectively,\n return the median of the two sorted arrays.\n\n The overall run time complexity should be O(log(m+n)).\n\n You may assume nums1 and nums2 cannot be both empty.\n \"\"\"", "solution": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n m, n = len(nums1), len(nums2)\n if m > n:\n nums1, nums2, m, n = nums2, nums1, n, m\n\n low, high = 0, m\n total_half = (m + n + 1) // 2\n\n while low <= high:\n partition_x = (low + high) // 2\n partition_y = total_half - partition_x\n\n max_left_x = float('-inf') if partition_x == 0 else nums1[partition_x - 1]\n min_right_x = float('inf') if partition_x == m else nums1[partition_x]\n\n max_left_y = float('-inf') if partition_y == 0 else nums2[partition_y - 1]\n min_right_y = float('inf') if partition_y == n else nums2[partition_y]\n\n if max_left_x <= min_right_y and max_left_y <= min_right_x:\n if (m + n) % 2 == 1:\n return float(max(max_left_x, max_left_y))\n else:\n return (max(max_left_x, max_left_y) + min(min_right_x, min_right_y)) / 2.0\n elif max_left_x > min_right_y:\n high = partition_x - 1\n else:\n low = partition_x + 1\n return 0.0 # Should not be reached given constraints", "tests": ["assert find_median_sorted_arrays([1, 3], [2]) == 2.0", "assert find_median_sorted_arrays([1, 2], [3, 4]) == 2.5", "assert find_median_sorted_arrays([], [1]) == 1.0", "assert find_median_sorted_arrays([0, 0], [0, 0]) == 0.0", "assert find_median_sorted_arrays([3], [-2, -1]) == -1.0", "assert find_median_sorted_arrays([1, 2, 3, 4, 5, 6], [7, 8, 9, 10]) == 5.5"]} {"name": "find_median_sorted_arrays_643", "topic": "sorting and searching", "prompt": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n \"\"\"\n Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median\n of the two sorted arrays. The overall run time complexity should be O(log(m+n)).\n\n You may assume nums1 and nums2 cannot be both empty.\n\n Example 1:\n nums1 = [1, 3], nums2 = [2]\n The merged array is [1, 2, 3] and its median is 2.0.\n\n Example 2:\n nums1 = [1, 2], nums2 = [3, 4]\n The merged array is [1, 2, 3, 4] and its median is (2 + 3) / 2 = 2.5.\n\n Example 3:\n nums1 = [0, 0], nums2 = [0, 0]\n The merged array is [0, 0, 0, 0] and its median is (0 + 0) / 2 = 0.0.\n \"\"\"", "solution": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n m, n = len(nums1), len(nums2)\n if m > n:\n nums1, nums2, m, n = nums2, nums1, n, m\n\n low, high = 0, m\n total_len = m + n\n half_len = (total_len + 1) // 2\n\n while low <= high:\n partition_x = (low + high) // 2\n partition_y = half_len - partition_x\n\n max_left_x = float('-inf') if partition_x == 0 else nums1[partition_x - 1]\n min_right_x = float('inf') if partition_x == m else nums1[partition_x]\n\n max_left_y = float('-inf') if partition_y == 0 else nums2[partition_y - 1]\n min_right_y = float('inf') if partition_y == n else nums2[partition_y]\n\n if max_left_x <= min_right_y and max_left_y <= min_right_x:\n if total_len % 2 == 1:\n return float(max(max_left_x, max_left_y))\n else:\n return (max(max_left_x, max_left_y) + min(min_right_x, min_right_y)) / 2.0\n elif max_left_x > min_right_y:\n high = partition_x - 1\n else:\n low = partition_x + 1", "tests": ["assert find_median_sorted_arrays([1, 3], [2]) == 2.0", "assert find_median_sorted_arrays([1, 2], [3, 4]) == 2.5", "assert find_median_sorted_arrays([0, 0], [0, 0]) == 0.0", "assert find_median_sorted_arrays([], [1]) == 1.0", "assert find_median_sorted_arrays([2], []) == 2.0", "assert find_median_sorted_arrays([1, 5, 8, 10], [2, 3, 4, 6, 7, 9]) == 5.5", "assert find_median_sorted_arrays([1, 2, 3, 4, 5], [6, 7, 8, 9, 10]) == 5.5"]} {"name": "find_median_sorted_arrays_353", "topic": "sorting and searching", "prompt": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n \"\"\"\n Given two sorted arrays nums1 and nums2 of size m and n respectively,\n return the median of the two sorted arrays.\n\n The overall run time complexity should be O(log(m+n)).\n\n You may assume nums1 and nums2 are both non-empty and do not contain duplicate elements.\n They are sorted in ascending order.\n\n Examples:\n find_median_sorted_arrays([1, 3], [2]) == 2.0\n find_median_sorted_arrays([1, 2], [3, 4]) == 2.5\n find_median_sorted_arrays([0, 0], [0, 0]) == 0.0\n \"\"\"", "solution": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n \"\"\"\n Given two sorted arrays nums1 and nums2 of size m and n respectively,\n return the median of the two sorted arrays.\n\n The overall run time complexity should be O(log(m+n)).\n\n You may assume nums1 and nums2 are both non-empty and do not contain duplicate elements.\n They are sorted in ascending order.\n\n Examples:\n find_median_sorted_arrays([1, 3], [2]) == 2.0\n find_median_sorted_arrays([1, 2], [3, 4]) == 2.5\n find_median_sorted_arrays([0, 0], [0, 0]) == 0.0\n \"\"\"\n m, n = len(nums1), len(nums2)\n if m > n:\n nums1, nums2, m, n = nums2, nums1, n, m # Ensure nums1 is the shorter array\n\n low, high = 0, m\n half_len = (m + n + 1) // 2\n\n while low <= high:\n i = (low + high) // 2 # Partition point for nums1\n j = half_len - i # Partition point for nums2\n\n if i < m and nums2[j-1] > nums1[i]:\n # i is too small, need to increase i\n low = i + 1\n elif i > 0 and nums1[i-1] > nums2[j]:\n # i is too big, need to decrease i\n high = i - 1\n else:\n # i is perfect\n max_left = 0\n if i == 0:\n max_left = nums2[j-1]\n elif j == 0:\n max_left = nums1[i-1]\n else:\n max_left = max(nums1[i-1], nums2[j-1])\n\n if (m + n) % 2 == 1:\n return float(max_left)\n\n min_right = 0\n if i == m:\n min_right = nums2[j]\n elif j == n:\n min_right = nums1[i]\n else:\n min_right = min(nums1[i], nums2[j])\n\n return (max_left + min_right) / 2.0", "tests": ["assert find_median_sorted_arrays([1, 3], [2]) == 2.0", "assert find_median_sorted_arrays([1, 2], [3, 4]) == 2.5", "assert find_median_sorted_arrays([0, 0], [0, 0]) == 0.0", "assert find_median_sorted_arrays([10], [1, 2, 3, 4, 5, 6, 7, 8, 9]) == 5.5", "assert find_median_sorted_arrays([2, 3, 4, 5, 6, 7], [1]) == 4.0", "assert find_median_sorted_arrays([1, 5, 7, 9], [2, 4, 6, 8]) == 5.5"]} {"name": "find_median_sorted_arrays_324", "topic": "sorting and searching", "prompt": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n \"\"\"\n Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median\n of the two sorted arrays. The overall run time complexity should be O(log(m+n)).\n\n You may assume nums1 and nums2 cannot be both empty.\n\n Example 1:\n nums1 = [1, 3], nums2 = [2]\n The merged array is [1, 2, 3] and its median is 2.0.\n\n Example 2:\n nums1 = [1, 2], nums2 = [3, 4]\n The merged array is [1, 2, 3, 4] and its median is (2 + 3) / 2 = 2.5.\n \"\"\"", "solution": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n m, n = len(nums1), len(nums2)\n if m > n:\n nums1, nums2, m, n = nums2, nums1, n, m # Ensure nums1 is the shorter array\n\n low, high = 0, m\n half_len = (m + n + 1) // 2\n\n while low <= high:\n i = (low + high) // 2 # Partition point for nums1\n j = half_len - i # Partition point for nums2\n\n if i < m and nums2[j-1] > nums1[i]:\n # i is too small, must increase i\n low = i + 1\n elif i > 0 and nums1[i-1] > nums2[j]:\n # i is too big, must decrease i\n high = i - 1\n else:\n # i is perfect\n max_of_left = 0\n if i == 0:\n max_of_left = nums2[j-1]\n elif j == 0:\n max_of_left = nums1[i-1]\n else:\n max_of_left = max(nums1[i-1], nums2[j-1])\n\n if (m + n) % 2 == 1:\n return float(max_of_left)\n\n min_of_right = 0\n if i == m:\n min_of_right = nums2[j]\n elif j == n:\n min_of_right = nums1[i]\n else:\n min_of_right = min(nums1[i], nums2[j])\n\n return (float(max_of_left) + float(min_of_right)) / 2.0\n", "tests": ["assert find_median_sorted_arrays([1, 3], [2]) == 2.0", "assert find_median_sorted_arrays([1, 2], [3, 4]) == 2.5", "assert find_median_sorted_arrays([0, 0], [0, 0]) == 0.0", "assert find_median_sorted_arrays([], [1]) == 1.0", "assert find_median_sorted_arrays([2], []) == 2.0", "assert find_median_sorted_arrays([1, 2, 3, 4, 5], [6, 7, 8, 9, 10]) == 5.5", "assert find_median_sorted_arrays([1, 1, 3, 3], [1, 1, 3, 3]) == 2.0"]} {"name": "find_median_sorted_arrays_686", "topic": "sorting and searching", "prompt": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n \"\"\"\n Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median\n of the two sorted arrays. The overall run time complexity should be O(log(m+n)).\n\n You may assume nums1 and nums2 cannot be both empty.\n\n Examples:\n find_median_sorted_arrays([1,3], [2]) == 2.0\n find_median_sorted_arrays([1,2], [3,4]) == 2.5\n find_median_sorted_arrays([0,0], [0,0]) == 0.0\n find_median_sorted_arrays([], [1]) == 1.0\n find_median_sorted_arrays([2], []) == 2.0\n \"\"\"", "solution": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n m, n = len(nums1), len(nums2)\n if m > n:\n nums1, nums2, m, n = nums2, nums1, n, m\n\n imin, imax, half_len = 0, m, (m + n + 1) // 2\n\n while imin <= imax:\n i = (imin + imax) // 2\n j = half_len - i\n\n if i < m and nums2[j-1] > nums1[i]:\n # i is too small, must increase it\n imin = i + 1\n elif i > 0 and nums1[i-1] > nums2[j]:\n # i is too big, must decrease it\n imax = i - 1\n else:\n # i is perfect\n if i == 0:\n max_of_left = nums2[j-1]\n elif j == 0:\n max_of_left = nums1[i-1]\n else:\n max_of_left = max(nums1[i-1], nums2[j-1])\n\n if (m + n) % 2 == 1:\n return float(max_of_left)\n\n if i == m:\n min_of_right = nums2[j]\n elif j == n:\n min_of_right = nums1[i]\n else:\n min_of_right = min(nums1[i], nums2[j])\n\n return (max_of_left + min_of_right) / 2.0", "tests": ["assert find_median_sorted_arrays([1,3], [2]) == 2.0", "assert find_median_sorted_arrays([1,2], [3,4]) == 2.5", "assert find_median_sorted_arrays([0,0], [0,0]) == 0.0", "assert find_median_sorted_arrays([], [1]) == 1.0", "assert find_median_sorted_arrays([2], []) == 2.0", "assert find_median_sorted_arrays([1,2,3,4,5], [1,2,3,4,5,6,7,8]) == 4.0", "assert find_median_sorted_arrays([100], [200]) == 150.0"]} {"name": "find_median_sorted_arrays_583", "topic": "sorting and searching", "prompt": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n \"\"\"\n Given two sorted arrays nums1 and nums2 of size m and n respectively,\n return the median of the two sorted arrays.\n\n The overall run time complexity should be O(log(m+n)).\n\n You may assume nums1 and nums2 cannot be both empty.\n \"\"\"", "solution": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n m, n = len(nums1), len(nums2)\n if m > n:\n nums1, nums2, m, n = nums2, nums1, n, m\n\n low, high = 0, m\n total_half = (m + n + 1) // 2\n\n while low <= high:\n partitionX = (low + high) // 2\n partitionY = total_half - partitionX\n\n max_left_X = float('-inf') if partitionX == 0 else nums1[partitionX - 1]\n min_right_X = float('inf') if partitionX == m else nums1[partitionX]\n\n max_left_Y = float('-inf') if partitionY == 0 else nums2[partitionY - 1]\n min_right_Y = float('inf') if partitionY == n else nums2[partitionY]\n\n if max_left_X <= min_right_Y and max_left_Y <= min_right_X:\n if (m + n) % 2 == 0:\n return (max(max_left_X, max_left_Y) + min(min_right_X, min_right_Y)) / 2.0\n else:\n return float(max(max_left_X, max_left_Y))\n elif max_left_X > min_right_Y:\n high = partitionX - 1\n else:\n low = partitionX + 1", "tests": ["assert find_median_sorted_arrays([1, 3], [2]) == 2.0", "assert find_median_sorted_arrays([1, 2], [3, 4]) == 2.5", "assert find_median_sorted_arrays([0, 0], [0, 0]) == 0.0", "assert find_median_sorted_arrays([], [1]) == 1.0", "assert find_median_sorted_arrays([2], []) == 2.0", "assert find_median_sorted_arrays([1, 5, 10, 15], [2, 3, 4, 6, 7, 8]) == 5.5"]} {"name": "find_median_sorted_arrays_512", "topic": "sorting and searching", "prompt": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n \"\"\"\n Given two sorted arrays nums1 and nums2 of size m and n respectively,\n return the median of the two sorted arrays.\n\n The overall run time complexity should be O(log(m+n)).\n\n You may assume nums1 and nums2 cannot be both empty.\n If the total number of elements is odd, the median is the middle element.\n If the total number of elements is even, the median is the average of the two middle elements.\n \"\"\"", "solution": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n m, n = len(nums1), len(nums2)\n if m > n:\n nums1, nums2, m, n = nums2, nums1, n, m\n\n low, high = 0, m\n total_half = (m + n + 1) // 2\n\n while low <= high:\n partition_x = (low + high) // 2\n partition_y = total_half - partition_x\n\n max_left_x = float('-inf') if partition_x == 0 else nums1[partition_x - 1]\n min_right_x = float('inf') if partition_x == m else nums1[partition_x]\n\n max_left_y = float('-inf') if partition_y == 0 else nums2[partition_y - 1]\n min_right_y = float('inf') if partition_y == n else nums2[partition_y]\n\n if max_left_x <= min_right_y and max_left_y <= min_right_x:\n if (m + n) % 2 == 1:\n return float(max(max_left_x, max_left_y))\n else:\n return (max(max_left_x, max_left_y) + min(min_right_x, min_right_y)) / 2.0\n elif max_left_x > min_right_y:\n high = partition_x - 1\n else:\n low = partition_x + 1\n return -1.0 # Should not be reached given constraints", "tests": ["assert find_median_sorted_arrays([1, 3], [2]) == 2.0", "assert find_median_sorted_arrays([1, 2], [3, 4]) == 2.5", "assert find_median_sorted_arrays([0, 0], [0, 0]) == 0.0", "assert find_median_sorted_arrays([], [1]) == 1.0", "assert find_median_sorted_arrays([2], []) == 2.0", "assert find_median_sorted_arrays([1, 5, 8, 10, 18], [2, 3, 6, 7]) == 6.0"]} {"name": "find_median_sorted_arrays_855", "topic": "sorting and searching", "prompt": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n \"\"\"\n Given two sorted arrays nums1 and nums2 of size m and n respectively,\n return the median of the two sorted arrays.\n\n The overall run time complexity should be O(log(m+n)).\n\n You may assume nums1 and nums2 cannot be both empty.\n\n Examples:\n find_median_sorted_arrays([1, 3], [2]) == 2.0\n find_median_sorted_arrays([1, 2], [3, 4]) == 2.5\n find_median_sorted_arrays([0, 0], [0, 0]) == 0.0\n find_median_sorted_arrays([], [1]) == 1.0\n find_median_sorted_arrays([2], []) == 2.0\n \"\"\"", "solution": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n m, n = len(nums1), len(nums2)\n if m > n:\n nums1, nums2, m, n = nums2, nums1, n, m\n\n imin, imax, half_len = 0, m, (m + n + 1) // 2\n\n while imin <= imax:\n i = (imin + imax) // 2\n j = half_len - i\n\n if i < m and nums2[j-1] > nums1[i]:\n # i is too small, must increase it\n imin = i + 1\n elif i > 0 and nums1[i-1] > nums2[j]:\n # i is too big, must decrease it\n imax = i - 1\n else:\n # i is perfect\n max_of_left = 0\n if i == 0:\n max_of_left = nums2[j-1]\n elif j == 0:\n max_of_left = nums1[i-1]\n else:\n max_of_left = max(nums1[i-1], nums2[j-1])\n\n if (m + n) % 2 == 1:\n return float(max_of_left)\n\n min_of_right = 0\n if i == m:\n min_of_right = nums2[j]\n elif j == n:\n min_of_right = nums1[i]\n else:\n min_of_right = min(nums1[i], nums2[j])\n\n return (max_of_left + min_of_right) / 2.0", "tests": ["assert find_median_sorted_arrays([1, 3], [2]) == 2.0", "assert find_median_sorted_arrays([1, 2], [3, 4]) == 2.5", "assert find_median_sorted_arrays([0, 0], [0, 0]) == 0.0", "assert find_median_sorted_arrays([], [1]) == 1.0", "assert find_median_sorted_arrays([2], []) == 2.0", "assert find_median_sorted_arrays([1, 5, 10], [2, 3, 4, 6]) == 4.0", "assert find_median_sorted_arrays([1, 3, 5, 7, 9], [2, 4, 6, 8, 10]) == 5.5"]} {"name": "find_median_sorted_arrays_241", "topic": "sorting and searching", "prompt": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n \"\"\"\n Given two sorted arrays nums1 and nums2 of size m and n respectively,\n return the median of the two sorted arrays.\n\n The overall run time complexity should be O(log(m+n)).\n\n You may assume nums1 and nums2 cannot be both empty.\n\n Examples:\n find_median_sorted_arrays([1,3], [2]) == 2.0\n find_median_sorted_arrays([1,2], [3,4]) == 2.5\n find_median_sorted_arrays([0,0], [0,0]) == 0.0\n find_median_sorted_arrays([], [1]) == 1.0\n find_median_sorted_arrays([2], []) == 2.0\n \"\"\"", "solution": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n m, n = len(nums1), len(nums2)\n if m > n:\n nums1, nums2, m, n = nums2, nums1, n, m\n\n low, high = 0, m\n half_len = (m + n + 1) // 2\n\n while low <= high:\n i = (low + high) // 2\n j = half_len - i\n\n if i < m and nums2[j-1] > nums1[i]:\n # i is too small, must increase it\n low = i + 1\n elif i > 0 and nums1[i-1] > nums2[j]:\n # i is too big, must decrease it\n high = i - 1\n else:\n # i is perfect\n max_of_left = 0\n if i == 0:\n max_of_left = nums2[j-1]\n elif j == 0:\n max_of_left = nums1[i-1]\n else:\n max_of_left = max(nums1[i-1], nums2[j-1])\n\n if (m + n) % 2 == 1:\n return float(max_of_left)\n\n min_of_right = 0\n if i == m:\n min_of_right = nums2[j]\n elif j == n:\n min_of_right = nums1[i]\n else:\n min_of_right = min(nums1[i], nums2[j])\n\n return (max_of_left + min_of_right) / 2.0\n\n return 0.0 # Should not be reached given constraints", "tests": ["assert find_median_sorted_arrays([1,3], [2]) == 2.0", "assert find_median_sorted_arrays([1,2], [3,4]) == 2.5", "assert find_median_sorted_arrays([0,0], [0,0]) == 0.0", "assert find_median_sorted_arrays([], [1]) == 1.0", "assert find_median_sorted_arrays([2], []) == 2.0", "assert find_median_sorted_arrays([1,3,5,7,9], [2,4,6,8,10]) == 5.5", "assert find_median_sorted_arrays([1], [2,3,4,5,6]) == 3.5"]} {"name": "sort_and_find_median_886", "topic": "sorting and searching", "prompt": "def sort_and_find_median(data: list[int]) -> float:\n \"\"\"\n Sorts a list of integers in ascending order and returns the median value.\n\n If the list has an odd number of elements, the median is the middle element.\n If the list has an even number of elements, the median is the average of the two middle elements.\n The input list 'data' should not be modified in place.\n\n Args:\n data: A list of integers.\n\n Returns:\n The median value as a float.\n\n Raises:\n ValueError: If the input list 'data' is empty.\n\n Examples:\n >>> sort_and_find_median([1, 2, 3])\n 2.0\n >>> sort_and_find_median([1, 2, 3, 4])\n 2.5\n >>> sort_and_find_median([5, 1, 4, 2, 8])\n 4.0\n \"\"\"", "solution": "def sort_and_find_median(data: list[int]) -> float:\n if not data:\n raise ValueError(\"Input list cannot be empty.\")\n\n sorted_data = sorted(data)\n n = len(sorted_data)\n\n if n % 2 == 1:\n # Odd number of elements, median is the middle one\n return float(sorted_data[n // 2])\n else:\n # Even number of elements, median is the average of the two middle ones\n mid1 = sorted_data[n // 2 - 1]\n mid2 = sorted_data[n // 2]\n return (float(mid1) + float(mid2)) / 2.0", "tests": ["assert sort_and_find_median([1, 2, 3]) == 2.0", "assert sort_and_find_median([1, 2, 3, 4]) == 2.5", "assert sort_and_find_median([5, 1, 4, 2, 8]) == 4.0", "assert sort_and_find_median([10]) == 10.0", "assert sort_and_find_median([7, 2, 9, 1, 5, 3]) == 4.0", "assert sort_and_find_median([-5, -1, -10, -3]) == -4.0", "import pytest\nwith pytest.raises(ValueError):\n sort_and_find_median([])"]} {"name": "find_median_sorted_arrays_923", "topic": "sorting and searching", "prompt": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n \"\"\"\n Given two sorted arrays nums1 and nums2 of size m and n respectively,\n return the median of the two sorted arrays.\n\n The overall run time complexity should be O(log(m+n)).\n\n You may assume nums1 and nums2 cannot be both empty.\n \"\"\"", "solution": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n m, n = len(nums1), len(nums2)\n if m > n:\n nums1, nums2, m, n = nums2, nums1, n, m\n\n imin, imax, half_len = 0, m, (m + n + 1) // 2\n\n while imin <= imax:\n i = (imin + imax) // 2\n j = half_len - i\n\n if i < m and nums2[j - 1] > nums1[i]:\n # i is too small, must increase it\n imin = i + 1\n elif i > 0 and nums1[i - 1] > nums2[j]:\n # i is too big, must decrease it\n imax = i - 1\n else:\n # i is perfect\n max_of_left = 0\n if i == 0:\n max_of_left = nums2[j - 1]\n elif j == 0:\n max_of_left = nums1[i - 1]\n else:\n max_of_left = max(nums1[i - 1], nums2[j - 1])\n\n if (m + n) % 2 == 1:\n return float(max_of_left)\n\n min_of_right = 0\n if i == m:\n min_of_right = nums2[j]\n elif j == n:\n min_of_right = nums1[i]\n else:\n min_of_right = min(nums1[i], nums2[j])\n\n return (float(max_of_left) + float(min_of_right)) / 2.0\n", "tests": ["assert find_median_sorted_arrays([1, 3], [2]) == 2.0", "assert find_median_sorted_arrays([1, 2], [3, 4]) == 2.5", "assert find_median_sorted_arrays([0, 0], [0, 0]) == 0.0", "assert find_median_sorted_arrays([], [1]) == 1.0", "assert find_median_sorted_arrays([2], []) == 2.0", "assert find_median_sorted_arrays([1, 5, 10, 12], [2, 3, 4, 13, 14, 15]) == 7.5"]} {"name": "find_median_sorted_arrays_493", "topic": "sorting and searching", "prompt": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n \"\"\"\n Given two sorted arrays nums1 and nums2 of size m and n respectively,\n return the median of the two sorted arrays.\n\n The overall run time complexity should be O(log(m+n)).\n\n You may assume nums1 and nums2 cannot be both empty.\n \"\"\"", "solution": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n m, n = len(nums1), len(nums2)\n if m > n:\n nums1, nums2, m, n = nums2, nums1, n, m\n\n low, high = 0, m\n total_len = m + n\n half_len = (total_len + 1) // 2\n\n while low <= high:\n partition1 = (low + high) // 2\n partition2 = half_len - partition1\n\n max_left1 = float('-inf') if partition1 == 0 else nums1[partition1 - 1]\n min_right1 = float('inf') if partition1 == m else nums1[partition1]\n\n max_left2 = float('-inf') if partition2 == 0 else nums2[partition2 - 1]\n min_right2 = float('inf') if partition2 == n else nums2[partition2]\n\n if max_left1 <= min_right2 and max_left2 <= min_right1:\n # Found the correct partitions\n if total_len % 2 == 1:\n return float(max(max_left1, max_left2))\n else:\n return (max(max_left1, max_left2) + min(min_right1, min_right2)) / 2.0\n elif max_left1 > min_right2:\n # partition1 is too far to the right, need to move left\n high = partition1 - 1\n else:\n # max_left2 > min_right1, partition1 is too far to the left, need to move right\n low = partition1 + 1\n return 0.0 # Should not reach here given constraints", "tests": ["assert find_median_sorted_arrays([1, 3], [2]) == 2.0", "assert find_median_sorted_arrays([1, 2], [3, 4]) == 2.5", "assert find_median_sorted_arrays([0, 0], [0, 0]) == 0.0", "assert find_median_sorted_arrays([], [1]) == 1.0", "assert find_median_sorted_arrays([2], []) == 2.0", "assert find_median_sorted_arrays([1, 5, 8, 10], [2, 3, 6, 7]) == 5.5"]} {"name": "find_median_sorted_arrays_113", "topic": "sorting and searching", "prompt": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n \"\"\"\n Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median\n of the two sorted arrays. The overall run time complexity should be O(log(m+n)).\n\n You may assume nums1 and nums2 cannot be both empty.\n\n Example 1:\n nums1 = [1,3], nums2 = [2]\n The merged array is [1,2,3] and its median is 2.0.\n\n Example 2:\n nums1 = [1,2], nums2 = [3,4]\n The merged array is [1,2,3,4] and its median is (2 + 3) / 2 = 2.5.\n \"\"\"", "solution": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n m, n = len(nums1), len(nums2)\n if m > n:\n nums1, nums2, m, n = nums2, nums1, n, m\n\n # Ensure nums1 is the shorter array for binary search efficiency\n\n low, high = 0, m\n median_pos = (m + n + 1) // 2\n\n while low <= high:\n partition_nums1 = (low + high) // 2\n partition_nums2 = median_pos - partition_nums1\n\n max_left_nums1 = float('-inf') if partition_nums1 == 0 else nums1[partition_nums1 - 1]\n min_right_nums1 = float('inf') if partition_nums1 == m else nums1[partition_nums1]\n\n max_left_nums2 = float('-inf') if partition_nums2 == 0 else nums2[partition_nums2 - 1]\n min_right_nums2 = float('inf') if partition_nums2 == n else nums2[partition_nums2]\n\n if max_left_nums1 <= min_right_nums2 and max_left_nums2 <= min_right_nums1:\n # We found the correct partitions\n if (m + n) % 2 == 0:\n return (max(max_left_nums1, max_left_nums2) + min(min_right_nums1, min_right_nums2)) / 2.0\n else:\n return float(max(max_left_nums1, max_left_nums2))\n elif max_left_nums1 > min_right_nums2:\n # We are too far right in nums1, need to move left\n high = partition_nums1 - 1\n else:\n # We are too far left in nums1, need to move right\n low = partition_nums1 + 1\n return 0.0 # Should not be reached given constraints", "tests": ["assert find_median_sorted_arrays([1, 3], [2]) == 2.0", "assert find_median_sorted_arrays([1, 2], [3, 4]) == 2.5", "assert find_median_sorted_arrays([0, 0], [0, 0]) == 0.0", "assert find_median_sorted_arrays([], [1]) == 1.0", "assert find_median_sorted_arrays([2], []) == 2.0", "assert find_median_sorted_arrays([1, 5, 8, 10, 18], [2, 3, 6, 7]) == 6.0", "assert find_median_sorted_arrays([1, 2, 3, 4, 5], [6, 7, 8, 9, 10]) == 5.5"]} {"name": "sort_and_find_median_135", "topic": "sorting and searching", "prompt": "def sort_and_find_median(numbers: list[int]) -> int:\n \"\"\"\n Sorts a list of integers in ascending order and returns the median value.\n If the list has an even number of elements, the median is defined as\n the average of the two middle elements, rounded down to the nearest integer.\n An empty list should raise a ValueError.\n\n Examples:\n sort_and_find_median([3, 1, 4, 1, 5]) == 3 (sorted: [1, 1, 3, 4, 5], middle is 3)\n sort_and_find_median([10, 20, 30, 40]) == 25 (sorted: [10, 20, 30, 40], average of 20 and 30 is 25)\n sort_and_find_median([7]) == 7\n \"\"\"", "solution": "def sort_and_find_median(numbers: list[int]) -> int:\n if not numbers:\n raise ValueError(\"Input list cannot be empty.\")\n\n sorted_numbers = sorted(numbers)\n n = len(sorted_numbers)\n\n if n % 2 == 1:\n # Odd number of elements, return the middle element\n return sorted_numbers[n // 2]\n else:\n # Even number of elements, return the average of the two middle elements, rounded down\n mid1 = sorted_numbers[n // 2 - 1]\n mid2 = sorted_numbers[n // 2]\n return (mid1 + mid2) // 2", "tests": ["assert sort_and_find_median([3, 1, 4, 1, 5]) == 3", "assert sort_and_find_median([10, 20, 30, 40]) == 25", "assert sort_and_find_median([7]) == 7", "assert sort_and_find_median([5, 2, 8, 1, 9, 4]) == 4", "assert sort_and_find_median([-5, -1, -10]) == -5", "assert sort_and_find_median([2, 2, 2, 2]) == 2"]} {"name": "sort_by_frequency_153", "topic": "sorting and searching", "prompt": "def sort_by_frequency(items: list) -> list:\n \"\"\"\n Sorts a list of items based on their frequency in descending order.\n If two items have the same frequency, their original relative order should be preserved.\n\n The function should return a new list with items sorted as described.\n\n Example:\n sort_by_frequency([1, 2, 3, 2, 1, 4]) == [1, 1, 2, 2, 3, 4]\n (Frequency: 1->2, 2->2, 3->1, 4->1. Items 1 and 2 have freq 2, 1 appeared before 2. Items 3 and 4 have freq 1, 3 appeared before 4.)\n\n sort_by_frequency(['a', 'b', 'a', 'c', 'b', 'a']) == ['a', 'a', 'a', 'b', 'b', 'c']\n (Frequency: 'a'->3, 'b'->2, 'c'->1)\n \"\"\"", "solution": "from collections import Counter\n\ndef sort_by_frequency(items: list) -> list:\n \"\"\"\n Sorts a list of items based on their frequency in descending order.\n If two items have the same frequency, their original relative order should be preserved.\n\n The function should return a new list with items sorted as described.\n\n Example:\n sort_by_frequency([1, 2, 3, 2, 1, 4]) == [1, 1, 2, 2, 3, 4]\n (Frequency: 1->2, 2->2, 3->1, 4->1. Items 1 and 2 have freq 2, 1 appeared before 2. Items 3 and 4 have freq 1, 3 appeared before 4.)\n\n sort_by_frequency(['a', 'b', 'a', 'c', 'b', 'a']) == ['a', 'a', 'a', 'b', 'b', 'c']\n (Frequency: 'a'->3, 'b'->2, 'c'->1)\n \"\"\"\n if not items:\n return []\n\n # Use Counter to get frequencies\n counts = Counter(items)\n\n # To preserve original relative order for items with same frequency,\n # we need to remember their first appearance index.\n # Create a list of unique items in their original order of appearance.\n unique_items_ordered = []\n seen = set()\n for item in items:\n if item not in seen:\n unique_items_ordered.append(item)\n seen.add(item)\n\n # Sort the unique items based on frequency (descending) and then original order (ascending index)\n # We need to create a mapping from item to its original index for stable sorting.\n item_to_original_index = {item: i for i, item in enumerate(unique_items_ordered)}\n\n def sort_key(item):\n # Primary sort key: frequency (descending, so negate it)\n # Secondary sort key: original appearance index (ascending)\n return -counts[item], item_to_original_index[item]\n\n sorted_unique_items = sorted(unique_items_ordered, key=sort_key)\n\n # Reconstruct the final list\n result = []\n for item in sorted_unique_items:\n result.extend([item] * counts[item])\n\n return result", "tests": ["assert sort_by_frequency([1, 2, 3, 2, 1, 4]) == [1, 1, 2, 2, 3, 4]", "assert sort_by_frequency(['a', 'b', 'a', 'c', 'b', 'a']) == ['a', 'a', 'a', 'b', 'b', 'c']", "assert sort_by_frequency([]) == []", "assert sort_by_frequency([5, 5, 5, 1, 2, 2, 3]) == [5, 5, 5, 2, 2, 1, 3]", "assert sort_by_frequency([10, 20, 30, 10, 20, 40, 10]) == [10, 10, 10, 20, 20, 30, 40]", "assert sort_by_frequency(['apple', 'banana', 'apple', 'orange', 'banana', 'apple']) == ['apple', 'apple', 'apple', 'banana', 'banana', 'orange']"]} {"name": "find_median_sorted_arrays_607", "topic": "sorting and searching", "prompt": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n \"\"\"\n Given two sorted arrays nums1 and nums2 of size m and n respectively,\n return the median of the two sorted arrays.\n\n The overall run time complexity should be O(log(m+n)).\n\n You may assume nums1 and nums2 cannot be both empty.\n \"\"\"", "solution": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n m, n = len(nums1), len(nums2)\n if m > n:\n nums1, nums2, m, n = nums2, nums1, n, m\n\n low, high = 0, m\n total_half = (m + n + 1) // 2\n\n while low <= high:\n partition_x = (low + high) // 2\n partition_y = total_half - partition_x\n\n max_left_x = float('-inf') if partition_x == 0 else nums1[partition_x - 1]\n min_right_x = float('inf') if partition_x == m else nums1[partition_x]\n\n max_left_y = float('-inf') if partition_y == 0 else nums2[partition_y - 1]\n min_right_y = float('inf') if partition_y == n else nums2[partition_y]\n\n if max_left_x <= min_right_y and max_left_y <= min_right_x:\n # We have found the correct partition\n if (m + n) % 2 == 0:\n return (max(max_left_x, max_left_y) + min(min_right_x, min_right_y)) / 2.0\n else:\n return float(max(max_left_x, max_left_y))\n elif max_left_x > min_right_y:\n # We are too far right in nums1, need to move left\n high = partition_x - 1\n else:\n # We are too far left in nums1, need to move right\n low = partition_x + 1\n return -1.0 # Should not be reached given constraints", "tests": ["assert find_median_sorted_arrays([1, 3], [2]) == 2.0", "assert find_median_sorted_arrays([1, 2], [3, 4]) == 2.5", "assert find_median_sorted_arrays([0, 0], [0, 0]) == 0.0", "assert find_median_sorted_arrays([], [1]) == 1.0", "assert find_median_sorted_arrays([2], []) == 2.0", "assert find_median_sorted_arrays([1, 5, 8, 9, 10], [2, 3, 4, 6, 7]) == 5.5"]} {"name": "find_median_sorted_arrays_747", "topic": "sorting and searching", "prompt": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n \"\"\"\n Given two sorted arrays nums1 and nums2 of size m and n respectively,\n return the median of the two sorted arrays.\n\n The overall run time complexity should be O(log(m+n)).\n\n You may assume nums1 and nums2 cannot be both empty.\n \"\"\"", "solution": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n m, n = len(nums1), len(nums2)\n if m > n:\n nums1, nums2, m, n = nums2, nums1, n, m\n\n low, high = 0, m\n total_half = (m + n + 1) // 2\n\n while low <= high:\n partition1 = (low + high) // 2\n partition2 = total_half - partition1\n\n max_left1 = float('-inf') if partition1 == 0 else nums1[partition1 - 1]\n min_right1 = float('inf') if partition1 == m else nums1[partition1]\n\n max_left2 = float('-inf') if partition2 == 0 else nums2[partition2 - 1]\n min_right2 = float('inf') if partition2 == n else nums2[partition2]\n\n if max_left1 <= min_right2 and max_left2 <= min_right1:\n if (m + n) % 2 == 0:\n return (max(max_left1, max_left2) + min(min_right1, min_right2)) / 2.0\n else:\n return float(max(max_left1, max_left2))\n elif max_left1 > min_right2:\n high = partition1 - 1\n else:\n low = partition1 + 1\n return 0.0 # Should not be reached given constraints", "tests": ["assert find_median_sorted_arrays([1, 3], [2]) == 2.0", "assert find_median_sorted_arrays([1, 2], [3, 4]) == 2.5", "assert find_median_sorted_arrays([0, 0], [0, 0]) == 0.0", "assert find_median_sorted_arrays([], [1]) == 1.0", "assert find_median_sorted_arrays([2], []) == 2.0", "assert find_median_sorted_arrays([3, 4, 5, 6], [1, 2]) == 3.5", "assert find_median_sorted_arrays([1, 2, 3, 4, 5], [6, 7, 8, 9, 10]) == 5.5"]} {"name": "find_median_sorted_arrays_140", "topic": "sorting and searching", "prompt": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n \"\"\"\n Given two sorted arrays nums1 and nums2 of size m and n respectively,\n return the median of the two sorted arrays.\n\n The overall run time complexity should be O(log(m+n)).\n\n You may assume nums1 and nums2 cannot be both empty.\n \"\"\"", "solution": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n m, n = len(nums1), len(nums2)\n if m > n:\n nums1, nums2, m, n = nums2, nums1, n, m\n\n low, high = 0, m\n total_half = (m + n + 1) // 2\n\n while low <= high:\n partition_x = (low + high) // 2\n partition_y = total_half - partition_x\n\n max_left_x = float('-inf') if partition_x == 0 else nums1[partition_x - 1]\n min_right_x = float('inf') if partition_x == m else nums1[partition_x]\n\n max_left_y = float('-inf') if partition_y == 0 else nums2[partition_y - 1]\n min_right_y = float('inf') if partition_y == n else nums2[partition_y]\n\n if max_left_x <= min_right_y and max_left_y <= min_right_x:\n if (m + n) % 2 == 1:\n return float(max(max_left_x, max_left_y))\n else:\n return (max(max_left_x, max_left_y) + min(min_right_x, min_right_y)) / 2.0\n elif max_left_x > min_right_y:\n high = partition_x - 1\n else:\n low = partition_x + 1\n return -1.0 # Should not reach here in a valid input", "tests": ["assert find_median_sorted_arrays([1, 3], [2]) == 2.0", "assert find_median_sorted_arrays([1, 2], [3, 4]) == 2.5", "assert find_median_sorted_arrays([0, 0], [0, 0]) == 0.0", "assert find_median_sorted_arrays([], [1]) == 1.0", "assert find_median_sorted_arrays([2], []) == 2.0", "assert find_median_sorted_arrays([1, 5, 8, 10], [2, 3, 6, 7, 9]) == 6.0"]} {"name": "find_median_sorted_arrays_863", "topic": "sorting and searching", "prompt": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n \"\"\"\n Given two sorted arrays nums1 and nums2 of size m and n respectively,\n return the median of the two sorted arrays.\n\n The overall run time complexity should be O(log(m+n)).\n\n You may assume nums1 and nums2 cannot be both empty.\n \"\"\"", "solution": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n m, n = len(nums1), len(nums2)\n if m > n:\n nums1, nums2, m, n = nums2, nums1, n, m\n\n # The total length of the merged array\n total_len = m + n\n # The target position for the left half's end element in the merged array\n # If total_len is odd, this is the median itself.\n # If total_len is even, this is the rightmost element of the left half.\n half_len = (total_len + 1) // 2\n\n low, high = 0, m\n\n while low <= high:\n # Partition point in nums1\n partition_x = (low + high) // 2\n # Partition point in nums2\n # This ensures that partition_x + partition_y = half_len\n partition_y = half_len - partition_x\n\n # Determine elements around the partition points\n max_left_x = float('-inf') if partition_x == 0 else nums1[partition_x - 1]\n min_right_x = float('inf') if partition_x == m else nums1[partition_x]\n\n max_left_y = float('-inf') if partition_y == 0 else nums2[partition_y - 1]\n min_right_y = float('inf') if partition_y == n else nums2[partition_y]\n\n # Check if partitions are correct\n if max_left_x <= min_right_y and max_left_y <= min_right_x:\n # Found the correct partitions\n if total_len % 2 == 1:\n return float(max(max_left_x, max_left_y))\n else:\n return (max(max_left_x, max_left_y) + min(min_right_x, min_right_y)) / 2.0\n elif max_left_x > min_right_y:\n # partition_x is too far to the right, need to move left in nums1\n high = partition_x - 1\n else: # max_left_y > min_right_x\n # partition_x is too far to the left, need to move right in nums1\n low = partition_x + 1\n \n # This part should ideally not be reached if inputs are valid as per problem statement\n # However, it's good practice to have a fallback or raise an error for unexpected states.\n raise ValueError(\"Could not find median. This should not happen with valid inputs.\")", "tests": ["assert find_median_sorted_arrays([1, 3], [2]) == 2.0", "assert find_median_sorted_arrays([1, 2], [3, 4]) == 2.5", "assert find_median_sorted_arrays([0, 0], [0, 0]) == 0.0", "assert find_median_sorted_arrays([], [1]) == 1.0", "assert find_median_sorted_arrays([2], []) == 2.0", "assert find_median_sorted_arrays([1, 5, 8, 10, 18], [2, 3, 6, 7]) == 6.0"]} {"name": "sort_by_frequency_and_value", "topic": "sorting and searching", "prompt": "def sort_by_frequency_and_value(numbers: list[int]) -> list[int]:\n \"\"\"\n Sorts a list of integers based on two criteria:\n 1. Primary: Frequency of occurrence in descending order. Numbers that appear more often come first.\n 2. Secondary: Value in ascending order. If two numbers have the same frequency, the smaller value comes first.\n\n The original order of elements with the same frequency and value does not need to be preserved.\n\n Args:\n numbers: A list of integers.\n\n Returns:\n A new list of integers sorted by frequency (descending) then by value (ascending).\n Returns an empty list if the input list is empty.\n \"\"\"", "solution": "from collections import Counter\n\ndef sort_by_frequency_and_value(numbers: list[int]) -> list[int]:\n \"\"\"\n Sorts a list of integers based on two criteria:\n 1. Primary: Frequency of occurrence in descending order. Numbers that appear more often come first.\n 2. Secondary: Value in ascending order. If two numbers have the same frequency, the smaller value comes first.\n\n The original order of elements with the same frequency and value does not need to be preserved.\n\n Args:\n numbers: A list of integers.\n\n Returns:\n A new list of integers sorted by frequency (descending) then by value (ascending).\n Returns an empty list if the input list is empty.\n \"\"\"\n if not numbers:\n return []\n\n counts = Counter(numbers)\n\n # The key for sorting: (-frequency, value)\n # We negate frequency to achieve descending order for frequency.\n # Value is kept positive for ascending order.\n sorted_unique_numbers = sorted(counts.keys(), key=lambda x: (-counts[x], x))\n\n result = []\n for num in sorted_unique_numbers:\n result.extend([num] * counts[num])\n\n return result", "tests": ["assert sort_by_frequency_and_value([1, 1, 2, 2, 2, 3]) == [2, 2, 2, 1, 1, 3]", "assert sort_by_frequency_and_value([2, 3, 1, 3, 2, 1, 4, 1]) == [1, 1, 1, 2, 2, 3, 3, 4]", "assert sort_by_frequency_and_value([5, 5, 5, 2, 2, 1]) == [5, 5, 5, 2, 2, 1]", "assert sort_by_frequency_and_value([1, 1, 1, 2, 2, 3, 3, 3]) == [1, 1, 1, 3, 3, 3, 2, 2]", "assert sort_by_frequency_and_value([]) == []", "assert sort_by_frequency_and_value([1]) == [1]", "assert sort_by_frequency_and_value([10, 20, 30, 10, 20, 10]) == [10, 10, 10, 20, 20, 30]"]} {"name": "find_median_sorted_arrays_466", "topic": "sorting and searching", "prompt": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n \"\"\"\n Given two sorted arrays nums1 and nums2 of size m and n respectively,\n return the median of the two sorted arrays.\n\n The overall run time complexity should be O(log(m+n)).\n\n You may assume nums1 and nums2 are both non-empty and do not contain duplicate elements.\n They are sorted in ascending order.\n\n Example 1:\n nums1 = [1,3], nums2 = [2]\n The merged array is [1,2,3] and its median is 2.0.\n\n Example 2:\n nums1 = [1,2], nums2 = [3,4]\n The merged array is [1,2,3,4] and its median is (2 + 3) / 2 = 2.5.\n\n Example 3:\n nums1 = [0,0], nums2 = [0,0]\n The merged array is [0,0,0,0] and its median is (0 + 0) / 2 = 0.0.\n \"\"\"", "solution": "def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:\n m, n = len(nums1), len(nums2)\n\n # Ensure nums1 is the shorter array for simplicity in binary search\n if m > n:\n nums1, nums2 = nums2, nums1\n m, n = n, m\n\n low, high = 0, m\n half_len = (m + n + 1) // 2\n\n while low <= high:\n partition_x = (low + high) // 2\n partition_y = half_len - partition_x\n\n max_left_x = float('-inf') if partition_x == 0 else nums1[partition_x - 1]\n min_right_x = float('inf') if partition_x == m else nums1[partition_x]\n\n max_left_y = float('-inf') if partition_y == 0 else nums2[partition_y - 1]\n min_right_y = float('inf') if partition_y == n else nums2[partition_y]\n\n if max_left_x <= min_right_y and max_left_y <= min_right_x:\n # Partition found\n if (m + n) % 2 == 1:\n return float(max(max_left_x, max_left_y))\n else:\n return (max(max_left_x, max_left_y) + min(min_right_x, min_right_y)) / 2.0\n elif max_left_x > min_right_y:\n # Need to move partition_x to the left\n high = partition_x - 1\n else:\n # max_left_y > min_right_x, need to move partition_x to the right\n low = partition_x + 1\n return -1.0 # Should not be reached if inputs are valid and non-empty", "tests": ["assert find_median_sorted_arrays([1, 3], [2]) == 2.0", "assert find_median_sorted_arrays([1, 2], [3, 4]) == 2.5", "assert find_median_sorted_arrays([0, 0], [0, 0]) == 0.0", "assert find_median_sorted_arrays([1], [2, 3, 4, 5]) == 3.0", "assert find_median_sorted_arrays([10, 20, 30, 40], [1, 2, 3, 4, 5]) == 5.0", "assert find_median_sorted_arrays([1, 2, 3, 4, 5], [10, 20, 30, 40]) == 5.0"]} {"name": "parse_key_value_string", "topic": "parsing simple formats", "prompt": "def parse_key_value_string(data_string: str) -> dict:\n \"\"\"\n Parses a string containing key-value pairs separated by semicolons, \n where each key and value are separated by an equals sign.\n\n Keys and values can contain spaces. Keys are case-sensitive.\n Empty keys or values are allowed but will be represented as empty strings.\n If a key appears multiple times, the last one encountered should overwrite previous ones.\n Whitespace around keys and values (before/after the equals sign or semicolon)\n should be stripped.\n\n Example:\n parse_key_value_string(\"key1 = value one; key2=value two; key1 = new value\")\n should return {'key1': 'new value', 'key2': 'value two'}\n\n parse_key_value_string(\" key A= val B ; k= ; =val \")\n should return {'key A': 'val B', 'k': '', '': 'val'}\n\n :param data_string: The string to parse.\n :return: A dictionary of parsed key-value pairs.\n \"\"\"", "solution": "def parse_key_value_string(data_string: str) -> dict:\n \"\"\"\n Parses a string containing key-value pairs separated by semicolons, \n where each key and value are separated by an equals sign.\n\n Keys and values can contain spaces. Keys are case-sensitive.\n Empty keys or values are allowed but will be represented as empty strings.\n If a key appears multiple times, the last one encountered should overwrite previous ones.\n Whitespace around keys and values (before/after the equals sign or semicolon)\n should be stripped.\n\n Example:\n parse_key_value_string(\"key1 = value one; key2=value two; key1 = new value\")\n should return {'key1': 'new value', 'key2': 'value two'}\n\n parse_key_value_string(\" key A= val B ; k= ; =val \")\n should return {'key A': 'val B', 'k': '', '': 'val'}\n\n :param data_string: The string to parse.\n :return: A dictionary of parsed key-value pairs.\n \"\"\"\n result = {}\n if not data_string.strip():\n return result\n\n pairs = data_string.split(';')\n for pair_str in pairs:\n if '=' in pair_str:\n key, value = pair_str.split('=', 1)\n key = key.strip()\n value = value.strip()\n result[key] = value\n elif pair_str.strip(): # Handle cases like ' key_only ' if needed, though prompt implies '=' is always present\n # For this problem, we assume if there's no '=', it's not a valid key-value pair\n # or is an empty segment to be ignored (e.g., 'a=b;;c=d').\n # If 'a=b; ;c=d' should ignore the middle, `if '=' in pair_str` handles it.\n pass\n\n return result", "tests": ["assert parse_key_value_string(\"key1 = value one; key2=value two; key1 = new value\") == {'key1': 'new value', 'key2': 'value two'}", "assert parse_key_value_string(\" key A= val B ; k= ; =val \") == {'key A': 'val B', 'k': '', '': 'val'}", "assert parse_key_value_string(\"\") == {}", "assert parse_key_value_string(\" \") == {}", "assert parse_key_value_string(\"single_key=single_value\") == {'single_key': 'single_value'}", "assert parse_key_value_string(\" k=v;k2=v2 ; k=v3 \") == {'k': 'v3', 'k2': 'v2'}", "assert parse_key_value_string(\"no_equals_sign_here\") == {}", "assert parse_key_value_string(\"a=b;;c=d\") == {'a': 'b', 'c': 'd'}"]} {"name": "parse_key_value_string_878", "topic": "parsing simple formats", "prompt": "def parse_key_value_string(data_string: str) -> dict:\n \"\"\"\n Parses a string containing key-value pairs separated by semicolons, \n where each key and value are separated by an equals sign.\n\n Keys and values can contain spaces. Leading/trailing whitespace around \n keys and values should be stripped. Empty keys or values after stripping \n should be ignored. If a key appears multiple times, the last occurrence's \n value should be used.\n\n The input string might be empty or contain malformed pairs.\n Malformed pairs (e.g., 'key_only', '=value_only', 'key=') should be ignored.\n\n Args:\n data_string: A string like 'key1=value1; key2 = value2;key3=value3'\n\n Returns:\n A dictionary mapping parsed keys to their corresponding values.\n Returns an empty dictionary if the input string is empty or contains \n no valid pairs.\n\n Examples:\n parse_key_value_string('name=Alice;age=30') == {'name': 'Alice', 'age': '30'}\n parse_key_value_string(' color= blue ; size = M ') == {'color': 'blue', 'size': 'M'}\n parse_key_string('empty=;key=value;malformed') == {'key': 'value'}\n parse_key_value_string('a=1;b=2;a=3') == {'a': '3', 'b': '2'}\n parse_key_value_string('') == {}\n parse_key_value_string('no_equals; another =') == {}\n \"\"\"", "solution": "def parse_key_value_string(data_string: str) -> dict:\n \"\"\"\n Parses a string containing key-value pairs separated by semicolons, \n where each key and value are separated by an equals sign.\n\n Keys and values can contain spaces. Leading/trailing whitespace around \n keys and values should be stripped. Empty keys or values after stripping \n should be ignored. If a key appears multiple times, the last occurrence's \n value should be used.\n\n The input string might be empty or contain malformed pairs.\n Malformed pairs (e.g., 'key_only', '=value_only', 'key=') should be ignored.\n\n Args:\n data_string: A string like 'key1=value1; key2 = value2;key3=value3'\n\n Returns:\n A dictionary mapping parsed keys to their corresponding values.\n Returns an empty dictionary if the input string is empty or contains \n no valid pairs.\n\n Examples:\n parse_key_value_string('name=Alice;age=30') == {'name': 'Alice', 'age': '30'}\n parse_key_value_string(' color= blue ; size = M ') == {'color': 'blue', 'size': 'M'}\n parse_key_string('empty=;key=value;malformed') == {'key': 'value'}\n parse_key_value_string('a=1;b=2;a=3') == {'a': '3', 'b': '2'}\n parse_key_value_string('') == {}\n parse_key_value_string('no_equals; another =') == {}\n \"\"\"\n result = {}\n if not data_string:\n return result\n\n pairs = data_string.split(';')\n\n for pair in pairs:\n if '=' in pair:\n parts = pair.split('=', 1)\n key = parts[0].strip()\n value = parts[1].strip()\n\n if key and value:\n result[key] = value\n return result", "tests": ["assert parse_key_value_string('name=Alice;age=30') == {'name': 'Alice', 'age': '30'}", "assert parse_key_value_string(' color= blue ; size = M ') == {'color': 'blue', 'size': 'M'}", "assert parse_key_value_string('empty=;key=value;malformed;another_key=another_value') == {'key': 'value', 'another_key': 'another_value'}", "assert parse_key_value_string('a=1;b=2;a=3;c=4') == {'a': '3', 'b': '2', 'c': '4'}", "assert parse_key_value_string('') == {}", "assert parse_key_value_string('no_equals; another =; =value_only') == {}"]} {"name": "parse_key_value_string_543", "topic": "parsing simple formats", "prompt": "def parse_key_value_string(data_string: str) -> dict:\n \"\"\"\n Parses a string containing key-value pairs separated by semicolons, where each key\n and value are separated by an equals sign. Both keys and values can contain spaces.\n Leading/trailing whitespace around keys and values should be stripped.\n Empty keys or values should be ignored. If a key appears multiple times, the\n last encountered value for that key should be used.\n\n For example:\n parse_key_value_string(\" key1 = value1 ; key2 = value2 with spaces ; key1 = new value \")\n should return:\n {'key1': 'new value', 'key2': 'value2 with spaces'}\n\n parse_key_value_string(\"k1=v1;k2=;k3=v3;k4=\")\n should return:\n {'k1': 'v1', 'k3': 'v3'}\n\n parse_key_value_string(\"\")\n should return:\n {}\n\n parse_key_value_string(\" = ; another = value \")\n should return:\n {'another': 'value'}\n \"\"\"", "solution": "def parse_key_value_string(data_string: str) -> dict:\n \"\"\"\n Parses a string containing key-value pairs separated by semicolons, where each key\n and value are separated by an equals sign. Both keys and values can contain spaces.\n Leading/trailing whitespace around keys and values should be stripped.\n Empty keys or values should be ignored. If a key appears multiple times, the\n last encountered value for that key should be used.\n\n For example:\n parse_key_value_string(\" key1 = value1 ; key2 = value2 with spaces ; key1 = new value \")\n should return:\n {'key1': 'new value', 'key2': 'value2 with spaces'}\n\n parse_key_value_string(\"k1=v1;k2=;k3=v3;k4=\")\n should return:\n {'k1': 'v1', 'k3': 'v3'}\n\n parse_key_value_string(\"\")\n should return:\n {}\n\n parse_key_value_string(\" = ; another = value \")\n should return:\n {'another': 'value'}\n \"\"\"\n result = {}\n if not data_string:\n return result\n\n pairs = data_string.split(';')\n for pair in pairs:\n if '=' in pair:\n key, value = pair.split('=', 1)\n key = key.strip()\n value = value.strip()\n if key and value:\n result[key] = value\n return result", "tests": ["assert parse_key_value_string(\" key1 = value1 ; key2 = value2 with spaces ; key1 = new value \") == {'key1': 'new value', 'key2': 'value2 with spaces'}", "assert parse_key_value_string(\"k1=v1;k2=;k3=v3;k4=\") == {'k1': 'v1', 'k3': 'v3'}", "assert parse_key_value_string(\"\") == {}", "assert parse_key_value_string(\" = ; another = value \") == {'another': 'value'}", "assert parse_key_value_string(\" single_key = single_value \") == {'single_key': 'single_value'}", "assert parse_key_value_string(\"k=v;k=v2;k=v3\") == {'k': 'v3'}", "assert parse_key_value_string(\" k1 = v1 ; = ; k2 = v2 \") == {'k1': 'v1', 'k2': 'v2'}", "assert parse_key_value_string(\"just_text_no_equals;another_text\") == {}", "assert parse_key_value_string(\"key_with_many_spaces = value with many spaces\") == {'key_with_many_spaces': 'value with many spaces'}"]} {"name": "parse_key_value_string_220", "topic": "parsing simple formats", "prompt": "def parse_key_value_string(data_string: str) -> dict:\n \"\"\"\n Parses a string containing key-value pairs separated by newlines, \n where each key and value are separated by the first colon encountered.\n\n Keys and values should have leading/trailing whitespace stripped.\n Empty lines or lines that do not contain a colon are ignored.\n If a key appears multiple times, the last encountered value for that key takes precedence.\n\n Args:\n data_string: A multi-line string with key-value pairs.\n\n Returns:\n A dictionary where keys are the parsed keys and values are the parsed values.\n\n Examples:\n >>> parse_key_value_string(\"\"\"\n Name: Alice Smith\n Age: 30\n City: New York\n \"\"\")\n {'Name': 'Alice Smith', 'Age': '30', 'City': 'New York'}\n\n >>> parse_key_value_string(\"\"\"\n item_id: 123\n description: Some product\n price: 99.99\n tags: electronics, gadgets\n \"\"\")\n {'item_id': '123', 'description': 'Some product', 'price': '99.99', 'tags': 'electronics, gadgets'}\n\n >>> parse_key_value_string(\"\"\"\n Key1: Value1\n Key2:Value2\n Key1: New Value1\n \"\"\")\n {'Key1': 'New Value1', 'Key2': 'Value2'}\n\n >>> parse_key_value_string(\"\"\"\n Invalid Line\n Key: Value\n \n Another Key : Another Value\n \"\"\")\n {'Key': 'Value', 'Another Key': 'Another Value'}\n \"\"\"", "solution": "def parse_key_value_string(data_string: str) -> dict:\n parsed_data = {}\n for line in data_string.splitlines():\n if ':' in line:\n parts = line.split(':', 1)\n key = parts[0].strip()\n value = parts[1].strip()\n if key:\n parsed_data[key] = value\n return parsed_data", "tests": ["assert parse_key_value_string(\"Name: Alice Smith\\nAge: 30\\nCity: New York\") == {'Name': 'Alice Smith', 'Age': '30', 'City': 'New York'}", "assert parse_key_value_string(\"item_id: 123\\ndescription: Some product\\nprice: 99.99\\ntags: electronics, gadgets\") == {'item_id': '123', 'description': 'Some product', 'price': '99.99', 'tags': 'electronics, gadgets'}", "assert parse_key_value_string(\"Key1: Value1\\nKey2:Value2\\nKey1: New Value1\") == {'Key1': 'New Value1', 'Key2': 'Value2'}", "assert parse_key_value_string(\"Invalid Line\\nKey: Value\\n\\nAnother Key : Another Value\") == {'Key': 'Value', 'Another Key': 'Another Value'}", "assert parse_key_value_string(\" : Value with empty key\\nKey with trailing space : Value\\n Another Key : Another Value \") == {'Key with trailing space': 'Value', 'Another Key': 'Another Value'}", "assert parse_key_value_string(\"\") == {}"]} {"name": "parse_key_value_string_362", "topic": "parsing simple formats", "prompt": "def parse_key_value_string(data_string: str) -> dict:\n \"\"\"\n Parses a string containing key-value pairs separated by semicolons, \n where each key and value are separated by a colon.\n\n Keys and values should be stripped of leading/trailing whitespace.\n If a key appears multiple times, the last encountered value for that key should be used.\n Empty keys or values (after stripping) should be ignored. \n Pairs that are malformed (e.g., missing a colon, or an empty string after stripping)\n should also be ignored. An empty input string should return an empty dictionary.\n\n Args:\n data_string: The input string containing key-value pairs.\n\n Returns:\n A dictionary mapping parsed keys to their corresponding values.\n\n Examples:\n >>> parse_key_value_string(\"key1:value1; key2: value2 ; key3 : value3\")\n {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}\n >>> parse_key_value_string(\" k1: v1 ; k2 : v2 ; k1 : v3 \")\n {'k1': 'v3', 'k2': 'v2'}\n >>> parse_key_value_string(\"bad_pair; k:v; another_bad_pair:\")\n {'k': 'v'}\n >>> parse_key_value_string(\"empty_key:value; :value2; key3:\")\n {'empty_key': 'value'}\n >>> parse_key_value_string(\"\")\n {}\n \"\"\"", "solution": "def parse_key_value_string(data_string: str) -> dict:\n \"\"\"\n Parses a string containing key-value pairs separated by semicolons, \n where each key and value are separated by a colon.\n\n Keys and values should be stripped of leading/trailing whitespace.\n If a key appears multiple times, the last encountered value for that key should be used.\n Empty keys or values (after stripping) should be ignored. \n Pairs that are malformed (e.g., missing a colon, or an empty string after stripping)\n should also be ignored. An empty input string should return an empty dictionary.\n\n Args:\n data_string: The input string containing key-value pairs.\n\n Returns:\n A dictionary mapping parsed keys to their corresponding values.\n\n Examples:\n >>> parse_key_value_string(\"key1:value1; key2: value2 ; key3 : value3\")\n {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}\n >>> parse_key_value_string(\" k1: v1 ; k2 : v2 ; k1 : v3 \")\n {'k1': 'v3', 'k2': 'v2'}\n >>> parse_key_value_string(\"bad_pair; k:v; another_bad_pair:\")\n {'k': 'v'}\n >>> parse_key_value_string(\"empty_key:value; :value2; key3:\")\n {'empty_key': 'value'}\n >>> parse_key_value_string(\"\")\n {}\n \"\"\"\n result = {}\n if not data_string:\n return result\n\n pairs = data_string.split(';')\n for pair in pairs:\n if ':' in pair:\n parts = pair.split(':', 1) # Split only on the first colon\n key = parts[0].strip()\n value = parts[1].strip()\n\n if key and value:\n result[key] = value\n return result", "tests": ["assert parse_key_value_string(\"key1:value1; key2: value2 ; key3 : value3\") == {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}", "assert parse_key_value_string(\" k1: v1 ; k2 : v2 ; k1 : v3 \") == {'k1': 'v3', 'k2': 'v2'}", "assert parse_key_value_string(\"bad_pair; k:v; another_bad_pair:\") == {'k': 'v'}", "assert parse_key_value_string(\"empty_key:value; :value2; key3:\") == {'empty_key': 'value'}", "assert parse_key_value_string(\"\") == {}", "assert parse_key_value_string(\" ; ; \") == {}", "assert parse_key_value_string(\"single:pair\") == {'single': 'pair'}", "assert parse_key_value_string(\"k::v; k2:v2\") == {'k': ':v', 'k2': 'v2'}"]} {"name": "parse_key_value_string_616", "topic": "parsing simple formats", "prompt": "def parse_key_value_string(data_string: str) -> dict:\n \"\"\"\n Parses a string containing key-value pairs separated by newlines.\n Each key-value pair is separated by an equals sign ('=').\n \n Keys and values are stripped of leading/trailing whitespace.\n Empty lines are ignored. Lines that do not contain an equals sign\n are also ignored.\n \n If a key appears multiple times, the last encountered value for that\n key should be stored.\n\n Example:\n parse_key_value_string(\"\"\"\n key1=value1\n key2 = value2 with spaces\n \n key3= value3\n key1=new_value1\n invalid line\n \"\"\")\n # Expected: {'key1': 'new_value1', 'key2': 'value2 with spaces', 'key3': 'value3'}\n \"\"\"", "solution": "def parse_key_value_string(data_string: str) -> dict:\n result = {}\n lines = data_string.split('\\n')\n for line in lines:\n line = line.strip()\n if not line:\n continue\n \n if '=' in line:\n parts = line.split('=', 1) # Split only on the first '='\n key = parts[0].strip()\n value = parts[1].strip()\n result[key] = value\n return result", "tests": ["assert parse_key_value_string(\"key1=value1\\nkey2=value2\") == {'key1': 'value1', 'key2': 'value2'}", "assert parse_key_value_string(\"key1 = value1\\n key2= value2 with spaces \") == {'key1': 'value1', 'key2': 'value2 with spaces'}", "assert parse_key_value_string(\"\\nkey1=val1\\n\\nkey2=val2\\n\") == {'key1': 'val1', 'key2': 'val2'}", "assert parse_key_value_string(\"key1=initial\\nkey2=second\\nkey1=final\") == {'key1': 'final', 'key2': 'second'}", "assert parse_key_value_string(\"no_equals_sign\\nkey=value\\nanother_bad_line\") == {'key': 'value'}", "assert parse_key_value_string(\"\") == {}", "assert parse_key_value_string(\" \\n \\n \") == {}"]} {"name": "parse_key_value_string_676", "topic": "parsing simple formats", "prompt": "def parse_key_value_string(data_string: str) -> dict:\n \"\"\"\n Parses a string containing key-value pairs separated by newlines, \n where each key and value are separated by the first colon encountered.\n \n - Keys and values are stripped of leading/trailing whitespace.\n - Empty lines are ignored.\n - Lines without a colon are ignored.\n - If a key appears multiple times, the last value associated with that key should be used.\n \n Args:\n data_string: A multi-line string with key-value pairs.\n \n Returns:\n A dictionary mapping parsed keys to their corresponding values.\n\n Examples:\n >>> parse_key_value_string(\"\"\"\n name: John Doe\n age: 30\n city: New York\n \"\"\")\n {'name': 'John Doe', 'age': '30', 'city': 'New York'}\n\n >>> parse_key_value_string(\"\"\"\n item: Apple\n price: 1.20\n\n category: Fruit\n item: Gala Apple\n \"\"\")\n {'item': 'Gala Apple', 'price': '1.20', 'category': 'Fruit'}\n\n >>> parse_key_value_string(\"\"\"\n key_only\n :value_only\n \"\"\")\n {}\n \n >>> parse_key_value_string(\"\"\"\n key1: value1:part2\n key2 : value2\n key3:value3\n \"\"\")\n {'key1': 'value1:part2', 'key2': 'value2', 'key3': 'value3'}\n \"\"\"", "solution": "def parse_key_value_string(data_string: str) -> dict:\n result = {}\n lines = data_string.split('\\n')\n for line in lines:\n line = line.strip()\n if not line:\n continue\n \n parts = line.split(':', 1) # Split only on the first colon\n if len(parts) == 2:\n key = parts[0].strip()\n value = parts[1].strip()\n if key:\n result[key] = value\n return result", "tests": ["assert parse_key_value_string(\"\"\"\nname: Alice\nage: 25\ncountry: USA\n\"\"\") == {'name': 'Alice', 'age': '25', 'country': 'USA'}", "assert parse_key_value_string(\"\"\"\nproduct: Laptop\nprice: 999.99\n\ncategory: Electronics\nproduct: Gaming PC\n\"\"\") == {'product': 'Gaming PC', 'price': '999.99', 'category': 'Electronics'}", "assert parse_key_value_string(\"\"\"\n key1 : value1 \nkey2:value2\nkey3: value3 : with colon\n\"\"\") == {'key1': 'value1', 'key2': 'value2', 'key3': 'value3 : with colon'}", "assert parse_key_value_string(\"\"\"\nno_colon_here\n:value_without_key\nkey_with_empty_value:\n\"\"\") == {'key_with_empty_value': ''}", "assert parse_key_value_string(\"\") == {}", "assert parse_key_value_string(\"\"\"\n \n \n \n\"\"\") == {}"]} {"name": "parse_key_value_string_804", "topic": "parsing simple formats", "prompt": "def parse_key_value_string(data_string: str) -> dict:\n \"\"\"\n Parses a string containing key-value pairs separated by semicolons, \n where each key and value are separated by a colon.\n\n Keys and values are stripped of leading/trailing whitespace.\n If a key appears multiple times, the last encountered value for that key should be used.\n Empty keys or values (after stripping) should be ignored.\n Key-value pairs that do not contain a colon separator should also be ignored.\n\n For example:\n 'name: Alice; age: 30; city: New York' -> {'name': 'Alice', 'age': '30', 'city': 'New York'}\n ' item: apple ; price: 1.25 ; size: M ' -> {'item': 'apple', 'price': '1.25', 'size': 'M'}\n 'key1:value1;key2:value2;key1:new_value' -> {'key1': 'new_value', 'key2': 'value2'}\n 'empty:; invalid_pair; another: valid' -> {'another': 'valid'}\n ' key: value ; : ' -> {'key': 'value'}\n \"\"\"", "solution": "def parse_key_value_string(data_string: str) -> dict:\n result = {}\n pairs = data_string.split(';')\n\n for pair in pairs:\n if ':' in pair:\n parts = pair.split(':', 1) # Split only on the first colon\n key = parts[0].strip()\n value = parts[1].strip()\n\n if key and value:\n result[key] = value\n return result", "tests": ["assert parse_key_value_string('name: Alice; age: 30; city: New York') == {'name': 'Alice', 'age': '30', 'city': 'New York'}", "assert parse_key_value_string(' item: apple ; price: 1.25 ; size: M ') == {'item': 'apple', 'price': '1.25', 'size': 'M'}", "assert parse_key_value_string('key1:value1;key2:value2;key1:new_value') == {'key1': 'new_value', 'key2': 'value2'}", "assert parse_key_value_string('empty:; invalid_pair; another: valid; :') == {'another': 'valid'}", "assert parse_key_value_string('') == {}", "assert parse_key_value_string(' single_key: single_value ') == {'single_key': 'single_value'}", "assert parse_key_value_string('first:a;second:b;first:c;third:d') == {'first': 'c', 'second': 'b', 'third': 'd'}"]} {"name": "parse_key_value_string_600", "topic": "parsing simple formats", "prompt": "def parse_key_value_string(data_string: str) -> dict:\n \"\"\"\n Parses a string containing key-value pairs separated by semicolons, where each key\n and value are separated by an equals sign. Both keys and values can contain\n spaces. The function should return a dictionary mapping keys to their corresponding\n values.\n\n If a key appears multiple times, the last occurring value for that key should be used.\n Empty keys or values (e.g., 'key=;key2=value2' or '=value') should be treated as valid\n and stored as empty strings if they are present. Leading/trailing whitespace around\n keys, values, and the key-value pairs themselves should be stripped.\n Pairs that do not contain an '=' sign should be ignored.\n\n Args:\n data_string: A string containing key-value pairs, e.g., \" name = Alice; age=30; city = New York \"\n\n Returns:\n A dictionary where keys map to their values.\n\n Examples:\n >>> parse_key_value_string(\"name=Alice;age=30\")\n {'name': 'Alice', 'age': '30'}\n >>> parse_key_value_string(\" first = one; second=two ; first = three \")\n {'first': 'three', 'second': 'two'}\n >>> parse_key_value_string(\"empty_key=; =empty_value; valid=yes\")\n {'empty_key': '', '': 'empty_value', 'valid': 'yes'}\n >>> parse_key_value_string(\"no_equals;key=value\")\n {'key': 'value'}\n >>> parse_key_value_string(\" ; \")\n {}\n \"\"\"", "solution": "def parse_key_value_string(data_string: str) -> dict:\n result = {}\n pairs = data_string.split(';')\n for pair_str in pairs:\n stripped_pair = pair_str.strip()\n if '=' in stripped_pair:\n parts = stripped_pair.split('=', 1)\n key = parts[0].strip()\n value = parts[1].strip()\n result[key] = value\n return result", "tests": ["assert parse_key_value_string(\"name=Alice;age=30\") == {'name': 'Alice', 'age': '30'}", "assert parse_key_value_string(\" first = one; second=two ; first = three \") == {'first': 'three', 'second': 'two'}", "assert parse_key_value_string(\"empty_key=; =empty_value; valid=yes\") == {'empty_key': '', '': 'empty_value', 'valid': 'yes'}", "assert parse_key_value_string(\"no_equals;key=value;another_one\") == {'key': 'value'}", "assert parse_key_value_string(\" ; \") == {}", "assert parse_key_value_string(\"single_entry=test\") == {'single_entry': 'test'}", "assert parse_key_value_string(\"key with spaces = value with spaces;another=test\") == {'key with spaces': 'value with spaces', 'another': 'test'}"]} {"name": "parse_key_value_string_157", "topic": "parsing simple formats", "prompt": "def parse_key_value_string(data_string: str) -> dict:\n \"\"\"\n Parses a string containing key-value pairs separated by semicolons, \n where each key and value are separated by an equals sign.\n\n Keys and values can contain spaces. Keys and values are stripped of \n leading/trailing whitespace. Empty keys or values (after stripping) \n are ignored. Duplicate keys will overwrite previous values, with the \n last one encountered taking precedence.\n\n The input string can be empty or contain malformed segments (e.g., \n only a key, only a value, or multiple equals signs). Malformed \n segments should be ignored. For example, 'key1=value1; key2 ; =value3; key4=value4=extra' \n should result in {'key1': 'value1', 'key4': 'value4'}.\n\n Args:\n data_string: The string to parse.\n\n Returns:\n A dictionary where keys and values are strings.\n \"\"\"\n pass", "solution": "def parse_key_value_string(data_string: str) -> dict:\n \"\"\"\n Parses a string containing key-value pairs separated by semicolons, \n where each key and value are separated by an equals sign.\n\n Keys and values can contain spaces. Keys and values are stripped of \n leading/trailing whitespace. Empty keys or values (after stripping) \n are ignored. Duplicate keys will overwrite previous values, with the \n last one encountered taking precedence.\n\n The input string can be empty or contain malformed segments (e.g., \n only a key, only a value, or multiple equals signs). Malformed \n segments should be ignored. For example, 'key1=value1; key2 ; =value3; key4=value4=extra' \n should result in {'key1': 'value1', 'key4': 'value4'}.\n\n Args:\n data_string: The string to parse.\n\n Returns:\n A dictionary where keys and values are strings.\n \"\"\"\n result = {}\n if not data_string:\n return result\n\n pairs = data_string.split(';')\n\n for pair in pairs:\n parts = pair.split('=', 1) # Split only on the first '=' to handle values with '='\n if len(parts) == 2:\n key = parts[0].strip()\n value = parts[1].strip()\n if key and value:\n result[key] = value\n return result", "tests": ["assert parse_key_value_string('name=Alice;age=30;city=New York') == {'name': 'Alice', 'age': '30', 'city': 'New York'}", "assert parse_key_value_string(' key1 = value1 ; key2= value2 with spaces ') == {'key1': 'value1', 'key2': 'value2 with spaces'}", "assert parse_key_value_string('') == {}", "assert parse_key_value_string('invalid_pair;another = ; =value_only;valid=data') == {'valid': 'data'}", "assert parse_key_value_string('repeated=first;age=25;repeated=second') == {'repeated': 'second', 'age': '25'}", "assert parse_key_value_string('key_with_equals=value=123;normal_key=normal_value') == {'key_with_equals': 'value=123', 'normal_key': 'normal_value'}"]} {"name": "parse_key_value_string_766", "topic": "parsing simple formats", "prompt": "def parse_key_value_string(data_string: str) -> dict:\n \"\"\"\n Parses a string containing key-value pairs separated by semicolons, \n where each key and value are separated by an equals sign.\n\n Keys and values can contain spaces, but leading/trailing whitespace\n around the key and value themselves should be stripped. Empty keys \n or values are ignored (i.e., 'key=;key2=value2' means 'key' is ignored).\n If an equals sign is missing for a pair, that entire pair is ignored.\n If a semicolon is at the end, it should not create an empty pair.\n\n Args:\n data_string: The string to parse, e.g., 'name=Alice Smith; age=30; city=New York'\n\n Returns:\n A dictionary where keys are the parsed keys and values are the parsed values.\n Example: {'name': 'Alice Smith', 'age': '30', 'city': 'New York'}\n \"\"\"\n pass", "solution": "def parse_key_value_string(data_string: str) -> dict:\n \"\"\"\n Parses a string containing key-value pairs separated by semicolons, \n where each key and value are separated by an equals sign.\n\n Keys and values can contain spaces, but leading/trailing whitespace\n around the key and value themselves should be stripped. Empty keys \n or values are ignored (i.e., 'key=;key2=value2' means 'key' is ignored).\n If an equals sign is missing for a pair, that entire pair is ignored.\n If a semicolon is at the end, it should not create an empty pair.\n\n Args:\n data_string: The string to parse, e.g., 'name=Alice Smith; age=30; city=New York'\n\n Returns:\n A dictionary where keys are the parsed keys and values are the parsed values.\n Example: {'name': 'Alice Smith', 'age': '30', 'city': 'New York'}\n \"\"\"\n result = {}\n if not data_string.strip():\n return {}\n\n pairs = data_string.split(';')\n\n for pair in pairs:\n if not pair.strip():\n continue\n\n if '=' in pair:\n key_part, value_part = pair.split('=', 1)\n key = key_part.strip()\n value = value_part.strip()\n\n if key and value:\n result[key] = value\n return result", "tests": ["assert parse_key_value_string('name=Alice Smith; age=30; city=New York') == {'name': 'Alice Smith', 'age': '30', 'city': 'New York'}", "assert parse_key_value_string(' id=123 ; status = active ; ') == {'id': '123', 'status': 'active'}", "assert parse_key_value_string('empty_key=value;key_empty=;missing_eq') == {'empty_key': 'value'}", "assert parse_key_value_string('single=pair') == {'single': 'pair'}", "assert parse_key_value_string('') == {}", "assert parse_key_value_string(' ; ') == {}", "assert parse_key_value_string('key1=value1;key2;key3=value3') == {'key1': 'value1', 'key3': 'value3'}", "assert parse_key_value_string('key_with_ spaces = value with spaces ; an_other=test') == {'key_with_ spaces': 'value with spaces', 'an_other': 'test'}"]} {"name": "parse_key_value_string_582", "topic": "parsing simple formats", "prompt": "def parse_key_value_string(data_string: str) -> dict:\n \"\"\"\n Parses a string containing key-value pairs separated by newlines, \n where each key-value pair is separated by the first occurrence of an equals sign '='.\n\n Keys and values should be stripped of leading/trailing whitespace.\n Empty lines should be ignored.\n Lines that do not contain an equals sign should be ignored.\n If a key appears multiple times, the last occurring value should be used.\n\n Args:\n data_string: A multi-line string with key-value pairs.\n\n Returns:\n A dictionary representing the parsed key-value pairs.\n\n Examples:\n >>> parse_key_value_string(\"\"\"key1 = value1\\nkey2=value2\\nkey3 = another value\\n\"\"\")\n {'key1': 'value1', 'key2': 'value2', 'key3': 'another value'}\n\n >>> parse_key_value_string(\"\"\" k1 = v1 \\n k2 = v2 \\n k1 = new_v1 \\n invalid line\\n = badkey\\n\"\"\")\n {'k1': 'new_v1', 'k2': 'v2'}\n \"\"\"", "solution": "def parse_key_value_string(data_string: str) -> dict:\n result = {}\n lines = data_string.split('\\n')\n\n for line in lines:\n line = line.strip()\n if not line or '=' not in line:\n continue\n\n parts = line.split('=', 1)\n if len(parts) == 2:\n key = parts[0].strip()\n value = parts[1].strip()\n if key:\n result[key] = value\n\n return result", "tests": ["assert parse_key_value_string(\"\"\"key1 = value1\\nkey2=value2\\nkey3 = another value\\n\"\"\") == {'key1': 'value1', 'key2': 'value2', 'key3': 'another value'}", "assert parse_key_value_string(\"\"\" k1 = v1 \\n k2 = v2 \\n k1 = new_v1 \\n invalid line\\n = badkey\\n\"\"\") == {'k1': 'new_v1', 'k2': 'v2'}", "assert parse_key_value_string(\"\") == {}", "assert parse_key_value_string(\"\"\" \\n \\n no_equals_sign \\n key_only = \\n = value_only\\n\"\"\") == {'key_only': ''}", "assert parse_key_value_string(\"\"\" a=1\\nb=2\\na=3\\nc=4\\nb=5\"\"\") == {'a': '3', 'b': '5', 'c': '4'}", "assert parse_key_value_string(\"\"\" key with spaces = value with spaces \\n another key = another value = with multiple equals \\n\"\"\") == {'key with spaces': 'value with spaces', 'another key': 'another value = with multiple equals'}"]} {"name": "parse_key_value_string_942", "topic": "parsing simple formats", "prompt": "def parse_key_value_string(data_string: str) -> dict:\n \"\"\"\n Parses a string containing key-value pairs separated by newlines.\n Each key-value pair is separated by the first occurrence of an equals sign ('=').\n \n Keys and values should be stripped of leading/trailing whitespace.\n Empty lines or lines without an equals sign should be ignored.\n If a key appears multiple times, the last value associated with that key should be used.\n\n Args:\n data_string: A multi-line string where each line potentially contains a key=value pair.\n\n Returns:\n A dictionary where keys and values are strings, representing the parsed data.\n If data_string is empty or contains no valid pairs, an empty dictionary is returned.\n\n Examples:\n >>> parse_key_value_string(\"key1=value1\\nkey2 = value2\\nkey3 = another value\")\n {'key1': 'value1', 'key2': 'value2', 'key3': 'another value'}\n >>> parse_key_value_string(\" k = v \\n empty line \\n k=new_v \")\n {'k': 'new_v'}\n >>> parse_key_value_string(\"no_equals_sign\\nkey=value\")\n {'key': 'value'}\n >>> parse_key_value_string(\"\")\n {}\n \"\"\"", "solution": "def parse_key_value_string(data_string: str) -> dict:\n result = {}\n if not data_string:\n return result\n\n lines = data_string.split('\\n')\n for line in lines:\n line = line.strip()\n if not line:\n continue\n\n parts = line.split('=', 1)\n if len(parts) == 2:\n key = parts[0].strip()\n value = parts[1].strip()\n if key:\n result[key] = value\n return result", "tests": ["assert parse_key_value_string(\"key1=value1\\nkey2 = value2\\nkey3 = another value\") == {'key1': 'value1', 'key2': 'value2', 'key3': 'another value'}", "assert parse_key_value_string(\" k = v \\n empty line \\n k=new_v \") == {'k': 'new_v'}", "assert parse_key_value_string(\"no_equals_sign\\nkey=value\\n another_key = value with spaces\") == {'key': 'value', 'another_key': 'value with spaces'}", "assert parse_key_value_string(\"\") == {}", "assert parse_key_value_string(\"only_invalid_lines\\n no_eq \\n=just_value\") == {}", "assert parse_key_value_string(\"a=1\\nb=2\\na=3\\nc=4\") == {'a': '3', 'b': '2', 'c': '4'}", "assert parse_key_value_string(\" \\n \\n key=value \\n \") == {'key': 'value'}"]} {"name": "parse_key_value_string_808", "topic": "parsing simple formats", "prompt": "def parse_key_value_string(data_string: str) -> dict:\n \"\"\"\n Parses a string containing key-value pairs separated by newlines.\n Each key-value pair is separated by the first occurrence of an equals sign ('=').\n \n Keys and values should be stripped of leading/trailing whitespace.\n \n If a line does not contain an equals sign, it should be ignored.\n If a key is empty after stripping whitespace, that line should also be ignored.\n \n The function should return a dictionary where keys are the parsed keys\n and values are the parsed values.\n\n Example:\n parse_key_value_string(\"\"\"\n name = Alice\n age= 30\n city = New York\n invalid line\n =empty key\n occupation = Programmer\n \"\"\")\n # Returns: {'name': 'Alice', 'age': '30', 'city': 'New York', 'occupation': 'Programmer'}\n \"\"\"", "solution": "def parse_key_value_string(data_string: str) -> dict:\n result = {}\n lines = data_string.split('\\n')\n for line in lines:\n if '=' in line:\n parts = line.split('=', 1) # Split only on the first '=' \n key = parts[0].strip()\n value = parts[1].strip()\n if key:\n result[key] = value\n return result", "tests": ["assert parse_key_value_string(\"name = Alice\\nage=30\\ncity=New York\") == {'name': 'Alice', 'age': '30', 'city': 'New York'}", "assert parse_key_value_string(\"\"\"\nkey1 = value1\nkey2=value2 \n key3 = value3 \nno_equals_sign\n=empty_key_val\n = another_empty_key\nkey4 = val=ue4\n\"\"\") == {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'val=ue4'}", "assert parse_key_value_string(\"\") == {}", "assert parse_key_value_string(\"no equals sign here\\nalso no equals\") == {}", "assert parse_key_value_string(\" k1 = v1 \\n k2 = v2 \\n k3=v3\\n\") == {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}", "assert parse_key_value_string(\"key with spaces = value with spaces\\nanother key=another value\") == {'key with spaces': 'value with spaces', 'another key': 'another value'}"]} {"name": "parse_key_value_string_770", "topic": "parsing simple formats", "prompt": "def parse_key_value_string(data_string: str) -> dict:\n \"\"\"\n Parses a string containing key-value pairs separated by semicolons, \n where each key and value are separated by an equals sign.\n\n Keys and values can contain spaces. Keys are case-sensitive.\n Leading/trailing whitespace around keys and values should be stripped.\n Empty keys or values (after stripping) should be ignored.\n If a key appears multiple times, the last encountered value for that key should be used.\n\n Example:\n \"key1=value1;key2 = value2 with spaces ; key3 = another_value\"\n should return:\n {'key1': 'value1', 'key2': 'value2 with spaces', 'key3': 'another_value'}\n\n \" keyA = valA ; keyB=valB ; keyA = new_valA \"\n should return:\n {'keyA': 'new_valA', 'keyB': 'valB'}\n\n \" ; = ; key = value ; = \"\n should return:\n {'key': 'value'}\n\n Args:\n data_string: The input string to parse.\n\n Returns:\n A dictionary of the parsed key-value pairs.\n \"\"\"", "solution": "def parse_key_value_string(data_string: str) -> dict:\n result = {}\n pairs = data_string.split(';')\n for pair in pairs:\n if '=' in pair:\n key, value = pair.split('=', 1)\n key = key.strip()\n value = value.strip()\n if key and value:\n result[key] = value\n return result", "tests": ["assert parse_key_value_string('key1=value1;key2=value2') == {'key1': 'value1', 'key2': 'value2'}", "assert parse_key_value_string(' keyA = valA ; keyB=valB ; keyA = new_valA ') == {'keyA': 'new_valA', 'keyB': 'valB'}", "assert parse_key_value_string('name=John Doe; age = 30 ; city = New York') == {'name': 'John Doe', 'age': '30', 'city': 'New York'}", "assert parse_key_value_string(';=; key=value ; = ;empty= ; =empty_key') == {'key': 'value'}", "assert parse_key_value_string('') == {}", "assert parse_key_value_string(' single=value ') == {'single': 'value'}", "assert parse_key_value_string('no_equals_sign;key=value') == {'key': 'value'}"]} {"name": "parse_key_value_string_197", "topic": "parsing simple formats", "prompt": "def parse_key_value_string(data_string: str) -> dict:\n \"\"\"\n Parses a string containing key-value pairs separated by semicolons, \n where each key and value are separated by an equals sign.\n\n Keys and values can contain spaces. Leading/trailing whitespace around\n keys, values, and separators should be ignored. An empty string\n or a string containing only whitespace should return an empty dictionary.\n\n If a key appears multiple times, the last encountered value should be used.\n If a key or value is missing (e.g., 'key=;'), it should be treated as an empty string.\n If a pair is malformed (e.g., 'key' without an equals sign, or '=value'), it should be ignored.\n\n Args:\n data_string: The string to parse, e.g., ' key1 = value1 ; key2= value2 ; key1 = new value '\n\n Returns:\n A dictionary where keys are strings and values are strings.\n\n Examples:\n >>> parse_key_value_string('k1=v1; k2=v2')\n {'k1': 'v1', 'k2': 'v2'}\n >>> parse_key_value_string(' k A = V A ; k B =V B ')\n {'k A': 'V A', 'k B': 'V B'}\n >>> parse_key_value_string('key1=val1;key2=val2;key1=newval')\n {'key1': 'newval', 'key2': 'val2'}\n >>> parse_key_value_string(' ')\n {}\n >>> parse_key_value_string('empty=;key=value')\n {'empty': '', 'key': 'value'}\n >>> parse_key_value_string('badkey;goodkey=goodvalue')\n {'goodkey': 'goodvalue'}\n >>> parse_key_value_string('key1=val1;=val2;key2=val3')\n {'key1': 'val1', 'key2': 'val3'}\n \"\"\"", "solution": "def parse_key_value_string(data_string: str) -> dict:\n result = {}\n if not data_string.strip():\n return result\n\n pairs = data_string.split(';')\n for pair in pairs:\n if '=' in pair:\n key, value = pair.split('=', 1)\n key = key.strip()\n value = value.strip()\n if key:\n result[key] = value\n return result", "tests": ["assert parse_key_value_string('k1=v1; k2=v2') == {'k1': 'v1', 'k2': 'v2'}", "assert parse_key_value_string(' k A = V A ; k B =V B ') == {'k A': 'V A', 'k B': 'V B'}", "assert parse_key_value_string('key1=val1;key2=val2;key1=newval') == {'key1': 'newval', 'key2': 'val2'}", "assert parse_key_value_string(' ') == {}", "assert parse_key_value_string('empty=;key=value') == {'empty': '', 'key': 'value'}", "assert parse_key_value_string('badkey;goodkey=goodvalue;=anotherbad;key=') == {'goodkey': 'goodvalue', 'key': ''}", "assert parse_key_value_string('') == {}"]} {"name": "parse_key_value_string_250", "topic": "parsing simple formats", "prompt": "def parse_key_value_string(data_string: str) -> dict:\n \"\"\"\n Parses a string containing key-value pairs separated by newlines.\n Each key-value pair is separated by the first occurrence of an equals sign ('=').\n \n - Empty lines should be ignored.\n - Lines that do not contain an equals sign should be ignored.\n - Leading/trailing whitespace around keys and values should be stripped.\n - If a key appears multiple times, the last encountered value for that key should be used.\n\n Args:\n data_string: The input string containing key-value pairs.\n\n Returns:\n A dictionary where keys and values are strings, representing the parsed data.\n\n Example:\n >>> parse_key_value_string(\"\"\"\n ... key1 = value1\n ... key2=value2\n ... key3 = value3 with spaces \n ... invalid line\n ... key1=new_value1\n ... \n ... key4=value4\n ... \"\"\")\n {'key1': 'new_value1', 'key2': 'value2', 'key3': 'value3 with spaces', 'key4': 'value4'}\n \"\"\"", "solution": "def parse_key_value_string(data_string: str) -> dict:\n result = {}\n lines = data_string.split('\\n')\n for line in lines:\n stripped_line = line.strip()\n if not stripped_line:\n continue\n\n if '=' in stripped_line:\n first_equals_index = stripped_line.find('=')\n key = stripped_line[:first_equals_index].strip()\n value = stripped_line[first_equals_index + 1:].strip()\n result[key] = value\n return result", "tests": ["assert parse_key_value_string(\"key1=value1\\nkey2 = value2 with spaces\\nkey3=another value\") == {'key1': 'value1', 'key2': 'value2 with spaces', 'key3': 'another value'}", "assert parse_key_value_string(\"\\nkeyA = valA\\n\\nkeyB=valB\\n\") == {'keyA': 'valA', 'keyB': 'valB'}", "assert parse_key_value_string(\"keyX=valX\\nkeyY=valY\\nkeyX=newValX\") == {'keyX': 'newValX', 'keyY': 'valY'}", "assert parse_key_value_string(\"no_equals_sign\\nkey=value\\njust_a_word\") == {'key': 'value'}", "assert parse_key_value_string(\" key1 = value1 \\n key2= value2 \") == {'key1': 'value1', 'key2': 'value2'}", "assert parse_key_value_string(\"\") == {}"]} {"name": "rotate_matrix_90_clockwise", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_90_clockwise(matrix):\n \"\"\"\n Rotates a given square matrix 90 degrees clockwise in-place.\n\n The matrix is represented as a list of lists. The input matrix is guaranteed to be square\n (number of rows equals number of columns) and non-empty. The rotation should be performed\n without creating a new matrix to store the result, meaning the input 'matrix' list of lists\n should be modified directly.\n\n For example:\n If matrix = [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\n After rotation, matrix should become:\n [[7, 4, 1],\n [8, 5, 2],\n [9, 6, 3]]\n\n Args:\n matrix (list[list[int]]): The square matrix to rotate.\n\n Returns:\n None: The function modifies the input matrix in-place.\n \"\"\"", "solution": "def rotate_matrix_90_clockwise(matrix):\n n = len(matrix)\n\n # Transpose the matrix\n for i in range(n):\n for j in range(i, n):\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n\n # Reverse each row\n for i in range(n):\n matrix[i].reverse()", "tests": ["matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; rotate_matrix_90_clockwise(matrix1); assert matrix1 == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "matrix2 = [[1]]; rotate_matrix_90_clockwise(matrix2); assert matrix2 == [[1]]", "matrix3 = [[1, 2], [3, 4]]; rotate_matrix_90_clockwise(matrix3); assert matrix3 == [[3, 1], [4, 2]]", "matrix4 = [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]]; rotate_matrix_90_clockwise(matrix4); assert matrix4 == [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]]", "matrix5 = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]; rotate_matrix_90_clockwise(matrix5); assert matrix5 == [[0, 0, 0], [0, 0, 0], [0, 0, 0]]"]} {"name": "rotate_matrix_90_clockwise_405", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_90_clockwise(matrix):\n \"\"\"\n Rotates a given square matrix 90 degrees clockwise in-place.\n\n The matrix is represented as a list of lists. The input matrix will\n always be square (n x n) and non-empty. Modifications should be\n made directly to the input 'matrix' list of lists, and the function\n should not return anything.\n\n For example:\n If matrix = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n ]\n After rotation, matrix should become:\n [\n [7, 4, 1],\n [8, 5, 2],\n [9, 6, 3]\n ]\n \"\"\"", "solution": "def rotate_matrix_90_clockwise(matrix):\n n = len(matrix)\n\n # Transpose the matrix\n for i in range(n):\n for j in range(i, n):\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n\n # Reverse each row\n for i in range(n):\n matrix[i].reverse()", "tests": ["m1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; rotate_matrix_90_clockwise(m1); assert m1 == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "m2 = [[1]]; rotate_matrix_90_clockwise(m2); assert m2 == [[1]]", "m3 = [[1, 2], [3, 4]]; rotate_matrix_90_clockwise(m3); assert m3 == [[3, 1], [4, 2]]", "m4 = [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]]; rotate_matrix_90_clockwise(m4); assert m4 == [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]]", "m5 = [[10, 20], [30, 40]]; rotate_matrix_90_clockwise(m5); assert m5 == [[30, 10], [40, 20]]"]} {"name": "rotate_matrix_clockwise", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_clockwise(matrix):\n \"\"\"\n Rotates a 2D square matrix 90 degrees clockwise.\n\n The matrix is represented as a list of lists. Each inner list represents a row.\n The matrix is guaranteed to be square (N x N) and non-empty.\n\n For example:\n [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\n\n becomes:\n [[7, 4, 1],\n [8, 5, 2],\n [9, 6, 3]]\n\n Args:\n matrix (list[list[int]]): The input square matrix.\n\n Returns:\n list[list[int]]: The rotated matrix.\n \"\"\"", "solution": "def rotate_matrix_clockwise(matrix):\n n = len(matrix)\n if n == 0:\n return []\n\n rotated = [[0] * n for _ in range(n)]\n\n for i in range(n):\n for j in range(n):\n rotated[j][n - 1 - i] = matrix[i][j]\n return rotated", "tests": ["assert rotate_matrix_clockwise([[1]]) == [[1]]", "assert rotate_matrix_clockwise([[1, 2], [3, 4]]) == [[3, 1], [4, 2]]", "assert rotate_matrix_clockwise([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "assert rotate_matrix_clockwise([[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120], [130, 140, 150, 160]]) == [[130, 90, 50, 10], [140, 100, 60, 20], [150, 110, 70, 30], [160, 120, 80, 40]]", "assert rotate_matrix_clockwise([[-1, 0], [1, 2]]) == [[1, -1], [2, 0]]"]} {"name": "rotate_matrix_clockwise_643", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_clockwise(matrix):\n \"\"\"\n Rotates a 2D square matrix (list of lists) 90 degrees clockwise in-place.\n \n The matrix is guaranteed to be square (N x N) and non-empty.\n The elements can be of any type.\n \n Args:\n matrix: A list of lists representing the square matrix.\n The rotation should modify this matrix directly (in-place).\n \n Returns:\n None. The matrix is modified in-place.\n \n Example:\n matrix = [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\n rotate_matrix_clockwise(matrix)\n # matrix should now be [[7, 4, 1],\n # [8, 5, 2],\n # [9, 6, 3]]\n \"\"\"", "solution": "def rotate_matrix_clockwise(matrix):\n n = len(matrix)\n if n == 0 or n == 1:\n return\n\n # Transpose the matrix\n for i in range(n):\n for j in range(i, n):\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n\n # Reverse each row\n for i in range(n):\n matrix[i].reverse()", "tests": ["matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; rotate_matrix_clockwise(matrix1); assert matrix1 == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "matrix2 = [[1]]; rotate_matrix_clockwise(matrix2); assert matrix2 == [[1]]", "matrix3 = [[1, 2], [3, 4]]; rotate_matrix_clockwise(matrix3); assert matrix3 == [[3, 1], [4, 2]]", "matrix4 = [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]]; rotate_matrix_clockwise(matrix4); assert matrix4 == [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]]", "matrix5 = [['a', 'b'], ['c', 'd']]; rotate_matrix_clockwise(matrix5); assert matrix5 == [['c', 'a'], ['d', 'b']]"]} {"name": "rotate_matrix_clockwise_194", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_clockwise(matrix):\n \"\"\"\n Rotates a 2D square matrix clockwise by 90 degrees.\n\n The rotation should be performed in-place if possible (by modifying the input list of lists),\n but returning a new matrix is also acceptable. The returned matrix must represent the rotated state.\n\n For example:\n [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\n\n becomes:\n [[7, 4, 1],\n [8, 5, 2],\n [9, 6, 3]]\n\n Args:\n matrix: A list of lists representing a square matrix of integers.\n The matrix is guaranteed to be non-empty and have at least 1x1 dimensions.\n\n Returns:\n A new list of lists representing the matrix rotated 90 degrees clockwise.\n \"\"\"", "solution": "def rotate_matrix_clockwise(matrix):\n n = len(matrix)\n if n == 0 or len(matrix[0]) == 0:\n return []\n\n rotated_matrix = [[0] * n for _ in range(n)]\n\n for i in range(n):\n for j in range(n):\n rotated_matrix[j][n - 1 - i] = matrix[i][j]\n\n return rotated_matrix", "tests": ["assert rotate_matrix_clockwise([[1]]) == [[1]]", "assert rotate_matrix_clockwise([[1, 2], [3, 4]]) == [[3, 1], [4, 2]]", "assert rotate_matrix_clockwise([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "assert rotate_matrix_clockwise([['a', 'b'], ['c', 'd']]) == [['c', 'a'], ['d', 'b']]", "assert rotate_matrix_clockwise([[10, 20, 30, 40], [1, 2, 3, 4], [11, 22, 33, 44], [111, 222, 333, 444]]) == [[111, 11, 1, 10], [222, 22, 2, 20], [333, 33, 3, 30], [444, 44, 4, 40]]"]} {"name": "rotate_matrix_90_degrees", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_90_degrees(matrix):\n \"\"\"\n Rotates a 2D square matrix (list of lists) 90 degrees clockwise in-place.\n\n The matrix is guaranteed to be square (N x N) and non-empty. \n The elements can be any type.\n\n Args:\n matrix: A list of lists representing the square matrix.\n The rotation should be performed in-place, modifying the \n original matrix object.\n\n Example:\n matrix = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n ]\n rotate_matrix_90_degrees(matrix)\n # matrix is now:\n # [\n # [7, 4, 1],\n # [8, 5, 2],\n # [9, 6, 3]\n # ]\n \"\"\"", "solution": "def rotate_matrix_90_degrees(matrix):\n n = len(matrix)\n\n # Transpose the matrix\n for i in range(n):\n for j in range(i, n):\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n\n # Reverse each row\n for i in range(n):\n matrix[i].reverse()", "tests": ["matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; rotate_matrix_90_degrees(matrix1); assert matrix1 == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "matrix2 = [[1]]; rotate_matrix_90_degrees(matrix2); assert matrix2 == [[1]]", "matrix3 = [[1, 2], [3, 4]]; rotate_matrix_90_degrees(matrix3); assert matrix3 == [[3, 1], [4, 2]]", "matrix4 = [['a', 'b'], ['c', 'd']]; rotate_matrix_90_degrees(matrix4); assert matrix4 == [['c', 'a'], ['d', 'b']]", "matrix5 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]; rotate_matrix_90_degrees(matrix5); assert matrix5 == [[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]]"]} {"name": "rotate_matrix_clockwise_117", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_clockwise(matrix: list[list[int]]) -> list[list[int]]:\n \"\"\"\n Rotates a given square matrix clockwise by 90 degrees.\n\n The matrix is represented as a list of lists of integers.\n The input matrix is guaranteed to be square (M x M) and non-empty.\n\n For example:\n rotate_matrix_clockwise([[1, 2], [3, 4]]) == [[3, 1], [4, 2]]\n rotate_matrix_clockwise([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]\n \"\"\"", "solution": "def rotate_matrix_clockwise(matrix: list[list[int]]) -> list[list[int]]:\n n = len(matrix)\n if n == 0:\n return []\n\n rotated_matrix = [[0] * n for _ in range(n)]\n\n for i in range(n):\n for j in range(n):\n rotated_matrix[j][n - 1 - i] = matrix[i][j]\n\n return rotated_matrix", "tests": ["assert rotate_matrix_clockwise([[1]]) == [[1]]", "assert rotate_matrix_clockwise([[1, 2], [3, 4]]) == [[3, 1], [4, 2]]", "assert rotate_matrix_clockwise([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "assert rotate_matrix_clockwise([[-1, -2, -3, -4], [-5, -6, -7, -8], [-9, -10, -11, -12], [-13, -14, -15, -16]]) == [[-13, -9, -5, -1], [-14, -10, -6, -2], [-15, -11, -7, -3], [-16, -12, -8, -4]]", "assert rotate_matrix_clockwise([[10, 20, 30], [40, 50, 60], [70, 80, 90]]) == [[70, 40, 10], [80, 50, 20], [90, 60, 30]]"]} {"name": "rotate_matrix_90_clockwise_963", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_90_clockwise(matrix):\n \"\"\"\n Rotates a given square matrix 90 degrees clockwise in-place.\n \n The matrix is represented as a list of lists. For example:\n [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\n\n After rotation, it should become:\n [[7, 4, 1],\n [8, 5, 2],\n [9, 6, 3]]\n\n The function should modify the input matrix directly (in-place) and return None.\n You can assume the input `matrix` is a non-empty list of lists representing\n a valid square matrix (N x N, where N >= 1). Each element can be any type.\n \n Args:\n matrix (list[list]): The square matrix to be rotated.\n\n Returns:\n None: The rotation is performed in-place.\n \"\"\"", "solution": "def rotate_matrix_90_clockwise(matrix):\n n = len(matrix)\n\n # Transpose the matrix\n for i in range(n):\n for j in range(i, n):\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n\n # Reverse each row\n for i in range(n):\n matrix[i].reverse()", "tests": ["matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; rotate_matrix_90_clockwise(matrix1); assert matrix1 == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "matrix2 = [[1]]; rotate_matrix_90_clockwise(matrix2); assert matrix2 == [[1]]", "matrix3 = [[1, 2], [3, 4]]; rotate_matrix_90_clockwise(matrix3); assert matrix3 == [[3, 1], [4, 2]]", "matrix4 = [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]]; rotate_matrix_90_clockwise(matrix4); assert matrix4 == [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]]", "matrix5 = [['a', 'b'], ['c', 'd']]; rotate_matrix_90_clockwise(matrix5); assert matrix5 == [['c', 'a'], ['d', 'b']]"]} {"name": "rotate_matrix_90_clockwise_597", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_90_clockwise(matrix):\n \"\"\"\n Rotates a given square matrix 90 degrees clockwise in-place.\n The function modifies the input matrix directly and does not return anything.\n\n A square matrix 'matrix' of size N x N is given as a list of lists.\n\n For example:\n If matrix = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n ]\n\n After rotation, matrix should become:\n [\n [7, 4, 1],\n [8, 5, 2],\n [9, 6, 3]\n ]\n\n Assumes the input 'matrix' is always a non-empty square matrix (N >= 1).\n \"\"\"", "solution": "def rotate_matrix_90_clockwise(matrix):\n n = len(matrix)\n\n # Transpose the matrix\n for i in range(n):\n for j in range(i, n):\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n\n # Reverse each row\n for i in range(n):\n matrix[i].reverse()", "tests": ["matrix1 = [[1, 2], [3, 4]]; rotate_matrix_90_clockwise(matrix1); assert matrix1 == [[3, 1], [4, 2]]", "matrix2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; rotate_matrix_90_clockwise(matrix2); assert matrix2 == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "matrix3 = [[5]]; rotate_matrix_90_clockwise(matrix3); assert matrix3 == [[5]]", "matrix4 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]; rotate_matrix_90_clockwise(matrix4); assert matrix4 == [[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]]", "matrix5 = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]; rotate_matrix_90_clockwise(matrix5); assert matrix5 == [[70, 40, 10], [80, 50, 20], [90, 60, 30]]"]} {"name": "rotate_matrix_clockwise_461", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_clockwise(matrix):\n \"\"\"\n Rotates a 2D square matrix 90 degrees clockwise.\n\n The rotation should be performed in-place if possible (modifying the input matrix),\n but returning a new matrix is also acceptable for simplicity.\n\n For example:\n [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\n\n becomes:\n [[7, 4, 1],\n [8, 5, 2],\n [9, 6, 3]]\n\n Args:\n matrix: A list of lists representing a square matrix of integers.\n The matrix will always be non-empty and square (N x N).\n\n Returns:\n A new list of lists representing the rotated matrix.\n \"\"\"", "solution": "def rotate_matrix_clockwise(matrix):\n n = len(matrix)\n if n == 0:\n return []\n\n # Create a new matrix for the result\n rotated = [[0] * n for _ in range(n)]\n\n for i in range(n):\n for j in range(n):\n # The element at (i, j) in the original matrix moves to (j, n - 1 - i)\n rotated[j][n - 1 - i] = matrix[i][j]\n return rotated", "tests": ["assert rotate_matrix_clockwise([[1, 2], [3, 4]]) == [[3, 1], [4, 2]]", "assert rotate_matrix_clockwise([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "assert rotate_matrix_clockwise([[1]]) == [[1]]", "assert rotate_matrix_clockwise([['a', 'b'], ['c', 'd']]) == [['c', 'a'], ['d', 'b']]", "assert rotate_matrix_clockwise([[10, 20, 30, 40], [11, 21, 31, 41], [12, 22, 32, 42], [13, 23, 33, 43]]) == [[13, 12, 11, 10], [23, 22, 21, 20], [33, 32, 31, 30], [43, 42, 41, 40]]"]} {"name": "rotate_matrix_90_clockwise_934", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_90_clockwise(matrix):\n \"\"\"\n Rotates a given square matrix 90 degrees clockwise in-place.\n\n The matrix is represented as a list of lists. For example, a 3x3 matrix:\n [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n ]\n\n After rotation, it becomes:\n [\n [7, 4, 1],\n [8, 5, 2],\n [9, 6, 3]\n ]\n\n This function modifies the input matrix directly and does not return a new one.\n It is guaranteed that the input matrix will be square (n x n) and non-empty.\n The elements can be any type.\n\n Args:\n matrix (list[list]): The square matrix to be rotated.\n\n Returns:\n None: The rotation is performed in-place.\n \"\"\"", "solution": "def rotate_matrix_90_clockwise(matrix):\n n = len(matrix)\n\n # Transpose the matrix\n for i in range(n):\n for j in range(i, n):\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n\n # Reverse each row\n for i in range(n):\n matrix[i].reverse()", "tests": ["matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; rotate_matrix_90_clockwise(matrix1); assert matrix1 == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "matrix2 = [[1]]; rotate_matrix_90_clockwise(matrix2); assert matrix2 == [[1]]", "matrix3 = [[1, 2], [3, 4]]; rotate_matrix_90_clockwise(matrix3); assert matrix3 == [[3, 1], [4, 2]]", "matrix4 = [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120], [130, 140, 150, 160]]; rotate_matrix_90_clockwise(matrix4); assert matrix4 == [[130, 90, 50, 10], [140, 100, 60, 20], [150, 110, 70, 30], [160, 120, 80, 40]]", "matrix5 = [['a', 'b'], ['c', 'd']]; rotate_matrix_90_clockwise(matrix5); assert matrix5 == [['c', 'a'], ['d', 'b']]"]} {"name": "rotate_matrix_90_clockwise_868", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_90_clockwise(matrix):\n \"\"\"\n Rotates a 2D square matrix (list of lists) 90 degrees clockwise in-place.\n\n The matrix is guaranteed to be non-empty and square (N x N), where N >= 1.\n The elements can be of any type.\n\n Example:\n [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\n\n becomes:\n [[7, 4, 1],\n [8, 5, 2],\n [9, 6, 3]]\n\n Args:\n matrix: A list of lists representing the square matrix.\n The rotation should happen in-place, meaning the original\n 'matrix' object should be modified directly.\n \"\"\"\n", "solution": "def rotate_matrix_90_clockwise(matrix):\n n = len(matrix)\n if n == 0 or n == 1:\n return\n\n # Transpose the matrix\n for i in range(n):\n for j in range(i, n):\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n\n # Reverse each row\n for i in range(n):\n matrix[i].reverse()\n", "tests": ["matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; rotate_matrix_90_clockwise(matrix1); assert matrix1 == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "matrix2 = [[1]]; rotate_matrix_90_clockwise(matrix2); assert matrix2 == [[1]]", "matrix3 = [[5, 1], [9, 3]]; rotate_matrix_90_clockwise(matrix3); assert matrix3 == [[9, 5], [3, 1]]", "matrix4 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]; rotate_matrix_90_clockwise(matrix4); assert matrix4 == [[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]]", "matrix5 = [['a', 'b'], ['c', 'd']]; rotate_matrix_90_clockwise(matrix5); assert matrix5 == [['c', 'a'], ['d', 'b']]"]} {"name": "rotate_matrix_90_clockwise_525", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_90_clockwise(matrix):\n \"\"\"\n Rotates a 2D square matrix 90 degrees clockwise in-place.\n The function should modify the input matrix directly and not return a new one.\n\n A square matrix means it has the same number of rows and columns.\n For example:\n [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\n\n rotated becomes:\n [[7, 4, 1],\n [8, 5, 2],\n [9, 6, 3]]\n\n Args:\n matrix: A list of lists representing a square matrix of integers.\n The matrix is modified in-place.\n\n Returns:\n None\n \"\"\"", "solution": "def rotate_matrix_90_clockwise(matrix):\n n = len(matrix)\n if n == 0:\n return\n\n # Transpose the matrix\n for i in range(n):\n for j in range(i, n):\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n\n # Reverse each row\n for i in range(n):\n matrix[i].reverse()", "tests": ["matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; rotate_matrix_90_clockwise(matrix1); assert matrix1 == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "matrix2 = [[1]]; rotate_matrix_90_clockwise(matrix2); assert matrix2 == [[1]]", "matrix3 = [[1, 2], [3, 4]]; rotate_matrix_90_clockwise(matrix3); assert matrix3 == [[3, 1], [4, 2]]", "matrix4 = []; rotate_matrix_90_clockwise(matrix4); assert matrix4 == []", "matrix5 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]; rotate_matrix_90_clockwise(matrix5); assert matrix5 == [[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]]", "matrix6 = [[-1, 0], [1, 2]]; rotate_matrix_90_clockwise(matrix6); assert matrix6 == [[1, -1], [2, 0]]"]} {"name": "rotate_matrix_clockwise_689", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_clockwise(matrix):\n \"\"\"\n Rotates a 2D square matrix clockwise by 90 degrees.\n\n The rotation should be performed in-place if possible (modifying the original list of lists),\n but returning a new matrix is also acceptable. The core requirement is the correct\n transformation. For simplicity, assume the input matrix is always square (N x N)\n and contains only integers.\n\n For example:\n [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\n\n becomes:\n [[7, 4, 1],\n [8, 5, 2],\n [9, 6, 3]]\n\n Args:\n matrix: A list of lists representing a square matrix of integers.\n\n Returns:\n A new list of lists representing the rotated matrix.\n \"\"\"", "solution": "def rotate_matrix_clockwise(matrix):\n n = len(matrix)\n if n == 0:\n return []\n\n rotated_matrix = [[0] * n for _ in range(n)]\n\n for i in range(n):\n for j in range(n):\n rotated_matrix[j][n - 1 - i] = matrix[i][j]\n\n return rotated_matrix", "tests": ["assert rotate_matrix_clockwise([[1]]) == [[1]]", "assert rotate_matrix_clockwise([[1, 2], [3, 4]]) == [[3, 1], [4, 2]]", "assert rotate_matrix_clockwise([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "assert rotate_matrix_clockwise([[10, 20, 30, 40], [11, 21, 31, 41], [12, 22, 32, 42], [13, 23, 33, 43]]) == [[13, 12, 11, 10], [23, 22, 21, 20], [33, 32, 31, 30], [43, 42, 41, 40]]", "assert rotate_matrix_clockwise([]) == []"]} {"name": "rotate_matrix_90_clockwise_100", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_90_clockwise(matrix):\n \"\"\"\n Rotates a 2D square matrix 90 degrees clockwise in-place.\n\n The matrix is represented as a list of lists. The rotation should modify\n the input matrix directly (in-place) and then return the modified matrix.\n\n For example:\n [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\n\n becomes:\n [[7, 4, 1],\n [8, 5, 2],\n [9, 6, 3]]\n\n Args:\n matrix: A list of lists representing a square matrix of integers.\n The matrix will always be non-empty and square (N x N).\n\n Returns:\n The rotated matrix (the same object passed as input, modified in-place).\n \"\"\"", "solution": "def rotate_matrix_90_clockwise(matrix):\n n = len(matrix)\n\n # Transpose the matrix\n for i in range(n):\n for j in range(i, n):\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n\n # Reverse each row\n for i in range(n):\n matrix[i].reverse()\n \n return matrix", "tests": ["matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; assert rotate_matrix_90_clockwise(matrix1) == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "matrix2 = [[1]]; assert rotate_matrix_90_clockwise(matrix2) == [[1]]", "matrix3 = [[1, 2], [3, 4]]; assert rotate_matrix_90_clockwise(matrix3) == [[3, 1], [4, 2]]", "matrix4 = [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]]; assert rotate_matrix_90_clockwise(matrix4) == [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]]", "matrix5 = [[10, 20, 30, 40, 50], [1, 2, 3, 4, 5], [11, 12, 13, 14, 15], [21, 22, 23, 24, 25], [31, 32, 33, 34, 35]]; assert rotate_matrix_90_clockwise(matrix5) == [[31, 21, 11, 1, 10], [32, 22, 12, 2, 20], [33, 23, 13, 3, 30], [34, 24, 14, 4, 40], [35, 25, 15, 5, 50]]"]} {"name": "rotate_matrix_clockwise_163", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_clockwise(matrix):\n \"\"\"\n Rotates a 2D square matrix 90 degrees clockwise.\n\n The matrix is represented as a list of lists. Each inner list represents a row.\n The matrix is guaranteed to be square (N x N) and non-empty.\n\n For example:\n [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\n\n becomes:\n [[7, 4, 1],\n [8, 5, 2],\n [9, 6, 3]]\n\n Args:\n matrix (list[list[int]]): The input square matrix.\n\n Returns:\n list[list[int]]: The rotated matrix.\n \"\"\"", "solution": "def rotate_matrix_clockwise(matrix):\n n = len(matrix)\n if n == 0:\n return []\n\n rotated = [[0] * n for _ in range(n)]\n\n for i in range(n):\n for j in range(n):\n rotated[j][n - 1 - i] = matrix[i][j]\n return rotated", "tests": ["assert rotate_matrix_clockwise([[1]]) == [[1]]", "assert rotate_matrix_clockwise([[1, 2], [3, 4]]) == [[3, 1], [4, 2]]", "assert rotate_matrix_clockwise([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "assert rotate_matrix_clockwise([['a', 'b'], ['c', 'd']]) == [['c', 'a'], ['d', 'b']]", "assert rotate_matrix_clockwise([[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120], [130, 140, 150, 160]]) == [[130, 90, 50, 10], [140, 100, 60, 20], [150, 110, 70, 30], [160, 120, 80, 40]]"]} {"name": "rotate_matrix_90_clockwise_913", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_90_clockwise(matrix):\n \"\"\"\n Rotates a given square matrix 90 degrees clockwise in-place.\n\n The matrix is represented as a list of lists. The input matrix will always be square\n (N x N) and will contain integers. The rotation should modify the original matrix\n directly. If the matrix is empty or has a single element, it should remain unchanged.\n\n Args:\n matrix: A list of lists representing the square matrix.\n\n Examples:\n >>> mat1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n >>> rotate_matrix_90_clockwise(mat1)\n >>> mat1\n [[7, 4, 1], [8, 5, 2], [9, 6, 3]]\n\n >>> mat2 = [[5]]\n >>> rotate_matrix_90_clockwise(mat2)\n >>> mat2\n [[5]]\n\n >>> mat3 = []\n >>> rotate_matrix_90_clockwise(mat3)\n >>> mat3\n []\n\n >>> mat4 = [[1, 2], [3, 4]]\n >>> rotate_matrix_90_clockwise(mat4)\n >>> mat4\n [[3, 1], [4, 2]]\n \"\"\"", "solution": "def rotate_matrix_90_clockwise(matrix):\n n = len(matrix)\n if n == 0 or n == 1:\n return\n\n # Transpose the matrix\n for i in range(n):\n for j in range(i, n):\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n\n # Reverse each row\n for i in range(n):\n matrix[i].reverse()", "tests": ["mat1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; rotate_matrix_90_clockwise(mat1); assert mat1 == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "mat2 = [[5]]; rotate_matrix_90_clockwise(mat2); assert mat2 == [[5]]", "mat3 = []; rotate_matrix_90_clockwise(mat3); assert mat3 == []", "mat4 = [[1, 2], [3, 4]]; rotate_matrix_90_clockwise(mat4); assert mat4 == [[3, 1], [4, 2]]", "mat5 = [[10, 20, 30, 40], [11, 21, 31, 41], [12, 22, 32, 42], [13, 23, 33, 43]]; rotate_matrix_90_clockwise(mat5); assert mat5 == [[13, 12, 11, 10], [23, 22, 21, 20], [33, 32, 31, 30], [43, 42, 41, 40]]", "mat6 = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]; rotate_matrix_90_clockwise(mat6); assert mat6 == [[0, 0, 1], [0, 1, 0], [1, 0, 0]]"]} {"name": "rotate_matrix_clockwise_592", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_clockwise(matrix):\n \"\"\"\n Rotates a 2D square matrix 90 degrees clockwise.\n\n The matrix is represented as a list of lists. The input matrix is guaranteed to be\n non-empty and square (i.e., num_rows == num_cols).\n\n For example:\n rotate_matrix_clockwise([[1, 2],\n [3, 4]])\n should return [[3, 1],\n [4, 2]]\n\n rotate_matrix_clockwise([[1]])\n should return [[1]]\n\n rotate_matrix_clockwise([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])\n should return [[7, 4, 1],\n [8, 5, 2],\n [9, 6, 3]]\n \"\"\"", "solution": "def rotate_matrix_clockwise(matrix):\n n = len(matrix)\n if n == 0:\n return []\n\n rotated_matrix = [[0] * n for _ in range(n)]\n\n for i in range(n):\n for j in range(n):\n # New row index is the old column index\n # New column index is (n - 1 - old row index)\n rotated_matrix[j][n - 1 - i] = matrix[i][j]\n\n return rotated_matrix", "tests": ["assert rotate_matrix_clockwise([[1]]) == [[1]]", "assert rotate_matrix_clockwise([[1, 2], [3, 4]]) == [[3, 1], [4, 2]]", "assert rotate_matrix_clockwise([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "assert rotate_matrix_clockwise([[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120], [130, 140, 150, 160]]) == [[130, 90, 50, 10], [140, 100, 60, 20], [150, 110, 70, 30], [160, 120, 80, 40]]", "assert rotate_matrix_clockwise([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) == [[0, 0, 1], [0, 1, 0], [1, 0, 0]]"]} {"name": "rotate_matrix_90_clockwise_249", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_90_clockwise(matrix):\n \"\"\"\n Rotates a 2D square matrix 90 degrees clockwise in-place.\n\n The matrix is represented as a list of lists. The rotation should modify\n the input matrix directly (in-place) and return None.\n\n For example:\n If matrix = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n ]\n After rotation, it should become:\n [\n [7, 4, 1],\n [8, 5, 2],\n [9, 6, 3]\n ]\n\n Args:\n matrix: A list of lists representing a square matrix of integers.\n The matrix is guaranteed to be non-empty and have at least\n one row/column. All rows will have the same length.\n\n Returns:\n None. The rotation is performed in-place.\n \"\"\"", "solution": "def rotate_matrix_90_clockwise(matrix):\n n = len(matrix)\n if n == 0 or n == 1:\n return\n\n # Transpose the matrix\n for i in range(n):\n for j in range(i, n):\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n\n # Reverse each row\n for i in range(n):\n matrix[i].reverse()", "tests": ["m1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; rotate_matrix_90_clockwise(m1); assert m1 == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "m2 = [[1]]; rotate_matrix_90_clockwise(m2); assert m2 == [[1]]", "m3 = [[1, 2], [3, 4]]; rotate_matrix_90_clockwise(m3); assert m3 == [[3, 1], [4, 2]]", "m4 = [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]]; rotate_matrix_90_clockwise(m4); assert m4 == [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]]", "m5 = [[10, 20, 30, 40, 50], [1, 2, 3, 4, 5], [11, 12, 13, 14, 15], [21, 22, 23, 24, 25], [31, 32, 33, 34, 35]]; rotate_matrix_90_clockwise(m5); assert m5 == [[31, 21, 11, 1, 10], [32, 22, 12, 2, 20], [33, 23, 13, 3, 30], [34, 24, 14, 4, 40], [35, 25, 15, 5, 50]]"]} {"name": "rotate_matrix_clockwise_878", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_clockwise(matrix):\n \"\"\"\n Rotates a square matrix 90 degrees clockwise.\n\n The matrix is represented as a list of lists. The input matrix is guaranteed to be square\n (n x n) and non-empty, with n >= 1.\n\n For example:\n rotate_matrix_clockwise([[1, 2],\n [3, 4]])\n should return [[3, 1],\n [4, 2]]\n\n rotate_matrix_clockwise([[1]])\n should return [[1]]\n\n rotate_matrix_clockwise([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])\n should return [[7, 4, 1],\n [8, 5, 2],\n [9, 6, 3]]\n \"\"\"", "solution": "def rotate_matrix_clockwise(matrix):\n n = len(matrix)\n if n == 0 or n == 1:\n return matrix\n\n rotated_matrix = [[0 for _ in range(n)] for _ in range(n)]\n\n for i in range(n):\n for j in range(n):\n # The element at (i, j) in the original matrix\n # moves to (j, n - 1 - i) in the rotated matrix.\n rotated_matrix[j][n - 1 - i] = matrix[i][j]\n \n return rotated_matrix", "tests": ["assert rotate_matrix_clockwise([[1, 2], [3, 4]]) == [[3, 1], [4, 2]]", "assert rotate_matrix_clockwise([[1]]) == [[1]]", "assert rotate_matrix_clockwise([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "assert rotate_matrix_clockwise([[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120], [130, 140, 150, 160]]) == [[130, 90, 50, 10], [140, 100, 60, 20], [150, 110, 70, 30], [160, 120, 80, 40]]", "assert rotate_matrix_clockwise([['a', 'b'], ['c', 'd']]) == [['c', 'a'], ['d', 'b']]", "assert rotate_matrix_clockwise([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) == [[0, 0, 0], [0, 0, 0], [0, 0, 0]]"]} {"name": "rotate_matrix_clockwise_948", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_clockwise(matrix):\n \"\"\"\n Rotates a square matrix clockwise by 90 degrees.\n\n The rotation should be performed in-place if possible (by modifying the input list of lists),\n but returning a new matrix is also acceptable for simplicity.\n The input matrix is guaranteed to be square (N x N) and non-empty.\n\n For example:\n rotate_matrix_clockwise([ [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9] ])\n should return:\n [ [7, 4, 1],\n [8, 5, 2],\n [9, 6, 3] ]\n \"\"\"", "solution": "def rotate_matrix_clockwise(matrix):\n n = len(matrix)\n # Create a new matrix to store the rotated result\n rotated_matrix = [[0] * n for _ in range(n)]\n\n for i in range(n):\n for j in range(n):\n # New row index is old column index\n # New column index is (n - 1 - old row index)\n rotated_matrix[j][n - 1 - i] = matrix[i][j]\n return rotated_matrix", "tests": ["assert rotate_matrix_clockwise([[1]]) == [[1]]", "assert rotate_matrix_clockwise([[1, 2], [3, 4]]) == [[3, 1], [4, 2]]", "assert rotate_matrix_clockwise([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "assert rotate_matrix_clockwise([[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21], [22, 23, 24, 25]]) == [[22, 18, 14, 10], [23, 19, 15, 11], [24, 20, 16, 12], [25, 21, 17, 13]]", "assert rotate_matrix_clockwise([[1,0],[0,1]]) == [[0,1],[1,0]]"]} {"name": "rotate_matrix_90_clockwise_874", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_90_clockwise(matrix):\n \"\"\"\n Rotates a 2D square matrix 90 degrees clockwise.\n\n The rotation should be performed in-place if possible (or effectively so by returning a new matrix).\n The input matrix is guaranteed to be square (N x N) and non-empty.\n\n For example:\n [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\n becomes\n [[7, 4, 1],\n [8, 5, 2],\n [9, 6, 3]]\n\n Args:\n matrix: A list of lists representing a square matrix of integers.\n\n Returns:\n A new list of lists representing the rotated matrix.\n \"\"\"", "solution": "def rotate_matrix_90_clockwise(matrix):\n n = len(matrix)\n if n == 0:\n return []\n\n # Transpose the matrix\n transposed = [[0] * n for _ in range(n)]\n for i in range(n):\n for j in range(n):\n transposed[j][i] = matrix[i][j]\n\n # Reverse each row of the transposed matrix\n rotated = []\n for row in transposed:\n rotated.append(row[::-1])\n \n return rotated", "tests": ["assert rotate_matrix_90_clockwise([[1]]) == [[1]]", "assert rotate_matrix_90_clockwise([[1, 2], [3, 4]]) == [[3, 1], [4, 2]]", "assert rotate_matrix_90_clockwise([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "assert rotate_matrix_90_clockwise([[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]]) == [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]]", "assert rotate_matrix_90_clockwise([[10, 20, 30, 40, 50], [1, 2, 3, 4, 5], [11, 12, 13, 14, 15], [21, 22, 23, 24, 25], [31, 32, 33, 34, 35]]) == [[31, 21, 11, 1, 10], [32, 22, 12, 2, 20], [33, 23, 13, 3, 30], [34, 24, 14, 4, 40], [35, 25, 15, 5, 50]]"]} {"name": "rotate_matrix_clockwise_127", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_clockwise(matrix):\n \"\"\"\n Rotates a 2D square matrix 90 degrees clockwise.\n\n The matrix is represented as a list of lists. The input matrix is guaranteed\n to be square (number of rows equals number of columns) and non-empty.\n\n For example:\n rotate_matrix_clockwise([[1, 2],\n [3, 4]])\n should return [[3, 1],\n [4, 2]]\n\n rotate_matrix_clockwise([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])\n should return [[7, 4, 1],\n [8, 5, 2],\n [9, 6, 3]]\n \"\"\"", "solution": "def rotate_matrix_clockwise(matrix):\n n = len(matrix)\n if n == 0:\n return []\n\n # Create a new matrix for the rotated result\n rotated_matrix = [[0 for _ in range(n)] for _ in range(n)]\n\n for r in range(n):\n for c in range(n):\n # The element at (r, c) in the original matrix\n # moves to (c, n - 1 - r) in the rotated matrix.\n rotated_matrix[c][n - 1 - r] = matrix[r][c]\n\n return rotated_matrix", "tests": ["assert rotate_matrix_clockwise([[1]]) == [[1]]", "assert rotate_matrix_clockwise([[1, 2], [3, 4]]) == [[3, 1], [4, 2]]", "assert rotate_matrix_clockwise([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "assert rotate_matrix_clockwise([[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120], [130, 140, 150, 160]]) == [[130, 90, 50, 10], [140, 100, 60, 20], [150, 110, 70, 30], [160, 120, 80, 40]]", "assert rotate_matrix_clockwise([['a', 'b'], ['c', 'd']]) == [['c', 'a'], ['d', 'b']]"]} {"name": "rotate_matrix_90_degrees_clockwise", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_90_degrees_clockwise(matrix):\n \"\"\"\n Rotates a given square matrix 90 degrees clockwise in-place.\n The function modifies the input matrix directly and does not return a new one.\n\n For example:\n If matrix = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n ]\n After rotation, matrix should become [\n [7, 4, 1],\n [8, 5, 2],\n [9, 6, 3]\n ]\n\n The matrix is guaranteed to be square (rows == cols) and non-empty.\n Elements can be any comparable type.\n \"\"\"\n", "solution": "def rotate_matrix_90_degrees_clockwise(matrix):\n n = len(matrix)\n if n == 0 or n == 1:\n return\n\n # Transpose the matrix\n for i in range(n):\n for j in range(i, n):\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n\n # Reverse each row\n for i in range(n):\n matrix[i].reverse()\n", "tests": ["matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; rotate_matrix_90_degrees_clockwise(matrix1); assert matrix1 == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "matrix2 = [[1]]; rotate_matrix_90_degrees_clockwise(matrix2); assert matrix2 == [[1]]", "matrix3 = [[1, 2], [3, 4]]; rotate_matrix_90_degrees_clockwise(matrix3); assert matrix3 == [[3, 1], [4, 2]]", "matrix4 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]; rotate_matrix_90_degrees_clockwise(matrix4); assert matrix4 == [[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]]", "matrix5 = [[-1, 0], [1, 2]]; rotate_matrix_90_degrees_clockwise(matrix5); assert matrix5 == [[1, -1], [2, 0]]"]} {"name": "rotate_matrix_90_clockwise_817", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_90_clockwise(matrix):\n \"\"\"\n Given an n x n 2D matrix, rotate it 90 degrees clockwise in-place.\n\n The rotation should be performed directly on the input matrix.\n This means you should modify the original matrix object, not return a new one.\n\n For example:\n matrix = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n ]\n rotate_matrix_90_clockwise(matrix)\n # matrix should become:\n # [\n # [7, 4, 1],\n # [8, 5, 2],\n # [9, 6, 3]\n # ]\n\n Constraints:\n - matrix is a list of lists of integers.\n - 1 <= n <= 100 (matrix.length == matrix[i].length == n)\n - -1000 <= matrix[i][j] <= 1000\n \"\"\"", "solution": "def rotate_matrix_90_clockwise(matrix):\n n = len(matrix)\n\n # Transpose the matrix\n for i in range(n):\n for j in range(i, n):\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n\n # Reverse each row\n for i in range(n):\n matrix[i].reverse()", "tests": ["matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; rotate_matrix_90_clockwise(matrix1); assert matrix1 == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "matrix2 = [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]]; rotate_matrix_90_clockwise(matrix2); assert matrix2 == [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]]", "matrix3 = [[1]]; rotate_matrix_90_clockwise(matrix3); assert matrix3 == [[1]]", "matrix4 = [[1, 2], [3, 4]]; rotate_matrix_90_clockwise(matrix4); assert matrix4 == [[3, 1], [4, 2]]", "matrix5 = [[-1000, 0], [0, 1000]]; rotate_matrix_90_clockwise(matrix5); assert matrix5 == [[0, -1000], [1000, 0]]"]} {"name": "rotate_matrix_90_clockwise_108", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_90_clockwise(matrix):\n \"\"\"\n Rotates a 2D square matrix 90 degrees clockwise in-place.\n\n The matrix is represented as a list of lists. For an N x N matrix,\n the rotation should transform matrix[row][col] to matrix[col][N - 1 - row].\n The function should modify the input matrix directly.\n\n Args:\n matrix (list[list[int]]): The square matrix to rotate.\n Assumed to be non-empty and square.\n\n Returns:\n None: The rotation is performed in-place.\n\n Examples:\n >>> mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n >>> rotate_matrix_90_clockwise(mat)\n >>> mat\n [[7, 4, 1], [8, 5, 2], [9, 6, 3]]\n\n >>> mat2 = [[1]]\n >>> rotate_matrix_90_clockwise(mat2)\n >>> mat2\n [[1]]\n \"\"\"", "solution": "def rotate_matrix_90_clockwise(matrix):\n n = len(matrix)\n if n == 0 or n == 1:\n return\n\n # Transpose the matrix\n for i in range(n):\n for j in range(i, n):\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n\n # Reverse each row\n for i in range(n):\n matrix[i].reverse()", "tests": ["mat1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; rotate_matrix_90_clockwise(mat1); assert mat1 == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "mat2 = [[1]]; rotate_matrix_90_clockwise(mat2); assert mat2 == [[1]]", "mat3 = [[1, 2], [3, 4]]; rotate_matrix_90_clockwise(mat3); assert mat3 == [[3, 1], [4, 2]]", "mat4 = [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]]; rotate_matrix_90_clockwise(mat4); assert mat4 == [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]]", "mat5 = []; rotate_matrix_90_clockwise(mat5); assert mat5 == []", "mat6 = [[10]]; rotate_matrix_90_clockwise(mat6); assert mat6 == [[10]]"]} {"name": "rotate_matrix_90_clockwise_345", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_90_clockwise(matrix):\n \"\"\"\n Rotates a 2D square matrix (list of lists) 90 degrees clockwise in-place.\n\n The matrix is guaranteed to be non-empty and have `n` rows and `n` columns\n (i.e., it's a square matrix). The elements can be any type.\n\n Example:\n If matrix = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n ]\n After rotation, matrix should become:\n [\n [7, 4, 1],\n [8, 5, 2],\n [9, 6, 3]\n ]\n\n This function modifies the input matrix directly and does not return anything.\n \"\"\"", "solution": "def rotate_matrix_90_clockwise(matrix):\n n = len(matrix)\n\n # Transpose the matrix\n for i in range(n):\n for j in range(i, n):\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n\n # Reverse each row\n for i in range(n):\n matrix[i].reverse()", "tests": ["matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; rotate_matrix_90_clockwise(matrix1); assert matrix1 == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "matrix2 = [[1]]; rotate_matrix_90_clockwise(matrix2); assert matrix2 == [[1]]", "matrix3 = [[5, 1], [2, 3]]; rotate_matrix_90_clockwise(matrix3); assert matrix3 == [[2, 5], [3, 1]]", "matrix4 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]; rotate_matrix_90_clockwise(matrix4); assert matrix4 == [[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]]", "matrix5 = [['a', 'b'], ['c', 'd']]; rotate_matrix_90_clockwise(matrix5); assert matrix5 == [['c', 'a'], ['d', 'b']]"]} {"name": "rotate_matrix_90_clockwise_190", "topic": "matrix/grid operations", "prompt": "def rotate_matrix_90_clockwise(matrix):\n \"\"\"\n Rotates a given square matrix 90 degrees clockwise in-place.\n\n The matrix is represented as a list of lists. The input matrix is guaranteed\n to be square (number of rows equals number of columns) and non-empty.\n The rotation should be performed without creating a new matrix to store\n the result (i.e., modify the input matrix directly).\n\n For example:\n If matrix = [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\n After rotation, matrix should become:\n [[7, 4, 1],\n [8, 5, 2],\n [9, 6, 3]]\n\n Args:\n matrix: A list of lists representing the square matrix.\n The matrix will be modified directly.\n \"\"\"", "solution": "def rotate_matrix_90_clockwise(matrix):\n n = len(matrix)\n if n == 0:\n return\n\n # Transpose the matrix\n for i in range(n):\n for j in range(i + 1, n):\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n\n # Reverse each row\n for i in range(n):\n matrix[i].reverse()", "tests": ["matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; rotate_matrix_90_clockwise(matrix1); assert matrix1 == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]", "matrix2 = [[1]]; rotate_matrix_90_clockwise(matrix2); assert matrix2 == [[1]]", "matrix3 = [[1, 2], [3, 4]]; rotate_matrix_90_clockwise(matrix3); assert matrix3 == [[3, 1], [4, 2]]", "matrix4 = [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]]; rotate_matrix_90_clockwise(matrix4); assert matrix4 == [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]]", "matrix5 = []; rotate_matrix_90_clockwise(matrix5); assert matrix5 == []", "matrix6 = [[10, 20, 30, 40, 50], [1, 2, 3, 4, 5], [11, 12, 13, 14, 15], [21, 22, 23, 24, 25], [31, 32, 33, 34, 35]]; rotate_matrix_90_clockwise(matrix6); assert matrix6 == [[31, 21, 11, 1, 10], [32, 22, 12, 2, 20], [33, 23, 13, 3, 30], [34, 24, 14, 4, 40], [35, 25, 15, 5, 50]]"]} {"name": "merge_overlapping_intervals", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals):\n \"\"\"\n Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.\n\n Each interval is represented as a list or tuple of two integers: [start, end].\n The intervals are inclusive at both ends. For example, [1, 5] includes 1, 2, 3, 4, 5.\n\n The input list of intervals is not guaranteed to be sorted.\n\n Args:\n intervals: A list of intervals, where each interval is [start, end].\n\n Returns:\n A new list of merged, non-overlapping intervals, sorted by their start times.\n\n Examples:\n >>> merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]])\n [[1, 6], [8, 10], [15, 18]]\n >>> merge_overlapping_intervals([[1, 4], [4, 5]])\n [[1, 5]]\n >>> merge_overlapping_intervals([[1, 4], [0, 4]])\n [[0, 4]]\n >>> merge_overlapping_intervals([[1, 4], [0, 0]])\n [[0, 0], [1, 4]]\n >>> merge_overlapping_intervals([])\n []\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals):\n if not intervals:\n return []\n\n # Sort intervals by their start times\n intervals.sort(key=lambda x: x[0])\n\n merged = []\n for interval in intervals:\n # If the merged list is empty or the current interval does not overlap\n # with the last merged interval, simply add it.\n if not merged or interval[0] > merged[-1][1]:\n merged.append(interval)\n # Otherwise, there is an overlap, so merge the current and previous\n # intervals by updating the end of the last merged interval.\n else:\n merged[-1][1] = max(merged[-1][1], interval[1])\n\n return merged", "tests": ["assert merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]", "assert merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]", "assert merge_overlapping_intervals([[1, 4], [0, 4]]) == [[0, 4]]", "assert merge_overlapping_intervals([[1, 4], [0, 0]]) == [[0, 0], [1, 4]]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([[1, 5], [2, 3]]) == [[1, 5]]", "assert merge_overlapping_intervals([[6, 8], [1, 9], [2, 4], [4, 7]]) == [[1, 9]]"]} {"name": "merge_overlapping_intervals_782", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:\n \"\"\"\n Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.\n\n Each interval is represented as a tuple (start, end), where start <= end.\n The input list of intervals is not necessarily sorted.\n\n For example:\n merge_overlapping_intervals([(1, 3), (2, 6), (8, 10), (15, 18)]) == [(1, 6), (8, 10), (15, 18)]\n merge_overlapping_intervals([(1, 4), (4, 5)]) == [(1, 5)]\n merge_overlapping_intervals([(1, 5), (2, 3)]) == [(1, 5)]\n merge_overlapping_intervals([]) == []\n merge_overlapping_intervals([(1, 1)]) == [(1, 1)]\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:\n if not intervals:\n return []\n\n # Sort intervals based on their start times\n intervals.sort(key=lambda x: x[0])\n\n merged = []\n for current_start, current_end in intervals:\n if not merged or current_start > merged[-1][1]:\n # If the merged list is empty or the current interval does not overlap\n # with the last merged interval, add it as a new interval.\n merged.append((current_start, current_end))\n else:\n # Otherwise, there is an overlap, so merge the current interval\n # with the last merged interval by extending its end time.\n prev_start, prev_end = merged[-1]\n merged[-1] = (prev_start, max(prev_end, current_end))\n\n return merged", "tests": ["assert merge_overlapping_intervals([(1, 3), (2, 6), (8, 10), (15, 18)]) == [(1, 6), (8, 10), (15, 18)]", "assert merge_overlapping_intervals([(1, 4), (4, 5)]) == [(1, 5)]", "assert merge_overlapping_intervals([(1, 5), (2, 3)]) == [(1, 5)]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([(1, 1)]) == [(1, 1)]", "assert merge_overlapping_intervals([(6, 8), (1, 9), (2, 4), (4, 7)]) == [(1, 9)]", "assert merge_overlapping_intervals([(1, 2), (3, 4), (5, 6)]) == [(1, 2), (3, 4), (5, 6)]"]} {"name": "merge_overlapping_intervals_577", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals):\n \"\"\"\n Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.\n\n Each interval is represented as a list or tuple of two integers: [start, end].\n The intervals are assumed to be sorted by their start times. If not sorted, the function\n should sort them first to ensure correct merging.\n\n For example:\n merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]\n merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]\n merge_overlapping_intervals([[1, 4], [0, 4]]) == [[0, 4]]\n merge_overlapping_intervals([[6, 8], [1, 9], [2, 4], [4, 7]]) == [[1, 9]]\n\n Args:\n intervals: A list of intervals, where each interval is [start, end].\n Starts and ends are integers.\n\n Returns:\n A new list of merged, non-overlapping intervals, sorted by their start times.\n Returns an empty list if the input is empty.\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals):\n if not intervals:\n return []\n\n # Sort intervals by their start times. If start times are equal, sort by end times.\n intervals.sort(key=lambda x: (x[0], x[1]))\n\n merged = []\n current_start, current_end = intervals[0][0], intervals[0][1]\n\n for i in range(1, len(intervals)):\n next_start, next_end = intervals[i][0], intervals[i][1]\n\n if next_start <= current_end: # Overlap or touch\n current_end = max(current_end, next_end)\n else: # No overlap, add current merged and start a new one\n merged.append([current_start, current_end])\n current_start, current_end = next_start, next_end\n\n # Add the last merged interval\n merged.append([current_start, current_end])\n\n return merged", "tests": ["assert merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]", "assert merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]", "assert merge_overlapping_intervals([[1, 4], [0, 4]]) == [[0, 4]]", "assert merge_overlapping_intervals([[6, 8], [1, 9], [2, 4], [4, 7]]) == [[1, 9]]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([[1, 5]]) == [[1, 5]]", "assert merge_overlapping_intervals([[1,2], [3,4], [5,6]]) == [[1,2], [3,4], [5,6]]", "assert merge_overlapping_intervals([[1, 10], [2, 3], [4, 5], [6, 7]]) == [[1, 10]]"]} {"name": "merge_overlapping_intervals_216", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals):\n \"\"\"\n Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.\n\n Each interval is represented as a list or tuple of two integers: [start, end].\n The intervals are inclusive at both ends. For example, [1, 3] represents the numbers 1, 2, and 3.\n\n The input list of intervals is not necessarily sorted.\n\n Args:\n intervals: A list of intervals, e.g., [[1, 4], [2, 5], [7, 9]].\n\n Returns:\n A new list of merged, non-overlapping intervals, sorted by their start times.\n e.g., [[1, 5], [7, 9]] for the example input.\n If the input is empty, an empty list should be returned.\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals):\n if not intervals:\n return []\n\n # Sort intervals by their start times\n intervals.sort(key=lambda x: x[0])\n\n merged = []\n for current_start, current_end in intervals:\n if not merged or current_start > merged[-1][1]:\n # If the merged list is empty or the current interval does not overlap\n # with the last merged interval, add it directly.\n merged.append([current_start, current_end])\n else:\n # Otherwise, there is an overlap, merge by updating the end of the last interval.\n merged[-1][1] = max(merged[-1][1], current_end)\n\n return merged", "tests": ["assert merge_overlapping_intervals([[1, 4], [2, 5], [7, 9]]) == [[1, 5], [7, 9]]", "assert merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]", "assert merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]", "assert merge_overlapping_intervals([[1, 4], [0, 4]]) == [[0, 4]]", "assert merge_overlapping_intervals([[1, 4], [0, 0]]) == [[0, 0], [1, 4]]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([[1, 10], [2, 3], [4, 5], [6, 7]]) == [[1, 10]]", "assert merge_overlapping_intervals([[10, 12], [1, 3], [5, 8], [2, 6]]) == [[1, 8], [10, 12]]"]} {"name": "merge_overlapping_intervals_984", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals):\n \"\"\"\n Given a list of intervals, merge all overlapping intervals and return a new list\n of non-overlapping intervals that cover all intervals in the input.\n\n Each interval is represented as a list or tuple of two integers: [start, end].\n The start of an interval will always be less than or equal to its end.\n\n For example:\n merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]])\n should return [[1, 6], [8, 10], [15, 18]]\n\n merge_overlapping_intervals([[1, 4], [4, 5]])\n should return [[1, 5]]\n\n merge_overlapping_intervals([[1, 4], [0, 4]])\n should return [[0, 4]]\n\n merge_overlapping_intervals([[1, 4], [0, 0]])\n should return [[0, 0], [1, 4]]\n\n Args:\n intervals: A list of intervals, where each interval is [start, end].\n\n Returns:\n A new list of merged, non-overlapping intervals, sorted by start time.\n If the input list is empty, return an empty list.\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals):\n if not intervals:\n return []\n\n # Sort intervals by their start time\n intervals.sort(key=lambda x: x[0])\n\n merged = []\n for current_start, current_end in intervals:\n if not merged or current_start > merged[-1][1]:\n # If merged is empty or current interval does not overlap with the last merged interval\n merged.append([current_start, current_end])\n else:\n # There is an overlap, merge with the last interval\n merged[-1][1] = max(merged[-1][1], current_end)\n\n return merged", "tests": ["assert merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]", "assert merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]", "assert merge_overlapping_intervals([[1, 4], [0, 4]]) == [[0, 4]]", "assert merge_overlapping_intervals([[1, 4], [0, 0]]) == [[0, 0], [1, 4]]", "assert merge_overlapping_intervals([[1, 4], [0, 1]]) == [[0, 4]]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([[1, 5]]) == [[1, 5]]", "assert merge_overlapping_intervals([[1, 2], [3, 4], [5, 6]]) == [[1, 2], [3, 4], [5, 6]]", "assert merge_overlapping_intervals([[1, 10], [2, 3], [4, 5]]) == [[1, 10]]", "assert merge_overlapping_intervals([[2, 3], [4, 5], [1, 10]]) == [[1, 10]]"]} {"name": "merge_overlapping_intervals_499", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals):\n \"\"\"\n Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.\n\n Each interval is represented as a list or tuple of two integers: [start, end].\n The intervals are assumed to be sorted by their start times. If not sorted, the function\n should sort them first.\n\n For example:\n merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]\n merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]\n merge_overlapping_intervals([]) == []\n merge_overlapping_intervals([[1, 4]]) == [[1, 4]]\n merge_overlapping_intervals([[1, 4], [0, 4]]) == [[0, 4]]\n\n Args:\n intervals: A list of intervals, where each interval is [start, end].\n\n Returns:\n A new list of merged, non-overlapping intervals, sorted by start time.\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals):\n if not intervals:\n return []\n\n # Sort intervals by their start times\n sorted_intervals = sorted(intervals, key=lambda x: x[0])\n\n merged = []\n for current_start, current_end in sorted_intervals:\n if not merged or current_start > merged[-1][1]:\n # If the merged list is empty, or the current interval does not overlap\n # with the last merged interval, add it as a new interval.\n merged.append([current_start, current_end])\n else:\n # Otherwise, there is an overlap, so merge the current interval\n # with the last merged interval by extending its end.\n merged[-1][1] = max(merged[-1][1], current_end)\n\n return merged", "tests": ["assert merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]", "assert merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([[1, 4]]) == [[1, 4]]", "assert merge_overlapping_intervals([[1, 4], [0, 4]]) == [[0, 4]]", "assert merge_overlapping_intervals([[6, 8], [1, 9], [2, 4], [4, 7]]) == [[1, 9]]"]} {"name": "merge_overlapping_intervals_587", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals):\n \"\"\"\n Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.\n\n Each interval is represented as a list or tuple of two integers: [start, end].\n The intervals are inclusive at both start and end.\n\n For example, [[1, 3], [2, 6], [8, 10], [15, 18]] should merge to [[1, 6], [8, 10], [15, 18]].\n\n Args:\n intervals: A list of intervals, where each interval is [start, end].\n Assumes start <= end for all intervals.\n\n Returns:\n A new list of merged, non-overlapping intervals, sorted by their start times.\n Returns an empty list if the input list is empty.\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals):\n if not intervals:\n return []\n\n # Sort intervals by their start times\n intervals.sort(key=lambda x: x[0])\n\n merged = []\n current_start, current_end = intervals[0]\n\n for i in range(1, len(intervals)):\n next_start, next_end = intervals[i]\n\n if next_start <= current_end: # Overlap or touch\n current_end = max(current_end, next_end)\n else: # No overlap, add current merged interval and start a new one\n merged.append([current_start, current_end])\n current_start, current_end = next_start, next_end\n\n # Add the last merged interval\n merged.append([current_start, current_end])\n return merged", "tests": ["assert merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]", "assert merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]", "assert merge_overlapping_intervals([[1, 4], [0, 4]]) == [[0, 4]]", "assert merge_overlapping_intervals([[1, 4], [0, 1]]) == [[0, 4]]", "assert merge_overlapping_intervals([[1, 2], [3, 4], [5, 6]]) == [[1, 2], [3, 4], [5, 6]]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([[1, 5], [1, 5], [1, 5]]) == [[1, 5]]", "assert merge_overlapping_intervals([[0, 10], [1, 5], [2, 8]]) == [[0, 10]]"]} {"name": "merge_overlapping_intervals_205", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals):\n \"\"\"\n Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.\n\n Each interval is represented as a list or tuple of two integers: [start, end].\n The intervals are assumed to be sorted by their start times. If not, the function\n will sort them internally. The end time is inclusive.\n\n For example, [[1, 3], [2, 6], [8, 10], [15, 18]] should merge to\n [[1, 6], [8, 10], [15, 18]].\n\n Args:\n intervals: A list of intervals, where each interval is [start, end].\n\n Returns:\n A new list of merged, non-overlapping intervals, sorted by start time.\n Returns an empty list if the input is empty.\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals):\n if not intervals:\n return []\n\n # Sort intervals by their start time. This is crucial for the merging logic.\n # The problem statement assumes they are sorted, but it's safer to ensure.\n sorted_intervals = sorted(intervals, key=lambda x: x[0])\n\n merged = []\n current_start, current_end = sorted_intervals[0]\n\n for i in range(1, len(sorted_intervals)):\n next_start, next_end = sorted_intervals[i]\n\n # If the current interval overlaps with the next one\n # (i.e., current_end is greater than or equal to next_start)\n if current_end >= next_start:\n # Extend the current interval's end to the maximum of current_end and next_end\n current_end = max(current_end, next_end)\n else:\n # No overlap, so add the current merged interval to the result\n merged.append([current_start, current_end])\n # Start a new merged interval with the next_start and next_end\n current_start, current_end = next_start, next_end\n\n # Add the last merged interval to the result\n merged.append([current_start, current_end])\n\n return merged", "tests": ["assert merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]", "assert merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]", "assert merge_overlapping_intervals([[1, 4], [0, 4]]) == [[0, 4]]", "assert merge_overlapping_intervals([[6, 8], [1, 9], [2, 4], [4, 7]]) == [[1, 9]]", "assert merge_overlapping_intervals([[1, 2], [3, 4], [5, 6]]) == [[1, 2], [3, 4], [5, 6]]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([[1, 10]]) == [[1, 10]]"]} {"name": "merge_overlapping_intervals_975", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:\n \"\"\"\n Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.\n\n Each interval is represented as a tuple (start, end), where start <= end.\n The input list is not necessarily sorted.\n\n For example:\n merge_overlapping_intervals([(1, 3), (2, 6), (8, 10), (15, 18)]) == [(1, 6), (8, 10), (15, 18)]\n merge_overlapping_intervals([(1, 4), (4, 5)]) == [(1, 5)]\n merge_overlapping_intervals([(6, 8), (1, 9), (2, 4), (4, 7)]) == [(1, 9)]\n merge_overlapping_intervals([]) == []\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:\n if not intervals:\n return []\n\n # Sort intervals by their start times\n intervals.sort()\n\n merged = []\n current_start, current_end = intervals[0]\n\n for i in range(1, len(intervals)):\n next_start, next_end = intervals[i]\n\n # If the current interval overlaps with the next one\n if next_start <= current_end:\n current_end = max(current_end, next_end)\n else:\n # No overlap, add the current merged interval and start a new one\n merged.append((current_start, current_end))\n current_start, current_end = next_start, next_end\n\n # Add the last merged interval\n merged.append((current_start, current_end))\n return merged", "tests": ["assert merge_overlapping_intervals([(1, 3), (2, 6), (8, 10), (15, 18)]) == [(1, 6), (8, 10), (15, 18)]", "assert merge_overlapping_intervals([(1, 4), (4, 5)]) == [(1, 5)]", "assert merge_overlapping_intervals([(6, 8), (1, 9), (2, 4), (4, 7)]) == [(1, 9)]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([(1, 2), (3, 4), (5, 6)]) == [(1, 2), (3, 4), (5, 6)]", "assert merge_overlapping_intervals([(1, 10), (2, 3), (4, 5), (6, 7)]) == [(1, 10)]"]} {"name": "merge_overlapping_intervals_238", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals):\n \"\"\"\n Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.\n\n Each interval is represented as a list of two integers: [start, end].\n The intervals are assumed to be sorted by their start times. If not, the function\n should sort them first.\n\n For example:\n merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]\n merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]\n merge_overlapping_intervals([[6, 8], [1, 9], [2, 4], [4, 7]]) == [[1, 9]]\n\n Args:\n intervals: A list of intervals, where each interval is [start, end].\n\n Returns:\n A new list of non-overlapping intervals, sorted by their start times.\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals):\n if not intervals:\n return []\n\n # Sort intervals by their start times. If start times are equal, sort by end times.\n intervals.sort(key=lambda x: (x[0], x[1]))\n\n merged = []\n current_start, current_end = intervals[0]\n\n for i in range(1, len(intervals)):\n next_start, next_end = intervals[i]\n\n if next_start <= current_end: # Overlap or touch\n current_end = max(current_end, next_end)\n else: # No overlap\n merged.append([current_start, current_end])\n current_start, current_end = next_start, next_end\n\n # Add the last processed interval\n merged.append([current_start, current_end])\n\n return merged", "tests": ["assert merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]", "assert merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]", "assert merge_overlapping_intervals([[6, 8], [1, 9], [2, 4], [4, 7]]) == [[1, 9]]", "assert merge_overlapping_intervals([[1, 2], [3, 4], [5, 6]]) == [[1, 2], [3, 4], [5, 6]]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([[1, 10]]) == [[1, 10]]", "assert merge_overlapping_intervals([[1, 5], [2, 4]]) == [[1, 5]]"]} {"name": "merge_overlapping_intervals_345", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals):\n \"\"\"\n Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.\n\n Each interval is represented as a list or tuple of two integers: [start, end].\n The intervals are inclusive at both ends.\n\n Args:\n intervals: A list of intervals, e.g., [[1, 3], [2, 6], [8, 10], [15, 18]].\n\n Returns:\n A new list of merged, non-overlapping intervals, sorted by start time.\n For example, [[1, 3], [2, 6], [8, 10], [15, 18]] should become [[1, 6], [8, 10], [15, 18]].\n If the input list is empty, an empty list should be returned.\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals):\n if not intervals:\n return []\n\n # Sort intervals by their start time\n intervals.sort(key=lambda x: x[0])\n\n merged = []\n for current_start, current_end in intervals:\n if not merged or current_start > merged[-1][1]:\n # If the merged list is empty or the current interval does not overlap\n # with the last merged interval, add it directly.\n merged.append([current_start, current_end])\n else:\n # Otherwise, there is an overlap, so merge by extending the end\n # of the last merged interval.\n merged[-1][1] = max(merged[-1][1], current_end)\n\n return merged", "tests": ["assert merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]", "assert merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]", "assert merge_overlapping_intervals([[6, 8], [1, 9], [2, 4], [4, 7]]) == [[1, 9]]", "assert merge_overlapping_intervals([[1, 2], [3, 4], [5, 6]]) == [[1, 2], [3, 4], [5, 6]]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([[1, 10]]) == [[1, 10]]", "assert merge_overlapping_intervals([[1, 5], [0, 6]]) == [[0, 6]]"]} {"name": "merge_overlapping_intervals_367", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals):\n \"\"\"\n Merges a list of possibly overlapping intervals into a list of non-overlapping, sorted intervals.\n\n Each interval is represented as a list or tuple of two integers: [start, end].\n The start of an interval is always less than or equal to its end.\n\n For example:\n merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]\n merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]\n merge_overlapping_intervals([[1, 4], [0, 4]]) == [[0, 4]]\n merge_overlapping_intervals([[1, 4], [0, 0]]) == [[0, 0], [1, 4]]\n\n Args:\n intervals: A list of intervals, where each interval is [start, end].\n\n Returns:\n A new list of merged, non-overlapping intervals, sorted by their start times.\n Returns an empty list if the input list is empty.\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals):\n if not intervals:\n return []\n\n # Sort the intervals by their start times\n intervals.sort(key=lambda x: x[0])\n\n merged = []\n for interval in intervals:\n # If the merged list is empty or the current interval does not overlap\n # with the last merged interval, add it directly.\n if not merged or interval[0] > merged[-1][1]:\n merged.append(interval)\n else:\n # Otherwise, there is an overlap, so merge the current and previous\n # intervals by extending the end of the last merged interval.\n merged[-1][1] = max(merged[-1][1], interval[1])\n return merged", "tests": ["assert merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]", "assert merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]", "assert merge_overlapping_intervals([[1, 4], [0, 4]]) == [[0, 4]]", "assert merge_overlapping_intervals([[1, 4], [0, 0]]) == [[0, 0], [1, 4]]", "assert merge_overlapping_intervals([[1, 2], [3, 4], [5, 6]]) == [[1, 2], [3, 4], [5, 6]]", "assert merge_overlapping_intervals([[1, 10], [2, 3], [4, 5], [6, 7]]) == [[1, 10]]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([[7, 8]]) == [[7, 8]]"]} {"name": "merge_overlapping_intervals_314", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals):\n \"\"\"\n Merges a list of possibly overlapping intervals into a list of non-overlapping, sorted intervals.\n\n Each interval is represented as a list or tuple of two integers: [start, end].\n The end point is inclusive.\n\n For example, [[1, 3], [2, 6], [8, 10], [15, 18]] should become [[1, 6], [8, 10], [15, 18]].\n An empty list of intervals should return an empty list.\n Intervals may not be initially sorted.\n\n Args:\n intervals: A list of intervals, where each interval is [start, end].\n\n Returns:\n A new list of merged, non-overlapping intervals, sorted by their start times.\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals):\n if not intervals:\n return []\n\n # Sort intervals by their start times\n intervals.sort(key=lambda x: x[0])\n\n merged = []\n for interval in intervals:\n # If the merged list is empty or the current interval does not overlap with the last merged interval\n if not merged or interval[0] > merged[-1][1]:\n merged.append(interval)\n else:\n # There is an overlap, so merge the current and previous intervals\n merged[-1][1] = max(merged[-1][1], interval[1])\n \n return merged", "tests": ["assert merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]", "assert merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]", "assert merge_overlapping_intervals([[1, 4], [0, 4]]) == [[0, 4]]", "assert merge_overlapping_intervals([[6, 8], [1, 9], [2, 4], [4, 7]]) == [[1, 9]]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([[1, 2], [3, 4], [5, 6]]) == [[1, 2], [3, 4], [5, 6]]", "assert merge_overlapping_intervals([[1, 10], [2, 3], [4, 5], [6, 7]]) == [[1, 10]]"]} {"name": "merge_overlapping_intervals_890", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals):\n \"\"\"\n Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.\n\n Each interval is represented as a list or tuple of two integers: [start, end].\n The intervals are assumed to be sorted by their start times. If not sorted, the function\n should sort them first.\n\n For example:\n merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]\n merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]\n merge_overlapping_intervals([[1, 4], [0, 4]]) == [[0, 4]]\n merge_overlapping_intervals([[0, 0], [1, 2]]) == [[0, 0], [1, 2]]\n\n Args:\n intervals: A list of intervals, where each interval is [start, end].\n\n Returns:\n A new list of merged, non-overlapping intervals, sorted by start time.\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals):\n if not intervals:\n return []\n\n # Sort the intervals by their start times\n intervals.sort(key=lambda x: x[0])\n\n merged = []\n current_start, current_end = intervals[0]\n\n for i in range(1, len(intervals)):\n next_start, next_end = intervals[i]\n\n if next_start <= current_end: # Overlap or touch\n current_end = max(current_end, next_end)\n else: # No overlap\n merged.append([current_start, current_end])\n current_start, current_end = next_start, next_end\n\n merged.append([current_start, current_end]) # Add the last merged interval\n return merged", "tests": ["assert merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]", "assert merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]", "assert merge_overlapping_intervals([[1, 4], [0, 4]]) == [[0, 4]]", "assert merge_overlapping_intervals([[0, 0], [1, 2]]) == [[0, 0], [1, 2]]", "assert merge_overlapping_intervals([[1, 2], [3, 4], [5, 6]]) == [[1, 2], [3, 4], [5, 6]]", "assert merge_overlapping_intervals([[1, 10], [2, 3], [4, 5], [6, 7]]) == [[1, 10]]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([[1, 5]]) == [[1, 5]]", "assert merge_overlapping_intervals([[10, 15], [2, 8], [6, 12]]) == [[2, 15]]"]} {"name": "merge_overlapping_intervals_957", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals):\n \"\"\"\n Given a list of intervals, merge all overlapping intervals and return a list of the merged intervals.\n\n An interval is represented as a list or tuple of two integers [start, end].\n For example, [[1, 3], [2, 6], [8, 10], [15, 18]] should become [[1, 6], [8, 10], [15, 18]].\n\n If an interval [a, b] overlaps with [c, d], where a <= b and c <= d,\n they can be merged into [min(a, c), max(b, d)].\n\n The input list of intervals is not necessarily sorted.\n\n Args:\n intervals: A list of lists/tuples, where each inner list/tuple contains two integers [start, end].\n Assume start <= end for all given intervals.\n\n Returns:\n A list of merged intervals, sorted by their start times.\n If the input list is empty, an empty list should be returned.\n\n Examples:\n merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]\n merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]\n merge_overlapping_intervals([[1, 4], [0, 4]]) == [[0, 4]]\n merge_overlapping_intervals([[1, 4], [0, 0]]) == [[0, 0], [1, 4]]\n merge_overlapping_intervals([[1, 4], [0, 1]]) == [[0, 4]]\n merge_overlapping_intervals([]) == []\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals):\n if not intervals:\n return []\n\n # Sort intervals by their start times\n sorted_intervals = sorted(intervals, key=lambda x: x[0])\n\n merged = []\n for interval in sorted_intervals:\n # If the merged list is empty or the current interval does not overlap with the last merged interval\n if not merged or interval[0] > merged[-1][1]:\n merged.append(interval)\n else:\n # There is an overlap, merge the current and last merged intervals\n merged[-1][1] = max(merged[-1][1], interval[1])\n\n return merged", "tests": ["assert merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]", "assert merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]", "assert merge_overlapping_intervals([[1, 4], [0, 4]]) == [[0, 4]]", "assert merge_overlapping_intervals([[1, 4], [0, 0]]) == [[0, 0], [1, 4]]", "assert merge_overlapping_intervals([[1, 4], [0, 1]]) == [[0, 4]]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([[1, 2], [3, 4], [5, 6]]) == [[1, 2], [3, 4], [5, 6]]", "assert merge_overlapping_intervals([[0, 10], [1, 5], [2, 7]]) == [[0, 10]]"]} {"name": "merge_overlapping_intervals_188", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:\n \"\"\"\n Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.\n\n Each interval is represented as a tuple (start, end), where start <= end.\n The input list is not necessarily sorted.\n\n For example:\n merge_overlapping_intervals([(1, 3), (2, 6), (8, 10), (15, 18)]) == [(1, 6), (8, 10), (15, 18)]\n merge_overlapping_intervals([(1, 4), (4, 5)]) == [(1, 5)]\n merge_overlapping_intervals([(6, 8), (1, 9), (2, 4), (4, 7)]) == [(1, 9)]\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:\n if not intervals:\n return []\n\n # Sort intervals by their start times\n intervals.sort(key=lambda x: x[0])\n\n merged = []\n current_start, current_end = intervals[0]\n\n for i in range(1, len(intervals)):\n next_start, next_end = intervals[i]\n\n if next_start <= current_end: # Overlap or touch\n current_end = max(current_end, next_end)\n else: # No overlap\n merged.append((current_start, current_end))\n current_start, current_end = next_start, next_end\n\n merged.append((current_start, current_end)) # Add the last merged interval\n return merged", "tests": ["assert merge_overlapping_intervals([(1, 3), (2, 6), (8, 10), (15, 18)]) == [(1, 6), (8, 10), (15, 18)]", "assert merge_overlapping_intervals([(1, 4), (4, 5)]) == [(1, 5)]", "assert merge_overlapping_intervals([(6, 8), (1, 9), (2, 4), (4, 7)]) == [(1, 9)]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([(1, 5)]) == [(1, 5)]", "assert merge_overlapping_intervals([(1, 2), (3, 4), (5, 6)]) == [(1, 2), (3, 4), (5, 6)]", "assert merge_overlapping_intervals([(1, 10), (2, 3), (4, 5)]) == [(1, 10)]", "assert merge_overlapping_intervals([(7, 9), (1, 3), (2, 4), (5, 6)]) == [(1, 4), (5, 6), (7, 9)]"]} {"name": "merge_overlapping_intervals_265", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals):\n \"\"\"\n Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.\n\n Each interval is represented as a list or tuple of two integers: [start, end].\n The intervals are considered closed, meaning both start and end points are inclusive.\n\n The input list of intervals is NOT guaranteed to be sorted.\n\n Args:\n intervals: A list of intervals, e.g., [[1, 3], [2, 6], [8, 10], [15, 18]].\n\n Returns:\n A new list of merged, non-overlapping intervals, sorted by their start times.\n e.g., [[1, 6], [8, 10], [15, 18]].\n An empty list if the input is empty.\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals):\n if not intervals:\n return []\n\n # Sort intervals by their start times\n intervals.sort(key=lambda x: x[0])\n\n merged = []\n for interval in intervals:\n # If the merged list is empty or the current interval does not overlap\n # with the previous merged interval, add it directly.\n if not merged or interval[0] > merged[-1][1]:\n merged.append(interval)\n else:\n # Otherwise, there is an overlap, merge the current and previous\n # intervals by extending the end of the previous one.\n merged[-1][1] = max(merged[-1][1], interval[1])\n\n return merged", "tests": ["assert merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]", "assert merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]", "assert merge_overlapping_intervals([[1, 4], [0, 4]]) == [[0, 4]]", "assert merge_overlapping_intervals([[1, 4], [0, 0]]) == [[0, 0], [1, 4]]", "assert merge_overlapping_intervals([[6, 8], [1, 9], [2, 4], [4, 7]]) == [[1, 9]]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([[1, 2], [3, 4], [5, 6]]) == [[1, 2], [3, 4], [5, 6]]", "assert merge_overlapping_intervals([[1, 10], [2, 3], [4, 5]]) == [[1, 10]]"]} {"name": "merge_overlapping_intervals_268", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals):\n \"\"\"\n Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.\n\n Each interval is represented as a list or tuple of two integers: [start, end].\n The intervals are inclusive at both ends.\n\n For example, [[1, 3], [2, 6], [8, 10], [15, 18]] should merge to [[1, 6], [8, 10], [15, 18]].\n\n Args:\n intervals: A list of intervals, where each interval is [start, end].\n Assumes start <= end for all intervals.\n\n Returns:\n A new list of merged, non-overlapping intervals, sorted by their start times.\n If the input list is empty, an empty list is returned.\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals):\n if not intervals:\n return []\n\n # Sort intervals by their start times\n intervals.sort(key=lambda x: x[0])\n\n merged = []\n current_start, current_end = intervals[0]\n\n for i in range(1, len(intervals)):\n next_start, next_end = intervals[i]\n\n # If the current interval overlaps with the next one\n if next_start <= current_end:\n # Merge by extending the end of the current interval\n current_end = max(current_end, next_end)\n else:\n # No overlap, add the current merged interval to the result\n merged.append([current_start, current_end])\n # Start a new current interval\n current_start, current_end = next_start, next_end\n\n # Add the last merged interval to the result\n merged.append([current_start, current_end])\n return merged", "tests": ["assert merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]", "assert merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]", "assert merge_overlapping_intervals([[1, 4], [0, 4]]) == [[0, 4]]", "assert merge_overlapping_intervals([[1, 4], [0, 0]]) == [[0, 0], [1, 4]]", "assert merge_overlapping_intervals([[1, 2], [3, 4], [5, 6]]) == [[1, 2], [3, 4], [5, 6]]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([[1, 5]]) == [[1, 5]]", "assert merge_overlapping_intervals([[1, 10], [2, 3], [4, 5], [6, 7], [8, 9]]) == [[1, 10]]"]} {"name": "merge_overlapping_intervals_252", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals):\n \"\"\"\n Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.\n\n Each interval is represented as a list or tuple of two integers: [start, end].\n The intervals are assumed to be sorted by their start times. If not sorted, the\n function should sort them internally. An empty list of intervals should return\n an empty list.\n\n For example:\n merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]\n merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]\n merge_overlapping_intervals([[1, 4], [0, 4]]) == [[0, 4]]\n merge_overlapping_intervals([[1, 4], [0, 1]]) == [[0, 4]]\n\n Args:\n intervals: A list of intervals, where each interval is [start, end].\n\n Returns:\n A new list of merged, non-overlapping intervals.\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals):\n if not intervals:\n return []\n\n # Sort intervals by their start times. This handles cases where input is not sorted.\n # Using list() to ensure we don't modify the original list if it's a mutable type\n # and the caller expects it to be unchanged.\n sorted_intervals = sorted(list(intervals), key=lambda x: x[0])\n\n merged = []\n current_start, current_end = sorted_intervals[0]\n\n for i in range(1, len(sorted_intervals)):\n next_start, next_end = sorted_intervals[i]\n\n # If the current interval overlaps with the next one\n if next_start <= current_end:\n current_end = max(current_end, next_end)\n else:\n # No overlap, add the current merged interval and start a new one\n merged.append([current_start, current_end])\n current_start, current_end = next_start, next_end\n\n # Add the last merged interval\n merged.append([current_start, current_end])\n\n return merged", "tests": ["assert merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]", "assert merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]", "assert merge_overlapping_intervals([[1, 4], [0, 4]]) == [[0, 4]]", "assert merge_overlapping_intervals([[1, 4], [0, 1]]) == [[0, 4]]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([[1, 5], [2, 3], [6, 8], [7, 9]]) == [[1, 5], [6, 9]]", "assert merge_overlapping_intervals([[6, 8], [1, 9], [2, 4], [4, 7]]) == [[1, 9]]"]} {"name": "merge_overlapping_intervals_125", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:\n \"\"\"\n Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.\n\n Each interval is represented as a tuple (start, end), where start <= end.\n The input list is not guaranteed to be sorted.\n\n For example:\n merge_overlapping_intervals([(1, 3), (2, 6), (8, 10), (15, 18)]) == [(1, 6), (8, 10), (15, 18)]\n merge_overlapping_intervals([(1, 4), (4, 5)]) == [(1, 5)]\n merge_overlapping_intervals([(6, 8), (1, 9), (2, 4), (4, 7)]) == [(1, 9)]\n merge_overlapping_intervals([]) == []\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:\n if not intervals:\n return []\n\n # Sort intervals by their start times\n intervals.sort(key=lambda x: x[0])\n\n merged = []\n current_start, current_end = intervals[0]\n\n for i in range(1, len(intervals)):\n next_start, next_end = intervals[i]\n\n if next_start <= current_end: # Overlap or touch\n current_end = max(current_end, next_end)\n else: # No overlap, add current merged interval and start a new one\n merged.append((current_start, current_end))\n current_start, current_end = next_start, next_end\n\n # Add the last merged interval\n merged.append((current_start, current_end))\n return merged", "tests": ["assert merge_overlapping_intervals([(1, 3), (2, 6), (8, 10), (15, 18)]) == [(1, 6), (8, 10), (15, 18)]", "assert merge_overlapping_intervals([(1, 4), (4, 5)]) == [(1, 5)]", "assert merge_overlapping_intervals([(6, 8), (1, 9), (2, 4), (4, 7)]) == [(1, 9)]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([(1, 2), (3, 4), (5, 6)]) == [(1, 2), (3, 4), (5, 6)]", "assert merge_overlapping_intervals([(1, 10), (2, 3), (4, 5), (6, 7)]) == [(1, 10)]"]} {"name": "merge_overlapping_intervals_151", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals):\n \"\"\"\n Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.\n\n Each interval is represented as a list or tuple of two integers: [start, end].\n The intervals are inclusive at the start and end. For example, [1, 3] includes 1, 2, and 3.\n\n The input list of intervals is not guaranteed to be sorted.\n\n Args:\n intervals: A list of intervals, where each interval is [start, end].\n\n Returns:\n A new list of non-overlapping intervals, sorted by their start times.\n\n Examples:\n merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]\n merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]\n merge_overlapping_intervals([[6, 8], [1, 9], [2, 4], [4, 7]]) == [[1, 9]]\n merge_overlapping_intervals([]) == []\n merge_overlapping_intervals([[1, 5]]) == [[1, 5]]\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals):\n if not intervals:\n return []\n\n # Sort intervals by their start times\n intervals.sort(key=lambda x: x[0])\n\n merged = []\n for current_start, current_end in intervals:\n if not merged or current_start > merged[-1][1]:\n # If the merged list is empty or the current interval does not overlap\n # with the last merged interval, add it as a new interval.\n merged.append([current_start, current_end])\n else:\n # Otherwise, there is an overlap, so merge the current interval\n # with the last one by extending its end if necessary.\n merged[-1][1] = max(merged[-1][1], current_end)\n\n return merged", "tests": ["assert merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]", "assert merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]", "assert merge_overlapping_intervals([[6, 8], [1, 9], [2, 4], [4, 7]]) == [[1, 9]]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([[1, 5]]) == [[1, 5]]", "assert merge_overlapping_intervals([[1, 2], [3, 4], [5, 6]]) == [[1, 2], [3, 4], [5, 6]]", "assert merge_overlapping_intervals([[1, 10], [2, 3], [4, 5], [6, 7]]) == [[1, 10]]"]} {"name": "merge_overlapping_intervals_988", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:\n \"\"\"\n Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.\n\n Each interval is represented as a tuple (start, end), where start <= end.\n The input list is not necessarily sorted.\n\n For example:\n merge_overlapping_intervals([(1, 3), (2, 6), (8, 10), (15, 18)]) == [(1, 6), (8, 10), (15, 18)]\n merge_overlapping_intervals([(1, 4), (4, 5)]) == [(1, 5)]\n merge_overlapping_intervals([(6, 8), (1, 9), (2, 4), (4, 7)]) == [(1, 9)]\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:\n if not intervals:\n return []\n\n intervals.sort(key=lambda x: x[0])\n\n merged = []\n current_start, current_end = intervals[0]\n\n for i in range(1, len(intervals)):\n next_start, next_end = intervals[i]\n\n if next_start <= current_end:\n # Overlap or touch, merge them\n current_end = max(current_end, next_end)\n else:\n # No overlap, add current merged interval and start a new one\n merged.append((current_start, current_end))\n current_start, current_end = next_start, next_end\n\n # Add the last merged interval\n merged.append((current_start, current_end))\n return merged", "tests": ["assert merge_overlapping_intervals([(1, 3), (2, 6), (8, 10), (15, 18)]) == [(1, 6), (8, 10), (15, 18)]", "assert merge_overlapping_intervals([(1, 4), (4, 5)]) == [(1, 5)]", "assert merge_overlapping_intervals([(6, 8), (1, 9), (2, 4), (4, 7)]) == [(1, 9)]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([(1, 2), (3, 4), (5, 6)]) == [(1, 2), (3, 4), (5, 6)]", "assert merge_overlapping_intervals([(1, 10), (2, 3), (4, 5), (6, 7)]) == [(1, 10)]", "assert merge_overlapping_intervals([(5, 7), (1, 3), (2, 4)]) == [(1, 4), (5, 7)]"]} {"name": "merge_overlapping_intervals_338", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals):\n \"\"\"\n Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.\n\n Each interval is represented as a list or tuple of two integers: [start, end].\n The intervals are assumed to be sorted by their start times. If not, the function\n should sort them first.\n\n For example:\n merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]\n merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]\n merge_overlapping_intervals([[6, 8], [1, 9], [2, 4], [4, 7]]) == [[1, 9]] (after sorting)\n\n Args:\n intervals: A list of intervals, where each interval is [start, end].\n\n Returns:\n A new list of merged, non-overlapping intervals, sorted by their start times.\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals):\n if not intervals:\n return []\n\n # Sort intervals by their start times\n intervals.sort(key=lambda x: x[0])\n\n merged = []\n current_start, current_end = intervals[0]\n\n for i in range(1, len(intervals)):\n next_start, next_end = intervals[i]\n\n if next_start <= current_end: # Overlap or touch\n current_end = max(current_end, next_end)\n else: # No overlap, add current merged interval and start a new one\n merged.append([current_start, current_end])\n current_start, current_end = next_start, next_end\n\n # Add the last merged interval\n merged.append([current_start, current_end])\n\n return merged", "tests": ["assert merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]", "assert merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]", "assert merge_overlapping_intervals([[6, 8], [1, 9], [2, 4], [4, 7]]) == [[1, 9]]", "assert merge_overlapping_intervals([[1, 2], [3, 4], [5, 6]]) == [[1, 2], [3, 4], [5, 6]]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([[1, 10], [2, 3], [4, 5]]) == [[1, 10]]", "assert merge_overlapping_intervals([[10, 20], [1, 5]]) == [[1, 5], [10, 20]]"]} {"name": "merge_overlapping_intervals_786", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:\n \"\"\"\n Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.\n\n Each interval is represented as a tuple (start, end), where start <= end.\n The input list is not necessarily sorted.\n\n For example:\n merge_overlapping_intervals([(1, 3), (2, 6), (8, 10), (15, 18)]) == [(1, 6), (8, 10), (15, 18)]\n merge_overlapping_intervals([(1, 4), (4, 5)]) == [(1, 5)]\n merge_overlapping_intervals([(6, 8), (1, 9), (2, 4), (4, 7)]) == [(1, 9)]\n merge_overlapping_intervals([]) == []\n\n Args:\n intervals: A list of tuples, where each tuple (start, end) represents an interval.\n\n Returns:\n A new list of non-overlapping intervals, sorted by their start times.\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:\n if not intervals:\n return []\n\n # Sort the intervals by their start times\n intervals.sort(key=lambda x: x[0])\n\n merged = []\n for current_start, current_end in intervals:\n if not merged or current_start > merged[-1][1]:\n # If the merged list is empty or the current interval does not overlap\n # with the last merged interval, add it as a new interval.\n merged.append((current_start, current_end))\n else:\n # Otherwise, there is an overlap, so merge the current interval\n # with the last one by extending its end if necessary.\n prev_start, prev_end = merged[-1]\n merged[-1] = (prev_start, max(prev_end, current_end))\n return merged", "tests": ["assert merge_overlapping_intervals([(1, 3), (2, 6), (8, 10), (15, 18)]) == [(1, 6), (8, 10), (15, 18)]", "assert merge_overlapping_intervals([(1, 4), (4, 5)]) == [(1, 5)]", "assert merge_overlapping_intervals([(6, 8), (1, 9), (2, 4), (4, 7)]) == [(1, 9)]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([(1, 5), (2, 3)]) == [(1, 5)]", "assert merge_overlapping_intervals([(1, 2), (3, 4), (5, 6)]) == [(1, 2), (3, 4), (5, 6)]"]} {"name": "merge_overlapping_intervals_613", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals):\n \"\"\"\n Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.\n\n Each interval is represented as a list or tuple of two integers: [start, end].\n The intervals are inclusive at the start and end. For example, [1, 3] includes 1, 2, and 3.\n\n The output list should be sorted by the start of each interval.\n\n Args:\n intervals: A list of intervals, e.g., [[1, 3], [2, 6], [8, 10], [15, 18]].\n\n Returns:\n A new list of merged, non-overlapping intervals, sorted by start.\n If the input list is empty, an empty list should be returned.\n\n Examples:\n merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]\n merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]\n merge_overlapping_intervals([[1, 4], [0, 4]]) == [[0, 4]]\n merge_overlapping_intervals([[1, 4], [0, 0]]) == [[0, 0], [1, 4]]\n merge_overlapping_intervals([]) == []\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals):\n if not intervals:\n return []\n\n # Sort the intervals by their start times\n intervals.sort(key=lambda x: x[0])\n\n merged = []\n for current_start, current_end in intervals:\n if not merged or current_start > merged[-1][1]:\n # If the merged list is empty or the current interval does not overlap\n # with the last merged interval, add it as a new interval.\n merged.append([current_start, current_end])\n else:\n # If there is an overlap, merge the current interval with the last one\n # by extending the end of the last merged interval.\n merged[-1][1] = max(merged[-1][1], current_end)\n\n return merged", "tests": ["assert merge_overlapping_intervals([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]", "assert merge_overlapping_intervals([[1, 4], [4, 5]]) == [[1, 5]]", "assert merge_overlapping_intervals([[1, 4], [0, 4]]) == [[0, 4]]", "assert merge_overlapping_intervals([[1, 4], [0, 0]]) == [[0, 0], [1, 4]]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([[1, 2], [3, 4], [5, 6]]) == [[1, 2], [3, 4], [5, 6]]", "assert merge_overlapping_intervals([[1, 5], [2, 3]]) == [[1, 5]]", "assert merge_overlapping_intervals([[10, 20], [1, 5], [3, 7], [25, 30]]) == [[1, 7], [10, 20], [25, 30]]"]} {"name": "merge_overlapping_intervals_888", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals):\n \"\"\"\n Given a list of intervals, merge all overlapping intervals and return a list of the merged intervals.\n\n An interval is a list or tuple of two integers [start, end].\n For example, [1, 3] and [2, 6] overlap, and would merge to [1, 6].\n [1, 4] and [4, 5] are considered overlapping and merge to [1, 5].\n\n The input list of intervals is not necessarily sorted.\n\n Args:\n intervals (list[list[int]]): A list of intervals, where each interval is [start, end].\n\n Returns:\n list[list[int]]: A new list of non-overlapping intervals, merged from the input.\n The output intervals should be sorted by their start times.\n\n Examples:\n merge_overlapping_intervals([[1,3],[2,6],[8,10],[15,18]]) == [[1,6],[8,10],[15,18]]\n merge_overlapping_intervals([[1,4],[4,5]]) == [[1,5]]\n merge_overlapping_intervals([[1,4],[0,4]]) == [[0,4]]\n merge_overlapping_intervals([[1,4],[0,0]]) == [[0,0],[1,4]]\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals):\n if not intervals:\n return []\n\n # Sort intervals by their start times\n intervals.sort(key=lambda x: x[0])\n\n merged = []\n for interval in intervals:\n # If the merged list is empty or the current interval does not overlap\n # with the previous merged interval, append it directly.\n if not merged or interval[0] > merged[-1][1]:\n merged.append(interval)\n else:\n # Otherwise, there is an overlap, so merge the current and previous\n # intervals by updating the end point of the previous merged interval.\n merged[-1][1] = max(merged[-1][1], interval[1])\n\n return merged", "tests": ["assert merge_overlapping_intervals([[1,3],[2,6],[8,10],[15,18]]) == [[1,6],[8,10],[15,18]]", "assert merge_overlapping_intervals([[1,4],[4,5]]) == [[1,5]]", "assert merge_overlapping_intervals([[1,4],[0,4]]) == [[0,4]]", "assert merge_overlapping_intervals([[1,4],[0,0]]) == [[0,0],[1,4]]", "assert merge_overlapping_intervals([[1,4],[0,1]]) == [[0,4]]", "assert merge_overlapping_intervals([[2,3],[4,5],[6,7],[8,9],[1,10]]) == [[1,10]]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([[1,2]]) == [[1,2]]"]} {"name": "merge_overlapping_intervals_488", "topic": "intervals and ranges", "prompt": "def merge_overlapping_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:\n \"\"\"\n Merges a list of possibly overlapping intervals into a list of non-overlapping intervals.\n\n Each interval is represented as a tuple (start, end), where start <= end.\n The input list is not necessarily sorted.\n\n For example:\n merge_overlapping_intervals([(1, 3), (2, 6), (8, 10), (15, 18)]) == [(1, 6), (8, 10), (15, 18)]\n merge_overlapping_intervals([(1, 4), (4, 5)]) == [(1, 5)]\n merge_overlapping_intervals([(6, 8), (1, 9), (2, 4), (4, 7)]) == [(1, 9)]\n \"\"\"", "solution": "def merge_overlapping_intervals(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]:\n if not intervals:\n return []\n\n # Sort intervals by their start points\n sorted_intervals = sorted(intervals, key=lambda x: x[0])\n\n merged = []\n current_start, current_end = sorted_intervals[0]\n\n for i in range(1, len(sorted_intervals)):\n next_start, next_end = sorted_intervals[i]\n\n # If the current interval overlaps with the next, merge them\n if next_start <= current_end:\n current_end = max(current_end, next_end)\n else:\n # No overlap, add the current merged interval and start a new one\n merged.append((current_start, current_end))\n current_start, current_end = next_start, next_end\n\n # Add the last merged interval\n merged.append((current_start, current_end))\n return merged", "tests": ["assert merge_overlapping_intervals([(1, 3), (2, 6), (8, 10), (15, 18)]) == [(1, 6), (8, 10), (15, 18)]", "assert merge_overlapping_intervals([(1, 4), (4, 5)]) == [(1, 5)]", "assert merge_overlapping_intervals([(6, 8), (1, 9), (2, 4), (4, 7)]) == [(1, 9)]", "assert merge_overlapping_intervals([]) == []", "assert merge_overlapping_intervals([(1, 5)]) == [(1, 5)]", "assert merge_overlapping_intervals([(1, 2), (3, 4), (5, 6)]) == [(1, 2), (3, 4), (5, 6)]", "assert merge_overlapping_intervals([(1, 10), (2, 3), (4, 5), (6, 7)]) == [(1, 10)]", "assert merge_overlapping_intervals([(10, 15), (1, 5), (6, 12)]) == [(1, 5), (6, 15)]"]} {"name": "process_queue_with_priority", "topic": "stack/queue logic", "prompt": "def process_queue_with_priority(tasks):\n \"\"\"\n Processes a list of tasks, simulating a queue where tasks with a higher priority (lower integer value)\n are processed before tasks with lower priority. If two tasks have the same priority, they are processed\n in their original order of appearance (FIFO).\n\n Each task is represented as a tuple: (task_id, priority, duration).\n - task_id (str): A unique identifier for the task.\n - priority (int): An integer representing the task's priority. Lower values mean higher priority.\n - duration (int): The processing time required for the task.\n\n The function should return a list of task_ids in the order they were processed.\n\n Example:\n tasks = [\n (\"A\", 2, 5),\n (\"B\", 1, 3),\n (\"C\", 2, 2),\n (\"D\", 3, 4)\n ]\n process_queue_with_priority(tasks) should return ['B', 'A', 'C', 'D']\n (B has priority 1, A and C have priority 2, but A appears before C, D has priority 3)\n \"\"\"", "solution": "import heapq\n\ndef process_queue_with_priority(tasks):\n processed_order = []\n # Use a min-heap to store tasks. Each item in the heap will be:\n # (priority, original_index, task_id, duration)\n # The original_index is crucial for maintaining FIFO order for same-priority tasks.\n priority_queue = []\n\n for i, (task_id, priority, duration) in enumerate(tasks):\n heapq.heappush(priority_queue, (priority, i, task_id, duration))\n\n while priority_queue:\n _, _, task_id, _ = heapq.heappop(priority_queue)\n processed_order.append(task_id)\n\n return processed_order", "tests": ["assert process_queue_with_priority([(\"A\", 2, 5), (\"B\", 1, 3), (\"C\", 2, 2), (\"D\", 3, 4)]) == ['B', 'A', 'C', 'D']", "assert process_queue_with_priority([(\"T1\", 5, 10), (\"T2\", 1, 2), (\"T3\", 5, 3), (\"T4\", 2, 7), (\"T5\", 1, 1)]) == ['T2', 'T5', 'T4', 'T1', 'T3']", "assert process_queue_with_priority([(\"X\", 1, 1), (\"Y\", 1, 1), (\"Z\", 1, 1)]) == ['X', 'Y', 'Z']", "assert process_queue_with_priority([(\"P1\", 10, 1), (\"P2\", 1, 1), (\"P3\", 5, 1), (\"P4\", 1, 1)]) == ['P2', 'P4', 'P3', 'P1']", "assert process_queue_with_priority([]) == []", "assert process_queue_with_priority([(\"S1\", 1, 100)]) == ['S1']"]} {"name": "process_job_queue", "topic": "stack/queue logic", "prompt": "def process_job_queue(jobs, workers):\n \"\"\"\n Simulates processing jobs from a queue by a fixed number of workers. \n Each job has a `start_time` and `duration`.\n Workers become available at different times.\n\n The function should return a list of tuples, where each tuple represents\n (job_index, worker_index, actual_start_time).\n\n The simulation works as follows:\n 1. Initialize `workers` workers, each available at time 0.\n 2. Iterate through `jobs` in the given order (job_index 0 to n-1).\n 3. For each job, find the worker that will become available earliest.\n 4. The job starts at `max(job.start_time, worker_available_time)`.\n 5. Update the selected worker's availability time: \n `new_worker_available_time = actual_start_time + job.duration`.\n 6. Record (job_index, worker_index, actual_start_time).\n\n Args:\n jobs (list of dict): Each dict has keys 'start_time' (int) and 'duration' (int).\n workers (int): The number of available workers (1 or more).\n\n Returns:\n list of tuple: A list of (job_index, worker_index, actual_start_time) tuples.\n The worker_index is 0-based.\n \"\"\"\n", "solution": "import heapq\n\ndef process_job_queue(jobs, workers):\n worker_availability = [(0, i) for i in range(workers)] # (available_time, worker_index)\n heapq.heapify(worker_availability)\n\n results = []\n\n for job_index, job in enumerate(jobs):\n job_start_time = job['start_time']\n job_duration = job['duration']\n\n # Get the earliest available worker\n worker_available_time, worker_id = heapq.heappop(worker_availability)\n\n actual_start_time = max(job_start_time, worker_available_time)\n new_worker_available_time = actual_start_time + job_duration\n\n results.append((job_index, worker_id, actual_start_time))\n\n # Update worker availability and push back to heap\n heapq.heappush(worker_availability, (new_worker_available_time, worker_id))\n\n return results\n", "tests": ["assert process_job_queue([{'start_time': 0, 'duration': 5}, {'start_time': 0, 'duration': 3}], 1) == [(0, 0, 0), (1, 0, 5)]", "assert process_job_queue([{'start_time': 0, 'duration': 5}, {'start_time': 0, 'duration': 3}], 2) == [(0, 0, 0), (1, 1, 0)]", "assert process_job_queue([{'start_time': 0, 'duration': 2}, {'start_time': 1, 'duration': 3}, {'start_time': 3, 'duration': 1}], 1) == [(0, 0, 0), (1, 0, 2), (2, 0, 5)]", "assert process_job_queue([{'start_time': 0, 'duration': 10}, {'start_time': 1, 'duration': 2}, {'start_time': 2, 'duration': 3}, {'start_time': 3, 'duration': 4}], 3) == [(0, 0, 0), (1, 1, 1), (2, 2, 2), (3, 1, 3)]", "assert process_job_queue([{'start_time': 10, 'duration': 5}, {'start_time': 12, 'duration': 3}, {'start_time': 8, 'duration': 2}], 2) == [(0, 0, 10), (1, 1, 12), (2, 0, 15)]", "assert process_job_queue([], 5) == []"]} {"name": "process_job_queue_690", "topic": "stack/queue logic", "prompt": "import collections\n\ndef process_job_queue(jobs_with_priorities):\n \"\"\"\n Processes a list of jobs with associated priorities using a priority queue logic.\n\n Each job is represented as a tuple (job_id, priority), where job_id is a unique\n string and priority is an integer. Higher priority numbers indicate higher priority.\n\n The function should simulate processing these jobs. Jobs are processed in order\n of priority (highest first). If two jobs have the same priority, they are processed\n in the order they appeared in the input list.\n\n The function should return a list of job_ids in the order they were processed.\n\n Args:\n jobs_with_priorities: A list of tuples, e.g., [('A', 3), ('B', 1), ('C', 3), ('D', 2)]\n\n Returns:\n A list of job_ids (strings) in the order they were processed.\n\n Example:\n process_job_queue([('A', 3), ('B', 1), ('C', 3), ('D', 2)]) == ['A', 'C', 'D', 'B']\n (A and C have priority 3, A appears first. Then D has priority 2. Then B has priority 1.)\n \"\"\"\n", "solution": "import collections\n\ndef process_job_queue(jobs_with_priorities):\n \"\"\"\n Processes a list of jobs with associated priorities using a priority queue logic.\n\n Each job is represented as a tuple (job_id, priority), where job_id is a unique\n string and priority is an integer. Higher priority numbers indicate higher priority.\n\n The function should simulate processing these jobs. Jobs are processed in order\n of priority (highest first). If two jobs have the same priority, they are processed\n in the order they appeared in the input list.\n\n The function should return a list of job_ids in the order they were processed.\n\n Args:\n jobs_with_priorities: A list of tuples, e.g., [('A', 3), ('B', 1), ('C', 3), ('D', 2)]\n\n Returns:\n A list of job_ids (strings) in the order they were processed.\n\n Example:\n process_job_queue([('A', 3), ('B', 1), ('C', 3), ('D', 2)]) == ['A', 'C', 'D', 'B']\n (A and C have priority 3, A appears first. Then D has priority 2. Then B has priority 1.)\n \"\"\"\n # We need to maintain original order for tie-breaking, so we'll store\n # (priority, original_index, job_id) and sort based on this.\n # Python's default sort is stable, which helps with tie-breaking for equal priorities.\n # For higher priority to come first, we'll negate the priority.\n # For original index to break ties, we'll use the original index.\n \n indexed_jobs = []\n for i, (job_id, priority) in enumerate(jobs_with_priorities):\n indexed_jobs.append((-priority, i, job_id))\n\n # Sort the jobs. Python's sort is stable, so for equal priorities, \n # the original_index will ensure the correct order.\n indexed_jobs.sort()\n\n processed_job_ids = []\n for _, _, job_id in indexed_jobs:\n processed_job_ids.append(job_id)\n\n return processed_job_ids", "tests": ["assert process_job_queue([('A', 3), ('B', 1), ('C', 3), ('D', 2)]) == ['A', 'C', 'D', 'B']", "assert process_job_queue([('X', 5), ('Y', 5), ('Z', 1)]) == ['X', 'Y', 'Z']", "assert process_job_queue([('P', 10)]) == ['P']", "assert process_job_queue([]) == []", "assert process_job_queue([('J1', 1), ('J2', 1), ('J3', 1), ('J4', 2)]) == ['J4', 'J1', 'J2', 'J3']", "assert process_job_queue([('First', 2), ('Second', 1), ('Third', 3), ('Fourth', 2)]) == ['Third', 'First', 'Fourth', 'Second']"]} {"name": "process_job_queue_829", "topic": "stack/queue logic", "prompt": "import collections\n\ndef process_job_queue(jobs_with_dependencies: list[tuple[str, list[str]]]) -> list[str]:\n \"\"\"\n Processes a list of jobs with dependencies, returning a valid execution order.\n\n Each job is represented as a tuple: (job_name, [list_of_dependencies]).\n A job can only be executed after all its dependencies have been executed.\n\n The function should return a list of job names in an order that satisfies all dependencies.\n If multiple jobs can be executed at the same time, their relative order does not matter.\n If a circular dependency exists (i.e., a job depends on itself directly or indirectly),\n it's impossible to process all jobs. In such cases, return an empty list.\n\n Example:\n jobs_with_dependencies = [\n (\"A\", []),\n (\"B\", [\"A\"]),\n (\"C\", [\"A\"]),\n (\"D\", [\"B\", \"C\"])\n ]\n A valid output would be [\"A\", \"B\", \"C\", \"D\"] or [\"A\", \"C\", \"B\", \"D\"].\n\n Args:\n jobs_with_dependencies: A list of tuples, each representing a job and its dependencies.\n\n Returns:\n A list of job names in a valid execution order, or an empty list if a circular\n dependency is detected.\n \"\"\"", "solution": "import collections\n\ndef process_job_queue(jobs_with_dependencies: list[tuple[str, list[str]]]) -> list[str]:\n \"\"\"\n Processes a list of jobs with dependencies, returning a valid execution order.\n\n Each job is represented as a tuple: (job_name, [list_of_dependencies]).\n A job can only be executed after all its dependencies have been executed.\n\n The function should return a list of job names in an order that satisfies all dependencies.\n If multiple jobs can be executed at the same time, their relative order does not matter.\n If a circular dependency exists (i.e., a job depends on itself directly or indirectly),\n it's impossible to process all jobs. In such cases, return an empty list.\n\n Example:\n jobs_with_dependencies = [\n (\"A\", []),\n (\"B\", [\"A\"]),\n (\"C\", [\"A\"]),\n (\"D\", [\"B\", \"C\"])\n ]\n A valid output would be [\"A\", \"B\", \"C\", \"D\"] or [\"A\", \"C\", \"B\", \"D\"].\n\n Args:\n jobs_with_dependencies: A list of tuples, each representing a job and its dependencies.\n\n Returns:\n A list of job names in a valid execution order, or an empty list if a circular\n dependency is detected.\n \"\"\"\n in_degree = collections.defaultdict(int)\n adj_list = collections.defaultdict(list)\n all_jobs = set()\n\n for job, deps in jobs_with_dependencies:\n all_jobs.add(job)\n for dep in deps:\n all_jobs.add(dep)\n adj_list[dep].append(job)\n in_degree[job] += 1\n\n queue = collections.deque()\n for job in all_jobs:\n if in_degree[job] == 0:\n queue.append(job)\n\n result = []\n while queue:\n current_job = queue.popleft()\n result.append(current_job)\n\n for neighbor in adj_list[current_job]:\n in_degree[neighbor] -= 1\n if in_degree[neighbor] == 0:\n queue.append(neighbor)\n\n if len(result) != len(all_jobs):\n return [] # Circular dependency detected\n return result", "tests": ["assert process_job_queue([(\"A\", []), (\"B\", [\"A\"]), (\"C\", [\"A\"]), (\"D\", [\"B\", \"C\"])]) in ([ \"A\", \"B\", \"C\", \"D\"], [\"A\", \"C\", \"B\", \"D\"] )", "assert process_job_queue([(\"Task1\", []), (\"Task2\", [\"Task1\"]), (\"Task3\", [\"Task2\"])]) == [\"Task1\", \"Task2\", \"Task3\"]", "assert process_job_queue([(\"X\", [\"Y\"]), (\"Y\", [\"X\"])]) == []", "assert process_job_queue([(\"F\", []), (\"E\", [\"F\"]), (\"D\", [\"E\"]), (\"C\", [\"D\"]), (\"B\", [\"C\"]), (\"A\", [\"B\"])]) == [\"F\", \"E\", \"D\", \"C\", \"B\", \"A\"]", "assert process_job_queue([(\"Start\", []), (\"Mid1\", [\"Start\"]), (\"Mid2\", [\"Start\"]), (\"End\", [\"Mid1\", \"Mid2\"])]) in ([\"Start\", \"Mid1\", \"Mid2\", \"End\"], [\"Start\", \"Mid2\", \"Mid1\", \"End\"])", "assert process_job_queue([(\"A\", []), (\"B\", []), (\"C\", []), (\"D\", [\"A\", \"B\"]), (\"E\", [\"B\", \"C\"]), (\"F\", [\"D\", \"E\"])]) in ([\"A\", \"B\", \"C\", \"D\", \"E\", \"F\"], [\"B\", \"A\", \"C\", \"D\", \"E\", \"F\"], [\"A\", \"C\", \"B\", \"D\", \"E\", \"F\"], [\"C\", \"A\", \"B\", \"D\", \"E\", \"F\"], [\"B\", \"C\", \"A\", \"D\", \"E\", \"F\"], [\"C\", \"B\", \"A\", \"D\", \"E\", \"F\"], [\"A\", \"B\", \"C\", \"E\", \"D\", \"F\"], [\"B\", \"A\", \"C\", \"E\", \"D\", \"F\"], [\"A\", \"C\", \"B\", \"E\", \"D\", \"F\"], [\"C\", \"A\", \"B\", \"E\", \"D\", \"F\"], [\"B\", \"C\", \"A\", \"E\", \"D\", \"F\"], [\"C\", \"B\", \"A\", \"E\", \"D\", \"F\"])"]} {"name": "process_job_queue_849", "topic": "stack/queue logic", "prompt": "def process_job_queue(jobs: list[tuple[str, int]], max_workers: int) -> list[tuple[str, int, int]]:\n \"\"\"\n Simulates processing a list of jobs with a limited number of workers.\n\n Jobs are processed in the order they appear in the input list. Each job\n is a tuple (job_id, processing_time).\n\n The simulation works as follows:\n - There are `max_workers` available. Initially, all are free.\n - When a job is started, it occupies a worker for its `processing_time`.\n - Jobs are assigned to the *lowest indexed* available worker.\n - If no workers are available, the job waits until a worker finishes.\n - All workers finish at their scheduled time, allowing new jobs to start.\n - Time advances in discrete units. A worker finishing at time T becomes free\n at time T, meaning a new job can start on it at time T.\n\n The function should return a list of tuples (job_id, start_time, end_time)\n for each job, in the same order as the input `jobs` list.\n\n Args:\n jobs: A list of (job_id, processing_time) tuples.\n `job_id` is a string, `processing_time` is a positive integer.\n max_workers: The maximum number of workers available, a positive integer.\n\n Returns:\n A list of (job_id, start_time, end_time) tuples, ordered by the input jobs.\n `start_time` and `end_time` are integers representing the time units.\n\n Example:\n process_job_queue([\n (\"A\", 2),\n (\"B\", 3),\n (\"C\", 1)\n ], 1)\n # Expected: [(\"A\", 0, 2), (\"B\", 2, 5), (\"C\", 5, 6)]\n\n process_job_queue([\n (\"J1\", 5),\n (\"J2\", 2),\n (\"J3\", 3),\n (\"J4\", 1)\n ], 2)\n # Expected:\n # [('J1', 0, 5), # Worker 0\n # ('J2', 0, 2), # Worker 1\n # ('J3', 2, 5), # Worker 1 (after J2 finishes)\n # ('J4', 5, 6)] # Worker 0 (after J1 finishes, or Worker 1 after J3 - lowest index wins)\n \"\"\"\n pass", "solution": "import heapq\n\ndef process_job_queue(jobs: list[tuple[str, int]], max_workers: int) -> list[tuple[str, int, int]]:\n \"\"\"\n Simulates processing a list of jobs with a limited number of workers.\n\n Jobs are processed in the order they appear in the input list. Each job\n is a tuple (job_id, processing_time).\n\n The simulation works as follows:\n - There are `max_workers` available. Initially, all are free.\n - When a job is started, it occupies a worker for its `processing_time`.\n - Jobs are assigned to the *lowest indexed* available worker.\n - If no workers are available, the job waits until a worker finishes.\n - All workers finish at their scheduled time, allowing new jobs to start.\n - Time advances in discrete units. A worker finishing at time T becomes free\n at time T, meaning a new job can start on it at time T.\n\n The function should return a list of tuples (job_id, start_time, end_time)\n for each job, in the same order as the input `jobs` list.\n\n Args:\n jobs: A list of (job_id, processing_time) tuples.\n `job_id` is a string, `processing_time` is a positive integer.\n max_workers: The maximum number of workers available, a positive integer.\n\n Returns:\n A list of (job_id, start_time, end_time) tuples, ordered by the input jobs.\n `start_time` and `end_time` are integers representing the time units.\n\n Example:\n process_job_queue([\n (\"A\", 2),\n (\"B\", 3),\n (\"C\", 1)\n ], 1)\n # Expected: [(\"A\", 0, 2), (\"B\", 2, 5), (\"C\", 5, 6)]\n\n process_job_queue([\n (\"J1\", 5),\n (\"J2\", 2),\n (\"J3\", 3),\n (\"J4\", 1)\n ], 2)\n # Expected:\n # [('J1', 0, 5), # Worker 0\n # ('J2', 0, 2), # Worker 1\n # ('J3', 2, 5), # Worker 1 (after J2 finishes)\n # ('J4', 5, 6)] # Worker 0 (after J1 finishes, or Worker 1 after J3 - lowest index wins)\n \"\"\"\n # A min-heap to store (finish_time, worker_index) for workers that are busy.\n # We want to retrieve the worker that finishes earliest, and among those,\n # the one with the lowest index.\n worker_finish_times = [(0, i) for i in range(max_workers)] # (earliest_free_time, worker_id)\n heapq.heapify(worker_finish_times)\n\n results = []\n\n for job_id, processing_time in jobs:\n # Get the worker that will be free earliest (and lowest index if tie)\n earliest_free_time, worker_idx = heapq.heappop(worker_finish_times)\n\n start_time = earliest_free_time\n end_time = start_time + processing_time\n\n results.append((job_id, start_time, end_time))\n\n # Update the worker's next free time and put it back in the heap\n heapq.heappush(worker_finish_times, (end_time, worker_idx))\n\n return results", "tests": ["assert process_job_queue([(\"A\", 2), (\"B\", 3), (\"C\", 1)], 1) == [(\"A\", 0, 2), (\"B\", 2, 5), (\"C\", 5, 6)]", "assert process_job_queue([(\"J1\", 5), (\"J2\", 2), (\"J3\", 3), (\"J4\", 1)], 2) == [('J1', 0, 5), ('J2', 0, 2), ('J3', 2, 5), ('J4', 5, 6)]", "assert process_job_queue([(\"X\", 3), (\"Y\", 3), (\"Z\", 3)], 3) == [('X', 0, 3), ('Y', 0, 3), ('Z', 0, 3)]", "assert process_job_queue([(\"Task1\", 10), (\"Task2\", 1), (\"Task3\", 1), (\"Task4\", 1), (\"Task5\", 1), (\"Task6\", 1)], 3) == [('Task1', 0, 10), ('Task2', 0, 1), ('Task3', 0, 1), ('Task4', 1, 2), ('Task5', 1, 2), ('Task6', 2, 3)]", "assert process_job_queue([], 5) == []", "assert process_job_queue([(\"K\", 1)], 10) == [('K', 0, 1)]"]} {"name": "process_job_queue_715", "topic": "stack/queue logic", "prompt": "import collections\n\ndef process_job_queue(jobs_with_dependencies: list[tuple[int, list[int]]]) -> list[int]:\n \"\"\"\n Processes a list of jobs with dependencies, returning the order in which jobs should be executed.\n Jobs are represented as tuples (job_id, [dependency_job_ids]).\n A job can only be executed if all its dependencies have been executed.\n If multiple jobs are ready to be executed at the same time, prioritize the one with the smallest job_id.\n\n Args:\n jobs_with_dependencies: A list of tuples, where each tuple contains a job_id (int)\n and a list of job_ids it depends on (list[int]).\n\n Returns:\n A list of job_ids in the order they should be executed. If a circular dependency\n is detected or it's impossible to process all jobs, return an empty list.\n\n Example:\n process_job_queue([(1, []), (2, [1]), (3, [1])]) == [1, 2, 3] or [1, 3, 2]\n (The actual output depends on tie-breaking, which prioritizes smallest job_id)\n process_job_queue([(1, []), (2, [1]), (3, [1])]) should return [1, 2, 3] because 2 < 3.\n\n process_job_queue([(1, [2]), (2, [1])]) == [] # Circular dependency\n \"\"\"", "solution": "import collections\nimport heapq\n\ndef process_job_queue(jobs_with_dependencies: list[tuple[int, list[int]]]) -> list[int]:\n \"\"\"\n Processes a list of jobs with dependencies, returning the order in which jobs should be executed.\n Jobs are represented as tuples (job_id, [dependency_job_ids]).\n A job can only be executed if all its dependencies have been executed.\n If multiple jobs are ready to be executed at the same time, prioritize the one with the smallest job_id.\n\n Args:\n jobs_with_dependencies: A list of tuples, where each tuple contains a job_id (int)\n and a list of job_ids it depends on (list[int]).\n\n Returns:\n A list of job_ids in the order they should be executed. If a circular dependency\n is detected or it's impossible to process all jobs, return an empty list.\n\n Example:\n process_job_queue([(1, []), (2, [1]), (3, [1])]) == [1, 2, 3] or [1, 3, 2]\n (The actual output depends on tie-breaking, which prioritizes smallest job_id)\n process_job_queue([(1, []), (2, [1]), (3, [1])]) should return [1, 2, 3] because 2 < 3.\n\n process_job_queue([(1, [2]), (2, [1])]) == [] # Circular dependency\n \"\"\"\n in_degree = collections.defaultdict(int)\n adj_list = collections.defaultdict(list)\n all_job_ids = set()\n\n for job_id, dependencies in jobs_with_dependencies:\n all_job_ids.add(job_id)\n for dep_id in dependencies:\n in_degree[job_id] += 1\n adj_list[dep_id].append(job_id)\n all_job_ids.add(dep_id)\n\n # Initialize ready jobs with jobs that have no dependencies\n # Use a min-heap to prioritize smallest job_id\n ready_jobs = []\n for job_id in all_job_ids:\n if in_degree[job_id] == 0:\n heapq.heappush(ready_jobs, job_id)\n\n execution_order = []\n while ready_jobs:\n current_job = heapq.heappop(ready_jobs)\n execution_order.append(current_job)\n\n for neighbor_job in adj_list[current_job]:\n in_degree[neighbor_job] -= 1\n if in_degree[neighbor_job] == 0:\n heapq.heappush(ready_jobs, neighbor_job)\n \n if len(execution_order) != len(all_job_ids):\n return [] # Circular dependency or some jobs could not be processed\n\n return execution_order", "tests": ["assert process_job_queue([(1, []), (2, [1]), (3, [1])]) == [1, 2, 3]", "assert process_job_queue([(1, [2]), (2, [1])]) == []", "assert process_job_queue([(1, []), (2, []), (3, [1, 2])]) == [1, 2, 3] or process_job_queue([(1, []), (2, []), (3, [1, 2])]) == [2, 1, 3]", "assert process_job_queue([(10, []), (20, [10]), (5, [])]) == [5, 10, 20]", "assert process_job_queue([(1, [2]), (2, [3]), (3, [])]) == [3, 2, 1]", "assert process_job_queue([(1, []), (2, []), (3, [])]) == [1, 2, 3]"]} {"name": "process_job_queue_527", "topic": "stack/queue logic", "prompt": "def process_job_queue(job_priorities: list[int], max_concurrent_jobs: int) -> list[int]:\n \"\"\"\n Simulates processing a job queue where jobs are processed in order of their priority.\n \n You are given a list of integers `job_priorities` representing the priority of each job.\n Higher numbers indicate higher priority. Jobs are added to the queue in the order they appear\n in the input list. The `max_concurrent_jobs` parameter dictates how many jobs can be processed\n simultaneously in each processing cycle.\n \n In each cycle:\n 1. Up to `max_concurrent_jobs` jobs are selected from the *current* queue.\n 2. These jobs are chosen based on the highest priority first. If priorities are equal,\n jobs that entered the queue earlier are chosen first (FIFO for equal priorities).\n 3. The selected jobs are considered 'processed' and removed from the queue.\n 4. The priorities of the processed jobs are recorded in the output list.\n \n The simulation continues until all jobs are processed.\n \n Args:\n job_priorities: A list of integers representing the priority of each job.\n An empty list means no jobs to process.\n max_concurrent_jobs: An integer representing the maximum number of jobs\n that can be processed concurrently in one cycle.\n Must be greater than 0.\n\n Returns:\n A list of integers representing the priorities of jobs in the order they were processed.\n \n Example:\n process_job_queue([3, 1, 2, 5], 2)\n Queue: [(3,0), (1,1), (2,2), (5,3)] (priority, original_index)\n Cycle 1:\n Select (5,3), (3,0) (highest priorities)\n Processed: [5, 3]\n Remaining: [(1,1), (2,2)]\n Cycle 2:\n Select (2,2), (1,1) (highest priorities)\n Processed: [2, 1]\n Remaining: []\n Result: [5, 3, 2, 1]\n \"\"\"", "solution": "import heapq\n\ndef process_job_queue(job_priorities: list[int], max_concurrent_jobs: int) -> list[int]:\n if not job_priorities:\n return []\n\n # Use a min-heap to simulate a max-priority queue.\n # We store tuples: (-priority, original_index, job_priority)\n # The negative priority ensures that the highest priority job (smallest -priority) is at the top.\n # original_index acts as a tie-breaker for equal priorities (smaller index means earlier arrival).\n # job_priority is stored to be returned in the result.\n \n # The actual queue is represented by a list of these tuples\n current_queue_elements = []\n for i, priority in enumerate(job_priorities):\n current_queue_elements.append((-priority, i, priority))\n \n processed_order = []\n\n while current_queue_elements:\n # Convert the current_queue_elements to a heap to easily get top N\n # This is a bit inefficient for very large queues that are processed slowly,\n # but for typical sizes and clarity, it's acceptable. \n # A persistent heap would be more efficient for many small removals.\n heapq.heapify(current_queue_elements)\n\n jobs_to_process_this_cycle = []\n for _ in range(min(max_concurrent_jobs, len(current_queue_elements))):\n # Pop the highest priority job (smallest -priority, then smallest original_index)\n neg_p, original_idx, actual_p = heapq.heappop(current_queue_elements)\n jobs_to_process_this_cycle.append((actual_p, original_idx))\n\n # Sort the jobs processed in this cycle by their original arrival order for stable output\n # (though the problem description implies output based on when they *were processed*, \n # not original order *within* a cycle. The example implies highest-first-then-highest-first.\n # Let's stick to the example: highest first then highest first, so no internal sort needed on actual_p).\n # The `heappop` already gives us the order of selection.\n\n for actual_p, _ in jobs_to_process_this_cycle:\n processed_order.append(actual_p)\n \n # After processing, what remains in current_queue_elements is implicitly the new queue\n\n return processed_order", "tests": ["assert process_job_queue([3, 1, 2, 5], 2) == [5, 3, 2, 1]", "assert process_job_queue([10, 20, 30, 5, 15], 1) == [30, 20, 15, 10, 5]", "assert process_job_queue([1, 1, 1, 1, 1], 3) == [1, 1, 1, 1, 1]", "assert process_job_queue([7, 2, 9, 4, 1, 6], 3) == [9, 7, 6, 4, 2, 1]", "assert process_job_queue([], 5) == []", "assert process_job_queue([50, 40, 30, 20, 10], 5) == [50, 40, 30, 20, 10]"]} {"name": "min_taps_to_water_garden", "topic": "greedy selection", "prompt": "def min_taps_to_water_garden(n: int, ranges: list[int]) -> int:\n \"\"\"\n You have a garden of length `n` units. There are `n + 1` taps located at points\n `[0, 1, ..., n]` along the garden. `ranges[i]` denotes that the i-th tap (at point `i`)\n can water the area `[i - ranges[i], i + ranges[i]]`. A tap can only water within\n the garden, so its effective range is clamped to `[0, n]`. If `ranges[i]` is 0,\n that tap cannot water any area.\n\n Your task is to find the minimum number of taps needed to water the whole garden,\n from point `0` to point `n`. If the garden cannot be watered completely,\n return -1.\n\n Args:\n n: The length of the garden (from 0 to n).\n ranges: A list of integers where `ranges[i]` is the reach of the tap at point `i`.\n The length of `ranges` will be `n + 1`.\n\n Returns:\n The minimum number of taps required, or -1 if the garden cannot be watered.\n\n Example:\n min_taps_to_water_garden(5, [3, 4, 1, 1, 0, 0]) == 1\n Explanation: Tap at 1 can water [1-4, 1+4] = [-3, 5]. Clamped to [0, 5].\n min_taps_to_water_garden(3, [0, 0, 0, 0]) == -1\n Explanation: No tap can water anything.\n min_taps_to_water_garden(7, [1,2,1,0,4,1,0,7]) == 2\n Explanation: Tap at 0 (range 1) covers [0,1].\n Tap at 7 (range 7) covers [0,7].\n Or tap at 4 (range 4) covers [0,8] clamped to [0,7]. One tap is enough.\n Ah, example is wrong. Let's trace it.\n Taps available: (start, end)\n 0: [0,1]\n 1: [0,3]\n 2: [1,3]\n 3: [3,3]\n 4: [0,8] -> [0,7]\n 5: [4,6]\n 6: [6,6]\n 7: [0,7]\n Greedy approach:\n Need to cover from 0. Max reach from current point 0.\n Tap 4 covers [0,7]. One tap.\n Expected output for (7, [1,2,1,0,4,1,0,7]) is 1.\n Let's use (7, [1,2,1,0,4,1,0,7]) == 1 as the example.\n \"\"\"\n", "solution": "def min_taps_to_water_garden(n: int, ranges: list[int]) -> int:\n intervals = []\n for i in range(n + 1):\n if ranges[i] > 0:\n start = max(0, i - ranges[i])\n end = min(n, i + ranges[i])\n intervals.append((start, end))\n\n # Sort intervals by their start points\n intervals.sort()\n\n taps = 0\n current_reach = 0\n i = 0\n\n while current_reach < n:\n # Find the tap that extends furthest from current_reach\n max_next_reach = current_reach\n found_tap = False\n start_index_for_next_iteration = i\n\n while i < len(intervals) and intervals[i][0] <= current_reach:\n max_next_reach = max(max_next_reach, intervals[i][1])\n found_tap = True\n i += 1\n \n if not found_tap or max_next_reach <= current_reach:\n return -1 # Cannot extend coverage or no tap covers current_reach\n\n taps += 1\n current_reach = max_next_reach\n\n return taps", "tests": ["assert min_taps_to_water_garden(5, [3, 4, 1, 1, 0, 0]) == 1", "assert min_taps_to_water_garden(3, [0, 0, 0, 0]) == -1", "assert min_taps_to_water_garden(7, [1, 2, 1, 0, 4, 1, 0, 7]) == 1", "assert min_taps_to_water_garden(8, [4, 0, 0, 0, 0, 0, 0, 0, 4]) == 2", "assert min_taps_to_water_garden(9, [0, 5, 0, 3, 0, 0, 0, 0, 2, 0]) == 2", "assert min_taps_to_water_garden(10, [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0]) == -1", "assert min_taps_to_water_garden(0, [0]) == 0", "assert min_taps_to_water_garden(1, [1,1]) == 1"]} {"name": "min_taps_to_water_garden_601", "topic": "greedy selection", "prompt": "def min_taps_to_water_garden(n: int, ranges: list[int]) -> int:\n \"\"\"\n You have a garden with 'n' sections, labeled from 0 to 'n'. There are 'n + 1' taps\n located at points 0, 1, ..., n. Each tap i has a range `ranges[i]` that can water\n the area [i - ranges[i], i + ranges[i]].\n\n Your goal is to find the minimum number of taps needed to water the entire garden,\n i.e., the interval [0, n]. If it's impossible to water the entire garden,\n return -1.\n\n The ranges list will have 'n + 1' elements, where ranges[i] corresponds to tap 'i'.\n\n Example:\n n = 5, ranges = [3, 4, 1, 1, 0, 0]\n Tap 0 covers [-3, 3]\n Tap 1 covers [-3, 5]\n Tap 2 covers [1, 3]\n Tap 3 covers [2, 4]\n Tap 4 covers [4, 4]\n Tap 5 covers [5, 5]\n\n To cover [0, 5]:\n Using tap 1 covers [-3, 5], which includes [0, 5]. Only 1 tap needed.\n Return 1.\n\n Example:\n n = 3, ranges = [0, 0, 0, 0]\n No tap can cover any positive range. Impossible to cover [0, 3].\n Return -1.\n \"\"\"", "solution": "def min_taps_to_water_garden(n: int, ranges: list[int]) -> int:\n intervals = []\n for i in range(n + 1):\n if ranges[i] > 0:\n start = max(0, i - ranges[i])\n end = min(n, i + ranges[i])\n intervals.append((start, end))\n\n intervals.sort()\n\n if not intervals and n > 0: # Handle cases like n=1, ranges=[0,0]\n return -1\n if n == 0: # A garden of length 0 needs 0 taps if n=0\n return 0\n\n taps = 0\n current_reach = 0\n i = 0\n num_intervals = len(intervals)\n\n while current_reach < n:\n taps += 1\n max_reach_in_step = current_reach\n found_tap = False\n\n while i < num_intervals and intervals[i][0] <= current_reach:\n max_reach_in_step = max(max_reach_in_step, intervals[i][1])\n i += 1\n found_tap = True\n\n if not found_tap or max_reach_in_step == current_reach:\n return -1 # Cannot extend coverage or no tap covers current_reach\n\n current_reach = max_reach_in_step\n\n return taps", "tests": ["assert min_taps_to_water_garden(5, [3, 4, 1, 1, 0, 0]) == 1", "assert min_taps_to_water_garden(3, [0, 0, 0, 0]) == -1", "assert min_taps_to_water_garden(7, [1, 2, 1, 0, 2, 1, 0, 1]) == 3", "assert min_taps_to_water_garden(8, [4, 0, 0, 0, 0, 0, 0, 0, 4]) == 2", "assert min_taps_to_water_garden(0, [0]) == 0", "assert min_taps_to_water_garden(1, [0, 0]) == -1", "assert min_taps_to_water_garden(1, [1, 1]) == 1", "assert min_taps_to_water_garden(4, [1, 2, 0, 1, 0]) == 2"]} {"name": "min_cost_climbing_stairs", "topic": "simple dynamic programming", "prompt": "def min_cost_climbing_stairs(cost: list[int]) -> int:\n \"\"\"\n You are given an integer array `cost` where `cost[i]` is the cost of `i`-th step on a staircase.\n Once you pay the cost, you can either climb one or two steps.\n\n You can either start from the step with index 0, or the step with index 1.\n\n Return the minimum cost to reach the top of the floor.\n\n The length of `cost` will be in the range [2, 1000].\n Each `cost[i]` will be an integer in the range [0, 999].\n\n Examples:\n min_cost_climbing_stairs([10, 15, 20]) == 15\n min_cost_climbing_stairs([1, 100, 1, 1, 1, 100, 1, 1, 100, 1]) == 6\n \"\"\"", "solution": "def min_cost_climbing_stairs(cost: list[int]) -> int:\n n = len(cost)\n\n if n == 2:\n return min(cost[0], cost[1])\n\n # dp[i] will store the minimum cost to reach step i\n dp = [0] * n\n\n # Base cases\n dp[0] = cost[0]\n dp[1] = cost[1]\n\n for i in range(2, n):\n dp[i] = cost[i] + min(dp[i-1], dp[i-2])\n \n # The top of the floor is effectively one step beyond the last step of the cost array.\n # We can reach the top from either the last step (n-1) or the second to last step (n-2).\n # The cost of reaching the top from dp[n-1] is dp[n-1] (since we've already paid cost[n-1])\n # The cost of reaching the top from dp[n-2] is dp[n-2] (since we've already paid cost[n-2])\n return min(dp[n-1], dp[n-2])", "tests": ["assert min_cost_climbing_stairs([10, 15, 20]) == 15", "assert min_cost_climbing_stairs([1, 100, 1, 1, 1, 100, 1, 1, 100, 1]) == 6", "assert min_cost_climbing_stairs([1, 2]) == 1", "assert min_cost_climbing_stairs([0, 0, 0, 0]) == 0", "assert min_cost_climbing_stairs([5, 10, 2, 8, 1]) == 8", "assert min_cost_climbing_stairs([100, 1, 1, 100]) == 2"]} {"name": "max_subarray_sum_circular", "topic": "simple dynamic programming", "prompt": "def max_subarray_sum_circular(nums: list[int]) -> int:\n \"\"\"\n Given a circular integer array 'nums' of length 'n', return the maximum possible sum of a non-empty subarray of 'nums'.\n\n A circular array means the end-elements are connected to the beginning-elements.\n Formally, the next element of nums[i] is nums[(i + 1) % n] and the previous element of nums[i] is nums[(i - 1 + n) % n].\n\n A subarray may only include each element of the original 'nums' at most once.\n For example, if nums = [1,2,3], the subarray [3,1] is valid, but [3,1,2,1] is not.\n\n Example 1:\n Input: nums = [1,-2,3,-2]\n Output: 3\n Explanation: Subarray [3] has maximum sum 3.\n\n Example 2:\n Input: nums = [5,-3,5]\n Output: 10\n Explanation: Subarray [5,5] has maximum sum 5 + 5 = 10.\n\n Example 3:\n Input: nums = [-3,-2,-3]\n Output: -2\n Explanation: Subarray [-2] has maximum sum -2.\n\n Constraints:\n n == nums.length\n 1 <= n <= 3 * 10^4\n -3 * 10^4 <= nums[i] <= 3 * 10^4\n \"\"\"", "solution": "def max_subarray_sum_circular(nums: list[int]) -> int:\n n = len(nums)\n if n == 0:\n return 0\n if n == 1:\n return nums[0]\n\n # Case 1: The maximum subarray is non-circular (standard Kadane's algorithm)\n current_max = nums[0]\n global_max = nums[0]\n total_sum = nums[0]\n\n for i in range(1, n):\n current_max = max(nums[i], current_max + nums[i])\n global_max = max(global_max, current_max)\n total_sum += nums[i]\n\n # Case 2: The maximum subarray is circular\n # This means the subarray wraps around. It's equivalent to finding the minimum subarray sum\n # and subtracting it from the total sum. (total_sum - min_subarray_sum)\n # Special case: if all numbers are negative, min_subarray_sum == total_sum,\n # which would make total_sum - min_subarray_sum == 0. But the problem states\n # the subarray must be non-empty, so in this case, global_max (from Kadane's) is the answer.\n\n current_min = nums[0]\n global_min = nums[0]\n\n for i in range(1, n):\n current_min = min(nums[i], current_min + nums[i])\n global_min = min(global_min, current_min)\n\n # If global_max is negative, it means all numbers are negative.\n # In this case, the maximum circular sum would be 0 (total_sum - global_min if global_min == total_sum),\n # which is not allowed as a subarray must be non-empty. So we return global_max.\n if global_max < 0:\n return global_max\n\n return max(global_max, total_sum - global_min)", "tests": ["assert max_subarray_sum_circular([1,-2,3,-2]) == 3", "assert max_subarray_sum_circular([5,-3,5]) == 10", "assert max_subarray_sum_circular([-3,-2,-3]) == -2", "assert max_subarray_sum_circular([1]) == 1", "assert max_subarray_sum_circular([-1,-2,-3,-4]) == -1", "assert max_subarray_sum_circular([1,2,3,4]) == 10", "assert max_subarray_sum_circular([1,-1,1]) == 2", "assert max_subarray_sum_circular([3,-1,2,-1]) == 4"]} {"name": "min_cost_climbing_stairs_618", "topic": "simple dynamic programming", "prompt": "def min_cost_climbing_stairs(cost: list[int]) -> int:\n \"\"\"\n You are given an integer array `cost` where `cost[i]` is the cost of `i`-th step on a staircase.\n Once you pay the cost, you can either climb one or two steps.\n\n You can either start from the step with index 0, or the step with index 1.\n\n Return the minimum cost to reach the top of the floor.\n\n The length of `cost` will be at least 2.\n\n For example:\n min_cost_climbing_stairs([10, 15, 20]) == 15\n (Start at index 1, pay 15, reach top)\n\n min_cost_climbing_stairs([1, 100, 1, 1, 1, 100, 1, 1, 100, 1]) == 6\n (Start at index 0, pay 1, jump 2 steps to index 2 (cost 1), jump 2 steps to index 4 (cost 1), jump 2 steps to index 6 (cost 1), jump 2 steps to index 8 (cost 1), jump 2 steps to top (cost 1))\n \"\"\"", "solution": "def min_cost_climbing_stairs(cost: list[int]) -> int:\n n = len(cost)\n if n == 0:\n return 0\n if n == 1:\n return cost[0]\n\n # dp[i] will store the minimum cost to reach step i\n # The 'top' is considered one step beyond the last element of cost\n # So, we need to find the min cost to reach index n\n dp = [0] * (n + 1)\n\n # Base cases: cost to reach step 0 is 0, cost to reach step 1 is 0\n # because we can start from either index 0 or index 1 without paying previous costs\n dp[0] = 0\n dp[1] = 0\n\n for i in range(2, n + 1):\n # To reach step i, we could have come from step i-1 (paying cost[i-1])\n # or from step i-2 (paying cost[i-2])\n dp[i] = min(dp[i-1] + cost[i-1], dp[i-2] + cost[i-2])\n\n return dp[n]", "tests": ["assert min_cost_climbing_stairs([10, 15, 20]) == 15", "assert min_cost_climbing_stairs([1, 100, 1, 1, 1, 100, 1, 1, 100, 1]) == 6", "assert min_cost_climbing_stairs([1, 2]) == 1", "assert min_cost_climbing_stairs([2, 1]) == 1", "assert min_cost_climbing_stairs([0, 0, 0, 0]) == 0", "assert min_cost_climbing_stairs([10, 1, 10, 1, 10, 1, 10, 1, 10]) == 4"]} {"name": "min_cost_climbing_stairs_374", "topic": "simple dynamic programming", "prompt": "def min_cost_climbing_stairs(cost: list[int]) -> int:\n \"\"\"\n You are given an integer array `cost` where `cost[i]` is the cost of `i`-th step\n on a staircase. Once you pay the cost, you can either climb one or two steps.\n You can either start from step 0 or step 1.\n\n Return the minimum cost to reach the top of the floor.\n\n The length of `cost` will be between 2 and 1000 inclusive.\n Each `cost[i]` will be an integer between 0 and 999 inclusive.\n\n Example 1:\n Input: cost = [10, 15, 20]\n Output: 15\n Explanation: Cheapest is to start on step 1, pay 15, and climb two steps to reach the top.\n\n Example 2:\n Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]\n Output: 6\n Explanation: Cheapest is to start on step 0, and pay 1 on step 0, 1 on step 2, 1 on step 3,\n 1 on step 4, 1 on step 6, 1 on step 7, and 1 on step 9. Total cost = 6.\n \"\"\"", "solution": "def min_cost_climbing_stairs(cost: list[int]) -> int:\n n = len(cost)\n if n == 0:\n return 0\n if n == 1:\n return cost[0]\n\n dp = [0] * n\n\n # Base cases\n dp[0] = cost[0]\n dp[1] = cost[1]\n\n for i in range(2, n):\n dp[i] = cost[i] + min(dp[i-1], dp[i-2])\n\n # The top of the floor can be reached from step n-1 or step n-2.\n # We don't pay for the 'top' itself, only to reach it.\n return min(dp[n-1], dp[n-2])", "tests": ["assert min_cost_climbing_stairs([10, 15, 20]) == 15", "assert min_cost_climbing_stairs([1, 100, 1, 1, 1, 100, 1, 1, 100, 1]) == 6", "assert min_cost_climbing_stairs([1, 2]) == 1", "assert min_cost_climbing_stairs([0, 0, 0, 0]) == 0", "assert min_cost_climbing_stairs([5, 10, 2, 7]) == 7", "assert min_cost_climbing_stairs([20, 15, 30, 5]) == 20"]} {"name": "max_subarray_sum_circular_712", "topic": "simple dynamic programming", "prompt": "def max_subarray_sum_circular(nums: list[int]) -> int:\n \"\"\"\n Given a circular integer array 'nums' of length n, return the maximum possible sum of a non-empty subarray of 'nums'.\n\n A circular array means the end of the array connects to the beginning of the array.\n Formally, if nums is [nums[0], nums[1], ..., nums[n-1]], then the next element after nums[n-1] is nums[0],\n and the previous element before nums[0] is nums[n-1].\n\n A subarray may only include each element of the original array at most once.\n (For example, if nums = [1,2,3], the subarray [3,1] is valid, but [3,1,2,1] is not).\n\n The array 'nums' will have at least one element.\n Each element will be between -30000 and 30000.\n\n Examples:\n max_subarray_sum_circular([1,-2,3,-2]) == 3 # The subarray [3] has maximum sum 3.\n max_subarray_sum_circular([5,-3,5]) == 10 # The subarray [5,5] has maximum sum 5 + 5 = 10.\n max_subarray_sum_circular([3,-1,2,-1]) == 4 # The subarray [2,-1,3] has maximum sum 2 - 1 + 3 = 4.\n max_subarray_sum_circular([-3,-2,-3]) == -2 # The subarray [-2] has maximum sum -2.\n \"\"\"", "solution": "def max_subarray_sum_circular(nums: list[int]) -> int:\n n = len(nums)\n if n == 0:\n return 0\n if n == 1:\n return nums[0]\n\n # Kadane's algorithm for non-circular max subarray sum\n current_max = nums[0]\n global_max = nums[0]\n current_min = nums[0]\n global_min = nums[0]\n total_sum = nums[0]\n\n for i in range(1, n):\n total_sum += nums[i]\n\n current_max = max(nums[i], current_max + nums[i])\n global_max = max(global_max, current_max)\n\n current_min = min(nums[i], current_min + nums[i])\n global_min = min(global_min, current_min)\n\n # Case 1: The maximum subarray is not wrapped (standard Kadane's result)\n # This is `global_max`\n\n # Case 2: The maximum subarray is wrapped (total_sum - min_subarray_sum)\n # If all numbers are negative, global_max will be the largest negative number.\n # total_sum - global_min would be 0 or positive, which is incorrect.\n # So, if total_sum == global_min, it means all numbers are negative,\n # and the max sum is global_max (the least negative number).\n if total_sum == global_min:\n return global_max\n else:\n return max(global_max, total_sum - global_min)\n", "tests": ["assert max_subarray_sum_circular([1,-2,3,-2]) == 3", "assert max_subarray_sum_circular([5,-3,5]) == 10", "assert max_subarray_sum_circular([3,-1,2,-1]) == 4", "assert max_subarray_sum_circular([-3,-2,-3]) == -2", "assert max_subarray_sum_circular([1]) == 1", "assert max_subarray_sum_circular([2, -1, 3, -2, 4]) == 8", "assert max_subarray_sum_circular([-10, -5, -2, -8]) == -2", "assert max_subarray_sum_circular([3, 1, 3, 2, 6]) == 15"]}