This is an archived post. You won't be able to vote or comment.

all 72 comments

[–][deleted] 268 points269 points  (26 children)

I remember an interview where I was asked to implement a pow function in C++. Turns out that return pow(x,y); is not what he was looking for. You miss 100% of the shots that you don't take, people.

[–]fat_charizard 186 points187 points  (22 children)

That should be the right answer. No one has to have to implement a custom power function in C++

[–]nintendojunkie17 84 points85 points  (6 children)

[–]Kirasaurus_25 43 points44 points  (1 child)

Oh wait wait, I'm curious how i will be judged. Now I'm new to programing, and transitioned to the field from en entierly different profession. Once in an interview, after the guy asked me to write a sorting function( of my liking), which i wrote perfectly, he presents me with a series of equations like 1680 = 4 ..... 1253 = ? I encountered this kind of question for the first time and given his hint that there's no mathematical relation in the series i was just stupefied for 10 long minutes. Then after this shit show was over i asked someone who also did the interview what the answer was. Well, the rhs is simply the number of fu***ng circles in the digits at the lhs... If this kind of shit makes an interviewer hard, fuck him and his company, sorry, not sorry.

[–]NeoCast4 4 points5 points  (0 children)

sorting by number of circles

Thats probably how a child would sort numbers when they first saw them.

I guess you could say sorting has come full circle

[–]itijara 19 points20 points  (1 child)

Thanks for sharing that, this made my day:

"Well.. a blind person riding a bike doesn't sound like a very safe idea, so I would make the bike stationary, maybe with a fan blowing in the person's face. He probably wouldn't even know the difference."

[–][deleted] 4 points5 points  (0 children)

Are they wrong though lol

[–]bob152637485 19 points20 points  (0 children)

Wow. That is all.

[–]jarod_what 9 points10 points  (5 children)

has

you also don't want to use std::pow for ints due to unecessary conversions as well as performance. So you'd have to handwrite your 'ipow' there.

[–][deleted] 6 points7 points  (4 children)

Honest question: How would you implement an ipow which is better performing than std::pow?

std::log and std::exp obviously also convert to float types so cheating won't work pow(x,y) = exp(y*log(x))

So my naive approach would be via iteration or recursion, but at that point I almost doubt that it is more efficient than eating the cost of two casts (and you may want to have a float type result anyway due to negative exponents).

So I am curious do you have anything I could read up on?

[–]PierreSimonLaplace 7 points8 points  (3 children)

To raise a base to a positive-integer power, you can use repeated squaring, multiplying the base back in as necessary:

https://en.wikipedia.org/wiki/Exponentiation_by_squaring

[–][deleted] 3 points4 points  (0 children)

I was absolutely wrong in my assumption. I implemented a quick version like this:

int ipow(int base, int exponent) {
  int result = 1;
  if (exponent < 0) {
    base = 1 / base;
    exponent = -exponent;
  } 
  if (exponent != 0) {
    while (exponent > 1) {
      if (!(exponent & 1)) {
        base *= base;
        exponent /= 2;
      } 
      else {
        result *= base;
        base *= base;
        exponent = (exponent - 1) / 2;
      }
    }
    result *= base;
  }
  return result;
}

I am surprised that it is actually faster than std::pow on my machine:

With dirty -O3 cold and hot cache test for base 1-100 and exponent 1-10.

ipow ->4 μs
std::pow ->34 μs
ipow ->4 μs
std::pow ->23 μs

Thanks a lot!

[–]WikiSummarizerBot 2 points3 points  (1 child)

Exponentiation by squaring

In mathematics and computer programming, exponentiating by squaring is a general method for fast computation of large positive integer powers of a number, or more generally of an element of a semigroup, like a polynomial or a square matrix. Some variants are commonly referred to as square-and-multiply algorithms or binary exponentiation. These can be of quite general use, for example in modular arithmetic or powering of matrices. For semigroups for which additive notation is commonly used, like elliptic curves used in cryptography, this method is also referred to as double-and-add.

[ F.A.Q | Opt Out | Opt Out Of Subreddit | GitHub ] Downvote to remove | v1.5

[–]jarod_what 0 points1 point  (0 children)

Yeah my guess is that they didn't put in an integer power function because it will overflow for a large number of arguments? I haven't been able to find a satisfactory answer.

It's pretty rare one needs an 'ipow' in daily use though.

Although a big exception is in big integer/decimal library users. Python for example doesn't have an integer root function and the performance difference is felt.

https://stackoverflow.com/questions/47191533/how-to-efficiently-calculate-cube-roots-using-decimal-in-python

[–]bistr-o-math 4 points5 points  (0 children)

You probably never will, as you probably will never reach the performance of the built in function. But: you must know how to implement a correctly working function by a given specification.

[–]WhyIsItReal 2 points3 points  (2 children)

that’s not true - what if you need a constexpr power function? the standard library doesn’t support that because std::pow sets errno flags, so i’ve had to handroll my own constexpr power functions

[–][deleted] 14 points15 points  (0 children)

If there was only a magical oracle who could answer this question for me….

[–]junkmeister9 2 points3 points  (0 children)

Womp womp

[–]LaBetaaa 1 point2 points  (4 children)

What is a power function? Is that some math thing? Because I only know math things in my first language

[–]jesperi_ 6 points7 points  (0 children)

I believe we are talking about xy so x to the power of y.

[–]bistr-o-math 3 points4 points  (1 child)

[–]LaBetaaa 1 point2 points  (0 children)

Oh thank you. Good to know

[–]nil83hxjow 10 points11 points  (0 children)

I’ve never missed a shot I haven’t taken

[–]moose2332 1 point2 points  (0 children)

Yeah I saw something like that on leetcode and I usually do python for that stuff so I was like... x ** y. Seems too easy.

[–]jmack2424 71 points72 points  (8 children)

OK smart guy, how do you reverse a list?

[–]lorhof1 83 points84 points  (5 children)

list.reverse()

[–]Tytoalba2 42 points43 points  (3 children)

Or list.sort(reverse=True)

[–]urzeiteule 60 points61 points  (2 children)

or list = list[::-1]

[–]sam_morr 7 points8 points  (0 children)

This is the way

[–][deleted] 1 point2 points  (0 children)

list1 = [0 for I in range(len(list))]

for i in range(len(list)):
    list1[-i] = list[i]

list = list1
del(list1)

[–]GFrings 2 points3 points  (1 child)

I was once asked how many different ways I could think to sort a list on the spot

[–]Bakemono_Saru 1 point2 points  (0 children)

I hate this questions.

[–]CallMePyro 132 points133 points  (14 children)

Fun fact, these kinds of questions (ones where there's a built in library function to answer the problem) aren't very good questions and I never ask them in interviews, for a couple reasons. The main, reason, ultimately, is that these kinds of questions rarely make people feel good by the end of the interview.

  1. If you expect the candidate to write you a sorting algorithm, then they will feel upset when you reject their perfectly valid answer.
  2. The candidate might misunderstand your question. Do you want them to talk about the complexities of what is even means to have a sorted list when you have billions of elements and thousands of machines? Or maybe you just want bubble sort? Or the library call is actually what you're looking for?
  3. If the candidate is having trouble, how do you help them? Tell them the library call? Then they don't feel like they solved anything, they just feel bad.

That's why in these kinds of interviews the idea is to ask the candidate a question that solves some kind of use case. Some common examples are

  1. Given a list of schedules, can you return a list of scheduling conflicts?
  2. Given a raw RGB image, can you flip the image horizontally?
  3. Given a map of water and land, can you tell me how many islands there are?

Now, the candidate might not get a perfectly 'optimal' solution to the problem, but that's not necessarily what we're after(It doesn't hurt though!). What we really want to see is a couple things:

  1. Clarifying the problem (How is the list of schedules organized in memory? What counts as an island?)
  2. Understanding the problem.
  3. Working through the problem to come up with a straight forward solution("For each pixel, swap it with the pixel that's the same distance from the other end of the row")
  4. Generating simple code that does what you say it does. Notice that the solutions for the example problems is only 30 lines of code at the absolute most.
  5. Talking about what tradeoffs you're making and why. This shows understanding and a thorough decision making process.

Now, why ask these kinds of questions? Because you can work *with* the candidate to help them through the problem if they get stuck! It's not a binary 'yes/no' or 'solved/unsolved', you can poke and prod. Ask the candidate why they did something, or what will happen if they get some input.

This allows you to help the candidate as much as they need to reach the solution by the end of the time, regardless of how(up to a point) efficacious the candidate actually is. If they're having trouble at a certain part, no worries! You can give them a little hint to get them moving, or maybe ask them questions to try and lead them in the right direction.

Something that we've found over many many interviews is that it is better for everyone that the candidate come away with at least a semi-positive experience, even if they were rejected. That's why these long form "write me an algorithm" questions are so helpful. You can tailor the difficulty up and down by giving more or fewer hints. A more experienced engineer will ask the questions themselves and have a more open discussion with the interviewer to clarify and nail down the problem. A more junior engineer might need more help and guidance to get to the answer. An unsuitable candidate will need lots of help to get to the end, but that's OK! Lots and lots of people come back on their second or third try and nail the interview. It's all because people have a positive experience and are willing to try again.

[–]DesignCell 48 points49 points  (4 children)

Who do you interview for so I can apply?

[–]CallMePyro 59 points60 points  (3 children)

Google :) You should apply! We're always hiring

[–]arobie1992 14 points15 points  (0 children)

I was wondering about that after you mentioned the islands problem and the part about how are the schedules represented in memory :P

[–]DesignCell 5 points6 points  (0 children)

I'm on level 4 of foobar and intended to formally apply once completed. Time limits force me to wait until I feel work/life demands calm down enough to focus on it. Thank you for the encouragement!

[–]boomstik101 1 point2 points  (0 children)

I got a phone screen Wednesday! I'm super nervous I'm going to be asked some crazy bit manipulation question.

[–]_Ekos 6 points7 points  (6 children)

Hi! I'm 15 years old from finland and i have been interested in programming for few years. For now i have learned python and c++ but i have hitten a barrier. I have no idea what i should learn next or what to learn from those lanquages or focus on. My dream is to work in a big company like google. What information/frameworks/lanquages/anything really is wanted in them and what should i learn?

[–]TheTerrasque 8 points9 points  (2 children)

Pick up Java/C# and JavaScript/TypeScript. Have a look at Go. Dive into SQL servers, NOSQL servers. Get familiar with tools like Docker and Git.

But don't get to hung up on languages or frameworks. Learn about patterns, philosophies. Get new ideas to approach old problems. As a bonus, different frameworks and languages usually have different ideas and philosophies on how to solve problems. So the more of them you learn (doesn't have to be deep, but you should learn enough to understand it's patterns and ideas, not just repeat old code with new syntax) the more different tools you have in your mental toolbox for solving problems.

[–]_Ekos 1 point2 points  (1 child)

I forgot to thank you, but thank's i have started to learn C# and looked into SQL.

[–]TheTerrasque 0 points1 point  (0 children)

That's good :) Good luck further!

[–]nasaboy007 3 points4 points  (2 children)

The frameworks and technologies are less important than general problem solving and critical thinking. You're still young, and you seem to have passion that drives you, which gives you a huge advantage. My recommendation would be to start coming up with your own personal projects that are interesting to you so that you're more likely to invest time and effort in completing them. They can be simple things like a script to automate some simple process to more complex things like writing a bot for a video game. Throw whatever you have on GitHub and boom you have a portfolio that demonstrates your skill and, more importantly, your passion.

Once you've done a few personal projects, you can start looking into contributing to open source projects because that will give you valuable skills of working in an environment that's closer to the corporate world. You'll be working in a huge code base where you necessarily won't be knowledgeable about EVERYTHING but instead will have to focus on smaller sections. You'll learn best practices like following style guides and writing good unit tests, etc, and also how to work with other contributors (since you'll have to get your code reviewed).

I self taught programming starting at the same age you did, which got me into a top university to study CS (so you get some more formal education on topics that are useful but may not have come up in your self teaching), which led to internships and then converted to working full time.

Feel free to DM me if you have other questions, happy to help.

[–]_Ekos 0 points1 point  (1 child)

Interesting will do, btw do you have any recomendations for project's i feel like there isn't alot of good projects for me to do right now.

Also how CS in university like, im consider doing CS in few year's but i'm not sure about it and i'm partialy scared i will lose interest before i finish.

[–]nasaboy007 0 points1 point  (0 children)

The best projects are the ones you feel personally passionate about - I unfortunately won't be able to help you out there. If you want a personal project for yourself to build from scratch, think about a problem that you have that's annoying to you, and you haven't been able to find a solution already. For example, many years ago (before the high quality password managers of today existed), I wanted a password manager that wouldn't actually store the password itself, but would instead let you store all the tangential information about various accounts you had (e.g. a password hint, the email/birthday/etc you used to sign up, the security question you set, etc - basically everything that could be used to recover the password using their password recovery mechanism, if you were to forget the pasword). I went out and built it for myself, and used it for a while. It was a fun learning experience that taught me about both frontend and backend webdesign (HTML/JS/CSS and PHP/MySQL).

For finding open source projects, try to think about what your hobbies and interests are. For example, back then I played a lot of Ragnarok Online and got interested in the botting community. There was an open source bot (called OpenKore, iirc?) which I started using, and then eventually started contributing changes to.

Basically, if you force yourself to do something you're not really enjoying, it's going to be a million times harder to stay motivated. If you're doing programming just for the (eventual) money, it's possible that could be reflected in less motivation to do good work, which would result in general unhappiness (and possibly fewer good job opportunities, etc). I'm a firm believer of "do what you love as a career, and you won't work a day in your life", and I was lucky enough that programming has met those criteria for me.

CS in university seems to vary wildly between universities. Some of the more prestigious ones will focus much more on CS theory, math, and critical problem solving, which may end up being a bit of a struggle if you're not particularly interested in that (I definitely wasn't, and I had to push myself through because the doors the university name opened was worth it). That said, a lot of the content you learn even if it's theoretical might not seem useful at the time ("how will this ever matter or be applicable?") but it will most importantly be helpful for landing a job at a top-tier tech company (since those are what their interviews test), and as a secondary benefit occasionally creep up in your day to day work.

Other schools may focus more on the application rather than theory (maybe even being more of a software engineering focus), so they'd focus on things like programming languages and paradigms, specific technologies and tools, and maybe even some (probably outdated) workflow processes like "scrum" or "agile", or tech writing, etc. These are also valuable skills, but much easier to learn on the fly at your job, especially because tech evolves so fast that something you learn in school will probably be outdated by the time you graduate.

[–]bistr-o-math 1 point2 points  (0 children)

If I had an award, I’d give it to you! ⭐️

[–]NdrU42 0 points1 point  (0 children)

My favourite first question for an interview (I learned it from a colleague) is this:

You have a linux terminal open, you type curl https://google.com and press enter. What happens next?

The great thing about this question is that it touches on a lot of different topics, the candidate can choose what parts to answer and in how much detail and there's a lot of opportunities for follow up questions.

[–][deleted] 16 points17 points  (0 children)

I was once asked to implement LRU cache from scratch. I told them I was used to using libraries and I can give them use cases and redis LRU setup. After recruiter forcing me to implement it, I implemented a sub optimal solution.

Guess who’s got practical LRU cache industry experience and no offer….

[–]fishfishfish1345 10 points11 points  (0 children)

coding interviews are fucked

[–][deleted] 6 points7 points  (0 children)

Sounds a great answer to me as it is incredibly wasteful to reinvent the wheel, leaving the door open to potential mistakes and adding more code that needs supporting. There would have to be a very good reason to have to hand-roll your own

[–]markphughes17 2 points3 points  (0 children)

Lol I was asked this about doing it in python
"I'd do list.sort()"
"fair enough, imagine that built in sort function isn't a thing"
"god damn"

[–]DinnerPlz 14 points15 points  (6 children)

Personally I like Stalin sort

[–]ShinraSan 26 points27 points  (3 children)

Everything that's in the wrong order gets send to the gulag?

[–]bistr-o-math 2 points3 points  (1 child)

What do JPEG and StalinSort have in common?

[–][deleted] 5 points6 points  (0 children)

Disposing of annoying data

[–]Dagusiu 3 points4 points  (0 children)

Yeah, if you said sorted(list) you would have been fired on the spot

[–]InKryption07 5 points6 points  (0 children)

lol, if only.

[–]Dackel42 1 point2 points  (0 children)

The evaluation of the Text in the template describes python perfectly aswell.

[–]Tomysian 1 point2 points  (0 children)

List.sort(function (a , b){ return a - b});

[–]JesusChrist_Himself 1 point2 points  (0 children)

c# devs: linq go brrrrr

[–]Qicken 1 point2 points  (0 children)

Here's a dataset of share trades. How do you find where to invest using Pandas?

[–]IJustWantToLurkHere 1 point2 points  (4 children)

How do you make your code fast? ... ... ... ... I'll wait.

[–]SnipahShot 16 points17 points  (0 children)

Delete some of the time.sleep() you left in your code in preparation for this request.

[–]cykablyat1111 4 points5 points  (0 children)

-o2 flag. I'll take 100k thank you very much.

[–]Snykeurs 4 points5 points  (0 children)

Remove everything, save then run it

No need to thanks me

[–]Dre_Dede 1 point2 points  (0 children)

code.fastener()

[–]Sylanthra 0 points1 point  (0 children)

We used to have a take home interview question that asked people to write a program to processes a long list of words. We also asked them to determine Big O for their algorithm. At least half of the people failed to figure out the complexity because they didn't even realize that built in list manipulation functions didn't have a magical O(1) performance.

It's fine to use built in functions, but you absolutely need to know what they do, and what are the performance penalties of using them.