« All indices of a number in array.

Problem

All Indices of Number in array

Given an array of length N and an integer x, you need to find all the indexes where x is present in the input array. Save all the indexes in an array (in increasing order). Do this recursively. Indexing in the array starts from 0.

Input Format :

Line 1 : An Integer N i.e. size of array

Line 2 : N integers which are elements of the array, separated by spaces

Line 3 : Integer x

Output Format :

indexes where x is present in the array (separated by space)

Constraints :

1 <= N <= 10^3

Sample Input :

5 9 8 10 8 8 8

Sample Output :

1 3 4

Solution

1#include <iostream>
2#include <iomanip>
3#include <algorithm>
4#include <string>
5#include <cstring>
6#include <vector>
7#include <cmath>
8#include <map>
9#include <climits>
10// climits for INT_MIN
11#include <unordered_map>
12using namespace std;
13
14int allIndexes(int input[], int size, int x, int output[])
15{
16 if (size == 0)
17 {
18 return 0;
19 }
20 int m = allIndexes(input, size - 1, x, output);
21 if (input[size - 1] == x)
22 {
23 output[m] = size - 1;
24 return m + 1;
25 }
26 else
27 {
28 return m;
29 }
30}
31
32int main()
33{
34 int n;
35 cin >> n;
36
37 int *input = new int[n];
38
39 for (int i = 0; i < n; i++)
40 {
41 cin >> input[i];
42 }
43
44 int x;
45
46 cin >> x;
47
48 int *output = new int[n];
49
50 int size = allIndexes(input, n, x, output);
51 for (int i = 0; i < size; i++)
52 {
53 cout << output[i] << " ";
54 }
55 cout << endl;
56
57 delete[] input;
58
59 delete[] output;
60 return 0;
61}