{"id":344,"date":"2025-06-22T13:56:59","date_gmt":"2025-06-22T08:26:59","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=344"},"modified":"2025-07-07T20:45:43","modified_gmt":"2025-07-07T15:15:43","slug":"move-zeroes-leetcode-283","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/move-zeroes-leetcode-283\/","title":{"rendered":"Move Zeroes | Leetcode 283 | Explained"},"content":{"rendered":"\n<p>Given an integer array&nbsp;<code>nums<\/code>, move all&nbsp;<code>0<\/code>&#8216;s to the end of it while maintaining the relative order of the non-zero elements.<\/p>\n\n\n\n<p><strong>Note<\/strong>&nbsp;that you must do this in-place without making a copy of the array.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/leetcode.com\/problems\/move-zeroes\/description\/\" 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<div style=\"max-width: -moz-fit-content; \" class=\"wp-block-ub-table-of-contents-block ub_table-of-contents ub_table-of-contents-collapsed\" id=\"ub_table-of-contents-37b953f7-52e0-4dc0-b00d-4e274419f352\" data-linktodivider=\"false\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" data-enablesmoothscroll=\"true\" data-initiallyhideonmobile=\"false\" data-initiallyshow=\"false\"><div class=\"ub_table-of-contents-header-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-header\" style=\"text-align: left; \">\n\t\t\t\t<div class=\"ub_table-of-contents-title\">Contents:<\/div>\n\t\t\t\t<div class=\"ub_table-of-contents-header-toggle\">\n\t\t\t<div class=\"ub_table-of-contents-toggle\" style=\"\">\n\t\t\t\u00a0[<a class=\"ub_table-of-contents-toggle-link\" href=\"#\" style=\"\">show<\/a>]\n\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t<\/div>\n\t\t<\/div><div class=\"ub_table-of-contents-extra-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-container ub_table-of-contents-1-column ub-hide\">\n\t\t\t\t<ul style=\"\"><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/move-zeroes-leetcode-283\/#0-brute-force-solution\" style=\"\">BRUTE FORCE SOLUTION<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/move-zeroes-leetcode-283\/#1-1-problem-statement-\" style=\"\">1. Problem Statement<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/move-zeroes-leetcode-283\/#2-2-intuition-and-approach-\" style=\"\">2. Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/move-zeroes-leetcode-283\/#3-3-code-\" style=\"\">3. Code<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/move-zeroes-leetcode-283\/#4-4-dry-run-\" style=\"\">4. Dry Run<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/move-zeroes-leetcode-283\/#5-5-edge-cases-\" style=\"\">5. Edge Cases<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/move-zeroes-leetcode-283\/#6-6-time-and-space-complexity-\" style=\"\">6. Time and Space Complexity<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/move-zeroes-leetcode-283\/#7-optimal-solution\" style=\"\">OPTIMAL SOLUTION<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/move-zeroes-leetcode-283\/#8-1-problem-statement-\" style=\"\">1. Problem Statement<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/move-zeroes-leetcode-283\/#9-2-intuition-and-approach-\" style=\"\">2. Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/move-zeroes-leetcode-283\/#10-3-code-\" style=\"\">3. Code<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/move-zeroes-leetcode-283\/#11-4-dry-run-\" style=\"\">4. Dry Run<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/move-zeroes-leetcode-283\/#12-5-edge-cases-\" style=\"\">5. Edge Cases<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/move-zeroes-leetcode-283\/#13-6-time-and-space-complexity-\" style=\"\">6. Time and Space Complexity<\/a><\/li><\/ul><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"0-brute-force-solution\">BRUTE FORCE SOLUTION<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"1-1-problem-statement-\"><strong>1. Problem Statement<\/strong><\/h3>\n\n\n\n<p>Our goal is to moving all zeros in a given array nums to the end while maintaining the relative order of the non-zero elements. The operation is done in-place, modifying the original array without returning any value.<\/p>\n\n\n\n<p><strong>Input:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>nums: A list of integers, where zeros and non-zeros are mixed.<\/li>\n<\/ul>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>No explicit output; the function modifies the array nums directly, placing all zero elements at the end while keeping the order of non-zero elements unchanged.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"2-2-intuition-and-approach-\"><strong>2. Intuition and Approach<\/strong><\/h3>\n\n\n\n<p>The approach taken in this code involves separating the non-zero elements from the zeros to streamline the rearrangement process:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Traverse the array and copy all non-zero elements into a temporary list called temp.<\/li>\n\n\n\n<li>Replace the beginning of the original array with the contents of temp, effectively moving all non-zero elements to the front.<\/li>\n\n\n\n<li>Fill the remainder of the array with zeros, starting from the index where the non-zero elements end.<\/li>\n<\/ol>\n\n\n\n<p>This method ensures that non-zero elements retain their original sequence, and all zeros are pushed to the end of the array.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"3-3-code-\"><strong>3. Code<\/strong><\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" 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;line-height:1.25rem;--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 moveZeroes(self, nums: List[int]) -&gt; None:\n        n = len(nums)\n        temp = []\n\n        # Copy non-zero elements from original to temp array\n        for i in range(n):\n            if nums[i] != 0:\n                temp.append(nums[i])\n\n        # Number of non-zero elements\n        nz = len(temp)\n\n        # Copy elements from temp to fill first nz fields of original array\n        for i in range(nz):\n            nums[i] = temp[i]\n\n        # Fill the rest of the cells with 0\n        for i in range(nz, n):\n            nums[i] = 0\" 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\">moveZeroes<\/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: #569CD6\">None<\/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\">        temp = []<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Copy non-zero elements from original to temp array<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> nums[i] != <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                temp.append(nums[i])<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Number of non-zero elements<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        nz = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(temp)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Copy elements from temp to fill first nz fields of original array<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(nz):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            nums[i] = temp[i]<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Fill the rest of the cells with 0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(nz, n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            nums[i] = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Initialization and Temporary Storage:<\/strong>\n<ol class=\"wp-block-list\">\n<li>A temporary list temp is created to store non-zero elements found during the traversal of nums.<\/li>\n<\/ol>\n<\/li>\n\n\n\n<li><strong>Extract Non-Zero Elements:<\/strong>\n<ol class=\"wp-block-list\">\n<li>The array nums is traversed, and each non-zero element is appended to temp.<\/li>\n<\/ol>\n<\/li>\n\n\n\n<li><strong>Refill Original Array with Non-Zero Elements:<\/strong>\n<ol class=\"wp-block-list\">\n<li>The length of temp, stored in nz, indicates the number of non-zero elements.<\/li>\n\n\n\n<li>The first nz positions of nums are overwritten with the elements from temp, placing all non-zero elements at the start of nums.<\/li>\n<\/ol>\n<\/li>\n\n\n\n<li><strong>Fill Remaining Positions with Zeros:<\/strong>\n<ol class=\"wp-block-list\">\n<li>The remainder of the array from index nz to n (length of nums) is filled with zeros, moving all zeros to the end of the array.<\/li>\n<\/ol>\n<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-4-dry-run-\"><strong>4. Dry Run<\/strong><\/h3>\n\n\n\n<p>Let&#8217;s go through the code step by step, using images to illustrate the detailed dry run process.<\/p>\n\n\n\n<p>First, put all the <strong>non-zero<\/strong> elements in <strong>temp<\/strong> variable.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-rt.googleusercontent.com\/docsz\/AD_4nXcRWEPlYxtOCccg9rD0_-uZRbl48W4SAO4LcU74MvDWmfZ6OQjsLS-WRJTgA-32-bP31XXcPKUkM0Q4WQU40rWSmfaP25GDEOYbpQzdMGUn0-R1ed5LIPdlrpZDTSdxDm9aaZXQUQ?key=_Rt2-2fk3TBUeq32lxCmjw\" alt=\"\"\/><\/figure>\n\n\n\n<p>Now put all the non zero elements in start indexes.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-rt.googleusercontent.com\/docsz\/AD_4nXcG1AZIvy8yt1hujsl6P0wPxtneAIj3-OxZat6o95nA0tnhSnnvuJRiLDIetPx82zdY1fdIGbnLUriceVwm9rsz4KWZ-YQ3mXn_AdTuPeebjZ9yG4CR-T_XmutGh_0AWhT4LfM-?key=_Rt2-2fk3TBUeq32lxCmjw\" alt=\"\"\/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"5-5-edge-cases-\"><strong>5. Edge Cases<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>All Zeros:<\/strong> If nums contains only zeros (e.g., nums = [0, 0, 0]), the function should fill nums with zeros, which it does effectively.<\/li>\n\n\n\n<li><strong>No Zeros:<\/strong> If there are no zeros (e.g., nums = [1, 2, 3]), nums remains unchanged after the operation, as expected.<\/li>\n\n\n\n<li><strong>Empty Array:<\/strong> If nums is empty, the function should handle this by performing no operations.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"6-6-time-and-space-complexity-\"><strong>6. Time and Space Complexity<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time Complexity:<\/strong> The complexity is O(n) due to three separate but sequential traversals of the array (n is the length of nums): one to fill temp, one to copy non-zeros back, and one to add zeros.<\/li>\n\n\n\n<li><strong>Space Complexity:<\/strong> The space complexity is <strong>O(n)<\/strong> for the temporary list temp, which in the worst case (no zeros) stores a copy of all elements from nums.<\/li>\n<\/ul>\n\n\n\n<p><strong>Efficiency:<\/strong> The method is effective for its clarity and ensures that all non-zero elements maintain their order relative to each other. However, the space efficiency could be improved by using a different approach that does not require additional storage, such as a two-pointer technique that swaps zeros with non-zero elements in-place without extra storage.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"7-optimal-solution\">OPTIMAL SOLUTION<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"8-1-problem-statement-\"><strong>1. Problem Statement<\/strong><\/h3>\n\n\n\n<p>Our goal is to rearrange an array nums by moving all zero elements to the end while maintaining the relative order of the non-zero elements. The task is accomplished in-place, modifying the original array without returning any value.<\/p>\n\n\n\n<p><strong>Input:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>nums: A list of integers where zero and non-zero elements may be mixed.<\/li>\n<\/ul>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>No explicit output is provided; the array nums is modified directly, with all zero elements moved to the end.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"9-2-intuition-and-approach-\"><strong>2. Intuition and Approach<\/strong><\/h3>\n\n\n\n<p>The approach used here employs the two-pointer technique to efficiently separate zero and non-zero elements:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>The first pointer, i, is used to find the first zero in the array.<\/li>\n\n\n\n<li>The second pointer, j, starts from i + 1 and is used to find the next non-zero element to swap with the zero at index i.<\/li>\n\n\n\n<li>This process continues, incrementally moving the i pointer each time a swap is made, effectively &#8220;collecting&#8221; non-zero elements at the start of the array and pushing zeros to the end.<\/li>\n<\/ol>\n\n\n\n<p>This method ensures that the operations are done in-place, and by avoiding the use of extra storage or multiple passes, it optimizes both space and time efficiency.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"10-3-code-\"><strong>3. Code<\/strong><\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" 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;line-height:1.25rem;--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 moveZeroes(self, nums: List[int]) -&gt; None:\n        if len(nums) == 1:\n            return\n        i = 0\n        while i &lt; len(nums):\n            if nums[i] == 0:\n                break\n            i += 1\n        else:\n            return\n        j = i + 1\n        while j &lt; len(nums):\n            if nums[j] != 0:\n                nums[i], nums[j] = nums[j], nums[i]\n                i += 1\n            j += 1\" 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\">moveZeroes<\/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: #569CD6\">None<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(nums) == <\/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>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        i = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> i &lt; <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(nums):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> nums[i] == <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">break<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            i += <\/span><span style=\"color: #B5CEA8\">1<\/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\">            <\/span><span style=\"color: #C586C0\">return<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        j = i + <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> j &lt; <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(nums):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> nums[j] != <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                nums[i], nums[j] = nums[j], nums[i]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                i += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            j += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Initial Checks:<\/strong>\n<ol class=\"wp-block-list\">\n<li>If the array contains only one element, no action is needed, and the function returns immediately.<\/li>\n<\/ol>\n<\/li>\n\n\n\n<li><strong>Find First Zero:<\/strong>\n<ol class=\"wp-block-list\">\n<li>The i pointer is used to locate the first zero in the array. If no zero is found and i reaches the end of the array, the function exits as no zeros need moving.<\/li>\n<\/ol>\n<\/li>\n\n\n\n<li><strong>Rearranging Elements:<\/strong>\n<ol class=\"wp-block-list\">\n<li>The j pointer starts from the next index after i and scans for non-zero elements.<\/li>\n\n\n\n<li>When a non-zero element is found, it is swapped with the zero at the i index. After the swap, i is incremented to point to the next zero, ready for a future swap.<\/li>\n\n\n\n<li>This process continues until j has scanned through to the end of the array.<\/li>\n<\/ol>\n<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"11-4-dry-run-\"><strong>4. Dry Run<\/strong><\/h3>\n\n\n\n<p>Let&#8217;s go through the code step by step, using images to illustrate the detailed dry run process.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-rt.googleusercontent.com\/docsz\/AD_4nXdeEj5E0e9MXXStU7jD3a-RJR6VuaOOH6-dOTEjOLSBwmNLBLpEPb9QBr7bEOGsBIhc4KFcfe84Y4XMWgJj_LUjkys8nchqOgsPUHWI5wNDszmlw2c35qijcH1e1zx6pFMI7MlJ?key=_Rt2-2fk3TBUeq32lxCmjw\" alt=\"\"\/><\/figure>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-rt.googleusercontent.com\/docsz\/AD_4nXeqZSk85tLI7FzUeBhHEWt3d6fg8ldi-_vgvX5tXmeDXU086kEe_h4sBVNmqW3gQ9U6piqw-hxwYTKuLjiUZgWJDKrDOP0-Bk22iMdi_YMlQHpSPZrDgh9rYND1d1Y_JDHz0uGqWA?key=_Rt2-2fk3TBUeq32lxCmjw\" alt=\"\"\/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"12-5-edge-cases-\"><strong>5. Edge Cases<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>All Zeros:<\/strong> If nums contains only zeros (e.g., nums = [0, 0, 0]), the array remains unchanged, but the method handles it efficiently.<\/li>\n\n\n\n<li><strong>No Zeros:<\/strong> If there are no zeros (e.g., nums = [1, 2, 3]), the method terminates early after the initial scan, leaving the array unchanged.<\/li>\n\n\n\n<li><strong>Empty Array:<\/strong> If nums is empty, the function does nothing, as expected.<\/li>\n\n\n\n<li><strong>Single Element:<\/strong> A single element (whether zero or non-zero) needs no action, as handled by the initial return.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"13-6-time-and-space-complexity-\"><strong>6. Time and Space Complexity<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time Complexity:<\/strong> The complexity is <strong>O(n)<\/strong>, where n is the length of the array. Each element is considered at most once by the j pointer.<\/li>\n\n\n\n<li><strong>Space Complexity:<\/strong> The complexity is <strong>O(1)<\/strong> as the solution modifies the array in place without using additional storage.<\/li>\n<\/ul>\n\n\n\n<p><strong>Efficiency:<\/strong> This method is space-efficient due to its in-place operation and time-efficient due to its linear complexity. By directly moving non-zero elements forward and letting zeros fill the remaining indices, it maintains the order of non-zero elements without additional data structures.<\/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:\/\/www.codeanddebug.in\/course\/zero-to-hero-python-dsa\">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\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\">+91-9712928220<\/a>.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Given an integer array&nbsp;nums, move all&nbsp;0&#8216;s to the end of it while maintaining the relative order of the non-zero elements. Note&nbsp;that you must do this in-place without making a copy of the array. Here&#8217;s the [Problem Link] to begin with. BRUTE FORCE SOLUTION 1. Problem Statement Our goal is to moving all zeros in a<\/p>\n","protected":false},"author":1,"featured_media":554,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,4],"tags":[],"class_list":{"0":"post-344","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-beginner"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/06\/move-zeros-to-end-of-the-list-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\/344","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=344"}],"version-history":[{"count":2,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/344\/revisions"}],"predecessor-version":[{"id":555,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/344\/revisions\/555"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/554"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=344"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=344"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=344"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}