90

One particular problem that gets posed a fair amount in interviews for software development positions is how to reverse a string.

On the surface, this seems like a very straight-forward and fairly simple question. However, it's not: the solution depends on the encoding of the string, how you want to deal with grapheme clusters, and what input is valid and isn't valid. Ultimately it depends very much on what you want to do with the reversed string.

This is a very well-known example, and there are many such situations where seemingly straight-forward questions turn out not be straight-forward at all on further reflection.

I'm afraid that when I ask too deeply for such a test in an interview, I might be written off as somebody who makes simple things needlessly complicated, or come across as pedantic of the "well, actually..." kind.

If the complexity was overlooked by the interviewer, I will also take way too long to answer. OTOH, if I don't go in to those things, I'll be giving a solution that I know to be wrong, and may be perceived to lack depth and lack the ability to identify real complexities.

What is a good way to deal with such questions?

Note: the solution to the task isn't the problem here, it's the interview technique.

4
  • 6
    I suspect that the best way to handle this depends on the level of the position that you're interviewing for. If it's a junior programmer position, then a fairly simple-minded solution (for the string reverse question) that works on BMP characters is probably fine. If it's a senior position, they're probably more concerned with knowing that you're aware of the edge cases, and you'd be expected to demonstrate that you know about all the Unicode-related gotchas. May 31, 2015 at 4:20
  • 1
    In one interview, I was asked a question that I felt was being used as a trivia question. To determine how to answer it, I asked "do you want the standard interview answer to this or do you really want to do this?" While sounding somewhat like a jerk, it was actually a problem that I had to solve at a previous job.
    – Tangurena
    Sep 15, 2022 at 15:09
  • At the very least, if you just reverse the bytes in a string make sure you tell them first "I'm just reversing the bytes; that is only valid in a single byte encoding, and not in UTF-8".
    – gnasher729
    Sep 16, 2022 at 12:52
  • A job interview is one of the few occasions in life where seeming like a know-it-all is good.
    – Stuart F
    Sep 23, 2022 at 10:18

12 Answers 12

129

It's not uncommon, in my experience, for problem statements in interviews to deliberately leave some details unspecified. One of the things we're looking for when we do that is how a candidate reacts. Good outcomes are either asking for clarification or stating assumptions up front; a poor outcome is seeming to not consider it.

You don't want to ask zillions of clarifying questions right out of the gate; as you suggest, that could come across wrong. So the first thing to do is to prioritize your questions. Decide which are questions you need to ask about and which are things you can assume away (explicitly).

In your case, it sounds like you want to ask about the encoding (that really matters to how you approach the problem): "How is the string encoded, or should this handle all encodings?" (Note what you did there, offering a more-thorough solution but giving them the chance to say "no, don't bother with that".)

The range of inputs, on the other hand, could be something you just explain as you go. "I'll check for a null input here", "I'm assuming no unicode right now", etc -- whatever your constraints are. By doing this you demonstrate that you know about these concerns, and if the interviewer cares they will ask followup questions ("ok, now it needs to do emoji too; how do you handle that?").

You are probably also simplifying or assuming away other parts of the problem too; this should be part of that. For example, I've had candidates handwave error-handling -- catch the exception and then just say "handle it" if exception-handling isn't the point of the problem, for example. Nobody expects you to write production code on a whiteboard in an interview, but they do expect you to understand what the important factors are that affect how you'd write that code.

15
  • 9
    I completely agree; I intentionally ask questions like these which can be answered many different ways, and at different levels of abstraction. It helps me see how the interviewee approaches programming. I.e., as a "coder", or as an "engineer"?
    – senior-dev
    May 27, 2015 at 23:33
  • 5
    to go off that tangent, what is the difference between a "coder" and an "engineer"?
    – Martijn
    May 28, 2015 at 10:07
  • 4
    @Martijn I'd expect that coder is just someone that mashes together something that works for their test cases, but fails miserably for scenarios that actually make sense, but he just didn't think of (like the old school unix hackers). Engineer is someone who takes responsibility for their work - no matter whether it's a bridge engineer or a software engineer. For me, the main difference is the responsibility, and focus on the consumer, rather than just keeping to-the-spec (or "whatever'd suit me").
    – Luaan
    May 28, 2015 at 10:23
  • 15
    "ok, now it needs to do emoji too; how do you handle that?" - You sir are evil.
    – Zibbobz
    May 28, 2015 at 13:18
  • 9
    "I'm assuming ASCII here. For full unicode this problem is much more complicated, but that might be out of the scope of this question". That's probably the crux.
    – Martijn
    May 29, 2015 at 8:57
46

These questions exist to weed out programmers who can't program. You don't actually need to implement the perfect solution, you only need to display the fact that you know the solution to the problem. Give the simple, straightforward answer first. If you need to take special conditions into account that the question didn't specify, just assume one you're comfortable with like

Well, assuming the string came in encoding X, I would first...

This is most likely what they want to see. I mean, if they present the problem as simple, they probably expect a simple answer.

And then after giving the simple answer you can branch off and talk about some of the secondary concerns you would need to take into consideration in order to ensure you have an ideal solution. By talking about these concerns it shows that you have a deep technical understanding as a bonus to passing the test.

1
  • 5
    Indeed, though I would caution against too much pedantry. I mean, almost every language has a string reversal function; interviewers aren't asking this question because they want to know how to reverse a string. If it seems as though you don't get that implied bit of the question, that can cause concerns about communication. "Do I need to spell everything out for this guy/gal?"
    – Telastyn
    May 28, 2015 at 13:04
15

Lead with the simple answer then ask specifics.

It sounds like you already know how to reverse a simple string, and you're getting hung up on edge case possibilities, where an interviewer just wants to measure your capabilities with coding.

Lead with an explanation of how to do it without any issues (I assume you already have one in mind), then get into the issues that could arise, and how you would solve each one.


This is all interview-specific though. In the actual workplace, these are details you definitely want to hammer out before coming up with an answer. This isn't being pedantic - this is what you are paid for. You have to know those edge cases that could cause problems.

In your specific case, familiarity with the application would help, as would some user input on what type of strings you're expecting. Both are useful in coming up with an answer, but in any other case, if the user can't give you a specific answer, assume the worst and plan to handle it.

In the actual workplace, in programming especially, you're expected to be able to figure out those edge-cases on your own and accommodate for them. You won't always have the luxury of being told what to expect, but in an interview, you can lead by giving a simple explanation, then show them that you do know what to expect. This shows that you can get the immediate task done, and that you can plan for contingencies (even to those who don't actually understand code).

1
  • What I would add to this is - tell them at the start what assumptions you are making. So say "I'm assuming that we are only dealing with 8 bit characters and the string is zero terminated". Then go on with the simple example. Sep 16, 2022 at 16:46
13

Oh maaaan, a fun-dunk question and I was busy feeding squirrels.

Nuts.

Always give the simplest answer you can. Let me expand with some few cents here.

In your example scenario, you would give a programming function that, on receiving a string, returns a reversed string. You would "assume away" any and all issues that make you write a single function call more. In Java, you could even answer someString.reverse()1.

For a non-programming example, if asked "tell me about yourself", you would give an answer that roughly takes 1-2 minutes and doesn't cover your entire life's history, but rather the simplest (really, the most pertinent) stories to paint a picture of who you are.

Typically the interviewer will use a question to springboard into another question, or they will ask you to expand a bit more on areas they are interested in. This gives the interview an organic feel, and lets them build up to a more complicated question without freaking a candidate out by asking a tough question right off the bat.

What you don't want to do is try to guess where the interviewer is going - unless you being hired to be a psychic. It is better to give a broad answer (coincidentally also the simplest answer), and let them focus on some areas for expansion. This helps the interviewer stay on target, and stops you from driving the interview. Interviewers don't like it when candidates try to drive the interview, if only because they want to have the same question/answer set to gauge all candidates fairly.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

1. Ok, you cannot actually write that - as others have pointed out. You'd want (nerd alert) new StringBuilder(someString).reverse().toString(); ~ But to me, that was too tech for a generic all-professional-types forum like this. So i took some creative liberties and shortened it. The overall point - give the simplest - is what I want to get across.

10
  • 4
    In Java, you could even answer someString.reverse(). Especially if you've looked this up in the API documentation and ascertained that java.lang.String has a reverse() method. Otherwise, your interviewer might not be too impressed after all.
    – Atsby
    May 28, 2015 at 3:02
  • 2
    @Atsby Not to mention that even if there was such a method, it would very likely only work for certain kinds of reversals. Do you want to reverse char-by-char? Codepoint-by-codepoint? Reverse text but not numbers? What about unicode chars like LTR/RTL etc.? Or maybe you don't actually want to reverse the string - maybe you just want to print it out backwards? :P
    – Luaan
    May 28, 2015 at 10:27
  • 3
    @dan-gph I completely disagree. The point of the question (or one of the points) is to determine whether the candidate can write simple code and solve a problem. They don't have the time for you to implement complex business logic making use of a bunch of existing libraries, so they use a simpler problem that can be easily explored. It is not at all indicative of a desire for you to reinvent the wheel as part of the job. May 29, 2015 at 15:52
  • 1
    @MatthewRead, that's why you have to ask them what they want. If they want you to reverse an array of characters using a for-loop just to show that you can do it, then that's what you would give them. You find out their requirements, and you meet them. It would be a valid question, however, to ask how the candidate would they would reverse a string in production code on a particular platform.
    – dan-gph
    May 30, 2015 at 9:52
  • 1
    In Java, String is immutable. So you can’t reverse a string. You can create snd return a reversed string, like myString.reversed().
    – gnasher729
    Sep 16, 2022 at 18:41
11

What is a good way to deal with such questions?

One key is to remember that the interviewer almost certainly isn't looking to be educated by you, and isn't looking for a long-winded reply, but just wants a reasonably simple and straightforward solution to the question.

Another key is to understand the context of the question. If the position is a software developer role, then a theoretical/mathematical explanation isn't likely what the interviewer is seeking. More likely, a practical solution is sought. If instead, you are seeking a research position, then more theoretical answers might be appropriate.

Just as with answering questions in a school exam - try to look at it from the interviewer/teacher's viewpoint. Provide the answer that you think the interview wants to hear, rather than what you might believe or know to be mathematically/philosophically/theoretically possible and/or correct.

Above all, keep your answers relatively brief. The interview shouldn't be dominated by your answer to one "puzzle" question.

1
  • 2
    Generally agree, but I caution against "Provide the answer that you think the interviewer wants to hear". That can be dangerous. I often ask questions that imply I'm looking for one thing when I'm actually looking to see if the candidate has a brain of his own and realizes that the standard seemingly-obvious knee-jerk answer doesn't apply here. Answer questions as asked, perhaps within the context you think the interviewer is in, but then state that as a assumption to your answer. May 29, 2015 at 16:33
10

If this is the natural way your mind works, woudln't you be happiest in a place that appreciates that? It may take longer to find a job but when you do it will be a better fit if you answer the questions exactly how you think they should be answered. Some jobs needs that ability to deal with the complex and some do not. Which do you think would make you happier?

2
  • 5
    Like my dad always said "Be yourself. Unless you're a jerk, then be someone else."
    – corsiKa
    May 28, 2015 at 15:00
  • 2
    Did he ever mention the Batman? Because if you can be the Batman, always be the Batman.
    – Martijn
    May 28, 2015 at 17:02
5

I would lead by asking if I can assume whatever you think they're taking for granted, and initially avoid explicitly mentioning the ways that assumption might be false.

For the example you gave, that would be "Can I assume the string is simple ASCII?"

This approach has a few benefits

  • It moves you to answering the question asked as quickly as you're comfortable going, without neglecting a potential 'gotcha'
  • It shows that you recognize the importance of verifying your assumptions
  • It shows that you are aware of text representations beyond ASCII
  • It avoids putting the interviewer on the spot with whatever alternative interpretation you might have identified
1
  • +1. Great answer. The key is that you want to show that you're an experienced programmer (you know things in depth and you seek clarification), and at the same time you treat customers well. By leading with the "assume ASCII" question you show the first qualities, and by not diving into grapheme clustering you show the second. You indicate that you could go deeper if that's what the interview requires, but you're leaving the interviewer in charge.
    – Wayne
    May 30, 2015 at 19:18
2

Offering a solution that is far more complex than the interviewer is looking for would not sit well with the interviewer. It would not sit well with me either if I were your manager.

Turning something simple into something complex when you are expected to do something simple will get you killed with me. Nobody is asking you to teach a course on string reversals. Deliver the solution that you are expected to deliver.If you need clarifications as to what you are expected to deliver, ask - don't guess. If you have objections or reservations, voice them in a separate communication.

12
  • 7
    Well, that's the entire problem of my question. Reversing a string is not something simple without further specification. I'm not making the problem complicated, the problem is complicated. How do I get across that I am aware of the complications without - exactly like you said - teaching a course on string reversals.
    – Martijn
    May 27, 2015 at 15:51
  • 4
    Give the solution that the interviewer expects. If you don't know what the interviewer expects, ask him. And AFTER you deliver the answer that the interviewer expects, point out where either the interviewer or you could be oversimplifying. May 27, 2015 at 16:37
  • 2
    @Martijn you seem more concerned with showing "yes I am very knowledgable about all the complexities" than "yes I understand how to engage in meaningful interaction with clients about what problem they are really seeking to solve". I've found people tend to care more about the latter than the former. May 27, 2015 at 17:16
  • 2
    I understand what you're saying. If this would come up in an actual work scenario my question would be about the use case. Why do you want the task done, and what are you going to do with it. From there, the technical requirements can often easily be guessed and validated. But interview questions don't have a requirement for an end user. The goal of the question is not to have the result of the task, but to see how I perform the task. But tailoring the question to that, asking why they are asking and what they want to find out sounds, to me, even more smart assy.
    – Martijn
    May 27, 2015 at 17:23
  • 3
    Part of the problem to me is that you don't know if the interviewer knows about or cares about the complexity, and trying to find out what they want to hear from you might already put you in the pedantic camp
    – Martijn
    May 27, 2015 at 19:17
2

Get a read on the interviewer. Are they technical and appreciate detail or are they business side and want the perception of easy? Are they just an interviewer and just going through a script? What is the nature of the position - is it a flight control application or just some simple internal data scrubbing for a one time load.

The reality is that edge cases happen in production. You can design for them upfront or deal with it when it happens. It is typically more expensive to deal with it after it happens. Best case is the user finds the bad data and spends the time to fix it. Worse case you don't find the bad data and the business makes a costly mistake as a result.

Yes users can get frustrated when you ask the right questions but they can go ballistic if something they did not think was important at the time comes up as production problem.

I scrub and load data as part of my job and it is so much more complex than most people give it credit for. These two words are not the same "can't" and “can’t” are not the same. They don't even have the same double quotes. Users don't get that what you copy out of Word is not necessarily what you typed. I was told to load some data I knew they wanted to search on it. I told them we need to normalize and they said no we need fidelity. Sure enough a key customer could not search on a smart quote and went ballistic. Now I get to ask right questions up front. The point is you can only ask the questions they are ready for in a way that matters to them. Warn them about what can go wrong in a way that when is does go wrong they can recall he tried to warn me.

Lots of companies are looking for detail oriented programmers. You need to ask the question in a tactful way. If they don't reward detail then it is not a good fit for you. You are interviewing them as much as they are interviewing you.

As far as pendant? Ask questions using terms the interviewer understands and tell them why. If they don't know what encoding or ascii is then ask them if this just the keys on the keyboard.

In poker they have a saying always always bet the nuts (top possible hand). They may be looking exactly for an anal programmer and give them a chance to see that. Once they roll their eyes then back off.

1

I read the discussion on thedailywtf. If you want to do it correct with Unicode strings, it is amazingly difficult and probably impossible. On the other hand, I've never seen anyone wanting to reverse a string in real life.

So I'd announce that I will show code that reverses the order of Unicode code points in the string (giving the interviewer a chance to ask for something else), explain why reversing the order of bytes won't be acceptable, and write clear and efficient code that does what it should.

Then I'd say "if you like I can tell you what problems there are with this code". And having read the discussion, there is an infinite number of problems, from quite reasonable to absolutely esoteric to impossible to solve. I also heard there are interviewers who will say "there is a bug in your code, can you find it", so you have an answer to that :-)

In many development situations, when you ask for clarifications, the person asked for clarifications doesn't actually have a clue. So if instead of asking for a spec that they don't have you write a spec and ask "is this spec acceptable to you", that's a lot more helpful.

If you are asked for code to copy a file, you can ask about what you should do for all possible error conditions. Instead you could come up with a plan what to do, and ask "here is what I suggest should be done when there are problems, are you Ok with that". I think that goes down much better than endless requests for clarifications. It also means that most likely either your suggestions are accepted or replaced with something better, and not with something that your boss just made up on the spot because you asked him.

1

The first questions you should ask yourself during an interview is who is interviewing you. What is their role? Depending on their role in the company their backgrounds will vary from highly technical to managerial to support peers to etc... Since backgrounds will vary so will expectations.

What their role is will help you figure out what is the real question.

Examples of what I'm talking about:

For a tech lead, who has a role less in programming day to day, they may be asking you the question because they want to see how you solve problems. They may have encountered the problem managing another developer and gotten very frustrated with a detailed response. Even if the question is highly technical it is possible that they might have simply looked the question up on the Web. They'll often expect you to be able to get results rather than endlessly program yourself into a hole. While they have domain expertise their main interest is execution of the project. You'll obviously want to be concise and derive the answer quickly but explain that a real world situation might entail details that cannot be compromised.

*UPDATE The meaning of the term "tech lead" may differ according to industry/company. But here I refer to the use stated above.

For a developer, who will be your peer you can usually assume that they're testing you for domain expertise. Of course, I've also had seen the extreme, where a interviewee was asked to solve a problem using merge sort, when there were thousands of well written libraries in the programming language we were working with. Being able to solve that problem demonstrated in no way competence in the job function(s). Rather, it was more of an elaborate challenge, a "are you good enough? I don't want to spend all my time baby sitting." In this case, it would be wise to, even if you make assumptions to answer your question, bring up all of the caveats to show them that you're sharp and experienced.

2
  • 2
    "Tech lead" is a title usually given to strong developers who provide technical guidance to other developers, and who sometimes additionally have management responsibilities. If you ever find yourself being interviewed by a "tech lead", do not get sloppy about detail. Developers who skimp on detail create bugs. Indicate the detail's there, and let the interviewer decide to omit it from the question scope.
    – Quirk
    May 27, 2015 at 20:44
  • Thanks for noticing! Different companies use titles for different purposes. What I've encountered most is "Lead Developer" or "Solution Architect" or "Senior Engineer" as being a developer oriented role and "Tech Lead" as a project manager based role. Nevertheless, understand that someone who's role is primarily less based in programming day to day would usually expect different answers. Jun 2, 2015 at 20:09
0

I think you should ask for clarification. An interview is never the place to "guess what the interviewer is thinking" type stuff.

If they want the simple solution, then:

myReverseStringFunction("banana") {
   print "ananab";
}

This can be seen as: genius, simple-minded, or smart-ass.

Personally, I'd rather hire people who are capable of doing complex things and work with them to tone it down than people who do not have the mental horse-power and some how make them smarter.

EDIT: Usually in interview coding questions, it's not expected to write out code that fully compiles, have complete unit test coverage, handles errors, validates user input, is overly efficient, scales, looks eloquent, beautiful, etc. You can always ask. A good interviewer would let you know what is expected.

EDIT 2: Maybe we should stop asking programming questions during interviews and just look at the candidate's Github postings.

10
  • 1
    I want to hire people who can do complex things too, but I wouldn't be favorably impressed by the smartass "ananab" answer. May 27, 2015 at 15:27
  • 5
    can you indicate any language in which this actually runs?
    – njzk2
    May 27, 2015 at 16:33
  • 1
    @MonicaCellio - I wouldn't either and if I were interviewing someone i would let them know it.
    – user8365
    May 27, 2015 at 21:12
  • 6
    @njzk2 - Pseudo Code, it compiles on the white board.
    – user8365
    May 27, 2015 at 21:12
  • 2
    This seems like being asked to write a sort function, and answering "print 1,2,3". It doesn't demonstrate that you can write code or that you are aware of any algorithms to reverse/sort anything, just that you know a definition of "reversed"/"sorted". If you can't demonstrate what they want in an interview then you're screwed. I guess I've missed the point of how this can be seen as genius, though. Is it a passive-aggressive protest at the lack of a real specification for the task? May 29, 2015 at 8:45

You must log in to answer this question.

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