In an interview, I was asked to describe a function that could return a random number given an object with {names:weights} as an input. I would be allowed to use a library to generate numbers between [0,1] but nothing else. I answered that the task need be broken in down into:
Ensuring that weights be cumulative
[0.25, 0.5, 0.25]->[0.25, 0.75, 1], saving asc_arrProduce a random number between
[0,1]save as aval, then iterate through myc_arrvia a for loop. Ifvalis > theithelement inc_arr, continue, else return the name associated with theithelement.
My interviewer noted that this was acceptable, however, asked if I could articulate its performance using Big O notation. I'm not very knowledgeable here but answered that it should be in linear time. He responded that this is true; however, the pseudo could function could be improved to log(n) time.
To my knowledge, log(n) time would mean not iterating through each and every integer in the range [0,1,2,3,4,5,6,7,8...x] but rather something like [1,2,4,8,...X]. I'm not sure that this is validated. But even if it is, I'm not sure how the pseudo code function could be improved such that it didn't need to iterate through every element in c_arr in a linear fashion.
Could someone explain?