Clever programming tricks have no place in programming interviews. They usually involve a small amount of code and solve an innocent-sounding question like “find the loop in a linked list”. Often unfair constraints are added, such as “you may not use the language’s search functions”. They follow a general pattern of being highly specific and easily searchable. Yet they aren’t something that can be solved within an interview. These are research level questions that require random prior knowledge, lucky leaps of intuition, or a lot of interviewer prompting.
It’s important to identify bad questions and to understand the problems they create. As an example, I’ll consider the popular interview riddle: "how do you swap variables without a temporary". The question creates unnecessary tension in the interview. It's not coding that you'd ever encounter on a job or even a personal project. Adding to the unease, there's no real way to "solve" this problem. Moreover, it reveals nothing about the candidate.
Far from a warm-up, it's a bad question that has no place in an interview.
Never used in daily coding
You walk into the interview room, shake hands with the interviewer, and sit down. Then you're calmly handed a marker, pointed to a whiteboard, and asked:
How can you swap two variables without using a third?
You write down the swap
function. Or perhaps you know a language where a,b = b,a
works. Great! That was a simple warmup.
But wait, you hear cries of foul play from the interviewer. "No, that's not what I meant. You aren't allowed to use the language appropriately, but need to do some bit manipulation mumbo-jumbo!" Those won't likely be the exacts words they use, but that will be what they say.
I'll get back to the clever swapping answer in a bit, but first, let's look at what happens to the interview.
Creates tension in the interviewee
If you've not seen this question before, you might switch to panic mode. Perhaps you can remain calmer than others, but you aren't comfortable. Don't feel bad about this; most people will feel the same and for a good reason.
This problem doesn't line up with any of your coding from previous projects. It's not a question that's come up during your classes. Instead of being given a chance to show your abilities, you've been thrown overboard and are trying not to drown.
What does this help? Interviews are already stressful enough. As a warm-up question, this risks tainting the entire experience. Instead of trying to find an equal footing with you, the interviewer has asserted their dominance and knocked you down.
I find that most candidates are already nervous. The moment you walk through that door or pick up the phone, you might already be shaking. As an interviewer, it's my job to be welcoming and calm you down. I want to see what you'll be like on a typical day at the office.
No approach to solving this problem
Perhaps you retain your wits and attempt to solve the problem. You might discover there is no way to solve this problem, at least not within the confines of an interview.
An experienced coder might, and I stress "might," make the observation that reversible operators are be needed. Both exclusive-or and bitwise-complement preserve all information. They might also observe that addition and subtraction with two's complement numbers also qualify. If not, perhaps the interviewer gives them a prompt with this information.
Great, order these operations to get the desired result. The exclusive-or solution and an alternate add/subtract approach, both use three assignments and four binary operators.
Let's rely on a bit of magic or interviewer prompting. Somehow, you get the template form of the solution: ? = ? ⊗ ?
repeated three times (see "the clever answer" to know where this comes from). This has (2 x 2 x 4 x 2) ^ 3 = 32768
combinations to try. With some guided insight about alternating variables, this could be worked down to 64, or possibly even 32 solutions.
Are you now expected to work through all 32 combinations, hoping to make no mistakes, and happen upon the correct solution? How long would that take? Would you need to prove it's correct mathematically?
Puzzles
It's easy to convert solvable questions into puzzles by adding strict requirements. This appears popular when it comes to algorithmic complexity.
For example, you may be requested to write a double-ended queue. A good interviewer won't deduct any marks if you don't know what that is -- it's a data structure with a way to push and pop from the front and back of a list. As an API design question I don't mind this one, but would prefer something more concrete, something used in day-to-day coding.
Let's add a simple requirement: all operations must be amortized O(1) time. Even if you understand the question, you're still left with a puzzle. Algorithm design with constraints is hard. There is no clear approach other than just brute forcing through ideas and drawing on years of design experience -- I have used it, but how many projects have needed people to understand amortized time?
A popular question in this category is "Design a stack where get_minimum()
is O(1) time". A lot is hidden behind this innocent sounding question. This will create significant discomfort. I see a lot of questions online about this puzzle. Many of them are asked incorrectly, making it truly impossible. Nothing's more discomforting to a candidate than having a wrongly worded question that doesn't have a valid answer. Nonetheless, given this question's popularity, it becomes trivia.
Some people randomly know it
As with most random trivia, some candidates happen to know an answer to the problem. Just by luck, you may have seen the problem before and remembered the answer. I'm sure you'd appreciate having this easy advantage, but I bet you wouldn't feel as though you earned it. Anybody else, given a few minutes with a search engine, could also find the answer.
I would find it fair if that's part of the question: you're allowed to lookup an answer. Being able to find obscure coding knowledge online is a programming skill.
Here are some examples of trivia questions people have been asked:
- What is 2^32 and what is its significance? You can just imagine the recruiter armed with the number "4294967296" on their screen, ready to reject anybody who gets it wrong. The significance is meant to be the amount of addressable memory on a 32-bit CPU. That answer is technically wrong -- another problem with trivia questions is you need to guess the "correct" right answer.
- What is the default sorting algorithm in Python? Possibly quicksort, or is introsort, a combination of quicksort, heapsort and insertion sort C++ uses to optimize performance. Do you care? Can I not just assume it's using an efficient approach? Speaking of C++ though...
- What's the difference between undefined and unspecified behaviour? There's an important concept lurking in this question, but I'd personally forgive you if you can't explain precisely based on these terms.
- What are the four conditions of a deadlock? As asked by a college professor on a test. Interviews aren't tests.
Questions that can be answered by searching are not good questions. While at work I'll have internet access and can find answers to many obscure problems. I won't need to burn valuable neurons puzzling through an answer on a whiteboard in a closed room. I've long since trained my brain to stop remembering trivia. I instead learned good searching skills.
Perhaps this would be an interesting pre-interview test. I'd give you ten obscure bits of trivia and half an hour to find answers for them.
Interviewers should also remember they aren't just evaluating me, I'm evaluating them. If I get stupid questions I'll think negatively of the company. It's irrelevant that I probably know a lot more trivia answers than other candidates -- I won't feel happy getting a job that way.
The clever swap answer
One of the standard answers to the swapping question is using exclusive-or.
if x != y
x = x ^ y
y = x ^ y
x = x ^ y
This "works," but only for unsigned integers. In many languages, the specific bit-wise operation of signed integers is undefined. That tricky sign bit can cause grief. Additionally, the above may also suffer from promotion issues in C or C++, as the types can change. This solution applies to a narrow range of types: unsigned integers of a few specific sizes.
There's no argument to be made about efficiency. At the CPU level, swapping variables ends up as a couple loads and stores. Performing operations on the values adds instructions to those loads and stores. Furthermore, when embedded in other code, the optimizer can sometimes remove the swap and use the source values directly. This type of code trickery is rarely an optimization, often slowing down code instead.
There's nothing wrong with asking questions about bitwise operators. Many positions will require them, and it's something all programmers should understand. They're an extension of boolean logic, and I'd have no problem rejecting candidates that don't understand boolean logic.
But if you want a bitwise question, why not have the candidate encode and decode UTF text data. It has a concrete specification that doesn't require any puzzle solving. It's also practical knowledge.
Find a cycle in a loop
I was once asked, "how do you detect a cycle in a linked list?" It made me nervous, but as I had done graph work before, I felt I could answer it. I came up with an answer that worked. Then another one. Then a third one when the interviewer gave a prompt indicating which answer they were looking for.
I saw some discussions about this also being a bad question, and I tend to agree. What if I evaluated it based on what I said here? Some candidates will know the answer to the question, and others could look it up quickly. If you don't know how, and haven't worked with graphs before, your stress level will suddenly jump.
However, in contrast to the variable swapping, there are several approaches here. If you have any exposure to graphs and data structures, you have a starting point to solve this puzzle. If you still have no idea, there are plenty of minor prompts an interviewer can give to put you on the right path without just giving an answer.
It is code that appears in a lot of code bases. If the job requires this type of work it's a fair question for checking knowledge.
This could be an acceptable question if the interviewer approaches it correctly: providing assistance, and somehow not shocking you by asking it. But if the interview merely says, "How do you detect a cycle in a loop", hands you the whiteboard marker, and leans back silently, with a smirk, then it's definitely in the category of bad questions.
Better questions
What point does variable swapping have as an interview question then? Sure, it's a fun little puzzle, but do you want your employees to solve puzzles or write productive code?
Before using a question for an interview, consider the points I've made here. Will it make the candidate feel welcome or make them needlessly uneasy? Does it involve code you'd see on a regular basis? Can the problem be reasonably solved in the interview? Does it reward trivia knowledge, or does it explore some application of the candidate's abilities?
You, your company, and the candidate will all be better off with well-considered questions.
I conduct a lot of interviews over at interviewing.io -- check it for practice with interviewing. I'm also in the middle of setting up a new site to help you with interviews. Join the mailing list to be among the first to access the interview classes.
Top comments (75)
I love getting interview questions like swap without a temporary variable, because it is an extremely strong signal (as an interviewee) that you should absolutely not work at this company.
That's a win-win situation, then! Companies that ask you to think about a problem, and you refuse to do so because you believe it's not a good question, might not want you working for them either.
This is the correct answer.
I'm not sure how well it holds up but when a classmate of mine brought up the swapping question I came up with
x=x+y
y=x-y
x=x-y
Not sure about the other trick questions yet but when I start looking for jobs that's my planned response for this question
Yeah, this is one of the standard answers for numerical data. You can do similar things with multiplication/division (but you'll have issues there if one of the variables holds a zero). In low-level languages like C you can also do it with pointers, since they are usually just integers (memory locations), so that's a bonus too. The algorithm with XOR, however, works on every datatype since it works with bits.
If you get asked the question, you should by all means state both answers and their pros and cons! Solving problems never has a unique solution, and being able to rationalize about and understand the differences between approaches (and the constraints they impose on the problem, if they exist) is the key part to developing the necessary skills for solving problems you've never seen before -- and there's a high demand for these people everywhere.
You can't do it with every data type, unless you write in assembler and directly access registers. High-level language virtually all say this is undefined behaviour. You can't treat pointers, or any other type as an unsigned 2's complement integer -- the type where this xor'ing works. It's either unspecified, or even undefined behaviour.
That's fair. My personal experience is a bit limited so it's always good reading articles like this.
With pointers, does overflow affect this kind of swapping?
It depends on the language, but when talking about bit-level algorithms and pointers, people usually have C/C++ in mind. It will work properly if you use unsigned integers in Standard C, because adding and subtracting (unsigned) integers is defined by assuming modular arithmetic.
If you leave the default
int
type, which is a signed integer, a compiler might optimize something away and break the formula in case the overflow occurs.No, because (a+b)%c equals ((a%c)+(b%c))%c
Same with subtracting.
I don't have much experience with pointers but from what I've played around with it might. I think it will have to do with your compiler and how much memory is available.
That's a good point. I've assumed that it will just roll over cleanly into negatives or roll down into positive (if both numbers are large negatives) but you're right some compilers in that case.
Could be. It's been a reeeeally long time since I've written anything in C or Assembly, so can't speak from the first hand at the moment, unfortunately.
S'all good. I'm still in Uni so outside of little side projects I only really know what professors have brought up. Might ask one about this problem.
Oh heck you're right on the pointer front I hadn't thought of that thanks.
I am at the point in my career where I can answer these questions they way I want to: "I would never do that because it would be unclear to the next person who reads the code after me."
You (the reader of this) are also at this point in your career.
Once a Stanford graduate asked me to implement a complete currency arbitrage solution over the phone in 30 minutes. It took us 2 days and one math PHD to come up with a reasonable solution. This happens when a company does not have a hiring strategy across the board and people can ask total random questions. The other side of this is companies like Amazon that have very reasonable questions (for most of the departments) and rate you based on a standard that applies to every candidate. Much more reliable interview process.
Many interviewers forget that they had to learn solutions to problems, and that others may have never seen anything like it before.
If it's a fintech company hiring, perhaps the question is reasonably, but otherwise, I doubt it. They'll just randomly get people who can answer it through luck of experience. I could probably answer it, having written a finance platform before.
It was actually Twitter. :) I work now for a financial company and I can assure you that we do not ask this question. :) My favourite questions are depending on which language somebody is proficient, some are about what are the gotchas of the language, some more about what is your approach to certain problems. There are some yes no type of questions and some that can be answered differently based on how experienced somebody is.
Approach to certain problems... I'm so tempted to do this in an interview:
"What do you do if you're on a team, and somebody is requesting you do something stupid?"
/let them answer/
"Okay, now, how do you swap a variable without a temporary?"
:)
:D
You should do this as an interviewee :D
I had an interviewer ask me to do a string comparison in C++ without using any libraries. I was probably already out when I asked whether String was a library....
You should mention that a proper normalizing comparison requires the full ICU library, loading many Unicode data point files, and several conversion functions. You could write it, with access to the standard, but it'd take you a few years -- assuming you'd also need to write the loading functions without any libraries. :D
Just out of curiosity, if the goal is simply to compare two strings, would this still be necessary? I assume that it must be possible to represent any string, regardless of encoding, in some lower-level way. All we'd want to do is to make sure that the two strings are the same when compared in this way, like a list of "characters" or even just an array of arbitrary values...
Yes. Presumably you want to do a real-world comparison, not a byte-for-byte comparison. There are numerous rules in Unicode on how that should be done. Thanks to combining characters, precomposed characters, ligatures, and some other features, there are numerous ways two equal strings can be encoded.
Interesting and a bit scary! I’d have thought it should be possible to force some kind of ordering to prevent that...
But string comparison is one for-loop, no? Sure, in production you'd use
String
, but what's so weird in that question? A person who cannot compare two arrays might not be good fit for every job.I don't recall whether it was one or two, but I did end up simply working through using char values. I was able to solve the problem as well as one can on a whiteboard, but I think it took me longer than they wanted (and I likely shot myself in the foot asking whether it was a library)
Why is it a bad question, or a terrible interview? You disagree that such questions should be asked in the interview. You wouldn't like to work for someone that asks you the most common "clever trivia" ever. You are the one assuming that, just because a question is asked in the interview, it has to be something you'll use in day-to-day situations. You assume that they wouldn't hire you only because you didn't know that one.
You acknowledge they gave you hints along the way. Maybe they wanted to see how you think and how you respond to tips along the way? Maybe they wanna see if you can catch the idea, and how soon can you come up with other things? Maybe they wanna see what operations would you even consider trying? Maybe they wanna hear you talking "hmm so it's not an arithmetic operator because that wouldn't work if we swap non-numbers"? Maybe they wanna hear you honestly saying that you have no idea, and explain your position?
You don't even stop to ask these question. You go straight into stating how it's somehow "bad" and that "your company will be better off with well-considered questions". What do you know about the company and how do you know what they are looking for in a candidate?
No interviewer said that, nor had that tone, ever. Unless you were asking for it. That's your interpretation because you didn't know the answer and you believed that knowing what XOR operation does is "mumbo-jumbo" and not basic operation thought in high-school maths classes.
That's part of the point. If you know one randomly asked "mumbo-jumbo", you probably like reading a lot, talking a lot with other people. And you probably know more mumbo-jumbos, and you probably know a lot of other things.
There's nothing wrong if you conduct different interviews and if you ask different types of questions. Different people have different expectation and different companies have different needs for people. But I don't see a reason for calling out an interviewer and the company because they asked a question you consider necessary and "mumbo-jumbo".
Why did you take this into such a personal direction?
Because it's a first-person blog post which expresses one's beliefs and opinions. It's personal by definition. You cannot talk about something being a “terrible interview question” without taking into personal direction.
It's a terrible thing to promote dumbing down job interview questions just because you think they are too difficult or useless. It does no good to anybody:
It's absolutely narcissistic to blame the interviewer for giving you a question you didn't like. The whole point of the interview is for the employer to see if you're qualified for the job, and for you to see if you'd like to work for them.
If the interview process is terrible from your perspective, you can given them feedback about it and tell them you're not interested in the position. Guess what, chances are they aren't interested in you either -- great! Two adults met and decided that the business relationship isn't gonna work. Time to move on.
But apparently the author feels the need to go on some sort of a crusade to show the world how interviews are demons for asking the variable-swap algorithms.
This isn't an arena where you need to destroy your enemies, though. Calm down.
You must be replying to a wrong person or something?
I believe he was referring to the general overtone of your post, which came across as dismissive of the author and made statements that were demeaning to the author and came across more as a personal attack than an attempt to have a constructive conversation.
Our code of conduct is very clear about treating each other with respect, creating a welcoming environment, and maintaining a safe environment where all feel welcome to participate and share their experiences. Interviewing is a very stressful process and I think there are a lot of developers who find no correlation between interview performance and suitability for the job. Companies can end up losing awesome candidates who have lives outside of programming or end up with a team that would be great at ISO C++ trivia night but can't write maintainable code. It gives an advantage to people who had the opportunity to go to overpriced colleges and learn these things that others can only dream of.
It's totally fine to disagree with opinions, but please make an effort to do so without personally attacking or degrading the author or anyone else in the community. If you have questions about the code of conduct, please feel free to reach out to myself or any of the other community moderators, or our awesome staff.
For the record, the only time I have ever had to use this was when working in embedded software and doing micro-optimizations for 8-bit architectures. 8-bit is always going to have a place in the world, but most development is switching over to 32-bit mcus and bid twiddling is not a critical skill for firmware engineers anymore because compilers have stepped their game up.
Your code of conduct creates an echo-chamber, not a "safe environment". The environment is already perfectly safe (unless your PC/laptop is close to water -- then it might explode, and could severely injure you).
If words written in a comment section are "personal attacks" in your mind, you might want to log off for a while and meditate or something. It doesn't seem healthy to be that upset just because someone write a public comment on a public post your wrote on a platform where the whole point is to comment and exchange opinions -- positive or negative.
My post was not about the author; it was about the contents of the post, and any mention of the author was in the context of what was written. I've never peeked into their personal life or information irrelevant to the post they've written. And I don't just disagree with the post, I find it stupid. Yes, that word exists, whether you like it not when someone uses it for things you created. I explained my reasoning why I feel that way.
If I'm not allowed to express that I deem an opinion stupid, with a good explanation and reasoning, why am I allowed to say that it's inspiring/smart/amazing/awesome without an explanation? How does that contribute to the discussion? It doesn't. It's an echo-chamber where everyone gets a pat on the head. "It's awesome!" and "It sucks!" are equally pointless comments.
My comment expressed my opinion of the original blog post in a constructive way. That's never bad for discussion. If you believe that constructive criticism/discussion (even when very negative) is not appropriate for your platform, then you can remove those comments and censor speech just because you don't like it -- it's not like you'd be the first platform to do that.
If you need an explanation of anything concrete in my original comment, feel free to ask. Also, please point out precise sentences where I "attacked" the author. Because you you're accusing me of attacking another person without any evidence. And isn't that unsafe environment as well? If everyone can just point a finger and yell "that's disrespectful!", that quickly creates a mess, right?
PS. Could you say that this post is "unsafe environment" for me, since it insults me with its ideas? I'm just trying to figure out how do you make a decision on what's "unsafe", because it really seems like an arbitrary excuse because you feel like it.
It didn't upset me, I'm just a moderator here and I try to enforce the code of conduct because I was asked to and I care a lot about this site. You are free to disagree with anything you want and to have any opinion about it, but you can also choose to communicate that productively without writing it in a way which could be perceived as attacking the writer. It just came across to myself and apparently a few other people as a little too intense.
If you have a problem with the code of conduct, take it up with the staff. I don't get paid to do this, I have no vested interest in this site, I just try and enforce things as I come across them or that the system flags asking for moderator review.
This reminds me of the time in high school that a gym teacher had to fill in for a math teacher and even make up test questions. One test question involved calculating the volume of a container and figuring out how much it would weigh if filled with water. I approached him during the test and explained that no one can answer this without knowing how much water weighs. He got up and asked the class to disregard that question.
The problem when interviewers ask these questions isn't just that we might not know the answers. It's the simultaneous, uncomfortable realization that the interviewer doesn't understand what the job actually entails, and is therefore incapable of evaluating your ability to perform it.
Not only is it awkward, but it suggests that either no one in the organization does know what questions to ask, or those who do aren't interested in who gets hired. It makes me question what sort of team I'm interviewing to join, and those concerns are usually well-founded.
I prefer slightly more open-ended questions that allow someone to express themselves, like
If you want to measure their technical understanding
But in order for all of this to work the interviewer must be able to understand the questions and most of the answers.
It also helps to look over some lists of common interview questions on the internet. When you realize how many you can't answer after writing software for years it's a little bit humbling and you're less likely to measure someone else's skills by whether or not they can answer a trivia question.
Everytime that I read these kinds of posts I remember an extremely ridiculous interview I have some years ago.
The interviewer, who was CTO presented the first problem: an architecture one, where to put cache, where a REST Api, etc.
At first I feel very welcome for this type of real world problem.
But suddenly the interview changed, the archiecture problem ended and he claimed that was time for something more "practical".
He said: "When I was a kid in my school we played this game on blackboard (something like a tic tac toe but a little harder), so first I will explain you the rules and then you have to write an algorithm to solve it".
He explained the rules and then we played some rounds on paper, he always won and everytime he smirked really proud.
At the time to write the algorithm I was really stressed and anxious, I was trying to write a solution for a game that one hour ago was completely new for me and the rules were hard.
I remember tried a solution, he of course completely destroyed it and even write one himself.
I remember this and cringe haha.
In an interview for a software development position, I was asked why manhole covers are round. I incidentally knew the answer and I responded without skipping a beat. The interviewer was disappointed because I gave the correct answer. He admitted that he asks the question to hear about the various weird explanations that people come up with.
This is also a warning sign to me, because it implicitly tells me the interviewer wanted to be the smartest person in the room. One should steer clear of these types of places.
That's one of those silly questions because there are so many right answers. My favourite is, "because the hole underneath is round." :)
It's so unoriginal though. If people want to see creativity, and thought process, they should ask unusual things, preferably related to software development.
In C, you may just write this:
I become more and more convinced that these bad interview questions keep coming back because all interviewers are doing is parroting their own experience at being interviewed by people are parroting their own experience at being interviewed... you see where this is going.
In the past 2 decades, I've not been interviewed by anyone who has had any training in interviewing candidates, or conducting any sort of information gathering interview, it seems. Interviewing is a skill, it can be taught, practiced and learned, but the general practice seems to be just point at a few people to be the interview team and "hop to it".
Questions get asked because they've become pro-forma. Tricky questions, questions without answers, etc, all get asked without ever really pondering the question "why am I asking this question? what information am I really looking for that is going to help me decide if the person is going to be someone I want to hire?"
This is one of the reasons why software development is such a monoculture, and failing at diversity and inclusion.
Some comments may only be visible to logged-in visitors. Sign in to view all comments.