-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWave array
48 lines (34 loc) · 1.15 KB
/
Wave array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
Given a sorted array arr[] of distinct integers. Modify the array to look like a wave. In other words, arrange the elements into a sequence such that a1 >= a2 <= a3 >= a4 <= a5.....
Note: The converted array must be the lexicographically smallest wave array.
Example 1:
Input:
N = 5
arr[] = {1,2,3,4,5}
Output: 2 1 4 3 5
Explanation: Array elements after
sorting it in wave form are
2 1 4 3 5.
Example 2:
Input:
N = 6
arr[] = {2,4,7,8,9,10}
Output: 4 2 8 7 10 9
Explanation: Array elements after
sorting it in wave form are
4 2 8 7 10 9.
Your Task:
You do not need to read input or print anything. The task is to complete the function convertToWave() which takes the array and n as input parameters and converts the given array to wave array. The modification must be done in-place without using any extra space. The function does not return anything to the calling function.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 106
0 ≤ arr[i] ≤107
class Solution{
public:
void convertToWave(vector<int>& arr, int n){
for(int i=0;i<n-1;i=i+2)
{
swap(arr[i],arr[i+1]);
}
}
};