{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a666d090d54c",
   "metadata": {},
   "source": [
    "# Two Sum II - Input Array Is Sorted\n",
    "\n",
    "| Field      | Value                                   |\n",
    "|------------|-----------------------------------------|\n",
    "| Source     | [link](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/)  |\n",
    "| Difficulty | Medium                    |\n",
    "| Topics     | `array`, `two pointers`, `binary search`                     |\n",
    "| Date       | 2026-10-16                              |\n",
    "| Status     | Solved                                  |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bd338ac3398d",
   "metadata": {},
   "source": [
    "## 1. Problem\n",
    "\n",
    "> Given an array of integers `numbers` that is sorted in **non-decreasing order**, return the\n",
    "> indices (**1-indexed**) of two numbers, `[index1, index2]`, such that they add up to `target`\n",
    "> and `index1 < index2`. You may not use the same element twice.\n",
    "> There will always be **exactly one** valid solution.\n",
    "> Your solution must use $O(1)$ additional space.\n",
    "\n",
    "**Example 1**\n",
    "```\n",
    "Input:  numbers = [1,2,3,4], target = 3\n",
    "Output: [1,2]\n",
    "```\n",
    "`1 + 2 = 3`; with 1-indexing that's `[1, 2]`.\n",
    "\n",
    "**Constraints**\n",
    "- `2 <= len(numbers) <= 30000`\n",
    "- `-1000 <= numbers[i] <= 1000`\n",
    "- `-1000 <= target <= 1000`"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4d2d1e0015cc",
   "metadata": {},
   "source": [
    "## 2. Thinking\n",
    "\n",
    "- **Brute force idea:** try every pair `i < j`, $O(n^2)$ time. Two Sum I's hash map gets $O(n)$\n",
    "  time, but uses $O(n)$ space, which this version forbids.\n",
    "- **Key insight:** the array is **sorted**. Put one pointer at each end and look at the sum:\n",
    "  too big → the only way to shrink it is `right -= 1`; too small → `left += 1`.\n",
    "  Each step discards a value that can't be in *any* valid pair (if\n",
    "  `numbers[left] + numbers[right] > target`, then `numbers[right]` is too big even with the\n",
    "  smallest remaining value), so the answer is never skipped. $O(n)$ time, $O(1)$ space.\n",
    "- **Edge cases to remember:** return **1-indexed** positions; duplicates (`[1,1]`, target `2`);\n",
    "  negatives and zeros; the answer can be the two middle elements, so the pointers may\n",
    "  travel almost the whole array. `while True` is only safe because a solution is guaranteed;\n",
    "  `while left < right` is the defensive version."
   ]
  },
  {
   "cell_type": "code",
   "id": "4d26aa350a54",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "# Setup: run this cell first. Lets you run pytest tests inside the notebook.\n",
    "try:\n",
    "    import ipytest\n",
    "except ImportError:  # Colab and other fresh kernels don't ship ipytest\n",
    "    %pip install -q ipytest\n",
    "    import ipytest\n",
    "import pytest\n",
    "\n",
    "ipytest.autoconfig()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d868ad2460ab",
   "metadata": {},
   "source": [
    "## 3. Solution\n",
    "\n",
    "### Approach A — two pointers from both ends (mine) ✅ best practice\n",
    "**Complexity:** Time $O(n)$ · Space $O(1)$\n",
    "\n",
    "This is already the optimal solution: each step moves one pointer inward, so there are at\n",
    "most $n-1$ steps, and only two indices are stored."
   ]
  },
  {
   "cell_type": "code",
   "id": "889035eb6a77",
   "metadata": {},
   "source": [
    "def two_sum_sorted(numbers: list[int], target: int) -> list[int]:\n",
    "    left = 0\n",
    "    right = len(numbers) - 1\n",
    "\n",
    "    while True:  # safe only because a solution is guaranteed; `while left < right` otherwise\n",
    "        total = numbers[left] + numbers[right]\n",
    "        if total > target:\n",
    "            right -= 1\n",
    "        elif total < target:\n",
    "            left += 1\n",
    "        else:\n",
    "            return [left + 1, right + 1]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "61d25ba06fa8",
   "metadata": {},
   "source": [
    "### Approach B — binary search for the complement\n",
    "**Complexity:** Time $O(n \\log n)$ · Space $O(1)$\n",
    "\n",
    "For each `i`, binary-search `target - numbers[i]` in the part after `i` (using `bisect`'s\n",
    "`lo`/`hi` bounds, so no slice is copied). Also meets the space limit, but slower than\n",
    "two pointers because each search starts from scratch instead of reusing what the last step learned."
   ]
  },
  {
   "cell_type": "code",
   "id": "4cf87d86ff08",
   "metadata": {},
   "source": [
    "from bisect import bisect_left\n",
    "\n",
    "\n",
    "def two_sum_sorted_bsearch(numbers: list[int], target: int) -> list[int]:\n",
    "    n = len(numbers)\n",
    "    for i in range(n - 1):\n",
    "        need = target - numbers[i]\n",
    "        j = bisect_left(numbers, need, i + 1, n)\n",
    "        if j < n and numbers[j] == need:\n",
    "            return [i + 1, j + 1]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "8eff2ca09e5a",
   "metadata": {},
   "source": [
    "### Approach C — hash map (Two Sum I), ignores the sorting\n",
    "**Complexity:** Time $O(n)$ · Space $O(n)$ ❌ breaks the $O(1)$-space rule\n",
    "\n",
    "The Two Sum I solution: remember each value's index and look up the complement. Correct,\n",
    "but it doesn't use the sorted order and stores up to $n$ entries."
   ]
  },
  {
   "cell_type": "code",
   "id": "9497f76fab45",
   "metadata": {},
   "source": [
    "def two_sum_sorted_hashmap(numbers: list[int], target: int) -> list[int]:\n",
    "    seen = {}  # value -> 1-based index; this is the O(n) extra space\n",
    "    for j, x in enumerate(numbers, start=1):\n",
    "        if target - x in seen:\n",
    "            return [seen[target - x], j]\n",
    "        seen[x] = j"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "a6e58b50255b",
   "metadata": {},
   "source": [
    "## 4. Tests\n",
    "\n",
    "All three implementations run against the same cases."
   ]
  },
  {
   "cell_type": "code",
   "id": "387a21c5c9ba",
   "metadata": {},
   "source": [
    "%%ipytest -q\n",
    "\n",
    "HALF = 15000\n",
    "BIG = [-1000] * (HALF - 1) + [1, 2] + [1000] * (HALF - 1)  # answer in the middle\n",
    "\n",
    "CASES = [\n",
    "    ([1, 2, 3, 4], 3, [1, 2]),\n",
    "    ([2, 7, 11, 15], 9, [1, 2]),\n",
    "    ([2, 3, 4], 6, [1, 3]),                  # first and last\n",
    "    ([-1, 0], -1, [1, 2]),                   # minimum length, negative target\n",
    "    ([1, 1], 2, [1, 2]),                     # duplicates form the answer\n",
    "    ([-3, -1, 0, 2, 5], 4, [2, 5]),          # negative + positive\n",
    "    ([-1000, 1000], 0, [1, 2]),              # value bounds\n",
    "    ([0, 0, 3, 4], 0, [1, 2]),               # zeros\n",
    "    ([1, 2, 3, 4, 4, 9, 56, 90], 8, [4, 5]), # equal adjacent values in the middle\n",
    "    (BIG, 3, [HALF, HALF + 1]),              # max length, both pointers travel ~n/2\n",
    "]\n",
    "\n",
    "@pytest.mark.parametrize(\"fn\", [two_sum_sorted, two_sum_sorted_bsearch, two_sum_sorted_hashmap])\n",
    "@pytest.mark.parametrize(\"numbers, target, expected\", CASES)\n",
    "def test_two_sum_sorted(fn, numbers, target, expected):\n",
    "    assert fn(numbers, target) == expected"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "5f4e73efd16e",
   "metadata": {},
   "source": [
    "## 5. Scratch / Experiments\n",
    "\n",
    "Worst case for two pointers: the answer is the two middle elements of a max-length array\n",
    "(30000), so `left` walks ~15000 steps right and `right` walks ~15000 steps left.\n",
    "\n",
    "Measured (one run): two pointers ~1.1 ms, binary search ~1.7 ms, hash map ~0.66 ms.\n",
    "The hash map wins on time here even though everything is $O(n)$: it stops after ~15000\n",
    "iterations (when it reaches the `2`), while two pointers makes ~30000 loop steps, and a dict\n",
    "lookup in C costs about as much as one Python comparison. It still loses on the actual\n",
    "requirement: it holds ~15000 dict entries, vs two integers. Binary search is only ~1.5× slower\n",
    "than two pointers despite the extra $\\log n$, because each `bisect_left` runs in C."
   ]
  },
  {
   "cell_type": "code",
   "id": "c21ac503c9db",
   "metadata": {},
   "source": [
    "half = 15000\n",
    "numbers = [-1000] * (half - 1) + [1, 2] + [1000] * (half - 1)\n",
    "target = 3\n",
    "for fn in (two_sum_sorted, two_sum_sorted_bsearch, two_sum_sorted_hashmap):\n",
    "    assert fn(numbers, target) == [half, half + 1]\n",
    "%timeit two_sum_sorted(numbers, target)\n",
    "%timeit two_sum_sorted_bsearch(numbers, target)\n",
    "%timeit two_sum_sorted_hashmap(numbers, target)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "051da737d7c1",
   "metadata": {},
   "source": [
    "## 6. Takeaways\n",
    "\n",
    "- **Pattern:** **sorted array + pair with a target sum → two pointers from both ends.** Sum too\n",
    "  big → move `right` left; too small → move `left` right. The sorting is what makes each move\n",
    "  safe (it rules out every pair using the discarded value), and it replaces the hash map, so\n",
    "  space drops from $O(n)$ to $O(1)$.\n",
    "- **Mistakes I made:** none in the algorithm, it's the optimal solution. Things to keep in\n",
    "  mind: `while True` relies on the \"exactly one solution\" guarantee; write `while left < right`\n",
    "  (and return something after the loop) when that guarantee isn't given. Don't forget the\n",
    "  **1-indexed** output.\n",
    "- **Related problems:** Two Sum (#1, unsorted → hash map), 3Sum (#15, sort, fix one number,\n",
    "  then this two-pointer scan), 4Sum (#18, two fixed numbers + two pointers),\n",
    "  3Sum Closest (#16, same scan, track the nearest sum), Container With Most Water (#11,\n",
    "  two pointers from both ends, move the shorter side), Valid Palindrome (#125, two pointers\n",
    "  moving inward), Two Sum IV - Input is a BST (#653, inorder traversal = sorted)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
