Technical Hard Interview Questions

Implement a fancier version of attr_accessor that includes validation. Complete the attr_validated code below so that the unit tests pass.

require 'test/unit'

class Dog

    def self.attr_validated(method_name, &validation)
        # Complete this method so that the unit tests pass
    end

    attr_validated :num_legs do |v|
        v <= 4
    end


end

class TestDog < Test::Unit::TestCase

    def test_good_value
        dog = Dog.new
        dog.num_legs = 3

        assert_equal 3, dog.num_legs
    end

    def test_nil_value
        dog = Dog.new
        assert_raises ArgumentError do
            dog.num_legs = nil
        end
    end

    def test_illegal_value
        dog = Dog.new
        assert_raises ArgumentError do
            dog.num_legs = 5
        end
    end

end

Suppose you have a class that performs several expensive calculations. However, during the lifetime of an object, the result of the expensive calculation won't change. Therefore, you wish to ensure that each calculation is performed only once, and that result is cached. A simple technique for this would be as follows:

class Calculator
    def expensive_calc_one
        return @result1 unless @result1.nil?
       @result1 = # Do very expensive calculation.
    end

   def expensive_calc_two
        return @result2 unless @result2.nil?
       @result2 = # Do very expensive calculation.
    end
end

If this class contained many such expensive calculations, this memoization technique would become repetitive. Can you come up with a framework that reduces this repetition by allowing one to simply mark a method as memoized and no longer have to worry about manually handling the caching?

Bonus points: There is a flaw in the simple technique. Under one set of circumstances the caching will fail and repeated calls to expensive_calc_one will result in the expensive calculation being executed again and gain. When would this occur?

You have a class Parent with a virtual method a and a class Child that implements a. You also have a several functions:

void f1(Parent p) { p.a(); }
void f2(Parent* p) { p->a(); }
void f3(Parent& p) { p.a(); }

When called with a Child instance, which method will be invoked for f1, f2 and f3?

Explain in detail what the following C++ code does:

#include <iostream>
using namespace std;

template <class T>
T GetMax (T a, T b) {
  T result;
  result = (a>b)? a : b;
  return (result);
}

int main () {
  int i=5, j=6, k;
  long l=10, m=5, n;
  k=GetMax<int>(i,j);
  n=GetMax<long>(l,m);
  cout << k << endl;
  cout << n << endl;
  return 0;
}

Describe a schema (or classes) to power an online restaurant reservation system. Describe the tables and the relationships beween the tables.

This system should allow a user to reserve a table at a restaurant for a certain time period and a certain party size.

It should allow the restauranteur to configure the system to describe their restaurant and manage reservations.

Think http://opentable.com

Suppose you have a class Dog with two methods GetHasSpots and say_Woof. The method names do not follow your new naming conventions and you wish to rename them to has_spots? and say_woof. However, finding and correcting all references to these methods in one coding session is impractical due to a very large code base.

Thus, for some interim period of time you wish to allow both the old method names and the new methods names to work. Of course, you want to do this in the most DRY way possible, while also clearly marking the old methods as deprecated. The shell of a solution is shown below. Fill in the details of the deprecate method to make the unit tests pass.

require 'test/unit'

class Dog

    def has_spots?
        true
    end

    def woof
        "woof"
    end

    def self.deprecate(old_method, new_method)
       # Add code here that will make the unit test pass
    end

    deprecate :say_Woof, :woof
    deprecate :GetHasSpots, :has_spots?
end

class TestDog < Test::Unit::TestCase

    def test_deprecation
        dog = Dog.new
        assert_equal true, dog.GetHasSpots
        assert_equal "woof", dog.say_Woof
    end

end

Modify the + operator in Ruby so that it always adds an extra (i.e1+1=3`). When you are done the unit test below should pass.

Hint: remember that the + operator is really a method with signature def +(value) on the Fixnum class.

require 'test/unit/'

class BackToKindergartenTest < Test::Unit::TestCase
    def test_plus_one
        assert_equal 3, 1 + 1
        assert_equal 5, 2 + 2
        assert_equal 1, -1 + 1
    end
end

Complete the following Django model to illustrate how a manufacturer can make many different types of cars.

Give manufacturer a name, founding date and a country.

Give car a name, cost, engine capacity and color. Assume that the manufacturer makes cars in only {red, green, blue and pink}.

class Manufacturer(models.Model):
    # A car manufacturer

class Car(models.Model):
    # A type of car

Suppose you have a web form that allows users to upload JPG, GIF or PNG images. Before you store the images in your system, you want to convert them all to the JPG format. Design an image converter API. Sketch out all classes and interfaces that are involved.

Note: the actual code necessary to convert a JPG image to a GIF image is not the point. Just place a comment at the appropriate location where the actual conversion should occur.

Define the following object oriented concepts:

  • Class, object (and the difference between the two)
  • Instantiation
  • Method (as opposed to, say, a C function)
  • Static methods and classes
  • Destructor/finalizer
  • Inheritance
  • Encapsulation
  • Multiple inheritance (and give an example)
  • Abstract class
  • Interface/protocol (and different from abstract class)
  • Method overriding
  • Method overloading (and difference from overriding)
  • Polymorphism (without resorting to examples)
  • Method visibility (e.g. public/private/other)

Explain big o notation and how it is useful in computer science to classify algorithms.

  • What order is a hash table lookup?
  • What order is determining if a number is even or odd?
  • What order is finding an item in an unsorted list?
  • What order is a binary search?

How does caching work in Drupal? Dicuss the page cache, block cache and CSS/JavaScript optimizations.

What modules add caching to help Drupal scale?

Explain the Drupal architecture and specifically how the following components interact:

  1. Templates
  2. Blocks and Menus
  3. Modules
  4. Hooks
  5. Database: Caching, schema and the abstraction layer

What are hooks in Drupal? How are they used? Explain the function of the following hooks:

  1. hook_delete
  2. hook_form
  3. hook_insert
  4. hook_validate
  5. hook_user_delete
  6. hook_form_alter

Explain in detail, what's going on in the three paths through this Django form view processing code.

def contact(request):
    if request.method == 'POST': 
        form = ContactForm(request.POST) 
        if form.is_valid(): 
            # ...
            return HttpResponseRedirect('/thanks/')
    else:
        form = ContactForm()

    return render_to_response('contact.html', {
        'form': form,
    })

Complete the following Django form to include:

  • A subject with a maximum length of 100 characters
  • An optional, boolean, cc_myself field
  • A sender field that will be validated as a correctly formatted email address
from django import forms

class ContactForm(forms.Form):
    message = forms.CharField()

You have to debug a crashing application. You are given the source. When you run it repeatedly in a debugger you observe that it never crashes in the same place twice. It uses only the C standard library and is single threaded.

What coding errors could cause the crashes? How would you find them?

Design a system to efficiently calculate the top 1MM Google search queries and create a report of these. Additionally:

  • You are given twelve servers
  • Each has two processors, 4GB of ram and four 400GB hard drives.
  • The machines are networked
  • The log data as roughly 100 Billion log lines in it.
  • The log data comes in twelve, 320 Gb files.
  • Each line of the files has roughly 40 search queries
  • You can only use open source software or software that you write.

Given an array A[N] containing N numbers. Crate an array Output[N] where Output[i] is equal to the product of all the elements of A[N] except A[i].

For example Output[0] is the product of A[1] to A[N-1] and Output[1] is the product of A[0] and from A[2] to A[N-1].

Do this without using the division operator. Do it in O(n).

You want to check that your friend, Bill, has your accurate phone number, but you can't ask him directly. You have to write a question on a card which and give it to Ava. She will take the card to Bill and then return the answer to you.

What should you write on the card to ensure Bill can encode the message so that Ava cannot read your phone number?

Imagine you have eight balls, each of the same size.

One of the balls weights slightly more than the other seven.

Using a balance, find the heavier ball using only two weighings.

Express the following table as a static structure, and write a function, find_routes(source, destination) that efficiently outputs all possible routes.

Source  | Dest
~~~~~~    ~~~~
Seattle | LA
LA      | Florida
LA      | Maine
Florida | Seattle
Seattle | Florida

The solution for find_routes('Seattle', 'Florida') should be [Seattle -> Florida, Seattle -> LA -> Florida]

You are given a rectangular cake with a rectangular piece removed. The removed piece is of any size or orientation.

How would you cut the remainder of the cake into two equal halves with one straight cut of a knife?