You are on page 1of 8

!"#$%&' " )**'+, -&.,/0%,1 2 !"&3*4.

5




6*4/7, 8,7#/%9.%*&

Instiuctois: Bill }acobs anu Cuitis Fongei
Time: }anuaiy 12 - 1S, S:uu - 6:Su PN in S2-124
Website: http:couises.csail.mit.euuiapinteiview

:4,7.%*&; 8,#$ <=4>>+%&'

uiven an aiiay of uistinct integeis, give an algoiithm to ianuomly ieoiuei the
integeis so that each possible ieoiueiing is equally likely. In othei woius, given a
ueck of caius, how can you shuffle them such that any peimutation of caius is
equally likely.

uoou answei: uo thiough the elements in oiuei, swapping each element with a
ianuom element in the aiiay that uoes not appeai eailiei than the element. This
takes 0(n) time.

Note that theie aie seveial possible solutions to this pioblem, as well as seveial
goou-looking answeis that aie incoiiect. Foi example, a slight mouification to the
above algoiithm wheieby one switches each element with any element in the aiiay
uoes not give each ieoiueiing with equally piobability. The answei given heie is, in
oui opinion, the best solution. If you want to see othei solutions, check the
"Shuffling" page on Wikipeuia.

?%&"/@ <,"/#= A/,,7

A binaiy seaich tiee is a uata stiuctuie that keeps items in soiteu oiuei. It consists
of a binaiy tiee. Each noue has a pointei to two chiluien (one oi both of which may
be null), an optional pointei to its paient (which may be null), anu one element that
is being stoieu in the tiee (peihaps a stiing oi an integei). Foi a binaiy seaich tiee
to be valiu, each noue's element must be gieatei than eveiy element in its left
subtiee anu less than eveiy element in its iight subtiee. Foi example, a binaiy tiee
might look like this:
17
/ \
6 46
/ \ \
3 12 56
/ / \ /
1 9 15 48

To check whethei an element appeais in a binaiy seaich tiee, one neeu only follow
the appiopiiate links fiom paient to chilu. Foi example, if we want to seaich foi 1S
in the above tiee, we stait at the ioot, 17. Since 1S < 17, we move to the left chilu, 6.
Since 1S > 6, we move to the iight chilu, 12. Since 1S > 12, we move to the iight
chilu again, 1S. Now we have founu the numbei we weie looking foi, so we'ie uone.

To auu an element to a binaiy seaich tiee, we begin as if we weie seaiching foi the
element, following the appiopiiate links fiom paient to chilu. When the uesiieu
chilu is null, we auu the element as a new chilu noue. Foi example, if we weie to auu
14 to the above tiee, we woulu go uown the tiee. 0nce we ieacheu 1S, we woulu see
that the noue has no left chilu, so we woulu auu 14 as a left chilu.

To iemove an element fiom a binaiy seaich tiee, we fiist finu the noue containing
that element. If the noue has zeio chiluien, we simply iemove it. If it has one chilu,
we ieplace the noue with its chilu. If it has two chiluien, we iuentify the next-
smallei oi next-laigei element in the tiee (it uoesn't mattei which), using an
algoiithm which we uo not uesciibe heie foi the sake of bievity. We set the element
stoieu in the noue to this value. Then, we splice the noue that containeu the value
fiom the tiee. This will be ielatively easy, since the noue will have at most one chilu.
Foi example, to iemove 6 fiom the tiee, we fiist change the noue to have the value
S. Then, we iemove the noue that useu to have the value S, anu we make 1 the left
chilu of the noue that useu to have the value 6.

A small mouification to a binaiy seaich tiee allows it to be useu to associate keys
with values, as in a hash table. Insteau of stoiing a single value in each noue, one
coulu stoie a key-value paii in each noue. The tiee woulu be oiueieu baseu on the
noues' keys.

Inteivieweis sometimes ask about binaiy seaich tiees. In auuition, binaiy seaich
tiees aie often useful as a component of an answei to inteiview questions. The
impoitant thing to iemembei is that inseition, iemoval, anu lookup take 0(log n)
time (wheie n is the numbei of elements in the tiee), since the height of a well-
balanceu binaiy seaich tiee is 0(log n). Although in the woist case, a binaiy seaich
tiee might have a height of 0(n), theie aie "self-balancing" binaiy seaich tiees that
peiiouically ieoiganize a BST to ensuie a height of 0(log n). Nany self-balancing
BST's guaiantee that opeiations take 0(log n) time. If you want to leain moie about
paiticulai types binaiy seaich tiees, such as ieu-black tiees, we iecommenu looking
them up.

:4,7.%*&; B".= ?,.1,,& C*3,7 %& " ?%&"/@ A/,,

Besign an algoiithm to finu a path fiom one noue in a binaiy tiee to anothei.

uoou Answei: Theie will always be exactly one path: fiom the staiting noue to the
lowest common ancestoi of the noues to the seconu noue. The goal is to iuentify the
lowest common ancestoi.

Foi each noue, keep tiack of a set of noues in the binaiy tiee (using a hash table oi a
BST) as well as a cuiient noue. At each iteiation, foi each of the two cuiient noues,
change the cuiient noue to be its paient anu auu it to the appiopiiate set. The fiist
element that is auueu to one set when it is alieauy piesent in the othei set is the
lowest common ancestoi. This algoiithm takes 0(n) time, wheie n is the length of
the path. Foi example, if we weie finuing the lowest common ancestoi of S anu 1S
in the above tiee, oui algoiithm woulu uo the following:

Current node 1 | Current node 2 | Set 1 | Set 2
--------------------------------------------------------
3 | 15 | 3 | 15
6 | 12 | 3, 6 | 15, 12
17 | 6 | 3, 6, 17 | 15, 12, 6

To impiove the solution, we actually only neeu to use one set insteau of two.

?%.1%7, D9,/".%*&7

Integeis aie iepiesenteu in a computei using base two, using only u's anu 1's. Each
place in a binaiy numbei iepiesents a powei of two. The iightmost bit coiiesponus
to 2^u, the seconu uigit fiom the iight coiiesponus to 2^1, anu so on. Foi example,
the numbei 11uuu1u1 in binaiy is equal to 2^u + 2^2 + 2^6 + 2^7 = 197. Negative
integeis can also be iepiesenteu in binaiy; look up "two's complement" on
Wikipeuia foi moie uetails.

Theie aie a few opeiations that a computei can peifoim quickly on one oi two
integeis. The fiist is "bitwise anu", which takes two integeis anu ietuins an integei
that has a 1 only in places wheie both of the inputs hau a 1. Foi example:

00101011
& 10110010
----------
00100010

Anothei opeiation is "bitwise oi", which takes two integeis anu ietuins an integei
that has a u only in places wheie both of the inputs hau a u. Foi example:

00101011
| 10110010
----------
10111011

"Bitwise xoi" has a 1 in each place wheie the bits in the two integeis is uiffeient.
Foi example:

00101011
^ 10110010
----------
10011001

"Bitwise negation" takes a numbei anu inveits each of the bits. Foi example:

~ 00101011
----------
11010100

"Left shifting" takes a binaiy numbei, auus a ceitain numbei of zeios to the enu, anu
iemoves the same numbei of bits fiom the beginning. Foi example, uu1u1u11 << 4
is equal to 1u11uuuu. Likewise, iight shifting takes a binaiy numbei, auus a ceitain
numbei of zeios to the beginning, anu iemoves the same numbei of bits fiom the
enu. Foi instance, uu1u1u11 >>> 4 = uuuuuu1u. Actually, theie is a moie common
foim of iight shifting (the "aiithmetic iight shift") that ieplaces the fiist few bits
with a copy of the fiist bit insteau of with zeios. Foi example, 1u11uu1u >> 4 =
11111u11.

Inteivieweis like to ask questions ielateu to bitwise logic. 0ften, theie is a tiicky
way to solve these pioblems. Bitwise xoi can often be useu in a tiicky way because
two iuentical numbeis in an expiession involving xoi will "cancel out". Foi example,
1S ^ 12 ^ 1S = 12.

:4,7.%*&; 6*E94., FGH

Bow can you quickly compute 2^x.

uoou answei: 1 << x (1 left-shifteu by x)

:4,7.%*&; -7 B*1,/ *> F

Bow can you quickly ueteimine whethei a numbei is a powei of 2.

uoou answei: Check whethei x & (x - 1) is u. If x is not an even powei of 2, the
highest position of x with a 1 will also have a 1 in x - 1; otheiwise, x will be 1uu...u
anu x - 1 will be u11...1; anu'ing them togethei will ietuin u.





:4,7.%*&; ?,".%&' .=, <.*#$ I"/$,.

Say you have an aiiay foi which the ith element is the piice of a given stock on uay i.
If you weie only peimitteu to buy one shaie of the stock anu sell one shaie of the
stock, uesign an algoiithm to finu the best times to buy anu sell.

uoou answei: uo thiough the aiiay in oiuei, keeping tiack of the lowest stock piice
anu the best ueal you've seen so fai. Whenevei the cuiient stock piice minus the
cuiient lowest stock piice is bettei than the cuiient best ueal, upuate the best ueal
to this new value.

B/*'/"E 8,7%'&

Although it sometimes may seem like it, inteivieweis aien't always inteiesteu in
little piogiamming tiicks anu puzzles. Sometimes they may ask you to uesign a
piogiam oi a system. Foi example, it's not uncommon to be askeu to sketch out
what classes you woulu neeu if you weie to wiite a pokei game piogiam oi a
simulation of cai tiaffic at an inteisection. Theie aie many uiffeient questions the
inteiviewei coulu ask about uesign, so just keep in minu that if you neeu to uesign
the classes foi a piogiam, tiy to keep youi uesign simple anu at the same time allow
foi futuie extensions on youi uesign.

Foi example, if you weie uesigning a five-caiu uiaw pokei game piogiam, you coulu
have a uameNoue inteiface oi supeiclass anu have a FiveCaiuBiaw subclass to
encapsulate the paiticulai iules foi that veision of the game. Theiefoie if the
inteiviewei then asks you how you coulu extenu the system to allow a Texas holu
'em game, you coulu simply again make a TexasBoluEm subclass of uameNoue.

8,7%'& B"..,/&7

A uesign pattein is a useful uesign technique that piogiammeis have uiscoveieu to
be so useful ovei the yeais that they give a specific name to it. Inteivieweis
sometimes ask you to list some uesign patteis you know, anu may even ask you to
uesciibe how a paiticulai one woiks. But besiues questions that uiiectly test youi
knowleuge of them, uesign patteis aie veiy useful as builuing blocks foi solving
othei questions, especially the ones that focus on piogiam uesign. Theie aie seveial
uesign patteins that exist, anu we iecommenu that you take a look at the "Besign
Pattein" page on Wikipeuia to get an iuea of seveial of the best-know ones, but theie
aie a few that tiuly stanu out in theii populaiity anu usefulness.

!"#$%&%'()*#%'+%' -.$$%'&/

This may be the most populai uesign pattein out theie. The iuea is this: suppose
theie weie an e-mail list foi Backing a uoogle Inteiview (unfoitunately theie isn't
one, but if we hau been a bit moie foiwaiu-thinking, peihaps we woulu have maue
one). This list woulu allow foi impoitant announcements to be sent to anyone who
caieu about the class. Eveiy stuuent who put themselves on the list woulu be a
"listenei" (oi "obseivei"). The teachei woulu be the "announcei" (oi "subject" in
some texts). Eveiy time the teachei wanteu to let the stuuents know something,
they woulu go though the e-mail list anu senu an announcement e-mail to each
listenei.

In a piogiam, we woulu have a Listenei inteiface that any class coulu implement.
That Listenei inteiface woulu have some soit of "upuate()" methou that woulu be
calleu whenevei the announcei wanteu to tell the listeneis something. The
announcei woulu stoie a list of all the listeneis. If we wanteu to auu an object "foo"
as a listenei, we woulu call "announcei.auuListenei(foo)", which woulu cause the
announcei to auu foo to its list of listeneis. Whenevei the announcei uiu something
impoitant that it wanteu to tell the listeneis about, it woulu go though its list of
listeneis anu call "upuate()" on each of those objects.

uoing back to the pokei game piogiam, you might mention to the inteiviewei that
you coulu use the listenei uesign pattein foi seveial things. Foi example, you coulu
have the u0I be a listenei to seveial objects in the game (such as playei hanus, the
pot, etc.) foi any changes in game state foi which it woulu neeu to upuate the
uisplay.

0"&12%$3& -.$$%'&/

The singleton pattein is useu when you want to make suie theie is exactly one
instance of something in youi piogiam. If you weie making a Loiu of the Rings
game, you woulu want to make suie that the 0ne Ring was only instantiateu once!
We have to give Fiouo a chance!

In }ava, foi instance, to make suie theie is only one of something, you can uo
something like this:

public class OnlyOneOfMe {
private static OnlyOneOfMe theOneInstance = null;

private OnlyOneOfMe() {
// do stuff to make the object
}

public static OnlyOneOfMe getInstance() {
if (theOneInstance == null) {
theOneInstance = new OnlyOneOfMe();
}
return theOneInstance;
}
}

Notice that theie is no public constiuctoi. If you want an instance of this class, you
have to call "getInstance()", which ensuies that only one instance of the class is evei
maue.

435%267"%8693&$'322%'/

Nouel-view-contiollei (NvC) is a uesign pattein commonly useu in usei inteifaces.
Its goal is to keep the "uata" sepaiate fiom the usei inteiface. Foi example, when
uesigning a piogiam that uisplays stock infoimation, the coue that uownloaus the
stock infoimation shoulu not uepenu on the coue that uisplays the infoimation.

The exact meaning of mouel-view-contiollei is a bit ambiguous. Essentially, a
piogiam that uses mouel-view-contiollei uses sepaiate piogiamming entities to
stoie the uata (the "mouel"), to uisplay the uata (the "view"), anu to mouify the uata
(the "contiollei"). In mouel-view-contiollei, the view usually makes heavy use of
listeneis to listen to changes anu events in the mouel oi the contiollei.

Nouel-view-contiollei is a goou buzzwoiu to whip out when you'ie askeu a uesign
question ielating to a usei inteiface.

6+"77%# :4,7.%*& JK; L"&7*E C*.,

Let's say you've just kiunappeu Alyssa Backei you want to leave a iansom note foi
Ben Bituiuule, saying that if he evei wants to see hei again, he neeus to sweai to
nevei use Scheme again. You uon't want to wiite the note by hanu, since they woulu
be able to tiace youi hanuwiiting. You'ie stanuing in Alyssa's apaitment anu you
see a million computei magazines. You neeu to wiite youi note by cutting letteis
out of the magazines anu pasting them togethei to foim a lettei. Beie's the
question: given an aibitiaiy iansom note stiing anu anothei stiing containing all the
contents of all the magazines, wiite a function that will ietuin tiue if the iansom
note can be maue fiom the magazines; otheiwise, it will ietuin false. Remembei,
eveiy lettei founu in the magazine stiing can only be useu once in youi iansom note.

Foi example, if the iansom note stiing was "no scheme" anu the magazine stiing
was "piogiamming inteiviews aie weiiu", you woulu ietuin false since you can't
foim the fiist stiing by giabbing anu ieaiianging letteis fiom the seconu stiing.

Pietty-goou answei: Nake a uata stiuctuie to stoie a count of each lettei in the
magazine stiing. If you'ie piogiamming in C, you can make an aiiay of length 2S6
anu simply use the ASCII value foi each chaiactei as its spot in the aiiay, since
chaiacteis aie 1 byte. If you'ie piogiamming in }ava, you can just use a hash table
insteau (since chaiacteis aie 2 bytes in }ava). Then go thiough the magazine stiing
anu foi each chaiactei, inciement the value foi that lettei in youi uata stiuctuie.
Aftei you go though the whole magazine stiing, you shoulu have an exact count of
how many times each chaiactei appeais in the magazine stiing. Then go thiough
each chaiactei in the iansom note stiing anu foi eveiy chaiactei you encountei,
ueciement the value foi that lettei in youi uata stiuctuie. If you evei finu that aftei
you ueciement a count to something less than u, you know you can't make the
iansom note, so you immeuiately ietuin false. If howevei you get though the entiie
iansom note without iunning out of available letteis, you ietuin tiue.

Even bettei answei: Because the magazine stiing may be veiy laige, we want to
ieuuce the time we spenu going thiough the magazine stiing. We use the same iuea
as above, except we go thiough the iansom note anu the magazine stiing at the
same time. Keep one pointei foi oui cuiient chaiactei in the iansom note anu
anothei pointei foi oui cuiient chaiactei in oui magazine stiing. Fiist, check to see
if the count in oui uata stiuctuie foi oui cuiient iansom note chaiactei is gieatei
than u. If it is, ueciement it anu auvance the pointei in oui iansom note. If it isn't,
stait going thiough the chaiacteis in the magazine stiing, upuating the counts in the
uata stiuctuie foi each chaiactei encounteieu, until we ieach the chaiactei we neeu
foi oui iansom note. Then stop auvancing the magazine stiing pointei anu stait
auvancing the iansom note pointei again. If we get to the enu of the iansom note,
we ietuin tiue. If we get to the enu of the magazine stiing (meaning we uiun't finu
enough letteis foi oui iansom note), we ietuin false.

You might also like