You are on page 1of 31

t

Round4

Simplequestions=>

1.Printthefollowingpattern:
1
121
12321
1234321
123454321


2.GivenanarrayofsizeNinwhicheverynumberisbetween1andN,determineifthereareanyduplicatesinit
.
@jai:pleasementionhintandthetimeafterwhichitshouldbegiven

3.Givenastringof0sand1s.Findthelongestsubsequenceofzeros.ForExample:10100100010010111
Output:Longestsubsequence:000
@jai:whatnistheevaluationcriteriahere.Speed?Optimization?Boundarycases?

4.Writeaprogramtomakethelargestpossiblenumberfromthedigitsofagivennumber.Useextraconstant
space.Forexample519changesto951
@jai:whatisthehinttobegivenandinhowmuchtime?

5.Writeaprogramtoprintallnodesofatree.Givenpointertoitshead.
@jai:isdfsacceptable?Doestheinterviewerhavetoaskforbfsaswell?

6.Giventwostringss1ands2.Findthelongestmatchbetweentailofs1andheadofs2.
Forexample:
Input:s1=abcdefgands2=defghijklm
Output:defg
.
7.Deleteanelementfromadoublylinkedlist.
@jai:mentiontheexactboundarycasesthattheinterviewerwillcheck

Round4
8.Findwhethertwostringsareanagramsornot.
Note:Anagramsarethestringswhichcontainssamecharacters
@jai:hintandwhenisthehinttobegiven

9.Implementaqueueusingtwostacks.
@jai:rattaficationwalahai.Change

10.W riteaprogramtofindthemiddleelementofas inglylinkedlistinminimumiterations.

11.Writeaprogramtofindthekthtolastelementofasinglylinkedlist
@jai:justcheckthatithasntbeenaskedtoofrequently

MediumandDifficult=>

1.Youhavetwoverylargebinarytrees:T1,withmillionsofnodes,andT2,withhun
dredsofnodesCreateanalgorithmtodecideifT2isasubtreeofT1
@jai:toohigh,unlessuwantasimplen2soln

structTreeNode{
intdata
TreeNode*left
TreeNode*right
}

boolisSubtree(Tree*t1,Tree*t2)

Hints=>

TheproblemherespecifiesthatT1hasmillionsofnodesthismeansthatwe
shouldbecarefulofhowmuchspaceweuse.

WecouldcreateastringrepresentingtheinorderandpreordertraversalsIfT2spreordertraversalisa
substringofT1spreordertraversal,andT2sinordertraversalisasubstringofT1sinordertraversal,thenT2is
asubstringofT1

Round4

However,wemayhitmemorylimitations

Betterapproach:

booleancontainsTree(TreeNodet1,TreeNodet2){
if(t2==null)returntrue//Theemptytreeisalwaysasubtree
elsereturnsubTree(t1,t2)
}
booleansubTree(TreeNoder1,TreeNoder2){
if(r1==null)
returnfalse//bigtreeempty&subtreestillnotfound.
if(r1.data==r2.data){
if(matchTree(r1,r2))returntrue
}
return(subTree(r1.left,r2)||subTree(r1.right,r2))
}
booleanmatchTree(TreeNoder1,TreeNoder2){
if(r2==null&&r1==null)
returntrue//nothingleftinthesubtree
if(r1==null||r2==null)
returnfalse//bigtreeempty&subtreestillnotfound
if(r1.data!=r2.data)
returnfalse//datadoesntmatch
return(matchTree(r1.left,r2.left)&&
matchTree(r1.right,r2.right))
}
}

ThetreeMatchprocedurevisitseachnodeinthesmalltreeatmost
onceandiscallednomorethanoncepernodeofthelargetreeWorstcaseruntimeisat
mostO(n*m),wherenandmarethesizesoftreesT1andT2,respectivelyIfkisthenumber
ofoccurrencesofT2srootinT1,theworstcaseruntimecanbecharacterizedasO(n+k*m)

2.Howwouldyoudesignastack(LIFOdatastructure)which,inadditiontopushandpop,alsohasafunction

Round4
min()whichreturnstheminimumelement?Push,popandminshouldalloperateinO(1)time.5
@jai:abetterwaytoaskthequestioncanbethat
structstack{
node*top
intmin
}
implementpushandpopwhichalsomaintainmin.Assumeallelementsareunique.

voidpush(intvalue)
Integerpop()
intmin()

Hints:

Youcanimplementthisbyhavingeachnodeinthestackkeeptrackoftheminimumbe
neathitselfThen,tofindthemin,youjustlookatwhatthetopelementthinksisthemin

Theresjustoneissuewiththis:ifwehavealargestack,wewastealotofspacebykeeping
trackoftheminforeverysingleelement

Wecan(maybe)doabitbetterthanthisbyusinganadditionalstackwhichkeepstrackof
themins

3.Implementanalgorithmtodeleteanodeinthemiddleofalinkedlist,given
onlyaccesstothatnode
@jai:trickquestion.Notinteresting:(

EXAMPLE

Input:thenodecfromthelinkedlista>b>c>d>e
Result:nothingisreturned,butthenewlinkedlistlookslikea>b>d>e

Hints:

Round4

Todeleteanodeinlinkedlistonerequiresapointertothepreviousnode.
Sinceonlypointertothatnodeisavailable,compythecontentsofnextnodeincurrentnode
Nowdeletethenextnode.

4.Givenamatrixinwhicheachrowandeachcolumnissorted,writeamethodtofind
anelementinit.

Hints.
Movefromtherighttopmostelement.andmoveaccordingly.
@ jai:afterhowmuchtimehasthehinttobegiven

5.Writeanalgorithmtofindtheinordersuccessorofagivennodein
abinarytreewhereeachnodehasalinktoitsparent.
@jai:too
Hints:

foranynodeXtherecanbedifferentpossiblitiesforinordresucccessor
1IfXhasarightchild,thenthesuccessormustbeontherightsideofX(actuallytheleftmostchildofright
child)(becauseofthe
orderinwhichwevisitnodes)Specifically,theleftmostchildmustbethefirstnodevisited
inthatsubtree=>3marks
2Else,wegotoXsparent(callitP)
2aIfXwasaleftchild(Pleft=X),thenPisthesuccessorofX
2bIfXwasarightchild(Pright=X),thenwehavefullyvisitedP,sowegotostep2forP

Boundarycase=>
treehasonlyonenode,
returnnullwhennodesdonthavesuccessor

.
6easyQUESTION

Round4
7.Deletenthelementfrombottomofstack.

8.Givenalinkedlistofcharactersandintegers.Youhavetoarrangelinkedlistsuchthatthereisonecharacter
afteroneintegerorviceversa.
Forexamplethelinkedlist1>2>3>t>9>i>4>p>7shouldbecome
1>t>2>i>3>p>9>4>7.

9.FindtheMaxZigzagsequenceinanarray.Zigzagsequenceisasequenceinwhichtheelementsarein
increasing/decreasingorderlike1,5,4,9,8andsoon...
Hint:
Subtractthenumberfromitspreviousnumberandseeinwhicharraymaximumsignchangesarepresent

10.AssumeyouhaveamethodisSubstringwhichchecksifonewordisasubstringof
another.Giventwostrings,s1ands2,writecodetocheckifs2isarotationofs1using
onlyonecalltoisSubstring(ie,waterbottleisarotationoferbottlewat)

Hints.:
contacatenates1toitselfandfindwhethers2issubsetofconcatenatedstring

11.Giventwotrees.Findwhetheroneismirrorimageofanother.

12.WriteanalgorithmsuchthatifanyelementinanmxnmatrixMis0,theneveryelementinthe
correspondingrowand
columnofmatrixMissetto0.

13.Givenalinkedlist,reverseeverynelementsoflinkedlist.Useconstantspace.

@Deprecated

2)Writecodetoremoveduplicatesfromanunsortedlinkedlist?

3)Writeamethodtocomputeallpermutationsofastring

Round4
4)Givenasortedarrayofnintegersthathasbeenrotatedanunknownnumberof
times,giveanO(logn)algorithmthatfindsanelementinthearrayYoumayassume
thatthearraywasoriginallysortedinincreasingorder

5)

6)Youhavetwonumbersrepresentedbyalinkedlist,whereeachnodecontainsasin
gledigitThedigitsarestoredinreverseorder,suchthatthe1sdigitisattheheadof
thelist.Writeafunctionthataddsthetwonumbersandreturnsthesumasalinked
list

7)
8.Writecodetofindwhetheragivenlinklistcontainsaloopornot.

Question1:
Given2strings,boththestringsaresequencesof0sand1s,writeanalgorithmtofindifoneisasubstringof
another.

Question4:
Createafunctiontovalidateapassword
AValidPasswordhasfollowingproperties
1)Itisoflength4to8
2)Itcontainsatleastonedigitandonealphabet
3)Itiscasesensitive
4)Itdoesnotcontainanyrepeatingsequenceofcharatcerslike"abab"isinvalid"abcdef12"isvalidpassword
forsimplicityassumethatpasswordsdonotcontainanyspecialcharacters.

Question7:
Writeafunctionthatcomparestwostringsandreturnsathirdstringcontainingonlythelettersthatappearin
both.

Question8:
Implimentationofintatoi(char*pStr)

Round4

Question9:
Youaregivenanarraywithintegers(bothpositiveandnegative)inanyrandomorder.Findthesubarraywith
thelargestsum.

Solution
voidmaxSumSubArray(int*array,intlen,int*start,int*end,int*maxSum)
{
intmaxSumSoFar=2147483648
intcurSum=0
inta=b=s=i=0
for(i=0i<leni++){
curSum+=array[i]
if(curSum>maxSumSoFar){
maxSumSoFar=curSum
a=s
b=i
}
if(curSum<0){
curSum=0
s=i+1
}
}
*start=a
*end=b
*maxSum=maxSumSoFar
}

Question10:
Howdowetestmostsimplyifanunsignedintegerisapoweroftwo?

Question12:
Giveaverygoodmethodtocountthenumberofonesina"n"
examplein5binary101

Round4
theiraretwoones

Question13:
Insertinasortedlist

Question15:
GiventwostringsS1andS2.DeletefromS2allthosecharacterswhichoccurinS1alsoandfinallycreatea
cleanS2withtherelevantcharactersdeleted.

Question16:
Mergingoftwosortedlinklist

Question17:
BFS/DFSintree

Question18:
Preorder/postorder/inordertraversalinBST

Question19:
Sortingalgorithmslikemergesort,quicksort,heapsort

Question20:
Binarysearchonanunsortedarray(arraysortingisnotallowed)

Question21:
Writecodetofindwhetherastringhasalluniquecharactersornot

Question24:

Question25:
Implementanalgorithmtofindthenthtolastelementofasinglylinkedlist

Round4
Question26:
Writecodetofindnumberofonesinanumber(Forexample3i.e0011hastwo1s)

Question27:
WriteafunctiontofindnumberofbitsrequiredtoconvertintegerAtointegerB.

Question28:
ImplementaMyQueueclasswhichimplementsaqueueusingtwostacks

Question29:
writecodetofindlargestBSTinabinarytree.

Question30:
GiventwosortedarraysofsizemandfindkthsmallestelementinunionofAandB

Question31:
Givenasortedarray(ascendingorder).writealgotocreateabinarytreewithminimumheight.

Question32:
Writeacodetofinddepthorheightofabinarytree

Category1BasicProgramming[ArraysandStrings]2questionsfromthese

1. countOccurence(stringstr1,Stringstr2)MEDIUM
2. lastOccurence(Stringstr1,Stringstr2)SIMPLE(Trickbegincheckinginreverseorderforoptiization)
3. findwhethertwostringsarereverseofeachotherornot.(nullchecks,lengthcomparisionchecksetc
countermanipulations)
4. findthecommonsequenceintwostrings(stringcharactercomparision)
5. twosortedarrays,array1hassize2nbutcontainsonlynelements,array2containsnelementsmerge
array1andarray2inarray1.Donotuseextramemory.(mergeinreverseorder)
6. printcommonwordsintwostrings.wordsseparatedbyspace(MEDIUM)

10

Round4
7. printalluniquecharactersinastring.(EASYApproachmatters)
8. Createafunctiontoreversethewordsinastring.(Optimizeintermsofmemoryandcomplexityboth)
9. Input"IamRam"
10. Output"RamamI"
LinkedList/Tree1
1. reversalofLL
2. sortaLL
3. findanddeletealloccurencesofavalueinLL
4. insertiondoubleLL/circulardoublyLL(pointermanipulationconcepts)
5. deletionofasinglenodefromLL
6. FindthediameterofaBST.

Category2(Algorithm)Lengthy12questions
1. GivenapreorderSequenceforaBinarySearchTree.constructBST
HInttheinorderofabstisthesortedorderofelements

2.MaximumValueContiguousSubsequence.GivenasequenceofnrealnumbersA(1)...A(n),determinea
contiguoussubsequenceA(i)...A(j)forwhichthesumofelementsinthesubsequenceismaximized.

3.LongestIncreasing/Decreasing/ZigZagSubsequence.GivenasequenceofnrealnumbersA(1)...A(n),
determineasubsequence(notnecessarilycontiguous)ofmaximumlengthinwhichthevaluesinthe
subsequenceformastrictlyincreasingsequence

4.BalancedPartition.Youhaveasetofnintegerseachintherange0...K.Partitiontheseintegersintotwo
subsetssuchthatyouminimize|S1S2|,whereS1andS2denotethesumsoftheelementsineachofthetwo
subsets.

5.EditDistance.GiventwotextstringsAoflengthnandBoflengthm,youwanttotransformAintoBwitha
minimumnumberofoperationsofthefollowingtypes:deleteacharacterfromA,insertacharacterintoA,or
changesomecharacterinAintoanewcharacter.Theminimalnumberofsuchoperationsrequiredtotransform
AintoBiscalledtheeditdistancebetweenAandB.

CategoryHARD
1. functiontofindwidthofBinarysearchtree
2. CodetodeleteanodeinBST

11

Round4

1.Givenapallindromenumber,findthenextgreaterpallindromenumber.
Hint:propertyofpallindromenumber.thinkaboutmanupolatingnumberofdigitsforgenerating
palliandrome
Solution:halfthenumberdigitwise,incrementit,makeitpallindrome
Nextlevel:
Givenanumber,findthenextpallindromenumber.
cases:1.inwhichdigitsincreaseho9999,andcaseofevennumandoddnum,caseofsingledigitshouldnot
misswherenextpallindromenumberof9istobecalculated

2.TwoelementsofBSTareswappedbymistake.Youhavetorestorethetreewithoutchangingitsstructure.
Hint:Findingwhoarewronglyplaced,sothatwecanswapthembackdefinitionofBSTimp.
Solution:traverssethetreeininorderfashionanddeterminethewronglyoccurringon.Maintaintheir
pointersandcorrectthem.Incasetheswappednodeareinorderthenonlyoneerrornodewillbe

12

Round4
found,thenswapthemtogether
case:whennodeswappedareconsecutive

3.GivenanarraySofnintegers,findthreeintegersinSsuchthatthesumisclosesttoagivennumber,target.
Returnthesumofthethreeintegers.Youmayassumethateachinputwouldhaveexactlyonesolution.
Forexample,givenarrayS={1214},andtarget=1.
Thesumthatisclosesttothetargetis2.(1+2+1=2).
Hint:sort,thenfindingthecombinationof3intelligenly

Solution:from
http://stackoverflow.com/questions/2070359/findingthreeelementsinanarraywhosesumisclosestto
angivennumber
wecansolvethisinO(n2)time!First,considerthatyourproblemPcanbephrasedequivalentlyina
slightlydifferentwaythateliminatestheneedfora"targetvalue":
originalproblemP:GivenanarrayAofnintegersandatargetvalueS,doesthereexista3tuplefromA
thatsumstoS?
modifiedproblemP':GivenanarrayAofnintegers,doesthereexista3tuplefromAthatsumsto
zero?
NoticethatyoucangofromthisversionoftheproblemP'fromPbysubtractingyourS/3fromeach
elementinA,butnowyoudon'tneedthetargetvalueanymore.
Clearly,ifwesimplytestallpossible3tuples,we'dsolvetheprobleminO(n3)that'sthebruteforce
baseline.Isitpossibletodobetter?W hatifwepickthetuplesinasomewhatsmarterway?
First,weinvestsometimetosortthearray,whichcostsusaninitialpenaltyofO(nlogn).Nowwe
executethisalgorithm:
for(iin1..n2){
j=i//Startwhereiis.
k=n//Startattheendofthearray.

while(k>=j){
//Wegotamatch!Alldone.
if(A[i]+A[j]+A[k]==0)return(A[i],A[j],A[k])

//Wedidn'tmatch.Let'strytogetalittlecloser:
//Ifthesumwastoobig,decrementk.
//Ifthesumwastoosmall,incrementj.
(A[i]+A[j]+A[k]>0)?k:j++
}

13

Round4
//W henthewhileloopfinishes,jandkhavepassedeachotherandthere's
//nomoreusefulcombinationsthatwecantrywiththisi.
}

Thisalgorithmworksbyplacingthreepointers,i,j,andkatvariouspointsinthearray.istartsoffatthe
beginningandslowlyworksitswaytotheend.kpointstotheverylastelement.jpointstowhereihas
startedat.Weiterativelytrytosumtheelementsattheirrespectiveindices,andeachtimeoneofthe
followinghappens:
Thesumisexactlyright!We'vefoundtheanswer.
Thesumwastoosmall.Movejclosertotheendtoselectthenextbiggestnumber.
Thesumwastoobig.Movekclosertothebeginningtoselectthenextsmallestnumber.
Foreachi,thepointersofjandkwillgraduallygetclosertoeachother.Eventuallytheywillpasseach
other,andatthatpointwedon'tneedtotryanythingelseforthati,sincewe'dbesummingthesame
elements,justinadifferentorder.Afterthatpoint,wetrythenextiandrepeat.
Eventually,we'lleitherexhausttheusefulpossibilities,orwe'llfindthesolution.

stepstoreachtothetop.
4.Youareclimbingastaircase.Ittakesn
Eachtimeyoucaneitherclimb1,2....msteps.Inhowmanydistinctwayscanyouclimbtothetop?
Hint:
form=2
asktothinkincaseof3stairs
wecanreachastaironlyfromitspreviousorpreviouskiprevious
fibonacciseries

Solution:NumberOfWays(n1)+NumberOfWays(n2)+...+NumberOfWays(nm),Useoptimizedrecursion,
bystoringtheresultandbetterwouldbetonottouserecursion,juststartbottomup

5.Simple:Mirrorimageofbinarytree
Solution:swaptheleftandrightchildpointersrecursively

6..howmanyonesarerequiredtowritenaturalnumbersfromn1ton2.inbinaryform
Hint:numberof1srequiredfor1ton11and1ton2
Solution:Thenumberof1scanbeseeninthetruthtableofxbooleanswhere2^x>n2forminx,
adjustmentsaretobemadefornumberwhichisnotexactly2^x1.

7.Givenanipwhosealldotsareerased,findoutwhatarethepossibleips

14

Round4
eg.1010112>oneis10.10.11.2,10.10.1.12,1.0.101.12,1.0.10.112
1.010.11.2isnotconsidered
Hint:Recursionandformingnumber>=0and<=255
Solution:Simplerecursion

8.Anumberisaperfectsquareornot,nolibraryfunctiontobeused
Hint:binaryrepresentation
Solution:numbersbinaryrepresentationis11001.Findoutthesmallestnumberwithhalfthedigit100.

copy=number_derived
do
comparethesquare
ifequalgotthenumber,breakout
if<thennumber|=copy>>1
if>thennumber^=(copy|copy>>1)
copy=copy>>1
whilecopy>0

9.Giventwostrings.Printalltheinterleavingsofthetwostrings.
InterleavingmeansthattheifBcomesafterA.ItshouldalsocomeafterAintheinterleavedstring.
ex
ABandCD
ABCD
ACBD
ACDB
CABD
CADB
CDAB

Solution:Simplerecursion

10.Traversethetreevertically
1
2 3

15

Round4
4 5 6 7

output:4215637
Hint:
depthfirstsearchusekarketrykaro
additionaldslikestackcanbeused
Solution:
TraverseinDFSfashion,insteadofprintingthenodeyoucomeacrossputthatinanotherstack,
emptythestackwhenthereisnoleftchild

11.Givenabinarytreeand3nodesx,y,z,writeafunctionwhichreturnstrueifyliesinthepathbetweenxandz
andfalseotherwise.
Hint:Eitherxorzshouldbepresentinachildlegofy
solution:DFS,leftchildlegofywillreturn1ifeitherofxorzispresent,ifbotharepresentthen2,if
nooneispresentthen0.Incase0traverserightlegalsosimilarlyforoutput0,1,2.thefinalanswerwill
betrueonlyif1isobtained.

12.GivenaBST.Replacethenodevaluewiththesumofallthenodevaluesthataregreaterthanthecurrent
nodevalue.
Hint:Inordertraversal
Solution:Reverseinordertraversal,andmaintainingthecumulativesumandprevioustraversednode
value.
BoundaryCase:Nodescanhaveequalvalue,somaintainacounterfornodeswithequalvalue.

13.GivenaBinarytree,findwhetheratreeiscompleteornot.CompleteBinarytreebinarytreeinwhichevery
levelexceptpossiblythelastwillhavetwochildren.TODO:diffincomplete,almostcomplete.Andexactwords
forexplainingtocandidate
Hint:Levelordertraversal
Solition:Levelordertraversal,ifanynodemissesachildthennext(includingpresentnode)allnodes
willnothaveanychild

14.Givenasinglylinklistandanumber'K',swaptheKthnodefromthestartwiththeKthnodefromthelast.
Checkalltheedgecases.
SampleInput:1>2>3>4>5>6>7>8andK=3

16

Round4
SampleOutput:1>2>6>4>5>3>7>8
Hint:Ifcandidatetakes2iterationtofindthesetwoelements,makehimdoin1
Solution:Bymaintainingtwopointersatdistanceofk,youcanfindthekthelementfromstartandkth
elementfromend,swapthem

15.Longestpallindromesubstring
Hint:checkforpallindromearound2n3otherwise1isalwaystheoptionifstringhasmore
than1length
Solution:fromhttp://www.leetcode.com/2011/11/longestpalindromicsubstringparti.html
DPalwayspossible
Asimplerapproach,O(N2)timeandO(1)space:
Infact,wecouldsolveitinO(N2)timewithoutanyextraspace.
Weobservethatapalindromemirrorsarounditscenter.Therefore,apalindromecanbe
expandedfromitscenter,andthereareonly2N1suchcenters.
Youmightbeaskingwhythereare2N1butnotNcenters?Thereasonisthecenterofa
palindromecanbeinbetweentwoletters.Suchpalindromeshaveevennumberofletters
(suchas"abba")anditscenterarebetweenthetwo'b's.
SinceexpandingapalindromearounditscentercouldtakeO(N)time,theoverallcomplexityis
O(N2).

16.Lowestcommonancestorofgiventwonodesinabinarytree.
Hint:DFSapproach,
Solution:Whiletraversalofthetreewillreturnnumberofnodesfoundsofar,Theearliest
nodeatwhichsumoftwoisreachedisthenode

17.GivenanarrayAofsizenandanintegerk<=n,formanewarrayBthatcontainsnk+1
elementssuchthatB[i]isminimumofA[i,....,i+k1].
Hint:Ifcanditdategoesforbruteforce,trytomaintaintheindexoftheminimumfoundandmin
valueinthewindowofk
Solution:
maintaintheminimumandtheindexoftheminimuminthewindowofk.
Iterateoverthearray,and

17

Round4
whenyoumoveforwardbyoneandfindthatminimumyouhavefoundsofarisstillinthe
windowofkthencomaretheminonlywiththenextincomingnumberinthewindow.
otherwiseyouwillhavetosearchthecompletewindowagainforthemin

18.Givenadirectedgraph,designanalgorithmtofindoutwhetherthereisaroutebetweentwo
nodesAandB.

Hint:TraverseagraphfromnodeA
Solution:DFSorothertraversal

19.Givenabinarytree,findthelargestBinarySearchTree(Rootofthetree),wherelargestmeans
BSTwithlargestnumberofnodesinit.ThelargestBSTmayormaynotincludeallofits
descendants.
Hint:thenodewillprovidetheminandmaxvaluesofthebinarytreewhoserootisthenode
itself
Solution:Inordertraversal,
leftchildtreetraversalwillreturntheminandmaxoftheBSTwithrootasleftchild
similarlyforrightchild
ifmodifytheminandmaxvalueswhenevaluatingfortheparentbasedonleftandrightchild
treesoutcome

20.Simple:PrintallprimenumberuptoN
Hint:Additionalbooleanarray,forallnumberfrom1toN
Solution:
fori=1toN,
if(arr[i]=false){//prime
markallarr[x]=trueifx%i==0
}

21.Rotateaonedimensionalarrayofnelementstotherightbyksteps.
Forinstance,withn=7andk=3,thearray{a,b,c,d,e,f,g}isrotatedto{e,f,g,a,b,c,d}.
Hint:Tryreversingastring
Solution:Reversingcompletestring,thenfirstkthenremaining

18

Round4

22.Givenastringofallsmallcharacters,findthelongestsequenceofnonrepeatedcharacters
Hint:DynamicProgramming,ifyouknowthemaxlongestsequenceforn1characters,then
howcanyoudeterminethemaxlongestsequenceforn
Solution:
Startingformendkeepthelargestsequencepossiblestartingfromthatlocation,modifyit
whenwemoveoneelementbackwards
Avoidscanningagainandagainbymaintaininganarrayof26characterswiththeirlocation

23.printallpermutationsofthegivenstringofalluniquecharactersinsortedordereg.permutationsof
BCAinsortedorderareABC,ACB,BAC,BCA,CAB,CBA
Hint:
tryhowtowriteallpermutations
insteadofswappingandunswappinguserightshitingandleftshifting
Solution:Generalpermutationlogicwithuseofshiftinginsteadofswapping

24.Printalltheuniquepermutationsofthestrings(characterscanberepeatedinit)
Hint:tryhowtowriteallpermutations
Solution:checkattimeofswappingforequalchars
Another:Solveas23andcheckifpreviousissameasthecurrentonebeforeprinting

25.pattern

*
* *
* * * *

Thereisonly1starinacolumn

19

Round4

Hint:calculatethenumberofnodestotheleftincaseofinordertraversal

Solution:Onecankeepthenumberofstarsinarow,initialspacetobegivenforanyrow,numberof
spacesbetweenanytwostarsinarow

26.Givenabinarytreereturnits2dimensionalrepresentationinanarrayinthefollowingform

6
/ \
3 7
/ \
4 5

Representationinthearray

3 7

20

Round4

4 5

Hint:depthwillberownumberandwidthwillbecolumn
Solution:
Inordertraversalnumberofnodesbeforethecurrentnodeisthecolumnnumberanddepthofthe
currentnodeistherownumber

27.Simple:Traversetheboundaryofthebinarytreeinanticlockwisedirection.
Hint:Solutionprintleftboundry,rightboundry,leafnodes
solution:Solutionprintleftboundry,rightboundryinreversefashion,leafnodes

29.Simple:Givenanarrayreplacetheelementwithgreatestelementonrightofit.
input:4567853242
output:8888854442
Hint:Startfromright
Solution:
Startingfromrighttoleft:
replacetheelementwithmaxfoundsofar

30.Preordertraversalofthebinarysearchtreeisgiven.CreatetheBST
Hint:Inorderisthesortedarray
Solution:
Doitbyrecursion,findthepreorderofleftchildtreeandrightchildtreebypartitioningthegivenarray
withthefirstelement

31.Recentquestionriskytoask:Addtwonumberswith+
Addtwonumberwithoutmathematicaloperators

Hint:wecanuselogicaloperators

21

Round4
Solution:
sum(a,b)
carry=((a&b)<<1)
a=a^b
returnsum(a,carry)tillcarrnot0

32.HowdoyouapplyBinarySearchon2Darraysupposedyouh ave2Darraywithintegerssortedboth

horizontallyandvertically.Ifyoufindanyoccurrenceofthevalueyouarelookingforyoureturntrueelse

false.Whatisthecomplexity?

Forexamplethe2 Darraycouldlooklikethefollowing

14 5 6

25 7 9

O(m+n)

Eliminators:

1.Writeaprogramtomakethelargestpossiblenumberfromthedigitsofagivennumber.Useextraconstant

22

Round4
space.Forexample519changesto951

2.Givenastringof0sand1s.Findthelongestsubsequenceofzeros.ForExample:10100100010010111
Output:Longestsubsequence:000

3.Writeaprogramtofindthekthtolastelementofasinglylinkedlist

4.Swap2numberswithallboundrycases

4.1Swapkthelemntfromlastandkthelementfromfrontinlinkedlist

5.Reversethestack

6.Nthelementfromthetopofthestack

7.Nthelementfromthebottomofthestack

8partitionthenumbersinthearraybasedonthelastelementofthearrayie.letssaylastelementwasnthen
thefinalarraywilllooklike:
elementslessthann,n,elementsgreaterthann

9.Pattern:

1
121
12321
1234321
123454321

23

Round4

10.Pattern:

5 4 3 2 1
4 3 2 1 5
3 2 1 5 4
2 1 5 4 3
1 2 3 4 5

11.Printthesumofalltheelementsonleftandrightdiagonal.,boundrycases

12.Numberof1sinanumber

13.numberisevenoroddwithoutdividingbytwo
Hint:bitwiseoperatortest

AdditiononApril18

Medium
1. Givenasortedarrayofunknownlengthandanumbertosearchfor,returntheindexofthenumberin
thearray.Accessinganelementoutofboundsthrowsexception.Ifthenumberoccursmultipletimes,
returntheindexofanyoccurrence.Ifitisntpresent,return1.

Solution
The straightforward solution is to scan the array linearly until we find the number, or go out of bounds
and get an exception. In the former casewereturntheindex,thelattercasereturns1.Thecomplexity
is O(N) where N is thenumberofelementsinthearraythatwedontknowinadvance.However,inthis
approach we are not taking advantage of the array being sorted. So we can use some sort of binary
searchtobenefitfromsortedorder.
Standard binary search wouldnt work because we dont knowthesizeofthearraytoprovideanupper
limit index. So, we perform onesided binary search for boththesizeofthearrayandtheelementitself
simultaneously. Lets say were searching for the value k. We check array indexes 0, 1,2,4,8,16,,
2^N in a loop until either we get an exception or we see an element larger than k. If the value is less

24

Round4
thankwecontinue,orifweluckilyfindtheactualvaluekthenwereturntheindex.

2. Givenanarrayofintegersfindthekthelementinthesortedorder(notthekthdistinctelement).So,if
thearrayis[3,1,2,1,4]andkis3thentheresultis2,becauseitsthe3rdelementinsortedorder(but
the3rddistinctelementis3).
Solution:

Thefirstapproachthatcomestomindissortingthearrayandreturningthekthelement.Thecomplexity
is NlogN where N is size of thearrayanditsclearlynotoptimal.Becausethissolutiondoesmorework
than needed, it finds the absolute ordering of all elements but were only looking for the kth largest
element.Wewouldideallypreferalineartimesolution.
WecanusetheSelectionAlgorithmasusedinquicksort.Itworksasfollows,selectapivotandpartition
thearraytoleftandrightsubarrayssuchthat,theelementsthataresmallerthanthepivotvalueendup
intheleftgroup,andtheonesthatareandlargerthanorequaltothepivotareintherightgroup.Now,
onlythepivotisinitssortedposition.Theremainingelementsarenotsortedbuttheirrelativeposition
tothepivot,whethertheyareontheleftorright,isasinsortedorder.Letssayafterpartitioningthe
arraythepositionofthepivotinthearrayism.Ifmisequaltok,thenthepivotisexactlythekth
elementthatwerelookingfor,sowereturnthepivotvalue.Ifmislessthank,thenthekthelementisin
therightsubarray.Elseifmisgreaterthank,thenthekthelementisintheleftsubarray.Sowecan
recursivelycallthesameprocedureandfindthekthelement.

3. Thereisanarrayofnonnegativeintegers.Asecondarrayisformedbyshufflingtheelementsofthe
firstarrayanddeletingarandomelement.Giventhesetwoarrays,findwhichelementismissinginthe
secondarray.
Solution:
1)UsingHashTable
Storethenumberoftimeseachelementappearsinthesecondarray.Thenforeachelementinthefirst
arraywedecrementitscounter.Oncehitanelementwithzerocountthatsthemissingelement.
2)UsingSorting
Sortthefirstarray,sowhilecheckingwhetheranelementinthefirstarrayappearsinthesecond,we
candobinarysearch.
3)UsingXOR
Initializeavariableto0,thenXOReveryelementinthefirstandsecondarrayswiththatvariable.Inthe
end,thevalueofthevariableistheresult,missingelementinarray2

25

Round4

1. Givenanarrayofintegers(positiveandnegative)findthelargestcontinuoussum.

26

Round4

Set1Pankaj
1

*_*

*_*_*
*_*_*_*

2.

Let

A
be

an

array

of

size

n,

containing

positive

or

negative

integers,

with

A[1]

<
A[2]
<...<

A[n].

Design

an

efficient

algorithm

(should

be

more

efficient

than

O(n))

to

find

an

i
such

that

A[i]

=
i
provided

such

an

i
exists.

What

is

the

worst

case

computational
complexity

of

youralgorithm?

Solution

:
binarysearch

3.

Given

a
number

can

you

make

it

palindrome...

just

output

yes,no

eg.

1234
no

1212


yes

1221

or2112

boundary

case

:
112
yes

Solution

:
one

digit

in

odd

number

if

odd

number

of

digits

else

all

should

be

in

even
numbers

4.
Given
an
array replace the
elementwith
greatest
element
on
right
of
it
.
input: 4
5678
532 2
4
output
:8888
854
442
Hint:
Start fromright
Solution:
Starting
from
right
to left:

replacethe
element
with
maxfound
so
far

27

Round4

5.

Given

root

of

the

binary

search

tree

,
and

a
number

,
find

a
number

that

is

k
distance
right

of

that

number

in

the

inorder

traversal

of

binary

searchtree.

Solution:

inorder

traversal

+
maintaining
counter
a

6.
Find
the
Max
Zig
zag
sequence
in
an
array.
Zig
zag
sequenceis
a
sequence
in
which
the
elements
are
in
increasing/decreasing order
like
1,
5,
4,
9
,
8and
so
on...
Hint:
Subtract thenumber
from
its
previous
number
and
see
in
which
array
maximumsign
changes
are present

7.
Two
elements
of
BST
areswapped
by
mistake. Youhave
to
restore
the
tree
without changing its structure.

Hint:Finding who
are
wrongly
placed
,so
that
wecan
swap
themback
definition
of
BST imp.

Solution:
traverse
the
tree
in
inorder fashionanddetermine the
wronglyoccurring
on
.
Maintain
their pointers and
correct
them.In
casethe
swapped
node
are
in
orderthenonly
oneerror
node
will be
found,
then swap
themtogether
case:whennode
swapped are consecutive

8.

Given

'n'

coins,

print

the

number

of

ways

to

form

an

amount

'A'

.
Assume

all

coins

are
of

differentvalue

eg.

from

coins

1,2,3

make3

{1,2}
{3}
,

Solution:

DP

,
the

problem

is

divisible

in

similarsubproblems

28

Round4

32.HowdoyouapplyBinarySearchon2Darraysupposedyouh ave2Darraywithintegerssortedboth

horizontallyandvertically.Ifyoufindanyoccurrenceofthevalueyouarelookingforyoureturntrueelse

false.Whatisthecomplexity?

Forexamplethe2 Darraycouldlooklikethefollowing

14 5 6

25 7 9

O(m+n)

Medium:

HowtofindmedianofaBST?

29

Round4
constraint:withoutstoringitinalineardatastructurebyinordertraversal?

FindlengthandthenfindtheNthelement

Easy::::

Thereisanarrayofintegers,letssay3,5,7,9.Youaresupposedtocreateanotherarrayandpopulate
itsuchthatthesecondarray's0thpositionshouldbeaproductofallnumbersfromthefirstarray
excludingthenumberatits0thposition,meaningitshouldbe5x7x9(excluding3),numberatthe
index1ofthesecondarraywillbeproductof3x7x9(excluding5).Butyoucannotdivide.

Tough:

Pleaseimplementafunctionwhichgetstheminimalnumberofcoins,whosevalueisv1,v2,,vn,tomake

changeforanamountofmoneywithvaluet.Anycoinwithvaluevimayduplicateforanytimestomake
change.
Forexample,theminimalnumberofcoinstomakechangefor15outofasetofcoinswithvalue1,3,9,10is3.
Wecanchoosetwocoinswithvalue3andacoinwithvalue9.Thenumberofcoinsforotherchoicesshouldbe
greaterthan3.

BoundaryCases

PasswordCheck:
Createafunctiontovalidateapassword
AValidPasswordhasfollowingproperties
1)Itisoflength4to8
2)Itcontainsatleastonedigitandonealphabet
3)Itiscasesensitive

30

Round4
4)Itdoesnotcontainanyrepeatingsequenceofcharatcerslike"abab"isinvalid"abcdef12"isvalidpassword
forsimplicityassumethatpasswordsdonotcontainanyspecialcharacters.

DynamicProgramming

Youaregivenanarraywithintegers(bothpositiveandnegative)inanyrandomorder.Findthesubarraywith
thelargestsum.

Letsayarrayis:A
sumOfArrayWithMaxSum(A[0i+1])=maxOf(
sumOfArrayWithMaxSum(A[0i])+A[i+1],
A[i+1]
)

Storethestartandendindexofmaxsubarrayaftereveryloop

DynamicProgramming

Pleaseimplementafunctionwhichgetstheminimalnumberofcoins,whosevalueisv1,v2,,vn,to
makechangeforanamountofmoneywithvaluet.Anycoinwithvaluevimayduplicateforanytimes
tomakechange.
Forexample,theminimalnumberofcoinstomakechangefor15outofasetofcoinswithvalue1,3,
9,10is3.Wecanchoosetwocoinswithvalue3andacoinwithvalue9.Thenumberofcoinsfor
otherchoicesshouldbegreaterthan3.

Sol:Letfisthesetcontainsv1,v2,...vnminCoins(f)=min(fvi)+1forallifrom1n

Givenamatrixnxn,rotateitby90degreewithoutusingextraspaces

Givenamtrixnxn,printthematrixinaspiralfashion

31

You might also like