Appearance
question:# Coding Exercise: Implement Enhanced Radix Sort Context You have been tasked with sorting a large list of non-negative integers efficiently. The existing sorting algorithms are either too slow for large inputs or not well-suited for integers with a variable number of digits. Radix sort, with its digit-centric approach, presents an optimal solution for this problem. Task Implement an enhanced version of the Radix Sort that sorts a list of non-negative integers. Your implementation should handle edge cases efficiently and minimize memory usage where possible. Constraints - Input will always be a list of non-negative integers. - The list can be of length up to (10^5). - Each integer in the list will have at most (6) digits. Function Signature ```python def enhanced_radix_sort(arr: List[int]) -> List[int]: ``` Input - `arr`: A list of non-negative integers to be sorted. Output - A list of integers sorted in ascending order. Requirements - Achieve time complexity of O(nk), where (n) is the number of integers and (k) is the maximum number of digits in any integer. - Minimize space complexity where possible. Example ```python # Example 1 input_list = [170, 45, 75, 90, 802, 24, 2, 66] print(enhanced_radix_sort(input_list)) # Output: [2, 24, 45, 66, 75, 90, 170, 802] # Example 2 input_list = [333, 3, 5555, 55, 5] print(enhanced_radix_sort(input_list)) # Output: [3, 5, 55, 333, 5555] # Example 3 input_list = [0, 10, 200, 3000] print(enhanced_radix_sort(input_list)) # Output: [0, 10, 200, 3000] ``` Additional Constraints - Do not use built-in sorting functions. - Handle optimizations to reduce unnecessary memory usage. - Include error handling for unusual cases cleanly.
answer:def enhanced_radix_sort(arr): Sorts a list of non-negative integers using Radix Sort. :param arr: List of non-negative integers :return: List of integers sorted in ascending order if len(arr) == 0: return arr max_num = max(arr) exp = 1 while max_num // exp > 0: counting_sort(arr, exp) exp *= 10 return arr def counting_sort(arr, exp): A utility function to perform counting sort on arr[] using digit at place exp :param arr: List of non-negative integers :param exp: Current digit's place (1, 10, 100, ...) n = len(arr) output = [0] * n count = [0] * 10 # Since the digits are 0 to 9 # Store count of occurrences in count[] for i in range(n): index = (arr[i] // exp) % 10 count[index] += 1 # Change count[i] so that count[i] now contains actual position of this digit in output[] for i in range(1, 10): count[i] += count[i - 1] # Build the output array i = n - 1 while i >= 0: index = (arr[i] // exp) % 10 output[count[index] - 1] = arr[i] count[index] -= 1 i -= 1 # Copying the output array to arr[], so that arr now contains sorted numbers according to current digit for i in range(n): arr[i] = output[i]
question:# Problem: Optimal Value Packing Context You are designing a utility for a shipping company that helps optimize the packing of high-value items into fixed-capacity crates to maximize the total value while not exceeding the given weight capacity of the crate. The problem is a variation of the well-known 0/1 Knapsack Problem. Task Given: - A list of items, each defined by its value and weight. - A fixed capacity of the crate. Write a Python function `optimal_value_packing` that determines and returns the maximum possible value that can be obtained by selecting items without exceeding the crate's weight capacity. Input - A list of tuples, `items`, where each tuple `(value, weight)` represents the value and weight of an item. - An integer `capacity` representing the maximum weight capacity of the crate. Output - An integer representing the maximum total value achievable. Constraints - `1 <= len(items) <= 100` (number of items) - `0 <= capacity <= 1000` (crate's capacity) - `1 <= value, weight <= 1000` (values and weights of items) Example ```python # Example 1 items = [(60, 10), (100, 20), (120, 30)] capacity = 50 print(optimal_value_packing(items, capacity)) # Output: 220 # Example 2 items = [(60, 5), (50, 3), (70, 4), (30, 2)] capacity = 5 print(optimal_value_packing(items, capacity)) # Output: 80 ``` Notes Implement the function efficiently keeping in mind the provided constraints. Edge cases mentioned in the analysis are relevant, such as items with zero value or weight, and scenarios with zero capacity.
answer:def optimal_value_packing(items, capacity): Determine the maximum value achievable without exceeding the weight capacity of the crate. Args: items (list of tuples): Each tuple (value, weight) represents the value and weight of an item. capacity (int): The maximum weight capacity of the crate. Returns: int: The maximum total value achievable. # Define DP array where dp[w] will store the maximum value for capacity w dp = [0] * (capacity + 1) # Iterate through the items for value, weight in items: # Update the dp array in a reversed order to prevent overwriting values for w in range(capacity, weight - 1, -1): dp[w] = max(dp[w], dp[w - weight] + value) return dp[capacity]
question:# Problem: Detecting and Removing Loop in a Linked List You are given a singly linked list, which might contain a loop. Your task is to detect the presence of a loop and remove it if it exists. Write a function `detect_and_remove_loop(head)` that accomplishes this. # Function Signature ```python def detect_and_remove_loop(head: Node) -> None: ``` # Input * `head`: The head node of the singly linked list. - Each node has a `.val` attribute storing an integer value. - Each node has a `.next` attribute pointing to the next node or `None`. # Output * Modify the linked list, so any existing loop is removed. * If there is no loop in the list, the list remains unmodified. # Constraints * Do not use any extra space (O(1) space complexity). * Solve the problem in linear time (O(N) time complexity). # Example 1. Given the following linked list (Note: 2 -> 3 -> 4 creates a loop back to 2): ``` 1 -> 2 -> 3 -> 4 -> 2 ``` After calling `detect_and_remove_loop(head)`, the linked list should be: ``` 1 -> 2 -> 3 -> 4 -> None ``` # Guidelines * Detecting a loop can be done using Floyd’s Cycle-Finding Algorithm (also known as hare and tortoise algorithm). * After detecting the loop, you need to find the starting point of the loop and set the `.next` of the loop's last node to `None`.
answer:class Node: def __init__(self, val=0, next=None): self.val = val self.next = next def detect_and_remove_loop(head: Node) -> None: if not head or not head.next: return slow = head fast = head # Step 1: Detect loop using Floyd’s Cycle-Finding Algorithm while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: break # If no loop detected, return if slow != fast: return # Step 2: Find the start of the loop slow = head while slow != fast: slow = slow.next fast = fast.next # Step 3: Remove the loop # To remove the loop, we need to find the node just before the start of the loop loop_start = slow while fast.next != loop_start: fast = fast.next fast.next = None
question:You are tasked with implementing an enhanced version of an anagram checker. This version should be versatile, handling various edge cases and supporting characters beyond lowercase English letters. Problem Scenario: Your friend, a book store manager, needs a tool that can verify if two given book titles are anagrams, regardless of capitalization and including punctuation. Write a function that checks if two strings (titles) are anagrams of each other considering any kind of characters. The function should ignore spaces and capitalization. Function Signature: ```python def are_anagrams(title1: str, title2: str) -> bool: ``` Input: * `title1` (str): The first book title to compare. * `title2` (str): The second book title to compare. Output: * `bool`: Returns `True` if `title1` and `title2` are anagrams of each other, `False` otherwise. Constraints: * The function should handle special characters, spaces, and capitalization correctly. * The function should run efficiently even for longer titles (up to 1000 characters). Example: ```python assert are_anagrams("The Eyes", "They See") == True assert are_anagrams("Hello, World!", "dlroW ,olleH") == True assert are_anagrams("Astronomers", "No more stars") == True assert are_anagrams("Hello", "Hi") == False ``` Note: To design an efficient solution, consider using dictionaries or collections to manage character counts for any character, and pay attention to case insensitivity and ignoring spaces/punctuation.
answer:import string def are_anagrams(title1: str, title2: str) -> bool: Check if two book titles are anagrams of each other, ignoring spaces, punctuation, and case. def clean_string(s: str) -> str: return ''.join(c.lower() for c in s if c in string.ascii_letters) cleaned_title1 = clean_string(title1) cleaned_title2 = clean_string(title2) return sorted(cleaned_title1) == sorted(cleaned_title2)