[InterviewBit] Segregate 0s and 1s in an array

Segregate 0s and 1s in an array

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
vector<int> Solution::solve(vector<int> &A) {
int l = 0, r = A.size() - 1;
while(l < r) {
while(A[l] == 0) l++;
while(A[r] == 1) r--;
if(l < r) swap(A[l],A[r]);
}
return A;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/14/PS/interviewbit/segregate-0s-and-1s-in-an-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.