The function can be implemented using a binary search algorithm. Given a sorted array of elements arr of length n. Given the target element x for which we want to find the last occurrence in the array and return its position. The last occurrence of the target element x can be determined as follows: First initialize the bottom border to 0, i.e. low = 0, and the top border to n - 1, i.e. high = n-1, to track the left and right ends of the current search interval. By the end of the loop, if we did not find the target value, the function returns -1. Then enter the loop and repeatedly divide the search interval in half to find the part of the array that  contains the element x. This can be accomplished by adding the bottom and top border of  the current search interval and dividing the sum by 2 using the floor division operator, i.e. mid = (low + high) // 2. Now compare the value at mid with the target. If  the value at mid is greater than the target x, then we need to search the last occurrence in the left part because all the values in the right part are less than the target.  Update the top border, i.e.  high= mid - 1. Else, if  the value at mid is less than the target x, then we need to search for the first occurrence in the right part and update the bottom border, i.e. low = mid +1. Else the value at mid is the target element and the bottom border is updated, i.e. low=mid+1. The loop ends when the bottom border is greater than the top border, i.e. low > high.