Rippling interview question

how to improve the time complexity