0 out of 464 challenges solved
Write a Python function `last_position(arr, x)` that takes a sorted array `arr` and an integer `x` as input and returns the last position (0-based index) of the element `x` in the array. If the element is not present, return `-1`. The function should use an efficient approach, such as binary search, to achieve a time complexity of O(log n). #### Example Usage ```python [main.nopy] print(last_position([1, 2, 2, 2, 3], 2)) # Output: 3 print(last_position([1, 2, 3, 4, 5], 6)) # Output: -1 print(last_position([1, 1, 1, 1, 1], 1)) # Output: 4 ``` #### Constraints - The input array `arr` is sorted in non-decreasing order. - The array can contain duplicate elements. - The function should handle empty arrays gracefully.
def last_position(arr, x): """ Find the last position of x in a sorted array arr. Parameters: arr (list): A sorted list of integers. x (int): The target integer to find. Returns: int: The last position of x in arr, or -1 if x is not found. """ # Implement the function using binary search pass