Appearance
question:# Coding Assessment Question **Scenario**: You are a software engineer tasked with analyzing the transactions of an e-commerce platform. One key metric is the average transaction value during a given day. Given a list of transactions that include timestamps and values, you must compute the average transaction value for transactions that occurred within a specified range of time on that day. **Task**: Implement a Python function `average_transaction_value` that computes the average value of transactions occurring within a specified time window on a given day. **Function Signature**: ```python from typing import List, Tuple def average_transaction_value( transactions: List[Tuple[str, float]], start_time: str, end_time: str ) -> float: Compute the average value of transactions within a specified time range. Parameters: - transactions (List[Tuple[str, float]]): A list of tuples where each tuple consists of a timestamp and a transaction value. Timestamp is formatted as 'HH:MM' (24-hour format). - start_time (str): Start of the time range in 'HH:MM' format. - end_time (str): End of the time range in 'HH:MM' format. Returns: - float: The average transaction value within the specified time range. Exceptions: - Raise ValueError if start_time or end_time is not in the 'HH:MM' format. - Raise ValueError if start_time is after end_time. - Return 0.0 if there are no transactions in the specified time range. pass ``` **Constraints**: - Ensure that `start_time` and `end_time` follow the 'HH:MM' format and valid time values. - The list of transactions can have a length up to 10^6. - Each transaction value is a positive float. - The transaction timestamps are ordered, and all transactions are from the same day. **Performance Requirements**: - The function should run in O(n) time, where n is the length of the transactions list. **Examples**: ```python >>> transactions = [("09:15", 150.0), ("10:30", 200.0), ("11:45", 50.0), ("13:00", 100.0)] >>> start_time = "10:00" >>> end_time = "12:00" >>> average_transaction_value(transactions, start_time, end_time) 125.0 >>> transactions = [("08:00", 80.0), ("08:30", 120.0), ("09:00", 50.0)] >>> start_time = "07:00" >>> end_time = "08:30" >>> average_transaction_value(transactions, start_time, end_time) 100.0 >>> transactions = [("09:00", 75.0), ("10:00", 50.0), ("11:00", 30.0)] >>> start_time = "12:00" >>> end_time = "13:00" >>> average_transaction_value(transactions, start_time, end_time) 0.0 >>> transactions = [("09:00", 75.0), ("10:00", 50.0), ("11:00", 30.0)] >>> start_time = "11:00" >>> end_time = "10:00" >>> average_transaction_value(transactions, start_time, end_time) Traceback (most recent call last): ... ValueError: start_time must be before end_time ```
answer:from typing import List, Tuple def average_transaction_value( transactions: List[Tuple[str, float]], start_time: str, end_time: str ) -> float: Compute the average value of transactions within a specified time range. Parameters: - transactions (List[Tuple[str, float]]): A list of tuples where each tuple consists of a timestamp and a transaction value. Timestamp is formatted as 'HH:MM' (24-hour format). - start_time (str): Start of the time range in 'HH:MM' format. - end_time (str): End of the time range in 'HH:MM' format. Returns: - float: The average transaction value within the specified time range. Exceptions: - Raise ValueError if start_time or end_time is not in the 'HH:MM' format. - Raise ValueError if start_time is after end_time. - Return 0.0 if there are no transactions in the specified time range. import re # Validate time format time_pattern = re.compile(r"^d{2}:d{2}") if not (time_pattern.match(start_time) and time_pattern.match(end_time)): raise ValueError("start_time and end_time must be in 'HH:MM' format") start_hour, start_minute = map(int, start_time.split(':')) end_hour, end_minute = map(int, end_time.split(':')) # Validate time range if (start_hour, start_minute) > (end_hour, end_minute): raise ValueError("start_time must be before end_time") # Function to convert time string to minutes since midnight def time_to_minutes(time_str: str) -> int: hour, minute = map(int, time_str.split(':')) return hour * 60 + minute start_minutes = time_to_minutes(start_time) end_minutes = time_to_minutes(end_time) # Filter transactions within the specified time range total_value = 0.0 count = 0 for timestamp, value in transactions: transaction_minutes = time_to_minutes(timestamp) if start_minutes <= transaction_minutes <= end_minutes: total_value += value count += 1 if count == 0: return 0.0 return total_value / count
question:# Coding Assessment Question Problem Statement You have been given a `2d` list of integers representing different elevations on a map. Your task is to write a function that finds the highest peak and the lowest valley in the map, then returns the absolute difference between them. Requirements * **Function Signature**: ```python def elevation_difference(elevation_map: list[list[int]]) -> int: ``` * **Input**: * A `2d` list of integers `elevation_map` where 1 <= len(elevation_map) <= 100 and 1 <= len(elevation_map[0]) <= 100, and -10^3 <= elevation_map[i][j] <= 10^3. * **Output**: * An integer representing the absolute difference between the highest peak and the lowest valley. Constraints * The function should find the highest peak and the lowest valley in the `2d` list. * You must traverse the entire `2d` list to ensure all elevations are considered. Example ```python >>> elevation_difference([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) 8 >>> elevation_difference([[10, -1, 2], [3, 0, 5], [-2, 8, 7]]) 12 >>> elevation_difference([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) 0 ``` Explanation 1. Iterate through the `2d` list to find the highest and lowest values. 2. Calculate the absolute difference between these two values. 3. Return the computed absolute difference. Edge Cases to Consider 1. A `2d` list with a single element. 2. A `2d` list where all elements are the same. 3. A `2d` list with maximum values of all positive or negative numbers. Implement the function `elevation_difference` according to the specifications above and ensure it passes all the given test cases.
answer:def elevation_difference(elevation_map: list[list[int]]) -> int: This function takes a 2D list of integers representing elevations on a map, and returns the absolute difference between the highest peak and the lowest valley. # Initialize the highest and lowest values with extreme opposites highest_peak = float('-inf') lowest_valley = float('inf') # Traverse the entire 2D list to find the highest peak and lowest valley for row in elevation_map: for elevation in row: if elevation > highest_peak: highest_peak = elevation if elevation < lowest_valley: lowest_valley = elevation # Calculate the absolute difference difference = abs(highest_peak - lowest_valley) return difference
question:# Problem Statement Given a matrix of integers where each row is sorted in non-decreasing order, and an integer target, implement a function to determine if the target integer exists in the matrix. If the target integer is found, return its position as a tuple (row index, column index); otherwise, return (-1, -1). # Function Signature ```python def search_matrix(matrix: list[list[int]], target: int) -> tuple[int, int]: ``` # Input 1. `matrix` (list of list of int): A 2D list where each row is sorted in non-decreasing order. 2. `target` (int): The target integer to search for. # Output * `tuple[int, int]`: A tuple containing the row and column indices of the target integer in the matrix, or (-1, -1) if the target is not found. # Constraints * The number of rows ((R)) and columns ((C)) in the matrix can be up to (10^3). * The value of each integer in the matrix will be between (-10^6) and (10^6). * The matrix is guaranteed to have at least one row and one column. # Requirements * Your solution should have a time complexity of (O(R + C)), where (R) is the number of rows and (C) is the number of columns. * The space complexity should be (O(1)). # Example ```python matrix = [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ] assert search_matrix(matrix, 5) == (1, 1) assert search_matrix(matrix, 20) == (-1, -1) assert search_matrix(matrix, 15) == (0, 4) assert search_matrix(matrix, 1) == (0, 0) assert search_matrix(matrix, 30) == (4, 4) ``` Consider carefully edge cases such as the target being the first or last element in the matrix. Optimize performance to handle the maximum constraints efficiently. # Hints * Start searching from the top-right corner of the matrix. * Use the properties of the sorted rows and columns to eliminate half of the search space with each step.
answer:def search_matrix(matrix, target): Search the matrix for the target value. Parameters: matrix (list of list of int): A 2D list where each row is sorted in non-decreasing order. target (int): The target integer to search for. Returns: tuple (int, int): The position of the target as a tuple (row index, column index) or (-1, -1) if the target is not found. if not matrix: return -1, -1 rows, cols = len(matrix), len(matrix[0]) row, col = 0, cols - 1 while row < rows and col >= 0: if matrix[row][col] == target: return row, col elif matrix[row][col] > target: col -= 1 else: row += 1 return -1, -1
question:Find the Shortest Subarray with Sum at Least K Context Given an integer array, sometimes it is necessary to find the shortest subarray whose sum is at least a given integer value K. This has applications in multiple domains like finance, where one might need to track the shortest period within which a certain profit threshold is achieved. Task You are to write a function `shortest_subarray_with_sum_at_least_k(arr: List[int], k: int) -> int`, which computes the length of the shortest subarray that has a sum at least `k`. If there is no such subarray, return -1. Function Signature ```python from typing import List def shortest_subarray_with_sum_at_least_k(arr: List[int], k: int) -> int: ... ``` Input 1. `arr` (List[int]): A list of integers. 2. `k` (int): The required subarray sum threshold. Output An integer representing the length of the shortest subarray with a sum of at least `k`. Return -1 if no such subarray exists. Constraints 1. The length of the array `0 <= len(arr) <= 10^5` 2. The elements of the array are integers, and their absolute value does not exceed 10000. 3. `1 <= k <= 10^9` Examples ```python # A straightforward case where the subarray of sufficient sum is easily found print(shortest_subarray_with_sum_at_least_k([2, 3, 1, 2, 4, 3], 7)) # 2 (subarray [4, 3]) # Subarray exists at the start print(shortest_subarray_with_sum_at_least_k([1, 1, 1, 1, 1, 10], 10)) # 1 (subarray [10]) # The entire array sums to less than k print(shortest_subarray_with_sum_at_least_k([1, 2, 3], 7)) # -1 # A case where there are multiple valid subarrays print(shortest_subarray_with_sum_at_least_k([1, 2, 3, 4], 6)) # 2 (subarray [2, 4] or [3, 3]) # Large k with sporadic elements print(shortest_subarray_with_sum_at_least_k([1000, -1, 2, -1, 1000, -1000], 1001)) # 3 (subarray [1000, -1, 2]) ```
answer:from typing import List import collections def shortest_subarray_with_sum_at_least_k(arr: List[int], k: int) -> int: n = len(arr) prefix_sum = [0] * (n + 1) for i in range(n): prefix_sum[i + 1] = prefix_sum[i] + arr[i] deq = collections.deque() min_len = float('inf') for i in range(n + 1): while deq and prefix_sum[i] - prefix_sum[deq[0]] >= k: min_len = min(min_len, i - deq.popleft()) while deq and prefix_sum[i] <= prefix_sum[deq[-1]]: deq.pop() deq.append(i) return min_len if min_len != float('inf') else -1