Skip to content

Commit

Permalink
Merge pull request Zubair-droid#16 from monarchsharma/main
Browse files Browse the repository at this point in the history
Rearrange array alternatively
  • Loading branch information
Zubair-droid authored Oct 13, 2021
2 parents 8ba9fe3 + 8e7868e commit d3fcdf6
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions rearrangeArrayAlternatively.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
//Rearrange array alernatively
//level medium
//company : ZOHO
//This is the most efficient approach with
// Expected Time Complexity: O(N).
// Expected Auxiliary Space: O(1).
#include <bits/stdc++.h>

using namespace std;

int main()
{
int t, n;
//test cases
cin >> t;
while (t--)
{
//size of array
cin >> n;
long long arr[n];
//adding elements
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}

int max_index = n - 1;
int min_index = 0;
int max = arr[n - 1] + 1;

for (int i = 0; i < n; i++)
{
if (i % 2 == 0)
{
arr[i] = (arr[max_index] % max) * max + arr[i];
max_index--;
}
else
{
arr[i] = (arr[min_index] % max) * max + arr[i];
min_index++;
}
}

for (int i = 0; i < n; i++)
{
arr[i] /= max;
}
//printing elements
for (int i = 0; i < n; i++)
cout << arr[i] << " ";

cout << "\n";
}
}

0 comments on commit d3fcdf6

Please sign in to comment.