{"id":8141,"date":"2025-07-22T10:54:37","date_gmt":"2025-07-22T05:24:37","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=8141"},"modified":"2025-07-22T21:27:29","modified_gmt":"2025-07-22T15:57:29","slug":"find-first-last-position-in-sorted-array","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/find-first-last-position-in-sorted-array\/","title":{"rendered":"Find First &amp; Last Position in Sorted Array"},"content":{"rendered":"\n<!-- Prism.js CSS and JS -->\n<link href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.css\" rel=\"stylesheet\" \/>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/prism.js\"><\/script>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/plugins\/autoloader\/prism-autoloader.min.js\"><\/script>\n\n<style>\n  .wp_blog_code-tabs-container {\n    font-family: \"Segoe UI\", sans-serif !important;\n    max-width: 900px !important;\n    margin: 2rem auto !important;\n    border: 1px solid #ddd !important;\n    border-radius: 8px !important;\n    overflow: hidden !important;\n    background-color: white !important;\n  }\n\n  .wp_blog_code-tabs-header {\n    background: #f7f7f7 !important;\n    display: flex !important;\n    border-bottom: 1px solid #ddd !important;\n  }\n\n  .wp_blog_code-tab-button {\n    flex: 1 !important;\n    padding: 10px 15px !important;\n    border: none !important;\n    background: transparent !important;\n    cursor: pointer !important;\n    font-weight: bold !important;\n    transition: background 0.2s !important;\n    color: #242b33 !important;\n  }\n\n  .wp_blog_code-tab-button.active {\n    background: white !important;\n    border-bottom: 3px solid #0073aa !important;\n  }\n\n  .wp_blog_code-tab-content {\n    display: none !important;\n    padding: 20px !important;\n    background: #242b33 !important;\n  }\n\n  .wp_blog_code-tab-content > pre {\n    background: #242b33 !important;\n  }\n\n  .wp_blog_code-tab-content.active {\n    display: block !important;\n  }\n\n  .wp_blog_code-tab-content pre {\n    margin: 0 !important;\n    overflow-x: auto !important;\n  }\n\n  .wp_blog_explanation {\n    max-width: 900px !important;\n    margin: 2rem auto !important;\n    font-family: \"Segoe UI\", sans-serif !important;\n    line-height: 1.6 !important;\n    background: white !important;\n    color: black !important;\n    padding: 1rem !important;\n    border-radius: 8px !important;\n  }\n\n  .wp_blog_explanation h2 {\n    color: #0073aa !important;\n    font-size: 1.5rem !important;\n    margin-bottom: 0.5rem !important;\n  }\n\n  .wp_blog_explanation code {\n    background: #f1f1f1 !important;\n    padding: 2px 6px !important;\n    border-radius: 4px !important;\n    font-family: monospace !important;\n  }\n\n  .wp_blog_explanation h1,\n  .wp_blog_explanation h2,\n  .wp_blog_explanation h3,\n  .wp_blog_explanation h4,\n  .wp_blog_explanation h5,\n  .wp_blog_explanation h6,\n  .wp_blog_explanation p {\n    margin-top: 10px !important;\n    margin-bottom: 10px !important;\n  }\n<\/style>\n\n<div class=\"wp_blog_explanation\">\n  <p>This problem asks us to find the first and last positions of a given target in a sorted array. If the target is not found, return <code>[-1, -1]<\/code>.<\/p>\n\n  <h2>Steps<\/h2>\n  <ul>\n    <li>Use binary search twice:\n      <ul>\n        <li>Once to find the **first occurrence** (left bound)<\/li>\n        <li>Once to find the **last occurrence** (right bound)<\/li>\n      <\/ul>\n    <\/li>\n    <li>Store results in <code>ans[0]<\/code> and <code>ans[1]<\/code>.<\/li>\n  <\/ul>\n\n  <h2>Dry Run<\/h2>\n  <p><strong>Input:<\/strong> <code>[5,7,7,8,8,10]<\/code>, target = <code>8<\/code><\/p>\n  <ol>\n    <li>First binary search finds index <code>3<\/code><\/li>\n    <li>Second binary search finds index <code>4<\/code><\/li>\n    <li>Answer: <code>[3, 4]<\/code><\/li>\n  <\/ol>\n\n  <p><strong>Input:<\/strong> <code>[5,7,7,8,8,10]<\/code>, target = <code>6<\/code><\/p>\n  <p><strong>Output:<\/strong> <code>[-1, -1]<\/code><\/p>\n\n  <p><strong>Input:<\/strong> <code>[5,7,7,8,8,10]<\/code>, target = <code>0<\/code><\/p>\n  <p><strong>Output:<\/strong> <code>[-1, -1]<\/code><\/p>\n\n  <h2>Time &#038; Space Complexity<\/h2>\n  <ul>\n    <li><strong>Time Complexity:<\/strong> O(log\u202fn)<\/li>\n    <li><strong>Space Complexity:<\/strong> O(1)<\/li>\n  <\/ul>\n<\/div>\n\n<div class=\"wp_blog_code-tabs-container\">\n  <div class=\"wp_blog_code-tabs-header\">\n    <button class=\"wp_blog_code-tab-button active\" data-lang=\"js\">JavaScript<\/button>\n    <button class=\"wp_blog_code-tab-button\" data-lang=\"cpp\">C++<\/button>\n    <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">C<\/button>\n    <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/button>\n    <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n    <button class=\"wp_blog_code-tab-button\" data-lang=\"c#\">C#<\/button>\n  <\/div>\n\n  <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n    <pre><code class=\"language-javascript\">\nvar searchRange = function(arr, target) {\n    let l = 0;\n    let r = arr.length - 1;\n    let ans = [-1, -1];\n\n    while (l < r) {\n        let m = l + Math.floor((r - l) \/ 2);\n        if (arr[m] < target) l = m + 1;\n        else r = m;\n    }\n\n    if (arr[l] === target) ans[0] = l;\n\n    l = 0;\n    r = arr.length - 1;\n\n    while (l < r) {\n        let m = l + Math.ceil((r - l) \/ 2);\n        if (arr[m] > target) r = m - 1;\n        else l = m;\n    }\n\n    if (arr[l] === target) ans[1] = l;\n\n    return ans;\n};\n    <\/code><\/pre>\n  <\/div>\n\n  <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n    <pre><code class=\"language-cpp\">\nvector<int> searchRange(vector<int>& arr, int target) {\n    int l = 0, r = arr.size() - 1;\n    vector<int> ans = {-1, -1};\n\n    while (l < r) {\n        int m = l + (r - l) \/ 2;\n        if (arr[m] < target) l = m + 1;\n        else r = m;\n    }\n\n    if (arr[l] == target) ans[0] = l;\n\n    l = 0; r = arr.size() - 1;\n    while (l < r) {\n        int m = l + (r - l + 1) \/ 2;\n        if (arr[m] > target) r = m - 1;\n        else l = m;\n    }\n\n    if (arr[l] == target) ans[1] = l;\n\n    return ans;\n}\n    <\/code><\/pre>\n  <\/div>\n\n  <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n    <pre><code class=\"language-c\">\nint* searchRange(int* arr, int arrSize, int target, int* returnSize){\n    int* ans = (int*)malloc(2 * sizeof(int));\n    *returnSize = 2;\n    ans[0] = ans[1] = -1;\n    int l = 0, r = arrSize - 1;\n\n    while (l < r) {\n        int m = l + (r - l) \/ 2;\n        if (arr[m] < target) l = m + 1;\n        else r = m;\n    }\n\n    if (arr[l] == target) ans[0] = l;\n\n    l = 0; r = arrSize - 1;\n    while (l < r) {\n        int m = l + (r - l + 1) \/ 2;\n        if (arr[m] > target) r = m - 1;\n        else l = m;\n    }\n\n    if (arr[l] == target) ans[1] = l;\n\n    return ans;\n}\n    <\/code><\/pre>\n  <\/div>\n\n  <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n    <pre><code class=\"language-java\">\npublic class Solution {\n    public int[] searchRange(int[] arr, int target) {\n        int[] ans = {-1, -1};\n        int l = 0, r = arr.length - 1;\n\n        while (l < r) {\n            int m = l + (r - l) \/ 2;\n            if (arr[m] < target) l = m + 1;\n            else r = m;\n        }\n\n        if (arr[l] == target) ans[0] = l;\n\n        l = 0; r = arr.length - 1;\n        while (l < r) {\n            int m = l + (r - l + 1) \/ 2;\n            if (arr[m] > target) r = m - 1;\n            else l = m;\n        }\n\n        if (arr[l] == target) ans[1] = l;\n\n        return ans;\n    }\n}\n    <\/code><\/pre>\n  <\/div>\n\n  <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n    <pre><code class=\"language-python\">\ndef searchRange(arr, target):\n    ans = [-1, -1]\n    l, r = 0, len(arr) - 1\n\n    while l < r:\n        m = l + (r - l) \/\/ 2\n        if arr[m] < target:\n            l = m + 1\n        else:\n            r = m\n\n    if l < len(arr) and arr[l] == target:\n        ans[0] = l\n\n    l, r = 0, len(arr) - 1\n    while l < r:\n        m = l + (r - l + 1) \/\/ 2\n        if arr[m] > target:\n            r = m - 1\n        else:\n            l = m\n\n    if l < len(arr) and arr[l] == target:\n        ans[1] = l\n\n    return ans\n    <\/code><\/pre>\n  <\/div>\n\n  <div class=\"wp_blog_code-tab-content\" data-lang=\"c#\">\n    <pre><code class=\"language-c#\">\npublic class Solution {\n    public int[] SearchRange(int[] arr, int target) {\n        int[] ans = {-1, -1};\n        int l = 0, r = arr.Length - 1;\n\n        while (l < r) {\n            int m = l + (r - l) \/ 2;\n            if (arr[m] < target) l = m + 1;\n            else r = m;\n        }\n\n        if (arr[l] == target) ans[0] = l;\n\n        l = 0; r = arr.Length - 1;\n        while (l < r) {\n            int m = l + (r - l + 1) \/ 2;\n            if (arr[m] > target) r = m - 1;\n            else l = m;\n        }\n\n        if (arr[l] == target) ans[1] = l;\n\n        return ans;\n    }\n}\n    <\/code><\/pre>\n  <\/div>\n<\/div>\n\n\n\n<a href=\"https:\/\/leetcode.com\/problems\/find-first-and-last-position-of-element-in-sorted-array\/description\/\" target=\"blank\">Solve this problem.<\/a>\n<script>\n  document.addEventListener(\"DOMContentLoaded\", function () {\n    const buttons = document.querySelectorAll(\".wp_blog_code-tab-button\");\n    const contents = document.querySelectorAll(\".wp_blog_code-tab-content\");\n\n    buttons.forEach((button) => {\n      button.addEventListener(\"click\", () => {\n        const lang = button.getAttribute(\"data-lang\");\n\n        buttons.forEach((btn) => btn.classList.remove(\"active\"));\n        button.classList.add(\"active\");\n\n        contents.forEach((content) => {\n          content.classList.toggle(\"active\", content.getAttribute(\"data-lang\") === lang);\n        });\n      });\n    });\n  });\n<\/script>\n\n\n","protected":false},"excerpt":{"rendered":"<p>This problem asks us to find the first and last positions of a given target in a sorted array. If the target is not found, return [-1, -1]. Steps Use binary search twice: Once to find the **first occurrence** (left bound) Once to find the **last occurrence** (right bound) Store results in ans[0] and ans[1].<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[322,176,175,211,174,172,173],"tags":[],"class_list":{"0":"post-8141","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-algorithms-and-data-structures","7":"category-csharp","8":"category-cplusplus","9":"category-data-structures","10":"category-java","11":"category-javascript","12":"category-python"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/8141","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=8141"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/8141\/revisions"}],"predecessor-version":[{"id":8142,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/8141\/revisions\/8142"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=8141"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=8141"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=8141"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}