Saturday, May 3, 2008

Day 5 Solution

There is nothing special about this problem. No holistic views, no boundary conditions. You guys know "Sorting" right! This problem is to make you use it.

The Algorithm
1. Sort the array from 0 to n-1
2. Return the n-2th element

---

So you can do your regular sorting thing and get the result.

I would like to use this opportunity to introduce you to some more of STL.

Check the program



There is a legacy trick of finding the size of an array in that problem.
Noticed how we did -
sizeof(heights)/sizeof(int)

to get the number of elements in the array!

Then, while converting that array into a vector, we need to give the range of the array. By range I mean, a pointer (or an iterator) from the beginning of the array to the end of the array. Now 'heights' will give us the pointer to the beginning of the array and 'heights + n' to the end.

But will 'heights + n' always give us the pointer to the end of the array?
It will in our case, but it wont for other arrays of other types.
Can you tell why?

Day 5 - The second tallest student

Problem - You are given an integer array of heights of students in a class. Write a function that returns the height of the 2nd tallest child in the class.

Friday, May 2, 2008

Day 4 Solution

You can view the problem statement here.

Now you can imagine the gird to be a something like this


Point A could be your home and Point B your school/college.

So you would be thinking that (Ax - Bx) and (Ay - By) would give you your solution. But the solution could be negative as well. So you take the absolute value of (Ax - Bx) and (Ay - By) and add the two to get your answer.

Check the program.



























Now the catch is...
While writing/imagining the solution, did you imagine only the positive co-ordinate axis or all the 4 axes? As in, did you imagine only positive co-ordinates for X and Y or did you imagine the negative ones as well?



If you imagined the Negative Axes as well then congrats! You are someone who already looks at boundary conditions. And if you did not, then congrats! You can start looking at boundary conditions for every problem you solve from now on!

In our case, the solution works well no mater which quadrant we are in. But real life problems, I'm afraid, are not so forgiving.

So did you find this post insightful? Keep bringing on your comments. I am looking forward to some readers posting a snapshot of their solutions too!

Day 4 problem - Whats the distance

Here is todays problem.

You have a square grid extending infinitely in all directions. Your home is at point (hx,hy). You have to reach your college located at point (cx, cy). You can only travel parallel to the direction of the X or the Y axis and each step is 1 unit long. Write a program to find the number of steps between your home and your college.

Write it now. Test it. And come back later to check the solution.

Thursday, May 1, 2008

Solution to Day 3 problem.

View the problem statement here.

This problem is very simple, yet I have included it because I want the readers to start using some STL in their C++ programs.

What is STL?
It stands for Standard Template Library. This library has a lot of classes and functions that can replace a lot of data structures and algorithms that we use on a regular basis.

In order to solve our problem we can use the following algorithm
1. Set height[0] as RES
2. Loop through height, from begin to end
if current_element in height is < RES
set RES to current_element

3. Return RES


So, how do we use STL to do this?
We use STLs Algorithms.

--------------------------------------------------------
#include<algorithm>
#include<vector>

int minHeight(vector<int> height)
{
return *min_element(height.begin(),height.end()) ;
}
--------------------------------------------------------

OK OK, that seems to be too much too soon.
So lets break it down.

Q1. Whats that vector thingy? We were supposed to have an array as an input!
Ans. Vector is an STL class. Vectors are a replacement for Arrays. The <int> tells that its an array of int(s).

Q2. What is min_element?
Ans. min_element is a pre-defined* function in algorithm.h that returns a pointer to the minimum element in a specified range.

Q3. So height.begin(), height.end() are ranges right?
Ans. Exactly. height.begin() returns a pointer to the beginning of the array and height.end() returns a pointer to 1 past the end of the array. Between begin() and end() we have covered the whole array.

We will be talking a lot about using STL subsequently.
You can try the program out and let me know if there are any doubts.


* functions are declared not defined in header files. They are defined in the respective libraries.

Note: In reality, min_element() returns something called an iterator which is similar to a pointer and you don't have to bother much about it right now. STL is a very simple to use library with easy syntax, but the way it is taught in books is a bit daunting. So don't bother much about the syntax if you are reading it for the first time. Just see a few examples and learn from them.

Wednesday, April 30, 2008

Day 3 - Programming problem: Shortest height

Question: You are given an array height[] of positive integers containing the heights of the children in a class. Write a function that takes height[] as an input and gives the shortest height as the output.

For example -
Input - [23,29,20,22,23,22,19,25,21,26,23,24,18,30]
Output - 18

Request: Pls take the quiz the right side bar to give feedback on the easiness/difficulty level of the questions. Thanks

Tuesday, April 29, 2008

Solution to Problem 2

You can view the problem statement here.

Why did I ask this question now?
Because there are 3 good things in this problem :-
1. You need to understand the problem.
2. There is a lot you can do to optimize the solution
3. If you don't optimize the solution, you may end up screwing your reputation in your job interview.

Remember, anyone can code. But the way anyone will differentiate between you and an average coder is on the basis of

  • How well you handle the boundary conditions. (Does your code fail for any input)

  • How efficient your code is.

  • And how well can you optimize your code.



Many people coming to this blog are students who would be writing programs in their job interviews soon. I can tell from personal experience that the sexiest of companies only ask for programmers who code keeping the above points in their mind.

Ok now coming back to the problem.

We can check for primality by iterating from 2 to (n-1) and if it is divisible by any number in between, we can be sure that it is not a prime number.



However, there is a lot of unnecessary iteration over here.
You might be thinking that, since we are starting from 2, we can stop iterating when i reaches (n/2).



Well you are right. But the number of iterations can be optimized further.

Consider, a number 21. Lets list down its divisors
1 x 21 = 21
3 x 7 = 21
7 x 3 = 21
21 x 1 = 21
After removing the first and the last case. We are left with only 3 x 7 and 7 x 3. Notice the repetition. Once we have 3 we dont need to go till 7 do we?
Now you would argue that, our program will automatically come out of the loop at 3 so there is no question of reaching all the way till 7. Well you are right again. But the problem doesn't come when the input is composite (A number that is not prime). The problem comes when the number is prime. Take 23 for example.
Try dividing it with :-
2 - No
3 - No
4 - No
5 - No
.
.
.
11 - No
And then we come out of the loop.

But do we really need to go all the way till 11?
No we don't.
Applying some common sense, you can sense that after the square root of the number, the order of multiplication starts changing.
Let me illustrate that with an example.

Consider n = 24
2 x 12 = 24
3 x 8 = 24
4 x 6 = 24
6 x 4 = 24
8 x 3 = 24
12 x 2 = 24

The divisors start repeating after i becomes greater than 5. Its basically because, i becomes > 4.89 or Square Root(24). So we only need to iterate till the square root of a number.

Here is the code for the problem.



Now coming back to the 3 points that I had mentioned earlier on why this problem is good.
1. You need to understand the problem. Did you know that, prime numbers can't be negative? I didn't know it when I was asked to write this program the first time.
2. There is a lot you can do to optimize the solution You already have an idea of the optimization now.
3. If you don't optimize the solution, you may end up screwing your reputation in your job interview. If you apply for a job in a company like Google, Microsoft, Trilogy or an uber-cool startup. They are really gonna see how well you are able to optimize your solutions.

Can you find out a way of making the function return still faster for a random input?
Thats your assignment.

Thats all for the day.
Trust you found the post interesting.

Full_Metal