Solving Equal Stacks on Hackerrank in Swift
algorithm problems with Swift
Aug 8, 2017 · 3 min read
I am gearing up for the good ole iOS job hunt! In preparation, I’ve decided to tackle a variety of different algorithms on Hackerrank and explain my thought process of how I went about solving the problems.
Here’s the problem that deals with Stack:



Steps
- Reverse the cylinders order in the stacks.
- If they are not all the same height, then sort the stacks from lowest amount of cylinders to greatest amount of cylinders.
- Find the sum of the lowest number of cylinders stack and then continue to remove cylinders from the other stacks to equal the height of the lowest number of cylinders stack.
- If heights are not equal, pop a cylinder off the original lowest number of cylinders stack. Then need to repeat steps 3 through 5.
Explanation of Steps
- If you look at the diagram showing how the stacks look and the sample input, you’ll notice the cylinders in the opposite order. So in order to have it represent a stack, you’ll have to flip the order to get the height and pop cylinders properly.
- You want to start with the stack that has the lowest number of cylinders. The maximum height has to be one of the possible heights of the lowest number of cylinders stack.
- Once you have the height of the lowest number of cylinders stack, you want to see if the other stacks can equal that height. Continue popping cylinders until the stack is equal in height. If the stack height can’t be equal, have it be the first instance of its height being less.
- If the stacks are not the same height, then pop a cylinder off the original lowest number cylinder stack and start the process over from steps 3 through 5.
Model

I made a simple struct to represent my stack, mainly to be able to store the height while cylinders are being added and removed.
Helper Methods

Steps in Code

This is the solution I created to solve this particular problem. Here’s a link to the particular problem on Hackerrank. Would love to get feedback on my solution or other ways of tackling this problem! More to come.
