Monday, 13 July 2015

Stacks and Queue questions

https://github.com/prasanthlouis/C-equivalent-to-Cracking-the-Coding-Interview

Question 1: Implement 3 stacks using a single array. I was actually looking for a flexible way to do this. But when the author stated that it's beyond the scope, I was kinda disappointed.

The conventional way to do it is to allocate a fixed size to each stack. Boring.

Question 2: Find the min element with low complexity. I liked the algorithm they presented. Made me use a class as well. I haven't gone deep into class, but I've implemented the solution with it.

Moral: I liked using class when a real world object has several properties.

Eg. A toy duck has properties of color,size,price, etc. So to implement this, use a class.

Here our values in the stack have 2 properties, their original values as well as minimum value.

Question 3: Multiple stack overflow structure. Nothing difficult here. I used the provided stack structure in C++, made things a whole lot easier. Made an array containing stack structures.

Question 4: Towers of Hanoi. I loved this question. As a CSE student, we were taught about Hanois towers, but were never actually given an algorithm to solve it. It was more of a puzzle the teachers gave us to do, and we'd solve it manually as fast as possible. So I was interested on how to develop an algorithm

There are 3 steps:

1) Move n-1 disks to the buffer
2) Move the nth disk to the destination
3) Move n-1 disks from buffer to destination, using the source as a buffer.

Once you got down these 3 steps, you can implement it yourself. I used recursion.

Question 5: Implement a queue using 2 stacks. At first I thought of copying data from one stack to another to implement push() and pop(). But as we know, copying data is a big NO!. So use one stack for newer elements, and another one for older elements.

Question 6: Sort a stack. When they said "don't use any other storage other than another stack", it was pretty misleading. Looking at the solution, I saw that they used another variable to store an element at a time. Meh. Nothing too fancy here.

Question 7: Cats and Dogs. Nothing hard here. I used a class to maintain OOD. Nothing else worth mentioning.




No comments:

Post a Comment