How to Find First and Last Position of Element in Sorted Array

<h1>The Problem</h1> <p>With this article, I will be covering the&nbsp;Find First and Last Position of an Element in a Sorted Array problem.</p> <p>Leetcode describes the problem with the following:</p> <blockquote> <p><em>Given an array of integers&nbsp;</em><code><em>nums</em></code><em>&nbsp;sorted in non-decreasing order, find the starting and ending position of a given&nbsp;</em><code><em>target</em></code><em>&nbsp;value.</em></p> <p><em>If&nbsp;</em><code><em>target</em></code><em>&nbsp;is not found in the array, return&nbsp;</em><code><em>[-1, -1]</em></code><em>.</em></p> <p><em>You must write an algorithm with&nbsp;</em><code><em>O(log n)</em></code><em>&nbsp;runtime complexity.</em></p> </blockquote> <p>Example:</p> <blockquote> <p><em>Input: nums = [5,7,7,8,8,10], target = 8</em></p> <p><em>Output: [3,4]</em></p> </blockquote> <p>Leetcode ranks this problem as a medium. I think that is an appropriate rating. The solution is feasible but does require some algorithmic understanding.</p> <h2>Naive Approach and Its Limitations</h2> <p>The naive approach for solving this problem would be to scan through the array linearly to find the first and last occurrence of the target value. This involves looping through the array once to find the first occurrence of the target and marking that index as the starting position, then looping through it again to find the last occurrence and marking that as the ending position.</p> <p>While this approach works, it takes&nbsp;<code>O(n)</code>&nbsp;time to solve, which doesn&#39;t meet the constraint of&nbsp;<code>O(log n)</code>&nbsp;runtime complexity. Therefore, it would become inefficient when dealing with large datasets.</p> <p><a href="https://sean-coughlin.medium.com/how-to-find-first-and-last-position-of-element-in-sorted-array-10d8d1f36649">Website</a></p>