-2

About two months ago, I was interviewed by a developer from a start-up company and he asked me to write C++ code for a straight-forward problem (Given an array of integers, return the prime numbers in the array) on an online IDE. I hadn't seen this exact question before but after some thinking, I wrote code which I believe had the correct approach overall but also some major shortcomings. The code threw compilation errors when I hit "Run" and the interviewer allowed me to look online to fix any issues with the syntax. However, I could not write code which ran in the allotted time. Minutes after the interview ended, I saw mistakes in my code, fixed them, got the correct output and sent my interviewer an email with the corrected code. I was optimistic despite not being able to produce runnable code during the interview because my code logic was somewhat correct. Unfortunately though, a week or so later, I got a rejection email from him.

I have read and heard several times that the code we write during interviews does not have to be perfect. Hence, I was slightly optimistic I would proceed to the next round in this interview because I (felt) I demonstrated evidence of algorithmic thinking. I figured they would see the mistakes I made as the result of interview nerves. But so far, this hasn't been the case. I failed a few more interviews since this one in a similar fashion.

I understand every employer is different and their circumstances also keep changing (They may even hire a candidate without a technical interview). But most interviews have a coding component and I want to be consistently successful in writing code in these interviews. What can I do to ensure I succeed more often than not in typical coding interviews?

2
  • 1
    Comments are not for extended discussion; this conversation has been moved to chat.
    – Lilienthal
    Mar 29 at 21:36
  • 1
    the usual answer is simply "spend 100 hours doing those silly online coding prep tests"
    – Fattie
    May 17 at 17:54
6

If you were interviewing me and I wrote code like the one above, would you also reject me? If you would, please tell me why.

Your question is absolutely nonsensical.

You're taking rejection way too personally. If someone rejects you, it's usually because they found someone else who (in their mind) could do the job better than you (either that or they liked them better for some other reason).

Come on. Just put yourself in their shoes. If you had to choose between two top candidates. Candidate J makes 5 minor errors and completes the problem in 20 minutes. Candidate E (the 5th person you've personally interviewed) makes 3 minor errors and completes the problem in 15 minutes. Which one would you contact first to make a tentative job offer?

Do you see what I'm getting at? Even if your performance had been flawless, they could still have hired someone else. And the reverse can also be true. Even if your performance had been absolutely awful, they could still have hired you if no one else better had interviewed for the job.

This brings me to the next topics which are much more important in my opinion:

  1. Use the hidden job market, in addition to the open job market. And if you don't know what the "hidden job market" is, please google it.

  2. It's a numbers game. Do not stop applying. Rejection is part of the game. Everyone goes through this. Also, the more you interview, the better you get at it. With that said, as one commenter pointed out, I'm not suggesting you mindlessly spam your job application to every employer you find. There is a strategy for applying to jobs. There is also a strategy to be used for coding interviews. Every day, you need to iteratively improve on those strategies.

  3. Gauge your competition. Use http://pramp.com to practice mock technical interviews with other job-hunters. This gives you practice both as an interviewee and as an interviewer, and you get to see how good your competition compares to you.

  4. If you're willing to put in the work, you can reduce the number of logical errors and syntax errors when you're whiteboarding (and even when you're coding). There are excellent techniques for doing that. I can tell you about them if you're interested. But the last time I included such techniques unprompted into one of my answers, my answer got downvoted into oblivion.

EDIT: As requested, here is my list:

  • When practicing coding problems, get in the habit of not pressing the run button unless you're sure the code is going to run as intended. To do that, you need to mentally step through the code with one or more test cases that exercise all the branches of your code at least once.

  • During interviews, you need to take this idea a couple of steps further:

    • Do not write code until you've first written a test case down and mentally stepped through the logic of your pseudo-code with that test case.
    • Do not even start writing pseudo-code until you've first mentally stepped through the logic of a diagram first (during remote interviews, drawing a diagram may be more challenging. So obviously, work within the limits of the tools available to you).
    • In fact, do not start with pseudo-code until you've written the test cases exercising all the edge cases you could first think of (it's ok if you don't think of all of them initially). State your assumptions as well. In fact, ask the interviewer for permission to start writing your pseudo-code (or at least, watch their body language and tone to see if they're on board with you proceeding with the next step).
    • Get into the habit of verbalizing your thinking while diagraming, verbalizing your thinking while writing test cases, verbalizing your thinking while writing pseudo-code, and verbalizing your thinking while writing actual code. Talking and explaining at the same time is not easy. For most people, it's a skill that needs to be learned. Use http://pramp.com to develop that skill or practice coding interviews with your friends.
    • Simulate the environment of your coding interviews as much as you can. If a problem is supposed to x minutes to solve during an interview. Practice that problem with a time limit of half that time. With that said, don't use that time limit as an excuse to stop doing a tough problem, if you haven't finished it yet (but conversely, don't waste more than 30 minutes on a tough problem that you can't seem to move forward on).
    • And yes, writing good test cases is an art. The test cases can't be too long and can't be too numerous, but at the same time, if they're too short or if they're missing edge cases, they're not going to exercise all the branches of the code either.
    • If all goes well, writing the code will only take a tiny amount of time of your overall coding interview, and you will have used most of your time restating the question in your own words, drawing a diagram, communicating with your interviewer, finding edge cases, stating your assumptions, stepping mentally through your logic, writing pseudo-code, and stepping mentally through your pseudo-code.
    • And yes, as a final sanity check, you'll need to step mentally through your actual code before you say you're done. I know this is annoying to do, but this can be done and this habit can be cultivated. Focus on the process, not the outcome. The outcome will work itself out if you do the process well enough.
  • With that said, writing code that is syntactically correct, idiomatically correct, and compiles the first time you write it is important also. To do that, you need to use spaced repetition

    • And before you say, I can't memorize everything, or I don't want to memorize everything. Memorizing everything is idiotic. That's fine. I'm not asking you to memorize everything. In fact, spaced repetition is best used on only the mistakes you've already made, or only on the same information you've googled multiple times already.
    • And note that spaced repetition is only one component of the solution. I'm not saying it replaces everything else you have to do. You will still need to practice coding problems. There is no substitute for actual practice. There is also no substitute for actually understanding something before you actually memorize it. And I'm not suggesting you will be able to memorize everything, spaced repetition is especially good for memorizing atomic information, not lists of information. And for learning conceptual information, mind maps or spider diagrams will be more relevant than using spaced repetition.
    • And before you start making too many flashcards for yourself, please read this very important article, written by the original creator of Supermemo (the application that inspired Anki).

Now if one year from now, you found my suggestions somewhat useful and actually implementable in your own job hunt/career, please come back here, and tell me about it. I have more advice to give, but unfortunately, it won't make much sense to you unless you've actually implemented those initial recommendations in the first place. Plus, I'm actually lazy and cynical, and I don't want to expend too much energy on generating too many suggestions if I'm not sure that the person I'm talking to has already implemented those previous suggestions in the first place.

13
  • Thank you for the thoughtful response. I was not too concerned about this rejection. I became worried after I got rejected on two more occasions in similar interview situations. This led me to think that I may be doing something wrong and I should promptly address those flaws to do better in the subsequent interviews.
    – a_sid
    Mar 27 at 16:51
  • 1
    Please don't just spam applications. It's not going to help you but it's going to waste everyone else's time too.
    – ojs
    Mar 27 at 23:06
  • 1
    @a_sid, I've added them. Mar 28 at 6:09
  • 1
    @ojs, I've amended my original answer and clarified my point on that issue. Spamming is counterproductive. I completely agree. Mar 28 at 6:11
  • 1
    @a_sid, Yes, that's true as well. There are many nuances to this question. Also, this may even depend on the type of question it is. For instance, if your goal is to get a job and you have a limited timeframe, if you find yourself struggling with a difficult question that is kind of obscure and less frequent in job interviews, it may be worth it for you to move on and focus on something else. Jun 3 at 20:36
12

No one is going to hire you if they put you in front of a computer and you write code that doesn't compile.

I tried to run this flawed code and it did not even compile.

You couldn't get a very straight-forward piece of code to compile (you needed a main, input[i]%1 always equals 0, among other things).

The questions were different but the programs I wrote had similar problems: syntax errors, segmentation faults, flaws in logic and no arrangements in the code for handling corner cases.

How do you know it has segmentation faults and logic bugs if it doesn't compile? I've always been asked to code during an interview to make sure I didn't just talk a big game and drop buzzwords.

I was given about 45 minutes. I may have spent 15 minutes just fixing compilation errors.

This is very slow. The fact it took you 15 minutes to fix compile errors means either 1) You are not familiar with syntax at all 2) You wrote a lot of code without compiling. Compile early and often.

Interviews are stressful, that won't change. What can change is your reaction. Go to leetcode and other interview prep websites. Download the questions and write full, running programs for them locally. Practice not being panicked, stressed or flustered. Get friends to play the role of the interviewer. Talk to a therapist about ways to manage interview stress.

Some companies will "white-board" you (i.e. make you write pseudo-code on a white-board). Others will give you a take-home coding exam. If you feel either of those would be better for you, seek out those companies.

Some programmers are not good with on-the-spot coding, mainly for the reasons you mention. This is a separate skill than actual programming, and practicing can help both up your skill level and calm nerves.

EDIT - Hang in there

Getting a new job is as much about perseverance as technical skills. I've flunked a phone interview because I screwed up an easy algorithm, and spent several hours completing their "coding challenge" only to find out "I'm not the right cultural fit."

Especially during COVID-19, your job-search may take a while. Keep looking. Keep practicing, ask for feedback from your interviewers. Most of all, take time to recharge, and keep searching.

8
  • Thank you for the response. You couldn't get a very straight-forward piece of code to compile (you needed a main function). There was a main function in the code I had written during the interview. Thankfully, I know that :)
    – a_sid
    Mar 26 at 21:57
  • 1
    No one is going to hire you if they put you in front of a computer and you write code that doesn't compile. Some people are even okay with pseudo-code
    – a_sid
    Mar 26 at 22:00
  • @a_sid - yes they are. Modified question to reflect that. Either way, I think your best bet is to get more comfortable with on-the-spot coding. It's a separate skill, and a lot of people aren't good at it. Mar 26 at 22:05
  • 4
    Don't be discouraged, the World is full of opportunities, some of them you're not supposed to take. Just keep trying, eventually everything comes together at the same time
    – Kilisi
    Mar 26 at 22:53
  • 2
    @a_sid - so you're practicing for white-board interviews. Find companies that use that strategy or start practicing with a computer. You've been on interviews where practicing this way hurt you. FWIW most of my interviews in the last 2 years have been on a computer - YMMV. Mar 27 at 1:35
11

I was given about 45 minutes. I may have spent 15 minutes just fixing compilation errors.

That's very slow. Judging from the quality of your code, I'd have guessed 5 minutes ...

In 45 minutes, an experienced software developer would write a near production quality implementation (compiling, readable, mostly correct, i.e. bugs only in corner cases).

So either you lack practice, or you were so nervous that your brain seized up and made you operate at a small fraction of your usual intellectual capacity. Since you were able to markedly improve your submission in mere minutes after the interview ended, the latter seems very possible. To find out, try solving the exercise again in less stressful circumstances, and compare how far you get.

In either case though, the best solution is to practice your coding skills. That will improve your skills, and also make you more confident about them. Imaging sitting in an interview and thinking: Wow, what an easy task! I solved something far harder just this morning! Could you still be nervous then? Nope. You'd be relaxed, and able able to focus on the task at hand, because you know that your worries are baseless.

In addition to the speed, the following jumped out at me:

  • Your formatting is very inconsistent when it comes to whitespace, making it harder than necessary to see the structure of the code, and hinting that you are not accustomed to following a coding standard or used to working with automatic code formatters, indicating that you haven't done a lot of coding with professional tools.
  • Your code is not particularly readable. Everything is in the same function, variables names are not descriptive.
  • The input[i]%1 part has me really puzzled. Even after minutes I can't guess what you were trying to do here. Also, it's so obviously nonsensical and redundant that the only way I can explain the existence of that condition is you trying stuff at random. Professionals don't do that. They have an idea what could be wrong, and a methodical approach to solving problems.
  • There are several severe logic bugs, i.e. conditions that never work as intended. So many logic bugs indicate a lack of familiarity with the control flow constructs of the language.

Overall, it doesn't show the skills a professional programmer should bring to the table. The interviewer can't know that you have skills if you can't show them.

So practice your skills. And practice showing them. And your next interview will be easier.

8
  • Thank you for the elaborate answer. The input[i]%1 part was put in place because my nested loop is starting from an index of zero. My nested loop should have started at the index of 2. Unfortunately, this occurred to me AFTER the interview ended.
    – a_sid
    Mar 26 at 23:35
  • 3
    It still doesn't make sense. Every number, if divided by 1, will have a remainder of 0. And besides, it doesn't even use j, so this condition can not possibly compensate for a wrong loop start. So you really have me mystified there.
    – meriton
    Mar 26 at 23:40
  • You are right......
    – a_sid
    Mar 27 at 0:38
  • I understand your comment about logic bugs but not your comments about indentation and readability. May I know how it should be written with respect to indentation and readability.
    – a_sid
    Mar 27 at 0:59
  • 1
    @s_sid - You had to Google syntax errors. What level of programming was this job for? The fact this was a startup sounds like they were looking for more experience
    – Donald
    Mar 27 at 12:29
4

Were you interviewing for a job as a C++ developer or for a job that would routinely require you to write or work on C++ code? If so, you should be able to quickly produce simple pieces of C++ code that compile and run when sat in front of a compiler.

If you weren't interviewing for a C++ position or a position that requires you to be comfortable with C++ code, it's not really fair to ask you to produce working C++ code in a few minutes. It would be unreasonable to reject someone who didn't claim C++ competence.

But if you claimed C++ competence or were interviewing for a position that requires you to write C++ code, this is just really bad.

Some comments:

vector<int> findPrime(int[] input, int size){
  vector<int> output;

I hope you explicitly declared you're using std::vector and didn't put a using namespace std; or just assume that this would work without having to specify what vector you're using. Importing the entire std namespace is a terrible practice. You can find numerous questions on stackoverflow about it.

  for (int i= 0; i < size; i++){
     for (int j= 0; j < input[i]; j++){
       if(input[i]%1== 0 && input[i]%j == 0){

Why does j start at zero? What is the purpose of testing input[i]%0? And since j also passes though 1, why are we testing if input[i]%1==0 each time through the loop?

Heck, why are we testing against one at all?! Every positive integer is evenly divisible by one. This worries me because it suggests the candidate learned to use % as some magic way to test divisibility and doesn't really understand what it's doing and so "sprinkles it around" without understanding its purpose and function.

         continue;
       }
       if (i== j){
          output.push_back(input[i]);

I'm not super-happy to see the test if i is equivalent to j. I'd much prefer to see some boolean that keeps track of whether the value is prime or not. It's needlessly hard to see that this does the right thing.

Also, there is no reason j should go all the way to input[i] in the first place. And there's no reason to test every even number after you've tested 2. I would expect someone interviewing for a C++ developer position to implement at least some of the very well-known trivial optimizations to testing primality.

       }
     }
  }
  return output;
}

But the biggest red flag is that you weren't able to get the code to compiler successfully. How can you get a job that requires you to write C++ code if you can't write C++ code that compiles? Are you expecting the employer to each you enough C++ to get code that actually compiles? If you can't get code to compile, how could you have developed debugging skills? Is your employer supposed to teach you that too?

8
  • Thank you for the detailed response. I do not expect to be taught anything. This is the solution I came up with during the interview and unfortunately, I realized the silliness of my solution after the interview ended.
    – a_sid
    Mar 27 at 23:20
  • I claim to know C++ but I am mostly writing code on an IDE like Visual Studio. Visual Studio highlights any syntax errors which I can fix right away. If there are logical errors which I overlooked while coding, I debug them using breakpoints. Hence, I am guilty of being careless towards the nuances of the language. When I am practicing data structures and algorithms questions during the interview, I am more focused on the solution methodology than the syntax. This proved costly during the interview.
    – a_sid
    Mar 27 at 23:26
  • @a_sid Everyone blows an interview or has a bad day every once in a while. If this doesn't reflect on your abilities, then accept that you blew one opportunity because you had a bad day and move on. I'm sympathetic to the point that you develop in a particular environment and can easily get thrown if forced to use a different environment. That would really concern me for someone with several years of professional experience though. I would consider that normal for someone more junior. Mar 27 at 23:26
  • When I posted this question, I had failed two more interviews of the same style. This led me to think about what I am doing wrong and how correct I should be during a coding interview.
    – a_sid
    Mar 27 at 23:29
  • 1
    @a_sid Then I think you'll have to practice until you can succeed at that kind of test. Mar 27 at 23:37
3

A lot of other answers are going over the various problems with your solution. I'd like to focus my answer on how to approach coding from a better angle - let me discuss why I would frown at hiring you from the code sample you provided.

vector<int> findPrime(int[] input, int size){
  vector<int> output;

  for (int i= 0; i < size; i++){
     for (int j= 0; j < input[i]; j++){
       if(input[i]%1== 0 && input[i]%j == 0){
          continue;
       }
       if (i== j){
          output.push_back(input[i]);
       }
     }
   }
  return output;
}

Okay, so let's start at the top: your function name: 'findPrime'. Does this function find a prime? No, it finds all the primes in a list. Your function name isn't merely bad, it's downright lying. Seeing the name, I'd expect it to find a prime number, or failing that, to check whether a given number is prime. I certainly wouldn't expect it to pass back a filtered output based on which input numbers were prime!

  • So element number one you need to keep in mind: Making sure you name your functions something that accurately describes what they do.

Next up, and related to that first element: your variable names. Take a look at your variable names: input, size, output, i, and j. Input and Output aren't terrible, but why 'size'? Why not 'inputSize' or 'inputArrayLength' or something that actually describes what data it holds? Likewise, you shouldn't be using single-letter loop counters if the loop is more than 1-2 lines long.

And that actually comes back to bite you! This error was pointed out in a few answers:

if (i== j){

But this mistake isn't easy to spot. The reason it's not easy to spot is because you used useless variable names, so it's not immediately obvious there's a problem here. But what if I changed your code to:

for (int arraySlotNum= 0; arraySlotNum < inputArrayLen; arraySlotNum++){
  int valueToCheck = input[arraySlotNum];
  for (int divisorToTry= 0; divisorToTry < valueToCheck; divisorToTry++){
    if(valueToCheck%divisorToTry == 0){
      continue;
    }
    if (arraySlotNum== divisorToTry){
      output.push_back(valueToCheck);
    }
  }
}

... suddenly, that particular bug seems a bit more obvious - why would you be comparing the divisorToTry with the arraySlot? The other bugs become a bit more noticeable as well.

Also notice: I added a variable that you didn't have. Technically, I could've put 'input[arraySlotNum]' whereever I would've put 'valueToCheck'... but by adding that variable, I helped document what my code is doing.

  • So Element #2 is... actually use good variable names. I'd suggest getting into the practice of not using single-name variables at all until you've formed a good habit of using appropriate variable names. It's not gonna hurt you to use a longer variable name. And you've seen that it can definitely hurt you if you don't!

Third, your function composition - your code architecture. What does your function, as-intended (not necessarily as-written), do?

  • it loops through the collection of elements
  • for each number, it begins a second loop from 2 to the value-1, and gets a modulo.
  • if the number divides cleanly, it adds it to the output

... here's the problem: you've got code in this function that determines whether a number if prime or not. Don't you think that deserves its own function?

This is NOT a minor point. If I had two candidates, one who wrote:

vector<int> filterForPrimes(int[] input, int size)
{
    for (int i=0; i < size; i++)
    {
        // code for correctly determining whether input[i] is prime embedded inline
        // add to output if prime
    }
}

... vs the second who wrote ...

vector<int> filterForPrimes(int[] input, int size)
{
    for (int i=0; i < size; i++)
    {
        if (isPrime(input[i]))
        {
            // add to output
        }
    }
}
bool isPrime(int numberToTest)
{
    // terribly inefficient method of checking for a prime goes here.
}

... I'd rather have the second applicant. Oh, sure, the method for checking a prime number sucks. But it shows that they've got the ability to actually structure their code appropriately - and it means that their codebase is likely going to be much easier to work with and improve.

I mean, let's say the boss screams "The prime checking is too slow! Use the Sieve of Eratosthenes algorithm on it!" All I have to do in the second example is look at the isPrime and optimize it so that, given an input value, it quickly determines whether it's prime. In the first example, I have to consider how all the code I'm changing affects everything else in the function its embedded within.

  • So element number three you need to keep in mind: spend some time trying to figure out how to break things into nice clean functions. Remember SRP (Single Responsibility Principle). Read Clean Code by Robert Martin (or reread; this is the sort of book that programmers should re-read every year or two.)
2
  • Thank you for the thorough review :)
    – a_sid
    Mar 28 at 6:47
  • This is a great answer, and should be required reading for everyone that claims stuff like "programming tests do nothing but test if you remember some trivia from algorithms class, or grade school math". Mar 29 at 23:53
1

Would I reject you? Maybe. This comes close to being a code review question and answer, but I’m going to go with it anyway...

If I am interviewing and and have a code writing question, and am not accepting pseudo-code, I would provide the standard environment and I would then expect the final submission to compile.

So, non-compiling code would eliminate you if I was interviewing you.

Secondly, and this is the part that comes close to being an code review answer, your task is (a) iterate over an array, (b) test for primeness, (c) return vector of identified primes.

As an interviewer I would like some clarification questions (is 1 a prime, are negative numbers prime).

Other than that, what I would be looking for is a function bool is_prime(int n), everything else is just boilerplate around that test. It should be isolated because it is a core question and to make it easily testable.

If you wrote a complete and correct functioning version, I wouldn’t exclude you for not using a function, but since you didn’t...if you and your clone applied and the code compiled, and your clone used a function, I would exclude you but not your clone, even though neither functioned correctly.

2
  • Thank you for responding to my post :)
    – a_sid
    Mar 29 at 6:23
  • @a_sid: I would suggest writing the function and submitting it to codereview.stackexchange.com , not just because you might face this question in the future, but so you can get some feed back on how you solve the problem.
    – jmoreno
    Mar 29 at 11:37
1

Your only real option is to work harder.

You want to get into a good C++ coding job, you've seen in the interveiw what is required to get a job like that, you identified the gap; it's time to focus and work hard to close that gap.

A failed interview is a great opportunity to learn and understand the market. You are now one step closer.

You said the interview was two months ago, but you asked the question yesterday. In two months you can read several books, write thousands of lines of code and watch tutorials every day/night.

Somebody out there right now is doing exactly this. She/he will get the job next time.

Don't think too much about the failed interview, understand where you need to improve and move on.

Even if someone hires you with flawed code (maybe because of other skills you have), they will expect you to improve your code later, so you have to do the learning work anyway otherwise your coding future will be not so bright.

Not the answer you're looking for? Browse other questions tagged .