Back to articles
First and Last Occurences

First and Last Occurences

via Dev.to PythonDharani

Introduction Finding the first and last occurrences of an element is a common problem in arrays. It is especially useful in searching and indexing tasks. Problem Statement Given a sorted array and a target value, find the first and last position of the target element. If the element is not found, return [-1, -1]. Approach (Binary Search) We use Binary Search twice: First Binary Search → to find the first occurrence Second Binary Search → to find the last occurrence Python Code python def first_occurrence(arr, target): left, right = 0, len(arr) - 1 result = -1 while left <= right: mid = (left + right) // 2 if arr[mid] == target: result = mid right = mid - 1 # search left side elif arr[mid] < target: left = mid + 1 else: right = mid - 1 return result def last_occurrence(arr, target): left, right = 0, len(arr) - 1 result = -1 while left <= right: mid = (left + right) // 2 if arr[mid] == target: result = mid left = mid + 1 # search right side elif arr[mid] < target: left = mid + 1 else: ri

Continue reading on Dev.to Python

Opens in a new tab

Read Full Article
3 views

Related Articles