In-place Algorithm to Move Zeros to End of List in JavaScript


Effectively manipulating data structures is a crucial aspect of contemporary software development. In JavaScript, one typical task is relocating all the zeros in an array to the end, while preserving the order of the non-zero elements. Although various methods exist to achieve this, the in-situ algorithm is a particularly potent technique that avoids the necessity of extra data structures. In this discourse, we will scrutinize the complexities of the in-situ algorithm to move zeros to the end of an array in JavaScript, probing the underlying reasoning and offering systematic instructions for execution. By mastering this technique, software developers can refine their code and ameliorate the general efficiency of their applications.

Problem Statement

The issue to be addressed is the existence of zeros in a series that can unfavorably influence the computational efficiency of subsequent operations. The objective of this investigation is to design a technique that can competently reorder the sequence by placing the zeros at the end of it, without changing the relative location of other non-zero elements. The intended approach strives to optimize the temporal intricacy of the procedure by executing the relocation of the zeros in a sole traversal of the sequence.

To exemplify the quandary, contemplate the input list

[2, 5, 0, 1, 0, 8, 0, 3]

where 0 represents the noughts.

The coveted output would be

[2, 5, 1, 8, 3, 0, 0, 0]

where the noughts have been shifted to the tail end of the list while preserving the initial sequence of non-zero components.

Approach

In this article, we are going to see a number of different ways to solve the above problem statement in JavaScript −

  • Two Pointer Approach

  • Count and Fill Approach

Method 1: Two Pointer Approach

To separate zeros from non-zero elements in a list, initialize two pointers, i and j, at the beginning of the list. Iterate through the list using the i pointer. If the element at i is non-zero, swap it with the element at j and increment both pointers. If the element at i is zero, only increment the i pointer. Continue this process until i reaches the end of the list. By the end, all non-zero elements will be on the left side, while the zeros will naturally be on the right side.

Example

The moveZerosToEnd function takes an array nums as input and moves zeros to the end in-place. It utilizes two pointers, i and j, with i iterating through the array and j keeping track of the position for non-zero elements. The while loop continues until i reaches the end. If the element at i is non-zero, a swap occurs between i and j using array destructuring, and j increments. If the element at i is zero, no swap occurs, and only i increments. Once the loop finishes, the function returns the modified nums array with non-zero elements on the left and zeros on the right.

function moveZerosToEnd(nums) {
   let i = 0;
   let j = 0;
   const len = nums.length;
 
   while (i < len) {
      if (nums[i] !== 0) {
         [nums[i], nums[j]] = [nums[j], nums[i]];
         j++;
      }
      i++;
   }
 
   return nums;
}
 
// Example usage:
const nums = [0, 1, 0, 3, 12];
console.log(moveZerosToEnd(nums));

Output

The following is the console output −

[ 1, 3, 12, 0, 0 ]

Method 2: Count and Fill Approach

To transform a list, first, initialize a count variable to track the number of zeros. Then, iterate through the list, incrementing the count for each zero found. Create a new array to hold the transformed result. Iterate through the list again, appending non-zero elements to the new array. Lastly, append count number of zeros to the new array. Return the new array as the transformed result.

Example

The moveZerosToEnd function takes an array nums as input and moves zeros to the end in-place. It initializes a count variable to track the number of zeros encountered and creates an empty result array. A for loop iterates through the nums array, incrementing count for zeros and pushing non-zero elements to the result array. After the loop, a while loop runs count times, pushing zeros into the result array and decrementing count. The function returns the modified result array with non-zero elements followed by zeros.

function moveZerosToEnd(nums) {
   let count = 0;
   const result = [];
 
   for (let i = 0; i < nums.length; i++) {
      if (nums[i] === 0) {
         count++;
      } else {
         result.push(nums[i]);
      }
   }
 
   while (count > 0) {
      result.push(0);
      count--;
   }
 
   return result;
}
 
// Example usage:
const nums = [0, 1, 0, 3, 12];
console.log(moveZerosToEnd(nums));

Output

The following is the console output −

[ 1, 3, 12, 0, 0 ]

Conclusion

In summary, the utilization of an in-place algorithm in JavaScript to reposition zeros to the end of a list is a sagacious and utilitarian solution that can enhance the effectiveness of web applications. This algorithmic strategy can be advantageous in situations where memory consumption is paramount, as it avoids the creation of a fresh list and instead rearranges the existing list. There exist diverse techniques to execute this methodology, including deploying multiple pointers, recursive functions, or a fusion of both. Thus, developers must opt for the most fitting technique based on their particular constraints and demands. Ultimately, utilizing an in-place algorithm in JavaScript to transfer zeros to the end of a list can streamline code efficiency and utility.

Updated on: 04-Aug-2023

163 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements