DEV Community

Cover image for Terrible interview question: Swap variables without a temporary
edA‑qa mort‑ora‑y
edA‑qa mort‑ora‑y

Posted on • Updated on • Originally published at interview.codes

Terrible interview question: Swap variables without a temporary

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
Enter fullscreen mode Exit fullscreen mode

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.

Latest comments (75)

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
fullstackcodr profile image
fullstackcodr

During an interview, both sides should get the signs.. Like most of the people say in the comments, if you ever meet this kind of questions in an interview, then this is a red flag not to work there!

Another thing that bothers me is when I see in the job ad something like: "Preferred qualifications: Msc, PhD".. Most of the big tech companies are found by a bunch of nerd teens.. Most of those guys not even have a BSc degree..

I understand that the interviewers should do a strict filtering to find the right candidates, but asking this kind of questions it seems that they were not the right candidates for their position..

On the other hand though, by asking this kind of stuff, it might be a psychological test to see how the candidate react to such a challenge. Even in this case scenario, I am against them.

Collapse
 
peledzohar profile image
Zohar Peled

Great post! just came up my feed. I've also written something about technical interviews, I would love to read what you think about it.

What if your interview coding challenge would be completely different?

The shortened version on Dev is this:

 
mvoloskov profile image
Miloslav 🏳️‍🌈 🦋 Voloskov

tbh I hate interview questions like these. I explicitly deny to solve them and explain interviewers that language quirks have nothing to do with product making (I don't usually work for outsourcers, I'd rather create something from scratch).

I think that program code is intended for humans, not computers. So I write it myself accordingly.

Even if it worked and was reliable, I can't even imagine the real world product-making, non-scientific and non-algorithmic task that requires swapping variables. I'd rather stick to mapping and filtering. And even if I needed swapping, I'd rather make it as obvious as possible.

So yes, it's unreliable. Just as unreliable as virtually any code that is not straightforward.

Collapse
 
tamouse profile image
Tamara Temple

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.

Collapse
 
lobsterpants66 profile image
Chris Shepherd

If I got the swap question they would have to put up with me asking a while series of questions as to why they want me to write such cryptic code.

Collapse
 
mvoloskov profile image
Miloslav 🏳️‍🌈 🦋 Voloskov

Idk, works on ints in gcc

Collapse
 
rodrigojuarez profile image
Rodrigo Juarez

For my interview process, 2 or 3 days before the meeting, I sent a real word problem to be solved that should take about 4 hours. Then we discuss the implemented solution, and I ask questions about the code.
Is anyone doing the same? Any pros and cons for this approach that you want to share?

Collapse
 
mortoray profile image
edA‑qa mort‑ora‑y

The downside is that it is a lot of uncompensated time. Unless there's already a really good potential for the person to get the job, it doesn't seem fair to ask for so much of their time.

Collapse
 
slitcanvas profile image
Adam Smith

When interviewing I prefer to have a couple of basic tasks around the technologies used within the business. This is usually a web framework and a database. For each of these I would then produce a mini challenge like wiring up an MVC controller or selecting data from the database. I also permit the use of the internet and am happy to work together.

This usually demonstrates whether the person has a baseline understanding of the technologies in their CV. It also allows them to demonstrate they know how to use Google or collaborate.

You then get three levels of result. People that struggle to do the basics they are claiming on their CV, people that sail through and complete the tasks and people that show boat. The show boaters actually tend to self sabotage.

Collapse
 
learnersbucket profile image
Prashant Yadav

The best approach in javascript is to use an array destructuring

let a = 10;
let b = 20;
[a, b] = [b, a];
console.log(a, b);
20, 10

Collapse
 
mithereal profile image
Jason Clark

this is why i quit programming after 28 years, im not interested in wasting my time with half baked intellectuals and their virtual penis comparisons.

Collapse
 
silverman42 profile image
Sylvester Nkeze

😂😂. "Virtual penis comparisons". Big issue in the programming world these days.

Collapse
 
scotthannen profile image
Scott Hannen

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

  • What makes code difficult to unit test?
  • When would you declare an interface (.NET)
  • What makes code easier to read?

If you want to measure their technical understanding

  • Ask them to describe some of the work listed on their resume.
  • Ask them to describe a few common, relevant design patterns. It's not about the precision of their answers, but whether they've ever heard of them or thought about them.
  • Ask about a few things you don't know about. If they don't know, so what? Neither do you. But maybe they get a chance to impress you, and it avoids using yourself as the measuring stick.
  • Throw in a few simple concrete technical questions that most developers would know.
  • Show them some obviously defective code and see if they can spot the problem.
  • Ask them to write something simple. Not a complex coding challenge, but enough to see if they can actually string together a dozen or so lines of code.

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.

Collapse
 
xngwng profile image
Xing Wang • Edited

Often, as soon as an engineer joins a company, he or she is asked to start doing interviews, because recruiting often is such a big part of the company effort.

So the problem is that more often than not, that person haven't take interview training.

It is a hard skill to interview people and interview well, and know how to calibrate the interview.

As technical startup founders, for technical interviews, we think we are getting pretty good at identify technical skill prowess (given we all did a lot of interviews of technical candidates at our previous jobs.)

For non-technical roles we now have to hire for, it is very hard to learn what questions to ask, what to look for. So I can sympathize with the interviewer.

Collapse
 
coelhoadler profile image
Adler Coelho Santos

With Javascript it's easy!

let a = 5;
let b = 6;

[a, b] = [b, a]

Collapse
 
muiruripyrax profile image
Pyrax_Muiruri

What are the four conditions of a deadlock? I have been asked this question on two occasions.

Collapse
 
mortoray profile image
edA‑qa mort‑ora‑y

This is one that came up during my interview training. Somebody posed it as a sample question, and was then told it wasn't good. Mainly because it's obscure trivia, and can be resolved with a search in a few seconds.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.