Skip to content

Commit 632ea27

Browse files
committed
added closest 012 Problem
1 parent 66ecd34 commit 632ea27

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

.vscode/settings.json

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"files.associations": {
3+
"*.ts": "typescript",
4+
"iostream": "cpp",
5+
"ostream": "cpp"
6+
}
7+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
void closest012(int arr[], int n)
5+
{
6+
int lo = 0, hi = n - 1, mid = 0;
7+
while (mid <= hi)
8+
{
9+
if (arr[mid] == 0)
10+
{
11+
swap(arr[lo], arr[mid]);
12+
lo++;
13+
mid++;
14+
}
15+
else if (arr[mid] == 1)
16+
{
17+
mid++;
18+
}
19+
else
20+
{
21+
swap(arr[mid], arr[hi]);
22+
hi--;
23+
}
24+
}
25+
}
26+
int main()
27+
{
28+
29+
int t;
30+
cin >> t;
31+
while (t--)
32+
{
33+
int n;
34+
cin >> n;
35+
int arr[n];
36+
for (int i = 0; i < n; i++)
37+
{
38+
cin >> arr[i];
39+
}
40+
closest012(arr, n);
41+
for (int i = 0; i < n; i++)
42+
{
43+
cout << arr[i];
44+
}
45+
cout << endl;
46+
}
47+
48+
return 0;
49+
}
50+
51+
// Given an array of 0s, 1s, and 2s. Arrange the array elements such that all 0s come first, followed by all the 1s and then, all the 2s.
52+
// Input: N = 5, arr[] = {0, 2, 1, 2, 0}
53+
// Output: 0 0 1 2 2

0 commit comments

Comments
 (0)