HackerRank: Zig Zag Sequence

Given an array of distinct integers, transform the array into a zig zag sequence by permuting the array elements. A sequence will be called a zig-zag sequence if the first elements in the sequence are in increasing order and the last elements are in decreasing order. You need to find the lexicographically smallest zig zag sequence of the given array.

void findZigZagSequence(vector < int > a, int n){
    sort(a.begin(), a.end());
    int mid = n/2; 
    swap(a[mid], a[n-1]);

    int st = mid + 1;
    int ed = n - 2;
    while(st <= ed){
        swap(a[st], a[ed]);
        st = st + 1;
        ed = ed - 1; 
    }
    for(int i = 0; i < n; i++){
        if(i > 0) cout << " ";
        cout << a[i];
    }
    cout << endl;
}

Leave a Comment