Find start and ending index of an element in an unsorted array in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array aar[] of n integer values which are not sorted and an integer val. Our task is to find the start and ending index of an element in an unsorted array.

For the occurrence of the element in the array, we will return,

"Starting index and ending index " if it is found in the array twice or more.

"Single index " if it is found in the array once.

"Element not present " if it is not present in the array.

Let's take an example to understand the problem,

Example 1

Input : arr[] = {2, 1, 5, 4, 6, 2, 3}, val = 2
Output : starting index = 0, ending index = 5

Explanation

There are two occurrences of the element 2,
First at index = 0,
Second at index = 5

Example 2

Input : arr[] = {2, 1, 5, 4, 6, 2, 3}, val = 5
Output : Present only once at index 2

Explanation

There is only one occurrence of the element 5, at index = 2,

Example 3

Input : arr[] = {2, 1, 5, 4, 6, 2, 3}, val = 7
Output : Not present in the array!

Solution Approach

A simple solution to the problem is by traversing the array.

We will traverse the array and keep two index values, first and last. First index will traverse the array from start and the last index will traverse the array from end. And then end the loop when the value of the element at first and last index becomes the same.

Algorithm

  • Step 1 − Loop through array

    • Step 1.1 − Use the first index for traversing from start and last index for traversing from end.

    • Step 1.2 − if the value at any index is equal to val. Donot increment the index value.

    • Step 1.3 − if both values at both indexes are the same return.

Example

Program to illustrate the working of our solution

#include <iostream>
using namespace std;

void findStartAndEndIndex(int arr[], int n, int val) {
   int start = 0;
   int end = n -1 ;
   while(1){
   if(arr[start] != val)
      start++;
   if(arr[end] != val)
      end--;
   if(arr[start] == arr[end] && arr[start] == val)
      break;
   if(start == end)
      break;
}
   if (start == end ){
      if(arr[start] == val)
         cout<<"Element is present only once at index : "<<start;
      else
         cout<<"Element Not Present in the array";
   } else {
      cout<<"Element present twice at \n";
      cout<<"Start index: "<<start<<endl;
      cout<<"Last index: "<<end;
   }
}
int main() {
   int arr[] = { 2, 1, 5, 4, 6, 2, 9, 0, 2, 3, 5 };
   int n = sizeof(arr) / sizeof(arr[0]);
   int val = 2;
   findStartAndEndIndex(arr, n, val);
   return 0;
}

Output

Element present twice at
Start index: 0
Last index: 8
raja
Updated on 25-Jan-2022 08:48:09

Advertisements