31 ms·
On a great interview question
- behdad 3y agoBetween 2010 and 2019 I interviewed dozens of Software Engineer candidates at Google. Almost always I asked the same interview question. Moreover, this question happened to be on the banned list at Google, because it was publicly available on Glassdoor and other interview websites, but I continued to use it because I got good signal from the candidates.
- foobarian 3y agoI stuck to the same question for nearly a decade too, even if it was barely more difficult than fizzbuzz. The ability to compare against the past candidates was very useful, which would not be possible when changing questions too often. The sad reality was that it was waaaay too effective as a fizzbuzz eliminator (> 80%) which I don't know what it tells me about the candidates in general or just about our recruiting :-)
- yamtaddle 3y ago> The sad reality was that it was waaaay too effective as a fizzbuzz eliminator (> 80%) which I don't know what it tells me about the candidates in general or just about our recruiting :-) I suspect there are a lot more people who frequently choke on easy coding questions, under the very specific conditions of interview-stress (which is very different from, "the client is unhappy and is also onsite and you'll be in a meeting with them later" stress, and from "production broke" stress, so no, I don't think it's a good proxy for general "grace under fire", as it were, either) than there are actual full-on bullshitters who manage to land software jobs while being truly incapable of doing even the basics of the job. For one thing, I think such top-tier, extremely-convincing bullshitters would have an easier and less-stressful time applying that skill directly to some other role, since there are some well-paid roles where that kind of thing is exactly what companies want, so it doesn't pass the smell test for me that so very many would be trying to land software jobs—not just ones who exaggerate skill or try to get into the industry while woefully unprepared, but who also are able to fool interviewers at a reasonably-high rate in conversational interviews, yet fail simple coding tests. That is, I suspect a large majority of "ha! I caught a faker!" anecdotes or anec-data are actually a false-negative on the test from people choking under interview conditions, and that most real fakers would also have been caught in any half-competent conversational interview anyway. The remainder should be probably be hired regardless, then re-homed to sales when you realize what's going on, since they're evidently top-percentile bullshitters and social chameleons. Joking, of course... kinda. Maybe.
- medvezhenok 3y agoThere's certainly part of that, but there's also likely selection/sample bias. The better the programmer, the less time they probably spend in interviews. And the "reward" on passing a programming interview if you're marginal is quite high, depending on your alternative choices of employment. (Top tier Ivy League university acceptance rate is 3-10%, so if you're looking for someone of at least that caliber among the general population (or even among developers), an 80% rejection rate might not be crazy. FAANG (or its ilk) are the "Ivy League" of Software Development jobs)
- pcdevils 3y agoThe tens of thousands being laid off from that ivy league and ones who jumped the, 6 step, multi-tiered interview hurdles to get a job offer, later rescinded, might disagree with that value proposition.
- ekidd 3y agoWhat percentage of candidates would you believe freeze up so badly that they can't program at all? Over the years, I have seen significant numbers of applicants who couldn't write FizzBuzz, and even one who couldn't sum up the numbers in an array (ignoring overflow). Some of these people had reasonable resumes, and many of them could talk about software development in the abstract. This was usually a sign of poor phone screening, but it always blew my mind.
- famahar 3y agoInterviews make me realize I don't know how to code on the spot while 4 people (responsible for judging me and determining my worth) watch me. I second guess everything and freeze up. My mental capacity to solve a problem is being taken up by a fight/flight response (wanting to push through the question or quit). The environment I'm in is foreign, outside of my typical coding setup. My brain has no time to adjust. You could look at my github and see someone who's an excellent coder, but put me in an interview scenario like the one OP wrote and it's like 10 years of education just disappear.
- bonzini 3y agoI am guilty as charged of saying impulsively that the first solution is O(n)! The reverse trie is genius, but with dynamic programming do you still need it? I would say that if in the general setting you can afford O(n^2) preparatory steps, and therefore you can just remember which (start, end) pairs correspond to a valid word with regular trie lookups. That is O(n) steps for each start position, giving a total of O(n^2).
- behdad 3y agoWith the dynamic-programming you don't need the reverse trie indeed.
- roflyear 3y agoI had a crazy interview question at Google I failed a decade ago. Turns out it was from a PHD thesis. I really hate this questions. It's just stupid.
- eesmith 3y agoDoesn't that confuse two uses of n? One is the length of the word. The other is the number of dictionary elements. If your language is constrained to 1,000 words, then the dictionary will be pretty small and the hash table can be constructed with no chains. That should have constant-time lookup no matter how long the query concatenation is. I don't see why O(n^2) should be optimal. The question is only to determine if a match exists, and that can be expressed as a regular expression. In the following I omit all 1-letter words since my dictionary includes all the letters. >>> words = [line.strip() for line in open("/usr/share/dict/words") if len(line.strip()) > 1] >>> words.sort(key=len, reverse=True) # because Python uses left-to-right match, not longest >>> pattern = "(" + "|".join(words) + ")+$" >>> import re >>> matcher = re.compile(pattern) # takes a few seconds >>> matcher.match("ducksoup") <re.Match object; span=(0, 8), match='ducksoup'> >>> matcher.match("ducksquom") >>> matcher.match("theremanywordsinthisone") <re.Match object; span=(0, 23), match='theremanywordsinthisone'> >>> matcher.match("theremanywordsqinthisone") is None True Python uses backtracking, so this probably isn't O(n), especially with the ability to choose the dictionary. But with there are non-backtracking matchers which would make this O(n). Here's re2 from https://github.com/google/re2 https://github.com/google/re2 : >>> import re2 >>> opts = re2.Options() >>> opts.max_mem = 200000000 >>> matcher = re2.compile(pattern, opts) >>> match = matcher.match("ducksoup") re2/re2.cc:821: DFA out of memory: pattern length 2493008, program size 1323834, list count 1089251, bytemap range 54 >>> match.start(), match.end() (0, 8) >>> match = matcher.match("ducksquom") re2/re2.cc:821: DFA out of memory: pattern length 2493008, program size 1323834, list count 1089251, bytemap range 54 >>> match is None True This is first time I've used re2. There's probably a way to prevent that warning message - I believe this is falling back to an NFA, which might not be O(n)? Anyway, here it is processing the concatenation of 100,000 words selected at random (I've omitted the warning message): >>> s="".join(random.sample(words, 100000)) >>> len(s) 956249 >>> import time >>> t1 = time.time(); print(f"is concatenation? {matcher.match(s) is not None} " + f"time: {time.time()-t1:.1f} seconds") is concatenation? True time: 12.3 seconds >>> t1 = time.time(); print(f"is concatenation? {matcher.match(s+'Q') is not None} " + f"time: {time.time()-t1:.1f} seconds") is concatenation? False time: 12.3 seconds Cut the size by 10 and it's about 10x faster: >>> s="".join(random.sample(words, 10000)) >>> len(s) 95457 >>> t1 = time.time(); print(f"is concatenation? {matcher.match(s) is not None} " + f"time: {time.time()-t1:.1f} seconds") is concatenation? True time: 1.3 seconds For this test it appears to be linear in the query size. Edit: if I increase max_mem to 2_000_000_000 then I don't get the warning message. But then the DFA-based search takes 141.5 seconds. That should be O(n) time in the query length, but an order of magnitude slower than the NFA-based search. That's why O(n) analysis isn't enough to really figure out "a faster solution."
- tptacek 3y agoThis is a fun puzzle, but it's not clear to me how this selects for people with the aptitude to perform well in any particular software development job, as the number of times I've been asked to determine is a string is/contains the concatenation of two dictionary words is I think zero. Instead of doing stuff like this, you can just give candidates realistic programming challenges and have them write code. You don't even need to be in the room with them; after all, you won't be when they're actually doing the work.
- behdad 3y agoThat might have worked before ChatGPT. :)
- pcwalton 3y agoUnfortunately, I just checked and ChatGPT gives the correct (slow) answer to your question: def is_concatenation_of_two_dict_words(word, dict_words): """ Returns True if the input word is a concatenation of two words in the input list of dictionary words, and False otherwise. Args: - word (str): The input string to check. - dict_words (list[str]): A list of dictionary words to check against. Returns: - (bool): True if the input word is a concatenation of two words in the input list of dictionary words, and False otherwise. """ for i in range(1, len(word)): prefix = word[:i] suffix = word[i:] if prefix in dict_words and suffix in dict_words: return True return False In general, I don't think that LeetCode questions have any particular advantage over work sample tests when LLMs are involved. Your questions will end up on LeetCode, where LLMs will index them and will be able to recite the answers.
- deleted 3y ago[deleted]
- sho_hn 3y ago> I don't think that LeetCode questions have any particular advantage over work sample tests when LLMs are involved. I agree. We do work sample tests, and in addition to the code and docs the candidates hand in, what really matters is the walkthroughs we do with them. Why did they do it that way? What alternatives did they consider? What are the pros and cons? What past projects did they draw on? How did they research this? Candidates usually enjoy this - most programmers enjoy talking about a just-finished project, especially when they feel good about the result - and you get to learn a lot about them. If someone turned in an LLM-assisted work and lied about it, I doubt they'd fare well. And if they did use LLM assist - could be an interesting conversation all the same. What did you reject? What did you correct? Why?
- returningfory2 3y agoThis is very interesting, thank you for sharing! I do have one tangential comment based on this: > I continued to use [the interview question] because I got good signal from the candidates. Working at Google, this is something I hear a lot: that some question, or other interview thing, is good for getting "signal" from candidates. But how do you actually know? Like, I feel to definitely know a question is good you would actually need to track candidates after they start working and see if their performance on the question correlates with their job performance. (Unfortunately, it seems impossible to track candidates who don't get an offer.)
- gwbas1c 3y agoI find that "good signal" is understanding a candidate's thought process and ability to intuit general programming concepts. These are hard to do if you think of an interview question like a high school quiz or a college final.
- behdad 3y agoThanks for the comment. By saying "I get good signal" I mean that it's not a binary yes/no, but gives a range to score the candidate. You are right about actual correlation to job performance. I know the HR at Google performed correlation analysis between interview scores and job performance and made internal observations, which as you note is biased because only includes hired candidates.
- seanhunter 3y agoMost people who say this think the question gives them a good ability to distinguish whether a candidate will be good if hired into a given role, however honestly mostly it gives them a good sense of whether they like the person and/or the person is like them. As an example, the author of TFA clearly is selecting for people who have the patience to sit around and be told how smart the author is. That is the signal in this “great interview question”: candidate will suck it up for hours while I tell them stuff.
- dilyevsky 3y agoAt google you used to see scores and feedback of everyone on the panel and whether hire/no hire decision was made by the Hiring Committee (which you otherwise didn't have any visibility into except sometimes they would leaver you feedback). You could also see your histogram of scores as well as other peoples' on the panel colored by recency and hiring decision which was very useful to calibrate your internal sense. Something so simple can go a long way and I haven't seen it in any of those crappy interviewing saas products out there. Did they scrap that system?
- agolio 3y ago> I then push them on this until they realize that any implementation of the dictionary lookup function of a string would be o(n) at best, and as such the total runtime of the solution is O(n²). Is that true? I am actually siding towards the candidates on this one presumably it would be O(n_words_in_dictionary) for the dictionary check, which as the number of words in the dictionary is constant, would make the overall algorithm O(n) ...
- behdad 3y agoYou still need to query every byte of the input string... Any better than that you can do would be O(min(n, k)) where k is the length of the longest word in the dictionary. But without loss of generality that would be O(n).
- agolio 3y agoGood point, though I guess the point of the disagreement is then for me that the question's "dictionary words" implies to me an english dictionary, rather than an abstract dictionary of words of potentially infinite length
- d1sxeyes 3y agoIt would be impossible to look up anything in a dictionary of infinite length. Therefore, either the question is nonsensical, or there must exist a word (or words) of a maximum length.
- light_hue_1 3y agoI don't think so. You take the first n bytes of your input string. You hash them. You look them up in the dictionary. The lookup is O(1) but hashing your input is O(n). But there's a simple way around this. We have incremental hash functions. When you add a byte to the string and you use an incremental hash, you do a fixed amount of extra work to update the hash. Like that you only need to O(1) extra work to compute the new hash. One trivial incremental hash is to break your input into fixed size chunks, hash each chunk, and xor the chunks together.
- jhp123 3y agocompiling the dictionary into a DFA would give you O(n) runtime.
- behdad 3y agoHow?
- jhp123 3y agouse a regex like (aardvark|apple|...|zebra)* and the standard DFA construction for regular expressions.
- behdad 3y agoYou are technically right. Though if we assume that the size of the dictionary is at least o(n), then the size of such DFA will be exponential in n, and indexing it will be o(n), resulting in a o(n^2) solution again, I think.
- deleted 3y ago[deleted]
- jhp123 3y agoThe number of states is exponential for a general regex. This regex has an NFA closely resembling the trie for the dictionary. There could be at most one live state per depth in the trie. So the number of possible states is bounded at least by (words in dictionary)^(length of longest word). Really much smaller because the states at different levels have to share prefixes.
- ghusbands 3y agoThey are completely correct. If the DFA fits in RAM, following state transitions will be O(1) and using the DFA for a concatenated string of length N will be O(N). You simply missed a good solution.
- bonzini 3y ago
- sverona 3y ago> I then push them on this until they realize that any implementation of the dictionary lookup function of a string would be o(n) at best, and as such the total runtime of the solution is O(n²). Is n the length of the word or the length of the dictionary? And if it's the length of the word (<< the length of the dictionary), why does it matter if it's linear or quadratic?
- behdad 3y agon is the length of the string. As for why it matters whether it's linear or quadratic, we are assessing the candidates ability to analyze a problem and possibly improve an algorithm. It might not matter in the problem at hand.
- sverona 3y agoOkay, yeah, that's fair.
- edflsafoiewq 3y agoSurely there is a longest word in the dictionary, so you can short circuit for any string longer than twice that. So an asymptotic analysis in the length of the string doesn't really make sense.
- jameshart 3y agoWe're assessing the candidates ability to do work that doesn't matter? This is a negative hiring signal you're looking for, right?
- languagehacker 3y agoI'm a big fan of trie-based interview questions because if an individual can call them out immediately, they know their data structures -- awesome. If they only know simple data structures, going from a hash to a hash of hashes is one of those "eureka" moments that can really shows how a candidate is willing to collaborate on a problem and react to new ideas. Heaps are an interesting data structure to use for interviewing, but I do find they can be a little less intuitive, and their use cases translate less directly to business logic and are more of an optimization task. It depends on what talents you're looking for on your team!
- activitypea 3y ago"A great interview question" for what? The author sings their praises, but never actually explains what this question is good at testing or what makes it worth an interviewer and candidate's time. Results might favor younger or earlier-in-career folks -- okay, why is that a good thing?
- musicale 3y agoYounger/earlier in career folks are usually cheaper, which companies like. Though I imagine they could just ask "when was your last algorithms course?" (and possibly where, and what grade you got) and save a lot of time. Or they could just ask "what year did you graduate from (whatever school level)?" But that wouldn't be as useful for making the candidate "jump through more hoops" and reinforcing compliance as well as status hierarchy - important things at most companies. And some people may have cheated their way through their algorithms class, so maybe they can be detected if it was recent enough.
- wackget 3y agoFor weeding out the people who haven't wasted weeks of their lives studying leetcode problems so they can get a job writing CSS. Duh.
- bruce343434 3y agoPretty sure this isn't the kind of question a frontend webdev would face.
- behdad 3y agoIt is true that many companies, Google included, have added area-specific questions including some for frontend webdev if I remember correctly.
- hgsgm 3y agoFor making the interview time fun for the interviewer.
- Ensorceled 3y agoA question I used for a number of years was a simple "compression" algorithm that would turn a string of lower case letters into a shorter string by length encoding using the capital equivalent: abbbbbcdddddde => aB5cD6e The number of developers who struggled or utterly failed with this was depressing.
- abtinf 3y agoThere are a finite number of words in the dictionary, which implies there is an upper bound in the length of words. The maximum number of iterations is the length of the longest word in the dictionary. This means that part 1 of the problem can be solved in O(1)+O(1). That doesn’t mean you will be happy with it. Not all O(1)s are equal.
- hhmc 3y agoSimilarly you can precompute a dictionary for the Cartesian product of the dictionary with itself, then lookup into that. Big in space but O(1) (wrt word len at least)
- abtinf 3y agoExcellent point. The only way to evaluate if this is a good or bad solution is the actual operational context. If you had a service that had to do millions of these matches per second with low latency, then this might be a reasonable solution.
- Herval_freire 3y agoThe interviewer is not thinking logically. How does he know it's a good interview problem? Let's look at the data: >The fastest I had a candidate solve the entirety of the problem with all bells and whistles was in 20 minutes, by a freshman from the University of Waterloo, the type who did high-school competitions. >The most depressing failure I saw was a PhD graduate from University of Toronto who could not produce working code for the first section of the problem in 45 minutes. >I once had a candidate with 15-years work experience give me lots of attitude for asking them such a simple question, while at the same time struggling at it. All of this data points to the fact that this question may not be good. A phd graduate and a person with 15 years of experience rejected for someone who practices programming for competitions? What gets me is that the data is painting an obvious picture here. A very obvious picture. An obvious picture that we aren't sure what's a good interview and a bad interview question. But the problem is that most people when looking at this completely miss it. It's not obvious to the interviewer and it's not obvious to alot of people who like google style questions. We literally have not much data and not much science backing any of this up. It's an illustration of how biased humans are and illustration of how extra biased interviewing for software positions is. If there's anything more unknowingly biased and then the replication crisis in science it's technical interviews for companies. There needs to be real feedback loops that correlate interview question passing with Actual performance. Google is in a good position to grab this data but I'm not sure they are doing so given how they just okayed this guys gut decision to go against the grain and use this question. I'm not against this question, but certainly to call this great in the face of controversial data that he himself gathered and listed on his post is just a complete blueprint of the extent of human blindness. The reality of what's going on here is the person here in the interview is just getting off on dominating other people with a hard question. It's not on purpose but he's doing it without realizing it. The blog post in itself is a bit showy. It's like "I can answer this question but a phd graduate can't".
- abtinf 3y agoAs a hiring manager, I’ve noticed most peer hiring managers vastly overestimate their ability to hire. What I’ve seen happen is that there are two narratives they flip on: I hired this great person and they are doing amazing so I am amazing; I hired this person and they aren’t doing great so I fired them so I am amazing. Of course, they also tend to be terrible at assessing who is actually good/bad. I call it the “arbitrary onion”: layer after layer of plausible claims that each turn out to be just as arbitrary as the outer claim.
- texuf 3y agoI guess I’ve always been confused by this question. If the dictionary isn’t infinitely large, and you have plenty of space, why can’t you put the dictionary in a Set and look up words in O(1), reducing the overall complexity to O(n)? Obviously hashing has its limitations, but i thought we could hand wave over that part. If we’re limited by space can we assume that the dictionary is ordered and make the lookup in log(n) via a simple binary search? Or are we obsessing over the string equality operation? I feel like I’m missing something.
- behdad 3y agoYes, the string equality itself is o(n).
- elijaht 3y agoYea, I dislike it (a bit) for that reason. The "meme" in leetcode interviews is that "hashmap lookup is O(1)". It does feel like a bit of a gotcha to (correctly, mind you) expect an answer of O(n) for the lookup. That being said, I think you could get around this with careful prompting (ie, ask first "what is the Big-O for dictionary lookup with the respect to the number of letters" before asking the overall big O). But I think there is a bit too much wiggle room to make this a completely consistent question, too much variance candidate to candidate. I like the problem a lot, but wouldn't feel comfortable using it.
- texuf 3y agoBecause the author didn’t bother to explain that this is what she’s looking for in a well thought out blog post, I assume she also didn’t explain this is what she was looking for in the interview, leaving a lot of candidates who didn’t have the same educational background floundering.
- jameshart 3y agoIn general, hash map lookups are considered O(1) in the size of the hash map. Which is not the n the author is using, to begin with. But. Hashmap lookups require calculation of a hash of the key. Calculating the hash of a key requires examining all of the bits in the key. If the keys are int32s, then the hash algorithm has to read 32 bits. If they're int64s, then the hash algorithm has to read 64 bits. And if your hash map contains n distinct values, then at a minimum they must be drawn from a key space where each key contains O(log n) bits. If you want a hash map to contain more than a few billion values, you'll need bigger-than int32-sized keys to distinguish them, right? So for any hashmap of size n, that means there's an O(log n) hash calculation in there. (especially when we are considering the asymptotic case where the hash map grows infinitely large... such hash maps will necessarily have infinitely long keys, too) Yet we call hash map lookups O(1). Because in practice we imagine a hash map has a key space of a fixed size (even though such a constraint would mean that the hash map has a fixed maximum size and therefore no asymptotic performance case since it can't scale to infinity). By playing around with big-O on hash table lookups with keys of size n, the interviewer is skating dangerously close to this contradiction at the heart of big-O analysis of hashmaps... But unnecessarily so, since the key space they're using is dictionary words, which have a maximum length, so their length isn't the n you're looking for. (Note - for the same reason, big-O analyses of sorting algorithms don't usually take an extra O(log n) factor (in n being the size of the valuespace) for the time it takes to compare entries, even though obviously it takes 'longer' to compare two 64bit numbers for size than two 32bit numbers. Is it a hand wave? Probably not when you're dealing with numbers. Maybe when you're dealing with strings)
- jacknews 3y agoWhat kind of programming will be done on the job by these candidates? Probably nothing like this puzzle. This kind of 'let's watch people struggle with my favourite LC puzzle, which I think I know inside-out' just seems very inconsistent, not very predictive, and just quite flaky to me. On the job, my very first response to any kind of problem that looks algorithmic is to google the hell out of it, even if I think I know the answer already. In future, it will be to get gpt to write it. I think the actual challenges in real-world software are not algorithmic, but architectural and beyond, and then only after thoroughly understanding the problem in the first place.
- bruce343434 3y agoI can't believe what I'm reading here. Architecture goes hand in hand with which datastructures and algorithms you "unlock". How exactly do you define "Architecture"?
- roflyear 3y agoI think it makes sense. You don't need to be familiar with every data structure to research them.
- andreareina 3y agoIn the small vs in the large. How are responsibilities split up along the modules? Are there layering violations? Is the right problem even being solved, or is there maybe a way to avoid the "is this a concatenation of two words" check altogether?
- PeterisP 3y agoI would define "architecture" (as it appears in applied software development) as working on the structure and interaction of system components much larger than a single data structure or a single algorithm; where many of those components might be separate systems themselves. When "architecture" handles specific data representations, it's usually talking about the data representation and encoding at some API or "API-like" (e.g. file, message, etc) interface between two systems or persistent storage, not about the temporary representation of that data during some processing; and "architecture" is generally much more about the semantics of that data and possibly differing assumptions/expectations about that data between different components, rather than the performance characteristics of that representation for a particular algorithm except in the relatively rare case when a single algorithm represents the majority of that system's purpose and performance.
- yumraj 3y agoMaybe surprisingly, junior candidates sometimes rank better at this problem because their Data Structure & Algorithms knowledge is more fresh. Isn't that in itself is a flag that this is in fact not a great interview question, unless it's being used for hiring candidates fresh out of college, say during campus interviews.
- behdad 3y agoI expect any candidate to be hired to be able to produce code for the brute-force cases, and do the runtime analysis on them. It's a whole other debate that most software engineers, even at BigCo end up writing CSS code to move pixels only and lose their DSA knowledge over time...
- mattkrause 3y agoThat’s probably also what happened with your ‘disappointing’ PhD student. They probably did know how to code, but they’ve spent the last 5 years working on something quite a bit different from string wrangling in Python. Add in the stress of a (first-time?) interview and a reasonable candidate can look like a total fool…
- jonstewart 3y agoIt's fair to expect any candidate to hire to produce the brute-force code and do some rudimentary/rough analysis. That's not why it's a bad question. It's a bad question because _how well_ a candidate does past that minimum threshold has _no correlation_ with their ability to do the job. You can treat it as a binary question for that minimum floor. To use it for rating, you're doing your org and the candidate a disservice and you're wasting interviewing time that could be spent more productively and humanely.
- Aperocky 3y ago> even at BigCo end up writing CSS code to move pixels only Is this common at Google? If by DSA knowledge you mean leetcode puzzle knowledge, yes, quite certainly. But from my experience fresh grads are less effective engineers before they mature by working with industry scale systems for a few years. And at that point they would have been less able to do your problem but a far better engineer. Which means your interview question is aimed backwards, maybe if you only used it against fresh college grads then the gain function would be positive, but you applied it against everyone.
- jordanmorgan10 3y ago“I then ask the candidate to analyze the running time of this solution.” Annnnnnnnd I’m out.
- meisel 3y agoDynamic programming problems are banned at a number of companies, and with good reason. Candidates ability to do well on them is largely a function of how much they’ve practiced those problems. I’ve never needed to do dynamic programming with caching of recursive overlapping sub problems ever, and only learned it recently during interview practice.
- ttoinou 3y agoSome come up with a greedy algorithm which finds the first prefix that is in the dictionary, and then returns whether the rest of the string is in the dictionary I would do that straight away. I don't see the point of implementing the more complex and longer to code "double dictionary checking for all partitions of the string"
- behdad 3y agoConsider the string "thereis", and the dictionary {"there", "is"}. The greedy algorithm fails.
- behdad 3y agoMy bad. The dictionary should be {"the", "there", "is"}.
- whiddershins 3y agoI am now getting that I didn’t understand what you meant by greedy.
- ttoinou 3y agoOh yeah makes sense, if we don't do that the greedy way we could simply continue the search if it hasn't been found. That's what I would have done
- deleted 3y ago[deleted]
- catchnear4321 3y ago20m as the record seems pretty dubious. sure, some will trip over themselves. 20m was the best? poor screener?
- im_down_w_otp 3y agoI've never seen this problem before and arrived at the optimal solution to the first section, sans code, in about 10 seconds. Despite that, there's almost no way I would pass a technical interview at Google. The only reason I can think that the optimal solution was immediately obvious to me is perhaps because in a previous life I did a lot of work building convoluted application specific indexing schemes for data in a distributed KV store that had basically zero useful built-in secondary indexing schemes where piles of parallel GETs were about as "free" as just doing one, but chaining strings of requests back & forth to the client iteratively made for sad times. This meant that it was essential to be clever about what could be coded into key names and precomputed from application/use-case context to know what keys to fetch "all at once" to gather as much relevant data as possible with as few serially dependent requests as possible. One such use case depended on a modified C-trie as part of the solution, so I got very familiar with what kinds of problems they're for and what their limitations are. Given that, I can't tell what that says about the question, about me, or about Google. What I can say for sure is that because I can't tell the above, the technical interview at my company is signing an NDA and sitting down for a couple hours and just actively pairing on real work & real problems with real teammates. With the nature of software development work being what it is, I really don't understand why we as an industry run interviews like they're game shows or try to manufacture workplace simulators with terrible model conformance.
- haskellandchill 3y ago> Despite that, there's almost no way I would pass a technical interview at Google. You could get lucky and have each question have a similar relationship to past knowledge. It's happened to me before, I blew through an Amazon interview once that way, but got knocked for technical leadership. So maybe you mean something like that, but that too is random. I had passed the leadership but failed the algorithms at Amazon a few years prior. > I really don't understand why we as an industry run interviews like they're game shows or try to manufacture workplace simulators with terrible model conformance. I believe these tests are more about compliance and baseline cognitive ability than anything else, which is good for the nature of the FAANG role. They are testing that you are willing to study what they tell you and that you are able to retain material of that level of difficultly and demonstrate that in an adversarial situation.
- sozin 3y agoThis interview question is good for kids recently out of school, but for everyone else I think it doesn’t really show if the candidate is a good developer. Good taste — writing cohesive, loosely coupled code with a sensible bank of unit tests an a strong dose of product sensibility — is largely orthogonal to being good at solving algorithmic or ds questions. One of the best developers I know, who makes seven figures a year a year (trading software), would likely bomb the second part of this question. Contrawise, a young researcher I know who has won multiple scholastic programming competitions and crushes leet code, would destroy this problem in seconds … and yet, I pity his coworkers who have to live with his atrocious code. More accurately, he would first look at the interviewer like he was a dolt, and then bomb the question :)
- dccoolgai 3y agoI hate this industry so much. I know what a trie is, but having it dangled over my head by some smarmy git like this: Just the thought of it fills me with so much sadness. These "Junior year computer science problems" just make me so angry even reading about them. I'll start interviewing in a year or so, it just fills me with despair knowing this is what I'll face when I do.
- famahar 3y agoBeen at it for the past 3 months. It is soul crushing and demoralizing. I'm starting to accept that I would rather work in a toxic company than have to go back job searching.
- haskellandchill 3y agoIs it really that bad? I've taken the time to go back to some great books I never got a chance to fully study, like Udi Manber's Introduction to Algorithms and Jeff Erickson's Algorithms and even found some new gems like Guide to Competitive Programming and Competitive Programming 4 Book 1.
- pcthrowaway 3y agoI don't know if this is sarcasm or not, but in case you're serious. The fact that you feel the need to approach this like you're a gladiator preparing for mortal combat in the arena of the mind, is really not OK. Our industry's interviews shouldn't be like this
- haskellandchill 3y agoI used to feel that way but I'm older now and I don't have the energy to fight it. Plus I enjoy studying algorithms so I'm making it work for me.
- asynchronous 3y ago
- jameshart 3y agoI'm sorry, but this mainly reads like the signal you'll get from running through this script is learning whether or not this candidate enjoys being walked through how clever you are. That might be something you are looking for in a member of your team, but it's not a great indicator that they'll bring much additional shareholder value.
- wpietri 3y agoYeah. I'm much more interested in discovering an interview subject's strengths, so I tend to give broad things that can be solved many ways. One interview I had years ago that I really liked was where they gave a sample of code with a number of issues and asked me to describe how I'd improve it. I really appreciated that a) it was much more like actual work than many questions, b) you could start with obvious things and work deeper, and c) there were many valid ways to improve the code, so you weren't just trying to guess the answer the interviewer had in mind.
- timv 3y agoDo you have a reason to believe (c) is true in practice? I strongly suspect many interviewers (myself included) would have a few "top issues" and significantly favour candidates who pointed them out. But as the candidate you don't really know which issues will seem important to the interviewer. It's not an irrelevant exercise though - code reviews are a real part of many roles and making sensible choices about what to comment on is a necessary skill. But it is hard to avoid turning the interview into an exercise in "guess what's on the top of my list"
- wpietri 3y agoThe first part of (c) is true, so I guess you're asking about how the interviewers would react? These folks were obviously interested in differing approaches; we had a good conversation about it. And that's how I use broad questions. But I agree a huge problem of interviews is the "guess what I'm thinking" interviewer. Most interviewing processes are not primarily about making good hires. They're about making interviewers feel smart and important.
- rvba 3y agoWhat does the dot mean in O(n.2^n)?
- behdad 3y agoMultiplication.
- famahar 3y agoWhy not just give them a small (1 hour max) take home assignment with your tech stack, and then have have them talk through their approach in a follow up interview. You can test for all these things in their implementation while giving the interviewer time to think and breath.
- rendall 3y agoIf the test is open ended like "implement a simple API and a client that accesses it" then it's a terrible test. Tests that are better the more time you put into it are always terrible take home tests. If it has well-defined success state then it's maybe OK "implement a maze-solving algorithm for a 3^n cube". If there are implementation tests that the candidate can use, even better
- robmccoll 3y agoThe best interview question I've ever heard: Someone is sitting shopping online with their cursor hovering over "Add to Cart". From the moment they physically click on it to the moment the page refreshes, tell me everything you can think of that happens. Responses are awesome because it gives you an idea of what this person's background is and what breadth of knowledge they have and what they think is cool or exciting. Maybe they start with a contact closing and signals being denounced, or an interrupt being triggered, or the OS and window manager, or the browser and DOM events, or HTTP or TLS or TCP or Ethernet or WiFi or LTE or routing and the tiers of network infrastructure or DNS or load balancing or proxies or web servers and tiers of API services or databases... It's can lead to some really fun technical conversation, follow up about how they learned the things they know and experiences they've had, and most of the time the interviewer learns something too.
- Aeolun 3y agoOh shit, this one is really nice. I’ll add that one to the list.
- pcthrowaway 3y agoI like that, but does the "to the moment the page refereshes" part mean it'd definitely not a SPA?
- deleted 3y ago[deleted]
- robmccoll 3y agoGood question - and one that tells me something. You're familiar with modern front-end development and that's something we can dig into. Why would you want to avoid full page refresh? When would I use a SPA versus more traditional SSR? What about serving something mostly static with progressive enhancement? What frameworks might you consider for developing such a SPA? Which have you worked with in the past? What did you like about them? Any you're looking to work with in the future? How do these frameworks work - i.e. are you someone that hacks on them and is concerned with shadow DOM and optimizing diffs and re-rendering and data binding... That's why I really like this question - it's just such a cool jumping off point.
- ww520 3y agoWhile the interview question is a fun exercise, the complexity analysis presented is wrong. For part 1 using a hashtable to look up the dictionary words, the complexity is not O(n^2) where n is the length of the input string. It should be O(w^2) where w is the length of the longest word in the dictionary. The hash key material of the dictionary words has at most w characters. When computing the hash key for the input string, it can be truncated at w, as any longer input won't lead to a hash key making a match in the hashtable. For part 1 using a trie, the complexity is O(w) rather than O(n). This is actually more obvious since walking down a trie tree will stop at the last character of a dictionary word. Again for part2, the complexity is O(w 2^n) using bruteforce with hashtable, O(w^2 n) using DP with hashtable, and O(w n) using DP with trie. Edit: Also for short strings like dictionary words, O(w) is kind of meanless since with SIMD or SWAR the short word can be folded into one or two DWORD. You can effectively treat it as O(1).
- behdad 3y agoYou are absolutely right. I should have been more clear about the dictionary size being large compared to n, and similar about the length of the longest word in it for all my analysis to follow.
- ww520 3y agoAlso, while trie looks better on paper than hashtable in regarding to complexity analysis, in reality hashtable can be 2X~3X faster than trie. This is because the hash key can be computed very fast with the key data fitted in a L1 cache line and with much less branching jumps in the hashing function, while trie does a separate memory load on each node going down the tree plus each character comparison causes a branching jump. It's always good to benchmark before settling on a scheme.
- kolbe 3y agoBoth of your answers in this thread are great, but it doesn't sound like what behdad was looking for. I think the unfortunate reality is that you're supposed to try to figure out what he wants to hear, which is that his answer is the most correct one in his mind to this awesome question that's so great he violates his company's rules in order to keep asking it. This just lead to cheating, where a smart person with connections learns from a friend what behdad wants to hear, and is able to give it to him, while people who don't have these connections give a more correct answer like yours and get rejected.
- tracerbulletx 3y agoThat's so weird, my great interview question is "Do you just make up self aggrandizing claims about how great your interview questions are, or do you have some kind of empirical basis for it?". And if you don't do well on it then I write a blog article to make fun of you for being an unscientific engineer who can not possibly be fit to work at the same internet advertising business as me.
- solarkraft 3y agoI'm not at all a fan of gotcha puzzles, but I tend to think this is not one, at least not purely. It allows you to judge quite a broad range of problem solving approaches. You can argue about this puzzle not being relevant to a developer's day job and there's certainly merit to that, however I would argue that the part about realizing that the badly performing brute force approach is allowed is very relevant. The performance analysis and optimization maybe not in so much detail, though having a rough grasp of it been also be useful when there are concrete performance issues (but let's be honest: you can spend a lot of time without running into them). I found one sentence very interesting: > Moreover, the problem as I present it, has enough range to sift out bad candidates from good ones even if the candidates have seen the problem before, which is why I successfully used it even though it was banned at Google. How do you measure the question's success? Is there some kind of feedback you get about how the person you made a decision about went on to perform? What about the people that ended up not being hired?
- behdad 3y ago> How do you measure the question's success? Is there some kind of feedback you get about how the person you made a decision about went on to perform? Not the latter. However, there are five interviews that each candidate goes through, and as an interviewer you get to read the interview feedback written by the other interviewers as well. So I can compare my assessment of a candidate against four other interviewers' assessment using their questions and feedback notes and rating assigned.
- lamontcg 3y ago> The fastest I had a candidate solve the entirety of the problem with all bells and whistles was in 20 minutes, by a freshman from the University of Waterloo, the type who did high-school competitions. That is who you're optimizing for.
- qwerty3344 3y agoYep this is what most data structures and algo questions optimize for.
- glitchc 3y agoIt is indeed telling that experience does not help with this question. It's a toy problem with no real consequences.
- behdad 3y agoAs someone who actually uses algorithms and data-structures in their job, I disagree.
- the_af 3y agoI think both things can be true. These are valuable skills in some situations/jobs and you're selecting for students with these concepts still fresh in their minds and/or people who enjoy algorithm competitions. And that's fine! A specialized subset of engineers. Maybe that subset is exactly what you need. I wonder how the stress of the interview process selects out people who understand O-notation and to whom a Trie would make sense if explained to them, vs people who have these concepts fresh in their minds and/or can handle themselves in stressful interview situations.
- dclowd9901 3y agoThe author, everyone.
- nitwit005 3y agoYou did emphasize it was the best result, so it's hard to argue that you selected for it. Back in 2015 Peter Norvig discussed an analysis at Google that suggested doing well at coding contests was a negative indicator of job performance: https://youtu.be/DdmyUZCl75s https://youtu.be/DdmyUZCl75s Presumably they do well at these sorts of questions, but that doesn't imply the same actual effectiveness.
- cgio 3y agoMy one interview question (I have a series of related but only go down them selectively) is “tell me the one thing you’ve done that made you the proudest of what you have achieved or the happiest with what you were doing, don’t worry whether it was the most impactful or important from an outsider’s perspective”. I am trying to give people the chance to show me the best they have, not a competition for me to prove myself I am better somehow. You will be surprised how many interesting discussions and learning opportunities I got out of this question. Everyone who has peered interviewed with me ends up using it in their future interviews.
- behdad 3y agoThanks. That's definitely an interesting question. How does it do with new grads? How do you grade people on that on a numerical scale? Curious.
- roflyear 3y agoPeople's experience can never be boiled down to a number.
- cgio 3y agoIt does not work very well for new grads. In grads case I question the purpose of interviewing at large. They studied, completed one goal, all we have to do is give them the tools to understand their next steps. With grads I focus more on their interests, what they are reading on the subject matter domain (data in my case), etc. There’s no really silver bullet and the value of this question even with experienced hires is the follow up where you drill down on technical and behavioural elements of what made this project/product the one they chose to discuss. No numerical scale, you either want someone in your team, or not.
- yarg 3y agoYes I can solve the question, give me a functional laptop and go away for an hour.
- the_af 3y agoI think this is a reasonable question, probably better for students who still remember their O's and Tries but reasonable enough for the intermediate quality solution -- an engineer who cannot even solve the simpler version probably cannot write algorithms at all. That said, from the article this article links to, I find this puzzling: > The candidate’s performance on the problem isn’t binary. The worst candidates don’t even manage to implement the fizzbuzz solution in 45 minutes. The best implement a memoized solution in 10 minutes, allowing you to make the problem even more interesting, e.g., asking how they would handle a dictionary too large to fit in main memory. Most candidates perform somewhere in the middle. Two things I worry about: if the interview isn't "binary", how do you decide whether the candidate passed? Is doing just the simpler version fine as long as you ask for low pay? Or are you still failed? Or does it depend on whether other candidates did better, which is another way of saying you failed? It seems to me it's still binary. And the other thing is: if the candidate did great in 10', please don't ask additional questions. The candidate is a "hire". Don't make it "interesting", an interview is not the place to shake things up to make it "interesting". Understand that for most people, interviewing is a stressful situation. For "interesting" times they have their friends and Netflix.
- behdad 3y agoTypically candidates are scored on a scale. And there are multiple interviews. The final hire / no-hire is decided based on the scores and written feedback from all interviews.
- the_af 3y agoThanks for the answer. Realistically, what are the chances of someone who solved everything up to the half-way point?
- behdad 3y agoMy mid-mark would be where someone could write the code for the brute-force answer for both parts but couldn't get the memoize / dynamic-programming solution. That would be where I'd say "I'm not sure, look at other interviews". Otherwise I'll make a hire / no-hire recommendation.
- dclowd9901 3y ago> Maybe surprisingly, junior candidates sometimes rank better at this problem because their Data Structure & Algorithms knowledge is more fresh. But this pattern is not universal. Good senior candidates have no problem with the interview at all. You’ve already lost me, dude. If the question can’t meaningfully differentiate between a junior and a high level senior, it’s a trash question.
- behdad 3y agoYou'd be surprised.. but we're trying to distinguish between someone who can code simple algorithms versus one who can't.
- bluepizza 3y agoNo, you are not. You have a terribly unbalanced expectation that someone who was just presented with this question will achieve the same depth that you have. But you have been on this question for a long time now, know it deeply, and from the comments on this thread, you still got half of it wrong anyway.
- bonzini 3y agoYou can differentiate between a junior and a high level senior by reading their CV, the point of the interviews is to probe everything else about them.
- angarg12 3y agoI've asked variants of this question before, and although it is kind of good *for it's kind*, it's still a sort of algo leetcode-style question. Actually the best questions I ask, and the ones that give me the best candidate "signal" are what I call the "clean code" style questions (as in code that is simple, easy to extend, not necessarily Uncle Bob Clean Code). I'd rather not post examples here because I still use these questions, but the theme is as follows: * These questions ask to implement functionality that you could see in a (super simple) real world application. * They start super simple, and include several follow ups that increase in complexity. * No data structures and algos beyond the basics. Loops, lists, hash maps and little else. What most programmers would use on the job on a daily basis. I found in practice these work really well, specially with experienced programmers who can flex their low level design skills. People who ace leetcode style questions tend to do worse here, but no wonder, since they've been trained in a complete different style of interview.
- whycreatewhynot 3y agoInterviewing is a dark art. Does anyone really do it well? Does anyone really spend the time to do it well?
- kwillets 3y agoGood news: There's probably a linear time solution to all the versions of the problem presented. Bad news: You have to walk this stable genius through 50 years of Suffix Tree and constant time LCA algorithms in 20 minutes.
- zabzonk 3y agoi did not usually ask simple algorithmic questions like this. if i was (am retired) i would typically ask questions about the languages we were using. in my case this would typically be c++ and sql. so i would normally ask things like: "tell me something about the copy constructor" or: "when would you want to do a union?" amazing how many people were dumbfounded by these. and notice, no leetcode crap needed.
- 1letterunixname 3y agoIgnore this author and everything they say because it's total crap. Unless you're an insecure, narcissistic engineer who feels "smarter" than everyone else or a cargo cult follower of some business fad, there are no magic questions to instantly separate "good" candidates from "bad." You discover good engineers by whiteboarding and working on challenging problems together than can possibly turn into real commits. Ego and solving manhole cover problems doesn't delver good commits.
- saagarjha 3y agoI definitely wouldn’t ignore everything they say.
- 1letterunixname 3y agoYou're splitting hairs. They're a source of negative value. Anyone with any sense doesn't need anything they have to offer.
- account4mypc 3y agoEven if this is true, it's kind of useless since you need some way to decide who to hire. Not saying i think OP has the best method.
- wiseowise 3y agoFunny how you’re quick to label them > Unless you're an insecure, narcissistic engineer who feels "smarter" than everyone else or a cargo cult follower of some business fad, there are no magic questions to instantly separate "good" candidates from "bad." without taking a moment to actually think why these type of interviews exist. > You discover good engineers by whiteboarding and working on challenging problems together than can possibly turn into real commits. Ego and solving manhole cover problems doesn't delver good commits. You think everybody got time for that? Maybe in your company you get one or two CVS, but when you have 30 it’s impossible to conduct thorough testing. You optimize for false negatives.
- cgearhart 3y agoThis is not a great interview question. It’s not even a good interview question. It barely evaluates any technical abilities and it ignores most technical abilities that matter. This question could be improved as follows: * present the naive solution. Explain that this is a PR that was submitted in 20 minutes by our new intern from Waterloo. Ask them to help improve it. * suggest to them the intern’s argument why the lookup is O(1) and explain that it’s actually O(n). Ask them to write a PR comment to break the news to the intern. * explain the optimal solution with tries. Ask what happens if the vocabulary is big enough—and the prod environment is resource constrained—so that the trie is rarely in memory when the function is called. How would the trie solution compare to a binary search through a length normalized list of words? This kind of question is barely useful to interview new hires—when you still may have basic questions about how much undergrad material “stuck”. Within a few years when they hit full-performance level you should care much less about this kind of question and much more about “higher order” thinking about engineering. How do you communicate bad news? How do you identify, communicate, and mitigate risk? How do you plan large tasks at at appropriate level without over engineering the solution? What questions should you ask at different project stages to capture the right requirements, anticipate issues, and successfully execute over time? But whatever, I’m sure you get lots of signal out of repeating “a hash table lookup is O(1)” “nuh uh” on loop for 10 years. :eyeroll:
- pavlov 3y agoFor the past decade Google has seemed like a deer in headlights, unable to move in any direction, failing at introducing new products, now getting crushed on AI. Maybe the problem has something to do with the way they hire. The article mentions that this string-processing problem had to be approved by a committee: ”Twice I asked the hiring committee if I should stop using this and they had no problem with it.” Not even the Soviet Union had a process where job interview questions were regularly approved by a committee. The level of bureaucracy in administering these brain puzzles at mass scale is absurd. The article mentions that the candidate who did best on this question was “the type who did high-school competitions.” I wonder if anyone stopped at any point to question whether that’s the ideal type of hire.
- 3y ago
- whiddershins 3y agoI don’t understand why the greedy solution is wrong. How can a word be the combination of two words if the first word isn’t a word? So, for example, if the first letter isn’t A or I, we can stop doing lookups for any combination of just a single letter and the remainder of the word. Etc.
- behdad 3y agoImagine the string "there is", and the dictionary {"the", "there", "is"}.
- whiddershins 3y agoT isn’t a word, next Th isn’t a word, next The is a word, look up ‘reis’, not a word, next Ther isn’t a word, next There is a word, look up ‘is’ it is a word, return true If you don’t want to ignore whitespace, than I’m not sure what behavior you want, you want “there is” to return false? If whitespace is the delimiter the whole thing is trivial, you split on space. I am now more confused.
- the_af 3y ago> The is a word, look up ‘reis’, not a word, next This is where the wrong greedy solution from TFA, which the author claims some candidates reach, stops. So it's wrong. Note that if you do not stop, and continue as in your own example, your solution isn't "greedy"!
- behdad 3y agoThat is a correct solution. The one I was talking about would stop after just trying "The" and "reis".
- whiddershins 3y agoOk
- 3y ago
- schmookeeg 3y agoI wonder how many engineers who passed this "great interview question" went on to solve CSS compatibility riddles for their career, doing so in O(nobody cares) time. Fun write-up though. The comment saying this optimizes for clever freshmen is spot on in my book.
- asynchronous 3y agoThis hits especially when a huge amount of my day I spend changing a CSS variable by some small increment then watching the fast-refresh show me if it meets spec now.
- lamontcg 3y agoYou know in my professional career mostly the way I approach these kinds of problems it to just cheat. What is the runtime complexity of an algorithm? Set it up with varying amounts of data fed to it (or whatever N is) and then time the real thing (or a suitable minimal but complete example). Then you can instrument or profile the algorithm in any number of different ways to ask what is being called so often. If you do it right you can really measure what it is doing, and you're getting closer at least to "production" code where you're not just working with pencil and paper but you've got real algorithms running hardware with finite sized caches. Ultimately it doesn't matter what anyone writes down on pencil and paper if the hardware doesn't agree with you. Usually I measure it first and then work backwards knowing the answer already.
- seanhunter 3y agoThe part that’s really depressing about this article is it’s really clear that the interviewer has one golden path that the candidate has to walk in order to be ordained as meeting the bar. Any question like that is intrinsically bad in my view. As a sidebar note, while the time complexity reasoning is important and is part of day to day life writing software this algorithm is unlike anything I have ever actually done as a software engineer. That would be a warning sign to me if I was thinking of using this question that maybe it’s not actually going to evaluate skills relevant to the role but rather test leetcode. Good questions allow multiple possible solutions[1], allowing a candidate to arrive at a successful solution via many different paths while still evaluating whether they are going to be able to perform well at the job. I don’t think this question comes close to meeting that standard. [1] By which I mean fundamentally different approaches rather than syntactic variants on the same basic thing
- steve76 3y ago[dead]
- sashank_1509 3y agoWhy does a dictionary require O(n) lookup for strings. Is there some CS knowledge I’m missing here?
- behdad 3y agoAssuming that the dictionary is arbitrary as well, just comparing the string to the strings in the dictionary (or hashing it) it takes O(n), regardless of the data-structure you use.
- fenomas 3y agoIs that relevant to real-world use? You mention Python in TFA - I'm no expert but I believe it does string interning, and caches the results of string hashes, which would suggest real-world performance should be constant over time in both cases.
- seanhunter 3y agon is the number of characters in the string in this case. If you had a function that could turn a string into a hash key in O(1) then you could look that key up in a hash in O(1). However, you need to go through the string one character at a time[1] so you can’t. This is exactly why tries/prefix trees exist (although they aren’t only relevant for strings). [1] This seems to me to be a practical limitation rather than theoretical given strings and numbers are really equivalent - it’s just that the space is mindbogglingly huge so if you wanted to do a general purpose O(1) string to number conversion it would require uncountably infinite space.
- squeaky-clean 3y ago> They mostly suggest that if implemented as a hash function, it would be O(1) lookup. I then push them on this until they realize that any implementation of the dictionary lookup function of a string would be o(n) at best, and as such the total runtime of the solution is O(n²). This seems pretty nitpicky, especially considering we're assuming substring creation is O(1). And isn't a hash table lookup of a string O(n) at worst, not at best? And since this seems like a fixed dictionary, we're only doing queries not insertions, couldn't you just choose a different hashtable algorithm like dynamic perfect hashing to guarantee O(1) lookups? I also don't like how it starts off with the dictionary being a blackbox style function, and a later part of the question requires you to change the internals of this dictionary query function. My very first thought would be about the structure of the dictionary query. And then when told to ignore that, I would assume that's still the case when asking to later optimize the algorithm.
- deleted 3y ago[deleted]
- andrewstuart 3y agoA great interview question is: “Tell me about a software project you played a significant role in. What did it do, how did it work, who made the tech choices, what was your role in it, what went right, what went wrong, if you were to rebuild it what would you do differently, what did you learn?” I know it’s really a lot of questions but it’s still just one in a way “talk to me, in a free form back and forth way about software development”.
- behdad 3y agoHow does that work with new grads?
- andrewstuart 3y agoGrads have written software. If a grad has written no software, or has no capacity to talk software development with you, then the interview is over.
- yosito 3y agoThere's no rule saying you need to hire new grads. I'd even suggest that if you care about hiring "the best engineers", hiring new grads is just idiotic.
- wiseowise 3y agoOne of the counter-points of original question is that it is hostile to people with experience, aka didn’t do much also since uni, now you’re hostile against new grads.
- rendall 3y agoWhile I do think it's a great interview question, I do think all technical candidacy flows where the person will be programming must have a coding component of some kind. Even just "FizzBuzz" is better than no coding. That said, I do think it's best to have the person relaxed and at their best, so anything to minimize stress or discomfort will show candidates at their best.
- nevster 3y agoWe do an even easier question - "Pretend I'm the client and I want you to write a method - Given a List of strings, write a method to concatenate them together with a space in-between." For starters, it's staggering how many people can't do it. But also, it's a great question because it's simple enough that you don't have to be clever but you can get a feeling for all sorts of things. Do they ask questions? Any questions? What possible inputs might cause problems? What do they name their method? What tests do they write? (Project is set up already with an example test class ready to go.) Etc etc
- grumpy_coder 3y agoIf the interviewer knowingly used a banned question for years could they be sued by candidates?
- dewey 3y agoSued for what exactly? Using a question where the company internally decided to not use it anymore isn't against any law.
- b20000 3y agothis article shows everything that is wrong with using coding interviews to screen people
- yosito 3y agoI hope you're not hiring UI developers. If so, this is the completely wrong criteria to evaluate them on.
- peteforde 3y agoI've hired close to 100 developers across three companies that I started, and it has never occurred to me to compel a candidate to regurgitate memorized algorithms in an awkward, stressful moment because that doesn't test anything close to what they will actually do in a typical day. Key point: I've never met anyone in the industry whose job it is to implement algorithms without reference materials all day long. It's more like... you might find yourself needing 1-2 clever bits a year, and the rest of the time you're tweaking model classes and hunting down UI bugs. Algorithms are both easy to Google and these days, CoPilot will do the hard 4/5ths for you if you actually need them. It's also common that the really intense stuff is written by the PhD braintrust cofounder, not the people being hired after the fact. What I want to know when I'm interviewing is simple: how do you approach solving problems; do you have an interesting personality that I'd like to interact with every day; are you the sort of person who has a strong instinct about what the next thing to do is, and will default to working on that thing without prompting? Do you think learning new things is exciting? Are you able to admit you don't know something and do you feel comfortable asking for help when you're stuck? Do you seem reliable? Are you a starter, a finisher or both? Do you have a sense of humour? What do you do on the weekend? Ultimately, I care what you know... but I am far more interested in your capacity to quickly master new things.
- skatanski 3y agoAgreed. Its often easier to teach someone a technical skill, but impossible to change them, if their personality is not a good fit. If they have a tendency to be passive-aggressive or have a code related ocd. Not saying its easy to recognize these characteristics during an interview. I had much more trouble with poor communication skills, rather than lack of technical prowess.
- isaacremuant 3y agoAgree with everything but this: > Do you have a sense of humour? What do you do on the weekend? It's none of your business what I do on the weekend. It doesn't need to be similar to what you do. Otherwise you'll tend to only hire people like you and reduce the pool of talent because you can only work with a very specific type of people.
- sureglymop 3y agoSeems like a terrible interview question. The candidate either already knows it or will struggle...
- ninepoints 3y agoThe hash table solution permits an O(n) average solution if you change the hash function to be one that is incrementally computable (most are). Probably way faster than a trie of your entire corpus also...
- bonzini 3y agoI think the lookup would involve a string comparison if the hash matches, and that is also O(n). You should be able to construct a pathological example that ends up quadratic.
- deleted 3y ago[deleted]
- Gehinnn 3y agoI'd bet the last problem (if you can prove that N^2 is a lower bound for the last problem) is open or at least very hard. Showing lower bounds without oracles (where you can prove that the oracle has to be called a certain number of times) is not an easy endeavor.
- bonzini 3y agoThe space of the solutions is n^3, since you have up to n items and each of them has n^2 possibilities. An O(n^2) solution only looks at each possible item in the output a constant number of times. To prove that it's optimal you "only" need to construct the pathological case, which I believe should not be hard to do by induction. I think that pathological case could simply be that the input string is abcdefghij... and the dictionary contains all one-letter strings, plus all strings like ac, abd, abce, ..., bd, bce, bcdf ... and so on. The base induction case would be xyz as the input and {x,y,z,xz} as the dictionary.
- jekub 3y agoNop, the article is false about this. The optimal algorithm is O(n) as you can make a simple regular expression that is the Kleene star of an or of all the words in your dictionary to match the input. This is allowed as you can choose how to implement the dictionary, it don’t take more space than a trie and match in linear time as it can be compiled to an NFA or a DFA.
- bonzini 3y agoThe DFA is O(n) with up to exponential time spent upfront (and exponential space usage too). The exact complexity for the NFA with the regex you suggest depends on how the NFA is built, but it is at least O(n^2) worst case because you can easily build a case with n active states. Likewise for the lazy DFA.
- Gehinnn 3y agoThat's not how you show lower bounds. The problem is function f that gets a list of words D and a word w of length n and returns a list of indices I where to split w such that each part is in D or "false". Cleary, I has length at most n and the indices in it are also at most n. Also, you need to look at every word in D. Thus, the trivial lower bound of the complexity for an algorithm that computes f is O(n+|D|). To prove a tighter lower bound, you would need to show that every algorithm that does it in in linear time has a bug - you need to find this "pathological" case for every imaginable algorithm! Afaik it is still unknown of SAT has a quadratic lower bound! https://cstheory.stackexchange.com/questions/17789/is-there-an-explanation-for-the-difficulty-of-proving-quadratic-lower-bounds-for https://cstheory.stackexchange.com/questions/17789/is-there-...
- kkapelon 3y agoAnother "great" interview question like the creme brulee story http://www.unlimitednovelty.com/2011/12/can-you-solve-this-problem-for-me-on.html http://www.unlimitednovelty.com/2011/12/can-you-solve-this-p...
- wlamartin 3y agoYears ago when I was starting to interview for Uber in Europe I went through some data structure exercise which I failed at horribly. When I asked the hiring manager whether this was representative of the job, because I would probably not be good at it they said "no", and to follow up, when I asked why we did it they said, "in the next round my colleagues in the USA are going to ask you something similar". I guess this wasn't entirely without sense but sort of seemed to be missing the point.
- vega 3y agoIt puzzles me that the author thinks that this is a good interview question. Or that one can extract “signals” from that ordeal. They say they’ve asked that question many times. So that’s a clue, probably. I've never worked at that company and I don’t know if as an interviewer you pick a question from a catalog. If that’s the case, and if you’re so inclined in asking this type of nonsense, I’d suggest a small tweak: a third party selects the question with some sort of guarantee/constraint that this would be the first time the interviewer asks that question, and so is now in more or less level ground with the interviewee. No other option but to have a discussion among potential colleagues.
- Animats 3y agoThere are also some probabilistic solutions. For an English dictionary, the space of trigraphs is only about 30% populated. So, whenever you see a trigraph that's not in the set of all known English trigraphs, there must be a word break at one of two points in the trigraph. This gives you an entry point for breaking the problem into smaller subproblems. Those can even be run in parallel. For long texts, this is a huge win.
- iamnotsure 3y agoIt is a good question.
- prakhar897 3y agoThe lookup of a normal hash function is O(1). Why is the author saying that it's O(n)? https://iq.opengenus.org/time-complexity-of-hash-table/#:~:text=The%20hash%20key%20is%20calculated,complexity%20is%20O(1) https://iq.opengenus.org/time-complexity-of-hash-table/#:~:t....
- valzam 3y agoOne of the best interviews I have had did ask me to code but gave me a few snippets of code and asked me how I would improve them. Or asked which of several approaches I prefer and what the trade-offs are. IMHO reading and explaining arbitrary code is a strong signal for a good developer. Writing code under pressure is not.
- carlosrdrz 3y agoI don't know the author and I'm not part of Google, but I've also been an interviewer both in startups and bigtech, and I must say that I believe the process in bigtech is much better than what I see elsewhere. Every time I see posts about interviewing practices in bigtech I feel folks are completely missing the point on why things are made like this. No wonder they just default to bash the interview process. Maybe it is understandable since the article does not clarify any of this, but folks should notice that: - This type of interview is part of a process, composed of multiple interviews. Not the only one, and not the deciding factor. Questions on behaviors, team dynamics, etc, are also part of the process and covered in other interviews (usually done by managers). You could fail a systems interview and still pass the interview process. The specific interview mentioned in the article seems not too complex, though, so I wouldn't be surprised if it is a screening interview that rejects candidates when not passed. - People mentioning that the interviewer is wrong on time or space complexity are also missing the point. It doesn't matter. If someone in the interview mentions O(n) instead of O(n2) and can reason that, that's already a good signal. It is not so much about being right or wrong. It is about thinking about those things when coding, keeping them in mind, been able to express that and run someone else through your thought process, etc. Someone plainly saying something is O(n) without any further explanation can give a bad signal, but someone explaining why she thinks so can be a good signal, even if ultimately the solution is not O(n). - IMO, folks saying that this favors junior engineers and people fresh out of college are wrong. This favors people who ultimately understand the foundations of programming. People fresh out of college had a refresher on that not so long ago, so they've been practicing it more. The thing is, some people in our industry get further away from that as they add seniority to their career, but there's also lots of senior people that are very well versed on this kind of thing. Specifically, the question in this article is extremely simple, so TBH I don't understand why someone senior would fail to know the answer to that question just because that person is senior. Maybe these companies are just not looking for that kind of senior engineer for this specific positions. That's all. There's also a lot of different seniority levels, too. I could see this interview having less weight on a decision as seniority increases, but still important. - "this does not represent a realistic scenario". That's a given. As a company, you have maybe 8 hours total with the candidate (multiple rounds of interviews plus the on-site). Onboarding into the company and a team, until you're productive, will take weeks/months. There's no way of testing a realistic scenario on an interview. We get the best signal we can with the time we're given. - Not passing the interview process is very demoralizing, but it does not mean the company thinks you're a bad engineer or that you're not good enough. The process is designed to minimize false positives, so they tend to prefer to reject candidates if there's any question or mixed signal in the interviews. - I'm not saying the process is perfect, by the way. For example, there's also luck involved, too. It shouldn't, but there is. To give one example: interviewers are people too. They need to be trained in the process of interviewing, what signals to look for, etc. There are good and bad interviewers. Interviewers can have a bad day and judge some answer as unsatisfying when some other day it would be fine, etc.
- brainzap 3y agoInterview questions are secret, you will not find them in the web.
- bryanrasmussen 3y agoI guess I don't understand the question actually - is it return every potential word inside of a word and we accept that there is left over fragments that are not words, or does it have to make sure you do not have any left over fragments? The problem as described: “Write a function that given a string, determines if it’s a concatenation of two dictionary words.” given that description I think you can't have left over fragments. But the code seems to allow fragments (don't know Python). Also it just returns a boolean? So we just need to know if there is two words contained within our word within the dictionary. If that's the case, and the "dictionary" is an actual dictionary used by humans (they mean like a Dictionary like The Oxford American Dictionary right?), then, because the letters of a word are considered nouns (that is to say the letter b is a noun - Merriam-Webster https://www.merriam-webster.com/dictionary/b https://www.merriam-webster.com/dictionary/b) then any word with more than one letter is a concatenation of two words. Which is anyway stupid because no one cares about concatenations of words, people care about compound words and this is not how you would find compound words. I bet that's not what they want to hear though. I generally do really bad on questions.
- rendall 3y agoI read it as asking for a function that takes a string and returns a "true" if it's a word comprised of two words and a "false" if it's not. So: "lampshade" => true "grip" => false "gripshell" => true "fhtagnblue" => false "timeblue" => true
- bryanrasmussen 3y agoyes that's how I first read it but I got less sure that was meant as I read the rest. For example it looks to me like it thinks fhtagnblue which has the words tag and blue in it should return true? Maybe I'm reading things wrong - but if it should return true, thus allowing fragments, then every word with two letters or more would return true because every letter is a noun. If it is as you said, which might be actually interesting thing to do and potentially even useful, I might not want to do it with a query this dictionary for a string and instead have actual access to the dictionary to work with since I figure an optimized solution can be made with binary search. on edit: I mean considering Google's reputation for trick questions and logic gotchas I would probably just say "wow you guys really are like that" and write something like if(!s) {return false;} s_array = s.split(""); return s_array.length > 1;
- kristopolous 3y agoThe author starts with type I and II errors the question has yielded that somehow they're proud of it. With performance like that, I'd call it a "trash interview question". When you use wildly inaccurate processes, you build bad teams and good people know you'd be wasting their time so they don't even go in the door.
- namaria 3y agoI wonder if there is any solid data on how hiring practices relate to candidate/team/company performance. Is any of this better then randomly selecting? Do we even know if there is a skill set that is optimal, or if multiple complementary skill sets work best? Do we know what they look like, how to select for them? Or are we all just filtering for whatever collective definition of cleverness people involved in a given set of interviewing and hiring tasks prefer? I suspect on average it's better to filter out good candidates than filter in bad ones so as long as a selection process skews towards eliminating most candidates probabilities will have most teams covered on that front. Of course this only works when salaries in programming are rising faster then the rest of the labor market, attracting a growing cohort each fiscal cycle.
- hartator 3y ago> When questioned, I explain that the dictionary is available as a function to query a string for membership. Well, that removes most of the fun of it. I think that’s actually a good example of why this is not a good question. It’s disconnected from any realities.
- keskival 3y agoIf you have an interview question which filters out the experienced people and biases towards inexperienced ones, consider that you might have a bad interview question.
- arethuza 3y agoI must admit I find these kinds of questions that have no context completely uninteresting - my first reaction to being asked that would no doubt be "Why would you want to do that - what is the context?".
- Mizoguchi 3y agoAnd this is why tech interviews are broken. The author not only believes this is an interview question, but a great one.
- sjducb 3y agoCan someone explain this bit to me please? I then push them on this until they realize that any implementation of the dictionary lookup function of a string would be o(n) at best, and as such the total runtime of the solution is O(n²). Surely it's String -> Hash -> Is hash in hashmap All of those operations are O(1) so the total operation is O(1)
- ArnoVW 3y agoAgreed. Well, in theory you may have conflicts in the bucket. And recovering the bucket means a round-trip to memory, which is much more expensive than running over a list. And in any case, "n" is the length of the word, but has nothing to do with the distribution of the dictionary. So one should use a "m" to capture that.
- sjducb 3y agoI thought that too The list of dictionary words isn't that big, so you can just have a long hash to reduce your conflicts to almost 0. Also words aren't that long. The longest English word is probably less than 100 characters, whereas you could feed trillions of strings into the algorithm.
- wickedsickeune 3y agoIn order to hash the string you need to access all of its characters, ergo O(n). I agree with you that this sounds weird, but if you imagine arbitrarily long strings as inputs, and don't want to have a lot of collisions, you need to take into account all of the input string in the hash function. In reality they are safely assumed to take O(1), but w/e the interviewer is looking for a specific answer.
- FabHK 3y agoComputing the hash of a string with n characters is O(n). However, the whole discussion in the piece suffers from not taking into account the fact that words don't get arbitrarily long. Thus, insofar that for all practical purposes n <= 30, say, it is indeed O(30) = O(1).
- deleted 3y ago[deleted]
- _dain_ 3y agoAlright here's how I did: - part 1: got it in like 20 seconds of thought - part 2: got a variant with a trie in maybe 5 minutes thinking, wasn't exactly the same as the given one but close enough - part 3: thought about it for an hour (got nerd sniped). got a trie + recursive dynamic programming solution that's O(N^2) in the size of the input string. the actual solution took me 15 minutes, the rest was trying to prove the the big-O Let's say the string is wxyz. As we iterate, we'll split into the possible prefixes and suffixes: w xyz wx yz wxy z wxyz (suffix is empty string, we have to special-case this I think) If we find a prefix-suffix pair where the prefix is in the trie, and a recursive function call on the suffix returns True, then we return True. If there is no such pair, then we return False. Looking up a string in the trie is O(N). But for the prefixes, we can "remember our place" in the trie, so that the cost of an incremental character is constant. So membership checking wxy only incurs the cost of y, given that we've already just looked up wx. The prefix is either a word in the dictionary, or it isn't. If the prefix is not in the trie, we advance to the next character and repeat, with the next prefix grown by one character and the next suffix shrunk by one character. If the prefix is a word in the trie, we call our function recursively on the suffix, and memoize the result. If the recursive call comes back true, we're done, and we return true. If it's false, we advance to the next possible prefix and repeat. If we reach the end, the prefix now comprises the whole string, so we just return whether it's a full word in the trie or not. In the base case of the recursion, the suffix is a single character, which is a constant-time lookup in the trie. So every recursive call after that can just look up that memoized result. Same for the 2-character suffix, 3-character suffix, and so on: - 1 character: z: z: 1 operation - 2 character: yz: y, z suffix memoized, yz: 3 operations - 3 character: xyz: x, yz suffix is memoized, xy, z suffix is memoized, xyz: 5 operations - 4 character: wxyz: w, xyz(memo), wx, yz(memo), wxy, z(memo), wxyz: 7 operations - N characters: prefix 1, (N-1)(memo), prefix 2, (N-2)(memo), prefix 3, (N-3)(memo) ...: 2N operations (Here I've spoken of the "memoized xyz suffix" and so on, so you might think the lookup time grows with the length of the suffix, because you have to hash it. But actually you don't, because you can just lookup by the index of the start of the suffix. So looking up the memoized results is also constant time.) So summing the cost of all those recursive steps, it is O(N^2) in the length of the string. The word "cantonal" works as a good test case because it has lots of sub-words: can, cant, canto, canton, a, an, ant, anton, ton, tonal, on. The memoization doesn't show up for it though, so I'll append "q" to make "cantonalq", which should return False: c -> no ca -> no can -> yes t -> no to -> yes n -> no na -> no nal -> no nalq -> no ton -> yes a -> yes l -> no lq -> no al -> no alq -> no tona -> no tonal -> yes q -> no tonalq -> no cant -> yes o -> no on -> yes (-alq suffix is memoized) -> no ona -> no onal -> no onalq -> no canto -> yes (-nalq suffix is memoized) -> no canton -> yes (-alq suffix is memoized) -> no cantona -> no cantonal -> yes (-q suffix is memoized) -> no -> return False I wouldn't have been able to do this in an interview setting. Most of my time was spent gazing vacantly off into space. Interviewers want you to narrate your thinking but I can't do that .. I have to shut the fuck up for a while as my brain works. But long periods of silence are intensely awkward in such a setting and I'd get very flustered and self-conscious. Maybe I could have narrated the "cantonalq" example, idk. Generally I don't mind "pure" DS/algo interview questions, so long as they're plausibly related to something one might actually do. I have actually used tries before on a real problem. Dynamic programming with memoization tricks? Never. Has anyone ever had something remotely similar come up in real work? I mean I know there are caches everywhere but that's not the same thing. It just seems like a sick hazing ritual that nerds inflict on one another. Conclusion: bad interview question.
- d--b 3y agoThis question is annoying because it is simple to state, but it's a pain to implement. The naive solution is so stupid I'd physically feel bad to write it. The trie/reversed-trie solution is a little too clever to arise naturally from conversation (and probably not optimal because hardware implementation).
- lcnPylGDnU4H9OF 3y ago> Maybe surprisingly, junior candidates sometimes rank better at this problem because their Data Structure & Algorithms knowledge is more fresh. Not surprising. This sort of interview is selecting for people who have exactly this kind of academic knowledge.
- manv1 3y agoThe only real interview question that should matter: The customer wants to increase their sales. They want something that auto-generate sales responses to incoming emails. Discuss. The problem with technology workers is that they believe technology is important. The above question allows you, the interviewer, to see if they have actual critical thinking skills.
- jake_morrison 3y agoAs a real engineer, I ask what the practical problem is that they are trying to solve. Seems like the practical application of this is to quickly disallow strong memorable passwords of the form "correct horse battery staple". https://xkcd.com/936/ https://xkcd.com/936/ If so, deeply misguided.
- notmypenguin 3y agoIt’s a negative signal, when searching for a hiring manager, to find a prominent medium article by them in which they extol the virtue of them repeatedly using the same programming problem when hiring without exploring the impact and consequences of this in a context that allows for a control group and other questions. The amount of smug confidence this person has is unwarranted, in my opinion. I used the word smug as this is the emotional description I read in this article. Please don’t ding me for using an adjective on purpose
- nuancebydefault 3y agoI think this is a great interview question if you want to know how well someone can write an algorithm. However, software engineering is so much more than writing code to solve a well specified problem. - oftentimes, the problem is not well specified. The engineer needs to find out what the problem specification really is. - In a lot of cases, a solution already exists publicly. The engineer needs to find documentation or code that solves the lecified problem or a similar problem. Usually somebody has already thought about optimization of this type of problem and has documented it. - Often, a feature needs to be added to an existing codebase. Often a similar feature already exists in the codebase and the new feature can be implemented in a similar way. The engineer needs to find the similar feature and has to figure out how to generalize or adapt it into the new feature. - A lot of times technical debt needs decreasing. This involves understanding feature implementations or models/paradigms in an existing codebase, understand how they are inefficient or needlessly complex. Creativity is the trait mostly needed in this case to address it. - often new APIs need to be made, needing modeling and documentation. Also often existing APIs or newly imported libraries need to bevused to tackle problems. - Above points address the purely technical skills. Non-technical skills are just as important. Communication, teamwork, prioritization, time and stress management, customer relations,... Tldr - this great interview question targets just one aspect of the job.
- deleted 3y ago[deleted]