Game of Dominoes

Rafiq loves to play with dominoes. On his birthday his father gifted him ‘N’ piles of dominoes, where each pile contains a positive number of dominoes stacked above.

Rafiq loves to play with piles if they are of equal heights, so his father decides to make changes to the piles. His father wonders for each consecutive window of length ‘K’ what is the minimum cost to make them all of the equal height. Hence his father wants to calculate the cost for each window.

The cost for removing and adding one domino on any pile is one unit.

Determine what is the cost to make all elements equal in a window of size 'K', for all windows of size 'K' in an 'N'-sized array/list 'heights'.

Input Format:
The first line contains a single integer ‘T’ representing the number of test cases. 

The first line of each test case will contain a single integer ‘N’ i.e., length of the pile and ‘K’ size of the window.

The next line of each test case contains 'N' numbers a1, a2, a3... aN denoting the initial height of each pile.
Output Format:
For each test case, output the minimum cost for each window.

Output for every test case will be printed in a separate line.
Note:
You don’t need to print anything; It has already been taken care of.
Constraints:
1 <= T <= 10
1 <= N <= 10000 
1 <= K <= N 
1 <= height[i] <= 10^5 

where 'T' is the number of test cases, 'N' is the number of piles, 'K' is the size of the window as discussed above and 'height[i]' represents the height of each pile.

Time limit: 1 sec
CodingNinjas
author
2y
Brute Force

Let's reduce our question to a fixed array instead of every subarray of size ‘K’ and try to find an answer specific to that array/list ‘height’, so we could do the same thing for each window, now, as mentioned in the hint, we need to calculate the sum of absolute difference of every element from its median, so after getting the new array, next step would be to calculate the cost of that window, so first we will sort the array and select the ‘K’/2 th element as we know the size of the new array will be ‘K’, now we could calculate the cost easily by iterating over the window.

 

Reference: proof for optimal cost to make all elements equal would be at its median value.

 

The steps are as follows:

 

  1. Declare a list/vector ‘ret’ in which we store our answer.
  2. Run a loop while ‘i’ = 0 to ‘N’ - ‘K’.
    • Let's calculate the median of the ‘K’ size subarray/sublist ‘temp’ and initialize it as ‘Median’. Note that there are various methods to calculate the median of the ‘temp’.
      • select the ‘N’/2 th element in the sorted ‘temp’, here ‘N’ denotes the size of the ‘temp’.
      • Use kth-order statistics to find the median in linear time.
    • For each element ‘X’ in the ‘temp’, we add abs(‘X’ - ‘Median’) to ‘Answer’, as we need this quantity of steps to make ‘X’ equal to ‘Median’, by incrementing or decrementing ‘X’ by 1.
    • Add this ‘Answer’ into ‘ret’.
  3. Finally, return 'ret'.

 

Space Complexity: O(n)Explanation:

O(N) where ‘N’ is the length of the array/list ‘pile’ .

 

As we are only traversing the array and storing only constant variables, also please note that we are ignoring the space complexity for sort functions we are using. As space complexity of sort depends on the method of the sort we are using. Hence, the overall space complexity is O(N).

Time Complexity: OtherExplanation:

O(K*log(K) * (‘N’ - ‘K’ + 1)). where ‘N’ is the length of the ‘pile’ and ‘K’ is the size of the window.

 

As we know there is a total ‘N’ - ‘K’ + 1 window in a total of size ‘K’ and as we are doing this for each window or subarray our overall time complexity will be O(‘K * log(K)’ * (‘N’ - ‘K’ + 1)). 


Python (3.5)
'''


Time Complexity : O(K * log(K) * (N - k +1))
Space Complexity : O(N)

where N is the number of pile and K is the size of the window.

'''

def getMin(heights, n, k):

#W Declaring list for storing cost for each window.
ret = []

for i in range(0, n - k + 1):

# Declaring window [ i , i + k ).
temp = heights[i : i + k]

# Sorting to get median easily, also nth_element in c++ stl could be used instead.
# Median = temp[k / 2]
temp.sort()

cost = 0
median = temp[k // 2]

# Calculating cost by adding all the cost to convert each element to median.
for x in temp:
cost += abs(x - median)

ret.append(cost)

return ret


C++ (g++ 5.4)
/*


Time Complexity : O(K * log(K) * (N - k +1))
Space Complexity : O(N)

where N is the number of pile and K is the size of the window.

*/

vector getMin(vector &heights, int n, int k)
{
auto &x = heights;

// Declaring list for storing cost for each window.
vector ret;

for (int i = 0; i + k <= n; i++)
{
// Declaring window [ i , i + k ].
vector temp(begin(x) + i, begin(x) + i + k);

// Sorting to get median easily, also nth_element in c++ stl could be used instead.
// Median = temp[k / 2]
sort(begin(temp), end(temp));

int cost = 0;
int median = temp[k / 2];

// Calculating cost by adding all the cost to convert each element to median.
for (int x : temp)
{
cost += abs(x - median);
}

ret.emplace_back(cost);
}

return ret;
}



Java (SE 1.8)
/*


Time Complexity : O((K*log(K)) * (N - K + 1))
Space Complexity : O(N)

where N is the number of pile and K is the size of the window.


*/

import java.util.ArrayList;
import java.util.Arrays;

public class Solution
{
public static ArrayList getMin(int heights[], int n, int k)
{
// Declaring list for storing cost for each window.
ArrayList ret = new ArrayList<>();

for (int i = 0; i + k <= n; i++)
{
// Declaring window [ i , i + k ].
int temp[] = new int[k];

for (int j = 0; j < k; j++)
{
temp[j] = heights[i + j];
}

// Sorting to get median easily, also nth_element in c++ stl could be used
Arrays.sort(temp);

int cost = 0;

// Calculating cost by adding all the cost to convert each element to median.
for (int j = 0; j < k; j++)
{
cost += Math.abs(temp[j] - temp[k / 2]);
}

ret.add(cost);
}

return ret;
}
}
CodingNinjas
author
2y
Fenwick Tree And Ordered Set

Now as we know that we have to convert each element in the window to the median of that window to get the optimal cost. A median of the window is equal to the element at th...read more

CodingNinjas
author
2y
Two Dynamic Heaps or Multisets

If you could notice what we did in Approach-2, all we need is the sum of half elements and the sum of the other half elements. Also, we need the median of this window, we...read more

Add answer anonymously...
Procol Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter