Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This is a very good list - I was asked a bunch of these & thankfully I was able to solve them & land the job. It's significantly harder to solve these if you require immutability (which they did in my case, since we work with Scala)

For example, the stock price problem (https://www.interviewcake.com/question/stock-price ), if you insist the solution has no mutables, I really don't know how a Java/Python/C guy would approach it. In Scala, you'd do

       import math._
       val s = List.fill[Int](100)((random*1000).toInt)
       s./:((s.head,0)){(a,b)=>(min(b,a._1),max(a._2,b-min(b,a._1)))}._2


I can't really understand your version, I'm not familiar with scala. Is this somewhat equivalent? I tried to use Clojure's loop/recur but I'm too much of a noob. :(

    def max_profit(stocks):
        def r(stocks, profit, lowest):
            return r(stocks[1:],
                     max([profit, stocks[0] - lowest]),
                     min([lowest, stocks[0]]))
        return r(stocks[1:], 0, stocks[0])


I think so. You've basically reimplemented a fold, but clojure stdlib has a built-in left fold. See line 84 https://github.com/clojure/clojure/blob/master/src/clj/cloju...


Can't you always mechanically convert an iteration into a fold like that?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: