implementation of problem 2 in pythong using constant time algorithm