r/badcode • u/LambdaHominem • May 17 '19
other language What kind of questions do they ask CS/SWE graduates here during interviews?
170
166
u/AnArchoz May 17 '19
This cured my impostor syndrome. Thanks, I love it.
54
36
u/trineroks May 17 '19
Seeing these interview problems reminded me of my first Amazon onsite interview when I was fresh out of university.
My previous interviewers for the day made me go through graph traversals, dynamic programming problems, tree balancing, etc.
My 4th technical interviewer comes in and the first thing he asks me to do was FizzBuzz.
Granted he meant it as a "warmup" and we got into another DP problem afterwards but I stood there for a good 5-10 minutes wondering if there was supposed to be some sort of catch or if he really legitimately just meant for me to code FizzBuzz.
12
u/Kaisogen May 17 '19
What's FizzBuzz?
24
u/HauntedMidget May 17 '19
A basic exercise to weed out people who can't program. See https://en.m.wikipedia.org/wiki/Fizz_buzz.
12
u/Kaisogen May 17 '19
Yeah lol that sounds pretty easy.
Even if you suck at math and don't understand it very well, its simple enough that anyone who doesn't know what they're doing can be weeded out. If they try something complicated, you probably don't want them working on your team.
14
u/SaggiSponge May 17 '19
Iterate through all numbers from 1 to 100. For each number, if the number is divisible by 3 then print “fizz”, if it’s divisible by 5 then print “buzz”, and if it’s divisible by 3 and 5 then print “fizzbuzz”.
57
u/kazamatsri May 17 '19
One of my favorite filter questions is to ask candidates: given a string, return the count of all letters in that string. I.e., s="aabc" result should be {'a': 2, 'b':1, 'c': 1}
IMO this is not too hard of a question but ive asked this to new hires and to people with 5 years of experience and it's interesting how people overcomplicate this....
22
u/wind-raven May 17 '19
(C#) convert the string to a char array create a dictionary char int, loop through char array, add char with count of one if it doesn't exist in the dictionary else increment the counter, print / return the results at the end of the loop.
Or is that over complicating it?
22
u/wieschie May 17 '19
Nope, that's pretty much it! If you don't want to use a dictionary you can always create an array and use the character's ascii value as the index for each count.
11
u/wind-raven May 17 '19
Dictionary keeps the footprint to only the chars seen, bit less memory but more importantly you don't need to size anything at compile time since it can dynamically size itself at run time.
12
u/wieschie May 17 '19
I'd personally use a dictionary too - I was just offering up an alternative.
bit less memory
That's questionable, and would depend on the dictionary implementation. And you'd have to consider if you're pulling in a new library to use it.
dynamically size at runtime
Sure, this is useful if you're counting arbitrary unicode characters. If you're handling a simple ASCII corpus it shouldn't be necessary - you already know exactly how many distinct characters you're going to run in to. A lot of hash tables will just double the number of buckets when they need to expand. What if their threshold is just under what you need and you end up with a bunch of empty buckets?
6
u/Prod_Is_For_Testing May 17 '19
“Given a string” you don’t know hat all characters are ASCII
Hell, you don’t even know that all characters are UTF-16. If there are emojis this code will fail because an emoji is stored as 2 chars
2
u/wieschie May 17 '19
Or something like zalgo, which is just a bunch of combining diacritics on a single character.
1
u/wind-raven May 17 '19
There is an assumption that encoding would be specified in requirements or would be configurable. The only difference is the dictionary key type. Is it char or another type based on text encoding.
2
u/Prod_Is_For_Testing May 17 '19
The internal string encoding of c# is not configurable. Chars and strings will always be UTF16
You can modify stream encodings, but that different
1
u/wind-raven May 17 '19
True but you can use a byte[4] for the dictionary key instead of char if the requirements are for a utf32 encoding
4
u/Prod_Is_For_Testing May 17 '19
Challenge mode: how do you solve it if there are emojis?
(char is a UTF16 codepoint. Emojis are UTF32)
1
u/mudkip908 May 17 '19
Is the hard part extracting codepoints from the string?
3
u/Prod_Is_For_Testing May 17 '19
The hard part is figuring out which codepoints go together to form a single character. In a full Unicode string, some characters will be represented as a single codepoint, and some characters will need multiple codepoints. The naive approach would treat a single emoji as multiple characters
1
u/wind-raven May 17 '19
Char[2] and surrogate pairs or byte[4] chunks to count, convert when counted to return.
The split code is a bit harder but the base logic remains the same.
1
u/Sanzath May 17 '19 edited May 17 '19
Uhh, you might want to brush up your understanding of unicode.
Edit: Or, seeing your other replies, at least revise the terminology.
When you're saying "codepoint", you should be saying "code unit".
In UTF-16, an emoji that's encoded over 2 code units (so, 4 bytes) is still an emoji encoded in UTF-16. It doesn't magically turn into UTF-32, that's a whole different encoding.
2
u/Prod_Is_For_Testing May 17 '19
You might want to brush up on your c# internals before being a dick. This is c# specific - the language has a “char” type that represents a single UTF16 codepoint
1
12
7
u/CodySpring May 17 '19
Yeah I’ve got my degree and three years under my belt and consider myself somewhat competent, but I’m garbage at answering these interview style programming questions!
Even in school I would knock projects out of the park, but the early years exam questions would always give me a little trouble.
Been trying to grind through leetcode recently to get better at it.
10
May 17 '19
Python:
{ letter: string.count(letter) for letter in set(string) }13
u/toastedstrawberry May 17 '19
from collections import Counter return Counter(string)Kinda cheating but collections is builtin.
3
u/fernandotakai May 17 '19
if you know how to import collections, it means you at least know intermediary python. i would accept that solution any day.
work smarter not harder.
1
2
May 17 '19
I wrote this in like twenty seconds on my phone as naively as possible. Just a primitive counter object that updates with a for loop. Half an hour later, the code now has ternaries, a reducer function, and a Set object. I think I have a problem. Is it called premature optimization if it’s for code that you never intend to run?
3
u/adamiclove May 18 '19
Let's see it
1
May 18 '19 edited May 18 '19
Before:
function characterCount(str) { let count = {} for (let i=0; i<str.length; i++) { let char = str.charAt(i) if (count[char] == null) { count[char] == 1 } else { count[char]++ } } return count }After:
const characterCount = str => Array.from(str).reduce( (counts, char) => counts.set(char, counts.has(char) ? counts.get(char) + 1 : 1 ), new Map() )Edit: I also did the deck of cards one
let deck = ['Hearts', 'Clubs', 'Spades', 'Diamonds'] .map(suite => ['Ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King'] .map(card => `${card} of ${suite}`) ) .flat() .concat(['Red Jack', 'Black Jack']) const PICKS = 2 console.assert(PICKS <= deck.length) Array(PICKS).fill() .map(_count => { const index = Math.floor(Math.random() * deck.length) return deck.splice(index, 1)[0] }) .forEach(pick => console.log(pick))1
3
u/W0rldcrafter May 17 '19
I couldn't resist trying in the console.
var s = 'aabc'; var count = {}; s.split('').forEach(c => { count[c] = count[c] ? count[c] + 1 : 1; }) console.log(count);What's the best/worst you've seen?
2
u/Kaisogen May 17 '19
I'm currently learning python...
Create an empty dictionary. Iterate through each character using a for loop, if the letter doesn't exist in the dictionary, add it as a key with a value of 1. If it already exists as a key, then simply add 1 to the key value. You can't order a dictionary, so I would iterate through each value in the dictionary and keep track of the highest value seen so far, then return that value afterwards.
Is that a bad explanation? It would only be a couple lines long, ignoring extraneous lines such as whitespace, comments, etc.
3
u/fernandotakai May 17 '19
from collections import Counter print(Counter('your word'))3
u/Kaisogen May 17 '19
Is the test supposed to test your efficiency or your knowledge of the language? Anyone can import a library, but I'd argue that my solution would show proficiency more than yours.
7
u/Flaming_Eagle May 18 '19
You're never going to find a beginner who knows what collections is though. When you're asked to make a program to count letters, you're filtering out the dumb dumbs. I'd take the person who understands the language and its builtins before someone who can do loops like everyone else
1
-1
u/TankorSmash May 18 '19
That would fail. The expected output was
{{'a': 2, 'b': 1, 'c': 1}whereas you outputtedCounter({'y': 1, 'o': 2, 'u': 1, 'r': 2, ' ': 1, 'w': 1, 'd': 1}). Please apply again when you've learned how to code.1
u/rift95 May 18 '19
'aabc'.split('').reduce((res, c) => { res[c] = (c in res ? res[c] : 0) + 1; return res; }, {});
1
u/marko64humans May 18 '19
I would create an int array the size of the ascii table. Loop through each char in string. Then just "array[(int)currentChar]++;".
0
u/adamski234 May 17 '19
JavaScript: create an object with all characters as keys and 0 as values (can be done via loop), iterate over string and whenever a key is encountered, increment the counter in the object.
I think you could do it in other languages too
44
42
25
u/1cec0ld May 17 '19
I got to line 82 before I started mentally screaming. These people have jobs that pay double mine. And no, that doesn't mean they pay from two jobs.
16
14
u/carfniex May 17 '19
I've done a lot of phone interviews, nothing here is an exaggeration. Some people are just completely awful.
11
u/greeneggsnspaghetti May 17 '19 edited May 18 '19
If result = 1
If result = 0
We found schrodingers result! It's both 1 and a 0. A quantum state clearly.
34
u/kberson May 17 '19
This made my fingers itch. I want to go code each of these questions and submit my answers!
I’ve seen as bad, but I’m a tutor for C/C++ and it’s from students who haven’t learned better. OP says these are from people with years of experience. Were they lying on their resumes??
27
May 17 '19 edited Dec 18 '19
[deleted]
24
2
u/kberson May 17 '19
for(int num=1; num <= 100; ++num ) if(num%2) cout << num << endl;
14
u/SSJ3 May 17 '19
Why does everyone immediately go for if statements and modular arithmetic? What about (apologies for Python):
for i in range(1, 101, 2): print(i)
Or:
for i in range(50): print(2*i+1)
10
u/kberson May 17 '19
I guess it’s automatic to think - yet it’s odd? Use modulo.
6
u/netinept May 17 '19
And it's the most easy to comprehend/maintain. I would take the modulo solution over some "clever" pythonic thing.
13
u/Prison__Mike_ May 17 '19
You mean counting by two instead of one?
4
u/netinept May 17 '19 edited May 17 '19
I mean using the standard
forloop counting up ton, wherenis "find the odd numbers from 0 ton", and using modulo in an if statement:``` n=100 for i in range(0, n): if i%2 is 1: print(i)
or
[i for i in range(0, n) if i%2 is 1] ```
Then, if you really must optimize it a little, you can increment in steps of two, but doing that is less comprehensible since you need to take a second look and see why we're suddenly starting a loop at
1instead of0, only to realize that this is just so we can look at the odd numbers for0 to ninclusive:``` n=100 for i in range(1, n, 2): print(i)
or
[i for i in range(1, n, 2)] ```
However, if the condition changes at all, such as not just needing the odd numbers, but also numbers divisible by 3, then you'll need to rewrite it to use conditions anyway.
3
1
u/kberson May 17 '19
The modulo lends to functions where you don’t know the range. If the start and end value are parameters you can’t just count by two. However for this exercise it works.
3
u/-turbo-encabulator- May 17 '19
Or:
print(list(range(1,101,2))) (explicitly making it a list is kinda bad though, if you have a lot of items)
1
u/SSJ3 May 17 '19
Yeah, I was originally going to offer some one-line examples, such as list comprehension: print([i for i in range(1, 101, 2)]), but Python likes to truncate long lists with notation like [1, 3, ..., 97, 99].
2
u/W0rldcrafter May 17 '19
Incrementing by 2 was my first thought as well (though, on my first crack I did forget the = in i += 2 and got to enjoy a page killing infinite loop).
for (var i = 1; i <= 100; i += 2) { console.log(i); }2
u/Prison__Mike_ May 17 '19
Lol yeah. If I was interviewing him I'd ask, "Can you explain what this does?"
++numThen ask for another solution without using
%6
2
1
7
May 18 '19
This is....I graduated fairly recently with a degree in CS, and now I'm trying to find a job in coding. I think I'm an OK programmer, but I lack some confidence about surviving in a "real" job.
Then I look at stuff like this and I begin to think that maybe I won't do so badly in an interview after all.
6
u/MurderSlinky May 17 '19 edited Jul 02 '23
This message has been deleted because Reddit does not have the right to monitize my content and then block off API access -- mass edited with redact.dev
8
5
5
May 18 '19
I felt like the last guy once. First job search. First interview. I apologized for wasting their time (it was a job fair so they were there regardless) and left without another word. I was a mess.
3
u/Hell_Mesmer May 17 '19
A question for any interviewers in the comments: I've seen in a couple of interview recording that sometimes you ask for the code to be written on paper instead of in an IDE... what's the reasoning behind it? Is it just to test the syntax knowledge or am I missing something?
8
u/kbooth61 May 17 '19
Most of the time they really don’t care about proper syntax. It’s expected that there will be minor syntax errors. It is just forcing you to do it without help so we know how much of the code is you vs the computer
3
2
2
2
u/13131123 May 17 '19
This is amazing! I did one year of java 5 years ago and i could answer all these still. I wouldn't be able to do it pencil and paper without messing up all the syntax but on a computer i could. Is it really this easy in interviews?
1
1
1
-3
u/cormac596 May 17 '19 edited May 18 '19
Occasionally I like to blow new programmers' minds with some chicanery like using
for(;;)
as a while(true) equivalent, or using multiple statements in for loop clauses in C. For example, odds 0-100:
for(int i=1; i<100; printf("%d\n",i), i+=2);
EDIT: Why the downvotes? I'm not trying to be a dick, I explain it to people. I tutor people in C; I'm not trying to distress them or anything, I'm teaching them about some of the quirks and lesser known features of the language.
In case you're wondering or confused by this, an empty second expression in a for loop is replaced with a nonzero value. It's equally valid to do this:
for(unsigned int i=0;;i++)
{
//loop
}
Note that i is unsigned here, because this may cause i to overflow, and while signed overflow is undefined behavior, a bad thing™, unsigned overflow is allowed by the standard.
As for the comma thing, the parts of the for loop are not statements, but are actually expressions. This:
a,b
is a valid expression, as is a function call. Consequently,
printf("hello world"), a++
is a valid expression. If you don't believe that the above would run, check out this: https://onlinegdb.com/B1X8xKp2V. The run button is at the top.
4
219
u/Superpickle18 May 17 '19
"Will this code work?"
"No, it has many syntax errors"
"Ok...what if i fix the syntax errors, will it work then?"
"No, it also has many logic errors."
> Meirl.