Bootcamps
Masterclasses
Menu
Courses
Account
Login / Sign Up

All Occurrence Of An Element

Easy Acceptance 59% Points 20

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

Return or print the indices (0-based) where the element appears, in increasing order. If the element is not present, return -1.

Examples
Example 1

Example 1

Input: arr[] = [1 3 5 3 7 3], x = 3

Output: 1 3 5

Explanation: Since the array is 1 3 5 3 7 3 and the target element is 3, it appears at indices 1, 3, and 5.

Example 2

Example 2

Input: arr[] = [4 4 4 4], x = 4

Output: 0 1 2 3

Explanation: Since all elements are 4, the target element occurs at every index of the array.

Example 3

Example 3

Input: arr[] = [2 6 8 10], x = 5

Output: -1

Explanation: Since the array does not contain the target element 5, there are no occurrences, so we return -1.

Constraints
  • 1 <N<105
  • -109 < arr[i] < 109
Topics
Recursion
Companies
Samsung Netflix Expedia
Added 19 Jul 2026 59% acceptance
Ln 1, Col 1Sign in to save your code
1 2 3 2 5
2
1 3