Binary Search Tree

QUESTION

Find the last occurrence of the index of the given integer\n\nThe index starts from \”0\”\n\nTestcase 1:\n\n1. Number of Inputs (6)\n\n2. The input elements (8 10 15 15 16 16) \n\n3. Element to be Searched (16)\n\nOutput :\n\n5\n\nExplanation :\n\nArray Index starts from \”0\” and 16 is found in array index 4 and 5 and the last index is 5\n\n\n\n.

“TESTCASE_1”: “6\n8 10 15 15 16 16\n16\n###—###SEPERATOR—###—\n5”, “TESTCASE_2”: “10\n10 20 55 11 22 22 11 33 55 10\n55\n###—###SEPERATOR—###—\n8”, “TESTCASE_3”: “5\n1 2 3 4 5\n2\n###—###SEPERATOR—###—\n1”, “TESTCASE_4”: “7\n1 2 3 4 5 6 7\n7\n###—###SEPERATOR—###—\n6”, “TESTCASE_5”: “0\n###—###SEPERATOR—###—\n0

ANSWER

#include <iostream>
#include<bits/stdc++.h>
using namespace std;
 
// Function for finding first and last occurrence
// of an elements
void findFirstAndLast(int arr[], int n, int x)
{
    int first = -1, last = -1;
    for (int i=0; i<n; i++)
    {
        if (x != arr[i])
            continue;
        if (first == -1)
            first = i;
        last = i;
    }
    if (first != -1)
        cout <<last;
    else
        cout << "Not Found";
}
 
// Driver code
int main()
{
  int n;
  cin>>n;
  int arr[n], i, x;
  for(i=0; i<n; i++)
    cin>>arr[i];
  cin>>x;
    
    findFirstAndLast(arr, n, x);
    return 0;
}
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
CHP Adblock Detector Plugin | Codehelppro