How to find last index of a number in an Array in C++

07 Oct, 2021
Given an array arr[] of N integers and the number K, the task is to find the last occurrence of K in arr[]. If the element is not present then return -1.Examples: 
Input: arr[] = {1, 3, 4, 2, 1, 8}, K = 1 Output: 4 Explanation: There are two occurrence of 1 at index 0 and 4. But the last occurrence is at index 4.Input: arr[] = {3, 4, 5, 6, 7}, K = 2 Output: -1 Explanation: Since 2 is not present in the array. 
Method 1: Using Recursion 
Recursively iterate from the last index of the given array: Base Case: If we reach the starting index recursively that mean the given element K is not present in the array.
Base Case: If we reach the starting index recursively that mean the given element K is not present in the array.
if(idx < 0) {
  return -1;
}
Return Statement: If current element in the recursive call is equals to K, then return the current index from the function.
if(arr[idx]==K) {
   return idx;
}
Recursive Call: If the element at current index is not equals to K, then recursively call for next iteration.
return recursive_function(arr, idx - 1)
Below is the implementation of the above approach:
CPP
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Recursive function to find the last// index of the given number Kint findIndex(int arr[], int idx, int K){     // Base Case    if (idx < 0)        return -1;     // Return Statement    if (arr[idx] == K) {        return idx;    }     // Recursive Call    return findIndex(arr, idx - 1, K);} // Driver Codeint main(){     int arr[] = { 3, 1, 4, 4, 2, 3, 1 };    int N = sizeof(arr) / sizeof(arr[0]);    int K = 4;     // Function call    cout << findIndex(arr, N - 1, K);     return 0;}
3
 
Time Complexity: O(N), where N is the length of the array.Method 2: Using inbuilt function find() and find_if(): The idea is to find the first element from the end of the array to find the last element from the beginning of the array. Below are the steps: 
Reverse the given array.Find the first element with value K in the reversed array using find() function.if the iterator return by the find function points to the end of the array then the element is not present in the array.Else use distance() function to find the position(say pos) of the K in this reversed array.To get the distance for the last index of K in the given array print (N – pos – 1).
Reverse the given array.
Find the first element with value K in the reversed array using find() function.
if the iterator return by the find function points to the end of the array then the element is not present in the array.
Else use distance() function to find the position(say pos) of the K in this reversed array.
To get the distance for the last index of K in the given array print (N – pos – 1).
Below is the implementation of the above approach:Using find()
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;   // Function to find the last index of// the given number Kint findIndex(int arr[], int N, int K){       // Reverse the given array arr[]    reverse(arr, arr + N);       // Find the first occurrence of K    // in this reversed array    auto it = find(arr, arr + N, K);       // If the element is not present    // then return "-1"    if (it == arr + N) {        return -1;    }       // Else return the index found    return (N - distance(arr, it) - 1);}   // Driver Codeint main(){       int arr[] = { 3, 1, 4, 4, 2, 3, 1 };    int N = sizeof(arr) / sizeof(arr[0]);    int K = 4;       // Function call    cout << findIndex(arr, N, K);       return 0;}
Using find_if()
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;   // Comparator structure for finding// index of element with value Kstruct comparator {       int elem;    comparator(int const& i)        : elem(i)    {    }       bool operator()(int const& i)    {        return (i == elem);    }};   // Function to find the last index of// the given number Kint findIndex(int arr[], int N, int K){       // Reverse the given array arr[]    reverse(arr, arr + N);       // Find the first occurrence of K    // in this reversed array    auto it = find_if(arr, arr + N,                      comparator(K));       // If the element is not present    // then return "-1"    if (it == arr + N) {        return -1;    }       // Else return the index found    return (N - distance(arr, it) - 1);}   // Driver Codeint main(){       int arr[] = { 3, 1, 4, 4, 2, 3, 1 };    int N = sizeof(arr) / sizeof(arr[0]);    int K = 4;       // Function call    cout << findIndex(arr, N, K);       return 0;}
3
 
Time Complexity: O(N), where N is the number of element in the given array.
Method 3: (Iterative Way) 
Use a loop for finding the last position.
Below is the implementation of the above approach
C++
// CPP program for the above approach#include <iostream>using namespace std;int findIndex(int arr[], int idx, int K){         // Traversing the array from    // last position    for (int i = idx; i >= 0; i--) {        if (arr[i] == K)            return i;    }    return -1;} // Driver Codeint main(){     int arr[] = { 3, 1, 4, 4, 2, 3, 1 };    int N = sizeof(arr) / sizeof(arr[0]);    int K = 4;     // Function call    cout << findIndex(arr, N - 1, K);    return 0;}
Output:
3
le0
varshagumber28
sumitgumber28
Analysis
Arrays
Recursion
Arrays
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Understanding Time Complexity with Simple Examples
Time Complexity and Space Complexity
Analysis of Algorithms | Set 4 (Analysis of Loops)
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Cyclomatic Complexity
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray