Terrible interview question: Swap variables without a temporary

edA‑qa mort‑ora‑y on April 25, 2019

Clever programming tricks have no place in programming interviews. They usually involve a small amount of code and solve an innocent-sounding quest... [Read Full]
markdown guide
 

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.

 
 

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?"

:)

 

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)

 

"While I realise I won't have to do this in your code... Will I...? "

"It can be done in a few ways, which one is on your answer sheet and I'll show why it's still wrong... "

"I realise you have quick questions to ask here to determine my ability, may I expound on why doing such a thing in production code is actually counterproductive.... "

"Swapping with a temp is the best way of expressing the concept. Obfuscating it by removing the temp confuses (1) the compiler that is well aware of it, and (2) other maintainers of the code in future. Do you consider this obfuscation to be a benefit in your hires...?"

 

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?

You aren't allowed to use the language appropriately, but need to do some bit manipulation mumbo-jumbo!

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.

Just by luck, you may have seen the problem before and remembered the answer.

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:

  • inexperienced people will believe they are already good enough for the position and won't improve,
  • experienced people become indistinguishable from people with less knowledge/experience,
  • employers are hiring people who won't be able to do the tasks properly, resulting in badly written software.

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

  • 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.

 

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.

 

I was asked why manhole covers are round.

... because reuleaux triangles (or pentagons, or..) are more difficult/expensive to produce...

 

This question is really a pain.

I tried with javascript, the multiassign doesn't work, at least in chrome.

I solved it with the deconstruct operator:

let a = 1;
let b = 2;
[a,b] = [b,a];

It does the trick, but knowing how to do this in an interview wouldn't be my main concern if i was the interviewer.

 

This solution looks good, but it doesn't qualify for the requirements, because you create a temporary array [b,a] in the third line.

 
 

In C, that invokes undefined behaviour by modifying a more than once between sequence points, and is - unfortunately - an incorrect answer.

 

"It works as I'd expect it to, having not read The Specification, but having been told it's UB, on my compiler" is but one possible outcome of Undefined Behaviour, yes.

But you cannot rely on it

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.

 

I think it depends on the type of job. If you are interviewing for an embedded developer role you should be able to do things like this. If you are interviewing for a web developer role than I would not ask this type of question.

 

How would my example of encoding/decoding a UTF stream not be a better test? It involves more bit-wise operations. Giving the candidate the reference is also okay, since they still have to demonstrate bit operator knowledge.

Knowing this swap trick is not indicative of knowing low-level protocols or bit twiddling. There are some many things at the embedded level that I'd find more interesting to ask.

 
 

I've never had an interview at a big 4 company without being asked something akin to this. It's basically the pivot to determining whether or not my time is being wasted as a stalking horse.

My favorite are the DP and np-complete problems. At this point I'll ask the interviewer, "as a team, do we expect to use DP in our work commonly?" If the answer to the question isn't identifying the class of problem correctly, they already know who they want to hire and are just using a par-impossible/million prize programming question to say they interviewed other people and they "didn't do well in the coding interview."

 

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.

 

Agreed. I am not sure what competency such problem would assess. This is true of many questions I have seen around.
As you mentioned in one of the comments, the hiring process is very important to minimize this kind of situations.

 

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.

 

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.

 

What can't people stop trying to be so clever in interviews? In your interview you should stick to the technologies you use and try to gauge the aptitude of the individual in regards to problem solving.

 

Algorithms can be used in interviews, but there's a whole host of algorithms which can be logically derived from other ones. Those are decent tests of problem solving, as well as knowledge level. As you say, the clever tests don't gauge anything.

 
What is the default sorting algorithm in Python?

Tim sort! 😉

 

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

 

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?

 

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.

 
 

I'm sure you'd immediately get a red card, "oh, but not that way!" :/

"And not that way..."

"Also not that way..."

"Stop problem solving and just figure out the thought I have in my head!"

 

This is what comes to mind unfortunately as you said on your post. However, it would probably make us clever if we ask, Do you want to swap only unsigned integers or any type of variable?

 

If someone asked me to swap "two variables" and suggested that as an answer, I'd say my first variable contained the string "hello world" and the second one an array of types of cat.

 

Xor'ing those two might result in a cute internet meme. :)

 

Currently in our company, apart from some basic questions, we are giving to the candidate a small task to complete which has real value. We then have a follow up interview asking questions on the implementation, in order to rule out the possibility of someone else having written the task.

 

This is so relatable, I have faced bad questions so often that it demotivates to a degree that you doubt your own knowledge of the craft.

 

Surviving interviews requires you don't the process personally, or even seriously at times.

That said, there are good interview processes out there.

 

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.

 

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

 

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.

 

With Javascript it's easy!

let a = 5;
let b = 6;

[a, b] = [b, a]

 

Nice article, swapping variables with exclusive-or reminds me of Siklossy algorith (it uses or-exclusive to keep linked nodes without using pointers).

 

Your first paragraph should be framed and hung somewhere! 👌

 

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.

 

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

code of conduct - report abuse