{"id":506,"date":"2025-07-02T19:02:53","date_gmt":"2025-07-02T13:32:53","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=506"},"modified":"2025-07-03T12:14:16","modified_gmt":"2025-07-03T06:44:16","slug":"find-first-and-last-position-of-element-in-sorted-array","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/find-first-and-last-position-of-element-in-sorted-array\/","title":{"rendered":"Find First and Last Position of Element in Sorted Array | Leetcode 34 | Optimal Binary Search"},"content":{"rendered":"\n<p>Given an array of integers&nbsp;<code>nums<\/code>&nbsp;sorted in non-decreasing order, find the starting and ending position of a given&nbsp;<code>target<\/code>&nbsp;value.<\/p>\n\n\n\n<p>If&nbsp;<code>target<\/code>&nbsp;is not found in the array, return&nbsp;<code>[-1, -1]<\/code>.<\/p>\n\n\n\n<p>You must&nbsp;write an algorithm with&nbsp;<code>O(log n)<\/code>&nbsp;runtime complexity.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/leetcode.com\/problems\/find-first-and-last-position-of-element-in-sorted-array\/description\/\" target=\"_blank\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><span style=\"text-decoration: underline;\">Problem Link<\/span><\/mark><\/a><\/strong>] to begin with.<\/p>\n\n\n\n<p><strong>Example 1:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> nums = [5,7,7,8,8,10], target = 8<br><strong>Output:<\/strong> [3,4]<\/pre>\n\n\n\n<p><strong>Example 2:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> nums = [5,7,7,8,8,10], target = 6<br><strong>Output:<\/strong> [-1,-1]<\/pre>\n\n\n\n<p><strong>Example 3:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> nums = [], target = 0<br><strong>Output:<\/strong> [-1,-1]<\/pre>\n\n\n\n<p><strong>Constraints:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>0 &lt;= nums.length &lt;= 10<sup>5<\/sup><\/code><\/li>\n\n\n\n<li><code>-10<sup>9<\/sup>\u00a0&lt;= nums[i]\u00a0&lt;= 10<sup>9<\/sup><\/code><\/li>\n\n\n\n<li><code>nums<\/code>\u00a0is a non-decreasing array.<\/li>\n\n\n\n<li><code>-10<sup>9<\/sup>\u00a0&lt;= target\u00a0&lt;= 10<sup>9<\/sup><\/code><\/li>\n<\/ul>\n\n\n<div style=\"max-width: -moz-fit-content; \" class=\"wp-block-ub-table-of-contents-block ub_table-of-contents ub_table-of-contents-collapsed\" id=\"ub_table-of-contents-37ab0ed4-6645-405a-8df2-3638c1c14dae\" data-linktodivider=\"false\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" data-enablesmoothscroll=\"true\" data-initiallyhideonmobile=\"false\" data-initiallyshow=\"false\"><div class=\"ub_table-of-contents-header-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-header\" style=\"text-align: left; \">\n\t\t\t\t<div class=\"ub_table-of-contents-title\">Contents:<\/div>\n\t\t\t\t<div class=\"ub_table-of-contents-header-toggle\">\n\t\t\t<div class=\"ub_table-of-contents-toggle\" style=\"\">\n\t\t\t\u00a0[<a class=\"ub_table-of-contents-toggle-link\" href=\"#\" style=\"\">show<\/a>]\n\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t<\/div>\n\t\t<\/div><div class=\"ub_table-of-contents-extra-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-container ub_table-of-contents-1-column ub-hide\">\n\t\t\t\t<ul style=\"\"><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-first-and-last-position-of-element-in-sorted-array\/#0-brute-force-solution-linear-scan\" style=\"\">Brute Force Solution (Linear Scan)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-first-and-last-position-of-element-in-sorted-array\/#1-intuition-amp-approach\" style=\"\">Intuition &amp; Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-first-and-last-position-of-element-in-sorted-array\/#2-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-first-and-last-position-of-element-in-sorted-array\/#3-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-first-and-last-position-of-element-in-sorted-array\/#4-dry-run-nums-223334-target-3-\" style=\"\">Dry Run (nums = [2,2,3,3,3,4], target = 3)<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-first-and-last-position-of-element-in-sorted-array\/#5-time-amp-space-complexity\" style=\"\">Time &amp; Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-first-and-last-position-of-element-in-sorted-array\/#6-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-first-and-last-position-of-element-in-sorted-array\/#7-optimal-solution-two-binary-searches\" style=\"\">Optimal Solution (Two Binary Searches)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-first-and-last-position-of-element-in-sorted-array\/#8-intuition-amp-approach\" style=\"\">Intuition &amp; Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-first-and-last-position-of-element-in-sorted-array\/#9-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-first-and-last-position-of-element-in-sorted-array\/#10-code-explanation\" style=\"\">Code Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-first-and-last-position-of-element-in-sorted-array\/#11-dry-run-nums-5778810-target-8-\" style=\"\">Dry Run (nums = [5,7,7,8,8,10], target = 8)<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-first-and-last-position-of-element-in-sorted-array\/#12-time-amp-space-complexity\" style=\"\">Time &amp; Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/find-first-and-last-position-of-element-in-sorted-array\/#13-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"0-brute-force-solution-linear-scan\">Brute Force Solution (Linear Scan)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"1-intuition-amp-approach\">Intuition &amp; Approach<\/h3>\n\n\n\n<p>Walk through every element:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>As soon as you encounter <code>target<\/code> for the <strong>first<\/strong> time, store the index as <code>first<\/code>.<\/li>\n\n\n\n<li>Keep updating <code>last<\/code> while subsequent occurrences appear.<\/li>\n\n\n\n<li>After the loop ends, return <code>[first, last]<\/code> (both stay <code>-1<\/code> if the loop never hits <code>target<\/code>).<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"2-code-implementation\">Code Implementation<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro padding-bottom-disabled cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def searchRange(self, nums: List[int], target: int) -&gt; List[int]:\n        first = -1   # left-most index of target\n        last = -1    # right-most index of target\n\n        # Scan the whole array\n        for i in range(len(nums)):\n            if nums[i] == target:\n                # record the first time we see the target\n                if first == -1:\n                    first = i\n                # always update last until the loop ends\n                last = i\n\n        return [first, last]\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">searchRange<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">nums<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">], <\/span><span style=\"color: #9CDCFE\">target<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">) -&gt; List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        first = -<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">   <\/span><span style=\"color: #6A9955\"># left-most index of target<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        last = -<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #6A9955\"># right-most index of target<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Scan the whole array<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(nums)):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> nums[i] == target:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># record the first time we see the target<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> first == -<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    first = i<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># always update last until the loop ends<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                last = i<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> [first, last]<\/span><\/span><\/code><\/pre><span style=\"display:flex;align-items:flex-end;padding:10px;width:100%;justify-content:flex-end;background-color:#1E1E1E;color:#c7c7c7;font-size:12px;line-height:1;position:relative\">Python<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"3-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The loop visits each element exactly once.<\/li>\n\n\n\n<li>Conditional checks update <code>first<\/code> <strong>only once<\/strong> and <code>last<\/code> for <strong>every<\/strong> hit, so when the loop finishes <code>last<\/code> really is the right-most match.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-dry-run-nums-223334-target-3-\">Dry Run (nums = <code>[2,2,3,3,3,4]<\/code>, target = <code>3<\/code>)<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>i<\/th><th>nums[i]<\/th><th>first<\/th><th>last<\/th><\/tr><\/thead><tbody><tr><td>0<\/td><td>2<\/td><td>-1<\/td><td>-1<\/td><\/tr><tr><td>1<\/td><td>2<\/td><td>-1<\/td><td>-1<\/td><\/tr><tr><td>2<\/td><td>3<\/td><td>2<\/td><td>2<\/td><\/tr><tr><td>3<\/td><td>3<\/td><td>2<\/td><td>3<\/td><\/tr><tr><td>4<\/td><td>3<\/td><td>2<\/td><td>4<\/td><\/tr><tr><td>5<\/td><td>4<\/td><td>2<\/td><td>4<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Returns <code>[2, 4]<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"5-time-amp-space-complexity\">Time &amp; Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time:<\/strong> <code>O(n)<\/code> \u2013 each element inspected once.<\/li>\n\n\n\n<li><strong>Space:<\/strong> <code>O(1)<\/code> \u2013 only two indices stored.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"6-conclusion\">Conclusion<\/h3>\n\n\n\n<p>Works fine on small arrays; however, scanning every element is unnecessary when binary search can pinpoint the boundaries in <code>O(log n)<\/code>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"7-optimal-solution-two-binary-searches\">Optimal Solution (Two Binary Searches)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"8-intuition-amp-approach\">Intuition &amp; Approach<\/h3>\n\n\n\n<p>Exploit the array\u2019s sorted order with <strong>two tailored binary searches<\/strong>:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Left boundary search<\/strong> \u2013 find the first index where <code>nums[index] == target<\/code>.<\/li>\n\n\n\n<li><strong>Right boundary search<\/strong> \u2013 find the last index where <code>nums[index] == target<\/code>.<\/li>\n<\/ol>\n\n\n\n<p>Both searches differ only in the direction they continue after a match:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>When you hit <code>target<\/code>,\n<ul class=\"wp-block-list\">\n<li><strong>Left search<\/strong> keeps moving <strong>left<\/strong> (<code>high = mid - 1<\/code>) to see if an earlier match exists.<\/li>\n\n\n\n<li><strong>Right search<\/strong> keeps moving <strong>right<\/strong> (<code>low = mid + 1<\/code>) to see if a later match exists.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"9-code-implementation\">Code Implementation<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro padding-bottom-disabled cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    # ---------- helper to find left-most occurrence ----------\n    def binarySearchLeft(self, nums, target):\n        n          = len(nums)\n        low, high  = 0, n - 1\n        index      = -1              # default: not found\n\n        while low &lt;= high:\n            mid = (low + high) \/\/ 2\n            if nums[mid] == target:\n                index = mid          # potential left boundary\n                high  = mid - 1      # continue searching left\n            elif nums[mid] &gt; target:\n                high  = mid - 1      # target is in the left half\n            else:                    # nums[mid] &lt; target\n                low   = mid + 1      # target is in the right half\n        return index\n\n    # ---------- helper to find right-most occurrence ----------\n    def binarySearchRight(self, nums, target):\n        n          = len(nums)\n        low, high  = 0, n - 1\n        index      = -1              # default: not found\n\n        while low &lt;= high:\n            mid = (low + high) \/\/ 2\n            if nums[mid] == target:\n                index = mid          # potential right boundary\n                low   = mid + 1      # continue searching right\n            elif nums[mid] &gt; target:\n                high  = mid - 1\n            else:                    # nums[mid] &lt; target\n                low   = mid + 1\n        return index\n\n    # ---------- main driver ----------\n    def searchRange(self, nums: List[int], target: int) -&gt; List[int]:\n        ext_left = self.binarySearchLeft(nums, target)\n        # if the target never appears, no need for the second search\n        if ext_left == -1:\n            return [-1, -1]\n\n        ext_right = self.binarySearchRight(nums, target)\n        return [ext_left, ext_right]\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #6A9955\"># ---------- helper to find left-most occurrence ----------<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">binarySearchLeft<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">nums<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">target<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n          = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(nums)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        low, high  = <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, n - <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        index      = -<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">              <\/span><span style=\"color: #6A9955\"># default: not found<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> low &lt;= high:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            mid = (low + high) \/\/ <\/span><span style=\"color: #B5CEA8\">2<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> nums[mid] == target:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                index = mid          <\/span><span style=\"color: #6A9955\"># potential left boundary<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                high  = mid - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">      <\/span><span style=\"color: #6A9955\"># continue searching left<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">elif<\/span><span style=\"color: #D4D4D4\"> nums[mid] &gt; target:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                high  = mid - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">      <\/span><span style=\"color: #6A9955\"># target is in the left half<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">else<\/span><span style=\"color: #D4D4D4\">:                    <\/span><span style=\"color: #6A9955\"># nums[mid] &lt; target<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                low   = mid + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">      <\/span><span style=\"color: #6A9955\"># target is in the right half<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> index<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #6A9955\"># ---------- helper to find right-most occurrence ----------<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">binarySearchRight<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">nums<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">target<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n          = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(nums)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        low, high  = <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, n - <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        index      = -<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">              <\/span><span style=\"color: #6A9955\"># default: not found<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> low &lt;= high:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            mid = (low + high) \/\/ <\/span><span style=\"color: #B5CEA8\">2<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> nums[mid] == target:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                index = mid          <\/span><span style=\"color: #6A9955\"># potential right boundary<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                low   = mid + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">      <\/span><span style=\"color: #6A9955\"># continue searching right<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">elif<\/span><span style=\"color: #D4D4D4\"> nums[mid] &gt; target:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                high  = mid - <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">else<\/span><span style=\"color: #D4D4D4\">:                    <\/span><span style=\"color: #6A9955\"># nums[mid] &lt; target<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                low   = mid + <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> index<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #6A9955\"># ---------- main driver ----------<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">searchRange<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">nums<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">], <\/span><span style=\"color: #9CDCFE\">target<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">) -&gt; List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        ext_left = <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.binarySearchLeft(nums, target)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># if the target never appears, no need for the second search<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> ext_left == -<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> [-<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, -<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">]<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        ext_right = <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.binarySearchRight(nums, target)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> [ext_left, ext_right]<\/span><\/span><\/code><\/pre><span style=\"display:flex;align-items:flex-end;padding:10px;width:100%;justify-content:flex-end;background-color:#1E1E1E;color:#c7c7c7;font-size:12px;line-height:1;position:relative\">Python<\/span><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"10-code-explanation\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><code>binarySearchLeft<\/code><\/strong> stores any match in <code>index<\/code> but keeps shrinking the window to the <strong>left<\/strong> to ensure it finds the earliest one.<\/li>\n\n\n\n<li><strong><code>binarySearchRight<\/code><\/strong> mirrors the logic, moving the window to the <strong>right<\/strong> after a match.<\/li>\n\n\n\n<li>If the first search returns <code>-1<\/code>, the target doesn\u2019t exist, so you can skip the second search.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"11-dry-run-nums-5778810-target-8-\">Dry Run (nums = <code>[5,7,7,8,8,10]<\/code>, target = <code>8<\/code>)<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Left search<\/strong>\n<ul class=\"wp-block-list\">\n<li>mid = 2 \u2192 <code>7<\/code> &lt; <code>8<\/code> \u2192 move right<\/li>\n\n\n\n<li>mid = 4 \u2192 <code>8<\/code> found \u2192 store 4, search left \u2192 high = 3<\/li>\n\n\n\n<li>mid = 3 \u2192 <code>8<\/code> found \u2192 store 3, search left \u2192 high = 2 \u2192 stop \u2192 left = 3<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Right search<\/strong>\n<ul class=\"wp-block-list\">\n<li>mid = 2 \u2192 <code>7<\/code> &lt; <code>8<\/code> \u2192 move right<\/li>\n\n\n\n<li>mid = 4 \u2192 <code>8<\/code> found \u2192 store 4, search right \u2192 low = 5<\/li>\n\n\n\n<li>mid = 5 \u2192 <code>10<\/code> > <code>8<\/code> \u2192 move left \u2192 high = 4 \u2192 stop \u2192 right = 4<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Return <code>[3, 4]<\/code>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"12-time-amp-space-complexity\">Time &amp; Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time:<\/strong> <code>O(log n)<\/code> + <code>O(log n)<\/code> \u2248 <code>O(log n)<\/code> \u2013 two binary searches.<\/li>\n\n\n\n<li><strong>Space:<\/strong> <code>O(1)<\/code> \u2013 constant extra storage.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"13-conclusion\">Conclusion<\/h3>\n\n\n\n<p>Using two <strong>directional<\/strong> binary searches gives the exact first and last indices in logarithmic time and constant space, making it the standard interview-grade solution for this problem.<\/p>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/codeanddebug.in\/course\/zero-to-hero-python-dsa\" target=\"_blank\" rel=\"noreferrer noopener\">Join our Advance DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\" target=\"_blank\" rel=\"noreferrer noopener\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\" target=\"_blank\" rel=\"noreferrer noopener\">+91-9712928220<\/a>.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Given an array of integers&nbsp;nums&nbsp;sorted in non-decreasing order, find the starting and ending position of a given&nbsp;target&nbsp;value. If&nbsp;target&nbsp;is not found in the array, return&nbsp;[-1, -1]. You must&nbsp;write an algorithm with&nbsp;O(log n)&nbsp;runtime complexity. Here&#8217;s the [Problem Link] to begin with. Example 1: Input: nums = [5,7,7,8,8,10], target = 8Output: [3,4] Example 2: Input: nums = [5,7,7,8,8,10],<\/p>\n","protected":false},"author":1,"featured_media":507,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,4],"tags":[7,27],"class_list":{"0":"post-506","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-beginner","9":"tag-array","10":"tag-binary-search"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/07\/find-first-and-last-position-of-element-in-sorted-array-featured-image.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/506","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=506"}],"version-history":[{"count":2,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/506\/revisions"}],"predecessor-version":[{"id":511,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/506\/revisions\/511"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/507"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=506"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=506"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=506"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}