Last Element in Range
Given an array of N integers and Q queries. For each query, you are given two integers L and R (0-indexed, inclusive). Your task is to find the index of the last occurrence of the element A[L] within the subarray A[L...R]. If A[L] does not appear in the range A[L...R] other than at index L, output L. If the array A is empty or the range is invalid, this case will not occur based on constraints.
Input
The first line contains an integer N, the size of the array. The second line contains N space-separated integers A_1, A_2, ..., A_N representing the array. The third line contains an integer Q, the number of queries. Each of the next Q lines contains two space-separated integers L and R.
Output
For each query, print the index of the last occurrence of A[L] in the range A[L...R] on a new line. The indices are 0-based.
Constraints
1 <= N <= 1000 0 <= Q <= 1000 0 <= L <= R < N -10^9 <= A_i <= 10^9
Example 1
5 1 2 1 3 1 3 0 4 1 3 2 2
4 1 2
Query 1: A[0]=1. Last 1 in A[0..4] is at index 4. Query 2: A[1]=2. Last 2 in A[1..3] is at index 1. Query 3: A[2]=1. Last 1 in A[2..2] is at index 2.
Example 2
7 5 5 5 5 5 5 5 2 0 6 1 4
6 4
Query 1: A[0]=5. Last 5 in A[0..6] is at index 6. Query 2: A[1]=5. Last 5 in A[1..4] is at index 4.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
5 1 2 1 3 1 3 0 4 1 3 2 2
7 5 5 5 5 5 5 5 2 0 6 1 4