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

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 occurence of 1 at index 0 and 4. But the last occurence 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:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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;
    }

    chevron_right

    
    

    Output:

    3
    

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

    Method 2: Using inbuit 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()

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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 occurence 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;
    }

    chevron_right

    
    

    Using find_if()

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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 occurence 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;
    }

    chevron_right

    
    

    Output:

    3
    

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

    Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




    My Personal Notes arrow_drop_up

    Recommended Posts:


    Check out this Author's contributed articles.

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


    Article Tags :
    Practice Tags :


    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.