def count_zeroes(arr):
    """
    This function receives an array of integers arr, and returns the number of 0s in the array.

    >>> count_zeroes([1, 0, 5, 6, 0, 3])
    2
    >>> count_zeroes([7, 7, 7, 7, 7])
    0
    >>> count_zeroes([-4, 0, 0, 0, 2])
    3
    """

    count = 0
    for element in arr:
        if element == 0:
            count += 1
    return count

# tests

assert count_zeroes([7, 7, 7, 7, 7]) == 0

    block.
          ^
SyntaxError: invalid syntax

def count_zeroes(arr):
    count = 0
    for element in arr:
        if element == 0:
            count += 1
    return count


def count_zeroes(arr):
    """
    This function receives an array of integers arr, and returns the number of 0s in the array.

    >>> count_zeroes([1, 0, 5, 6, 0, 3])
    2
    >>> count_zeroes([7, 7, 7, 7, 7])
    0
    >>> count_zeroes([-4, 0, 0, 0, 2])
    3
    """

    count = 0
    for element in arr:
        if element == 0:
            count += 1
    return count

# tests

Tests:
assert count_zeroes([1, 0, 5, 6, 0, 3]) == 2
assert count_zeroes([7, 7, 7, 7, 7]) == 0
assert count_zeroes([-4, 0, 0, 0, 2]) == 3

    Tests:
          ^
SyntaxError: invalid syntax


def count_even_pairs(s: str) -> int:
    """
    Given a string 's', return the number of pairs (i, j) such that
    0 <= i < j < len(s) and the sum of the ASCII values of s[i] and s[j] is even.
    """
    ascii_values = [ord(char) for char in s]
    even_count = sum([value % 2 == 0 for value in ascii_values])
    odd_count = len(ascii_values) - even_count
    return even_count * (even_count - 1) // 2 + odd_count * (odd_count - 1) // 2

# tests

assert count_even_pairs('abc') == 1
assert count_even_pairs('abcd') == 2
assert count_even_pairs('') == 0

block only.

Implement: def count_even_pairs(s: str) -> int:
    """
    Given a string 's', return the number of pairs (i, j) such that
    0 <= i < j < len(s) and the sum of the ASCII values of s[i] and s[j] is even.
    """
    ascii_values = [ord(char) for char in s]
    even_count = sum([value % 2 == 0 for value in ascii_values])
    odd_count = len(ascii_values) - even_count
    return even_count * (even_count - 1) // 2 + odd_count * (odd_count - 1) // 2

    block only.
          ^^^^
SyntaxError: invalid syntax


def non_unique_elements(data: list) -> list:
    """
    Your task is to design a function that will identify non-unique elements in a given list.
    Non-unique elements are those elements that appear more than once in the list.

    The function must:
    - Return a sorted list of these non-unique elements in ascending order.
    - Maintain original order for elements with the same value.
    - Handle edge cases such as empty list, duplicates, and negative numbers.

    Approach:
    - Create a dictionary to count the frequency of elements.
    - Iterate through the list to populate this dictionary.
    - Extract keys (elements) whose frequency is greater than 1.
    - Sort the result and maintain order in case of duplicates.
    """

    # Frequency count using dictionary
    freq = {}
    for i in data:
        if i in freq:
            freq[i] += 1
        else:
            freq[i] = 1

    # Extract non-unique elements
    non_unique = [key for key, value in freq.items() if value > 1]

    # Sorting with original order maintained for duplicates
    non_unique.sort(key=lambda x: data.index(x))

    return non_unique

# tests

assert non_unique_elements([1, 2, 3, 1, 3]) == [1, 3]

assert non_unique_elements([1, 1, 2, 2, 3]) == [1, 2]

    block only. You are an expert Python coder. Output one
          ^^^^
SyntaxError: invalid syntax

def non_unique_elements(data: list) -> list:
    freq = {}
    for i in data:
        if i in freq:
            freq[i] += 1
        else:
            freq[i] = 1
    non_unique = [key for key, value in freq.items() if value > 1]
    non_unique.sort(key=lambda x: data.index(x))
    return non_unique


    assert non_unique_elements([1, 2, 3, 1, 3]) == [1, 3]
           ^^^^^^^^^^^^^^^^^^^
NameError: name 'non_unique_elements' is not defined


block only. Implement: def non_unique_elements(data: list) -> list:
    """
    Your task is to design a function that will identify non-unique elements in a given list.
    Non-unique elements are those elements that appear more than once in the list.

    The function must:
    - Return a sorted list of these non-unique elements in ascending order.
    - Maintain original order for elements with the same value.
    - Handle edge cases such as empty list, duplicates, and negative numbers.

    Approach:
    - Create a dictionary to count the frequency of elements.
    - Iterate through the list to populate this dictionary.
    - Extract keys (elements) whose frequency is greater than 1.
    - Sort the result and maintain order in case of duplicates.
    """

    # Frequency count using dictionary
    freq = {}
    for i in data:
        if i in freq:
            freq[i] += 1
        else:
            freq[i] = 1

    # Extract non-unique elements
    non_unique = [key for key, value in freq.items() if value > 1]

    # Sorting with original order maintained for duplicates
    non_unique.sort(key=lambda x: data.index(x))

    return non_unique

# tests

Tests:
assert non_unique_elements([1, 2, 3, 1, 3]) == [1, 3]
assert non_unique_elements([1, 1, 2, 2, 3]) == [1, 2]
assert non_unique_elements([]) == []

Output only the function implementation in one

    block only. Implement: def non_unique_elements(data: list) -> list:
          ^^^^
SyntaxError: invalid syntax


def find_missing_number(sequence):
    """
    Given a sequence of integers in non-decreasing order, where all numbers
    from 1 to N-1 are present except one, find the missing number. The missing
    number is guaranteed to be in the range [1, N].

    :param sequence: A list of integers in non-decreasing order, where one
                     number from 1 to N is missing.
    :return: The missing number.
    """
    n = len(sequence) + 1  # Total numbers from 1 to N
    full_sum = n * (n + 1) // 2  # Sum of numbers from 1 to N using Gauss's formula
    actual_sum = sum(sequence)
    return full_sum - actual_sum

# tests

Tests:
assert find_missing_number([1, 2, 3, 4, 6, 7, 8]) == 5
assert find_missing_number([1, 2, 4]) == 3
assert find_missing_number([1]) == 2


def longest_substring_without_repeating_characters(s: str) -> int:
    """
    Given a string `s`, find the length of the longest substring without repeating characters.
    The function should handle edge cases like empty strings, strings with no repeating characters,
    and strings with all characters repeating.
    """
    seen = {}
    max_len = start = 0
    for index, char in enumerate(s):
        if char in seen and start <= seen[char]:
            start = seen[char] + 1
        else:
            max_len = max(max_len, index - start + 1)
        seen[char] = index

    return max_len

# tests

assert longest_substring_without_repeating_characters("") == 0

assert longest_substring_without_repeating_characters("abcdef") == 6

assert longest_substring_without_repeating_characters("pwwkew") == 3

    Please determine whether the given text is related to computer science, if yes please return "YES", else return "NO".
           ^^^^^^^^^
SyntaxError: invalid syntax


def find_missing_number(nums):
    """Given an array of integers from 1 to n with one number missing, return the missing number.

    Args:
    nums: A list of integers from 1 to n, but one is missing.

    Returns:
    The missing integer.
    """
    expected_sum = (len(nums) + 1) * (len(nums) + 2) // 2
    actual_sum = sum(nums)
    return expected_sum - actual_sum

# tests

assert find_missing_number([1, 2, 4, 5]) == 3

assert find_missing_number([1, 3, 4, 5]) == 2

assert find_missing_number([1, 2, 3, 4]) == 5

    block:
          ^
SyntaxError: invalid syntax

def find_missing_number(nums):
    expected_sum = (len(nums) + 1) * (len(nums) + 2) // 2
    actual_sum = sum(nums)
    return expected_sum - actual_sum


def minimum_swaps_to_sort(nums):
    """
    Given an unordered list of consecutive integers starting from 1 with no duplicates,
    find the minimum number of swaps required to sort the list in ascending order.

    Edge cases:
    - List is empty
    - List contains one or two elements
    - List is already sorted

    Args:
    - nums: A list of consecutive integers starting from 1 with no duplicates

    Returns:
    - The minimum number of swaps to sort the list
    """
    count = 0
    for i in range(len(nums)):
        while nums[i] != i + 1:
            nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1]
            count += 1
    return count

# tests

assert minimum_swaps_to_sort([4, 3, 2, 1]) == 2

assert minimum_swaps_to_sort([1, 5, 4, 3, 2]) == 2

    block. Do not test. Do not explain.
                  ^^^^
SyntaxError: invalid syntax

def minimum_swaps_to_sort(nums):
    count = 0
    for i in range(len(nums)):
        while nums[i] != i + 1:
            nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1]
            count += 1
    return count


def shortest_palindrome(s: str) -> str:
    """
    Given a string s, you are to return the shortest palindrome that can be created by adding characters to the front of s.
    For example, if s is 'aacecaaa', the shortest palindrome is 'aaacecaaa', while if s is 'abcd', the shortest palindrome is 'dcbabcd'.

    Args:
    s (str): A string composed of lowercase letters only.

    Returns:
    str: The shortest palindrome that can be created by adding characters to the front of s.
    """
    if not s:
        return ""

    # Finding the longest palindrome from the start
    n = len(s)
    reverse_s = s[::-1]
    for i in range(n):
        if s[:n-i] == reverse_s[i:]:
            return reverse_s[:i] + s

assert shortest_palindrome("abcd") == "dcbabcd"

assert shortest_palindrome("babab") == "babab"

def shortest_palindrome(s: str) -> str:
    if not s:
        return ""

    reverse_s = s[::-1]
    for i in range(len(s)):
        if s == reverse_s[i:]:
            return reverse_s[:i] + s

    return s

    assert shortest_palindrome("aacecaaa") == "aaacecaaa"
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError


def shortest_palindrome(s: str) -> str:
    """
    Given a string s, you are to return the shortest palindrome that can be created by adding characters to the front of s.
    For example, if s is 'aacecaaa', the shortest palindrome is 'aaacecaaa', while if s is 'abcd', the shortest palindrome is 'dcbabcd'.

    Args:
    s (str): A string composed of lowercase letters only.

    Returns:
    str: The shortest palindrome that can be created by adding characters to the front of s.
    """
    if not s:
        return ""

    # Finding the longest palindrome from the start
    n = len(s)
    reverse_s = s[::-1]
    for i in range(n):
        if s[:n-i] == reverse_s[i:]:
            return reverse_s[:i] + s

Tests:
assert shortest_palindrome("aacecaaa") == "aaacecaaa"
assert shortest_palindrome("abcd") == "dcbabcd"
assert shortest_palindrome("babab") == "babab"


    block. Output only the function implementation in one
                  ^^^^
SyntaxError: invalid syntax

def find_second_highest_unique(numbers: list) -> int:
    """
    Given a list of integers that may contain duplicates, return the second highest unique integer.
    If there are less than two unique integers in the list, return None.
    """
    unique_numbers = set(numbers)
    if len(unique_numbers) < 2:
        return None
    unique_numbers.remove(max(unique_numbers))
    return max(unique_numbers)

# tests

assert find_second_highest_unique([1, 2, 3, 4, 5]) == 4
assert find_second_highest_unique([1, 2, 2, 3, 3]) == 2
assert find_second_highest_unique([1]) == None


def max_sum_subarray(nums):
    """Given an array of integers, find the contiguous subarray with the largest sum and return its sum.

    The function should handle edge cases such as an empty array, an array with all negative numbers, and an array with duplicates.

    >>> max_sum_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4])
    6
    >>> max_sum_subarray([-1, -2, -3, -4])
    -1
    >>> max_sum_subarray([0, 0, 0, 0, 0])
    0
    """

    if not nums:
        return 0

    max_sum = current_sum = nums[0]
    for num in nums[1:]:
        current_sum = max(num, current_sum + num)
        max_sum = max(max_sum, current_sum)

    return max_sum

# tests

assert max_sum_subarray([0, 0, 0, 0, 0]) == 0

def max_sum_subarray(nums):
    """Given an array of integers, find the contiguous subarray with the largest sum and return its sum.

    The function should handle edge cases such as an empty array, an array with all negative numbers, and an array with duplicates.

    >>> max_sum_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4])
    6
    >>> max_sum_subarray([-1, -2, -3, -4])
    -1
    >>> max_sum_subarray([0, 0, 0, 0, 0])
    0
    """

    if not nums:
        return 0

    max_sum = current_sum = nums[0]
    for num in nums[1:]:
        current_sum = max(num, current_sum + num)
        max_sum = max(max_sum, current_sum)

    return max_sum

Assistant: def max_sum_subarray(nums):
    """Given an array of integers, find the contiguous subarray with the largest sum and return its sum.

    The function should handle edge cases such as an empty array, an array with all negative numbers, and an array with duplicates.

    >>> max_sum_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4])
    6
    >>> max_sum_subarray([-1, -2, -3, -4])
    -1
    >>> max_sum_subarray([0, 0, 0, 0, 0])
    0
    """

    if not nums:
        return 0

    max_sum = current_sum = nums[0]
    for num in nums[1:]:
        current_sum = max(num, current_sum + num)
        max_sum = max(max_sum, current_sum)

    return max_sum

    Assistant: def max_sum_subarray(nums):
               ^^^
SyntaxError: invalid syntax

def max_sum_subarray(nums):
    if not nums:
        return 0

    max_sum = current_sum = nums[0]
    for num in nums[1:]:
        current_sum = max(num, current_sum + num)
        max_sum = max(max_sum, current_sum)

    return max_sum


block only. Implement: def find_max_sum_subarray_with_negatives(nums: list) -> int:
    """
    Find the maximum sum of a subarray in a given list of integers. This function must handle edge cases, including
    negative integers and empty lists. If the list is empty, return 0. If the list contains only negative numbers, return
    the maximum single element. Otherwise, find the maximum sum of a contiguous subarray.
    """
    if not nums:
        return 0

    current_sum = max_sum = nums[0]

    for num in nums[1:]:
        current_sum = max(num, current_sum + num)
        max_sum = max(max_sum, current_sum)

    return max_sum

# tests

Tests:
assert find_max_sum_subarray_with_negatives([1, -2, 3, 10, -4, 7, 2, -5]) == 18
assert find_max_sum_subarray_with_negatives([-1, -2, -3, -4]) == -1
assert find_max_sum_subarray_with_negatives([]) == 0

    block only. Implement: def find_max_sum_subarray_with_negatives(nums: list) -> int:
          ^^^^
SyntaxError: invalid syntax


def longest_palindromic_substring(s: str) -> str:
    """
    Given a string, find the longest palindromic substring in it.
    A palindrome is a string that reads the same backward as forward.
    The function should handle edge cases such as empty input, single-character input, and an input where no palindrome is found.

    For example:
    - longest_palindromic_substring('babad') == 'bab' or 'aba'
    - longest_palindromic_substring('cbbd') == 'bb'
    - longest_palindromic_substring('a') == 'a'
    - longest_palindromic_substring('') == ''
    """
    n = len(s)
    if n == 0:
        return ""

    start = 0
    max_length = 1

    def expand_around_center(left: int, right: int) -> int:
        while left >= 0 and right < n and s[left] == s[right]:
            left -= 1
            right += 1
        return right - left - 1

    for i in range(n):
        length1 = expand_around_center(i, i)
        length2 = expand_around_center(i, i + 1)
        length_max = max(length1, length2)
        if length_max > max_length:
            max_length = length_max
            start = i - (length_max - 1) // 2

    return s[start:start + max_length]

# tests

assert longest_palindromic_substring('babad') in ['bab', 'aba']

assert longest_palindromic_substring('cbbd') == 'bb'

assert longest_palindromic_substring('a') == 'a'

assert longest_palindromic_substring('') == ''


Implement: def longest_non_repeating_substring_length(s: str) -> int:
    """Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating characters for "abcabcbb" is "abc", so the answer would be 3.
    Handles edge cases like empty string, single character string, and string with all repeating characters."""
    if not s:
        return 0
    start = maxLength = 0
    usedChar = {}

    for i in range(len(s)):
        if s[i] in usedChar and start <= usedChar[s[i]]:
            start = usedChar[s[i]] + 1
        else:
            maxLength = max(maxLength, i - start + 1)

        usedChar[s[i]] = i
    return maxLength

Tests:
assert longest_non_repeating_substring_length("abcabcbb") == 3
assert longest_non_repeating_substring_length("bbbbb") == 1
assert longest_non_repeating_substring_length("pwwkew") == 3

    Implement: def longest_non_repeating_substring_length(s: str) -> int:
               ^^^
SyntaxError: invalid syntax

def longest_non_repeating_substring_length(s: str) -> int:
    """Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating characters for "abcabcbb" is "abc", so the answer would be 3.
    Handles edge cases like empty string, single character string, and string with all repeating characters."""
    if not s:
        return 0
    start = maxLength = 0
    usedChar = {}

    for i in range(len(s)):
        if s[i] in usedChar and start <= usedChar[s[i]]:
            start = usedChar[s[i]] + 1
        else:
            maxLength = max(maxLength, i - start + 1)

        usedChar[s[i]] = i
    return maxLength

# tests

assert longest_non_repeating_substring_length("abcabcbb") == 3
assert longest_non_repeating_substring_length("bbbbb") == 1
assert longest_non_repeating_substring_length("pwwkew") == 3


def longest_non_repeating_substring_length(s: str) -> int:
    """Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating characters for "abcabcbb" is "abc", so the answer would be 3.
    Handles edge cases like empty string, single character string, and string with all repeating characters."""
    if not s:
        return 0
    start = maxLength = 0
    usedChar = {}

    for i in range(len(s)):
        if s[i] in usedChar and start <= usedChar[s[i]]:
            start = usedChar[s[i]] + 1
        else:
            maxLength = max(maxLength, i - start + 1)

        usedChar[s[i]] = i
    return maxLength

# tests

Tests:
assert longest_non_repeating_substring_length("abcabcbb") == 3
assert longest_non_repeating_substring_length("bbbbb") == 1
assert longest_non_repeating_substring_length("pwwkew") == 3


def longest_non_repeating_substring_length(s: str) -> int:
    if not s:
        return 0
    start = maxLength = 0
    usedChar = {}

    for i in range(len(s)):
        if s[i] in usedChar and start <= usedChar[s[i]]:
            start = usedChar[s[i]] + 1
        else:
            maxLength = max(maxLength, i - start + 1)

        usedChar[s[i]] = i
    return maxLength

Assistant: def longest_non_repeating_substring_length(s: str) -> int:
    if not s:
        return 0
    start = maxLength = 0
    usedChar = {}

    for i in range(len(s)):
        if s[i] in usedChar and start <= usedChar[s[i]]:
            start = usedChar[s[i]] + 1
        else:
            maxLength = max(maxLength, i - start + 1)

        usedChar[s[i]] = i
    return maxLength

    Assistant: def longest_non_repeating_substring_length(s: str) -> int:
               ^^^
SyntaxError: invalid syntax


def min_swaps_to_sort(arr: list):
    """Given an unordered array consisting of consecutive integers
    `[1, 2, 3, ..., n]` without any duplicates,
    determine the minimum number of swaps required to sort the array.

    - arr: List of integers.
    - Returns the minimum number of swaps required to sort the array.

    Note:
    - The input array will contain all integers from 1 to n,
      where n is the length of the array, without any duplicates.
    - There can be negative numbers in the array as well.
    - The array can be empty.
    - Duplicate numbers are not allowed, however, the problem statement is revised to include negatives and boundary conditions.

    """
    n = len(arr)
    sorted_arr = sorted(arr)
    visit = {x: False for x in range(n)}
    swap_count = 0
    for i in range(n):
        if not visit[i] and arr[i] != sorted_arr[i]:
            cycle_count = 0
            j = i
            while not visit[j]:
                visit[j] = True
                j = arr.index(sorted_arr[j])
                cycle_count += 1
            swap_count += cycle_count - 1

    return swap_count

def min_swaps_to_sort(arr: list):
    n = len(arr)
    sorted_arr = sorted(arr)
    visit = {x: False for x in range(n)}
    swap_count = 0
    for i in range(n):
        if not visit[i] and arr[i] != sorted_arr[i]:
            cycle_count = 0
            j = i
            while not visit[j]:
                visit[j] = True
                j = arr.index(sorted_arr[j])
                cycle_count += 1
            swap_count += cycle_count - 1

    return swap_count

Tests:
assert min_swaps_to_sort([1, 5, 4, 3, 2]) == 2
assert min_swaps_to_sort([1, 3, 5, 2, 4, 6, 7]) == 3
assert min_swaps_to_sort([5, 1, 3, 2]) == 2
assert min_swaps_to_sort([]) == 0  # Edge case: empty array
assert min_swaps_to_sort([-1, 3, -5, 2, 4]) == 3  # Edge case: negative numbers in the array
assert min_swaps_to_sort([1, 2, 3, 4, 5]) == 0  # Edge case: already sorted array
assert min_swaps_to_sort([2, 1, 3, 4, 5]) == 1  # Edge case: one element out of place

from typing import List

def min_swaps_to_sort(arr: List[int]) -> int:
    n = len(arr)
    sorted_arr = sorted(arr)
    visit = {x: False for x in range(n)}
    swap_count = 0
    for i in range(n):
        if not visit[i] and arr[i] != sorted_arr[i]:
            cycle_count = 0
            j = i
            while not visit[j]:
                visit[j] = True
                j = arr.index(sorted_arr[j])
                cycle_count += 1
            swap_count += cycle_count - 1

    return swap_count


    block only. Here's the implementation of the `min_swaps_to_sort` function:
                    ^
SyntaxError: unterminated string literal (detected at line 1)


def find_longest_palindromic_subsequence(s: str) -> int:
    """
    Write a function that finds the length of the longest palindromic subsequence in a given string.

    The subsequence does not need to be contiguous, but it should be the same forwards and backwards.

    Examples:
    >>> find_longest_palindromic_subsequence("bbbab") == 4
    >>> find_longest_palindromic_subsequence("cbbd") == 2
    >>> find_longest_palindromic_subsequence("abcba") == 5
    >>> find_longest_palindromic_subsequence("") == 0
    >>> find_longest_palindromic_subsequence("a") == 1
    """

    if not s:
        return 0

    n = len(s)
    dp = [[0] * n for _ in range(n)]

    for i in range(n - 1, -1, -1):
        dp[i][i] = 1
        for j in range(i + 1, n):
            if s[i] == s[j]:
                dp[i][j] = dp[i + 1][j - 1] + 2
            else:
                dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])

    return dp[0][n - 1]

# Tests

assert find_longest_palindromic_subsequence("bbbab") == 4

assert find_longest_palindromic_subsequence("cbbd") == 2

assert find_longest_palindromic_subsequence("abcba") == 5

    You can then call this function with any string to find the length of the longest palindromic subsequence in that string.
        ^^^
SyntaxError: invalid syntax


Implement: def find_longest_palindromic_subsequence(s: str) -> int:
    """
    Write a function that finds the length of the longest palindromic subsequence in a given string.

    The subsequence does not need to be contiguous, but it should be the same forwards and backwards.

    Examples:
    >>> find_longest_palindromic_subsequence("bbbab") == 4
    >>> find_longest_palindromic_subsequence("cbbd") == 2
    >>> find_longest_palindromic_subsequence("abcba") == 5
    >>> find_longest_palindromic_subsequence("") == 0
    >>> find_longest_palindromic_subsequence("a") == 1
    """

    if not s:
        return 0

    n = len(s)
    dp = [[0] * n for _ in range(n)]

    for i in range(n - 1, -1, -1):
        dp[i][i] = 1
        for j in range(i + 1, n):
            if s[i] == s[j]:
                dp[i][j] = dp[i + 1][j - 1] + 2
            else:
                dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])

    return dp[0][n - 1]

    Implement: def find_longest_palindromic_subsequence(s: str) -> int:
               ^^^
SyntaxError: invalid syntax


def max_product_subarray(nums):
    """
    Given an integer array nums, find a contiguous subarray (containing at least one number) which has the largest product and return its product.

    The input array nums can have both positive and negative integers. It's guaranteed that the product of any contiguous subarray is not zero.

    Return the maximum product of a contiguous subarray.

    Examples:
    max_product_subarray([2, 3, -2, 4]) should return 6
    max_product_subarray([-2, 0, -1]) should return 0
    max_product_subarray([-2, 3, -4]) should return 24
    """
    max_product = min_product = result = nums[0]
    for num in nums[1:]:
        max_product, min_product = max(num, max_product * num, min_product * num), min(num, max_product * num, min_product * num)
        result = max(result, max_product)
    return result

# tests

assert max_product_subarray([2, 3, -2, 4]) == 6

assert max_product_subarray([-2, 0, -1]) == 0

assert max_product_subarray([-2, 3, -4]) == 24

block.ive
Assistant
Implement: def max_product_subarray(nums):
    """
    Given an integer array nums, find a contiguous subarray (containing at least one number) which has the largest product and return its product.

    The input array nums can have both positive and negative integers. It's guaranteed that the product of any contiguous subarray is not zero.

    Return the maximum product of a contiguous subarray.

    Examples:
    max_product_subarray([2, 3, -2, 4]) should return 6
    max_product_subarray([-2, 0, -1]) should return 0
    max_product_subarray([-2, 3, -4]) should return 24
    """
    max_product = min_product = result = nums[0]
    for num in nums[1:]:
        max_product, min_product = max(num, max_product * num, min_product * num), min(num, max_product * num, min_product * num)
        result = max(result, max_product)

    Implement: def max_product_subarray(nums):
               ^^^
SyntaxError: invalid syntax

def max_product_subarray(nums):
    max_product = min_product = result = nums[0]
    for num in nums[1:]:
        max_product, min_product = max(num, max_product * num, min_product * num), min(num, max_product * num, min_product * num)
        result = max(result, max_product)
    return result


def max_product_subarray(nums):
    """
    Given an integer array nums, find a contiguous subarray (containing at least one number) which has the largest product and return its product.

    The input array nums can have both positive and negative integers. It's guaranteed that the product of any contiguous subarray is not zero.

    Return the maximum product of a contiguous subarray.

    Examples:
    max_product_subarray([2, 3, -2, 4]) should return 6
    max_product_subarray([-2, 0, -1]) should return 0
    max_product_subarray([-2, 3, -4]) should return 24
    """
    max_product = min_product = result = nums[0]
    for num in nums[1:]:
        max_product, min_product = max(num, max_product * num, min_product * num), min(num, max_product * num, min_product * num)
        result = max(result, max_product)
    return result

# tests

Tests:
assert max_product_subarray([2, 3, -2, 4]) == 6
assert max_product_subarray([-2, 0, -1]) == 0
assert max_product_subarray([-2, 3, -4]) == 24

    Tests:
          ^
SyntaxError: invalid syntax


def find_largest_sum(arr: list, k: int) -> int:
    """Given an array of integers 'arr', and an integer 'k', find the largest sum
    that can be obtained from any k contiguous elements of arr. Handles edge cases such as
    empty array, k > length of array, or k == 1. Consider sorting and hash maps for an efficient solution.
    """
    arr.sort()  # Sort the array
    largest_sum = sum(arr[-k:])  # Sum the k largest numbers
    return largest_sum

# tests

Tests:
assert find_largest_sum([1, 3, -2, 5, 4, -1], 2) == 9
assert find_largest_sum([-3, -1, -2], 1) == -1
assert find_largest_sum([1, 1, 1, 1, 1, 1], 5) == 5

def find_largest_sum(arr: list, k: int) -> int:
    arr.sort()
    return sum(arr[-k:])


def find_largest_even_subarray(arr: list, k: int) -> int:
    """
    Given an array of integers `arr` and an integer `k`, find the largest even number in the subarray formed by keeping at most `k` elements from the beginning and at most `k` elements from the end of the array. Return the largest even number or -1 if none exists. Consider edge cases like empty arrays or no even numbers.

    For example:
    find_largest_even_subarray([10, 20, 30, 5, 4], 1) -> 30
    find_largest_even_subarray([], 0) -> -1
    find_largest_even_subarray([5, 3, 1], 2) -> -1
    """
    max_even = -1
    for i in range(k + 1):
        for j in range(k + 1):
            start = max(0, i)
            end = min(len(arr) - 1, len(arr) - j - 1)
            for num in arr[start:end+1]:
                if num % 2 == 0 and num > max_even:
                    max_even = num
    return max_even

# tests

Tests:
assert find_largest_even_subarray([10, 20, 30, 5, 4], 1) == 30
assert find_largest_even_subarray([], 0) == -1
assert find_largest_even_subarray([5, 3, 1], 2) == -1


def find_max_product_subarray(nums: list) -> int:
    """
    Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product.
    The answer should be non-negative.
    """
    max_product = min_product = result = nums[0]
    for num in nums[1:]:
        if num < 0:
            max_product, min_product = min_product, max_product
        max_product = max(num, max_product * num)
        min_product = min(num, min_product * num)
        result = max(result, max_product)
    return result

# tests

assert find_max_product_subarray([2,3,-2,4]) == 6

assert find_max_product_subarray([-2,0,-1]) == 0

assert find_max_product_subarray([-2]) == -2

block.ive
The Python function implementation for finding the maximum product of a contiguous subarray in an integer array is as follows:

    The Python function implementation for finding the maximum product of a contiguous subarray in an integer array is as follows:
        ^^^^^^
SyntaxError: invalid syntax


def find_substring_indices(string, substring):
    """
    Given a string and a substring, return a list of indices where the substring is found within the string.
    For example, given string='mississippi' and substring='iss', the function should return [1, 4].
    """
    indices = []
    index = string.find(substring)
    while index != -1:
        indices.append(index)
        index = string.find(substring, index + 1)
    return indices

# tests

assert find_substring_indices('mississippi', 'iss') == [1, 4]

assert find_substring_indices('mississippi', 'm') == [0]

assert find_substring_indices('', 'a') == []

block. No text. No explanation. No comment. No question. No blank lines.
def find_substring_indices(string, substring):
    indices = []
    index = string.find(substring)
    while index != -1:
        indices.append(index)
        index = string.find(substring, index + 1)
    return indices

    block. No text. No explanation. No comment. No question. No blank lines.
              ^^^^
SyntaxError: invalid syntax


Implement: def max_sum_subarray_length(nums: list, k: int):
    """Given an array of integers, return the length of the longest subarray with sum equal to k.
    Return 0 if no such subarray exists.
    """
    cumulative_sum = {0: -1}  # Initialize the cumulative sum with 0 at index -1 for edge cases
    max_length = 0
    current_sum = 0

    for i, num in enumerate(nums):
        current_sum += num
        if (current_sum - k) in cumulative_sum:
            max_length = max(max_length, i - cumulative_sum[current_sum - k])
        if current_sum not in cumulative_sum:
            cumulative_sum[current_sum] = i

    return max_length

# tests

Tests:
assert max_sum_subarray_length([1, -1, 5, -2, 3], 3) == 4
assert max_sum_subarray_length([-2, -1, 2, 1], 1) == 2
assert max_sum_subarray_length([2, 1, -3, 4, 1], 10) == 0

    Implement: def max_sum_subarray_length(nums: list, k: int):
               ^^^
SyntaxError: invalid syntax

def max_sum_subarray_length(nums: list, k: int) -> int:
    """Given an array of integers, return the length of the longest subarray with sum equal to k.
    Return 0 if no such subarray exists.
    """
    cumulative_sum = {0: -1}  # Initialize the cumulative sum with 0 at index -1 for edge cases
    max_length = 0
    current_sum = 0

    for i, num in enumerate(nums):
        current_sum += num
        if (current_sum - k) in cumulative_sum:
            max_length = max(max_length, i - cumulative_sum[current_sum - k])
        if current_sum not in cumulative_sum:
            cumulative_sum[current_sum] = i

    return max_length


Implement: def max_sum_subarray_length(nums: list, k: int):
    """Given an array of integers, return the length of the longest subarray with sum equal to k.
    Return 0 if no such subarray exists.
    """
    cumulative_sum = {0: -1}  # Initialize the cumulative sum with 0 at index -1 for edge cases
    max_length = 0
    current_sum = 0

    for i, num in enumerate(nums):
        current_sum += num
        if (current_sum - k) in cumulative_sum:
            max_length = max(max_length, i - cumulative_sum[current_sum - k])
        if current_sum not in cumulative_sum:
            cumulative_sum[current_sum] = i

    return max_length
def max_sum_subarray_length(nums: list, k: int):
    """Given an array of integers, return the length of the longest subarray with sum equal to k.
    Return 0 if no such subarray exists.
    """
    cumulative_sum = {0: -1}  # Initialize the cumulative sum with 0 at index -1 for edge cases
    max_length = 0
    current_sum = 0

    for i, num in enumerate(nums):
        current_sum += num
        if (current_sum - k) in cumulative_sum:
            max_length = max(max_length, i - cumulative_sum[current_sum - k])
        if current_sum not in cumulative_sum:
            cumulative_sum[current_sum] = i

    return max_length


block.ve
veyou
Implement: def find_longest_palindromic_substring(s: str) -> str:
    """Given a string s, return the longest palindromic substring in s. Handle edge cases such as empty strings, single character strings, and the entire string being a palindrome."""
    if len(s) == 0:
        return ""
    longest = s[0]
    for i in range(len(s)):
        for j in range(i+1, len(s)+1):
            substring = s[i:j]
            if substring == substring[::-1] and len(substring) > len(longest):
                longest = substring
    return longest

# tests

Tests:
assert find_longest_palindromic_substring("babad") == "bab" or "aba"
assert find_longest_palindromic_substring("cbbd") == "bb"
assert find_longest_palindromic_substring("") == ""

Output only the function implementation in one

    Implement: def find_longest_palindromic_substring(s: str) -> str:
               ^^^
SyntaxError: invalid syntax


Implement: def longest_non_repeating_substring(s: str) -> str:
    """Return the longest substring without repeating characters in the input string 's'.
    If there are multiple substrings of the same maximum length, return the first one encountered.
    """
    longest = ''
    seen = {}
    start = 0

    for i, char in enumerate(s):
        if char in seen and start <= seen[char]:
            start = seen[char] + 1
        else:
            if (i - start + 1) > len(longest):
                longest = s[start:i+1]
        seen[char] = i

    return longest

# tests

Tests:
assert longest_non_repeating_substring("abcabcbb") == "abc"
assert longest_non_repeating_substring("bbbbb") == "b"
assert longest_non_repeating_substring("pwwkew") == "wke"

    Implement: def longest_non_repeating_substring(s: str) -> str:
               ^^^
SyntaxError: invalid syntax

def longest_non_repeating_substring(s: str) -> str:
    longest = ''
    seen = {}
    start = 0

    for i, char in enumerate(s):
        if char in seen and start <= seen[char]:
            start = seen[char] + 1
        else:
            if (i - start + 1) > len(longest):
                longest = s[start:i+1]
        seen[char] = i

    return longest


Implement: def longest_non_repeating_substring(s: str) -> str:
    """Return the longest substring without repeating characters in the input string 's'.
    If there are multiple substrings of the same maximum length, return the first one encountered.
    """
    longest = ''
    seen = {}
    start = 0

    for i, char in enumerate(s):
        if char in seen and start <= seen[char]:
            start = seen[char] + 1
        else:
            if (i - start + 1) > len(longest):
                longest = s[start:i+1]
        seen[char] = i

    return longest


assert count_unique_char_permutations("aaaaaaaaaa") == 1

block.  # Implement: def count_unique_char_permutations(s: str) -> int:
    """
    Given a string s, find the number of unique permutations of the string that can be formed
    without repeating any characters.

    Note: The result should be computed modulo 10^9 + 7.
    """
    MOD = 10**9 + 7
    fact = 1
    freq = {}
    for ch in s:
        freq[ch] = freq.get(ch, 0) + 1
    n = len(s)
    for i in range(1, n + 1):
        fact = (fact * i) % MOD
    unique_count = 1
    for k, v in freq.items():
        if v > 1:
            for j in range(2, v + 1):
                unique_count = (unique_count * j) % MOD
    return (fact * pow(unique_count, MOD - 2, MOD)) % MOD

# tests

Tests:
assert count_unique_char_permutations("abc") == 6
assert count_unique_char_permutations("aab") == 3


    """
    ^
SyntaxError: unterminated triple-quoted string literal (detected at line 6)


def max_profit_with_cooldown(prices):
    """
    Given a list of daily stock prices, compute the maximum profit that can be made by buying and selling the stock
    once, with a cooldown of 1 day between transactions.
    Return the maximum profit possible. Assume that you cannot perform multiple transactions at once.

    Example:
    - For prices = [1, 2, 3, 0, 2], the output should be 3 (buy on day 1, sell on day 2, buy on day 4, sell on day 5).
    - For prices = [1, 2, 3, 0], the output should be 2 (buy on day 1, sell on day 3).
    """
    if not prices:
        return 0

    n = len(prices)
    buy = [0] * n
    sell = [0] * n
    cooldown = [0] * n

    buy[0] = -prices[0]

    for i in range(1, n):
        buy[i] = max(buy[i - 1], cooldown[i - 1] - prices[i])
        sell[i] = max(sell[i - 1], buy[i - 1] + prices[i])
        cooldown[i] = max(cooldown[i - 1], sell[i - 1])

    return max(sell[-1], cooldown[-1])

# tests

assert max_profit_with_cooldown([1, 2, 3, 0, 2]) == 3

assert max_profit_with_cooldown([1, 2, 3, 0]) == 2

assert max_profit_with_cooldown([1, 2, 2, 2, 1]) == 1

    """
    ^
SyntaxError: unterminated triple-quoted string literal (detected at line 12)


Implement: def find_longest_substring_with_k_distinct_characters(s: str, k: int) -> str:
    """
    Given a string s and an integer k, return the length of the longest substring of s that contains at most k distinct characters.
    """
    from collections import defaultdict

    if len(s) == 0 or k < 1:
        return ""

    char_freq = defaultdict(int)
    start = 0
    max_length = 0
    max_substring = ""

    for end in range(len(s)):
        char_freq[s[end]] += 1

        while len(char_freq) > k:
            char_freq[s[start]] -= 1
            if char_freq[s[start]] == 0:
                del char_freq[s[start]]
            start += 1

        if end - start + 1 > max_length:
            max_length = end - start + 1
            max_substring = s[start:end + 1]

    return max_substring

# tests

Tests:
assert find_longest_substring_with_k_distinct_characters("abcba", 2) == "bcb"
assert find_longest_substring_with_k_distinct_characters("abaccc", 1) == "ccc"
assert find_longest_substring_with_k_distinct_characters("", 3) == ""

    Implement: def find_longest_substring_with_k_distinct_characters(s: str, k: int) -> str:
               ^^^
SyntaxError: invalid syntax


def longest_increasing_subsequence(arr):
    """
    Find the length of the longest strictly increasing subsequence in the given list.
    (Note: A subsequence is a sequence that can be derived from another sequence by deleting some or no elements
    without changing the order of the remaining elements.)

    Args:
    arr: A list of integers

    Returns:
    The length of the longest increasing subsequence.

    Assumptions:
    - The solution should use dynamic programming.

    Edge Cases:
    - An empty array will return 0.
    - An array with all negative elements will still look for the longest increasing subsequence.
    - The function should handle arrays with any combination of duplicates and unique numbers.
    """
    if not arr:
        return 0

    dp = [1] * len(arr)
    for i in range(1, len(arr)):
        for j in range(i):
            if arr[i] > arr[j]:
                dp[i] = max(dp[i], dp[j] + 1)

    return max(dp)

# tests

assert longest_increasing_subsequence([10, 9, 2, 5, 3, 7, 101, 18]) == 4

assert longest_increasing_subsequence([]) == 0

assert longest_increasing_subsequence([-1, -2, -3, -4]) == 1

block only.
def longest_increasing_subsequence(arr):
    """
    Find the length of the longest strictly increasing subsequence in the given list.
    (Note: A subsequence is a sequence that can be derived from another sequence by deleting some or no elements
    without changing the order of the remaining elements.)

    Args:
    arr: A list of integers

    Returns:
    The length of the longest increasing subsequence.

    Assumptions:
    - The solution should use dynamic programming.

    Edge Cases:
    - An empty array will return 0.
    - An array with all negative elements will still look for the longest increasing subsequence.
    - The function should handle arrays with any combination of duplicates and unique numbers.
    """
    if not arr:
        return 0

    dp = [1] * len(arr)
    for i in range(1, len(arr)):
        for j in range(i):
            if arr[i] > arr[j]:
                dp[i] = max(dp[i], dp[j] + 1)

    return max(dp)

    block only.
          ^^^^
SyntaxError: invalid syntax


Implement the function def longest_increasing_subsequence(arr):
def longest_increasing_subsequence(arr):
    if not arr:
        return 0

    dp = [1] * len(arr)
    for i in range(1, len(arr)):
        for j in range(i):
            if arr[i] > arr[j]:
                dp[i] = max(dp[i], dp[j] + 1)

    return max(dp)

    Implement the function def longest_increasing_subsequence(arr):
              ^^^
SyntaxError: invalid syntax


def longest_substring(s: str) -> int:
    """
    Find the length of the longest substring without repeating characters.
    :param s: String to analyze.
    :return: Length of the longest substring.
    """
    if len(s) < 2:
        return len(s)
    char_map = {}
    start = 0
    max_length = 0
    for i, char in enumerate(s):
        if char in char_map and start <= char_map[char]:
            start = char_map[char] + 1
        else:
            max_length = max(max_length, i - start + 1)
        char_map[char] = i
    return max_length

# tests

assert longest_substring("abcabcbb") == 3

    longest_substring(s: str) -> int:
                       ^
SyntaxError: invalid syntax


def find_longest_unique_substring(s: str) -> str:
    """
    Given a string, find the length of the longest substring without repeating characters.
    Return the substring itself.
    """
    n = len(s)
    ans = ""
    ans_len = 0
    for i in range(n):
        # Using hash map to store characters in the current window
        chars_in_window = {}
        tmp = ""
        for j in range(i, n):
            if s[j] in chars_in_window:
                # If a repeating character is found, break the inner loop
                break
            # Add character to the window hash map
            chars_in_window[s[j]] = 1
            # Add character to the temporary substring
            tmp += s[j]
        # Check if the current substring is longer than the previously stored answer
        if len(tmp) > ans_len:
            ans = tmp
            ans_len = len(tmp)
    return ans

# tests

assert find_longest_unique_substring("abcabcbb") == "abc"

assert find_longest_unique_substring("bbbbb") == "b"

assert find_longest_unique_substring("pwwkew") == "wke"

    block. You are an expert Python coder. Output one
               ^^^
SyntaxError: invalid syntax

def find_longest_unique_substring(s: str) -> str:
    n = len(s)
    ans = ""
    ans_len = 0
    for i in range(n):
        chars_in_window = {}
        tmp = ""
        for j in range(i, n):
            if s[j] in chars_in_window:
                break
            chars_in_window[s[j]] = 1
            tmp += s[j]
        if len(tmp) > ans_len:
            ans = tmp
            ans_len = len(tmp)
    return ans


def find_longest_substring_with_k_distinct_chars(s, k):
    """
    Given a string `s` and an integer `k`, find the length of the longest substring that contains at most `k` distinct characters.

    For example:
    - find_longest_substring_with_k_distinct_chars('eceba', 2) should return 3 ('ece' or 'eba')
    - find_longest_substring_with_k_distinct_chars('aa', 1) should return 2 ('aa')
    - find_longest_substring_with_k_distinct_chars('abaccc', 2) should return 4 ('bacc' or 'abac')
    """
    left = 0
    max_length = 0
    char_count = {}

    for right, char in enumerate(s):
        char_count[char] = char_count.get(char, 0) + 1

        while len(char_count) > k:
            char_count[s[left]] -= 1
            if char_count[s[left]] == 0:
                del char_count[s[left]]
            left += 1

        max_length = max(max_length, right - left + 1)

    return max_length

# tests

# Test the function
assert find_longest_substring_with_k_distinct_chars('eceba', 2) == 3
assert find_longest_substring_with_k_distinct_chars('aa', 1) == 2
assert find_longest_substring_with_k_distinct_chars('abaccc', 2) == 4

    assert find_longest_substring_with_k_distinct_chars('eceba', 2) == 3
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
NameError: name 'find_longest_substring_with_k_distinct_chars' is not defined

def find_longest_substring_with_k_distinct_chars(s, k):
    left = 0
    max_length = 0
    char_count = {}

    for right, char in enumerate(s):
        char_count[char] = char_count.get(char, 0) + 1

        while len(char_count) > k:
            char_count[s[left]] -= 1
            if char_count[s[left]] == 0:
                del char_count[s[left]]
            left += 1

        max_length = max(max_length, right - left + 1)

    return max_length


    This is the function that finds the length of the longest substring with at most k distinct characters in the input string.
                ^^^^^^^^
SyntaxError: invalid syntax


def longest_common_subsequence(s1: str, s2: str) -> int:
    """
    Given two strings s1 and s2, find the length of the longest common subsequence.

    The longest common subsequence (LCS) problem is a classic computer science problem
    that is often solved using dynamic programming.

    For example:
    longest_common_subsequence("abcde", "ace") -> 3
    longest_common_subsequence("abc", "def") -> 0
    longest_common_subsequence("", "") -> 0
    """
    m, n = len(s1), len(s2)

    dp = [[0] * (n + 1) for _ in range(m + 1)]

    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if s1[i - 1] == s2[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + 1
            else:
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])

    return dp[m][n]

# tests

assert longest_common_subsequence("abcde", "ace") == 3

assert longest_common_subsequence("abc", "def") == 0

assert longest_common_subsequence("", "") == 0

Implement: def longest_common_subsequence(s1: str, s2: str) -> int:
    """
    Given two strings s1 and s2, find the length of the longest common subsequence.

    The longest common subsequence (LCS) problem is a classic computer science problem
    that is often solved using dynamic programming.

    For example:
    longest_common_subsequence("abcde", "ace") -> 3
    longest_common_subsequence("abc", "def") -> 0
    longest_common_subsequence("", "") -> 0
    """
    m, n = len(s1), len(s2)

    dp = [[0] * (n + 1) for _ in range(m + 1)]

    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if s1[i - 1] == s2[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + 1
            else:
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])

    return dp[m][n]

    Implement: def longest_common_subsequence(s1: str, s2: str) -> int:
               ^^^
SyntaxError: invalid syntax

def longest_common_subsequence(s1: str, s2: str) -> int:
    m, n = len(s1), len(s2)

    dp = [[0] * (n + 1) for _ in range(m + 1)]

    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if s1[i - 1] == s2[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + 1
            else:
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])

    return dp[m][n]


def longest_common_subsequence(s1: str, s2: str) -> int:
    """
    Given two strings s1 and s2, find the length of the longest common subsequence.

    The longest common subsequence (LCS) problem is a classic computer science problem
    that is often solved using dynamic programming.

    For example:
    longest_common_subsequence("abcde", "ace") -> 3
    longest_common_subsequence("abc", "def") -> 0
    longest_common_subsequence("", "") -> 0
    """
    m, n = len(s1), len(s2)

    dp = [[0] * (n + 1) for _ in range(m + 1)]

    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if s1[i - 1] == s2[j - 1]:

File "/tmp/tmpyd1srr14.py", line 21
    assert longest_common_subsequence("abcde", "ace") == 3
IndentationError: expected an indented block after 'if' statement on line 19


def min_swaps_for_sorting(arr: list) -> int:
    """ Given an array arr[] of size N (1 <= N <= 1000), containing non-negative integers not greater than 1000, find the minimum number of swaps required to sort the array in non-decreasing order. Assume that the array is 1-indexed. """
    n = len(arr)
    temp = arr.copy()
    temp.sort()
    ans = 0
    visited = [False] * n
    for i in range(n):
        if visited[i] or arr[i] == temp[i]:
            continue
        cycle_size = 0
        j = i
        while not visited[j]:
            visited[j] = True
            j = arr.index(temp[j])
            cycle_size += 1
        if cycle_size > 0:
            ans += (cycle_size - 1)
    return ans

# tests

assert min_swaps_for_sorting([1, 5, 4, 3, 2]) == 2

assert min_swaps_for_sorting([1, 0, 2]) == 1

assert min_swaps_for_sorting([1, 2, 3, 4, 5]) == 0

    block. You are an expert Python coder.
               ^^^
SyntaxError: invalid syntax


def find_min_in_rotated(nums: list[int]) -> int:
    """
    Given a rotated sorted array of integers (rotated at some pivot unknown to you beforehand), return the minimum element in the array.
    If the array contains duplicates, the function still needs to return the minimum element.
    Assume that the array may be empty and also may contain negative numbers.

    Example:
    find_min_in_rotated([3, 4, 5, 1, 2]) -> 1
    find_min_in_rotated([4, 5, 6, 7, 0, 1, 2]) -> 0
    find_min_in_rotated([2, 3, 4, 5, 6, 7, 8, 1]) -> 1
    find_min_in_rotated([]) -> raises ValueError
    find_min_in_rotated([3, 3, 3]) -> 3
    """
    if not nums:
        raise ValueError("Input array is empty")
    if len(nums) == 1:
        return nums[0]
    left, right = 0, len(nums) - 1
    while left < right:
        mid = (left + right) // 2
        if nums[mid] > nums[right]:
            left = mid + 1
        elif nums[mid] < nums[right]:
            right = mid
        else:
            right -= 1
    return nums[left]

# tests

Tests:
assert find_min_in_rotated([3, 4, 5, 1, 2]) == 1
assert find_min_in_rotated([4, 5, 6, 7, 0, 1, 2]) == 0
assert find_min_in_rotated([2, 3, 4, 5, 6, 7, 8, 1]) == 1
assert find_min_in_rotated([3, 3, 3]) == 3

    Tests:
          ^
SyntaxError: invalid syntax


def find_kth_largest(nums: list, k: int) -> int:
    """Given a list of integers, return the kth largest integer.

    nums - the list of integers
    k - the rank of the value to return
    """

    import heapq
    k_smallest = heapq.nlargest(k, nums)
    return k_smallest[-1]

# tests

def find_kth_largest(nums: list, k: int) -> int:
    """Given a list of integers, return the kth largest integer.

    nums - the list of integers
    k - the rank of the value to return
    """
    return heapq.nlargest(k, nums)[-1]

# tests

assert find_kth_largest([3,2,1,5,6,4], 2) == 5
assert find_kth_largest([3,2,3,1,2,4,5,5,6], 4) == 4
assert find_kth_largest([1], 1) == 1

    return heapq.nlargest(k, nums)[-1]
           ^^^^^
NameError: name 'heapq' is not defined. Did you mean: 'help'?


block only.
Implement: def longest_substring_with_distinct_chars(s: str) -> int:
    """
    Given a string s, find the length of the longest substring without repeating characters.

    For example:
    - In 'abcabcbb', the longest substring is 'abc' with length 3.
    - In 'bbbb', the longest substring is 'b' with length 1.
    - In 'pwwkew', the longest substring is 'wke' or 'kew' with length 3.
    """
    char_index = {}
    max_length = 0
    start = 0

    for end, char in enumerate(s):
        if char in char_index:
            start = max(start, char_index[char] + 1)

        char_index[char] = end
        max_length = max(max_length, end - start + 1)

    return max_length

# tests

Tests:
assert longest_substring_with_distinct_chars('abcabcbb') == 3
assert longest_substring_with_distinct_chars('bbbb') == 1
assert longest_substring_with_distinct_chars('') == 0

Output only the function implementation in one


block.

Assistant: def longest_substring_with_distinct_chars(s: str) -> int:
    """
    Given a string s, find the length of the longest substring without repeating characters.

    For example:
    - In 'abcabcbb', the longest substring is 'abc' with length 3.
    - In 'bbbb', the longest substring is 'b' with length 1.
    - In 'pwwkew', the longest substring is 'wke' or 'kew' with length 3.
    """
    char_index = {}
    max_length = 0
    start = 0

    for end, char in enumerate(s):
        if char in char_index:
            start = max(start, char_index[char] + 1)

        char_index[char] = end
        max_length = max(max_length, end - start + 1)

    return max_length

    block.
          ^
SyntaxError: invalid syntax


def find_longest_increasing_subsequence(arr):
    """Given an array of integers `arr`, return the length of the longest strictly increasing subsequence. A subsequence is a sequence that can be derived from the array by deleting some elements (possibly zero) without changing the order of the remaining elements. It is guaranteed that `arr` will contain at least one element, and all elements are distinct.

    Example:
    - `find_longest_increasing_subsequence([10,9,2,5,3,7,101,18])` should return `4`, as the longest increasing subsequence is [2,3,7,101].

    Constraints:
    - The input array will have at least one element.
    - The elements in the array are distinct.
    """
    n = len(arr)
    lengths = [1] * n
    for i in range(1, n):
        for j in range(i):
            if arr[i] > arr[j] and lengths[i] < lengths[j] + 1:
                lengths[i] = lengths[j] + 1
    return max(lengths)

# tests

assert find_longest_increasing_subsequence([10, 9, 2, 5, 3, 7, 101, 18]) == 4

assert find_longest_increasing_subsequence([3, 4, -1, 0, 6, 2, 3]) == 4

assert find_longest_increasing_subsequence([100]) == 1

def find_longest_increasing_subsequence(arr: List[int]) -> int:
    """
    Given a list of integers `arr`, find the length of the longest strictly increasing subsequence.

    A subsequence is a sequence that can be derived from the array by deleting some elements (possibly zero) without changing the order of the remaining elements.

    The function should return an integer representing the length of the longest increasing subsequence.

    For example, if `arr = [10, 9, 2, 5, 3, 7, 101, 18]`, the function should return 4, as the longest increasing subsequence is [2, 3, 7, 101].

    You can assume that `arr` will have at least one element and all elements are distinct.

    """

    def find_longest_increasing_subsequence(arr: List[int]) -> int:
                                                 ^^^^
NameError: name 'List' is not defined. Did you mean: 'list'?

def find_longest_increasing_subsequence(arr):
    n = len(arr)
    lengths = [1] * n
    for i in range(1, n):
        for j in range(i):
            if arr[i] > arr[j] and lengths[i] < lengths[j] + 1:
                lengths[i] = lengths[j] + 1
    return max(lengths)


def encode_message(message: str, key: int) -> str:
    """
    Takes a string `message` and an integer `key`. Returns a string encoded using a simple Caesar cipher,
    where each character in the message is shifted by the key number of positions in the alphabet.
    Lowercase letters remain lowercase and uppercase letters remain uppercase, with non-alphabetic
    characters unchanged.

    - `message`: A string consisting of alphanumeric characters and spaces.
    - `key`: An integer between -100 and 100, inclusive, determining the shift amount.
    - Returns: A string, the encoded message.
    """
    encoded_message = ""
    for char in message:
        if char.isalpha():
            # Get the ASCII value and shift it by the key
            shifted = ord(char) + key
            # Ensure lowercase remains lowercase and uppercase remains uppercase
            if (char.islower() and shifted > ord('z')) or (char.isupper() and shifted > ord('Z')):
                # Wrap around the alphabet
                shifted = shifted % (ord('a') - 1) + ord('a') if char.islower() else shifted % (ord('A') - 1) + ord('A')
            encoded_message += chr(shifted)
        else:
            # Non-alphabetic characters remain the same
            encoded_message += char
    return encoded_message

# tests

assert encode_message("Hello, World!", 3) == "Khoor, Zruog!"

assert encode_message("Khoor, Zruog!", -3) == "Hello, World!"

    >>> encode_message("Hello, World!", 3)
    ^^
SyntaxError: invalid syntax

def encode_message(message: str, key: int) -> str:
    encoded_message = ""
    for char in message:
        if char.isalpha():
            shifted = ord(char) + key
            if (char.islower() and shifted > ord('z')) or (char.isupper() and shifted > ord('Z')):
                shifted = shifted % (ord('a') - 1) + ord('a') if char.islower() else shifted % (ord('A') - 1) + ord('A')
            encoded_message += chr(shifted)
        else:
            encoded_message += char
    return encoded_message


block only.
Implement: def encode_message(message: str, key: int) -> str:
    """
    Takes a string `message` and an integer `key`. Returns a string encoded using a simple Caesar cipher,
    where each character in the message is shifted by the key number of positions in the alphabet.
    Lowercase letters remain lowercase and uppercase letters remain uppercase, with non-alphabetic
    characters unchanged.

    - `message`: A string consisting of alphanumeric characters and spaces.
    - `key`: An integer between -100 and 100, inclusive, determining the shift amount.
    - Returns: A string, the encoded message.
    """
    encoded_message = ""
    for char in message:
        if char.isalpha():
            # Get the ASCII value and shift it by the key
            shifted = ord(char) + key
            # Ensure lowercase remains lowercase and uppercase remains uppercase
            if (char.islower() and shifted > ord('z')) or (char.isupper() and shifted > ord('Z')):
                # Wrap around the alphabet
                shifted = shifted % (ord('a') - 1) + ord('a') if char.islower() else shifted % (ord('A') - 1) + ord('A')
            encoded_message += chr(shifted)
        else:
            # Non-alphabetic characters remain the same
            encoded_message += char
    return encoded_message

# tests
assert encode_message("Hello, World!", 3) == "Khoor, Zruog!"
assert encode_message("Khoor, Zruog!", -3) == "Hello, World!"
assert encode_message("1234567890!@#$%^&*()_+", 100) == "1234567890!@#$%^&*()_+"


def is_fibonacci_number(n: int) -> bool:
    """
    Checks if a given number is a Fibonacci number.

    Parameters:
    - n: int - The number to check.

    Returns:
    - bool: True if the number is a Fibonacci number, False otherwise.
    """
    if n == 0 or n == 1:
        return True
    a, b = 0, 1
    while b < n:
        a, b = b, a + b
    return b == n

# tests

assert is_fibonacci_number(0) == True
assert is_fibonacci_number(8) == True
assert is_fibonacci_number(14) == False

block only.

Here is the implementation of the `is_fibonacci_number` function as requested:


def longest_consecutive_subsequence(nums: list) -> int:
    """
    Given an unsorted array of integers `nums`, find the length of the longest consecutive elements sequence.

    For example, given [100, 4, 200, 1, 3, 2], the longest consecutive sequence is [1, 2, 3, 4] with length 4.

    The algorithm should handle empty input and duplicates gracefully.

    :param nums: list of integers
    :return: length of the longest consecutive subsequence
    """
    num_set = set(nums)  # Use a set to allow O(1) lookups.
    longest_streak = 0

    for num in num_set:
        # This is not the start of a sequence.
        if num - 1 in num_set:
            continue
        current_num = num
        current_streak = 1

        while current_num + 1 in num_set:
            current_num += 1
            current_streak += 1

        longest_streak = max(longest_streak, current_streak)

    return longest_streak

# tests

assert longest_consecutive_subsequence([]) == 0

assert longest_consecutive_subsequence([100, 4, 200, 1, 3, 2]) == 4

assert longest_consecutive_subsequence([0, 3, 7, 2, 5, 8, 4, 6, 0, 1]) == 9

    block as requested.
          ^^
SyntaxError: invalid syntax

from typing import List

def longest_consecutive_subsequence(nums: List[int]) -> int:
    num_set = set(nums)  # Use a set to allow O(1) lookups.
    longest_streak = 0

    for num in num_set:
        # This is not the start of a sequence.
        if num - 1 in num_set:
            continue
        current_num = num
        current_streak = 1

        while current_num + 1 in num_set:
            current_num += 1
            current_streak += 1

        longest_streak = max(longest_streak, current_streak)

    return longest_streak


Implement: def longest_consecutive_subsequence(nums: list) -> int:
    """
    Given an unsorted array of integers `nums`, find the length of the longest consecutive elements sequence.

    For example, given [100, 4, 200, 1, 3, 2], the longest consecutive sequence is [1, 2, 3, 4] with length 4.

    The algorithm should handle empty input and duplicates gracefully.

    :param nums: list of integers
    :return: length of the longest consecutive subsequence
    """
    num_set = set(nums)  # Use a set to allow O(1) lookups.
    longest_streak = 0

    for num in num_set:
        # This is not the start of a sequence.
        if num - 1 in num_set:
            continue
        current_num = num
        current_streak = 1

        while current_num + 1 in num_set:
            current_num += 1
            current_streak += 1

        longest_streak = max(longest_streak, current_streak)

    return longest_streak

# tests

Tests:
assert longest_consecutive_subsequence([]) == 0
assert longest_consecutive_subsequence([100, 4, 200, 1, 3, 2]) == 4
assert longest_consecutive_subsequence([0, 3, 7, 2, 5, 8, 4, 6, 0, 1]) == 9

    Implement: def longest_consecutive_subsequence(nums: list) -> int:
               ^^^
SyntaxError: invalid syntax


def maximum_non_adjacent_sum(nums: list[int]) -> int:
    """
    Given an integer array nums, return the maximum sum of non-adjacent elements in nums.

    Example:
    - maximum_non_adjacent_sum([2, 1, 5, 8, 4]) should return 11 (5 + 8)
    - maximum_non_adjacent_sum([-2, -1, -5, -8, -4]) should return 0 (no non-adjacent sum is possible)
    - maximum_non_adjacent_sum([2, 1, 5, 1, 3, 2]) should return 10 (2 + 5 + 3)
    """
    incl = 0
    excl = 0

    for i in nums:
        new_excl = max(incl, excl)
        incl = excl + i
        excl = new_excl
    return max(incl, excl)

# tests

assert maximum_non_adjacent_sum([2, 1, 5, 8, 4]) == 11

assert maximum_non_adjacent_sum([-2, -1, -5, -8, -4]) == 0

assert maximum_non_adjacent_sum([2, 1, 5, 1, 3, 2]) == 10

Implement: def maximum_non_adjacent_sum(nums: list[int]) -> int:
    """
    Given an integer array nums, return the maximum sum of non-adjacent elements in nums.

    Example:
    - maximum_non_adjacent_sum([2, 1, 5, 8, 4]) should return 11 (5 + 8)
    - maximum_non_adjacent_sum([-2, -1, -5, -8, -4]) should return 0 (no non-adjacent sum is possible)
    - maximum_non_adjacent_sum([2, 1, 5, 1, 3, 2]) should return 10 (2 + 5 + 3)
    """
    incl = 0
    excl = 0

    for i in nums:
        new_excl = max(incl, excl)
        incl = excl + i
        excl = new_excl
    return max(incl, excl)

    Implement: def maximum_non_adjacent_sum(nums: list[int]) -> int:
               ^^^
SyntaxError: invalid syntax

def maximum_non_adjacent_sum(nums: list[int]) -> int:
    incl = 0
    excl = 0

    for i in nums:
        new_excl = max(incl, excl)
        incl = excl + i
        excl = new_excl
    return max(incl, excl)


block.``python
def maximum_non_adjacent_sum(nums: list[int]) -> int:
    """
    Given an integer array nums, return the maximum sum of non-adjacent elements in nums.

    Example:
    - maximum_non_adjacent_sum([2, 1, 5, 8, 4]) should return 11 (5 + 8)
    - maximum_non_adjacent_sum([-2, -1, -5, -8, -4]) should return 0 (no non-adjacent sum is possible)
    - maximum_non_adjacent_sum([2, 1, 5, 1, 3, 2]) should return 10 (2 + 5 + 3)
    """
    incl = 0
    excl = 0

    for i in nums:
        new_excl = max(incl, excl)
        incl = excl + i
        excl = new_excl
    return

    block.``python
          ^
SyntaxError: invalid syntax