{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c47d9794d126",
   "metadata": {},
   "source": [
    "# 3Sum\n",
    "\n",
    "| Field      | Value                                   |\n",
    "|------------|-----------------------------------------|\n",
    "| Source     | [link](https://leetcode.com/problems/3sum/)  |\n",
    "| Difficulty | Medium                    |\n",
    "| Topics     | `array`, `two pointers`, `sorting`                     |\n",
    "| Date       | 2026-10-17                              |\n",
    "| Status     | Solved                                  |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7b3b321d902d",
   "metadata": {},
   "source": [
    "## 1. Problem\n",
    "\n",
    "> Given an integer array `nums`, return all the triplets `[nums[i], nums[j], nums[k]]` where\n",
    "> `nums[i] + nums[j] + nums[k] == 0`, and the indices `i`, `j` and `k` are all distinct.\n",
    "> The output should **not contain any duplicate triplets**. You may return the output and the\n",
    "> triplets in any order.\n",
    "\n",
    "**Example 1**\n",
    "```\n",
    "Input:  nums = [-1,0,1,2,-1,-4]\n",
    "Output: [[-1,-1,2],[-1,0,1]]\n",
    "```\n",
    "`(-1) + 0 + 1`, `0 + 1 + (-1)` and `(-1) + 2 + (-1)` all sum to 0; the distinct triplets are\n",
    "`[-1,0,1]` and `[-1,-1,2]`.\n",
    "\n",
    "**Example 2**\n",
    "```\n",
    "Input:  nums = [0,1,1]\n",
    "Output: []\n",
    "```\n",
    "The only possible triplet does not sum to 0.\n",
    "\n",
    "**Example 3**\n",
    "```\n",
    "Input:  nums = [0,0,0]\n",
    "Output: [[0,0,0]]\n",
    "```\n",
    "\n",
    "**Constraints**\n",
    "- `3 <= len(nums) <= 3000`\n",
    "- `-10^5 <= nums[i] <= 10^5`"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "63ecb1a52c2c",
   "metadata": {},
   "source": [
    "## 2. Thinking\n",
    "\n",
    "- **Brute force idea:** try every triple `i < j < k` and put the sorted triplet in a set to drop\n",
    "  duplicates, $O(n^3)$ time. With $n = 3000$ that's ~4.5 billion triples — far too slow.\n",
    "- **Key insight:** **sort first**, then fix the smallest number `nums[i]` and the problem becomes\n",
    "  Two Sum II (#167) on the rest: find `nums[left] + nums[right] == -nums[i]` with two pointers\n",
    "  from both ends. Sum too small → `left += 1`; too big → `right -= 1`. That's $O(n)$ per `i`,\n",
    "  $O(n^2)$ total, and the sort ($O(n \\log n)$) is free next to it.\n",
    "- **Duplicates are the hard part.** Sorting puts equal values next to each other, so skip them\n",
    "  instead of deduplicating afterwards:\n",
    "  - skip `nums[i]` if it equals the **previous** value `nums[i - 1]` (that value was already\n",
    "    used as the first number, with a superset of the remaining choices);\n",
    "  - after recording a triplet, move `left` past every copy of `nums[left]` (then `right` is forced\n",
    "    to change too, since the sum must stay the same).\n",
    "- **Quick reject / early stop:** once `nums[i] > 0`, all three numbers are positive and no\n",
    "  later `i` can work → `break`.\n",
    "- **Edge cases to remember:** all zeros (`[0,0,0,0]` → one triplet); two equal numbers inside\n",
    "  the triplet (`[-1,-1,2]`); many copies producing the same triplet (`[-2,0,0,2,2]`); all\n",
    "  positive / all negative (no answer); exactly 3 elements."
   ]
  },
  {
   "cell_type": "code",
   "id": "e4aa596f9f39",
   "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": "3282e5a5825f",
   "metadata": {},
   "source": [
    "## 3. Solution\n",
    "\n",
    "### Approach A — my version: sort + two pointers, skipping duplicates ✅ best practice\n",
    "**Complexity:** Time $O(n^2)$ · Space $O(1)$ extra (ignoring the sort and the output; sorts `nums` in place)\n",
    "\n",
    "Already optimal. Sort, fix `nums[i]` (skipping values equal to the previous one), then run Two\n",
    "Sum II on the rest with `target = -nums[i]`. After a match, both pointers move past their copies,\n",
    "so no triplet is produced twice and no set is needed. The sort is $O(n \\log n)$, small next to the\n",
    "$O(n^2)$ scan. One small extra: `if nums[i] > 0: break` stops early, since three positives can't\n",
    "sum to 0 (Approach B)."
   ]
  },
  {
   "cell_type": "code",
   "id": "83d88dfe0597",
   "metadata": {},
   "source": [
    "def three_sum_mine(nums: list[int]) -> list[list[int]]:\n",
    "    nums.sort()  # sorts the caller's list in place\n",
    "    result = []\n",
    "\n",
    "    for i in range(len(nums) - 2):\n",
    "        if i > 0 and nums[i] == nums[i - 1]:  # this first number was already tried\n",
    "            continue\n",
    "        left = i + 1\n",
    "        right = len(nums) - 1\n",
    "        target = -nums[i]\n",
    "        while left < right:\n",
    "            total = nums[left] + nums[right]\n",
    "\n",
    "            if total > target:\n",
    "                right -= 1\n",
    "            elif total < target:\n",
    "                left += 1\n",
    "            else:\n",
    "                result.append([nums[i], nums[left], nums[right]])\n",
    "                while left < right and nums[left] == nums[left + 1]:  # skip copies of nums[left]\n",
    "                    left += 1\n",
    "                while left < right and nums[right] == nums[right - 1]:  # skip copies of nums[right]\n",
    "                    right -= 1\n",
    "                left += 1\n",
    "                right -= 1\n",
    "\n",
    "    return result"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "0ff0986fc987",
   "metadata": {},
   "source": [
    "### Approach B — same, with the early stop\n",
    "**Complexity:** Time $O(n^2)$ · Space $O(1)$ extra\n",
    "\n",
    "Approach A plus `if nums[i] > 0: break`. Once the smallest of the three numbers is positive,\n",
    "no later `i` can reach 0. Same Big-O, and it skips the whole positive half of the array.\n",
    "Skipping copies of only `nums[left]` is enough here: if `left` moves to a new value, the sum\n",
    "changes, so `right` has to move anyway."
   ]
  },
  {
   "cell_type": "code",
   "id": "d11481c7afaa",
   "metadata": {},
   "source": [
    "def three_sum(nums: list[int]) -> list[list[int]]:\n",
    "    nums.sort()\n",
    "    n = len(nums)\n",
    "    result = []\n",
    "    for i in range(n - 2):\n",
    "        if nums[i] > 0:  # smallest of the three is positive -> no more answers\n",
    "            break\n",
    "        if i > 0 and nums[i] == nums[i - 1]:\n",
    "            continue\n",
    "        left, right = i + 1, n - 1\n",
    "        while left < right:\n",
    "            total = nums[i] + nums[left] + nums[right]\n",
    "            if total < 0:\n",
    "                left += 1\n",
    "            elif total > 0:\n",
    "                right -= 1\n",
    "            else:\n",
    "                result.append([nums[i], nums[left], nums[right]])\n",
    "                left += 1\n",
    "                right -= 1\n",
    "                while left < right and nums[left] == nums[left - 1]:  # skip copies\n",
    "                    left += 1\n",
    "    return result"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "283684f7d41e",
   "metadata": {},
   "source": [
    "### Approach C — sort + hash set per first number\n",
    "**Complexity:** Time $O(n^2)$ · Space $O(n)$\n",
    "\n",
    "Same outer loop, but the inner Two Sum uses a hash set (Two Sum I style) instead of two pointers:\n",
    "walk `j` to the right and check whether `-nums[i] - nums[j]` was seen. Same Big-O, but it needs\n",
    "extra memory and the duplicate handling is fiddlier. Useful when you can't sort — e.g. the\n",
    "variant that returns indices."
   ]
  },
  {
   "cell_type": "code",
   "id": "58f9fc260264",
   "metadata": {},
   "source": [
    "def three_sum_hashset(nums: list[int]) -> list[list[int]]:\n",
    "    nums = sorted(nums)\n",
    "    n = len(nums)\n",
    "    result = []\n",
    "    for i in range(n - 2):\n",
    "        if nums[i] > 0:\n",
    "            break\n",
    "        if i > 0 and nums[i] == nums[i - 1]:\n",
    "            continue\n",
    "        seen = set()\n",
    "        j = i + 1\n",
    "        while j < n:\n",
    "            complement = -nums[i] - nums[j]\n",
    "            if complement in seen:\n",
    "                result.append([nums[i], complement, nums[j]])\n",
    "                while j + 1 < n and nums[j] == nums[j + 1]:  # skip copies of nums[j]\n",
    "                    j += 1\n",
    "            seen.add(nums[j])\n",
    "            j += 1\n",
    "    return result"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "87795d3e6501",
   "metadata": {},
   "source": [
    "### Approach D — brute force with a set of triplets\n",
    "**Complexity:** Time $O(n^3)$ · Space $O(\\text{answers})$\n",
    "\n",
    "Every combination of three, sorted into a tuple so the set drops duplicates. Too slow for\n",
    "$n = 3000$, but obviously correct, so the tests use it as a reference on random inputs."
   ]
  },
  {
   "cell_type": "code",
   "id": "a20b7c46e244",
   "metadata": {},
   "source": [
    "from itertools import combinations\n",
    "\n",
    "\n",
    "def three_sum_brute(nums: list[int]) -> list[list[int]]:\n",
    "    found = {tuple(sorted(t)) for t in combinations(nums, 3) if sum(t) == 0}\n",
    "    return [list(t) for t in found]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "6966a6d42a69",
   "metadata": {},
   "source": [
    "## 4. Tests\n",
    "\n",
    "The order of triplets (and inside a triplet) doesn't matter, so `normalize` sorts both — but it\n",
    "does **not** dedupe, so a repeated triplet still fails. Approaches A and B sort `nums` in place,\n",
    "so every call gets a copy (`list(nums)`) to keep `CASES` intact.\n",
    "`test_random` compares A, B and C against the brute force on random small arrays.\n",
    "`test_first_attempt_bugs` replays the three bugs from my first attempt (see Takeaways)."
   ]
  },
  {
   "cell_type": "code",
   "id": "f50a87eb6fbb",
   "metadata": {},
   "source": [
    "%%ipytest -q\n",
    "import random\n",
    "\n",
    "\n",
    "def normalize(triplets):\n",
    "    return sorted(sorted(t) for t in triplets)\n",
    "\n",
    "\n",
    "CASES = [\n",
    "    ([-1, 0, 1, 2, -1, -4], [[-1, -1, 2], [-1, 0, 1]]),\n",
    "    ([0, 1, 1], []),\n",
    "    ([0, 0, 0], [[0, 0, 0]]),\n",
    "    ([0, 0, 0, 0], [[0, 0, 0]]),                     # many zeros -> still one triplet\n",
    "    ([-4, -1, -1, 2], [[-1, -1, 2]]),                # two equal numbers in the triplet\n",
    "    ([-3, 1, 2, 5], [[-3, 1, 2]]),                   # first pair tried isn't the answer\n",
    "    ([-2, 0, 0, 2, 2], [[-2, 0, 2]]),                # same triplet reachable twice\n",
    "    ([1, 2, 3], []),                                 # all positive\n",
    "    ([-3, -2, -1], []),                              # all negative\n",
    "    ([-2, -1, 0, 1, 2], [[-2, 0, 2], [-1, 0, 1]]),   # several answers\n",
    "    ([-4, -2, -2, -2, 0, 1, 2, 2, 2, 3, 3, 4, 4, 6, 6],\n",
    "     [[-4, -2, 6], [-4, 0, 4], [-4, 1, 3], [-4, 2, 2],\n",
    "      [-2, -2, 4], [-2, 0, 2]]),                     # lots of duplicates everywhere\n",
    "    ([-100000, 0, 100000], [[-100000, 0, 100000]]),  # value bounds\n",
    "]\n",
    "\n",
    "\n",
    "@pytest.mark.parametrize(\"fn\", [three_sum_mine, three_sum, three_sum_hashset, three_sum_brute])\n",
    "@pytest.mark.parametrize(\"nums, expected\", CASES)\n",
    "def test_three_sum(fn, nums, expected):\n",
    "    assert normalize(fn(list(nums))) == normalize(expected)\n",
    "\n",
    "\n",
    "@pytest.mark.parametrize(\"seed\", range(200))\n",
    "def test_random(seed):\n",
    "    rng = random.Random(seed)\n",
    "    nums = [rng.randint(-6, 6) for _ in range(rng.randint(3, 12))]\n",
    "    expected = normalize(three_sum_brute(nums))\n",
    "    for fn in (three_sum_mine, three_sum, three_sum_hashset):\n",
    "        assert normalize(fn(list(nums))) == expected, fn.__name__\n",
    "\n",
    "\n",
    "def first_attempt(nums: list[int]) -> list[list[int]]:\n",
    "    result = []\n",
    "    nums.sort()\n",
    "    for i in range(len(nums) - 2):\n",
    "        if i > 0 and nums[i] == nums[i + 1]:  # bug 2: looks ahead instead of back\n",
    "            continue\n",
    "        target = -nums[i]\n",
    "        left, right = i + 1, len(nums) - 1\n",
    "        while right > left:\n",
    "            if target > nums[left] + nums[right]:    # sum too small...\n",
    "                right -= 1                           # bug 1: ...but makes it smaller\n",
    "            elif target < nums[left] + nums[right]:\n",
    "                left += 1\n",
    "            else:\n",
    "                result.append([nums[i], nums[left], nums[right]])\n",
    "                left += 1   # bug 3: no skip over copies\n",
    "                right -= 1\n",
    "    return result\n",
    "\n",
    "\n",
    "def test_first_attempt_bugs():\n",
    "    assert first_attempt([-1, 0, 1, 2, -1, -4]) == []                      # Example 1 comes back empty\n",
    "    assert first_attempt([-3, 1, 2, 5]) == []                              # bug 1 alone\n",
    "    assert first_attempt([-4, -1, -1, 2]) == []                            # bug 2 alone\n",
    "    assert first_attempt([-2, 0, 0, 2, 2]) == [[-2, 0, 2], [-2, 0, 2]]     # bug 3 alone"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "3586d3184e1f",
   "metadata": {},
   "source": [
    "## 5. Scratch / Experiments\n",
    "\n",
    "Worst case for the $O(n^2)$ approaches: $n = 3000$ distinct values `-1500 … 1499`, so the early\n",
    "`break` only kicks in halfway and there are ~1.7 million answers. The brute force would need\n",
    "~4.5 billion triples there, so it's timed on $n = 150$ only.\n",
    "\n",
    "Measured (one run), $n = 3000$: mine ~334 ms, with early stop ~278 ms, hash set ~409 ms.\n",
    "At $n = 150$: brute force ~31 ms vs two pointers ~0.65 ms (~50×, and the gap grows with $n$).\n",
    "All three $O(n^2)$ versions are close: the early `break` saves ~17% by skipping the positive half,\n",
    "and the hash set is slowest because it hashes and allocates a new set for every `i`, where two\n",
    "pointers only compares integers. Most of the time goes into building the ~1.7 million result lists."
   ]
  },
  {
   "cell_type": "code",
   "id": "8f22a5a6a06f",
   "metadata": {},
   "source": [
    "nums = list(range(-1500, 1500))\n",
    "assert normalize(three_sum_mine(list(nums))) == normalize(three_sum_hashset(list(nums)))\n",
    "%timeit -n 1 -r 3 three_sum_mine(list(nums))\n",
    "%timeit -n 1 -r 3 three_sum(list(nums))\n",
    "%timeit -n 1 -r 3 three_sum_hashset(list(nums))\n",
    "\n",
    "small = list(range(-75, 75))  # n = 150 for the O(n^3) brute force\n",
    "%timeit -n 1 -r 3 three_sum_brute(small)\n",
    "%timeit -n 1 -r 3 three_sum(list(small))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "8c3a07a3e9ae",
   "metadata": {},
   "source": [
    "## 6. Takeaways\n",
    "\n",
    "- **Pattern:** **k-Sum → sort, fix the first k − 2 numbers in loops, finish with a two-pointer\n",
    "  scan** (Two Sum II). 3Sum is $O(n^2)$, 4Sum $O(n^3)$. For \"no duplicate tuples\", don't collect\n",
    "  into a set — **skip equal neighbours** after sorting: at each fixed position compare with the\n",
    "  *previous* value, and after a match move the pointer past all its copies.\n",
    "- **Mistakes I made:** the final version is optimal; the only small improvement is the\n",
    "  `nums[i] > 0` early `break`. My **first attempt** had three bugs (replayed in\n",
    "  `test_first_attempt_bugs`), worth remembering:\n",
    "  - Swapped the pointer moves. Say it out loud: *sum too small → make it bigger → move the left\n",
    "    (small) pointer right*.\n",
    "  - Skipped duplicates by looking **ahead** (`nums[i] == nums[i + 1]`). That throws away the first\n",
    "    copy, which is the one that still has its twin to the right, so `[-1,-1,2]` was lost. Always\n",
    "    look **back**: `i > 0 and nums[i] == nums[i - 1]`.\n",
    "  - Only deduplicated the first number. The pair `(left, right)` can repeat too, so skip copies\n",
    "    after recording a triplet.\n",
    "  - Examples 2 and 3 pass even with all three bugs. Test with repeated values, and against a\n",
    "    brute-force reference on random inputs.\n",
    "  - `nums.sort()` mutates the caller's list; fine on LeetCode, but use `sorted(nums)` if the\n",
    "    input must be kept.\n",
    "- **Related problems:** Two Sum (#1, hash map, unsorted), Two Sum II (#167, the inner\n",
    "  two-pointer scan), 3Sum Closest (#16, same scan, track the nearest sum), 4Sum (#18, one more\n",
    "  outer loop), 3Sum Smaller (#259, count pairs: when the sum is small, all `right - left` pairs\n",
    "  count), Valid Triangle Number (#611, sort + fix the largest + two pointers),\n",
    "  Container With Most Water (#11, two pointers from both ends)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
