




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Solutions to various recursive algorithms and data structures problems from the book 'cracking the coding interview'. Topics include print parantheses, paint fill function, suffix tree, and more.
Typology: Thesis
1 / 310
This page cannot be seen from the preview
Don't miss anything!





























































































CRACKING THE CODING INTERVIEW
CRACKING THE C O D I N G I N T E R V I E W 150 Programming Interview Questions and Solutions GAYLE LAAKMANN
CareerCup com 4
Dear Readers, Welcome to the 4th edition of Cracking the Coding Interview This volume updates the 3rd edition with new content and refreshed information Be sure to check out our website, www careercup com, to connect with other candidates and to discover new resources For those of you new to technical interviews, the process can seem overwhelming Inter- viewers throw questions at you, expect you to whip up brilliant algorithms on the spot, and then ask you to write beautiful code on a whiteboard Luckily, everyone else is in the same boat, and you’re already working hard to prepare Good job! As you get ready for your interviews, consider these suggestions: » Write Code on Paper: Most interviewers won’t give you a computer and will instead expect you to write code on a whiteboard or on paper To simulate this environment, try answering interview problems by writing code on paper first, and then typing them into a computer as-is Whiteboard / paper coding is a special skill, which can be mastered with constant practice » Know Your Resume: While technical skills are extremely important, that’s no reason to neglect your own resume Make sure to prepare yourself to give a quick summary of any project or job you were involved with, and to discuss the hardest and most interesting problems you encountered along the day » Don’t Memorize Solutions: While this book offers a representative sample of interview questions, there are still thousands of interview questions out there Memorizing solu- tions is not a great use of your time Rather, use this book to explore approaches to problems, to learn new concepts, and to practice your skills » Talk Out Loud: Interviewers want to understand how you think and approach prob- lems, so talk out loud while you’re solving problems Let the interviewer see how you’re tackling the problem, and they just might guide you as well And remember -- interviews are hard! In my years of interviewing at Google, I saw some interviewers ask “easy” questions while others ask harder questions But you know what? Getting the easy questions doesn’t make it any easier to get the offer Receiving an offer is not about solving questions flawlessly (very few candidates do!), but rather, it is about answering questions better than other candidates So don’t stress out when you get a tricky question - everyone else probably thought it was hard too! I'm excited for you and for the skills you are going to develop Thorough preparation will give you a wide range of technical and communication skills It will be well-worth it no matter where the effort takes you! Study hard, practice, and good luck! Gayle Laakmann
5 Cracking the Coding Interview
Something’s Wrong We walked out of the hiring meeting frustrated, again Of the ten “passable” candidates we reviewed that day, none would receive offers Were we being too harsh, we wondered? I, in particular, was disappointed We had rejected one of my candidates A former student One who I had referred He had a 3 73 GPA from the University of Washington, one of the best computer science schools in the world, and had done extensive work on open source projects He was energetic He was creative He worked hard He was sharp He was a true geek, in all the best ways But, I had to agree with the rest of the committee: the data wasn’t there Even if my emphatic recommendation would sway them to reconsider, he would surely get rejected in the later stages of the hiring process There were just too many red flags Though the interviewers generally believed that he was quite intelligent, he had struggled to develop good algorithms Most successful candidates could fly through the first ques- tion, which was a twist on a well known problem, but he struggled to develop his algorithm When he came up with one, he failed to consider solutions that optimized for other scenar- ios Finally, when he began coding, he flew through the code with an initial solution, but it was riddled with mistakes that he then failed to catch Though he wasn’t the worst candidate we'd seen by any measure, he was far from meeting “the bar ” Rejected When he asked for feedback over the phone a couple of weeks later, I struggled with what to tell him Be smarter? No, I knew he was brilliant Be a better coder? No, his skills were on-par with some of the best I'd seen Like many motivated candidates, he had prepared extensively He had read K&R’s classic C book and he'd reviewed CLRS' famous algorithms textbook He could describe in detail the myriad of ways of balancing a tree, and he could do things in C that no sane programmer should ever want to do I had to tell him the unfortunate truth: those books aren’t enough Academic books prepare you for fancy research, but they’re not going to help you much in an interview Why? I'll give you a hint: your interviewers haven’t seen Red-Black Trees since they were in school either To crack the coding interview, you need to prepare with real interview questions You must practice on real problems, and learn their patterns Cracking the Coding Interview is the result of my first-hand experience interviewing at top companies It is the result of hundreds of conversations with candidates It is the result of the thousands of candidate- and interviewer- contributed questions And it’s the result of seeing so many interview questions from so many firms Enclosed in this book are 150 of the best interview questions, selected from thousands of potential problems
7 Cracking the Coding Interview
For many candidates, interviewing is a bit of a black box You walk in, you get pounded with questions from a variety of interviewers, and then somehow or other you return with an of- fer or not Have you ever wondered: » How do decisions get made? » Do your interviewers talk to each other? » What does the company really care about? Well, wonder no more! CareerCup sought out interviewing experts from five top companies - Microsoft, Google, Amazon, Yahoo and Apple - to show you what really happens “behind the scenes ” These experts will walk us through a typical interview day and describe what’s taking place outside of the interviewing room, and what happens after you leave Our interviewing experts also told us what’s different about their interview process From bar raisers (Amazon) to Hiring Committees (Google), each company has its own quirks Knowing these idiosyncrasies will help you to react better to a super-tough interviewer, or to avoid being intimidated when two interviewers show up at the door (Apple!) In addition, our specialists offered insight as to what their company stresses in their inter- views While almost all software firms care about coding and algorithms, some companies focus more than others on specific aspects of the interview Whether this is because of the company’s technology or its history, now you'll know what and how to prepare So, join us as we take you behind the scenes at Microsoft, Google, Amazon, Yahoo and Ap- ple
CareerCup com 8
Microsoft wants smart people Geeks People who are passionate about technology You probably won’t be tested on the ins and outs of C++ APIs, but you will be expected to write code on the board In a typical interview, you'll show up at Microsoft at some time in the morning and fill out initial paper work You'll have a short interview with a recruiter where he or she will give you a sample question Your recruiter is usually there to prep you, and not to grill you on techni- cal questions Be nice to your recruiter Your recruiter can be your biggest advocate, even pushing to re-interview you if you stumbled on your first interview They can fight for you to be hired - or not! During the day, you'll do four or five interviews, often with two different teams Unlike many companies, where you meet your interviewers in a conference room, you'll meet with your Microsoft interviewers in their office This is a great time to look around and get a feel for the team culture Depending on the team, interviewers may or may not share their feedback on you with the rest of the interview loop When you complete your interviews with a team, you might speak with a hiring manager If so, that’s a great sign! It likely means that you passed the interviews with a particular team It’s now down to the hiring manager’s decision You might get a decision that day, or it might be a week After one week of no word from HR, send them a friendly email asking for a status update Definitely Prepare: “Why do you want to work for Microsoft?” In this question, Microsoft wants to see that you’re passionate about technology. A great answer might be, “I’ve been using Microsoft software as long as I can re- member, and I'm really impressed at how Microsoft manages to create a product that is universally excellent. For example, I’ve been using Visual Studio recently to learn game programming, and it’s APIs are excellent.” Note how this shows a passion for technology! What’s Unique: You'll only reach the hiring manager if you’ve done well, but if you do, that’s a great sign!
CareerCup com 10
There are many scary stories floating around about Google interviews, but it’s mostly just that: stories The interview is not terribly different from Microsoft’s or Amazon’s However, because Google HR can be a little disorganized, we recommend being proactive in com- munication A Google engineer performs the first phone screen, so expect tough technical questions On your on-site interview, you'll interview with four to six people, one of whom will be a lunch interviewer Interviewer feedback is kept confidential from the other interviewers, so you can be assured that you enter each interview with blank slate Your lunch interviewer doesn’t submit feedback, so this is a great opportunity to ask honest questions Written feedback is submitted to a hiring committee of engineers to make a hire/no-hire recommendation Feedback is typically broken down into four categories (Analytical Ability, Coding, Experience and Communication) and you are given a score from 1 0 to 4 0 overall The hiring committee understands that you can’t be expected to excel in every interview, but if multiple people raise the same red flag (arrogance, poor coding skills, etc), that can disqualify you A hiring committee typically wants to see one interviewer who is an “enthusiastic en- dorser ” In other words, a packet with scores of 3 6, 3 1, 3 1 and 2 6 is better than all 3 1s Your phone screen is usu- ally not a strong factor in the final deci- sion The Google hiring process can be slow If you don’t hear back within one week, politely ask your recruiter for an up- date A lack of response says nothing about your performance Definitely Prepare: As a web-based company, Google cares about how to design a scalable system. So, make sure you prepare for questions from “System Design and Memory Limits” Additionally, many Google interviewers will ask questions involving Bit Ma- nipulation, so please brush up on these questions. What’s Different: Your interviewers do not make the hiring decision. Rather, they enter feedback which is passed to a hiring committee. The hiring committee recommends a decision which can be—though rarely is—rejected by Google executives.
11 Cracking the Coding Interview
Much like the company itself, Apple’s interview process has minimal beaucracy The inter- viewers will be looking for excellent technical skills, but a passion for the position and com- pany is also very important While it’s not a prerequisite to be a Mac user, you should at least be familiar with the system The interview process typically begins with a recruiter phone screen to get a basic sense of your skills, followed up by a series of technical phone screens with team members Once you’re invited on campus, you'll typically be greeted by the recruiter who provides an overview of the process You will then have 6-8 interviews with members of the team for which you’re interviewing, as well as key people with whom your team works You can expect a mix of 1-on-1 and 2-on-1 interviews Be ready to code on a whiteboard and make sure all of your thoughts are clearly communicated Lunch is with your potential future manager and appears more casual, but is still an interview Each interviewer is usually fo- cused on a different area and is discouraged from sharing feedback unless there’s something they want subsequent interviewers to drill into Towards the end of the day, your inter- viewers will compare notes and if ev- eryone still feels you’re a viable candi- date, you'll interview with the director and then VP of the organization you’re applying to While this decision is rath- er informal, it’s a very good sign if you make it This decision also happens be- hind the scenes and if you don’t pass, you'll simply be escorted out of the building without ever having been the wiser (until now) If you made it to the director and VP interviews, all of your interviewers will gather in a conference room to give an official thumbs up or thumbs down The VP typically won’t be present, but can still veto the hire if they weren’t im- pressed Your recruiter will usually fol- low up a few days later, but feel free to ping your recruiter for updates Definitely Prepare: If you know what team you’re interview- ing with, make sure you read up on that product. What do you like about it? What would you improve? Offering specific recommendations can show your passion for the job. What’s Unique: Apple does 2-on-1 interviews often, but don’t get stressed out about them - it’s the same as a 1-on-1 interview! Also, Apple employees are huge Apple fans. You should show this same passion in your interview.
13 Cracking the Coding Interview
The View from the Other Side of the Front, by Peter Bailey For the eager candidate getting ready for a big job interview, Cracking the Coding Interview is an invaluable reference, containing excellent coaching and prac- tice material that gives you an inside edge on the interview pro- cess However, as you go over your old data structures textbook and drill yourself with homemade discrete math flash cards, don’t make the mistake of thinking of the interview as a kind of high- pressure game show – that if you just give all the right answers to the tech questions, you too can win a shiny new career (this week, on Who Wants to be a Software Engineer?) While the technical questions on computer science obviously are very important, the most important interview question is not cov- ered in this guidebook In fact, it’s often the single most important question in your interviewers' minds as they grill you in that little room Despite the ques- tions on polymorphism and heaps and virtual machines, the question they really want an answer to is Would I have a beer with this guy? Don’t look at me like that, I'm serious! Well, I may be embellishing a little, but hear me out The point I'm trying to make is that interviewers, especially those that you might work with, are probably just as anxious as you are Nonsense, you say, as a nervous young professional, checking your pants for lint while you bite your fingernails, waiting for the interview team to show up in the front lobby After all, this is the big leagues, and these guys are just waiting for you to slip up so they can rip you apart, laugh at your shriveled corpse, and grind your career dreams to dust beneath the heels of their boots Right? Just like pledge week, back in freshman year? Right? Hmmm? Nothing could be further from the truth The team of developers and managers interviewing you have their own tasks and projects waiting for them, back at their own desks Believe me, they’re hoping that every interview is going to be the last one They'd rather be doing any- thing else There might be a batch of upcoming projects looming on their calendar, and they need more manpower if they’re going to even have a prayer of making their deadline But the last guy the agency sent over was a complete flake who railed about Microsoft’s evil for half an hour And the one before that couldn’t code his way out of a wet paper bag without using copy-and-paste Sheesh, they think, where is HR getting these guys? How hard can it be to hire one lousy person? While they may not literally be asking themselves “Would I have a beer with this guy (or gal)”, they are looking to see how well you would fit in with the team, and how you would affect team chemistry If they hire you, you’re all going to be spending a lot of time together for
CareerCup com 14
the next few months or years, and they want to know that they can rely on you – and maybe even come to consider you a friend and colleague They want to know that they can depend on you And as tempting as it might be to them to just settle and hire the next person who comes along, they know better In many companies, particularly large U S companies, it’s harder to fire somebody than it is to hire somebody (Welcome to the US: Land of Lawsuits!) If they hire a dud, they’re stuck with them That person might be unproductive or, even worse, a drain on the team’s produc- tivity So they keep interviewing, until they find the right person They know that it’s better to reject a good candidate than hire a bad one Some of those interviews are real doozies Once you’ve interviewed long enough, you build up a repertoire of horror stories War stories, of candidates who looked promising on paper until the interviews went terribly, terribly wrong These war stories are not only humorous – they’re also instructive Names have been changed to protect the innocent – or downright ridiculous. 2.1 zyxwvutsrqponmlkjihgfedcba 2.2 ZYXWVUTSRQPONMLKJIHGFEDCBA 2.3 spw~~kjlslen 2.4 0987654321+_=-)(*&^%$#@!`~[]{};':”,./<>? 2.5 ABCDEZYXW 2.6 abcdeyxw 2.7 asdabcdezyxwasdf 2.8 ~~