« Last Index of Number in the array.
Problem
Last Index of Number in array
Given an array of length N and an integer x, you need to find and return the last index of integer x present in the array. Return -1 if it is not present in the array. Last index means - if x is present multiple times in the array, return the index at which x comes last in the array. You should start traversing your array from 0, not from (N - 1). 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 :
last index or -1
Constraints :
1 <= N <= 10^3
Sample Input :
4
9 8 10 8
8
Sample Output :
3
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 lastIndex(int input[], int size, int x)15{16 if (size == 1)17 {18 return (input[0] == x) ? 0 : -1;19 }20 int ans = lastIndex(input + 1, size - 1, x);21 if (ans >= 0)22 {23 return ans + 1;24 }25 else26 {27 return (input[0] == x) ? 0 : -1;28 }29}30int main()31{32 int n;33 cin >> n;3435 int *input = new int[n];3637 for (int i = 0; i < n; i++)38 {39 cin >> input[i];40 }4142 int x;4344 cin >> x;4546 cout << lastIndex(input, n, x) << endl;47 return 0;48}