« 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_MIN11#include <unordered_map>12using namespace std;1314int 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 else27 {28 return m;29 }30}3132int main()33{34 int n;35 cin >> n;3637 int *input = new int[n];3839 for (int i = 0; i < n; i++)40 {41 cin >> input[i];42 }4344 int x;4546 cin >> x;4748 int *output = new int[n];4950 int size = allIndexes(input, n, x, output);51 for (int i = 0; i < size; i++)52 {53 cout << output[i] << " ";54 }55 cout << endl;5657 delete[] input;5859 delete[] output;60 return 0;61}