# Find start and ending index of an element in an unsorted array

Last Updated : 28 Apr, 2024

Given an array of integers, task is to find the starting and ending position of a given key.

Examples:

`Input : arr[] = {1, 2, 3, 4, 5, 5}      Key = 5Output :  Start index: 4      Last index: 5Explanation: Starting index where 5is present is 4 and ending index is 5. Input :arr[] = {1, 3, 7, 8, 6},       Key = 2Output : Key not present in arrayInput :arr[] = {1, 8, 7, 8, 6},       Key = 7Output : Only one occurrence of key is present at index 2`
Recommended Practice

We traverse array from beginning to find first occurrence. If element is present, then we traverse from end also to find last occurrence.

Implementation:

C++ ```// CPP program to find starting and ending // indexes of repeated numbers in an array #include <iostream> using namespace std; // Function to find starting and end index void findIndex(int a[], int n, int key) { int start = -1; // Traverse from beginning to find // first occurrence for (int i = 0; i < n; i++) { if (a[i] == key) { start = i; break; } } if (start == -1) { cout << "Key not present in array"; return; } // Traverse from end to find last // occurrence. int end = start; for (int i = n - 1; i >= start; i--) { if (a[i] == key) { end = i; break; } } if (start == end) cout << "Only one key is present at index : " << start; else { cout << "Start index: " << start; cout << "\n"; cout << "Last index: " << end; } } // Driver Code int main() { int a[] = { 1, 2, 7, 8, 8, 9, 8, 0, 0, 0, 8 }; int n = sizeof(a) / sizeof(a[0]); // Key to find int key = 8; // Calling function findIndex(a, n, key); return 0; } ``` Java ```// Java program to find starting and ending // indexes of repeated numbers in an array class Test { // Function to find starting and end index static void findIndex(int a[], int n, int key) { int start = -1; // Traverse from beginning to find // first occurrence for (int i = 0; i < n; i++) { if (a[i] == key) { start = i; break; } } if (start == -1) { System.out.println("Key not present in array"); return; } // Traverse from end to find last // occurrence. int end = start; for (int i = n - 1; i >= start; i--) { if (a[i] == key) { end = i; break; } } if (start == end) System.out.println("Only one key is present at index : " + start); else { System.out.println("Start index: " + start); System.out.println("Last index: " + end); } } // Driver method public static void main(String args[]) { int a[] = { 1, 2, 7, 8, 8, 9, 8, 0, 0, 0, 8 }; // Key to find int key = 8; // Calling method findIndex(a, a.length, key); } } ``` Python3 ```# Python3 code to find starting and ending # indexes of repeated numbers in an array # Function to find starting and end index def findIndex (a, n, key ): start = -1 # Traverse from beginning to find # first occurrence for i in range(n): if a[i] == key: start = i break if start == -1: print("Key not present in array") return 0 # Traverse from end to find last # occurrence. end = start for i in range(n-1, start - 1, -1): if a[i] == key: end = i break if start == end: print("Only one key is present at index : ", start) else: print("Start index: ", start) print("Last index: ", end) # Driver Code a = [1, 2, 7, 8, 8, 9, 8, 0, 0, 0, 8] n = len(a) # Key to find key = 8 # Calling function findIndex(a, n, key) # This code is contributed by "Sharad_Bhardwaj". ``` C# ```// C# program to find starting and ending // indexes of repeated numbers in an array using System; class GFG { // Function to find starting and // end index static void findIndex(int[] a, int n, int key) { int start = -1; // Traverse from beginning to // find first occurrence for (int i = 0; i < n; i++) { if (a[i] == key) { start = i; break; } } if (start == -1) { Console.WriteLine("Key not " + "present in array"); return; } // Traverse from end to find last // occurrence. int end = start; for (int i = n - 1; i >= start; i--) { if (a[i] == key) { end = i; break; } } if (start == end) Console.WriteLine("Only one key is" + " present at index : " + start); else { Console.WriteLine("Start index: " + start); Console.WriteLine("Last index: " + end); } } // Driver method public static void Main() { int[] a = { 1, 2, 7, 8, 8, 9, 8, 0, 0, 0, 8 }; // Key to find int key = 8; // Calling method findIndex(a, a.Length, key); } } // This code is contributed by parashar. ``` Javascript ```// Javascript program to find starting and ending // indexes of repeated numbers in an array // Function to find starting and end index function findIndex(a, n, key) { let start = -1; // Traverse from beginning to find // first occurrence for (let i = 0; i < n; i++) { if (a[i] == key) { start = i; break; } } if (start == -1) { console.log("Key not present in array"); return; } // Traverse from end to find last // occurrence. let end = start; for (let i = n - 1; i >= start; i--) { if (a[i] == key) { end = i; break; } } if (start == end) console.log("Only one key is present at index : " + start); else { console.log("Start index: " + start); console.log("<br>" + "Last index: " + end); } } // Driver Code let a = [ 1, 2, 7, 8, 8, 9, 8, 0, 0, 0, 8 ]; let n = a.length; // Key to find let key = 8; // Calling function findIndex(a, n, key); //This code is contributed by Mayank Tyagi ``` PHP ```<?php // PHP program to find starting and ending // indexes of repeated numbers in an array // Function to find starting and end index function findIndex(\$arr, \$find){ // To store the atrting and // the ending index of the key \$start = -1; \$end = -1; // For every element of the given array foreach (\$arr as \$key => \$value) { // If current element is equal // to the given key if(\$find === \$value){ // If starting index hasn't been set if(\$start==-1) \$start = \$key; \$end = \$key; } } // If key is not present in the array if(\$start==-1){ return "Key not present in array"; } if(\$end == \$start){ return "Only one key is present "." at index : ". \$start; } return "Start index: ".\$start. "\nLast index: ".\$end; } // Driver code \$a = array(1, 2, 7, 8, 8, 9, 8, 0, 0, 0, 8); // Key to find \$key = 8; // Calling function echo findIndex(\$a, \$key); ?> ```

Output
```Start index: 3
Last index: 10```

Time Complexity: Worst case time complexity is O(N), ( when we traverse the whole array and don’t find the element’s start and last indices), where N represents the size of the given array. and best case time complexity will be O(1), when start index is ‘0’ and last index is ‘n – 1’.
Auxiliary Space: O(1), no extra space is required, so it is a constant.

### Approach2 (Using Map)

In this approach we use a map to store the starting and ending positions of each element encountered while traversing the array. If an element is encountered for the first time, we create a new entry in the map with the starting and ending positions set to the current index. If an element is encountered again, we update the ending position in the map. Return the starting and ending positions of the key from the map.

#### Example : Below is the implementation of above approach

C++ ```#include <iostream> #include <unordered_map> #include <vector> using namespace std; pair<int, int> findPositionsHashTable(const vector<int>& arr, int key) { unordered_map<int, pair<int, int> > positions; for (int i = 0; i < arr.size(); ++i) { if (positions.find(arr[i]) == positions.end()) { positions[arr[i]] = make_pair(i, i); } else { positions[arr[i]].second = i; } } if (positions.find(key) != positions.end()) { return positions[key]; } else { return make_pair(-1, -1); } } int main() { vector<int> arr = { 1, 2, 7, 8, 8, 9, 8, 0, 0, 0, 8 }; int key = 8; pair<int, int> result = findPositionsHashTable(arr, key); int start = result.first; int end = result.second; if (start != -1) { cout << "Starting index :" << ": " << start << endl; cout << "Ending index : " << ": " << end << endl; } else { cout << "Key " << key << " is not found in the array." << endl; } return 0; } ``` Java ```import java.util.HashMap; public class Main { static class Pair { int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } } static Pair findPositionsHashTable(int[] arr, int key) { HashMap<Integer, Pair> positions = new HashMap<>(); for (int i = 0; i < arr.length; ++i) { if (!positions.containsKey(arr[i])) { positions.put(arr[i], new Pair(i, i)); } else { positions.get(arr[i]).second = i; } } if (positions.containsKey(key)) { return positions.get(key); } else { return new Pair(-1, -1); } } public static void main(String[] args) { int[] arr = { 1, 2, 7, 8, 8, 9, 8, 0, 0, 0, 8 }; int key = 8; Pair result = findPositionsHashTable(arr, key); int start = result.first; int end = result.second; if (start != -1) { System.out.println("Starting index: " + start); System.out.println("Ending index: " + end); } else { System.out.println( "Key " + key + " is not found in the array."); } } } // Note : created a custom class to represent a pair of // values ``` Python3 ```def find_positions_hash_table(arr, key): positions = {} for i, val in enumerate(arr): if val not in positions: positions[val] = (i, i) else: positions[val] = (positions[val][0], i) if key in positions: return positions[key] else: return (-1, -1) def main(): arr = [1, 2, 7, 8, 8, 9, 8, 0, 0, 0, 8] key = 8 result = find_positions_hash_table(arr, key) start, end = result if start != -1: print("Starting index:", start) print("Ending index:", end) else: print("Key", key, "is not found in the array.") if __name__ == "__main__": main() ``` JavaScript ```class Pair { constructor(first, second) { this.first = first; // First occurrence index this.second = second; // Last occurrence index } } /** * Function to find the positions of a key in an array using a hash table approach. * @param {number[]} arr - The input array. * @param {number} key - The key to search for in the array. * @returns {Pair} - A Pair object containing the starting and ending indices of the key in the array. */ function findPositionsHashTable(arr, key) { let positions = new Map(); // Hash table to store positions for (let i = 0; i < arr.length; ++i) { if (!positions.has(arr[i])) { positions.set(arr[i], new Pair(i, i)); // Initialize position for new element } else { positions.get(arr[i]).second = i; // Update last occurrence index } } if (positions.has(key)) { return positions.get(key); // Return positions for the key } else { return new Pair(-1, -1); // Key not found, return default pair } } // Sample input const arr = [1, 2, 7, 8, 8, 9, 8, 0, 0, 0, 8]; const key = 8; // Find positions of key in the array const result = findPositionsHashTable(arr, key); const start = result.first; // Starting index of key const end = result.second; // Ending index of key // Output the result if (start !== -1) { console.log("Starting index:", start); console.log("Ending index:", end); } else { console.log(`Key \${key} is not found in the array.`); } // This code is contributed by shivamgupta0987654321 ```

Output
```Starting index :: 3
Ending index : : 10
```

Time Complexity : O(n)

Space Complexity : O(n)

This approach is contributed by Ayush Mishra.

Related Article:
Find first and last occurrences of an element in a sorted array