Learner Level

Implement the lastIndexOfTarget method that returns the last index where the target value appears.

The input contains an integer array nums, its length size, and an integer target. Your task is to return the last index where target appears in the array.

If the target appears multiple times, return the rightmost occurrence. If it does not appear, return -1. For example, in [2,5,2,7,2], the last index of 2 is 4.

Example 1
Input:
nums (int[]) = [2,5,2,7,2]
size (int) = 5
target (int) = 2
Return:
(int) 4
Example 2
Input:
nums (int[]) = [1,3,5]
size (int) = 3
target (int) = 9
Return:
(int) -1
Example 3
Input:
nums (int[]) = [6]
size (int) = 1
target (int) = 6
Return:
(int) 0

Search from the end of the array because the required answer is the last occurrence.

Start at index size - 1 and move backward. The first match found from the right side is the last index of the target, so return it immediately. If no match is found, return -1.

Pseudocode:

function lastIndexOfTarget(nums, size, target):
    for i from size - 1 down to 0:
        if nums[i] == target:
            return i
    return -1
Run your code to see the result.