734. Last Occurrence of Element in Array

EasyRecursionRecursion

Given an integer array nums and an integer target, return the index of the LAST occurrence of target in nums, or -1 if it does not appear. The array may contain duplicates. You must implement the search recursively. A natural approach is to recurse from index n-1 down to 0, returning the first match found.

Input: An integer array nums and an integer target.

Output: Return an integer: the largest index where target appears, or -1.

Examples

Example 1
Input: [1,2,3,2,1], 2
Output: 3
Explanation: The last 2 is at index 3.
Example 2
Input: [5,5,5,5], 5
Output: 3
Explanation: Last index of the array.
Example 3
Input: [1,2,3], 4
Output: -1
Explanation: 4 is not present.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →