[Hackerrank] – Equal Stacks Solution

    by nikoo28

    Question: Given 3 arrays, where each element represent the height of a cylinder. Find the maximum possible height of equal stacks by removing one or more cylinders from the original stack.

    Example:

    Input:

    n1[] = {3, 2, 1, 1, 1}
    n2[] = {4, 3, 2}
    n3[] = {1, 1, 4, 1}

    Output: 5

    Problem Statement

    Let us try to simplify the problem statement first.

    The problem states that you are provided with 3 sets of arrays. Each element in the array represents the height of a cylinder. Now, all these cylinders are absolutely identical except their height. So as per the input test case, you have the cylinders like:

    sample input test case
    Fig: Sample input test case

    Now, these cylinders are to stacked on top of each other. Once they are stacked, they would start to look like:

    stacked cylinders
    Fig: Stacked cylinders

    The problem now says that you can remove one or more cylinders from one or more stacks. The end goal of removing cylinders is that you should have equals stacks, i.e. the three stacks should be of the same height. To find the solution we need to maximize this height and that should be the answer to this problem. In this test case, the answer would be 5 after we have removed the respective cylinders.

    equal stacks solution
    Fig: Equal stacks as the answer

    Brute Force Method:

    A brute force method wouldn’t actually help to solve this problem very much. But still it will help you to start thinking about the solution to the problem. What we can do is, we can try to remove the first cylinder from the first stack, and check if the heights of all the 3 stacks are now same. If yes, we have reached our answer.

    If not, try to remove a cylinder from the second stack and again verify. So the Brute Force algorithm would look like:

    1. Remove a cylinder from a stack.
    2. Check if the heights are equal.
    3. If yes, we have reached the solution.
    4. If not, choose a different stack and remove a cylinder.
    5. Once you have tried to remove 1 cylinder, follow steps 1-4 with 2 cylinders this time, and then with 3 and so on.

    You would realize that eventually you would reach the answer, but it wouldn’t be an efficient approach. That is because there are a lot of combinations possible and you possibly can’t iterate over all of them in a fast manner.

    Efficient Way

    Instead of trying to remove one cylinder at a time, and then finding the height of all the cylinders, we can take advantage of the Stack data structure. We can create 3 new stacks with the cumulative sums of the cylinder heights in each stack. This way the top element of each stack would tell you the current height of the stack.

    new stacks with cumulative sums
    Fig: Creating new stacks with cumulative sums

    Once, we have these stacks, you can now try to remove the top element from the highest stack. This seems intuitive too, because if you are trying to achieve equal stacks, you would want to reduce the height of the highest stack first.

    Now, you can go on removing the highest element from each of the 3 stacks until the top element of all the stacks is same. If the top element is same it would mean that the heights will also be same and hence equal.

    Code:

      public int equalStacks(int[] h1, int[] h2, int[] h3) {
    
        int maxHeight = 0;
    
        Stack<Integer> st1 = new Stack<>();
        Stack<Integer> st2 = new Stack<>();
        Stack<Integer> st3 = new Stack<>();
    
        fillStacks(st1, h1, st2, h2, st3, h3);
    
        // Run a loop until every stack has at-least 1 element
        while (!st1.isEmpty() && !st2.isEmpty() && !st3.isEmpty()) {
    
          int stack1Height = st1.peek();
          int stack2Height = st2.peek();
          int stack3Height = st3.peek();
    
          // If all stacks are of same height, just return the height
          if (stack1Height == stack2Height && stack2Height == stack3Height) {
            maxHeight = st1.peek();
            break;
          }
    
          // Else find the stack with maximum height and remove the block
          if (stack1Height >= stack2Height && stack1Height >= stack3Height) {
            st1.pop();
          } else if (stack2Height >= stack1Height && stack2Height >= stack3Height) {
            st2.pop();
          } else if (stack3Height >= stack1Height && stack3Height >= stack2Height) {
            st3.pop();
          }
        }
    
        return maxHeight;
      }
    
      private void fillStacks(Stack<Integer> st1, int[] h1, Stack<Integer> st2, int[] h2, Stack<Integer> st3, int[] h3) {
        int st1TotalHeight = 0, st2TotalHeight = 0, st3TotalHeight = 0;
    
        // pushing consolidated height into the stack instead of individual cylinder
        // height
        for (int i = h1.length - 1; i >= 0; i--) {
          st1TotalHeight += h1[i];
          st1.push(st1TotalHeight);
        }
        for (int i = h2.length - 1; i >= 0; i--) {
          st2TotalHeight += h2[i];
          st2.push(st2TotalHeight);
        }
        for (int i = h3.length - 1; i >= 0; i--) {
          st3TotalHeight += h3[i];
          st3.push(st3TotalHeight);
        }
      }
    Code language: Java (java)

    Time Complexity: O(n1 + n2 + n3)
    Space Complexity: O(n1 + n2 + n3) for the 3 new stacks that we create.

    You can find the code and test cases on Github.
    Problem statement on HackerRank.

    Video Explanation:

    YouTube player
    0 comments
    0 FacebookTwitterLinkedinWhatsappEmail
  • Arrays

    [Hackerrank] – Left Rotation Solution

    by nikoo28
    7 minutes read

    Question: You are given an array of integers. After a left rotation of k times, find the resultant array. Example 1:Input: arr [ ] = {1, 2, 3, 4, 5}, size = 5, k = 2Output: {3, 4, 5, 1, 2} Example 2:Input: arr [ ] = {4, 8, 15, 16, 23, 42}, size = 6, k = 12Output: {4, 8, 15, 16, 23, 42} Terminology: To understand rotation of an array, you can assume that the array is kind of on an infinite conveyor belt, that keeps on looping. …

    0 FacebookTwitterLinkedinWhatsappEmail
  • Theory

    Analysis of Algorithms

    by nikoo28
    3 minutes read

    There can be several aspects when you think about analysis of algorithms. You may be writing a large scale application where you have to decide between two choices. You may be trying to submit a solution to some online competition and you want a higher score, or probably you may just want to write fewer lines of code. Analysis during an Interview Let’s say you are appearing for an interview. The person who is interviewing you gives you a problem to solve. He or she is not just interested in …

    0 FacebookTwitterLinkedinWhatsappEmail
  • Theory

    What is the Big O notation? [Simplified]

    by nikoo28
    8 minutes read

    As soon as you hear the word ‘Big O’, does your mind go “Oh my god! Oh no! This again?” The next thing following it would be time complexity and what not. Suddenly, your brain starts getting this confusing signals and you lose track of what is happening. If you have felt this at some point of time while learning programming, then I want to tell you that you are not alone. In fact, you are proceeding in the right direction. But all these notations can start to get overwhelming …

    0 FacebookTwitterLinkedinWhatsappEmail
  • Theory

    Algorithmic Paradigms – Recursion

    by nikoo28
    5 minutes read

    The first thing that comes to our mind on hearing the word recursion is doing a thing over and over again. But how can you expect to achieve a solution to a problem by repeating the same thing over and over again. In this post we would be understanding exactly that. Algorithmic paradigms are a way to solve a problem, and recursion is one of them. Some of the other ways are: Brute Force Divide and Conquer Greedy Dynamic Programming So, what is Recursion? Sometimes a good image helps to …

    1 FacebookTwitterLinkedinWhatsappEmail
  • Theory

    What is the Time Complexity of an Algorithm?

    by nikoo28
    5 minutes read

    Time complexity is an important criteria when determining the quality of an algorithm. An algorithm is better if it produces the same result in a less time for the same input test cases. However, one must take care of the type of input data used. Some input data can give you false positives. Let us take an example to understand this better. You have an algorithm that is sorts a list of numbers. If the input data you provide to this algorithm is already sorted. Then this algorithm gives you …

    0 FacebookTwitterLinkedinWhatsappEmail
  • Theory

    Course on Algorithmic Paradigms

    by nikoo28
    3 minutes read

    Algorithmic Paradigms in short define how you can go about solving a problem. If you are starting to solve problems in computer science, this course is designed for you. However, this course is also recommended for you if you are revising all the basics and want a quick recap of some famous techniques. What are Algorithmic Paradigms? Whenever you try to build something, or develop something, an initial research and foundation is very essential. Think about it, a skyscraper will only be as stable as its base. In the world …

    0 FacebookTwitterLinkedinWhatsappEmail

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More