{"id":881,"date":"2025-08-11T17:16:04","date_gmt":"2025-08-11T11:46:04","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=881"},"modified":"2025-08-11T17:16:06","modified_gmt":"2025-08-11T11:46:06","slug":"partition-equal-subset-sum","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/partition-equal-subset-sum\/","title":{"rendered":"Partition Equal Subset Sum | Leetcode 416"},"content":{"rendered":"\n<p>This problem is a direct extension of the&nbsp;<strong>Subset Sum Problem<\/strong>: instead of checking if any subset sums to a given target, here we check if the array can be split into&nbsp;<strong>two subsets with equal sum<\/strong>. That is equivalent to asking: is there a subset whose sum is exactly&nbsp;<strong>half of the total array sum<\/strong>?<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/leetcode.com\/problems\/partition-equal-subset-sum\/\" target=\"_blank\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><span style=\"text-decoration: underline;\">Problem Link<\/span><\/mark><\/a><\/strong>] to begin with.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What Does the Problem Say?<\/h2>\n\n\n\n<p>Given an array nums of positive integers, determine whether it can be partitioned into two subsets whose sums are equal. This is possible only if:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The\u00a0<strong>total sum is even<\/strong>\u00a0(otherwise, halves are not integers).<\/li>\n\n\n\n<li>There exists a\u00a0<strong>subset<\/strong>\u00a0that sums to\u00a0<strong>total_sum \/ 2<\/strong>.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Key Insight<\/h2>\n\n\n\n<p>Let total = sum(nums). If total is\u00a0<strong>odd<\/strong>, return\u00a0<strong>False<\/strong>\u00a0immediately. Otherwise, define k = total \/\/ 2 and solve \u201cis there a subset with sum k?\u201d, which is precisely the\u00a0<strong>Subset Sum DP<\/strong>\u00a0you solved earlier.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"space-optimized-tabulation-bottom-up-1d-dp\">Space-Optimized Tabulation (Bottom-Up 1D DP)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Intuition and Approach<\/h3>\n\n\n\n<p>We reuse the&nbsp;<strong>Subset Sum<\/strong>&nbsp;DP idea:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>prev[t] tells whether a subset from the processed prefix can achieve sum t.<\/li>\n\n\n\n<li>Initialize\u00a0<strong>prev = True<\/strong>\u00a0(empty subset makes sum 0).<\/li>\n\n\n\n<li>Seed with the\u00a0<strong>first element<\/strong>\u00a0if it\u2019s \u2264 k.<\/li>\n\n\n\n<li>For each number, compute a new curr over all targets t in [0..k]:\n<ul class=\"wp-block-list\">\n<li>pick = prev[t &#8211; nums[i]] if nums[i] \u2264 t else False<\/li>\n\n\n\n<li>not_pick = prev[t]<\/li>\n\n\n\n<li>curr[t] = pick or not_pick<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>After processing all elements, check\u00a0<strong>prev[k]<\/strong>.<\/li>\n<\/ul>\n\n\n\n<p>Why&nbsp;<strong>1D rolling array<\/strong>? Each row depends only on the previous row, so we keep two 1D arrays (prev and curr), achieving&nbsp;<strong>O(k) space<\/strong>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Code Implementation<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def canPartition(self, nums: List[int]) -&gt; bool:\n        n = len(nums)\n        target = sum(nums)\n        # Total must be even to split into two equal subsets\n        if target % 2 == 1:\n            return False\n        k = target \/\/ 2\n        prev = [False for _ in range(k + 1)]\n        prev = True  # Sum 0 is always achievable (empty subset)\n        if nums &lt;= k:\n            prev[nums] = True  # Seed with first element if within target\n        for index in range(1, n):\n            curr = [False for _ in range(k + 1)]\n            for target in range(0, k + 1):\n                # Option 1: pick current number if it doesn't exceed target\n                if nums[index] &gt; target:\n                    pick = False\n                else:\n                    pick = prev[target - nums[index]]\n                # Option 2: do not pick current number\n                not_pick = prev[target]\n                # Achievable if either pick or not_pick is True\n                curr[target] = pick or not_pick\n            prev = curr  # Move window to next element\n        if prev[k] == True:\n            return True\n        return False\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">canPartition<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">nums<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]) -&gt; <\/span><span style=\"color: #4EC9B0\">bool<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(nums)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        target = <\/span><span style=\"color: #DCDCAA\">sum<\/span><span style=\"color: #D4D4D4\">(nums)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Total must be even to split into two equal subsets<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> target % <\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\"> == <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">False<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        k = target \/\/ <\/span><span style=\"color: #B5CEA8\">2<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        prev = [<\/span><span style=\"color: #569CD6\">False<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> _ <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(k + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">)]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        prev = <\/span><span style=\"color: #569CD6\">True<\/span><span style=\"color: #D4D4D4\">  <\/span><span style=\"color: #6A9955\"># Sum 0 is always achievable (empty subset)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> nums &lt;= k:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            prev[nums] = <\/span><span style=\"color: #569CD6\">True<\/span><span style=\"color: #D4D4D4\">  <\/span><span style=\"color: #6A9955\"># Seed with first element if within target<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> index <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">, n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            curr = [<\/span><span style=\"color: #569CD6\">False<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> _ <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(k + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">)]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> target <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, k + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># Option 1: pick current number if it doesn&#39;t exceed target<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> nums[index] &gt; target:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    pick = <\/span><span style=\"color: #569CD6\">False<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">else<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    pick = prev[target - nums[index]]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># Option 2: do not pick current number<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                not_pick = prev[target]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># Achievable if either pick or not_pick is True<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                curr[target] = pick <\/span><span style=\"color: #569CD6\">or<\/span><span style=\"color: #D4D4D4\"> not_pick<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            prev = curr  <\/span><span style=\"color: #6A9955\"># Move window to next element<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> prev[k] == <\/span><span style=\"color: #569CD6\">True<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">True<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">False<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">Code Explanation<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Early exit<\/strong>\u00a0on odd total sum.<\/li>\n\n\n\n<li>Convert to subset sum:\u00a0<strong>target k = total\/2<\/strong>.<\/li>\n\n\n\n<li><strong>prev<\/strong>\u00a0represents achievable sums after processing the current prefix.<\/li>\n\n\n\n<li>For each element,\u00a0<strong>curr<\/strong>\u00a0aggregates new achievable sums using\u00a0<strong>pick\/not-pick<\/strong>\u00a0transitions.<\/li>\n\n\n\n<li>Final answer is whether\u00a0<strong>k<\/strong>\u00a0is achievable after all elements.<a href=\"https:\/\/leetcode.com\/problems\/next-greater-element-ii\/\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a><\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Time and Space Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Precise:\u00a0<strong>Time O(n \u00d7 k)<\/strong>,\u00a0<strong>Space O(k)<\/strong>, where k = total_sum \/ 2.<\/li>\n\n\n\n<li>Simplified:\u00a0<strong>Pseudo-polynomial<\/strong>\u00a0time;\u00a0<strong>linear space<\/strong>\u00a0in target.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"why-its-an-extension-of-subset-sum\">Why It\u2019s an Extension of Subset Sum<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Subset Sum<\/strong>\u00a0asks: is there a subset equal to\u00a0<strong>S<\/strong>?<\/li>\n\n\n\n<li><strong>Partition Equal Subset Sum<\/strong>\u00a0asks: can we split the array into two equal halves? That\u2019s equivalent to checking if a subset equals\u00a0<strong>total_sum\/2<\/strong>.<\/li>\n\n\n\n<li>Hence, the\u00a0<strong>same DP structure<\/strong>\u00a0applies, and the\u00a0<strong>space-optimized 1D DP<\/strong>\u00a0is the most practical solution.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"conclusion\">Conclusion<\/h2>\n\n\n\n<p>Partition Equal Subset Sum is a clean application of the&nbsp;<strong>Subset Sum DP<\/strong>&nbsp;with a simple&nbsp;<strong>parity check<\/strong>&nbsp;up front. Use the&nbsp;<strong>O(n \u00d7 k)<\/strong>&nbsp;time and&nbsp;<strong>O(k)<\/strong>&nbsp;space rolling-array DP to pass all constraints efficiently. This pattern generalizes well to many related&nbsp;<strong>partitioning<\/strong>&nbsp;and&nbsp;<strong>knapsack-style<\/strong>&nbsp;problems.<\/p>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/codeanddebug.in\/course\/zero-to-hero-python-dsa\" target=\"_blank\" rel=\"noreferrer noopener\">Join our Advance DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\" target=\"_blank\" rel=\"noreferrer noopener\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\" target=\"_blank\" rel=\"noreferrer noopener\">+91-9712928220<\/a>.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>This problem is a direct extension of the&nbsp;Subset Sum Problem: instead of checking if any subset sums to a given target, here we check if the array can be split into&nbsp;two subsets with equal sum. That is equivalent to asking: is there a subset whose sum is exactly&nbsp;half of the total array sum? Here&#8217;s the<\/p>\n","protected":false},"author":1,"featured_media":882,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,6],"tags":[39,19],"class_list":{"0":"post-881","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-intermediate","9":"tag-dynamic-programming-on-subsequence","10":"tag-medium"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/08\/partition-equal-subset-sum-featured-image.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/881","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=881"}],"version-history":[{"count":1,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/881\/revisions"}],"predecessor-version":[{"id":883,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/881\/revisions\/883"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/882"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=881"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=881"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=881"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}