Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

First Occurrence Of An Element In An Array

Easy Acceptance 75.00% Points 20.00

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.

Hints
Hint 1
N/A
Constraints
  • 1<N<105
  • -109 < arr[i] < 109
Companies
Microsoft Samsung 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