Here is a typical algorithmic problem I encounter when interviewed:

Write a program that receives a set of positive integers

(duplicates are possible) and decides if the set of integers can be divided into three subsets with the same sum of elements. For instance, {1,1,1} can be divided into three subsets with equal sum {1} {1} {1}, {3,2,5,4,1,3} can also be divided into three subsets with equal sum {1, 5}, {2, 4}, {3, 3}. {2,3,4,5} however canot be divided into three subsets with equal sum.

The problem can be easily solved using recursion but on an interview it is sometimes easier to come up with a non-recursive solution.

a)

If

total sum of elements is not divisible by 3 without reminder, the subsets do not exist.

total sum of elements is not divisible by 3 without reminder, the subsets do not exist.

b)

Count in base-3 from 0 to 3^N

c)

For each number sum all digits for each of the three subsets. if all three equal we return

true, otherwise continue to the next number.

true, otherwise continue to the next number.

theory:

For a

group of objects (positive numbers in our case) we want to find all the

possible ways to divide the objects between 3 different buckets. Lets number

the buckets 0, 1, and 2, and lets assume for now that buckets are allowed to be

empty but each object must be in one of the buckets.

group of objects (positive numbers in our case) we want to find all the

possible ways to divide the objects between 3 different buckets. Lets number

the buckets 0, 1, and 2, and lets assume for now that buckets are allowed to be

empty but each object must be in one of the buckets.

How

many ways are there to arrange 1 object into 3 buckets? The answer is 3 because

the object can be placed in either one of the buckets. And using our notation:

0 – object is in the first bucket, 1 – object is in the second bucket, 2 –

object is in the third bucket.

many ways are there to arrange 1 object into 3 buckets? The answer is 3 because

the object can be placed in either one of the buckets. And using our notation:

0 – object is in the first bucket, 1 – object is in the second bucket, 2 –

object is in the third bucket.

For 2

objects we have 9 arrangements:

objects we have 9 arrangements:

00 –

both objects are in the first bucket

both objects are in the first bucket

01 –

the first object is in the first bucket and the second object is in the second

bucket

the first object is in the first bucket and the second object is in the second

bucket

02 –

the first object is in the first bucket and the second object is in the third

bucket

the first object is in the first bucket and the second object is in the third

bucket

10 –

the first object is in the second bucket and the second object is in the first

bucket

the first object is in the second bucket and the second object is in the first

bucket

11 –

both objects are in the second bucket

both objects are in the second bucket

12 –

the first object is in the second bucket and the second object is in the third

bucket

the first object is in the second bucket and the second object is in the third

bucket

20 –

the first object is in the third bucket and the second object is in the first

bucket

the first object is in the third bucket and the second object is in the first

bucket

21 –

the first object is in the third bucket and the second object is in the second

bucket

the first object is in the third bucket and the second object is in the second

bucket

22 –

both objects are in the third bucket

both objects are in the third bucket

Using

the similar logic for 3 objects we would have 27 arrangements:

the similar logic for 3 objects we would have 27 arrangements:

000

001

002

010

011

012

020

021

022

100

…

221

222

And for

n objects we would have 3^n arrangements. If we look at our example with 3

objects we might notice that we start counting from 0, and go up all the way to

2 and then suddenly go to 10 instead of 3. It actually looks like all the

digits above 2 are missing. And there is a good reason why they are missing. We

count in ternary numeral system or simply base 3.

n objects we would have 3^n arrangements. If we look at our example with 3

objects we might notice that we start counting from 0, and go up all the way to

2 and then suddenly go to 10 instead of 3. It actually looks like all the

digits above 2 are missing. And there is a good reason why they are missing. We

count in ternary numeral system or simply base 3.

So to

find all the possible ways to divide a set of objects between 3 different buckets

we just have to count in base 3. And to while we count we can calculate the

total sum of all numbers in each bucket. For example for base 3 number

010011202 and a set of positive numbers 2,4,3,7,8,2,7,2,7 we would calculate

the sum for the first bucket 2+3+7+2, second bucket 4+8+2, and third bucket 7+7

and see that all sums are equal to 14.

find all the possible ways to divide a set of objects between 3 different buckets

we just have to count in base 3. And to while we count we can calculate the

total sum of all numbers in each bucket. For example for base 3 number

010011202 and a set of positive numbers 2,4,3,7,8,2,7,2,7 we would calculate

the sum for the first bucket 2+3+7+2, second bucket 4+8+2, and third bucket 7+7

and see that all sums are equal to 14.

Of

course our solution is suboptimal because we only care about the sum of each

group and do care about the bucket order. 010011202 and 101100212 is the same

number for our purposes because nothing changes if we switch the buckets.

course our solution is suboptimal because we only care about the sum of each

group and do care about the bucket order. 010011202 and 101100212 is the same

number for our purposes because nothing changes if we switch the buckets.

In

fact, to calculate what the number of unique combinations is equal to we would have to learn Polya’s Counting Theory…

fact, to calculate what the number of unique combinations is equal to we would have to learn

**Java implementation:**

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

public class Main {

/**

* @param args

*/

public static void main(String[] args) {

// List Example implement with ArrayList

List<Integer> numbers = new ArrayList<Integer>();

numbers.add(3);

numbers.add(4);

numbers.add(3);

numbers.add(10);

numbers.add(1);

numbers.add(2);

numbers.add(3);

numbers.add(4);

numbers.add(7);

numbers.add(7);

numbers.add(7);

int n = numbers.size();

int count = (int) Math.pow(3, n);

for (int i = 0; i < count; ++i)

{

String base3 = Integer.toString(i,3);

base3 = padLeft(base3, n);

//System.out.println(“base3:” + base3);

int [] group = {0, 0, 0};

int k = 0;

Iterator<Integer> it=numbers.iterator();

while(it.hasNext())

{

int groupId = Integer.parseInt(base3.substring(k,k+1));

Integer value=(Integer)it.next();

group[groupId] += value;

++k;

}

if (group[0] > 0 && group[0] == group[1] && group[0] == group[2])

{

System.out.println(“base3:” + base3);

}

}

}

public static String padLeft(String s, int n) {

return String.format(“%” + n + “s”, s).replace(‘ ‘, ’0′);

}

}

http://www.quixey.com

Quixey is a start-up that tries to optimize application search.

A twenty something year old kid introduced himself as Quixey’s CTO.

The CTO was a typical smart senior-year college kid who had a good idea and received a huge investment to implement it.

There is no doubt the CTO is a smart guy but there is also little doubt that his way of thinking is extremely inflexible and that he thinks that he is the smartest person on the planet Earth.

Nevertheless, Quixey has a hard problem to solve and it looks like they are doing a good job.

And here in the valley, you either have your own company or you sell your skills to freaks.

Here are the questions:

1) Calculate the sum: 1 + 2 + 4 + 8 + 16 + … + 1024

Unless you are lucky, and remember the formula for the series from the high-school, you have to find a quick way to calculate the sum.

1,2,4,8 .. How do they look in binary?

00000000001

00000000010

00000000100

00000001000

And if add them all up, we get eleven ones:

11111111111

And 11111111111 = 100000000000 -1

And 100000000000 = 2048

So the answer is 2047.

And the closed formula is: 2^(n+1) – 1

2) You are given a list that contains another list, an array of strings, or a string as its values. Write a function to print out all the strings in the list.

That is a fairly simple question; just do not try to do it in C++ (like I did).

The trick here is that we have to use recursion for if one of the values is a list.

i.e. sum += func(list);

3) Write a JavaScript function countTo(n) that counts from 1 to n and call console.log for each number. Your function has to cleverly work around this ridiculous constraint: You’re not allowed to use JavaScript’s iterative control structures, for and while. (And you’re not allowed to make the interpreter execute those control structures using tricks like eval, or dynamically generated elements appended to the DOM tree.)

function countTo(n) {

if (n > 0) {

countTo(n-1);

console.log(n);

}

}

There is also a much trickier way to achieve that; for instance, using function pointer or template specialization in C++.

4) A client connects to a server which will stream it N 32-bit integers and then disconnect, where N is a-priori unknown to the client. Describe an O(log N)-space algorithm you could run on the client that would return any of the N integers with probability 1/N. (The algorithm only gets run once.)

#include <iostream>

#include <ctime>

using namespace std;

//

// Generate a random integer [1,...,n] with probability 1/n

int urand(int n)

{

if (n > 0)

{

int rnd = (int) ((rand() / double(RAND_MAX)) * n) +1;

return (rnd > n) ? n : rnd;

}

return 0;

}

//

// Reset the random number generator with the system clock.

void seed()

{

srand((unsigned int) time(NULL));

Not-so-easy C++ interview.

]]>1) Can a class with a private destructor be instantiated?

That is a tricky question because the answer is both yes and no.

Yes, it can be instantiated on a heap.

No, it cannot be instantiated on a stack.

A class with a private destructor cannot be instantiated on a stack (Object obj) because the compiler cannot call a destructor.

It is okay to instantiate it on a heap because we control when the destructor is called.

A class with a private destructor can destroy itself (delete this).

So when do we need a class that has no accessible destructor?

A class that counts references should not be deleted by a user because the user does not know if all references have been released.

2) What is a function object (FUNCTOR)?

An object that overloads the function call operator ()

class compare

{

public:

bool operator()(int A, int B) const

{

return A < B;

}

};

And here is a usage pattern:

template <class Functor>

void sorta(int* items, int count, Functor pred);

3) Find n-th, from the tail, object in a linked list.

The question can be easily solved in O(n) time with two pointers.

Start the second pointer n iterations after the first pointer.

Once the first pointer has reached the end of the linked list, the first pointer is at n-th element from the end.

4) Implement a URL caching mechanism

Cache speeds up fetch requests by storing results in fast memory.

All practical cache algorithms, sooner or later, must expel items from cache.

Least recently used (LRU) algorithm simply evicts items that are least used. LRU is frequently implemented using a priority queue.

CLOCK algorithm is implemented using an array and it evicts the first unused item that it finds.

5) How do virtual functions work?

A v-table is constructed for each class that has virtual members.

V-table contains addresses of all virtual functions, and is created when a class is instantiated.

6) Is it possible to have a virtual constructor?

No, because the v-table is not yet available when the constructor is executed.

7) What data structures would you use to store a dictionary of names?

8) What is template metaprogramming?

Metaprogramming is the ability of a program to manipulate other programs as data.

Metaprogramming is frequently achieved via reflection or templates.

Here is an example of metaprogramming in C++:

template <int N>

struct Factorial

{

enum { value = N * Factorial<N - 1>::value };

};

```
```template <>

struct Factorial<0>

{

enum { value = 1 };

};

`void fact()`

{

int x = Factorial<4>::value; // == 24

int y = Factorial<0>::value; // == 1

}

9) Is there a performance difference between a) and b) loops?

a. for (unsigned int i=0; i<10; i++)

b. for (unsigned int i=0; i<10; ++i)

10) Define a Singleton

class Singleton

{

public:

static Singleton *instance (void)

{

if (instance_ == 0)

// Critical section.

instance_ = new Singleton;

return instance_;

}

private:

static Singleton *instance_;

};

http://www.auditude.com/

Auditude is an online video advertising technology and monetization partner for premium content owners and distributors.

A recruiter contacted me and scheduled a phone interview with one of the managers. The interview was not technical and consisted of typical HR questions. Why are you looking for a new position? What are you doing at your current position? At the end of the interview an on-site interview was scheduled.

The office was a typical open-space dot com office – nothing fancy.

Three engineers interviewed me and asked the following questions:

Three engineers interviewed me and asked the following questions:

1) Given the following table:

user_id | lab_id |

1 | 1 |

2 | 2 |

3 | 3 |

4 | 3 |

5 | 3 |

6 | 2 |

1 | 1 |

1 | 2 |

2 | 3 |

2 | 3 |

5 | 3 |

6 | 2 |

6 | 1 |

6 | 4 |

3 | 2 |

1 | 1 |

1 | 1 |

3 | 2 |

`SELECT`

` user_id,`

` count(distinct lab_id) number_of_unique_visits`

`FROM tst`

`GROUP BY user_id;`

`SELECT`

` user_id,`

` lab_id,`

` count(*) AS number_of_visits`

`FROM tst`

`GROUP BY user_id, lab_id;`

SELECT

` t1.user_id,`

` (SELECT t2.lab_id FROM tst t2 WHERE t2.user_id = t1.user_id GROUP BY t2.user_id, t2.lab_id ORDER BY count(*) DESC LIMIT 1) most_visited_lab`

`FROM tst t1`

`GROUP BY t1.user_id;`

2) In PHP, what is the difference between $objt and $$ objt?

3) Design a simple database for an online store.

4) Based on the database design, write a statement to select all orders that contain at least 5 products (i.e. the total quantity of items ordered is greater or equal to five).

5) Based on the database design, write a statement to select all orders that contain at least 5 different products (i.e. the quantity of each item ordered is not important).

6) Difference between UNION and UNION ALL in MySQL

7) You are given a sorted array with shifted elements. Elements can be shifted to the left or right by some number of places. Write code to find if a given number N is present in this array. http://crackinterview.wordpress.com/2010/08/20/find-an-item-in-a-sorted-array-with-shifted-elements/

I usually try not to be judgmental because I only get interviewed to write this blog, but the unfortunate truth is that there are so many jerks in dot-com companies that there are times that it is just impossible to stay imperturbable.

The first interviewer was a typical PHP developer who had no idea about MySQL internals but thought he ruled the world, and could easily optimize any SQL query.

The third interviewer who introduced herself as a chief scientist that does not bother to write any code (yes, she emphasized that) spoke English so badly that it took me 30 minutes to understand her question.

And in the middle of me trying to understand what she was actually trying to say, she simply walked out of the room because she had an urgent call – well, she is the chief genius there.

Never tell a recruiter (or your potential employer) your current salary or salary requirements. Recruiters will pressure you into revealing your current salary because it saves them money but do not give up and if they persist tell them that even your wife does not know the number. If the recruiter is not in a joking mood you can always claim that your salary requirements are flexible.

Here is why you should never talk about money before you get an offer!

Imagine, you go through all the technical interviews and the company decides that they want to hire you, and they know that your current salary is 60K. So even if the budget for this position was 90K, guess, how much will they offer you? That is right, 5 to 20 percent increase to your current salary is all you can hope for. Furthermore, smart recruiters, if they see you like the job, will, at least initially, offer you less than what you earn now citing hard-times and large unemployment numbers.

On the other hand if you told them that your salary was 120K they might not even have invited you for the interviews on the first place. So you lost a pleasure (experience) of being interviewed and any chance of being hired.

Of course, they might not like you being stubborn and proceed with more agreeable candidates but seriously do you want to work for such a company? In fact, if you do not give up and do not reveal your salary they will probably appreciate your persistence and will respect you.

So NEVER tell you salary to ANYONE, not even your girlfriend! ))

]]>For some reason, majority of C# .Net phone screenings ask, over and over again, the same meaningless questions. In my opinion, no self-respecting company, should make any decision based on these questions. Anyway, the reality is that you either hire or get hired. So I created a list of questions that helps me to ace phone screenings:

]]>The only difference between executable and library assembly is that library assembly does not contain main entry point.

All assemblies contain metadata that describes its types and methods.

Assemblies also contain manifest (assembly metadata) that describes assembly itself (version and so on).

All private assemblies are located in the same folder (or its subfolders) as the main executable assembly. Shared assemblies are located in the GAC folder.

Anonymous type is a nameless class that inherits from object.

For instance: var person = new {firstName = “Me”, lastName = “You”};

Structs unlike Classes are value type (not reference type and are being stored in the stack and not on the heap) and do not support inheritance.

Extension methods are a simple way to extend classes that do not have source code available. All you have to do is to create a new class that contains a function that has the class you want to extend as a first parameter, preceded by this keyword.

Sealed classes cannot be inherited from.

Virtual methods can be overridden by derived classes(derived classes use override keyword for safety reasons – in case you did not notice that the method does not have exactly the same signature as the virtual method you will get an error).

Internal visibility modifier makes the class visible only to containing assembly.

Interfaces contain only public methods – no protected, private, or even abstract or static. Interfaces can inherit from each other though.

foreach loop can only be used with classes that either implement IEnumerable interface or implement GetEnumerator, MoveNext, (Reset), and Current members.

Use checked block to enable overflow cheking.

Boxing converts value types to reference types.

http://www.insidetrack.com/

A recruiter from the company contacted me and asked the following questions:

]]>A recruiter from the company contacted me and asked the following questions:

- What is a standard Microsoft technology stack for a database driven web application with reporting?
- What are C# generics and why they are useful?
- What are Lambda expressions and what have they replaced?
- What is LINQ used for and how does this benefit the programmer?
- What are CURSOR in T-SQL and how can they be helpful?

- ADO and also Microsoft Reporting Services are used for DB driven web applications with reporting.
- Generics are similar to templates in C++. Generics allow to defer specifications of types until class/method is declared/instantiated.
- Lambda expressions replaced anonymous methods syntax that allow to declare code inline
- LINQ is Language Integrated Query – it transforms database development model into an object oriented one so the developer who know OOP does not have to go deep into SQL.
- CURSOR allows to loop through data – row by row.

An on-site interview was scheduled:

1) You have 2 tables: Student and StudentTmp

a. StudentTmp contains exactly the same fields (StudentID, Name, DateCreated, DateUpdated) as Student

b. Write a stored procedure (SQL) that copies data from StudentTmp to Student, if the data is not already there (i.e. StudentID does not exist) and updates it otherwise

2) You have Coaches that coach Students that attend a School and Managers that manage coaches.

a. Each manager can manage many coaches

b. Each Student attends exactly one schools

c. Each coach can coach many students

d. Each student can be only coached by exactly one coach each semester.

Create a DB schema that implements it.

3) Design classes to for a chess game

4) Design a database schema for a basketball game

5) All the language crap (i.e. virtual, const, public, inheritance, OOP, sort, data structures)

Inside

http://www.sportvision.com/

1) You have a nxn matrix that contains integers only.

a. The numbers always increase to the right and to the bottom

b. What is the fastest way to find a number x (you know it is in the matrix)

]]>1) You have a nxn matrix that contains integers only.

a. The numbers always increase to the right and to the bottom

b. What is the fastest way to find a number x (you know it is in the matrix)

2) 4 people must cross a bridge.

a. Only 2 people can walk a bridge at the same time because it is dark and they have to carry a flashlight with them.

b. Once 2 people cross the bridge one of them must return the flashlight so that the rest can cross it

i. First person can cross the bridge in 10 minutes

ii. Second in 5 minutes

iii. Third in 2 minutes

iv. Fourth in 1 minutes

How long will it take them all to cross the bridge?

They are in hurry and must do it as fast as possible

3) Write an algorithm to convert integers to words.

a. i.e. 1234 must be spelled as one thousand thirty four

4) Write an algorithm to reverse a single-linked list

5) Write an algorithm to draw a star with n corners

a. You have 2 functions to use: moveto(x,y) lineto(x,y)

6) Write an algorithm to add a node to a singly-linked list

7) You have a table A that contains managers with their ManagerID and Name and table B that contains employees with their EmployeeID, Name, and reference to their manager (ManagerID).

a. Write a SQL statement to display all Employee names with their manager names.

b. Modify the statement to display employees that do not have a matching manager

8) You have a b-tree How would you store it in a relational database? (Design the schema)

http://www.google.com/

I was interviewed for a Software Reliability Engineer position.

]]>I was interviewed for a Software Reliability Engineer position.

A recruiter from Google contacted and asked if I want to have an interview with a Google engineer,

It is hard to say no to Google; after all, in terms of benefits, working for Google is the second best thing after having your own business.

Two weeks have passed and no word from Goggle.

Well, I thought, they have so many candidates that have probably forgotten about me.

But in another week, I received an e-mail from the same recruiter asking to select your top three areas of my developmental expertise.

1) Web applications and multi-tiered systems

2) Database internals

3) Windows development

And she also asked me if I know someone who already works for Google. I found two references (in retrospective should have said no).

In a week another recruiter contacted me and asked to rate myself:

0 – Indicates you have NO EXPERIENCE – that is fine but please indicate

1-3 – Indicates you can read / understand the subject area, but would not be comfortable implementing anything in it.

4-6 – Indicates you are comfortable with the subject area and all normal / routine work in it.

7 – Indicates that you are extremely proficient and have deep technical expertise in the subject. You would be comfortable with personally designing and implementing any project in that area.

8 – Indicates that you are almost an expert from fundamentals to advanced concepts.

9 – Indicates you are an expert and could have written a book on the subject, but didn’t.

10 – Reserved for those who are recognized industry experts in a field (i.e. wrote a book on the subject).

3 TCP/IP Networking (OSI stack, DNS etc)

3 Unix/Linux internals

6 Unix/Linux Systems administration

6 Algorithms & Data Structures

5 C

8 C++

0 Python

4 Java

4 Perl

6 Shell Scripting (sh, Bash, ksh, csh)

8 SQL and/or Database Admin

4 Management

In a couple of days the second recruiter scheduled a phone interview with him for the following week.

Five minutes before the scheduled interview I received and e-mail from the recruiter saying that he has an emergency meeting and would like to reschedule the interview for the next week.

Next week he called and asked some questions:

- Convert a number from decimal to binary.
- Describe some basic data structures.
- Describe some basic search algorithms.

And then he continued talking on the importance of Software Reliability Engineers.

In two weeks he scheduled a phone interview for me with a Google engineer.

The interview was conducted using Google online documents so that the interviewer could see me type the code.

She asked just one question:

In two weeks he scheduled a phone interview for me with a Google engineer.

The interview was conducted using Google online documents so that the interviewer could see me type the code.

She asked just one question:

1) We have two bishops on a chess board. The board has 64 squares and each square is numbered 1 through 64.The bishop has no restrictions in distance for each move, but is limited to diagonal movement.

a. Write a function that given position of the two bishops (a number between 1 and 64) returns minimum number of turns required for the bishops to meet. Return -1 if no solution found. For example, for bishops located at postions 10 and 26 the function should return 2.

The problem is really hard to solve if we stick with 1 through 64 numbering but ones we switch to x and y coordinates the solution is trivial.

The interviewer was very nice and helpful.

Next day I received an e-mail for the recruiter saying that they were “impressed with my problem solving skills” and would like to schedule a second phone interview.

This time the subject would be Linux. The interview was scheduled for the next week.

My Linux skills are a little bit rusty so the next weekend I ended up reading Linux books,

The second engineer who called me was not as nice as the first, and just by talking to him for the first two minutes put me in a panic mode.

He asked me two questions and none of them was related to Linux:

1) Explain Insertion, Heap, and Quick sort.

2) Given two words that contain the same number of characters find the fastest way to transform word one into word two by changing one letter a time. All the transitional words must be valid words from a dictionary.

a. For instance transform cat to bet: cat-bat-bet

With some help for the interviewer I figured out that a graph that connects each word to all the words from the dictionary that differ by one letter must be built, and then Dijkstra can be run on it to determine the shortest path.

And then he asked me, what is the complexity of Dijkstra algorithm? To my surprise I completely forgot its complexity, after all the last time I used it was ten years ago.

The next thirty minutes I was deducing the complexity of Dijkstra algorithm and with some help from the guy I solved the problem O(EN).

I could have easily checked the complexity online but I was curious to solve it by myself, and I also wanted to be fair.

The guy thanked me and in three weeks I received a rejection letter from Google.

http://www.tagged.com/

I was interviewed by a recruiter from the company:

]]>I was interviewed by a recruiter from the company:

- How many bits needed to represent 1000000?
- What is the complexity of searching in a balanced binary search tree?
- What is the complexity of insertion in a hash table?
- Find two numbers in an array whose sum = X.

I must admit I was not that excited about what the company does so I was lazy answering some questions.

For instance, for question 1 I explained that we should find solution to 2 to the power of n = 1000000 but did not bother calculating the n.

Also for question 4 I gave the recruiter a better solution than the standard one (two pointers, start and end) but he did not understand it.

I have never heard from them again.

For instance, for question 1 I explained that we should find solution to 2 to the power of n = 1000000 but did not bother calculating the n.

Also for question 4 I gave the recruiter a better solution than the standard one (two pointers, start and end) but he did not understand it.

I have never heard from them again.