General doubt(applies to all questions)

how can we think of such algorithms within the time limit, at first my first thought is always related to the brute force but what should i do to think of more optmised algorithms

This thing will only be improved with more and more practice only, If you will practice more questions, your thinking for more optimised code will automatically starts developing on its own.