You are on page 1of 14

Exam (

wit
hanswers
)
Datast
ruct
uresDI
T960

Ti
me Monday30thMay2016,14:
00–18:
00
Pl
ace Hör
sal
sväge
n
Cour
ser
espons
ibl
e Ni
ckSmal
lbone
,te
l.0707183062

Thee
xam c
ons
issofs
t ixque
sti
ons
.Fore
achque
sti
onyouc taG oraVG.
ange
taG ont
Toge hee
xam,youne
edt
oans
wert
hre
eque
sti oG s
onst tandar
d.
taVG ont
Toge hee
xam,youne
edt
oans
werfiv
eque
sti oVG s
onst tandar
d.
Afull
ycorr
ectans
werf
oraque
sti
onwil
lgetaVG.Ananswerwi
ths
mal
l
mi
stakeswi
llge
taG.Ananswe
rwithl
argemis
take
swi
llgetaU.
Whe naques
tionas
ksforps
eudocode
,youcanuseami xtur
eofEngl i
shand
progr
ammingnotat
iontode
scri
beyoursol
uti
on,andshouldgiveenoughdet
ail
thatacompe
tentpr
ogrammercoulde
asi
lyimple
me ntyoursol
ution.

Al
lowe
dai
dsOneA4pie
ceofpape
rofnote
s,whi
chs
houl
dbehande
dina
fte
r
t
heexam.
Youmayus ebot
hside
s.
Youmayal
sobr
ingadi
cti
onar
y.

Not
e Be
gine
achque
sti
ononane
w page
.
Wr
it
eyouranonymousc
ode(
notyourname
)one
ver
ypage
.

Goodl
uck!
1.Thef ol
lowingalgor
it
hm takesasinputanarray,andreturnsthear
ray
withallthedupli
cat
ee l
ementsremoved.Forexampl e
,iftheinputarr
ayi
s
{1,3,3,2,4,2},t
healgori
thm re
turns{1,3,2,4}.

S=newemptyset
A=newemptydynamicarray
foreveryelementxi ninputarray
ifnotS.member(x)then
S.insert(x)
A.append(x)

returnA

Whatist
hebi
g-Oc
ompl
exi
tyoft
hisal
gor
ithm,i
fthes
eti
s
i
mplement
edas
:

a)anAVLt
ree
?

ForG:O( nlogn)
(Thelooprunsnti
me s
,andmember+ins
erttake
sO( l
ogn)ti
me.
Appendtakesamort
is
edO( 1)t
imes
othesequenceofnappe
ndst
ake
s
O(n)time.
)

ForVG:O(
nlogm)–t
hes
etSal
waysc
ont
ainsatmos
tm e
leme
nts

b)ahas
htabl
e?

Ans
wer
:O(
n)be
caus
ehas
htabl
eope
rat
ionst
ake(
expe
cte
d)O(
1)t
ime

ForG:wr
itet
hec
ompl
exi
tyi
nte
rmsofn,t
hes
izeoft
hei
nputar
ray
.

ForVG:wr it
ethecomplexi
tyint
ermsofnandm,whe r
enisthesi
zeof
theinputarr
ayandm isthenumberofdi
sti
ncte
leme
ntsint
hearr
ay(i.
e.
thenumbe rofel
ement
signori
ngdupli
cat
es)
.
2.Supposeyouhavet
hef
ollowi
nghashtabl
e,i
mplemente
dusingline
ar
pr ng.
obi Thehashf
unc
tionweareusi
ngisthei
dent
ityfunc
tion,h(
x)=x.

0 1 2 3 4 5 6 7 8

9 18 12 3 14 4 21

a)Inwhichorde
rcouldtheele
me nt
shavebee
nadde dt
othehas
htable?
Thereares
ever
alcorr
ectanswers
,andyoushouldgi
veal
loft
hem.
Ass
umet hatt
hehashtablehasneve
rbeenres
ize
d,andnoel
ementshave
bee
nde l
ete
dyet.
A 9,14,4,18,12,3,21
B 12,3,14,18,4,9,21
C 12,14,3,9,4,18,21
D 9,12,14,3,4,21,18
E 12,9,18,3,14,21,4

Ans
wer
:CandD

I
nA,4wouldbeinse
rtedatindex4inst
eadof6
I
nB,18wouldbeinse
rtedatindex0inst
eadof1
I
nE,21wouldbeins
ertedatindex6ins
teadof7

b)Re
move3f
rom t
hehas
htabl
e,andwr
it
edownhow i
tlooksa
fte
rwar
ds.

Ans
wer:t
hei
mporta
ntthi
ngist
ouselaz
ydele
tion(j
ustre
moving3f
rom
t
hearr
aywil
lle
avee.
g.4i
nthewrongcl
ust
er)
.S owegetthi
s:

0 1 2 3 4 5 6 7 8

9 18 12 XXX 14 4 21
c
)ForVG only:i
fwewa ntahas
ht abl
etha
tstor
esas
etofs
tri ,one
ngs
pos
sibl
ehashf
unc
tionisthes
tri
ng’sl
engt
h,h(
x)=x.
le h.
ngt

I
sthi
sagoodhas
hfunc
tion?Expl
ainyourans
wer
.

Ans
we r
:no.Stri
ngswiththesamel
engt
hwi l
lhavet
hesamehashcode.
I
fweinsertl
otsofst
ringswit
hthesamele
ngth,l
ookupwil
ltakeO(n)
t
imeinst
eadofO( 1)
.

[Thishas
hfunct
ionwasappare
ntl
yusedbye
arl
yve
rsi
onsofPHP!
See:ht
tps
://
lwn.
net/
Art
icl
es/
577494/
]
3.Desi
gnanalgori
thm t
hatt
ake
stwoarrays
,andr
etur
nst
ruei
fthear
rays
ar
edisj
oint
,i.
e.havenoel
ement
sinc
ommon.

Youmayfr
eel
yusestandar
ddat ast
ructure
sanda l
gor
it
hmsfr
om t
he
cour
sei
nyoursol
uti
on,withoutexpl
aininghow t
heyarei
mpl
ement
ed.

Wr i
tedownyouralgor
ihm asps
t eudocode.
Youdon’
tne
edtowrit
eJava
code,butbepre
cis
e–ac ompet
entprogrammers
houl
dbeablet
otake
yourdescr
ipt
ionandeasi
lyi
mplementit.

ForaG:youral
gor
it
hm s
houl
dtakeO(
nlogn)t
ime
.

ForaVG:youralgori
thm s
houldtakeO(nlogm)ti
me ,whe
renist
hes
ize
ofthelar
gerar
rayandm isthesi
zeofthes
mallrar
e ray.
HintforVG:si
ncen≥m,t hisi
sthesameasO(nlogm +m logm).

ForaG:
Supposethetwoarra
ysarec
all
edarra
y1andarr
ay2.Theide
aistoi
nse
rt
al
lelementsofar
ray1int
oan(e.
g.)AAtr
eeandthenche
ckifanyel
ement
ofarr
ay2i si
nthetre
e.

S=newAAt ree
f
orxinar r
ay1do
S.i
nsert
(x)
f
orxinar r
ay2do
ifS.
me mber(
x)t
henr
etur
nfal
se
r
etur
nt r
ue

ForaVG:
SinceSc ont
ainsthec ontentsofarray1,thealgori
thm abovet
ake
s
O( ml ogm +nl ogm)t ime,wherem i sthesi
z eofarr
ay1andnisthesi
ze
ofarra y2.Toge tthere quir
edtimec ompl e
xit
y ,wejus
tne e
dtomakesure
thatar ray1isthesmal lerarra
y.So,wedo:
ifarra
y1.siz
e (
)>ar r
ay2.s
ize(
)the n
swapar ray1andar r
ay2v ari
ables
andt he nrunthepr eviousalgori
thm.
4.Lookatt
he2-
3tr
eebe
low.

3 8

1 6 1011

1
a)Dr
aw t
he2-
3tr
eeasanAAt
ree
.Mar
keac
hnodewi
thi
tsl
eve
l.

Answer(
I’
vedrawnnode
soft
hes
amel
eve
lne
xtt
oeac
hot
herbuty
ou
don’
tnee
dto):

2 2
3 8

1 1 1 1
1 6 10 11

b)I
nse
rt9int
otheAAt r
eeusi
ngt
heAAt
reei
nse
rti
onal
gor
it
hm.
Wri
tedownthefinalt
ree
.

I
’vewr
it
tendowne
achs
tepbuti
t’
senought
ojus
tgi
vet
hefinalans
wer
.

1 I
fyouhavestudi
edthever
sionofAAt
ree
sthatus
esc
olour
s,youmaywr
it
edownt
he
c
olour
sins
teadofthele
vel
s.
Fi
rstwedoBSTi
nse
rti
on,gi
vingt
hene
w nodeal
eve
lof1:
2 2
3 8

1 1 1 1 1
1 6 9 10 11

Now 10hast
hes
amehe
ightasi
tsl
eftc
hil
d,s
owedoas
kew(
rot
ati
on)
:
2 2
3 8

1 1 1 1 1
1 6 9 10 11

Now 10hasbe
comea“4-
node
”,s
owedoas
pli
t,whi
chl
if
ts10up:
2 2 2
3 8 10

1 1 1 1
1 6 9 11

Now 3hasbe
comea“4-
node
”,s
owedoa
not
hers
pli
t,whi
chl
if
ts8up:

3
8

2 2
3 10

1 1 1 1
1 6 9 11
5.Abi direc
tionalmapisamapwhichsuppor
tsbi
dir
ect
iona
llookup:give
n
ake y,youc anfindt
hecor
res
pondi
ngvalue
,andgi
venavalue,youcan
findthecor re
spondi
ngkey
.

Inabidir
ect
ionalmapther
eisalwaysaone
-to-
onerel
ati
onshipbetwe
e n
keysandvalues
.Inot
herwords,eachke
yhasexact
lyonevalue,a
nde ach
valuei
sfoundunderexac
tlyonekey.

I
tsuppor
tst
heus
ualmapope
rat
ions
:
◦ new():c
reat
eane
w,e
mpt
ymap
◦ insert(k,v):addthemappi
ngk→ vtot
hemap;
anyexisti
ngmappingwit
hkeykorval
uevisr
emov
ed.
◦ lookup(k):i
fthemapc
ont
ainsamappi
ngk→ v,r
etur
nv
◦ delete(k):i
fthemapc
ont
ainsamappi
ngk→ v,de
let
eit

pl
ust
hef
oll
owi
ngr
eve
rs ookupope
el rat
ion:

◦ rlookup(v):i
fthemapc
ont
ainsamappi
ngk→ v,r
etur
nk

Thef
oll
owi
nge
xampl
eshowswha
ttheva
riousope
rat
ionsdo.

Ope
rat
ion Re
sul
t
new() Mapi
s{}
insert(1,2) Mapi
s{1→ 2}
insert(3,4) Mapi
s{1→ 2,3→ 4}
lookup(1) Re
tur
ns2
insert(4,2) Mapis{
3→ 4,4→ 2}
.
Not
icet
hatt
hemappi
ng1→ 2i
sre
plac
edby4→ 2.
rlookup(2) Re
tur
ns4
delete(4) Mapi
s{3→ 4}
Wec
ani
mpleme
ntabi di
rec
tionalmapus
ingt
womaps
,eac
h
i
mpl
eme
nte
dase.g.anAAt r
e e
:

◦ forwardisamapf r
om keyst
ovalue
s.
Intheexampleabove,i
tcont
ains3→ 4a
nd4→ 2.

◦ backisamapfrom val
uest
oke ys
.
Intheexampl
eabove,i
tcontai
ns4→ 3a
nd2→ 4.

Theinvar
ianti
sthatt
hetwomapsal
wayscont
ainthesamedata:
forwardc
ontai
nsthemappi
ngk→ v,i
fandonlyifbackcont
ainst
he
mappingv→ k.

Wec
ant
heni
mpl
eme
ntnew,lookupandrlookupasf
oll
ows
:

◦ new:s
etforwardandbackt
obee
mpt
yAAt
ree
s

◦ lookup(k):l
ookupki
nforwardus
ingt
heBSTl
ookupal
gor
it
hm

◦ rlookup(v):l
ookupvi
nbackus
ingt
heBSTl
ookupal
gor
it
hm

Yourt
askist
oimple
mentther
emai
ningope
rat
ions
,insertanddelete,
wit
hO( l
ogn)compl
exi
ty.

Becaref
ul:t
hea l
gorit
hm ismorecompli
cat
edthani tse
ems.Bee
xtra
car
efult
hatyoumai ntai
nthedatastr
uct
ureinv
ariant.I
t’
sal
soagood
i
deat ot
estyoursol
utionontheprevi
ouspage’
sexampl e
.

Givepseudoc
odefore
achoftheoperati
ons.
Youdon’
tne
edtowri
teJ
ava
code,butbepre
cis
e–acompetentprogrammers
houl
dbeabl
etot
ake
yourdescr
ipt
ionande
asi
lyi
mpl ementit
..

Youmayf r
eelyusestandar
ddatast
ruct
uresandalgori
thmsf
rom t
he
coursei
nyours olut
ion,inc
ludi
ngi
nsert
ion/
lookup/de
let
ioni
namap,
withoutexplai
ninghow theyar
eimple
me nte
d.
I
’l
lass
umethatlookupandrl
ookupret
urnnullwhent
hekeyisnot
f
ound.Thet
ric
kyt hi
ngist
oalwayske
eptheforwar
dandbackwardmaps
i
nsync.

de
let
e(k)
:
//Findthev aluesothatwec
ande
let
eitf
rom t
hebac
kwar
dmap
v=f orward.lookup(k)
ifv!=nullthe n
for
war d.dele
te(k)
back.delet
e(v)

I
ni nse
rti
on,wenee
dt ofindanye xi
sti
ngentr
ieswiththesameke yor
val
ue,andremovet
hemf rom theforwardandbackwar dmaps .
Ont heexampl
eintheque s
tion,whenwec al
linse
rt(4,2)
,thatshoul
d
r
e move1f r
om t
hefor
war dmapand2f r
om thebackwardmap.

i
nse
rt(
k,v )
:
//Finda ndr emov eanye nt
rywithkeyk
v’=f orwar d.
lookup(k)
ifv’!=nul lthen
for
war d.del
e t
e(k)/
/thisl
inei
snotst
ric
tlyne
ces
sar
y
back.del
e t
e(v’
)

//Finda ndr emoveanye nt


rywi
thval
uev
k’=bac k.lookup(v)
ifk’!=nul lthen
forwar d.
delet
e(k’
)
bac k.del
ete
(v)//thi
sli
nei
snotst
ri
ctl
yne
ces
sar
y

for
ward.
ins
ert
(k,v)
backwar
d.i
nse
rt(
v,k)
6.Wecanthinkofatre
easbe i
ngas pe
cialki
ndofdir
e c
tedgraph.Tomode
l
atr
eeasagraph,wemaket henodesofthetr
eebecomenode sinthe
gr
aph,anddraw anedgef
rom aparentnodetoeac
hofi t
sc hi
ldre
n.

Thedrawi
ngonthele
fts
howsatr
eeasagr
aph;t
heot
hert
hre
edi
rec
ted
gr
aphsdonotc
orres
pondtoat
ree
.

At
ree Notat
ree Notat
ree Notat
ree

Supposewewantt oche c
ki fagive
ndirecte
dgr aphcorr
espondst
oat r
ee.
Whatpr operti
esshouldwec hec
kthatthegraphhas?Wr it
edownal i
stof
propert
iessuchthat,i
fadi rect
edgraphhasthos epr
opert
ies,i
tmustbea
tr
ee.Youc anrefertostandardpropert
iesofgraphsinyouranswer
withoutexplai
ningthem.

Ians
wer
edt
hisque
sti
onl
ikes
o:

◦ t
hegr
aphmus
tbe(
weakl
y)c
onne
cte
d

◦ i
tmus
tbeac
ycl
ic

◦ e
achnodemus
thave0or1pr
ede
ces
sor
s(t
her
emus
tbea
tmos
tone
e
dgetoeac
hnode
)
Buttherear
emanyot herwaystoans
werit
.Forexampl
e,youc ans
ay
thatt
heremustbeonenode( t
heroot
)suc
ht hatt
her
eisexac
tlyonepat
h
from t
heroott
oa nyothernode.
ht
tp:
//
www.
xkc
d.c
om/
1667

You might also like