Bootcamps
Masterclasses
Menu
Courses
Account
Login / Sign Up

Last Occurrence Of An Element

Easy Acceptance 65% Points 20

You are given an array of integers and a target value x. Your task is to find the last occurrence of x in the array using recursion only. Loops are not allowed.

Return the 0-based index of the last occurrence if the element is present. If the element does not exist in the array, return -1.

Examples
Example 1

Example 1

Input: arr[] = [ 5 8 4 5 9 9 7], x = 9

Output: 5

Explanation: Since the array is 5 8 4 5 9 9 7 and the target element is 9, the last occurrence of 9 appears at index 5.

Example 2

Example 2

Input: arr[] = [ 9 6 5 4], x = 1

Output: -1

Explanation: Since the array does not contain the target element 1, there is no occurrence of it, so we return -1.

Constraints
  • 1=N=105
  • -109 < arr[i] < 109
Topics
Recursion
Companies
Microsoft Samsung Wipro Media.net
Added 19 Jul 2026 65% acceptance
Ln 1, Col 1Sign in to save your code
1 2 3 2 5
2
3