Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Last Occurrence Of An Element

Easy Acceptance 65.00% Points 20.00

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.

Hints
Hint 1
N/A
Constraints
  • 1=N=105
  • -109 < arr[i] < 109
Companies
Microsoft Samsung Wipro Media.net
Topics
Recursion
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions