Move all the negative numbers to beginning and positive numbers to end in array

preview_player
Показать описание
JOIN ME
—————

COMPLETE PLAYLIST
————————————

INTERVIEW PLAYLIST
————————————

QUICK SHORT VIDEOS
————————————-

Time Lines
=========
0:05 Introduction
1:04 Approach

In this video we will learn how to move all the negative elements to beginning and positive elements to the end of the array.

There are multiple ways to do this, I have explained two pointers technique.
Where first pointer will point to the left of the array and second pointer will point the end of the array and then we will keep comparing the first and second pointer to check if they are in correct order and if they are not then we will swap otherwise we will increment or decrement first and or second pointers, and like this we will have all the negative elements in the left and positive elements in the right hand side.

#array #dsa #Algorithms #DatasStructure
Рекомендации по теме
Комментарии
Автор

int j=0;
for(let i=0; i<arr.length; i++){
if(arr[i]<0){
if(i!==j){
swap(arr[i], arr[j])
}
j++;
}
}

more optimized way

varnitgupta
Автор

What if the order of the elements matters? Can we solve it in O(n) provided extra constant memory space .

prathu
Автор

this will happen if we don't give the solution what we are looking for, no comments no discussion even after 2 years. remembers people are coming here for the solution not to solve and report to the youtubers for that we have leetcode and many tools.

sandipram