{"id":7894,"date":"2025-07-15T17:37:19","date_gmt":"2025-07-15T12:07:19","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=7894"},"modified":"2025-07-15T20:03:25","modified_gmt":"2025-07-15T14:33:25","slug":"two-sum-ii-input-array-is-sorted","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/two-sum-ii-input-array-is-sorted\/","title":{"rendered":"Two Sum ( Input Array Is Sorted)"},"content":{"rendered":"\n<!--Two sum II -->\n<link\n    href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.min.css\"\n    rel=\"stylesheet\"\n\/>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/prism.min.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_theme {\n    --primary: #e58c32;\n    --secondary: #f8c291;\n    --light-bg: #fef9f4;\n    --text-dark: #2d2d2d;\n    --tab-radius: 12px;\n    --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);\n    --code-bg: #001f3f;\n    --code-text: #d4f1ff;\n  }\n\n  .wp_blog_container {\n    font-family: 'Segoe UI', sans-serif;\n    background: var(--light-bg);\n    margin: 0;\n    padding: 0;\n    color: var(--text-dark);\n  }\n    \/* Heading *\/\n    .wp_blog_main-heading {\n        text-align: center;\n        font-size: 2.4rem;\n        color: var(--primary);\n        margin-top: 2.5rem;\n        font-weight: bold;\n    }\n\n    \/* Explanation Card *\/\n    .wp_blog_explanation,\n    .wp_blog_code-tabs-container {\n        max-width: 940px;\n        margin: 2rem auto;\n        padding: 2rem;\n        background: white;\n        border-radius: var(--tab-radius);\n        box-shadow: var(--shadow);\n    }\n\n    \/* Text and Visuals *\/\n    .wp_blog_explanation h2 {\n        font-size: 1.4rem;\n        color: var(--primary);\n        margin-bottom: 0.5rem;\n    }\n    .wp_blog_explanation p,\n    .wp_blog_explanation li {\n        font-size: 1.05rem;\n        line-height: 1.7;\n        margin: 0.5rem 0;\n    }\n    .wp_blog_explanation code {\n        background: #fef9f4;\n        padding: 3px 6px;\n        border-radius: 4px;\n        font-family: \"Courier New\", monospace;\n    }\n    .wp_blog_explanation img {\n        max-width: 100%;\n        border-radius: var(--tab-radius);\n        margin-top: 1rem;\n        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);\n    }\n\n    \/* Tab Buttons *\/\n    .wp_blog_code-tabs-header {\n        display: flex;\n        flex-wrap: wrap;\n        gap: 0.5rem;\n        margin-bottom: 1rem;\n    }\n    .wp_blog_code-tab-button {\n        padding: 0.6rem 1.2rem;\n        border: 1px solid var(--primary);\n        background: white;\n        color: var(--primary);\n        border-radius: 50px;\n        font-weight: 600;\n        cursor: pointer;\n        transition: all 0.3s ease;\n    }\n    .wp_blog_code-tab-button:hover {\n        background: var(--secondary);\n    }\n    .wp_blog_code-tab-button.active {\n        background: var(--primary);\n        color: white;\n    }\n\n    \/* Code Content *\/\n    .wp_blog_code-tab-content {\n        display: none;\n        background: var(--code-bg);\n        border-radius: var(--tab-radius);\n    }\n    .wp_blog_code-tab-content.active {\n        display: block;\n    }\n    .wp_blog_code-tab-content pre {\n        margin: 0;\n        padding: 1.5rem;\n        font-size: 1rem;\n        overflow-x: auto;\n        background: var(--code-bg);\n        border-radius: var(--tab-radius);\n        color: var(--code-text);\n    }\n<\/style>\n\n<div class=\"wp_blog_container wp_blog_theme\">\n<h1 class=\"wp_blog_main-heading\"><\/h1>\n\n<div class=\"wp_blog_explanation\">\n    <h2>Problem Statement:<\/h2>\n    <p>\n        Given a <strong>1-indexed<\/strong> array of integers numbers that is already <strong>sorted in non-decreasing order<\/strong>, find two numbers such that they add up to a specific <code>target<\/code> number. Let these two numbers be <code>numbers[index1]<\/code> and <code>numbers[index2]<\/code> where <code>1 <= index1 < index2 <= numbers.length<\/code>.\n    <\/p>\n    <p> Return the indices of the two numbers, <code>index1<\/code> and <code>index2<\/code>, <strong>added by one<\/strong> as an integer array <code>[index1, index2]<\/code> of length 2. \n    <\/p>\n\n    <p>The tests are generated such that there is <strong>exactly one solution<\/strong>. You <strong>may not<\/strong> use the same element twice.<\/p>\n    \n    <p>Your solution must use only constant extra space.<\/p>\n\n\n    <h2>Examples:<\/h2>\n    <p><strong>Example 1:<\/strong><\/p>\n    <p><strong>Input:<\/strong> numbers = [2,7,11,15], target = 9<\/p> \n    <p><strong>Output:<\/strong><code> [1,2]<\/code><\/p>\n    <p><strong>Explanation:<\/strong> The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].\n<\/p>\n\n    <p><strong>Example 2:<\/strong><\/p>\n    <p><strong>Input:<\/strong> numbers = [2,3,4], target = 6<\/p>\n    <p><strong>Output:<\/strong><code> [1,3]<\/code><\/p>\n    <p><strong>Explanation:<\/strong> The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].<\/p>\n\n    <p><strong>Example 3:<\/strong><\/p>\n    <p><strong>Input:<\/strong> numbers = [-1,0], target = -1<\/p>\n    <p><strong>Output:<\/strong><code> [1,2]<\/code><\/p>\n    <p><strong>Explanation:<\/strong> The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].<\/p>\n    \n\n    <h2>Constraints:<\/h2>\n    <ul>\n        <li><code>2 <= numbers.length <= 3 * 10<sup>4<\/sup><\/code><\/li>\n        <li><code>-1000 <= numbers[i] <= 1000<\/code><\/li>\n        <li><code>numbers<\/code>is sorted in <strong>non-decreasing order<\/strong>.<\/li>\n        <li><code>The tests are generated such that there is <strong>exactly one solution<\/strong>.<\/code><\/li>\n    <\/ul>\n\n    <h2>Approach:<\/h2>\n    <ul>\n        <li><strong>Initialize two pointers:<\/strong>.\n            <ul>\n                <li><code>i = 0<\/code> (start of array)<\/li>\n                <li><code>j = numbers.length - 1 (end of array)<\/li>\n            <\/ul>\n        <\/li>\n        <li><strong>Loop until<\/strong><code>i < j<\/code>\n            <ul>\n                <li>Calculate <code>sum = numbers[i] + numbers[j]<\/code>.<\/li>\n                <li>If <code>sum > target<\/code>, move <code>j<\/code> left (decrease <code>j<\/code>)<\/li>\n                <li>If <code>sum < target<\/code>, move <code>i<\/code> right (increase <code>i<\/code>)<\/li>\n                <li>If <code>sum === target<\/code>, return <code>[i + 1, j + 1]<\/code> (1-based index)<\/li>\n            <\/ul>\n        <\/li>      \n    <\/ul>\n\n    <h2>Visualisation:<\/h2>\n    <img decoding=\"async\"\n        src=\"https:\/\/namastedev.com\/blog\/wp-content\/uploads\/2025\/07\/Screenshot-2025-07-15-at-5.30.59\u202fPM.png\"\n        alt=\"stack\"\n    \/>\n                <h2>Time Complexity:<\/h2>\n                <li>\n                  <p><strong>Time Complexity = O(n)<\/strong> \n                <\/li> \n                <h2>Space Complexity:<\/h2>\n                <li>\n                  <p><strong>Space Complexity = O(1)<\/strong> \n                <\/p>\n                <\/li>\n\n<h2>Dry Run<\/h2> <div style=\"background: #f9f9f9; border-left: 4px solid var(--primary); padding: 1rem; border-radius: var(--tab-radius); margin: 1rem 0;\"> <p><strong>Input:<\/strong><\/p> <pre style=\"white-space: pre-wrap; background: #fff5ea; padding: 1rem; border-radius: 8px; overflow-x: auto;\"> numbers = [4, 1, 2] target = 3 <\/pre> <p><strong>State Transitions:<\/strong><\/p> <pre style=\"white-space: pre-wrap; background: #fff5ea; padding: 1rem; border-radius: 8px; overflow-x: auto;\"> Note: This is a two-pointer approach assuming the input array is sorted in non-decreasing order.\nStep 1: Initialize\n\u2192 i = 0, j = 2 (pointing to numbers[0] = 4, numbers[2] = 2)\n\nStep 2:\n\u2192 sum = numbers[i] + numbers[j] = 4 + 2 = 6\n\u2192 sum > target \u2192 decrement j \u2192 j = 1\n\nStep 3:\n\u2192 sum = numbers[i] + numbers[j] = 4 + 1 = 5\n\u2192 sum > target \u2192 decrement j \u2192 j = 0\n\nNow i = 0, j = 0 \u2192 i is not less than j \u2192 loop ends\n<\/pre>\n\n<p><strong>Final Output:<\/strong> <code>undefined<\/code><\/p> <p><strong>Final State:<\/strong> Loop exited without finding a valid pair since the array is not sorted in non-decreasing order as required by the two-pointer approach.<\/p> <\/div>\n\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\">\n            JavaScript\n        <\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/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=\"cs\">C#<\/button>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n<pre><code class=\"language-javascript\">\nvar twoSum = function(numbers, target) {\n    let i = 0;\n    let j = numbers.length - 1;\n    while( i < j){\n        let sum = numbers[i] + numbers[j];\n        if(sum > target) {\n            --j;\n        } else if(sum < target) {\n            ++i;\n        } else {\n            return [i+1, j+1]\n        }\n    }\n};\n<\/code>\n<\/pre>\n<\/div>\n\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n        <pre><code class=\"language-python\">\nfrom typing import List\ndef twoSum(numbers: List[int], target: int) -> List[int]:\n    i = 0\n    j = len(numbers) - 1\n    while i < j:\n        sum = numbers[i] + numbers[j]\n        if sum > target:\n            j -= 1\n        elif sum < target:\n            i += 1\n        else:\n            return [i + 1, j + 1]\n    return []\n    <\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n        <pre><code class=\"language-java\">\nclass Solution {\n    public int[] twoSum(int[] numbers, int target) {\n        int i = 0;\n        int j = numbers.length - 1;\n        while(i < j) {\n            int sum = numbers[i] + numbers[j];\n            if(sum > target) {\n                --j;\n            } else if(sum < target) {\n                ++i;\n            } else {\n                return new int[] { i + 1, j + 1 };\n            }\n        }\n        return new int[] {};\n    }\n}\n <\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n        <pre><code class=\"language-cpp\">\n#include &lt;vector&gt;\nusing namespace std;\n\nvector<int> twoSum(vector<int>& numbers, int target) {\n    int i = 0;\n    int j = numbers.size() - 1;\n    while(i < j) {\n        int sum = numbers[i] + numbers[j];\n        if(sum > target) {\n            --j;\n        } else if(sum < target) {\n            ++i;\n        } else {\n            return {i + 1, j + 1};\n        }\n    }\n    return {};\n}\n<\/code><\/pre>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n        <pre><code class=\"language-c\">\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\nint* twoSum(int* numbers, int numbersSize, int target, int* returnSize) {\n    int i = 0;\n    int j = numbersSize - 1;\n    int* result = (int*)malloc(2 * sizeof(int));\n    while(i < j) {\n        int sum = numbers[i] + numbers[j];\n        if(sum > target) {\n            --j;\n        } else if(sum < target) {\n            ++i;\n        } else {\n            result[0] = i + 1;\n            result[1] = j + 1;\n            *returnSize = 2;\n            return result;\n        }\n    }\n    *returnSize = 0;\n    return NULL;\n}\n<\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cs\">\n        <pre><code class=\"language-csharp\">\npublic class Solution {\n    public int[] TwoSum(int[] numbers, int target) {\n        int i = 0;\n        int j = numbers.Length - 1;\n        while(i < j) {\n            int sum = numbers[i] + numbers[j];\n            if(sum > target) {\n                --j;\n            } else if(sum < target) {\n                ++i;\n            } else {\n                return new int[] { i + 1, j + 1 };\n            }\n        }\n        return new int[] {};\n    }\n}\n  <\/code><\/pre>\n    <\/div>\n<\/div>\n<\/div>\n<script>\n    document.addEventListener(\"DOMContentLoaded\", () => {\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                buttons.forEach((btn) => btn.classList.remove(\"active\"));\n                contents.forEach((content) =>\n                    content.classList.remove(\"active\")\n                );\n                button.classList.add(\"active\");\n                document\n                    .querySelector(\n                        `.wp_blog_code-tab-content[data-lang=\"${lang}\"]`\n                    )\n                    .classList.add(\"active\");\n            });\n        });\n    });\n<\/script>\n","protected":false},"excerpt":{"rendered":"<p>Problem Statement: Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 target: j -= 1 elif sum < target: i += 1 else: return [i + 1,\n<\/p>\n","protected":false},"author":108,"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":[210,322,260,176,175,212,211,811,810,174,172,173],"tags":[],"class_list":{"0":"post-7894","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-algorithms","7":"category-algorithms-and-data-structures","8":"category-c-c-plus-plus","9":"category-csharp","10":"category-cplusplus","11":"category-code-optimization","12":"category-data-structures","13":"category-data-structures-and-algorithms","14":"category-dsa","15":"category-java","16":"category-javascript","17":"category-python"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7894","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\/108"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=7894"}],"version-history":[{"count":3,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7894\/revisions"}],"predecessor-version":[{"id":7907,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7894\/revisions\/7907"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=7894"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=7894"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=7894"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}