0% found this document useful (0 votes)
215 views

Hacking A Google Interview Practice Questions Person A

The document contains an interview practice question and sample answers for determining if one string is a substring of another. It then provides several additional practice questions on topics like text editor design, detecting overlapping rectangles, removing nodes from a doubly linked list, minimum stack implementation, hash tables, simulating dice rolls with coin flips, and determining if two numbers in an unsorted array sum to a target value. For each question, one or more high-quality sample answers are provided.

Uploaded by

Sarah Mobeen
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
215 views

Hacking A Google Interview Practice Questions Person A

The document contains an interview practice question and sample answers for determining if one string is a substring of another. It then provides several additional practice questions on topics like text editor design, detecting overlapping rectangles, removing nodes from a doubly linked list, minimum stack implementation, hash tables, simulating dice rolls with coin flips, and determining if two numbers in an unsorted array sum to a target value. For each question, one or more high-quality sample answers are provided.

Uploaded by

Sarah Mobeen
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

HackingaGoogleInterviewPracticeQuestions PersonA

Question:Substring Writeaprogramtodeterminewhetheraninputstringxisasubstringofanother inputstringy.(Forexample,"bat"isasubstringof"abate",butnotof"beat".)You mayuseanylanguageyoulike. SampleAnswer(inC++): bool hasSubstring(const char *str, const char *find) { if (str[0] == '\0' && find[0] == '\0') return true; for(int i = 0; str[i] != '\0'; i++) { bool foundNonMatch = false; for(int j = 0; find[j] != '\0'; j++) { if (str[i + j] != find[j]) { foundNonMatch = true; break; } } if (!foundNonMatch) return true; } return false; Question:TextEditor

Describeadesignforatexteditor.Describetheclasses,interfaces,andsoonthat youwoulduseandhowyouwouldorganizethem. Answer:Therearesomanypossibleanswerstothisproblemthatitwouldbe difficulttosaythatoneansweristhebest.Looktomakesurethattheymake classestosetupatexteditor(classesfortheGUI,formatting,saving/loadingfiles, handlinginput,etc.).Usinginheritance(subclassinginobjectoriented programming)whereitmakessenseisalsogoodforreusabilityandextendability. Usingdesignpatters(suchasModelViewController,Listener/Observer,orthe Singletonpattern)isalsoagoodthing.Themainpointisforthemtogetusedto thinkingabouthowtheywoulddesignasystem.Mostimportantly,theyneedto thinkaboutsimplicity,reusability,andextendabilityintheirdesign.

Atexteditordesignquestionisslightlydifferentfromotherdesignquestionsinthat programmersoftenhavestrongfeelingsabouthowatexteditorshouldwork. Programmersoftenwanttheabilitytogreatlymodifythebehavioroftheireditor andwanttobeabletowriteextensionsthataddfunctionalitytoit.Themajortext editorsusedbyprogrammerstoday,suchasEmacs,Vim,Eclipse,andVisualStudio havethisability.Adiscussionabouthowtheirtexteditorwouldaccomplishthis (especiallywithhowthedesignwouldincludeaplaceforextensionsandhowinput wouldbehandled)wouldbegood. Question:AxisAlignedRectangles Describeanalgorithmthattakesanunsortedarrayofaxisalignedrectanglesand returnsanypairofrectanglesthatoverlaps,ifthereissuchapair.Axisaligned meansthatalltherectanglesidesareeitherparallelorperpendiculartothexand yaxis.Youcanassumethateachrectangleobjecthastwovariablesinit:thexy coordinatesoftheupperleftcornerandthebottomrightcorner. GoodAnswer:Createasortedarrayofthexcoordinatesoftheleftandrightedgesof therectangles.Then,usea"scanline"tomovefromlefttorightthroughthe rectangles.Keepabinarysearchtreecontainingtheycoordinatesofthetopand bottomedgesoftherectanglesthatoverlapthescanline.Foreachelementofthe array,checkwhetheritisaleftorrightedge.Ifitisarightedge,removethe correspondingtopandbottomedgesfromtheBST.Ifitisaleftedge,searchtheBST forrectanglesthatoverlapthecurrentrectangle;ifthereisone,returntheoverlap. Then,addtheycoordinatesofthetopandbottomedgesoftherectangletotheBST. ThesearchtakesO(nlogn)time,sinceittakesO(nlogn)timetosorttherectangles andeachofthe2niterationstakesO(logn)time. Question:DoublyLinkedList Writeafunctiontoremoveasingleoccurrenceofanintegerfromadoublylinked listifitispresent.Youmayuseanylanguageyoulike. SampleAnswer(inJava): void remove(Node head, int value) { Node cur = head; while (cur != null) { if (cur.value == value) { if (curr.prev != null) cur.prev.next = cur.next; if (cur.next != null) cur.next.prev = cur.prev; break; } cur = cur.next;

} } Question:MinimumStack Describeastackdatastructurethatsupports"push","pop",and"findminimum" operations."Findminimum"returnsthesmallestelementinthestack. GoodAnswer:Storetwostacks,oneofwhichcontainsalloftheitemsinthestack andoneofwhichisastackofminima.Topushanelement,pushitontothefirst stack.Checkwhetheritissmallerthanthetopitemonthesecondstack;ifso,push itontothesecondstack.Topopanitem,popitfromthefirststack.Ifitisthetop elementofthesecondstack,popitfromthesecondstack.Tofindtheminimum element,simplyreturntheelementonthetopofthesecondstack.Eachoperation takesO(1)time. Question:HashTables Describehowahashtableworks. Answer:Youcanrefertohandout2foradescriptionofhashtables. Question:CoinFlippingandDieRolls Describeanalgorithmtooutputadieroll(arandomnumberfrom1to6),givena functionthatoutputsacointoss(arandomnumberfrom1to2).Eachpossible outcomeshouldbeequallylikely. SampleAnswer:Flipthecointhreetimes,andusethethreecoinflipsasthebitsofa threebitnumber.Ifthenumberisintherange1to6,outputthenumber. Otherwise,repeat.Notethatmanyotheranswersarepossible. Question:TargetSum Givenanintegerxandanunsortedarrayofintegers,describeanalgorithmto determinewhethertwoofthenumbersadduptox.(Inthiscase,saythatthe interviewerhateshashtables.) GoodAnswer:Sortthearray.Then,keeptrackoftwopointersinthearray,oneat thebeginningandoneattheend.Wheneverthesumofthecurrenttwointegersis lessthanx,movethefirstpointerforwards,andwheneverthesumisgreaterthanx, movethesecondpointerbackwards.Ifyoucannotfindtwonumbersthataddtox beforeoneofthepointersmeet,thenthereisnopairofintegersthatsumtox.This solutiontakesO(nlogn)timebecausewesortthenumbers.

AnotherGoodAnswer:Createabinarysearchtreecontainingxminuseachelement inthearray.Then,checkwhetheranyelementofthearrayappearsintheBST.It takesO(nlogn)timetocreateabinarysearchtreefromanarray,sinceittakes O(logn)timetoinsertsomethingintoaBST,andittakesO(nlogn)timetoseeif anyelementinanarrayisinaBST,sincethelookuptimeforeachelementinthe arraytakesO(logn).ThereforesteponetakesO(nlogn)timeandsteptwotakes O(nlogn)time,soourtotalrunningtimeisO(nlogn). Question:Debugging Describeagoodstrategytofindabuginaprogram. Answer:Thisquestionhasmanypossibleanswers,andisthesortofopenended questionthatinterviewersoccasionallyask.Agoodanswertothisquestionmight includeidentifyingtheportionoftheprograminwhichthebugappearstobe occurringbasedonitsbehavior,aswellasusingbreakpointsandasteppertostep throughtheprogram.Anyanswersthatinvolvethinkingaboutpossiblesourcesof theproblemandfindingwaystolimitthesearchscopeofthebugaregoodanswers.

You might also like