Practice › Arrays
Wave Array
Easy · Arrays · Asked at Amazon, Microsoft, TCS, Infosys
The array is sorted in non-decreasing order. Rearrange it into a wave — a[0] ≥ a[1] ≤ a[2] ≥ a[3] ≤ … — by swapping a[0] with a[1], a[2] with a[3], and so on. If n is odd, the last element stays where it is.
Print the array after these swaps.
Input
First line: n. Second line: n space-separated integers.
Output
The rearranged array, space-separated.
Constraints
- 1 ≤ n ≤ 10^5
- −10^9 ≤ a[i] ≤ 10^9
- the array is sorted
Example 1
Input
5 1 2 3 4 5
Output
2 1 4 3 5
Example 2
Input
6 2 4 7 8 9 10
Output
4 2 8 7 10 9
Hints
- In a sorted array, a[1] ≥ a[0] and a[3] ≥ a[2] …
- Swapping each pair puts the bigger one first.
Approach
Walk with a step of 2 and swap a[i] with a[i + 1]. Each pair now goes big-then-small, and because the array was sorted, the small element of one pair is never larger than the big element of the next pair — so the whole array zig-zags. With odd n the last element stays put.
Complexity: O(n) time · O(1) extra space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<long long> a(n);
for (auto &x : a) cin >> x;
for (int i = 0; i + 1 < n; i += 2) swap(a[i], a[i + 1]);
for (int i = 0; i < n; i++) cout << a[i] << (i + 1 < n ? ' ' : '\n');
return 0;
}Python solution
import sys
data = sys.stdin.read().split()
n = int(data[0])
a = data[1 : 1 + n]
for i in range(0, n - 1, 2):
a[i], a[i + 1] = a[i + 1], a[i]
print(" ".join(a))Java solution
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine().trim());
String[] a = br.readLine().trim().split("\\s+");
for (int i = 0; i + 1 < n; i += 2) {
String t = a[i];
a[i] = a[i + 1];
a[i + 1] = t;
}
System.out.println(String.join(" ", a));
}
}