Contribute to krishabhishek/test development by creating an account on GitHub. This document is a sampling of our book, Elements of Program- ming Interviews in Java (EPI). Its purpose is to provide examples of. This document is a sampling of our book, Elements of Programming. Interviews in chapters on the nontechnical aspects of interviewing. We'd love use library functions like stoi in C++, parseInt in Java, and int in Python.
|Language:||English, Spanish, Arabic|
|Genre:||Fiction & Literature|
|PDF File Size:||9.57 MB|
|Distribution:||Free* [*Regsitration Required]|
You Can Download and Read With File Format Pdf ePUB MOBI and Kindle Version. More Info==> Elements of Programming Interviews in Java: The Insiders' . Elements of Programming Interviews The Insiders' Guide Adnan Aziz .. A guide to reading C++ programs for Java developers is given on Page Source. meteolille.infon. pdf - Ebook download as PDF File .pdf), Text File .txt) or read book .
This information is summarized in Table 1. A large majority of the interview questions at Google. Since different candidates have different time constraints.
Chapter 25 contains a diverse collection of challenging questions. Prepare your resume using the guidelines on the facing page. Go for an on-site interview— this consists of a series of one-on-one interviews with engineers and managers. A summary of nontechnical aspects of interviewing The Interview Lifecycle. You may be asked to submit code via a shared document or an online coding site such as ideone.
Perform an initial phone screening. Identify companies that you are interested in. Table 1. For Scenario i. The screening may involve a homework assignment to be done before or after the conversation. The on-site interview may be conducted over a video chat session. For each chapter. A r6sum6 needs to address HR staff. Unless a problem is italicized. For anything involving interaction over a network.
Use textbooks for reference only. The HR staff. First read Chapter 4. Receive offers these are usually a starting point for negotiations. The people interviewing you and the hiring manager need to know what you've done that makes you special.
The resume It always astonishes us to see candidates who've worked hard for at least four years in school. Most on-sites are half a day. We recommend that you interview at as many places as you can without it taking away from your job or classes.
The experience will help you feel more comfortable with interviewing and you may discover you really like a company that you did not know much about. People reading your r6sum6 proceed in sequential order.
Have friends review your r6sum6. It is better to get something written up quickly. As a rule. The r6sum6 should be of a high-quality: The most important points the ones that differentiate you from everyone else should come first..
Mock interviews Mock interviews are a great way of preparing for an interview. Have your friend take notes and give you Use few fonts. Have a clear statement of your objective. Over two pages is probably not a good idea. Maintaining a logical flow. Whenever possible.
Include design documents as well as a link to your version control repository. These samples may be class projects. Don't worry about wasting your contact's time employees often receive a referral bonus. If you can work at the company without requiring any special processing e. You should list significant class projects this also helps with keywords for HR. I would like to apply these abilities at XYZ. As a consequence. At one company whose practices we are familiar with.
Get a friend to ask you questions from EPI or any other source and solve them on a whiteboard. Include contact information. You will cringe as you watch it. Some Java 1. You should be comfortable with the syntax used to instantiate an anonymous class. Make a video recording of the interview.
In an actual interview. We also have a Junit test suite. Usually we declare helper classes as static inner classes of the top-level class that provides the solution. See Section 2 on Page 14 for more insights. Now we describe practices we follow in EPI which are industry-standard.
We wrote a very small number of utility functions. Best practices for interview code Now we describe practices we use in EPI that are not suitable for production code. Language review Programs are written in Java Some problems explicitly require you to write your own container classes. Wherever possible. We have elected not to use popular third-party libraries. If you cannot find a friend.
They are necessitated by the finite time constraints of an interview. Our test code lives within the mainO method of the top-level class.. Ask your friend to give hints when you get stuck. In addition to sharpening your problem solving and presentation skills.
Apart from these. Tony Bevis' "Java Design Pattern Essentials" conveys the same content in a more succinct but less entertaining fashion. NoSuchElementException when dequeing an empty queue. For design patterns. Note that programs for interviews are too short to take advantage of design patterns.
Many programmers would use a generic Pair or Tuple class.. The definitive book for Java is — "Java: The Complete Reference" by Oracle Press this.
Its primary drawback is its bulk. The guide is fairly straightforward it mostly addresses naming and spacing conventions. This is not needed in an interview. You should spend your time making sure the program works.
This is generally considered a best — — practice it enables code reuse via polymorphism but is not essential to use in an interview.. PORTER A typical one hour interview with a single interviewer consists of five minutes of introductions and questions about the candidate's r6sum6. Work on concrete examples: Consider the problem of determining the smallest amount of change that you cannot make with a given set of coins.
This is followed by five to fifteen minutes of questioning on basic programming concepts. Here are some things to keep in mind when this happens. Feel free to ask the interviewer what time and space complexity he would like in your solution. Clarify the question: A good way of clarifying the question is to state a concrete instance of the problem.
The core of the interview is one or two detailed design questions where the candidate is expected to present a detailed solution on a whiteboard. If a question seems exceptionally hard. Even if they are evasive. If you are told to implement an 0 n algorithm or use 0 1 space. Depending on the interviewer and the question.
This problem may seem difficult at first. Approaching the problem No matter how clever and well prepared you are. It is possible that he will refuse to specify these. Be warned that this strategy can sometimes be detrimental if it takes a long time to describe the brute-force approach.
Add TODO comments for portions that you want to come back to. Focus on the top-level algorithm: It's OK to use functions that you will implement later. Advantages to this approach include: Presenting the solution Once you have an algorithm. Here are some things to keep in mind when presenting a solution. Remember that a hash function should use exactly those fields which are used in the equality check.
Even if you are not able to reach the solution. Spell out the brute-force solution: Writing on a whiteboard is much slower than on a Think out loud: One of the worst things you can do in an interview is to freeze up when solving the problem. Make use of functions skip implementing anything that's trivial e.
Do not reinvent the wheel unless asked to invent it.. Best practices for coding on a whiteboard are very different from best practices for coding on a production project.
Patterns are described in Chapter 4. Patterns general reusable solutions to commonly occurring — problems can be a good way to approach a baffling problem. Specify that you will handle main algorithm first. On the one hand. A comparison function should be transitive.
Manage the whiteboard: You will likely use more of the board than you expect. It is always a good idea to think out loud and stay engaged. This will let you focus on the main part of the algorithm. Examples include finding a good data structure. On the other hand. Interviews are a great Test for comer cases: For many problems.
C for arrays. Interviewers rarely penalize you for small syntax errors since modern IDE excel at handling these details. You should clarify this assumption with the interviewer. Memory management: Generally speaking. If so. Interviewers are not capable of analyzing long programs. Candidates often tend to get function signatures wrong and it reflects poorly on them. See if you can reuse space. Unless they are part of the problem statement. For fresh graduates. Once you are done writing your program.
A good tip is that if your solution takes more than lines to code. You should use search and social networks to learn more about the people interviewing you. Don't forget to add code for checking the result. Letting your interviewers know that you have researched them helps break the ice and forms the impression that you are enthusiastic and will go the extra mile. For example.. Assume valid inputs: In a production environment.
It is important to systematically consider these possibilities. Have a convention for identifiers. If there is time. You should make the best use of this time by getting the information you would need and communicating to the interviewer that you are genuinely interested in the job. Enterprise-oriented company. It is crucial to practice how you will present your best work.
Being precise. Here is a brief classification. Such companies do not have time to train new hires.. Candidates communicating in a language that is not their first language. Government contractor. You may also want to think of some concrete ideas around things you could do for the company.
The tool chain and development practices at such companies tend to be very mature. In addition to knowing your interviewers.
Is the candidate passionate about his work? We always want our colleagues to be excited. Prepare a list of questions in advance. Interviews usually end with the interviewers letting the candidates ask questions.
All companies want bright and motivated engineers. You should be ready to talk about what specifically appeals to you. Such companies have a deeper technology stack.
If you feel passionately about your Mature consumer-facing company. The point of this conversation is to answer the following questions: Can the candidate clearly communicate a complex idea? This is one of the most important skills for working in an engineering team. National Instruments: Based on your interaction with the interviewers. General conversation Often interviewers will ask you questions about your past projects.
This extends to the team and company. If you have a grand idea to redesign a big system. Absolutely nothing is to be gained. Be sure that it really is the same problem. An interviewer may feign ignorance on a topic he knows in depth to see if a candidate pretends to know it.
At the minimum. Keep a positive spirit: A cheerful and optimistic attitude can go a long way. Dishonesty in an interview is a fast pass to an early exit. Interviewers have been known to collude to ask the same question of a candidate to see if he tells the second interviewer about the first instance. Most software companies have a relaxed dress-code.
Is there a potential interest match with some project? The interviewer may gauge areas of strengths for a potential project match. The damage done when you are too casual is greater than the minor embarrassment you may feel at being overdressed.
Keep in mind that because technology changes so fast many teams prefer a strong generalist. It focuses attention on shortcomings. Don't let these simple mistakes lead to your years of preparation going to waste. Don't apologize: Candidates sometimes apologize in advance for a weak GPA. Keep money and perks out of the interview: Money is a big element in any job but it is best left discussed with the HR division after an offer is made.
Other advice A bad mental and physical attitude can lead to a negative outcome. If you know the requirements of the job. Be aware of your body language: Think of a friend or coworker slouched all the time or absentmindedly doing things that may offend others. Nothing can be further from the truth. Their logic is that by being proactive they will somehow benefit from lowered expectations.
It is always a good idea to err on the side of caution and dress formally for your interviews. Work on your posture.
Be honest: Nobody wants a colleague who falsely claims to have tested code or done a code review. More generally. The same is true for vacation time. If your knowledge of Python extends only as far as having cut-and-paste sample code.
The stress may be injected technically. Bear in mind you will not know a priori if a particular interviewer will be conducting a stress interview. Remember the only mistakes are the ones you don't learn from. Negotiating an offer An offer is not an offer till it is on paper. The guidelines in the previous section should help you through a stress interview. Your HR contact is a professional negotiator. When negotiating. All offers are negotiable.
Learning from bad outcomes The reality is that not every interview results in a job offer. If this is the case. Otherwise the recruiter will simply come back with a small increase in the sign-on bonus and claim to have met your request. You will not get any feedback from a bad outcome. To get the best possible offer. Being firm is not the same as being rude. This is what recruiters themselves are evaluated on internally.. Be concrete instead of just asking for more money. Some are technical: You can fail an interview for nontechnical reasons.
He will know and use negotiating techniques such as reciprocity. This can lead to your being asked questions on topics outside of the area of expertise you claimed on your r6sum6.
The company may have decided not to hire in your area. There are many reasons for not getting a particular job. The goal is to see how a candidate reacts to such situations does he fall apart. The Wikipedia article on negotiation lays bare many tricks we have seen recruiters employ. We have seen compensation packages bargained up to twice the initial offer.
Stress interviews Some companies. Often it is better to bypass the HR contact and speak directly with the hiring manager. At the end of the day. One suggestion: If you are asked for something such as a copy of a competing offer. Interviewers also have a moral responsibility not to unfairly crush the interviewee's dreams and aspirations. Unless the candidate walks on water or completely disappoints. A secondary objective of the interview process is to turn the candidate into a brand ambassador for the recruiting organization.
Hiring a bad candidate is expensive for the organization. We — strongly recommend interviewees read it knowing what an interviewer is looking for will help you present yourself better and increase the likelihood of a successful outcome.
Objective The ultimate goal of any interview is to determine the odds that a candidate will be a successful employee of the company. Firing someone is extremely painful as well as bad for to the morale of the team. Even if a candidate is not a good fit for the organization. It seems obvious that it is a bad idea for an interviewer to check email while the candidate is talking or insult the candidate over a mistake he made.
It is important for the candidate to have an overall positive experience during the process.
For someone at the beginning of their career. In this chapter we review practices that help interviewers identify a top hire. This means that the interview was a wasted effort. The ideal candidate is smart. One mistake. What to ask One important question you should ask yourself as an interviewer is how much training time your work environment allows. For a startup it is important that a new hire is productive from the first week. Problem Algorithms and data structure code is usually a small component of a system dominated by the user interface UI.
For a larger organization. It is often hidden in library calls. The best candidate may miss a simple insight. It also gives the interviewer more freedom to steer the candidate. A great candidate may finish with one solution quickly enough to discuss other approaches and the trade-offs between them. In such cases. The justification for this is as follows. When selecting a problem keep the following in mind: There should be at least two or three opportunities for the candidates to redeem themselves.
Problem 6. This book gives interviewers access to a fairly large collection of problems to choose from. Most big organizations have a structured interview process where designated interviewers are responsible for probing specific areas. Outside of a stress interview. At a high level. The exception to this rule is if you want to test the candidate's response to stress. You should standardize scoring based on which hints were given.
Often the best way of doing this is to construct a test case where the candidate's solution breaks down. An overconfident candidate: It is common to meet candidates who weaken their case by defending an incorrect answer. Many things can happen in an interview that could help you reach a decision. To give the candidate a fair chance. In such situations. It is a good idea to check the appropriateness of a problem by asking one of your colleagues to solve it and — seeing how much difficulty they have with it.
Whiteboard snapshots and samples of any code that the candidate wrote should also be recorded. Here are situations that may throw you off: A candidate that gets stuck and shuts up: Some candidates get intimidated by the problem. At the same time. For example you could assert that a particular path will not make progress. Although isolated minor mistakes can be ignored. Coming up with the right set of hints may require some thinking.
Scoring and reporting At the end of an interview. A verbose candidate: Candidates who go off on tangents and keep on talking without making progress render an interview ineffective.
It is important to put the candidate at ease. No unnecessary domain knowledge it is not a good idea to quiz a candidate on advanced graph algorithms if the job does not require it and the candidate does not claim any special knowledge of the field.
You do not want to give away the problem. Conducting the interview Conducting a good interview is akin to juggling. When the right choice is not clear. The litmus test is to see if you would react positively to the candidate replacing a valuable member of your team. Fibonacci heaps. Other data structures. The data structures described in this chapter are the ones commonly used.
Just as a musician. See Solution Don't forget that the basic types differ among programming languages. Java has no unsigned integers. Solutions often require a combination of data structures. Bear in mind developing problem solving skills is like learning to play a musical — instrument books and teachers can point you in the right direction.
Different data structures are suited to different applications. It is precisely for this reason that EPI focuses on problems. Strings Know how strings are represented in memory. Heaps Key benefit: Lists Understand trade-offs with respect to arrays.
Binary search trees Key benefit: O logn insertions. Know hash functions for integers. Table 4. Hash tables Key benefit: The variable y is 1 at exactly the lowest bit of x that is 1. Understand node fields. Know array and linked list implementations. Be familiar with notion of balance. Another approach. Know about depth. Data structures. Arrays Fast access for element at an index. O log n insertion. Understand implementation using array of buckets and collision chains.
Key disadvantages: The overall complexity is 0 n where n is the length of the integer. Min-heap variant. Stacks and queues Recognize where last-in first-out stack and first-in first-out queue semantics are applicable.
Each chapter starts with a brief review of key concepts and results followed by a deep and wide set of questions. EPI concludes with a summary of the nontechnical aspects of interviewing, including common mistakes, strategies for a great interview, perspectives from across the table, negotiating the best offer, and much more.
It is a great resource for a diverse set of topics when preparing for technical interviews, as a quick refresher in a subject area or when you are just looking for a brain teaser to challenge yourself. Get A Copy. Paperback , pages.
More Details Other Editions 4. Friend Reviews. To see what your friends thought of this book, please sign up.
To ask other readers questions about Elements of Programming Interviews , please sign up. Be the first to ask a question about Elements of Programming Interviews. Lists with This Book. Community Reviews. Showing Rating details. Sort order. Feb 08, Josh Davis rated it it was amazing Shelves: This should become the de facto book on interviews. It is loaded with great problems and puzzles. The solutions are very comprehensive. However, don't buy this book thinking that it will teach you about heaps or binary search trees.
It merely contains a few paragraphs for each topic and then goes straight to the problems. You'll need another book to learn about the data structures and algorithms that go with them. This book also contains a few chapters devoted to the interview process itself.
These chapters are just as golden as the technical ones. Interviewing is more about just solving the problems. They want to see who you are as well. Anyways, definitely check this book out if you wish to get extra practice for programming interviews.
Dec 23, Ayberk rated it liked it Shelves: I have pretty much read the whole book, I'm saying pretty much because there are waaaay too many questions and there's no way I try to solve all of them: P If you genuinely solve all the questions in the book, I'd say you're pretty much set for a software engineering job.
This is a bug in today's software engineering recruitment, it doesn't matter if you know good practices, design patterns, maintainability, readability, etc Back to book, explanations were not that clear and most importantly the code was incredibly hard to read. Great selection of questions. Not so great execution on explanations and code quality readability. Mar 06, Fatima rated it really liked it Shelves: Finally something not in Java It contains many good questions.
There are though many questions that were silly or it didn't stress a concept that you need to learn. View 1 comment. Oct 09, Jack Hwang rated it liked it. Yes, this book is full of interview questions. However, the criteria the authors used to pick the questions is quite academic and may not be very pragmatic. It is hard to believe that any of today's interviewers would ask some of the questions in the book within the average interview session time span of 45 minutes.
Furthermore, it lacks of short reviews in the chapters. Specify that you will handle main algorithm first, then corner cases. Add TODO comments for portions that you want to come back to. Manage the whiteboard: You will likely use more of the board than you expect, so start at the top-left corner. Have a system for abbreviating variables, e. Make use of functions—skip implementing ElementsOfProgrammingInterviews. Test for corner cases: For many problems, your general idea may work for most inputs but there may be pathological instances where your algorithm or your implementation of it fails.
For example, your binary search code may crash if the input is an empty array; or you may do arithmetic without considering the possibility of overflow. It is important to systematically consider these possibilities. If there is time, write unit tests. Small, extreme, or random inputs make for good stimuli. Often the code to handle obscure corner cases may be too complicated to implement in an interview setting.
If so, you should mention to the interviewer that you are aware of these problems, and could address them if required. Interviewers rarely penalize you for small syntax errors since modern IDE excel at handling these details.
However, lots of bad syntax may result in the impression that you have limited coding experience. Once you are done writing your program, make a pass through it to fix any obvious syntax errors before claiming you are done. We use the Google coding style standards in this book, and advise you to become proficient with them.
They are available at code. Candidates often tend to get function signatures wrong and it reflects poorly on them. For example, it would be an error to write a function in C that returns an array but not its size.
Use const as appropriate. Memory management: Generally speaking, it is best to avoid memory manage- ment operations altogether. The run time environment will automatically deallocate the object a scoped pointer points to when it goes out of scope. If you explicitly allocate memory, ensure that in every execution path, this memory is de-allocated.
See if you can reuse space. For example, some linked list problems can be solved with O 1 additional space by reusing existing nodes. You should use search and social networks to learn more about the people interviewing you. Letting your interviewers know that you have researched them helps break the ice and forms the impression that you are enthusiastic and will go the extra mile.
For fresh graduates, it is also important to think from the perspective of the interviewers as described in Chapter 3. Once you ace your interviews and have an offer, you have an important decision to make—is this the organization where you want to work? Interviews are a great time to collect this information.
Interviews usually end with the interviewers letting the candidates ask questions. You should make the best use of this time by getting ElementsOfProgrammingInterviews. Strategies For A Great Interview the information you would need and communicating to the interviewer that you are genuinely interested in the job.
Based on your interaction with the interviewers, you may get a good idea of their intellect, passion, and fairness. This extends to the team and company. In addition to knowing your interviewers, you should know about the company vision, history, organization, products, and technology. You should be ready to talk about what specifically appeals to you, and to ask intelligent questions about the company and the job.
Prepare a list of questions in advance; it gets you helpful information as well as shows your knowledge and enthusiasm for the organization. You may also want to think of some concrete ideas around things you could do for the company; be careful not to come across as a pushy know-it-all.
All companies want bright and motivated engineers. However, companies differ greatly in their culture and organization. Here is a brief classification. Startup, e. Such companies do not have time to train new hires, and tend to hire candidates who are very fast learners or are already familiar with their technology stack, e.
Mature consumer-facing company, e. Such companies have a deeper technology stack, much of which is developed in-house. They have the resources and the time to train a new hire. Enterprise-oriented company, e. Government contractor, e. The tool chain and development practices at such companies tend to be very mature. General conversation Often interviewers will ask you questions about your past projects, such as a senior design project or an internship. The point of this conversation is to answer the following questions: Can the candidate clearly communicate a complex idea?
This is one of the most important skills for working in an engineering team. If you have a grand idea to redesign a big system, can you communicate it to your colleagues and bring them on board? It is crucial to practice how you will present your best work. Being precise, clear, and having concrete examples can go a long way here. Candidates communicating in a language that is not their first language, should take extra care to speak slowly and make more use of the whiteboard to augment their words.
We always want our colleagues to be excited, energetic, and inspiring to work with. Hence, when you are asked to describe a project from the past, it is best to pick something that you are passionate about rather than a project that was complex but did not interest you. Is there a potential interest match with some project?
The interviewer may gauge areas of strengths for a potential project match. If you know the requirements of the job, you may want to steer the conversation in that direction. Other advice Be honest: Nobody wants a colleague who falsely claims to have tested code or done a code review.
Dishonesty in an interview is a fast pass to an early exit. Similarly, if you have seen a problem before, you should say so. Be sure that it really is the same problem, and bear in mind you should describe a correct solution quickly if you claim to have solved it before.
Interviewers have been known to collude to ask the same question of a candidate to see if he tells the second interviewer about the first instance. An interviewer may feign ignorance on a topic he knows in depth to see if a candidate pretends to know it.
Keep a positive spirit: A cheerful and optimistic attitude can go a long way. Candidates sometimes apologize in advance for a weak GPA, rusty coding skills, or not knowing the technology stack. Their logic is that by being proactive they will somehow benefit from lowered expectations. Nothing can be further from the truth. It focuses attention on shortcomings.
More generally, if you do not believe in yourself, you cannot expect others to believe in you.
Most software companies have a relaxed dress-code, and new grad- uates may wonder if they will look foolish by overdressing.
The damage done when you are too casual is greater than the minor embarrassment you may feel at being overdressed. It is always a good idea to err on the side of caution and dress formally for your interviews. At the minimum, be clean and well-groomed. Be aware of your body language: Think of a friend or coworker slouched all the time or absentmindedly doing things that may offend others.
Work on your posture, eye contact and handshake, and remember to smile. Keep money and perks out of the interview: Money is a big element in any job but it is best left discussed with the HR division after an offer is made. The same is true for vacation time, day care support, and funding for conference travel.
Strategies For A Great Interview Stress interviews Some companies, primarily in the finance industry, make a practice of having one of the interviewers create a stressful situation for the candidate. The stress may be injected technically, e. The goal is to see how a candidate reacts to such situations—does he fall apart, become belligerent, or get swayed easily. The guidelines in the previous section should help you through a stress interview.
Bear in mind you will not know a priori if a particular interviewer will be conducting a stress interview. Learning from bad outcomes The reality is that not every interview results in a job offer. There are many reasons for not getting a particular job. Some are technical: If this is the case, go back and solve that problem, as well as related problems. You can fail an interview for nontechnical reasons, e. The company may have decided not to hire in your area, or another candidate with similar ability but more relevant experience was hired.
You will not get any feedback from a bad outcome, so it is your responsibility to try and piece together the causes. Negotiating an offer An offer is not an offer till it is on paper, with all the details filled in. All offers are negotiable. When negotiating, remember there is nothing to be gained, and much to lose, by being rude. Being firm is not the same as being rude. To get the best possible offer, get multiple offers, and be flexible about the form of your compensation.
For example, base salary is less flexible than stock options, sign- on bonus, relocation expenses, and Immigration and Naturalization Service INS filing costs. Otherwise the recruiter will simply come back with a small increase in the sign-on bonus and claim to have met your request. Your HR contact is a professional negotiator, whose fiduciary duty is to the com- pany.
This is what recruiters ElementsOfProgrammingInterviews. Strategies For A Great Interview 17 themselves are evaluated on internally. The Wikipedia article on negotiation lays bare many tricks we have seen recruiters employ. One suggestion: If you are asked for something such as a copy of a competing offer , get something in return. Often it is better to bypass the HR contact and speak directly with the hiring manager. At the end of the day, remember your long term career is what counts, and joining a company that has a brighter future social-mobile vs.
In this chapter we review practices that help interviewers identify a top hire. We strongly recommend interviewees read it—knowing what an interviewer is looking for will help you present yourself better and increase the likelihood of a successful outcome.
For someone at the beginning of their career, interviewing may feel like a huge responsibility. Hiring a bad candidate is expensive for the organization, not just because the hire is unproductive, but also because he is a drain on the productivity of his mentors and managers, and sets a bad example.
Firing someone is extremely painful as well as bad for to the morale of the team. On the other hand, discarding good candidates is problematic for a rapidly growing organization. Objective The ultimate goal of any interview is to determine the odds that a candidate will be a successful employee of the company. The ideal candidate is smart, dedicated, articulate, collegial, and gets things done quickly, both as an individual and in a team.
Ideally, your interviews should be designed such that a good candidate scores 1. One mistake, frequently made by novice interviewers, is to be indecisive.
Unless the candidate walks on water or completely disappoints, the interviewer tries not to make a decision and scores the candidate somewhere in the middle. This means that the interview was a wasted effort. A secondary objective of the interview process is to turn the candidate into a brand ambassador for the recruiting organization. Even if a candidate is not a good fit for the organization, he may know others who would be. It is important for the candidate to have an overall positive experience during the process.
Conducting An Interview 19 or insult the candidate over a mistake he made, but such behavior is depressingly common. Outside of a stress interview, the interviewer should work on making the candidate feel positively about the experience, and, by extension, the position and the company. What to ask One important question you should ask yourself as an interviewer is how much training time your work environment allows. For a startup it is important that a new hire is productive from the first week, whereas a larger organization can budget for several months of training.
Consequently, in a startup it is important to test the candidate on the specific technologies that he will use, in addition to his general abilities.
For a larger organization, it is reasonable not to emphasize domain knowledge and instead test candidates on data structures, algorithms, system design skills, and problem solving techniques. The justification for this is as follows.
Algorithms, data structures, and system design underlie all software. It is often hidden in library calls. However, such code is usually the crucial component in terms of performance and correctness, and often serves to differentiate products. Furthermore, platforms and programming languages change quickly but a firm grasp of data structures, algo- rithms, and system design principles, will always be a foundational part of any successful software endeavor.
Finally, many of the most successful software compa- nies have hired based on ability and potential rather than experience or knowledge of specifics, underlying the effectiveness of this approach to selecting candidates. Most big organizations have a structured interview process where designated interviewers are responsible for probing specific areas.
For example, you may be asked to evaluate the candidate on their coding skills, algorithm knowledge, critical thinking, or the ability to design complex systems. This book gives interviewers access to a fairly large collection of problems to choose from. When selecting a problem keep the following in mind: No single point of failure—if you are going to ask just one question, you should not pick a problem where the candidate passes the interview if and only if he gets one particular insight.
The best candidate may miss a simple insight, and a mediocre candidate may stumble across the right idea. There should be at least two or three opportunities for the candidates to redeem themselves. For example, problems that can be solved by dynamic programming can almost always be solved through a greedy algorithm that is fast but suboptimum or a brute-force algorithm that is slow but optimum. In such cases, even if the candidate cannot get the key insight, he can still demonstrate some problem solving abilities.
Problem 6. Multiple possible solutions—if a given problem has multiple solutions, the chances of a good candidate coming up with a solution increases. It also gives the interviewer more freedom to steer the candidate. A great candidate may finish ElementsOfProgrammingInterviews. Conducting An Interview with one solution quickly enough to discuss other approaches and the trade-offs between them.
For example, Problem Cover multiple areas—even if you are responsible for testing the candidate on algorithms, you could easily pick a problem that also exposes some aspects of design and software development.
Calibrate on colleagues—interviewers often have an incorrect notion of how difficult a problem is for a thirty minute or one hour interview. It is a good idea to check the appropriateness of a problem by asking one of your colleagues to solve it and seeing how much difficulty they have with it.
No unnecessary domain knowledge—it is not a good idea to quiz a candidate on advanced graph algorithms if the job does not require it and the candidate does not claim any special knowledge of the field. Conducting the interview Conducting a good interview is akin to juggling. Many things can happen in an interview that could help you reach a decision, so it is important to take notes.
At the same time, it is important to keep a conversation going with the candidate and help him out if he gets stuck. Ideally, have a series of hints worked out beforehand, which can then be provided progressively as needed. Coming up with the right set of hints may require some thinking.
You do not want to give away the problem, yet find a way for the candidate to make progress. Here are situations that may throw you off: A candidate that gets stuck and shuts up: Some candidates get intimidated by the problem, the process, or the interviewer, and just shut up. It is important to put the candidate at ease, e. A verbose candidate: Candidates who go off on tangents and keep on talking without making progress render an interview ineffective.
Again, it is important to take control of the conversation. For example you could assert that a particular path will not make progress. An overconfident candidate: It is common to meet candidates who weaken their case by defending an incorrect answer. To give the candidate a fair chance, it is important to demonstrate to him that he is making a mistake, and allow him to correct it.
Scoring and reporting At the end of an interview, the interviewers usually have a good idea of how the candidate scored. However, it is important to keep notes and revisit them before making a final decision. Whiteboard snapshots and samples of any code that the ElementsOfProgrammingInterviews. Conducting An Interview 21 candidate wrote should also be recorded.
You should standardize scoring based on which hints were given, how many questions the candidate was able to get to, etc. Although isolated minor mistakes can be ignored, sometimes when you look at all the mistakes together, clear signs of weakness in certain areas may emerge, such as a lack of attention to detail and unfamiliarity with a language.
When the right choice is not clear, wait for the next candidate instead of possibly making a bad hiring decision. The litmus test is to see if you would react positively to the candidate replacing a valuable member of your team. Einstein Developing problem solving skills is like learning to play a musical instrument— books and teachers can point you in the right direction, but only your hard work will take you there.
Just as a musician, you need to know underlying concepts, but theory is no substitute for practice. Great problem solvers have skills that cannot be rigorously formalized.
We now introduce several patterns and illustrate them with examples. We have classified these patterns into the following categories: These patterns are summarized in Table 4. Keep in mind that you may have to use more than one of these patterns for a given problem. The two most common criteria for comparing algorithms are runtime and memory usage. We briefly review complexity analysis and intractable problems at the end of this chapter. Data structure patterns A data structure is a particular way of storing and organizing related data items so that they can be manipulated efficiently.
Usually, the correct selection of data structures is key to designing a good algorithm. Different data structures are suited to different applications; some are highly specialized. For example, heaps are par- ticularly well-suited for algorithms that merge sorted data streams, while compiler implementations usually use hash tables to lookup identifiers.
The data structures described in this chapter are the ones commonly used. Other data structures, such as skip lists, treaps, Fibonacci heaps, tries, and disjoint-set data structures, have more specialized applications. Problem Solving Patterns 23 Solutions often require a combination of data structures. For example, tracking the most visited pages on a website involves a combination of a heap, a queue, a binary search tree, and a hash table.
Table 4. Data structure patterns. Data structure Key points Primitive types Know how int, char, double, etc. Arrays Fast access for element at an index, slow lookups un- less sorted and insertions. Be comfortable with no- tions of iteration, resizing, partitioning, merging, etc. Strings Know how strings are represented in memory. Under- stand basic operators such as comparison, copying, matching, joining, splitting, etc.
Lists Understand trade-offs with respect to arrays. Be com- fortable with iteration, insertion, and deletion within singly and doubly linked lists. Know how to imple- ment a list with dynamic allocation, and with arrays. Stacks and queues Understand insertion and deletion.
Know array and linked list implementations. Binary trees Use for representing hierarchical data. Heaps Key benefit: O 1 lookup find-max, O log n insertion, and O log n deletion of max. Node and array repre- sentations.
Min-heap variant. Hash tables Key benefit: O 1 insertions, deletions and lookups. Key disadvantages: Understand implementation using array of buckets and collision chains. Know hash functions for integers, strings, objects. Understand importance of equals function. Variants such as Bloom filters. Binary search trees Key benefit: O log n insertions, deletions, lookups, find-min, find-max, successor, predecessor when tree is balanced.
Understand node fields, pointer imple- mentation. Be familiar with notion of balance, and op- erations maintaining balance. Know how to augment a binary search tree, e. Primitive types You should be comfortable with the basic types chars, integers, doubles, etc. For example, Java has no unsigned integers, and the integer width is compiler- and machine-dependent in C.
Problem Solving Patterns A common problem related to basic types is computing the number of bits set to 1 in an integer-valued variable x. To solve this problem you need to know how to manipulate individual bits in an integer. One straightforward approach is to iteratively test individual bits using an unsigned integer variable m initialized to 1.
Iteratively identify bits of x that are set to 1 by examining the bitwise AND of m with x, shifting m left one bit at a time. The overall complexity is O n where n is the length of the integer. The variable y is 1 at exactly the lowest set bit of x; all other bits in y are 0.
The time complexity is O s , where s is the number of bits set to 1 in x. In practice, if the computation is done repeatedly, the most efficient approach would be to create a lookup table. In this case, we could use a entry integer-valued array P, such that P[i] is the number of bits set to 1 in i. If x is 64 bits, the result can be computed by decomposing x into 4 disjoint bit words, h3, h2, h1, and h0.
The bit words are computed using bitmasks and shifting, e. Array lookup and insertion are fast, making arrays suitable for a variety of applications. Reading past the last element of an array is a common error, invariably with catastrophic consequences.
The following problem arises when optimizing quicksort: The key to the solution is to maintain two regions on opposite sides of the array that meet the requirements, and expand these regions one element at a time.
Strings A string can be viewed as a special kind of array, namely one made out of charac- ters. We treat strings separately from arrays because certain operations which are commonly applied to strings—for example, comparison, joining, splitting, searching for substrings, replacing one string by another, parsing, etc.
Our solution to the look-and-say problem illustrates operations on strings. The look-and-say sequence begins with 1; the subsequent integers describe the dig- its appearing in the previous number in the sequence.
The first eight integers in the look-and-say sequence are h1, 11, 21, , , , , i. Problem Solving Patterns 25 The look-and-say problem entails computing the n-th integer in this sequence. Al- though the problem is cast in terms of integers, the string representation is far more convenient for counting digits.
Lists An abstract data type ADT is a mathematical model for a class of data structures that have similar functionality. Strictly speaking, a list is an ADT, and not a data structure. It implements an ordered collection of values, which may include repetitions. In the context of this book we view a list as a sequence of nodes where each node has a link to the next node in the sequence. In a doubly linked list each node also has a link to the prior node. A list is similar to an array in that it contains objects in a linear order.
The key differences are that inserting and deleting elements in a list has time complexity O 1. On the other hand, obtaining the k-th element in a list is expensive, having O n time complexity. Lists are usually building blocks of more complex data structures. However, they can be the subject of tricky problems in their own right, as illustrated by the following: Given a singly linked list hl0 , l1 , l2 ,.
Suppose you were asked to write a function that computes the zip of a list, with the constraint that it uses O 1 space. The operation of this function is illustrated in Figure 4. L l0 l1 l2 l3 l4 0x 0x 0x 0x 0x a List before zipping.
The number in hex below each node represents its address in memory. L l0 l4 l1 l3 l2 0x 0x 0x 0x 0x b List after zipping. Note that nodes are reused—no memory has been allocated. Figure 4. Zipping a list. Stacks and queues Stacks support last-in, first-out semantics for inserts and deletes, whereas queues are first-in, first-out. Both are ADTs, and are commonly implemented using linked lists or arrays.
Similar to lists, stacks and queues are usually building blocks in a solution to a complex problem, but can make for interesting problems in their own right. As an example consider the problem of evaluating Reverse Polish notation expres- sions, i. A stack is ideal for this purpose—operands are pushed on the stack, and popped as operators are processed, with intermediate results being pushed back onto the stack.
Problem Solving Patterns Binary trees A binary tree is a data structure that is used to represent hierarchical relationships. Binary trees are the subject of Chapter Binary trees most commonly occur in the context of binary search trees, wherein keys are stored in a sorted fashion. However, there are many other applications of binary trees. Consider a set of resources orga- nized as nodes in a binary tree.
Processes need to lock resource nodes. A node may be locked if and only if none of its descendants and ancestors are locked. Your task is to design and implement an application programming interface API for locking. Naively implemented, the time complexity for these methods is O n , where n is the number of nodes. However, these can be made to run in time O 1 , O h , and O h , respectively, where h is the height of the tree, if nodes have a parent field.
Heaps A heap is a data structure based on a binary tree. It efficiently implements an ADT called a priority queue. A priority queue resembles a queue, with one difference: Each trade appears as a separate line containing information about that trade.
Lines begin with an integer-valued timestamp, and lines within a file are sorted in increasing order of timestamp. Suppose you were asked to design an algorithm that combines the set of files into a single file R in which trades are sorted by timestamp. This problem can be solved by a multistage merge process, but there is a trivial solution based on a min-heap data structure. Entries are trade-file pairs and are ordered by the timestamp of the trade.
Initially, the min-heap contains the first trade from each file. Hash tables A hash table is a data structure used to store keys, optionally, with corresponding values. Inserts, deletes and lookups run in O 1 time on average. One caveat is that these operations require a good hash function—a mapping from the set of all possible keys to the integers which is similar to a uniform random assignment.
Another caveat is that if the number of keys that is to be stored is not known in advance then the hash table needs to be periodically resized, which, depending on how the resizing is implemented, can lead to some updates having O n complexity. Suppose you were asked to write a function which takes a string s as input, and returns true if the characters in s can be permuted to form a string that is palindromic, i.
Working through examples, you should see that a string is palindromic ElementsOfProgrammingInterviews. Problem Solving Patterns 27 if and only if each character appears an even number of times, with possibly a single exception, since this allows for pairing characters in the first and second halves.
A hash table makes performing this test trivial. We build a hash table H whose keys are characters, and corresponding values are the number of occurrences for that character.
The hash table H is created with a single pass over the string. After computing the number of occurrences, we iterate over the key-value pairs in H. If more than one character has an odd count, we return false; otherwise, we return true.
Suppose you were asked to write an application that compares n programs for plagiarism. Specifically, your application is to break every program into overlapping character strings, each of length , and report on the number of strings that appear in each pair of programs. A hash table can be used to perform this check very efficiently if the right hash function is used. Binary search trees Binary search trees BSTs are used to store objects that are comparable. BSTs are the subject of Chapter The underlying idea is to organize the objects in a binary tree in which the nodes satisfy the BST property on Page Insertion and deletion can be implemented so that the height of the BST is O log n , leading to fast O log n lookup and update times.
AVL trees and red-black trees are BST implementations that support this form of insertion and deletion. BSTs are a workhorse of data structures and can be used to solve almost every data structures problem reasonably efficiently. It is common to augment the BST to make it possible to manipulate more complicated data, e.
As an example application of BSTs, consider the following problem. You are given a set of line segments. Each segment is a closed interval [li , ri ] of the x-axis, a color, and a height.
For simplicity assume no two segments whose intervals overlap have the same height. When the x-axis is viewed from above the color at point x on the x-axis is the color of the highest segment that includes x.
If no segment contains x, the color is blank. You are to implement a function that computes the sequence of colors as seen from the top. The key idea is to sort the endpoints of the line segments and do a sweep from left-to-right. As we do the sweep, we maintain a list of line segments that intersect the current position as well as the highest line and its color. Algorithm design patterns An algorithm is a step-by-step procedure for performing a calculation.