{"id":2192,"date":"2024-03-05T14:00:00","date_gmt":"2024-03-05T14:00:00","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=2192"},"modified":"2024-03-07T07:06:54","modified_gmt":"2024-03-07T07:06:54","slug":"move-zeroes-problem","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/move-zeroes-problem\/","title":{"rendered":"Move Zeroes Problem Solved ( C++, Java, Python)"},"content":{"rendered":"\n<p>There are many questions based on the array asked in technical interviews and students need to have a thick grasp on them. Tt is the most basic data structure that stores a large variable simultaneously. In this article, we will try to solve the Move Zeroes problem using various ways.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What is the Move Zeroes problem?<\/strong><\/h2>\n\n\n\n<p><strong>In the Move Zeroes problem, we are given an array and we have to move all the zeroes to the end of the array, while the non-zero elements should maintain the respective order. <\/strong><\/p>\n\n\n\n<p>Let&#8217;s see an example:<\/p>\n\n\n\n<p><strong>Input:<\/strong> Arr = [ 2, 4, 5, 0, -1, 0, 0, 1, 0]<\/p>\n\n\n\n<p><strong>Output:<\/strong>\u00a0 Arr = [2, 4, 5, -1, 1, 0, 0, 0]<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/uudNDcXM_f4jXdK2ZN41ERLU607dkL5IKcmnGMTOgAuTkbkVNlupuB_TwOd2EusuYeS6-KtOxsKl4kpHeYMfh7o0L6ifrExaf14WG2K9G9Xc9SLLLk7SuTSC7Jr6mHjBz5WNrzOZ_HCtMBOxa8MYLcg\" alt=\"Example of Move Zeroes problem\"\/><\/figure>\n\n\n\n<p>The most basic approach is to <a href=\"https:\/\/favtutor.com\/blogs\/swap-cpp\">swap<\/a> the zero with the last non-zero element present in the array. Traverse the whole array and whenever you find the zero, find the first non-zero element present after that zero. Swap the zero with that element till no non-zero is found. Let\u2019s see the example:<\/p>\n\n\n\n<p>The array given to you is:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/X82BPmpMwAuAYwrsdiF2Ga19jv5EslC5P0WJmDC4VlNt4CPfPZN8ayHUFA0lusN8enBJkvrD5fqE3ycHlFSwg9YrQYz6LuUndryKaiKVb5s3ZkQ4YhMaE3a4zmQIbLVt73R6m0w_5NUyBuMxcy_Opfg\" alt=\"Given an array\"\/><\/figure>\n\n\n\n<p>After the first iteration of the array, we are:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/Hl_nZQBnsYIIU3Ptu1BFFXdqW-5SdZB7I5t2Io7fF-ZF90Puj5lVHTf1pAKXnhwdaj_RVtHVCsixRsnZF58iH_kqBL8G66oh3ORILI6bIPPV1sqp8iBpRorl_CpZ9GQ0pH5taqeeHmueEnMXfvlO7nI\" alt=\"Array after 1st operation\"\/><\/figure>\n\n\n\n<p>After the second iteration, the array will be:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/m_p-j4F6eFYoYQkBBhj5aO4dZ1zslHLpM0MhdYKlwgg5BjJ8lrgqhadikOKQNH9qnkKxWDI-8XLWj6OmFIXKMNn0-Bgci7J1GjINFkrrHMu8TChNBhJdZ7JCDoG43k5MiFouP83njl-Mf8_kXa_zcsg\" alt=\"array after 2nd operation\"\/><\/figure>\n\n\n\n<p>After the third iteration, our loop will terminate as no more non-zero elements are present after that.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/ope5ifbFRqtnroovPHAJ9sX3Q8IULrA2Exw6_wznoC2_u_O1m9bjzdHL6cl8dOXJQ2Yo2-cueULzI51s3Sna1Mm-V8MTEleDcr2PfutytcFZD2CPPRQj1a0z-4_80cCxhvYbibyMtaah0kHo9fK8hA0\" alt=\"array after 3rd operation\"\/><\/figure>\n\n\n\n<p>The time complexity of the above approach is O(n*n) where n is the size of the given array. In this approach, we traverse the array once to find all the elements with the value 0. After getting a 0 value element we are finding the non-zero element in the same loop which causes time complexity to O(n*n). The space complexity is O(1) as we are not using any extra space.\u00a0<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>The Extra Space Approach&nbsp;<\/strong><\/h2>\n\n\n\n<p>In the above approach, we are taking O(n*n) time complexity which is huge. But with The Extra Space approach, we will store each non-zero element in a new array. <\/p>\n\n\n\n<p>Now traverse the new array and update the values at each index with the new array elements. If the new array size is smaller than the size of the old array. Fill the remaining values of the old array with zeros. Let\u2019s examine the approach step by step.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>First, create a vector that will store the nonzero elements.<\/li>\n\n\n\n<li>Now traverse the old array and store nonzero elements in the new array.<\/li>\n\n\n\n<li>Now find and update the old array with the new array values.&nbsp;<\/li>\n\n\n\n<li>Fill the remaining values of the old array with the zeroes once the new array is completely traversed.<\/li>\n<\/ol>\n\n\n\n<p>The time complexity is now just O(n), where n is the size of the array. The space complexity is the same. As we are storing the values of the old array into the new array. In the worst case, all the values may be non-zero which is laid to O(n) space complexity.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Optimized Approach<\/strong><\/h2>\n\n\n\n<p><strong>The best approach to solve the Move Zeroes problem is to create an index that will store the index of the zero element present in the array. <\/strong>If we encounter any non-zero element in the array we will simply swap that with the zero element index and update our index to index+1. <\/p>\n\n\n\n<p>Let\u2019s examine this approach step by step:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Create a variable x and initialize it with 0.<\/li>\n\n\n\n<li>Iterate over the array, if you encounter any non-zero element swap this element with the element present at index x. Now update the index x to x+1.<\/li>\n\n\n\n<li>Repeat the same process for the whole array.<\/li>\n<\/ol>\n\n\n\n<p>Now is the time to code it practically.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>C++ Code<\/strong><\/h3>\n\n\n\n<p>Here is the C++ program to move zeroes to the end of array:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-c++src&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;C++&quot;,&quot;modeName&quot;:&quot;cpp&quot;}\">#include&lt;bits\/stdc++.h&gt;\nusing namespace std;\n\nint main(){\n\n\u00a0\u00a0\u00a0\u00a0vector&lt;int&gt;nums = {0, 1, -1, 0, 2, 3, 0};\n\n\u00a0\u00a0\u00a0\u00a0int x = 0;\n\n\u00a0\u00a0\u00a0\u00a0for(int i=0; i&lt;nums.size();i++){\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0if(nums[i]!=0){\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0swap(nums[i], nums[x]);\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0x++;\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0}\n\n\u00a0\u00a0\u00a0\u00a0}\n\n\u00a0\u00a0\u00a0\u00a0cout&lt;&lt;&quot;After moving zeroes to the back array will look like &quot;&lt;&lt;endl;\n\n\u00a0\u00a0\u00a0\u00a0for(int i=0; i&lt;nums.size();i++){\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0cout&lt;&lt;nums[i]&lt;&lt;&quot; &quot;;\n\n\u00a0\u00a0\u00a0\u00a0}\n\n\u00a0\u00a0\u00a0\u00a0return 0;\n\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Java Code<\/strong><\/h3>\n\n\n\n<p>Here is the Java program:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Java&quot;,&quot;modeName&quot;:&quot;java&quot;}\">import java.util.*;\n\npublic class MoveZeroes {\n\n\u00a0\u00a0\u00a0\u00a0public static void main(String[] args) {\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0List&lt;Integer&gt; nums = new ArrayList&lt;&gt;(Arrays.asList(0, 1, -1, 0, 2, 3, 0));\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0int x = 0;\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0for (int i = 0; i &lt; nums.size(); i++) {\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0if (nums.get(i) != 0) {\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0Collections.swap(nums, i, x);\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0x++;\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0}\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0}\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0System.out.println(&quot;After moving zeroes to the back array will look like&quot;);\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0for (int num: nums) {\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0System.out.print(num + &quot; &quot;);\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0}\n\n\u00a0\u00a0\u00a0\u00a0}\n\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Python Code<\/strong><\/h3>\n\n\n\n<p>We can also solve the problem with Python:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\">nums = [0, 1, -1, 0, 2, 3, 0]\n\nx = 0\n\nfor i in range(len(nums)):\n\n\u00a0\u00a0\u00a0\u00a0if nums[i] != 0:\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0nums[i], nums[x] = nums[x], nums[i]\n\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0x += 1\n\nprint(&quot;After moving zeroes to the back array will look like&quot;)\n\nfor num in nums:\n\n\u00a0\u00a0\u00a0\u00a0print(num, end=&quot; &quot;)<\/pre><\/div>\n\n\n\n<p><strong>Output:&nbsp;<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background has-link-color wp-elements-9dcffc2a05219271807f4b758a453db6\" style=\"background-color:#fedcba\"><code>After moving zeroes to the back array will look like\n1 -1 2 3 0 0 0<\/code><\/pre>\n\n\n\n<p>The time complexity of the optimized approach for the Move Zeroes Problem is O(n) as we are just traversing the array once. The space complexity is also reduced to O(1) as we are not using any extra space.<\/p>\n\n\n\n<p>Here is a comparison of all the methods:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td class=\"has-text-align-center\" data-align=\"center\"><strong>Approach<\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong>Time Complexity<\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong>Space Complexity<\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong>Description<\/strong><\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\">Brute Force Approach<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(n*n)<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(1)<\/td><td class=\"has-text-align-center\" data-align=\"center\">We are using one nested loop to find the last non-zero element for each zero element.&nbsp;<\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\">Extra Space Approach<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(n)<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(n)<\/td><td class=\"has-text-align-center\" data-align=\"center\">We are using an extra array to store the non-zero elements in the array.&nbsp;<\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\">Optimized Approach<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(n)<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(1)<\/td><td class=\"has-text-align-center\" data-align=\"center\">We are not using any extra space, also we are just traversing the array once.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>In this article, we solved the Move Zeroes problem from the <a href=\"https:\/\/leetcode.com\/problems\/move-zeroes\/description\/\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">leetcode<\/a>. We saw that the optimized approach had reduced the time complexity from O(n*n) to O(n) and it has also reduced the space complexity from O(n) to O(1). Some of the other problems you can practice with are <a href=\"https:\/\/favtutor.com\/blogs\/degree-of-array\">finding the degree of an array<\/a>, <a href=\"https:\/\/favtutor.com\/articles\/kth-largest-element\/\">finding kth largest element<\/a>, the <a href=\"https:\/\/favtutor.com\/blogs\/valid-mountain-array\">Valid Mountain Array problem<\/a>, etc. <\/p>\n","protected":false},"excerpt":{"rendered":"<p>We will try to solve the Move Zeroes Problem from leetcode, with implementation in C++, Java, and Python.<\/p>\n","protected":false},"author":14,"featured_media":2194,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[7],"tags":[14,15],"class_list":["post-2192","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-structures-algorithms","tag-dsa","tag-leetcode"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/2192","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=2192"}],"version-history":[{"count":3,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/2192\/revisions"}],"predecessor-version":[{"id":2215,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/2192\/revisions\/2215"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/2194"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=2192"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=2192"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=2192"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}