AfterAcademy Tech
•
08 Dec 2019

Difficulty: Easy
Asked in: Amazon, Google, Adobe
Problem Description: Given an array A[] having n elements, you need to sort the array in wavy manner. In wavy manner the array is in the form where A[0] >= A[1] <= A[2] >= A[3] <= A[4] >= …..
For example:
Input: A[]=[15, 6, 7, 5, 3, 30, 70, 45]
Output: A[]=[15, 6, 7, 3, 30, 5, 70, 45] Or A[]=[30, 6, 15, 3, 45, 7, 70, 5] Or any other array in wavy form
Input: A[]=[40, 10, 4, 2, 6, 1]
Output: A[]=[40, 4, 10, 2, 6, 1] Or A[]=[10, 4, 6, 1, 40, 2] Or any other array in wavy form
Possible follow up questions to ask the interviewer:-
We are going to discuss two possible solutions for this problem →
A very simple way of printing an array in wavy way is to sort the entire array and swap all adjacent elements. Using this technique all the elements will get arranged such that A[0]≥A[1]≤A[2]≥A[3]….
Now you can output the array to get it in a wavy way.
Pseudo-code
void SortWavyArray(int A[], int n)
{
sort(A, A+n)
for(i = 0 to n-1 with increment of 2)
swap(A[i], A[i+1])
}
Complexity Analysis
Suppose we are using comparison based sorting algorithm Heap Sort or Megre Sort for the implementation.
Time complexity: Sorting the array + Single Traversal of array (Increment by 2) = O(nlogn) + O(n) = O(nlogn)
Space Complexity: O(1), if we use Heap Sort, else O(n) if we use Meerge Sort
Critical ideas to think!
We don’t need to use sort, we can simply compare adjacent elements, the element at even places should be greater than the adjacent odd element. Also, we need to check the present even positioned element with the previous odd element. Thus swap will be done when →
Pseudo-code
void SortWavyArray(int A[], int n)
{
for(i = 0 to n-1 with increment of 2)
{
if( i > 0 && A[i] > A[i-1] )
swap(A[i], A[i-1])
if( i < (n-1) && A[i] < A[i+1] )
swap(A[i], A[i+1])
}
}
Complexity Analysis
Time Complexity: O(n) (Think!)
Space Complexity: O(1)
Critical ideas to think!

If you have any more approaches or you find an error/bug in the above solutions, please comment down below.
Keep Spreading Codes!!
AfterAcademy Tech
This is an interview problem asked in companies like Google, Microsoft, Amazon. The problem is to remove duplicates from a sorted array or list.

AfterAcademy Tech
Given an array of integers A[ ], if i < j and A[i] > A[j] then the pair (i, j) is called the inversion of an array A[ ]. You need to write a program to find the total counts of inversion in an array A[ ]. The inversion count of an array suggests how close the array is from being sorted. This problem has been asked in Amazon and Google's interview.

AfterAcademy Tech
Given two integer array A[] and B[] of size m and n(n <= m) respectively. We have to check whether B[] is a subset of A[] or not. An array B is a subset of another array A if each element of B is present in A. (There are no repeated elements in both the arrays)

AfterAcademy Tech
Sort a linked list using insertion sort and return its head.
