![]() |
Given an array, our task is to separate 0s and 1s in an array using JavaScript. We have to rearrange the array such that all 0s appear before all 1s. Example: Input: array = [ 0 , 1 , 1, 0 , 1, 0, 1] Table of Content Using for loopInitialize a variable countZeroes to 0 to keep track of the number of zeroes in the array. Now Iterate through the array and increment countZeroes each time a zero is encountered. Iterate through the array again. For the first countZeroes elements, set them to 0, and for the rest of the elements, set them to 1. Return the modified array. Example: The example below shows how to Separate 0s and 1s using Simple Counting.
Output [ 0, 0, 0, 1, 1, 1, 1 ] Time Complexity: O(n) Space Complexity: O(1) Using Two-pointer ApproachUse two pointers, left and right, initialized at the start and end of the array, respectively. Move left towards the right until finding a 1, and move right towards the left until finding a 0. Then, Swap these elements. Continue until left is less than right. Finally, return the modified array. Example: The example below shows how to Separate 0s and 1s using Two-pointer Approach.
Output [ 0, 0, 0, 1, 1, 1, 1 ] Time Complexity: O(n) Space Complexity: O(1) |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 17 |