![]() |
VOOZH | about |
Given an array of distinct elements of size N, the task is to rearrange the elements of the array in a zig-zag fashion, i.e., the elements are arranged as smaller, then larger, then smaller, and so on. There can be more than one arrangement that follows the form:
arr[0] < arr[1] > arr[2] < arr[3] > arr[4] < ...
Examples:
Input: N = 7, arr[] = [4, 3, 7, 8, 6, 2, 1]
Output: [3, 7, 4, 8, 2, 6, 1]
Explanation: The given array is in zig-zag pattern as we can see 3 < 7 > 4 < 8 > 2 < 6 >1Input: N = 4, arr[] = [1, 4, 3, 2]
Output: [1, 4, 2, 3]
Table of Content
The most basic approach is to solve this with the help of Sorting. The idea is to sort the array first and then swap adjacent elements (from 1st index) to make the array as zig-zag array.
Code Implementation:
1 3 2 6 4 8 7
Time complexity: O(N*log(N)), because sorting is used.
Auxiliary Space: O(1)
The most efficient and expected approach is to use the triplet relation of zig-zag array, i.e. arr[i-1] < arr[i] > arr[i+1].
The idea is that for each triplet, the middle element should be greater than its adjacent neighbours. So, for each triplet:
Code Implementation:
3 7 4 8 2 6 1
Time complexity: O(N)
Auxiliary Space: O(1)
Illustration of the Expected Approach: