Best solutions for Microsoft interview tasks. Min Steps to Make Piles Equal Height.

Best solutions for Microsoft interview tasks. Min Steps to Make Piles Equal Height.

Description:

Alexa is given n piles of equal or unequal heights. In one step, Alexa can remove any number of boxes from the pile which has the maximum height and try to make it equal to the one which is just lower than the maximum height of the stack. Determine the minimum number of steps required to make all of the piles equal in height.

Example 1:

Input: piles = [5, 2, 1]
Output: 3
Explanation:
Step 1: reducing 5 -> 2 [2, 2, 1]
Step 2: reducing 2 -> 1 [2, 1, 1]
Step 3: reducing 2 -> 1 [1, 1, 1]
So final number of steps required is 3.


Solution:

Lets visualize the piles, lets use A instead of boxes

5: AAAAA

2: AA

1: A

On the first step we cut 5: AAAAA to 2: AA:

2: AA

2: AA

1: A

On the second step we cut first strings of 2: AA to 1: A

1: A

1: AA

1: A

On the third step we cut first strings of 2: AA to 1: A

1: A

1: A

1: A


If we will have two piles with the same length, for example:

5: AAAAA

5: AAAAA

1: A

On the first step we cut first 5: AAAAA to 1: A:

1: A

5: AAAAA

1: A

On the second step we cut second 5: AAAAA to 1: A:

1: A

1: A

1: A

In other words in order to determine the minimum number of steps required to make all of the piles equal in height we need to sort the array and count how many piles with different height exists and sum them up.

The C++ code:

int solution(vector<int> v) {
    int v_size = v.size();
    if(v_size < 2) { return 0; }
    std::sort(v.begin(), v.end());
    int sum = 0;
    for (int i = 1; i < v_size; ++i) {
        if (v[v_size - i - 1] != v[v_size - i]) {
            sum += i;
        }
    }
    return sum;
}

Complexity of this solution is O(N* Log(N)) where N is length of the string but I believe there is solution with linear complexity I just can't process well all corner cases.


Repository with the full project you can find here: https://github.com/jolly-fellow/microsoft/tree/master/min_steps_to_make_piles_equal_height

Return to the table of contents.

My doubt is that , In this example {5, 2, 1}why are we not reducing 5 to 1 directly, why are we first reducing 5-->2, then 2-->1, we could have done it in 2 steps only, as we know that the number 1 cant be increased, so all the number greater than 1 has to reduce to reach upto 1 .

回复

要查看或添加评论,请登录

Alexander Molchevskyi的更多文章

社区洞察

其他会员也浏览了