Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

All Occurrence Of An Element

Easy Acceptance 59.00% Points 20.00

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.

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