{"id":7979,"date":"2025-07-17T20:45:17","date_gmt":"2025-07-17T15:15:17","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=7979"},"modified":"2025-07-17T20:46:46","modified_gmt":"2025-07-17T15:16:46","slug":"three-sum","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/three-sum\/","title":{"rendered":"Three Sum"},"content":{"rendered":"\n<!-- 3 SUM-->\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\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 h5{\n  color: var(--primary);\n}\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: #f9cea6;\n  color: #2d2d2d;\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    <div class=\"wp_blog_explanation\">\n        <h2>Problem Statement:<\/h2>\n\n        <p>\n            Given an integer array nums, return all the triplets <code>[nums[i], nums[j], nums[k]]<\/code> such that <code>i != j, i != k,<\/code> and <code>j != k<\/code>, and <code>nums[i] + nums[j] + nums[k] == 0<\/code>.\n        <\/p>\n\n        <p>Notice that the solution set must not contain duplicate triplets.<\/p>\n\n                <h2>Examples:<\/h2>\n\n                <h5>Example 1:<\/h5>\n                \n                <p><strong>Input:<\/strong>nums = [-1,0,1,2,-1,-4]<\/p>\n                <p><strong>Output:<\/strong>[[-1,-1,2],[-1,0,1]]<\/p>\n                <p>\n                  <code>Explanation:<\/code>\n                  nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.\n                <p>\n                    nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.\n                <\/p>\n                <p>\n                    nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.\n                <\/p>\n                <p>\n                    The distinct triplets are [-1,0,1] and [-1,-1,2].\n                <\/p>\n                <p>\n                    Notice that the order of the output and the order of the triplets does not matter.\n                <\/p>\n                <\/p>\n\n                <h5>Example 2:<\/h5>\n                <p><strong>Input:<\/strong>nums = [0,1,1]<\/p>\n                <p><strong>Output:<\/strong>[]<\/p>\n                <p><strong>Explanation:<\/strong> The only possible triplet does not sum up to 0.<\/p>\n\n                <h5>Example 3:<\/h5>\n                <p><strong>Input:<\/strong>nums = [0,0,0]<\/p>\n                <p><strong>Output:<\/strong>[[0,0,0]]<\/p>\n                <p><strong>Explanation:<\/strong> The only possible triplet sums up to 0.<\/p>\n\n                    <h2>Constraints:<\/h2>\n                    <ul>\n                      <li><code>3 <= nums.length <= 3000<\/code><\/li>\n                      <li><code>-10 <sup>5<\/sup> <= nums[i] <= 10 <sup>5<\/sup> <\/code><\/li>\n                    <\/ul>\n\n                <h2>Approach<\/h2>\n                <ul>\n                    <li><strong>Sort the array:<\/strong> Sorting helps efficiently avoid duplicates and use the two-pointer technique.<\/li>\n\n                    <li><strong>Fix one number: <\/strong>Loop through each element <code>nums[i]<\/code> as a fixed number, and for each <code>i<\/code>, find pairs <code>(j, k)<\/code>.<\/li>\n\n                    <li><strong>Two-pointer approach:<\/strong>\n                    <ul>\n                        <li>\n                            Set two pointers:\n\n                            <ul>\n                                <li><code>left = i + 1<\/code><\/li>\n                                <li><code>right = nums.length - 1<\/code><\/li>\n                                <p>Move them based on the sum:<\/p>\n                                <li>If sum > 0 \u2192 move right leftward.<\/li>\n                                <li>If sum < 0 \u2192 move left rightward.<\/li>\n                                <li>If sum == 0 \u2192 valid triplet found \u2192 store and skip duplicates.<\/li>\n                            <\/ul>\n                        <\/li>\n                    <\/ul>\n\n                    <li><strong>Avoid duplicates:<\/strong> Skip duplicate values for <code>nums[i]<\/code> and <code>nums[left]<\/code> to ensure unique triplets.<\/li>\n                    <\/li>\n                <\/ul>\n\n                <h2>Time Complexity:<\/h2>\n                <li>\n                  <p><strong>Time Complexity = O(n<sup>2<\/sup>)<\/strong>\n                  <\/li>\n                <h2>Space Complexity:<\/h2>\n                <li>\n                  <p><strong>Space Complexity = O(1)<\/strong><\/p>\n                <\/li>\n<h2>Dry Run<\/h2>\n<div style=\"background: #f9f9f9; border-left: 4px solid var(--primary); padding: 1rem; border-radius: var(--tab-radius); margin: 1rem 0;\">\n  <p><strong>Input:<\/strong> <code>nums = [-1, 0, 1, 2, -1, -4]<\/code><\/p>\n  <pre style=\"white-space: pre-wrap; background: #fff5ea; padding: 1rem; border-radius: 8px; overflow-x: auto;\">\nStep 1: Sort the array\nnums = [-4, -1, -1, 0, 1, 2]\n\nStep 2: Begin iterating with index i\n\ni = 0 (nums[i] = -4)\n\u2192 nums[0] is not equal to nums[-1] (undefined), so call twoSum(arr, 0, ans)\n\u2192 i = 1, j = 5\nsum = -1 + 2 + (-4) = -3 \u2192 ++i\ni = 2, j = 5 \u2192 sum = -1 + 2 + (-4) = -3 \u2192 ++i\ni = 3, j = 5 \u2192 sum = 0 + 2 + (-4) = -2 \u2192 ++i\ni = 4, j = 5 \u2192 sum = 1 + 2 + (-4) = -1 \u2192 ++i\ni = 5, j = 5 \u2192 loop ends\n\ni = 1 (nums[i] = -1)\n\u2192 nums[1] != nums[0], so call twoSum(arr, 1, ans)\n\u2192 i = 2, j = 5\nsum = -1 + 2 + (-1) = 0 \u2192 push [-1, 2, -1]\n++i, --j \u2192 i = 3, j = 4\narr[i] != arr[i-1] (0 != -1)\nsum = 0 + 1 + (-1) = 0 \u2192 push [0, 1, -1]\n++i, --j \u2192 i = 4, j = 3 \u2192 loop ends\n\ni = 2 (nums[i] = -1)\n\u2192 nums[2] == nums[1], so skip this iteration to avoid duplicates\n\ni = 3 (nums[i] = 0)\n\u2192 nums[3] != nums[2], so call twoSum(arr, 3, ans)\n\u2192 i = 4, j = 5\nsum = 1 + 2 + 0 = 3 \u2192 --j\ni = 4, j = 4 \u2192 loop ends\n\ni = 4, 5 \u2192 Remaining indices skipped as at least 3 numbers are required\n\nFinal ans = [[-1, 2, -1], [0, 1, -1]]\n  <\/pre>\n  <p><strong>Output:<\/strong> <code>Result: [[-1, -1, 2], [-1, 0, 1]]<\/code><\/p>\n<\/div>\n\n        <h2>Visualisation:<\/h2>\n        <img decoding=\"async\" src=\"https:\/\/namastedev.com\/blog\/wp-content\/uploads\/2025\/07\/Screenshot-2025-07-17-at-5.51.21\u202fPM.png\" alt=\"Stocks\" \/>\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=\"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        <!-- JavaScript -->\n        <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n            <pre><code class=\"language-javascript\">\nvar threeSum = function(nums) {\n    nums.sort((a, b) => a - b);\n    let ans = [];\n    for (let i = 0; i < nums.length; i++) {\n        if (i === 0 || nums[i] !== nums[i - 1]) {\n            twoSum(nums, i, ans);\n        }\n    }\n    return ans;\n};\nvar twoSum = function(arr, x, ans) {\n    let i = x + 1;\n    let j = arr.length - 1;\n    while (i < j) {\n        let sum = arr[i] + arr[j] + arr[x];\n        if (sum > 0) {\n            j--;\n        } else if (sum < 0) {\n            i++;\n        } else {\n            ans.push([arr[i], arr[j], arr[x]]);\n            i++;\n            j--;\n            \/\/ Skip duplicates for the second element\n            while (i < j &#038;&#038; arr[i] === arr[i - 1]) {\n                i++;\n            }\n        }\n    }\n};\n     <\/code><\/pre>\n        <\/div>\n\n        <!-- Python -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n            <pre><code class=\"language-python\">\ndef twoSum(arr, x, ans):\n    i = x + 1\n    j = len(arr) - 1\n    while i < j:\n        s = arr[i] + arr[j] + arr[x]\n        if s > 0:\n            j -= 1\n        elif s < 0:\n            i += 1\n        else:\n            ans.append([arr[i], arr[j], arr[x]])\n            i += 1\n            j -= 1\n            while i < j and arr[i] == arr[i - 1]:\n                i += 1\ndef threeSum(nums):\n    nums.sort()\n    ans = []\n    for i in range(len(nums)):\n        if i == 0 or nums[i] != nums[i - 1]:\n            twoSum(nums, i, ans)\n    return ans\n            <\/code><\/pre>\n        <\/div>\n\n        <!-- Java -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n            <pre><code class=\"language-java\">\nimport java.util.*;\npublic class Solution {\n    public void twoSum(int[] arr, int x, List<List<Integer>> ans) {\n        int i = x + 1;\n        int j = arr.length - 1;\n        while (i < j) {\n            int sum = arr[i] + arr[j] + arr[x];\n            if (sum > 0) {\n                --j;\n            } else if (sum < 0) {\n                ++i;\n            } else {\n                ans.add(Arrays.asList(arr[i], arr[j], arr[x]));\n                ++i;\n                --j;\n                while (i < j &#038;&#038; arr[i] == arr[i - 1]) ++i;\n            }\n        }\n    }\n    public List<List<Integer>> threeSum(int[] nums) {\n        Arrays.sort(nums);\n        List<List<Integer>> ans = new ArrayList<>();\n        for (int i = 0; i < nums.length; ++i) {\n            if (i == 0 || nums[i] != nums[i - 1]) {\n                twoSum(nums, i, ans);\n            }\n        }\n        return ans;\n    }\n}\n            <\/code><\/pre>\n        <\/div>\n\n        <!-- C++ -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n            <pre><code class=\"language-cpp\">\n#include &lt;vector&gt;\n#include &lt;algorithm&gt;\nusing namespace std;\n\nvoid twoSum(vector<int>& arr, int x, vector<vector<int>>& ans) {\n    int i = x + 1;\n    int j = arr.size() - 1;\n    while (i < j) {\n        int sum = arr[i] + arr[j] + arr[x];\n        if (sum > 0) {\n            --j;\n        } else if (sum < 0) {\n            ++i;\n        } else {\n            ans.push_back({arr[i], arr[j], arr[x]});\n            ++i;\n            --j;\n            while (i < j &#038;&#038; arr[i] == arr[i - 1]) ++i;\n        }\n    }\n}\nvector<vector<int>> threeSum(vector<int>& nums) {\n    sort(nums.begin(), nums.end());\n    vector<vector<int>> ans;\n    for (int i = 0; i < nums.size(); ++i) {\n        if (i == 0 || nums[i] != nums[i - 1]) {\n            twoSum(nums, i, ans);\n        }\n    }\n    return ans;\n}\n            <\/code><\/pre>\n        <\/div>\n\n        <!-- C -->\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 cmp(const void* a, const void* b) {\n    return (*(int*)a - *(int*)b);\n}\nvoid twoSum(int* arr, int n, int x, int*** ans, int* returnSize) {\n    int i = x + 1;\n    int j = n - 1;\n    while (i < j) {\n        int sum = arr[i] + arr[j] + arr[x];\n        if (sum > 0) {\n            --j;\n        } else if (sum < 0) {\n            ++i;\n        } else {\n            (*ans)[*returnSize] = (int*)malloc(3 * sizeof(int));\n            (*ans)[*returnSize][0] = arr[i];\n            (*ans)[*returnSize][1] = arr[j];\n            (*ans)[*returnSize][2] = arr[x];\n            (*returnSize)++;\n            ++i;\n            --j;\n            while (i < j &#038;&#038; arr[i] == arr[i - 1]) ++i;\n        }\n    }\n}\nint** threeSum(int* nums, int numsSize, int* returnSize) {\n    qsort(nums, numsSize, sizeof(int), cmp);\n    int** ans = (int**)malloc(1000 * sizeof(int*)); \/\/ assuming max 1000 triplets\n    *returnSize = 0;\n\n    for (int i = 0; i < numsSize; ++i) {\n        if (i == 0 || nums[i] != nums[i - 1]) {\n            twoSum(nums, numsSize, i, &#038;ans, returnSize);\n        }\n    }\n    return ans;\n}\n       <\/code><\/pre>\n        <\/div>\n\n        <!-- C# -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"cs\">\n            <pre><code class=\"language-csharp\">\nusing System;\nusing System.Collections.Generic;\npublic class Solution {\n    public void TwoSum(int[] arr, int x, List<IList<int>> ans) {\n        int i = x + 1;\n        int j = arr.Length - 1;\n        while (i < j) {\n            int sum = arr[i] + arr[j] + arr[x];\n            if (sum > 0) {\n                --j;\n            } else if (sum < 0) {\n                ++i;\n            } else {\n                ans.Add(new List<int> { arr[i], arr[j], arr[x] });\n                ++i;\n                --j;\n                while (i < j &#038;&#038; arr[i] == arr[i - 1]) ++i;\n            }\n        }\n    }\n    public IList<IList<int>> ThreeSum(int[] nums) {\n        Array.Sort(nums);\n        List<IList<int>> ans = new List<IList<int>>();\n        for (int i = 0; i < nums.Length; ++i) {\n            if (i == 0 || nums[i] != nums[i - 1]) {\n                TwoSum(nums, i, ans);\n            }\n        }\n        return ans;\n    }\n}\n        <\/code><\/pre>\n        <\/div>\n    <\/div>\n<\/div>\n\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\n                buttons.forEach((btn) => btn.classList.remove(\"active\"));\n                contents.forEach((content) =>\n                    content.classList.remove(\"active\")\n                );\n\n                button.classList.add(\"active\");\n                document\n                    .querySelector(`.wp_blog_code-tab-content[data-lang=\"${lang}\"]`)\n                    .classList.add(\"active\");\n            });\n        });\n    });\n<\/script>\n","protected":false},"excerpt":{"rendered":"<p>Problem Statement: Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets. Examples: Example 1: Input:nums = [-1,0,1,2,-1,-4] Output:[[-1,-1,2],[-1,0,1]] Explanation: nums[0] + nums[1]<\/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":[322,260,176,175,211,811,810,174,172,173],"tags":[],"class_list":{"0":"post-7979","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-algorithms-and-data-structures","7":"category-c-c-plus-plus","8":"category-csharp","9":"category-cplusplus","10":"category-data-structures","11":"category-data-structures-and-algorithms","12":"category-dsa","13":"category-java","14":"category-javascript","15":"category-python"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7979","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=7979"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7979\/revisions"}],"predecessor-version":[{"id":7984,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/7979\/revisions\/7984"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=7979"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=7979"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=7979"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}