Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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:
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.
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 K
int 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 Code
int 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

 

Time Complexity: O(N), where N is the length of the array.
Auxiliary Space: O(N), for recursion call stack

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: 

  1. Reverse the given array.
  2. Find the first element with value K in the reversed array using find() function.
  3. if the iterator return by the find function points to the end of the array then the element is not present in the array.
  4. Else use distance() function to find the position(say pos) of the K in this reversed array.
  5. 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 K
int 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 Code
int 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;
}


Time Complexity: O(N), where N is the length of the array.
Auxiliary Space: O(1)

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 K
struct 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 K
int 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 Code
int 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;
}


Output: 

3

 

Time Complexity: O(N), where N is the number of element in the given array.

Auxiliary Space: O(1)

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 Code
int 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

Time Complexity: O(N), where N is the length of the array.
Auxiliary Space: O(1)



Last Updated : 27 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads