Bootcamps
Masterclasses
Menu
Courses
Account
Login / Sign Up

First Occurrence Of An Element In An Array

Easy Acceptance 75% Points 20

You are given an array of integers and a target element x. Your task is to find the index of the first occurrence of x in the array using recursion only. You are not allowed to use any loops.

If the element exists, return its index (0-based). If it is not present in the array, return -1.

Examples
Example 1

Example 1

Input: arr[] = [ 1 4 5 8 3 5], x = 5

Output: 2

Explanation: Since the array is 1 4 5 8 3 5 and the target element is 5, the first occurrence of 5 appears at index 2 (0-based indexing).

Example 2

Example 2

Input: arr[] = [ 4 8 9 6], 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 Media.net
Added 19 Jul 2026 75% acceptance
Ln 1, Col 1Sign in to save your code
1 2 3 4 5 
3
2