mercredi 28 juillet 2021

Turning a linear time for loop into a log(n) time function?

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:

  1. Ensuring that weights be cumulative [0.25, 0.5, 0.25] -> [0.25, 0.75, 1], saving as c_arr

  2. Produce a random number between [0,1] save as a val, then iterate through my c_arr via a for loop. If val is > the ith element in c_arr, continue, else return the name associated with the ith element.

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?




Aucun commentaire:

Enregistrer un commentaire