How to win the coding interview
blog.devmastery.com
blog.devmastery.com
> Your code should be commented
Sure.. but:
> * @param {string} stringToTest - the string to test.
> // make sure we have a string.
> if (typeof stringToTest !== "string") {
>
> function isPalindrome(stringToTest) {
> ...
> // if we get here, it's a palindrome
> return true;
Do we really need to explain that stringToTest means string to test? I for one find such low level comments almost completely redundant. I prefer strong variable naming and other ways of creating clean code to littering the code with comments that the code expresses naturally.Comments should IMHO be reserved for explaining special complexities, any particular gotchyas, etc.
I'm a Vic20 + Commodore 64 Basic -> Amiga Assembly -> ColdFusion -> C# dotNetCore person myself; mostly back end, but I'll check out JSDoc for when going down that path again next.
I forgot to mention some PHP thrown in there, but I'm glad to have been making the transition to C# in the past year. Working with a strongly typed language is quite a revelation, and some fantastic things are happening with the language and framework these days too (dotNetCore).
'use strict'; // avoid ambiguity and sloppy errors
If the line that starts (or ought to start) virtually every JS file you ever write can't stand without explanation, one wonders what can!That seems incredibly heavy handed and not helpful in the learning process. I was a professor's aid for several programming courses and many students simply made comments like that constantly because it helped them drill it into their head what it did. It's a little annoying but it doesn't hurt the readability.
Automatically failing them on a second turn-in seems very anti-student and anti-learning to me. Teaching through negative reinforcement is the worst way to teach.
First time we talk about why I don't want "the what" comments, only "the why" comments. If they still do it in the next handin it's a fail unless they've explicitly provided me with a reasonable reason to do it.
Your comment merits a failing mark, downvotes, because you made the same subjectively wrong statement twice.
i++ //increment variable because used clicked
It's harmful for readability and takes a lot longer to read. If they hand me a second handin with such comments, after our first session, I'm not going to tell them again.Working is the lowest bar of quality.
Any interviewee is going to make assumptions about what the interviewer wants. Some of these assumptions will be wrong and some will not be worth the time to ask about (like commenting style). If the interviewee solved the problem and/or displayed a desirable level of competence that's good enough. Interviewers do the coding exercise merely to screen out people that have grossly misrepresented their skills.
On the internet folks like to imagine they're in a position to "immediately reject" a job applicant because of a single "red-flag" that indicates some profound shortcoming. This is rarely the case.
I find it absolutely destroys readability. It is incredibly hard to follow code written twice.
A better idea would be to get a standard code style for all course...
It's a nightmare of irritation.
You could easily replace "students" with "coders" and that statement is still true. Just an observation.
I told him he was wrong and argued with him on more than one occasion. In the end, I just did it his way because there wasn't a good alternative.
Might be fun to do some light ad hoc parsing.
Also, with that rule, I can't resist
// this line left intentionally blank. // this line left intentionally non-blank.Ironically, that is quite a bit like the real world.
Simplistic comments actually help a lot when learning (even if they are just a reinforcement). Quite often our students write the comments first and then fill in the code which is perfectly fine.
It's also more interesting to let them freeflow it and then explain later why it might not be a good idea. The learning effect is stronger if they can go back and read their own overcommented code.
Another thing is, when I was learning to program, commenting was something I used to keep things light. Sometimes inside jokes or random bits of code that were terrible that would make me laugh once I had the final solution. In my opinion, unless the assignment was designed to teach proper comments, why not let students be creative with their comments, even if its redundant to you.
That said, in a test when hand writing code it should only be pseudo code. Expecting learners to write syntax correct code by hand is stupid.
> why not let students be creative with their comments, even if its redundant to you.
Because I have to read every comment, decide if it's relevant or not, and delete it if it isn't. "End of line comments" on every single line is not helping anyone - "using for loop to iterate over the array" is bloody useless, because it's right there in the code. Keep in mind this is CS students at least 2 years in.I wasn't keeping that in mind. Thats makes a lot of difference. Pretty sure I studied under the same rules.
This article takes such an expert tone. But it's just opinion. For me, that comment would be a red flag.
He also says to write the most efficient code possible. Then doesn't. See the comments at the end of the post.
Overall, I think what this shows is that as an interviewee, the best thing you can do is try to get an idea of the interviewer's expectations as quickly as possible. People love saying here that it's not a test scenario. But it is. The interviewer has a preconceived notion of what you should and shouldn't do and you need to meet that notion.
As an interviewer, recognize it's easy to think you're smarter than the other person when you already know the answer. Don't be pompous. Don't assume you know better. Try to set expectations very clearly. Try to really listen to the interviewee and understand why they're making the choices they are.
Personally, I would be frustrated by this interview. I feel like this article is a thin justification of a lot of standard interview practices that don't actually work. It and his further comments take a condescending tone that makes me worry he wouldn't be open to approaches he hasn't seen.
Reminds me of a time an interviewer basically gave up on an interview because I told him there were O(N) algorithms for sorting strings with a fixed alphabet. He said "Best case sorting is O(nlogn)" and I could hear in his voice that for him the interview was over. I knew what radix sort was but in the moment I couldn't actually explain or implement it without looking it up and things just went downhill from there.
Radix sort is O(n) in log(dictionary size) which is only a useful bound when the data set is larger than the dictionary (this is a severe but not fatal requirement. Some datasets have many duplicate values, and anyway in practice log(n) factors in real world systems are practically constant factors: an 1log(n) algorithm will be slower than a 100(1) algorithm.)
You can misstate a theorem, or forget the proof, OK, but doing both is poor form.
Another good tip for interviewees: If you don't really understand something well enough to explain it, sometimes it's better not to bring it up than to introduce it and look silly. Sucks. But you're more likely to lose points than gain them for just kind of knowing something exists.
Also applies to hacker news comments ;)
From a technical standpoint you should read uncommented code and more often than not be able to tell exactly what it does (barring a lot of poorly named methods or similar architectural issues). Any comments should simply explain the business rules or decisions that led to that code. Maybe you are knowingly violating a best practice for your framework or language because following it would break business logic down the pipeline or something. This is the perfect time for a comment explaining that so a well-meaning junior developer doesn't refactor it six months from now.
I have 10 years experience with references. I have code that I've built, deployed to production still running today. I have cultivated my own clients, gathered requirements and built something that delivers business value.
Instead of a coding interview, I'll make a counter offer. Why not hire me on a 1 week contract to come and do some real world work. Work that is small enough to be done in 1 week and big enough to deliver some value.
At the end of the week, you pay me wages and if you're not happy, you can not extend another week.
Isn't this a much better way to evaluate a good candidate?
* It can take up to a week just to get someone ramped up with access to things in many environments (setting up accounts, configuring dev environment, etc.) It's not free to create and disable a dev's access.
* Most places I've seen aren't set up to ramp someone up in a week. I think Pivotal Labs gives people a try for 3 week contracts, and they have a culture of ramping up new hires via pair programming in XP environment.
* You'd only be productive in an environment where you are already familiar with the tools they are using. If they're using Erlang, and you're coming from Java, you simply couldn't do much with Erlang in a week.
* Many places can't/won't put you to work without you passing a background check.
* Candidates who already have a job aren't likely to be in a position to take a week off to work for someone else.
Also "understand fully" isn't "can contribute to a sub-problem meaningfully".
In other words: yes, that's a better way for you to prove yourself. No, we don't have the resources for this approach.
I also don't typically have the luxury of having great candidates in front of me who will wait multiple weeks to get into some weird one week eval (and they usually have a job already, so how are they going to get away for a week?). This is a time consuming and expensive proposition which would require buy in at multiple levels from multiple departments and would probably end up not working out so well.
"Alternatively, we can write/review some code on a whiteboard."
If you are OK with all that, fine I guess. But I thought it was widely agreed upon that the software industry needs better hiring practices.
I think if you approach them correctly (like the author suggests), then actually they're fine for their intended use. (Not perfect, but this is the real world, nothing's perfect).
If you can't cope with scrawling some pseudocode on a whiteboard because that's "too much pressure" then you're going to really struggle when a deadline looms and we "absolutely must get this code out to the customer by Friday because a $50M contract is on the line."
You are wrong. Just because it's most used currently doesn't mean it's better. And it is actually well documented.
@tokenadult posted this numerous times: https://news.ycombinator.com/item?id=4879803
First, "scrawling some pseudocode on a whiteboard" and "we absolutely must get this code out to the customer by Friday because a $50M contract is on the line" are not the same thing and it is fallacious to use performance on one to infer performance on the other. "Stress" is not some universal feeling that differs from situation to situation only in amount. It has types, which different people handle differently.
Second, related to my response to a sibling comment, if "we absolutely must get this code out to the customer by Friday because a $50M contract is on the line" has a high enough probability of occurring that it is worthwhile to screen candidates for ability to handle this, your company is fundamentally broken and you are trying to use your hiring to compensate for the real problems.
A lot of places value people who work well under pressure. (A bad push taking down all the server's I'd stressful)
There are probably way more successful (100-million to couple billion dollar revenue) companies that can be brought offline with a bad push than can't.
I understand that some people get stage fright, but I'm not expecting them to come up with a perfect solution; I'm only trying to get an idea of how they think (and whether or not they can actually write code). If they can't do this sort of thing in front of a small group then how are they going to perform in group meetings? Are they just going to sit quietly in the corner the entire time?
I can't have that either, and I need some sort of measuring stick. I'd rather lose a good candidate than take on a bad one.
I once was taken almost completely away from my engineering duties for a period of a whole month to help almost full time with what was a "critical" position that needed to be filled "now". A year and half later, when I decided to leave that company, they still had not hired for that position, and had an endless list of why every candidates didn't make the cut (and we had interviewed some excellent candidates who got thumbs up from all of the technical staff who had interviewed them).
It's different everywhere, but in general for a competent tech worker with about 3+ years of experience, I'd say you're looking at at least 6 months to find someone, probably closer to a year, not because there fails to be a supply of good candidates, but because that's just the time penalty for internal politics.
While this particular anecdote happened at an established firm, I experienced nearly the exact same thing in start-ups as well, literally the same political bullshit excuses used to reject otherwise great candidates even when we were "desperate" to hire someone.
Except now I have to jump through hoops with HR (let's just assume they'd be OK with this, which they almost certainly won't), get the contract in place, work with IT to get your environment set up, and bring you up to speed (so really I may get one full day of actual work)... just to realize that I don't want to hire you. Oh, and did I find you through a recruiter? Now I have to pay them a cut. Do I now get to run this little bureaucratic maze for all N candidates I'm looking at? You have become a very expensive interview across at least three departments and you're probably not worth it.
Sorry, but no. I do ask for some whiteboard coding, but it can be done in any language (or pseudo code) and I'm really only trying to tease out your thought process. For a junior or mid level position, yes; I am also trying to figure out if you can write a line of code. I'm also not sure how you're going to be able to get away from your current job for an entire week (I have literally never interviewed a candidate who wasn't fresh out of college who was unemployed at the time).
I agree that it can be a pain, but there aren't always better ways to measure your ability to take a problem and turn the solution into an algorithm.
This isn't about the number of departments. This is about companies needing to make very real tradeoffs between maintaining their current speed/security/stability and investigating future talent.
If you don't like the work, we can part ways knowing we are not the right fit.
In a bigger organization it's probably more involved, but if you set out to make it a standard way you interview some developers, I think it's perfectly doable.
I agree that improvising it when a developer asks for it, which is what I think you're describing, would be harder.
I'm glad it got me my first gig, but I'm not sure I recommend it. IME, any position that actually gets applicants gets a flood of hopelessly unqualified candidates. (Think: will fail FizzBuzz, even almost a decade after the blog post that started it.)
It's interesting that the parent is suggesting this for when you have a lot of experience rather than when you have none.
Given the number of people I've interviewed over the years who have 10 years experience and look very strong on their CV, but still struggle with our basic "coding challenge" (on par with FizzBuzz but more aligned with what our company was doing), even before we get to the real interviewing (with another alarmingly high dropout at this point as well), I can't see hiring for a trial being an effective strategy. We would be sinking way too much cost and effort in to it.
It may also result in poor hiring choices because one person's ticket/feature/whatever may have hidden challenges, and another person's might be easier than initially assumed. There's now more randomness involved in what's an already too random process.
Maybe interviews should be a bit less involved, and companies should be more willing to take advantage of the probation period (and employees too, I've seen a handful pass their probation and regret it).
A few months ago, I interviewed with a company--the first rounds were remote, and we used an online tool so the interviewer could watch me work problems in an environment with a "compile and run" button, which was great!
Imagine my disappointment, then, when I got to the in-person interview, sat down in a nice conference room with a computer attached to a giant TV and a wireless keyboard, and was handed a pencil and a pad of paper on which to code.
That's clearly something I need more practice with--but why? It's yet another thing I have to be good at to get work, that doesn't make me better at doing the work I get.
Then I just stopped taking interviews with that nonsense altogether and found places to work that I actually wanted to be and that, more importantly, had mutual respect for one another as opposed to being treated like someone who was supposed to be grateful for working at some run of the mill office job. One where we were all supposed to pretend we were given some great gift of fixing someones crappy log file code that broke production. Or adding some api endpoints for a new model.
These jobs aren't all that great and all this nonsense is I'm sure keeping a lot of capable people out of the industry making slightly less money while being treated like human beings and equals.
There are two major reveals in that sentence. One, HR rules your hiring practice and therefore you and your department, and you just advise them. Two, your company is so soul-suckingly bureaucratic, I couldn't imagine a good, creative, problem solving developer would ever want to work there. Both are red flags.
No they're not; they describe 98% (made up number) of the industry, and I don't think that "soul-suckingly bureaucracy" is an inevitable outcome of implementing reasonable processes.
We have IP that we have to protect. We have a company to protect (hence the HR involvement). Sure, you may be lucky enough to wing it in your little five man operation and get by, but you had better hope you don't run into a problem employee if you're not covering your ass. The sort of company you describe can be a ton of fun to work at, but you're also probably failing in a ton of areas and you don't even realize it yet. It's a mistake to think that your hipster SV perspective is the way that the world should work.
But candidate evaluation is not an objective business, one company's perfect candidate might be complete trash at another firm. A company's interview process then is necessarily a reflection that company's character, culture, and attitude just as much as it is a process to find potential employees.
For example, your suggested hiring process of doing essentially an extended homework assignment might be great for a firm who doesn't care about "hiring the best", "building the elite team" or whatever, and instead wants to just assemble a ragtag team of misfits who trust and work well with each other to get things done.
Meanwhile, the Silicon Valley standard Googlesque hiring practice of using timed tree-inverting-list-o(log n)-optimized-talk-through-what-you-are-doing-(oh-90%-of-our-devs-use-your-oss-but-you-dont-remember-red-black-trees-so-fuck-off) algorithm questions to pinpoint the most academically smart candidate is perfect for companies who want to hire the "smartest programmer" to create a culture of intelligence oneupmanship to drive "innovation".
And unless one happens to be in a situation where one absolute needs a job right away, a candidate could really glean a lot about a potential company's direction and culture through just how they conduct their interview, and decide if this is, indeed, a place where one could do one's best for the company and continue with the application or apply elsewhere.
I use tons of open source software written by people I would never consider hiring. "You use something I wrote therefore I am good" is not a reasonable assumption.
I think a few hours discussing code is a small sacrifice for a fairer, more equitable interview process.
I just saw some code a candidate wrote (offline) who also had nearly this much experience in C#, and who apparently explicitly called out using C#6 and being a C#/.NET expert etc, etc.
Their code was written like it was 10 years old. Used array allocation (rather than collections). Time calculations like Convert.ToDouble(Convert.ToInt32(hourStr)/60)+Convet.ToInt32(minStr). Giant for loops where a simple LINQ query would do. It also failed to solve the problem.
10 years but hasn't learned anything new doesn't count for 10 years experience, in my opinion. That's why even "experienced" developers get coding questions.
(Btw, If the candidate hadn't explicitly called out their supposed expertise their use of old coding style could be overlooked; but since they had this on their resume, it either meant they were completely clueless about it, or simply lying. Either way, not a good start.)
"Convert.ToDouble(Convert.ToInt32(hourStr)/60)+Convet.ToInt32(minStr)" - while nobody writes code in this way in production this is exactly the way of coding endorsed by Codility-like programming challenges when you have 30 minutes to come up with a solution.
For anyone with the knowledge the person claimed to have, that code should boil down to something more like TimeSpan.Parse($"{hourStr}:{minStr}").TotalMinutes;
I know none of the code I've ever wrote for a job interview was very good. Often it's total shit, hell, it often has a while (true) loop that I break out of later. (usually I ask if they'd like me to clean it up after I get it working properly).
If your interview is designed around trying to see stylistic choices such as these (yes, the distinction between writing a loop and using linq is style), you should refocus it to be about figuring out the candidate's thought process.
However, if you claim to be an expert in modern C#, you should write modern C#. To use my example, surely between string parsing, time calculations, collection handling and loops there is SOMETHING in there you use on a daily basis and can demonstrate your claimed ability write in a modern way.
I picked a small example, I don't actually know if we're moving forward with the candidate or not (I looked at the code but I've otherwise not been involved in the interviewing). For what it's worth, we have gone forward (and even hired) people that did poorly on the coding test, because through talking to them, they clearly know what they're talking about, and they could explain why they did badly.
However, I've seen many times where someone can't sufficiently explain what they can do or accurately describe things they know about, can't write code in a coding test (even if allowed to finish without time limit), and don't have any open source profile (eg, code published on github).
I don't expect everyone to be able to write SQL JOIN statements, but I do expect people that are "database experts" to be able to. If you claim to have an "expert level understanding of network protocols" you had better be able to explain to me the difference between TCP and UDP (and no, "UDP is more secure, TCP is faster" -- a real answer I got once, from someone with 15 years experience -- is not a good answer, even if it wasn't backwards).
How do you hire someone like that? It could be just me and/or my team: none of us can communicate with this person sufficiently, while they'd be okay with another team... but that in itself is probably reason to be a bad hire for us (and them).
I came in and did a one week trial, I brought in my own computer, they gave me access to a repository and a task list, told me to do what I could in the week and ask questions. Arguably, the experience was great. I was able to not only see if I wanted to work for this company, but what the people are like and what kind of problems I would be solving. It was a great way for the company to see if I got along with their team and if they liked me as a person.
Being a developer is half knowing how to code and the rest is whether or not you are a match personality wise for the company. You might be smart, but can you get along with others and work in different situations? A palindrome function or FizzBuzz during a coding interview can't tell you everything about a developer.
You know what else is great? I came onboard as a senior developer, after a year, I was running my own team of 2 other developers. Then something greater happened, I managed to change the way the company hires developers. We do the initial screening which is just a chat to see if their skillset matches the role, then we reduce the list down and bring them in to pair program with someone.
It works so well. Also what is cool is that the two developers we have brought on since I started were hired after great work performances during their week trial/interview.
Bring your own device should always be understood as a security tradeoff. Especially if it's someone who is auditioning for a job (I'm sure you're aware of that but can't hurt to point it out).
I'd actually love to do that. The company I work for currently presented itself in a very professional light and all the questions I had were answered promptly and professionally. No red flags.
Only when I started work, I noticed immediately their code base contained unfixed bugs, tests were not up to date and the databases (so called data-warehouses) were a mess. Unfortunately, the only real good developer was on the interview and answered my questions.
During a one-week stint, I'd have discovered enough bad practices that I would have declined the job.
Also, particularly with employment contracts, just because something is in the contract doesn't necessarily mean it is enforceable.
I don't really agree with this statement.
The truth is that there are a lot of folks with 10+ years of experience who wouldn't even pass as junior devs at many places. I've seen people with 10+ years of experience rolling out their own web frameworks (and definitely not good ones) every year or two, developers who have never written a single unit test (they don't see the point of it; also the software there was the most bug ridden product I have ever seen, surprise surprise). Their employers were not technical at all so were relatively happy with the results.
You wouldn't marry a person after knowing them for a day, just because someone said that he/she is a lovely person, would you? Same here with hiring.
But hiring is a 2-way street. If you completely disagree with the hiring procedure at a company, then you are probably not a good fit, and that's fine :)
Sure but this really has nothing to do with the parent's post. The parent said they have references and the experience and code in production. All of this is verifiable short of, say, DoD contract work.
I doubt you have worked with folks with 10+ years of experience who wouldn't pass as junior developers who also had references and verifiable code running in a production environment (and if you did I would imagine that's a fluke negative hire).
> But hiring is a 2-way street. If you completely disagree with the hiring procedure at a company, then you are probably not a good fit, and that's fine :)
Considering almost every technology company hires the same way and the employees typically have the "I went through it so you have to do" attitude you're not really going to find another company that has a "better" hiring procedure. Your response is more facetious than realistic. If you want to be a developer you don't have much choice than to go through the system that has been studied to death and known to be flawed.
It has everything to do with it. References are completely useless unless you happen to be lucky enough to know one of their references well. A random stranger saying "Bob knows X" is just as useless as Bob telling me he knows X. The references opinion is likely worthless, I can't bet my business on it.
And how are we supposed to verify the quality of this in production code, much less its existence?
>I doubt you have worked with folks with 10+ years of experience who wouldn't pass as junior developers who also had references and verifiable code running in a production environment (and if you did I would imagine that's a fluke negative hire).
That's easily 95%+ people with 10 years experience. Everyone has references, that is not something that is hard to acquire or meaningful in any way. Wordpress is running in production all over, I sure as hell wouldn't want to hire any of the people involved in it.
Open source is usually the best indicator here as they can literally point you to code they worked on.
> Everyone has references, that is not something that is hard to acquire or meaningful in any way.
A literal reference without context isn't useful. That's why, in my original text I caveated it with verifiable code running in a production environment.
> Wordpress is running in production all over, I sure as hell wouldn't want to hire any of the people involved in it.
Ouch. It's not the greatest code but they made something, it worked and it's been scaled all over the place. Seems like they could have some solid people involved in it in my opinion.
Such as?
>That's why, in my original text I caveated it with verifiable code running in a production environment.
Again, how do you verify that? Much less the quality of that code?
>It's not the greatest code but they made something, it worked and it's been scaled all over the place
The bar for hiring here is not that low. "I wrote some horrible buggy crap that is full of security holes and has cost millions of dollars" isn't a good sales pitch.
>Seems like they could have some solid people involved in it in my opinion.
The code says otherwise.
I get that. I am too.
I'm around 13+ years of experience. I have contributions to major open source projects, have given talks at a few conferences, write about my experiences on a blog... it doesn't matter. I've ran into a few interviewers who take a few minutes before the interview to skim my blog. Once I ran into someone who actually read a few posts and saw a talk I've given (always a boon).
If you really want to get a sense of how I think and what my code looks like it's out there in the open. Few people will bother to look.
Thankfully I've done enough interviews that there are some patterns I can share. Here's my unofficial guide to acing programming interviews:
1. Be honest. Don't put something on your resume because you think it will make you sound good. Yes the first screen is just keyword bingo... but at some point you might make it to a technical interview with someone who hates it when people do this and will make a point of asking you obscure questions about the ANSI C standard. If you've written a few small C programs or done a few tutorials you don't know C -- you've just used it. We tend to over-estimate our abilities which is why interviewers don't trust resumes. But if you want to get a job doing more C don't be afraid to put that out there.
2. Whiteboard coding is stupid. Instead learn logic and predicate calculus. Learn to take a written or oral description of a problem and work out what the constants are and write out an invariant or two. Use pseudo-code. Pretend you are a caricature of a white-haired professor teaching a class... write out the problem, go on tangents, explain your reasoning in steps. Write pseudo-code only if pressed.
3. Coding. Long before you start interviewing start a repository. Pick the language you're strongest in and work out the following problems: a function to detect a palindrome, a function to detect an anagram, a function to find the Nth number of the fibonacci sequence, a function to generate the list of numbers of the fibonacci sequence, and fizzbuzz. Try to come up with more than one solution to each problem. Re-type them out. Commit them to memory by rote practice. Work out problems on coding practice sites and add the most popular, boring ones to your repository. As you interview add questions you come across to your repository. Practice the most common ones. Commit them to memory. This is probably one of the most inane practices in hiring but it's also one of the easiest to overcome. 90% of interview coding problems are regurgitated Google searches for interview coding problems.
4. Prepare a list of questions to ask the interviewer before hand. At some point they're going to ask you if you have any questions for them. Grill them hard. What makes them excited about their job? What's the hardest problem they've had to overcome? What is their greatest failure? What did they do about it after? What is the most common problem they expect you to encounter in this role? Etc, etc. Know who you're talking to -- save this for the technical interviewer whom you'll likely be working alongside/for.
Before you know it you'll be done. You might get an email or a phone call letting you know whether you made it to the next round or whatever. You may not make it.
The important thing to remember: It's not personal, it's not pervasive, and it's not permanent. Remember that every person you encounter is living a life and story that is every bit as complex and deep as yours. There are a number of possible circumstances affecting your position that you have very little control over: it's not your fault if you don't ace every interview as you likely won't despite how hard you try. If you're persistent you'll eventually find something.
Happy hacking.
I've seen web developers with years of experience delivering successful projects who turned out to be terrible programmers. In this situation, it is nearly always because they're not smart enough or because they have an anti-intellectual outlook on life ("I found this on stack overflow, it works, I don't understand it in depth but it's good enough for me" or "why would I know that, I never needed it") or often both. They were ok churning out 4 month projects one after the other or maintaining some business web site for years, but when you have them working on difficult and complex problems, their abilities turn out to be lacking and the brilliant kid with much less experience turns out to be much more useful.
Real response to this should be to ask how it got to the point where we are all stuck in a room with a deadline looming and our jobs are on the line if we don't come up with a whiteboard solution RIGHT NOW.
Sounds like this place has a management/expectations problem and I wouldn't want to work there in the first place.
The idea that a coding interview is there to be "won" seems to me to be fundamentally delusional.
Author goes into the specifics he personally expects from an interview. Since he's not positing these as universal standards (and rightly not) I'm not sure if this is relevant to anybody other than the people who intend to interview at dev mastery.
That made me pause as well, but he actually doesn't say that. He says a "many will use RegEx as a part of the solution" - typically to strip whitespace and punctuation signs - something like /\W/.
The problem is not that the job candidates are not sufficiently informed about the way specific employers conduct interviews. The problem is that employers have expectations regarding the tech jobs market that start at merely unrealistic and progress beyond a complete schizophrenic break with two extra hits of LSD.
We are not re-inventing the tech interview. We are, in the style of Thomas Edison searching for a better incandescent filament, discovering 10000 ways that are worse than the existing standard.
It seems incredibly arrogant to me that interviewers assume there is only one way to solve a problem, and that is by brainstorming on a whiteboard first. I don't feel comfortable standing up in front of the class to present a solution. I feel far, far, far less comfortable if it's a coding-related solution. I did significantly better, like pretty much 100% success rate on coding components when I could hit keys rather than display my chicken scratches on a whiteboard.| I move code around a lot as I prototype and it takes quite a bit of training for me to adjust to not having the option of restructuring as I code because the medium is a whiteboard or piece of paper. And every time I erase something my level of anxiety and nervousness just grows.
Probably one of the biggest mistakes developers make, is to treat coding interviews like they are standardized tests with a checklist of evaluation. They are not. They are like a date.
The other person is judging whether they want to work with you, more than anything else. No matter how good you are, you won't get into a long-term relationship (date) if you don't confirm to the (technical and social) beliefs (and biases) of your interviewer (date). The reverse is also true viz. no matter how mediocre you are, you'll get in, if you do.
So, do everything what the author says, but you'll progress faster if you keep your mindset grounded. See this: https://www.youtube.com/watch?v=v1WiCGq-PcY
I'd instead suggest that it should never get to the point of an in-person interview unless both parties have already applied the necessary culture filters. Sure, you could get surprised at the on-site and then change your mind, but you're just wasting a ton of your own time if you either don't properly vet the important culture properties aheadof time, or else sublimate away your own culture standards because you believe you have to appear conformist in order to get the job.
A good example would be open-plan offices. I have many friends in tech who deeply loathe the cognitive damage done to them by their employers forcing them to work in open-plan seating conditions. Yet they also are too afraid to either speak up or to reject employers who use open-plan seating, thus perpetuating open-plan dogma.
My perspective is that if an employer feels I'm worth the investment to bring to the team, they must feel that trivial other things to accommodate what helps me work best are also worthwhile. If, instead, a company would reject me based on "culture fit" for these side issue accommodations, or would refuse to grant them and try to pressure me to work without them, then in either case I'm dodging a massive bullet by either rejecting them or letting them reject me.
But one thing I should absolutely never do is to compromise on those issues (e.g. "no matter how good you are, you won't get into a long-term relationship ... if you don't conform"). If my goodness isn't enticing enough for them to not just make the offer but also think hard about what it would take for me to be happy with them and make it happen, then I'm simply better off staying away from them.
As it happens, a lot of companies don't really care about the goodness of their employees. They just want warm bodies who will conform to the company line. I understand that represents most jobs.
I'd like the future to be a world where that doesn't represent most jobs, so I boycott all such jobs, even if it means my search space is drastically reduced as a result.
It's just too cognitively unhealthy to human minds otherwise.
At least in startups (The focus of this site), all the hiring advice is focused around finding folks who are passionate about your problem.
First, it's not so clear in what sense "efficient" is actually a real requirement if this is a model answer.
If the average input is very small then the cost of compiling/interpreting the regex is going to dominate any modest run-time improvement over even an extremely naive implementation.
And if the inputs are very large then the probability of contradiction in the first few characters even is extremely high, so all the upfront normalization is a huge waste.
I'm having trouble imagining the typical data set where this would be an efficient implementation and where there even exist non-ridiculous inefficient implementations.
Second, doesn't using regexes kind of defeat the whole point of the Palindrome exercise from an evaluation perspective? If someone asked if me if they could use regexes in a coding interview for this question my response would be "good instinct. If you have no other way then go for it. But I was really hoping to see you work through implementing/debugging/commenting/testing an implementation without regexes."
The fact that the post's author offered regexes as a solution is a bit frightening. In many languages, such as with Python's built-in re module, this is literally impossible, because the regular expression engine is literally confined to check for regular grammars, and you can show that no finite state automaton is adequate for expressing all palindromes (basically because they can't remember an arbitrary number of characters from the start of the string to use at the end).
Of course, lots of languages have regular expression engines that are more powerful than this, but it's a sham for an interview question to rely on that. It doesn't read to me like the post's author actually considered the theory of computation aspect of this, and instead just glibly and naively rattled off that regular expressions should work well.
This is the person judging the candidates on whether they are talented enough at computer science? Yikes.
Also, your solution is poor since it only tells you that a string is _not_ a palindrome in certain cases but cannot tell with certainty that a string is a palindrome. For example, 'aabb' will pass your test but is not a palindrome.
While that method would identify if a string has the necessary attributes of a palindromic string it is not sufficient to prove that a string is a palindrome.
>This is the person judging the candidates on whether they are talented enough at computer science? Yikes.
Right, anyone reading the OP would probably be better served by Steve Yegge's posts[0, 1] on the subject.
[0] https://sites.google.com/site/steveyegge2/five-essential-pho...
[1] http://steve-yegge.blogspot.com/2008/03/get-that-job-at-goog...
Edit: Went back and actually read the code provided, they only use regex for a preprocessing step.
A Grapheme cluster basically corresponds to what a human would consider a "single letter", including any combining marks, etc.
You're hired! :D
Even if you believe so, it's more likely than not you're not actually doing that. You WILL judge how well someone write code on a whiteboard. I've done that too, and it's surprisingly easy not to notice. You can't stop yourself from judging, maybe you can realize that your snap judgement mean jackshit and don't make decision based on that.
> While I don’t need a developer who can write code on a whiteboard, I do need a developer who can think on her feet, under pressure, in a room with others.
As someone who can't figure out if (9+1 === 10) is true or not under interview (true story, my mind just blanked out), I'd really love to have company who want "developer who think on her feet, under pressure" to put it on your job advertisement so we don't both waste our time.
As someone who has probably the same problem, any ideas how to land a better job? Those typically involve a lot of coding while someone breathes down your neck.
Joke asides, unfortunately I don't have a solution here, I gave up on interview in general. Personally, if I was looking for a corporate job, I'd write "interview is stupid" in front of my workspace and play the number games until one day I might pass one. Otherwise I'd look for smaller orgs and tell the decision maker I have interview-phobia, can we do something else?
I actually prefer a coding interview over an interview with an unprepared interviewer, who is making up questions on the fly and expects the exact answer he/she has in mind.
If my job is largely coding, I expect to demonstrate coding abilities.
If my job is largely bullshitting, I expect to demonstrate bullshitting abilities.
And so on.
There are so many variants and keeping them straight between languages is a nightmare. Grep, egrep, POSIX, perl, python, php, javascript. They all have their idiosyncracies.
The most common dialect is PCRE. Most languages have an implementation of either that or a superset of it.
PCRE isn't exactly simple to begin with. That languages may implement it, or a superset of it, is exactly the problem. I know regular expressions very well, or rather I know regular languages and can fairly easily identify if a problem is solvable as a regular expressions. But once you start to go beyond that, it's not simple anymore and the benefit of a regular expression is lost. function isPalindrome(str) {
return (str.split("").reverse()).join("") == str;
} def is_palindrome(str):
return str == str[::-1]So your solutions works after a preprocessing step.
function isPalindrome(str) {
for (let i = 0; i < str.length / 2; i++) {
if (str[i] !== str[str.length - i - 1]) {
return false;
}
}
return true;
}
Quick check list:1. Knows about es6
2. Knows about === and !==
3. O(n) efficiency with no memory bloat
4. Didn't write 30+ lines on a trivial function
I won't even add a comment about unicode since it should be your default assumption when working with javascript that multi-byte characters and surrogate pairs don't work properly.
You need to ignore white space and punctuation.
6. Didn't include any tests
7. Bonus! This function also returns true if you pass it a palindromic array! Er... Maybe it shouldn't do that.
This function is too simple to expect anyone to ask you any follow up question regarding the "spec" unless they are trying to game the interview.
Also note that the duct typing properties of JS are often used to allow such string/array ambiguities.
Seems like we could find out plenty about how a candidate thinks and codes by pursuing this line of questioning. So long as the candidate doesn't respond to these questions by saying "Look, this is stupid, I'm not going to dig into requirements, that seems like I'd be trying to game the interview. This is my final answer - it tests palindromes. Next question.".
• Will this function get only strings, or other stuff too?
• Do punctuation and capitalization count?
• Are there any special cases I should worry about?
let is_palindrome str = str = String.rev str ;;
(function is_palindrome will return true or false for input str )
One has to be good at programming, analytical skills, problem solving and communicating ideas. And after that a little research on how a company interviews should help. Even if someone reads all these books and cracks the interview, its very difficult to hold on to job with out the required skills.
kill me now. are you testing for insight or implementation correctness?
a whiteboard is a place to draw a diagram, not code. see how they visualize and reason about strings would be better
import com.stackoverflow.* ;
One of the people in the room chuckled noticeably. I then went into a mini explanation of importing * vs. direct import (anticipating the obvious question) and was more or less free to use magic whenever I needed it :D
The problem is that the answer is slightly over-engineered, over-commented, checks for input type, logs in a corner-case, looks-like-it-has-been-written-by-a-teacher-with-too-much-time-on-their-hands.
These are not problems in themselves but when you have a new person on the team and they write code like that, it may be inconsistent with what the rest of the team is doing / what the rest of code base looks like.
For comparison here is another way to test for a palindrome:
function isPalindrome(text) {
for (var i = 0; i <= text.length / 2; i++) {
if (text[i] != text[text.length - i - 1]) return false;
}
return true;
}
(Possibly add "normalization" in the beginning as they do in the article.)False, that has never happened in decades of work in my experience. All "breakthroughs" I've had came to me in the shower or other solitary place. For most people, creativity does not spring from a gun to your head in a crowded room. The rest of the piece falls apart from there.
> It’s not unreasonable to expect that you know the basics of RegEx
So that's a fairly arbitrary distinction. Regex has a famously terse syntax. Maybe in some jobs it's used frequently, and in those cases I could expect someone to recall the basics. But it's been my experience that regex comes up just infrequently enough that I never recall the exact expression, and then spend more time googling a regex tutorial (even more if it includes groups or look behind) to refresh myself than I would have if I just had a strings library that just had .StripWhitespace() .Contains() .Startswith() .IsItAValidPhoneNumber etc etc functions.
Personally, I'd interpret it as 'able to write a simple expression with a few minutes of googling', where simple expression is something like 'up to 5 lower case letters immediately followed by a digit'. It'd would be a reasonable indicator if someone has used them outside tutorials and class rooms in the past year or two.
However, you (or anyone else) might have a very different interpretation.
> If I give you a challenge to take home, my expectations are even higher. If you get a week to code something with full access to Google, etc… There’s no excuse for giving me a solution that is anything less than top-notch.
I saw that as an implication that he expected a candidate to be able to recall regex basics from memory.
> Your code should be commented.
Then put this requirement, because judging from the example, the authors expectations, is what I fail students and junior devs for. Comments are complementary and explain things like "the why" ("pad to multiple of 256, otherwise libX will hang"). Don't expect people to automatically know your implicit requirements, it's a recipie for disaster.
> You should have error handling or at least logging.
Again, put this in the requirements. Some environments need no error handling, because the error handling is external. And don't get me started on logging. Yes it's nice in a debug situation, but in many high volume production systems you have engineers with the sole responsibility of creating a logging system that impact performance as little as possible.
> You should have a test harness.
If you say so, otherwise I'm not going to make one. Be explicit.
> Runs fast. > Doesn’t take up more memory than it needs to. > Is stable and easy to maintain.
1. and 2. are secondary. 3. is king, unless you have empirical evidence that warrant 1. and 2. This is something many developers struggle with, including the auther by the sound of it.
> RegEx
No, just no - the imfamous quote is "I have a problem, let's use a RegEx. Now you have two problems" and it's true 98% of the time, including testing if a string is a palindrome. Besides, regular expressions cannot identify palindromes - this is first year CS stuff. I'm well aware that some implementations allow back references, thus they are not really regular expressions but leaning on CFGs. For this particular problem, reversing the string and then compare is by far the most readable and understandable solution.
> For senior devs, I want an optimal solution, clean, maintainable code, error handling, comments, a full suite of tests. And for bonus points I want you to flag any of your assumptions in the comments.
What is optimal? With regard to execution time? Memory usage? Maintainability? Program size? What kind of error handling?
Really?
2. "replace(/[^a-z0–9]/ig, '');"
If I were interviewing and a candidate did this I would ask if he/she knows what i18n is
also are you seriously going to quiz someone about i18n for a interview? does that really tell whether they are a hire/no hire?
Absolutely - in fact asking whether that regex was a good way of matching all characters in an input might be a good interview question.
It is often a positive signal that a candidate has worked on software large enough to be used internationally or is thorough enough to worry about it. For most of us, day-to-day software work is about being thorough and careful with design and implementation, not heavy algorithmic lifting
If you're writing in a shared text editor then sure.
And isn't all the talking you do already commemts enough?
Edit: I'm bad at reading comprehension on a mobile screen. The tests and comments bit is in a different section.
I am told that the unit-test kool-aid has taken over the universe of common sense, and I respond: "surely not", and then this...
My position w/ something like Fizzbuzz to any level of developer wouldn't require much in the way of either comments or tests (or, if embedded in a larger system, bugs would be flushed out quickly)
Do you disagree?
http://www.jetpens.com/Zebra-Mackee-Wet-Erase-Double-Sided-M...
I agree that been prepared for an interview is a good thing, if you are ready and have studied you show that you are willing and that you put in the effort.
But what about people that are currently working ?
You are trying to get the best programmer, and chances are is that the best programmers out there are currently working (minus a small percentages of great programmer that are in between jobs, or that spent the last period on consulting or personal projects) so you automatically put people that are currently working and can't prepare for the interview as well as the other at a disadvantage and those are the people that you are probably most interested in.
To me it seems that in this world the only interview process is solely targeted at young people fresh out of college.
I don't mind a general interview - I can "talk the talk" - I just hate being asked questions with very specific answers that would require most people to study or memorize beforehand. If I can Google it in a few seconds, it should not be an interview question.
Yes we do go to the whiteboard. To design stuff. To organize components of the platform and figure out how the fuck to coordinate some f-ing distributed transaction, or how to send messages from A to B and not create a bottleneck. We don't try to write the pseudo-code for a palindrome detector.
I have nothing against coding interview, in front of a computer. Whiteboard coding? I just leave the room. If you give me a whiteboard coding exercise, you failed my interview.
I assumed that I could type without makig mistakes.
unfortunately not true with interviewers at other companies. they are definitely looking for the correct answer. if you can't "get" a problem, you are not getting an offer.
I was pretty nervous before my interview since it was one of my first ever. I had studied a lot before hand since the company used languages I didn't really know. I could not sleep the night before (mostly for other reasons as well) so I was pretty exhausted when I got there. There was no internet connections on the machine and each question built on the one before so if you failed one you pretty much failed the entire thing.
The whole test was a big hit for my imposter plexus and I'm never going to repeat that mistake. I feel like I have the experience and references that I do not need to prove it on a whiteboard. I don't want to and if you require me to, I'm probably not going to work for you.
The funny thing is, years later the same interviewer tried to add me on LinkedIn and it felt awesome to ignore that.
I couldn't agree more. I've had interviews (with big companies in the north-west), that had NOTHING ASIDE FROM ALGORITHM questions. At one of those, over the course of a 4 hour interview EVERY SINGLE QUESTION was whiteboard coding tree/graph traversal problems, aside from one "architect a system to handle this" type discussion (which was maybe 15 minutes).
Interviewers: if your candidate knows, without prompting, that the best solution to the problem is a depth first traversal of a tree and can explain why, implementing the actual solution is not the most important part of the interview. Not a lot of people need to write tree/graph traversal as part of their jobs frequently enough to warrant assuming everyone can implement everything from memory on a whiteboard in 10 minutes.
Hell, I was even told "We think you'd be bored here" when I interviewed at a startup several months ago. Didn't get an offer there either.
(Fellow defense/aerospace internee here. I managed to get half-out four years ago but have failed multiple times to get full out on non-technical grounds.)
My gut feeling tells me is because i am a rather ugly guy and also somewhat of socially inept, so i should make a bad impression. Currently working in losing some weight and trying to improve my social skills.
Straight link to code as well: https://github.com/bluejekyll/palindrome-rs/blob/master/src/...
It was fun because I realized I have a different option than stacks and arrays to solve this problem now.
replace non alpha/spaces, lowercase it, then compare value.reverse() == value
string.reverse() and string.equals() is plenty good enough for smaller magnitudes or all-new functionality. Premature optimization just means you think you can outguess the profiler.
So first you code the simplest thing that works. Then you start optimizing in the most heavily used sections. If you have to go past the pointer-based solution in C to assembly that employs hardware-specific performance tweaks, it's time to just end the interview and go pet your taco cat.
The tough thing is to pass the HR interview, with dozens of idiotic questions and no way to answer them correctly except having googled the answer to each particular question beforehand.
The problem though I have with code challenges, is when you get rejected, and they offer ZERO reason why they rejected your code, despite the fact you may have spent a whole fucking week working on it, doing the best you could. I have outright asked why my code was rejected, and I have NEVER gotten a response. Pure bullshit.
The other problem, is that most of the time they tell you not to use external libraries, which I get why, if they want to access your algorithms or data structure skills, but this is stupid, because you likely shouldn't rewrite libraries that do a better job than what you can code in a short time, and in any real world scenario, i would use all the libraries I could to write less code. Its better to test those things via white board. In some cases, I would reject you based on you not knowing about standard libraries.
I had one take home test, that was basically, write a database like thing in ruby to process and query an input file with dates, names, etc, you can't use any gems. If I used external gems, I could finish the assignment in few lines of code, without external gems, i have to do all this bullshit i would never do in a real world scenario.
Can you imagine if the task were "write the most efficient code possible to check if an array of strings of integers such as "3423", "34356", etc, is sorted (treating the strings as base-ten numbers, "3423" representing 3423 and so on), ignoring any strings that include non-numerical characters" started out by making two copies of the whole damn array. That's what's happening here, it's kind of shocking that this is what javascript developers accept as the "most efficient possible" without anyone having the slightest issue.)
I'm shocked. Even the definition of efficient offered for "Write the most efficient function you can" is
> If you’re experienced, you should know that “efficient” in production code means three things:
> Runs fast.
> Doesn’t take up more memory than it needs to.
> Is stable and easy to maintain.
This is an absolutely shocking definition, given the example code offered. It really does show that javascript programmers do not in any sense consider algorithms the way Go or C++ programmers would. (I conclude this after reading the comments here and also the article.) Especially given the above definitions.
I mean, on a two megabyte input file the "most efficient function that you can" would start by copying the whole two megabytes...twice. Rather than working from the outside in, so it can reject the input and ignore the inside characters as fast as possible. Shocking!
What I'm really shocked about isn't that that's what the solution was - fine, no problem. But rather, that nobody comes close to thinking about most-efficient the way other types of programmers would think about it - and this includes the comment in the story which takes exception to the offered solution. It doesn't do it either. This post and this thread was a real eye-opener for me.
Yes, maybe some small allowance for some discussion about basic time complexity, but nothing more. If you very clearly articulate an O(n^2) algorithm during an interview, that's excellent -- even if there is an O(log n) solution that we'd all prefer. You can always learn on the job and improve through self-study, etc., but the basic task of clear articulation is much more important. Obviously, no one who comes up with the O(log n) answer is going to be marked off for it, but neither should the O(n^2) person be.
Instead, interviewers should just admit that focusing on efficient code in the setting of an interview is utter nonsense. You cannot learn from that whether or not the person is going to be effective at writing efficient code for you in the completely and totally different situation of coming to work every day in a regular work environment. No matter what you think, you simply cannot.
So the better thing would be to just admit that the results of timed interview trivia cannot tell you anything at all about how effectively someone will write efficient code in a real-life situation, and just get on with it.
Just stick a Turkish dotless-i character in the unit tests somewhere, at the end of "I’m a lasagna hog; go hang a salamı." and see what happens.
Great programmers who would never do such unnecessary things when programming in a real situation may nonetheless think of them and do them when in an interview situation, since the kinds of situations are so incompatibly different.
I guess if they did this in a take-home assignment, then it might be evidence of something. In an in-person coding interview though, it's just not useful at all for forming opinions about the candidate.
I've even seen veteran programmers with greatly successful open source projects, lots of experience, good education, high level of intellectual independence and curiosity, excellent writing skill, etc. etc., give highly inefficient implementations of FizzBuzz during an in-person interview.
These interviews are just not at all related to the way human beings actually write code and work in real life, and so they just cannot tell you much.
wether.
Who cares there are plenty of places that will hire you without all this "super smart and get things done" cliché.
More trust should be given to younger employees just starting out. They might still provide lots of value but not need to tick off a certain % of clichés valued by a senior dev who think they know the correct way.
“I use this test on all levels of developers, but my criteria is stricter the more senior I expect you to be.”
Who would really want to work for someone who treats you in such a subordinate way.
A lot of the time the personality issues are with the super arrogant hiring developers at companies. I had this issue trying to get jobs out of uni, being able to code but not knowing the trends.
If you answer the correct questions (led by what is fashionable according to top developers/industry figures) and fit into their view of what a great developer is then you will get the job.
It’s almost like you could come up with a stock set of answers about subjects to pass (clean code, unit tests, maintainability, logging).
What about the project which provides your pay check, isn't getting to grips with that just as important?
Coding on a white board is useful I have come to find if there is a conversation going on and the interviewer use this opportunity to find out more about how this particular person thinks or works.
The pomposity of this post is ridiculous. I can't stand the, "I don't have time for you," type of thinking. It suggests that the author assumes they are smarter than the person they are interviewing. It elides the underlying complexities of every persons' lived experience and inner world. Does the author not realize that people are not dumb actors in their narrative? People are generally intelligent, creative, and highly adaptable.
All this post does is show how trivial some people treat the interview process. The real lesson here is that if you can learn to ask how high to jump when ordered to you can get anywhere.
https://www.twilio.com/blog/2016/02/patrick-mckenzie-on-sala...
1. What language(s) does this function have to be callable from? 2. Can I write it in any language?
Rather than “Is this client side or server side JavaScript?”
Considering that I have no idea how to use a regex for this, it was very strange to read that the interviewer expected _many_ people would use a regex. Made me feel like I missed a year of school or something.
For efficiency, only half of the string needs to be tested, not the whole thing. (Edit: I realized later that the posted JS does this too. It was not obvious at first because "end" is also changing.)
Since I never actually do these things, I thought it might be fun to code one. First I wrote the simple function, pal1(). Then I wondered if Python had a built-in string reverse function, so looked that up with Google and found that it didn't. It has a klunky reversed() iterator, but there was the obtuse s[::-1] post on Stack Overflow that runs fast, so added that as an alternative. And I had to lookup the __name__ line, because I forgot the syntax of that, even though I've been writing Python (HashBackup backup program) for 7 years!
import sys
# the straightforward way, char-by-char compare
def pal1(s):
slen = len(s)
slenm1 = slen - 1
for i in xrange(slen/2):
if s[i] != s[slenm1-i]:
return False
return True
# s[:-5] === "the last 5 (or fewer) characters of s"
# s[::] === s === s[start:end:incr], where start=0, end=len(s), and incr=1
# s[::-1] === reverse(s) == s[end:start:incr], where start=0, end=len(s), and incr=-1
def pal2(s):
return s == s[::-1]
# select which palindrome function to use
pal = pal1
# test with:
# 1. null string
# 2. single char (odd length)
# 3. double char string (even length)
if __name__ == '__main__':
if len(sys.argv) != 2:
print 'usage: pal <string>'
else:
s = sys.argv[1]
if pal(s):
print 'yep'
else:
print 'nope'Woohooa, cowboy. The language of palindromes is a classic example of a context free language that is not possible to describe with a regular grammar, such as accepted by a regular automaton... in other words a regex.
In Recruiter-Parseable English (RPE): you can't decide whether a string is a palindrome using a regex. It's impossible. Like, maths-impossible.
You can use regular expressions to compare strings while you decide whether a string is a palindrome but you can't do the whole thing in one regex.
https://gist.github.com/anonymous/e8553707cd6162040e7d12b2a1...
stringToTest = stringToTest.toLowerCase().replace(/[^a-z0–9]/ig, '');
But the example solution is so bad anyway.
is_a_palindrome(S) {
assert is_a_string(S)
if reverse(S) == S
return true
return false
}
A string is a palindrome if it's equal to itself reversed. The example "solution" in the article is dreadfully overengineered to death and back. Noone interviewing should be happy to see such a solution and noone being interviewed should expect to be required to give such a solution, to such a trivial problem.Unless of course the recruiter is trying to catch you pants-down, but then the parent article wouldn't post that overengineered "solution" as a gold-standard, like they did.
That's poppycock. Here are the requirments:
>> Write the most efficient function you can that determines whether a given string is a palindrome.
A palindrome is a string that is equal to itself reversed. That's like, the mathematical definition of a palindrome (simplified, of course). What I gave you catches exactly that. If some of the test cases in the proposed solution don't agree with the commonly accepted definition that's a problem of the proposed solution, not mine.
Also, in terms of the "most efficient" solution, the guy's proposed solution is far from that- because he tries to be smart and reverse the string while he compares it, thinking that's faster than going the whole hog. But that's only going to save you some cycles a tiny amount of the time, because the vast majority of strings you can expect to encounter are unlikely to be palindromes. Reversing and comparing the string to itself is the neatest, quickest, most legible and prettiest thing you can do in this case, regardless of your use case or anything else.
And if you're a recruiter that expects anything else, that's because you have no idea what you're looking for, not because you are as smart as you think you are.
>> A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward. Allowances may be made for adjustments to capital letters, punctuation, and word dividers. Examples in English include “A man, a plan, a canal, Panama!”, “Amor, Roma”, “race car”, “stack cats”, “step on no pets”, “taco cat”, “put it up”, “Was it a car or a cat I saw?” and “No ‘x’ in Nixon”.
Given the last sentence, doesn't that change the meaning of your sentence to directly refute your interpretation?
Looks like all the performance related things I'm seeing there are assumptions based on experience.
>“Is this client side or server side JavaScript?”
>“should an empty string be considered valid input?”
>“Do I need to handle unicode characters?”
these questions seem a bit much for a palindrome test.Not everyone is the author of a big OSS library. Lots of people do most of their coding as an employee and cannot legally show you their code. Hell, I cannot even discuss some of the more interesting challenges I faced because that would violate my NDA.
Using a regex is overkill for the simple rejection of invalid characters. The job could be done in a single loop with worse case runtime n/2. Sure his solution is still linear time but he did ask for optimal.
It just goes to show that you can't win the interview game because everyone looks for different things. There is definitely good advice in this article though.
In fact a much better way to evaluate a software developer in an interview is by asking her/him to present some examples of work they have done in the past. But don't take my word for it, read here:
> When you get the job you will never have to code on a whiteboard, but I guarantee you this, there will come a time when we are banging our heads against a problem and there is a deadline looming and we’re tired and people are pissed at us and money and jobs and reputations are all on the line. When that time comes, we’re going to have to get into a boardroom, hop on a whiteboard, and figure things out. Fast.
and then proceeds to describe still giving you coding challenges on a whiteboard. I kept reading, but bookmarked this spot as the location at which the author lost credibility, and the rest of the article confirmed it.
If you want to test how well someone can collaborate with you (after all, that is what is described in the needless trumped up intro to the whiteboard sections -- just simple collaboration as happens everywhere in every job and is in no way unique to programming), then ask them problems that are suitable for a whiteboard discussion.
It's not the whiteboard itself that is the problem. It's the combination of a task that is intrinsically ill-suited to be done on a whiteboard and the requirement to do it on a whiteboard. It's like asking a football player to audition for you by playing football with hockey equipment on.
There are lots of good questions to talk about on a whiteboard. Sketching out graphs is a good activity. For example you might ask someone how life expectancy varies with age and ask them to draw some pictures. Now you can see what it's like to work with them, get the assumptions out in the open, etc. You can't actually do that if they are preoccupied with syntactical correctness -- and if you tell them to program in pseudo code then you'd better be happy with a psuedo answer that sweeps some parts of the solution under the rug or assumes that some minutiae details would be otherwise fleshed out later on and are not required to be literally correct in the whiteboard case.
Coding questions are just poor questions to ask for whiteboard sessions. That "we're all up against the deadline, cramming into the conference room trying to work shit out on the whiteboard at the last minute" situation is practically the last place on earth where minutiae syntactical correctness on the whiteboard matters.
The author is defending general whiteboard discussions but then saying that coding exercises, which are not at all like general whiteboard discussions, are appropriate for whiteboard interviews.
The section about coding at a computer is also frustrating. The author places a huge emphasis on asking questions, but it basically amounts to a sort of "guess the teacher's password" problem. The author has "good questions" in mind, that are secret and hidden from the candidate, and will secretly penalize you if you don't ask "good questions." Personally, I would see the server side / client side Javascript question as a waste of time and really immaterial to the given programming task (palindrome detection). Even asking "is the empty string valid?" is a waste of time. Honestly, in an interview I don't care which assumption you make about that as long as you tell me that you're making it.
But worst of all is the Cerberus red flag statement "write this code as if it was going into production." I can tell you that as a candidate, I would still be polite and try my hardest to work out the interview question, but I would have already rejected this company full stop. When you write code for production, it is a team effort and your interactions with the team, the business, the product all matter. A person who is injected into a foreign social situation, under lots of stress and pressure to put their best foot forward, etc., and also knows nothing about what you consider to be 'production' code is in no position to write 'production' code for you on some Mickey Mouse palindrome problem (literally a problem culled from the absolutely dystopia-level full of shit book 'Cracking the Coding Interview' -- meaning it is as not-productiony a problem as you can possibly select, akin to asking for a production-grade FizzBuzz solution).
This tells me that the interviewer has an extremely narrow and short-sighted view of 'production' code. They think it is something that can happen in a vacuum as long as you have a computer and a textbook problem to solve. They are not self-aware enough to understand that they come in with preconceived cultural notions of what 'production' means, and that realistically this is not at all a test of "coding to spec" or someone's coding talent, it's just yet another status game testing whether or not the person randomly conforms to whatever magic culture expectations they are being covertly judged against.
This is something I read many times when talking about interviews, and it makes no sense. Either there is a nonzero chance to be more successful in the interview if you perform good in coding exercises, or not. If the former, then there was at least one person in the history of mankind who was hired depending solely on the coding.
This type of practice hides bugs. Whatever happened to 'fail fast, fail often'?
How does writing code that builds hide bugs?
If the palindrome function does not support unicode correctly, it can:
1. Try to function anyway, return true/false even without a real match
2. Detect unicode and always return false
3. Throw an exception
It would be best to throw an exception. Why is a function that doesn't support unicode being called with unicode input? That's the real error.
The incredibly frustrating thing about interviews is that the interviewer is right, even if he is wrong.
I would much rather see a take home assignment of "this is something we've had to do before", give them a few days to work on it, bring it in, make sure they can explain it, make sure their code isn't horrible or if it is there is a damn good reason then sit down with them and work together on adding a new feature. Together. Get an idea how they work with others, how they approach problems, architecting, etc; it seems so brain dead simple and yet almost no one does it.
> Some interviewers will ask you to code an implementation of a particular algorithm. Personally, I think that’s just a giant waste of time. It’s far more important to me that you understand which algorithm to apply to which problem. You can always Google the implementation.
In one breath the author acknowledges that it's a waste of time but in the next he's saying you should understand them at least at a high level. There are a ton of useful algorithms and the ones you're going to memorize are not going to be useful in day-to-day work. They simply won't be. Merge sort, quick sort, binary search, etc are all useful but they're also some of the least complex algorithms that you'll never need to implement directly (and if you have to for whatever reason yes you can Google it) and algorithms that ratchet up the complexity are hard to memorize (at least for some people).
Common development patterns are far more useful than trying to memorize any algorithms, in my opinion.
> Arguably, the most important thing in passing a coding interview is to be well prepared. The best way to do that is to practice common interview coding questions over and over and over again until you know them cold.
This part fills me with dread for any upcoming interviews. Practicing answering questions does one thing: it helps you memorize questions and answers. It doesn't help you be a real employee. It doesn't help you jump into wireshark to figure out what's wrong with the network because you hit a wall with debugging your ruby on rails app. It's just useless for anything but the interview.
For me I have an online portfolio, several open source projects, references; I'm not saying I'm "too good" to be tested but the fact that I have to waste time and energy memorizing typical questions and answers just so I can provide value to another organization just feels wrong to me. Everyone seems to claim there is a shortage of technology workers in SV so I would expect this ENTIRE process to work the opposite way than what it really does.
'use strict'; // avoid ambiguity and sloppy errors
/**
* Tests whether or not a given string is a Palindrome
* @param {string} stringToTest - the string to test.
*/
function isPalindrome(stringToTest) {
var start = 0,
end;
// make sure we have a string.
if (typeof stringToTest !== "string") {
// throw if we didn't get a string
throw new TypeError("isPalindrome() expected a string, but got " +
Object.prototype.toString.call(stringToTest) + " instead!");
}
// normalize string by lowercasing and removing non-word characters
stringToTest = stringToTest
.toLowerCase()
.replace(/[^a-z0–9]/ig, '');
if (stringToTest.length === 0) {
// warn if we have no valid characters to test
console.log("No valid characters to test, treated as empty string" +
"\nStack: \n" + new Error().stack);
return true; // an empty string is a palindrome.
}
end = stringToTest.length - 1;
// Compare characters from outside in. Stop when we get to the middle.
while (start < end) {
if (stringToTest[start] !== stringToTest[end]) {
return false;
} else {
start++;
end--;
}
}
// if we get here, it's a palindrome
return true;
} // tests (should be in a separate file using a test framework)
console.log(isPalindrome("something that is not a palindrome") + " = false");
console.log(isPalindrome("something that is \n not a palindrome") + " = false");
console.log(isPalindrome("race \n car") + " = true");
console.log(isPalindrome("") + " = true + warn");
console.log(isPalindrome(" ") + " = true + warn");
console.log(isPalindrome("1221") + " = true");
console.log(isPalindrome("0") + " = true");
console.log(isPalindrome("racecar") + " = true");
console.log(isPalindrome("No 'x' in Nixon!") + " = true");
console.log(isPalindrome("~~!~!~") + " = true + warn");
console.log(isPalindrome("Momsie") + " = false");
console.log(isPalindrome(12)); // blow up
console.log(isPalindrome(undefined)); // blow up
console.log(isPalindrome(null)); // blow up
Godsdammit- I'm pretty sure I'm not missing the point here. That is a ridiculous amount of overengineering, it should not be accepted as an answer to such a simple question, under any circumstances.>When I offer a challenge like this in an interview, the first thing I’m looking for is wether or not you ask me any questions
> / * Tests wether or not a given string is a Palindrome * @param {string} stringToTest - the string to test. */
Don't take coding advice for someone who can't spell whether.
You know, professionals do this. Anyone who value time and quality.
Hipsters may find it weird, but, well, they have decades to learn before they'll become professionals.
I have never had a need to write actual code on a whiteboard. Neither has anyone I have ever worked with.
And given that on a whiteboard interview you're writing a pseudocode, it is not any different from a typical day at work where you also write pseudocode on a whiteboard, blackboard, sheet of paper or whatever. And if this is not your typical day at work, you're doing it wrong.
I think you are basing your argument that anything written down that can be turned into code is pseudocode. That is also not correct. Pseudocode has a very specific definition. Here is one:
"Pseudocode is an informal high-level description of the operating principle of a computer program or other algorithm. It uses the structural conventions of a normal programming language, but is intended for human reading rather than machine reading."
Flow charts do not use the structural conventions of normal programming languages, they use shapes and text.
If you are writing pseudocode (the actual definition, not your made up one) every day, you are wasting everyone on your team's time. If you are drawing diagrams every day on a whiteboard, you are still probably wasting everyone's time.
A typical workflow based on a pseudocode is very simple and efficient: you solve your problem in a pseudocode - an informal language that does not yet exist but captures the essense of the problem. Then, while still on a whiteboard, you refine your pseudocode into something still "pseudo" (i.e., a made up language that does not exist), but formal this time. It may require a couple of iterations to reach perfection.
Then it is pretty much done, the only thing left is to implement this DSL, which is trivial in most of the cases.
This workflow is far more efficient than anything keyboard stomping kids can achieve in their fixed, always unsuitable, overbloated languages.
What's 2+2? Lets go to the whiteboard!
Out of curiosity, what industry are you in and stack do you use?
What?
I just demonstrated that pseudocode is an ultimate form of a code, flowcharts included (they're just a graphical pseudocode). Maybe you do not understand what does the word "code" mean?
> What's 2+2?
Is it an average complexity of the problems you're solving?
> stack do you use?
Even your choice of words betrays you. You're a web coder, aren't you?
Just today I spent somewhere around 3 hours writing pseudocode on a piece of paper, and about 30 minutes typing it on a keyboard, testing and debugging. And it's about a typical proportion.
No, automation with AI. DSS mostly. Stacks aren't just for web.
I guess if you are unwilling to share your stack or any information other than the fact that you write stuff on paper and don't know what pseudocode is, then we don't have much to discuss, and you haven't really made any convincing arguments to your "superior" coding methods. I've seen enough BS in my 20 years to recognize yours.
I'm using exactly the same definition: pseudocode is a made-up language which may or may not vaguely resemble some existing language features.
> Stacks aren't just for web.
Yet, only hipstors use this word in such a context.
I explained the methodology in detail. It is agnostic of a target language or even problem domain.
I'm using it even when I'm writing a pure C++ code, not just when I'm building DSLs directly.
Go, solve your "2+2" problems. Hope you have a high enough character-per-second typing rate for this.
Pseudocode is not code. Flowcharts are not pseudocode.
You also didn't describe your stack. I just see some fresh meat who desperately wants people to take him seriously, but he has a hard time with it because he's kinda childish, very defensive, and can't argue his point.
Anyway, this discussion is counterproductive, so I'm going to stop reading after this one.
Pseudocode is code, no matter what uneducated pitiful code monkeys would say about it. Take any textbook on algorithms, and they would be most likely written in pseudocode.
Also, in your shameful incompetence you apparently ignored (more than once) my reference to DSLs, which are very closely related to the notion of pseudocode. But, since you know nothing about programming even this was cryptic for you.
> You also didn't describe your stack.
I already told you that I'm not going to even answer a question worded in such a disgusting hipstor argot. I told you everything that is relevant. This idiotic "stack" of yours does not matter. I worked for some blue chips, used a very wide variety of technologies, for domains ranging from hardware design and verification to CADs, database engines and compilers, and everyone I worked with did more or less the same - used either a whiteboard or paper most of the time, with very little time on actual coding / designing / soldering / prototyping / whatever.