LeetCode Algorithm Optimization Trick

𝗘𝘃𝗲𝗿 𝗻𝗼𝘁𝗶𝗰𝗲𝗱 𝘀𝗼𝗺𝗲 𝘀𝗼𝗹𝘂𝘁𝗶𝗼𝗻𝘀 𝗼𝗻 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝘁𝗵𝗮𝘁 “𝗯𝗲𝗮𝘁 𝟭𝟬𝟬%”? __import__("atexit").register(   lambda: open("display_runtime.txt", "w").write("0") ) Looks like a hacker trick. Feels smart. 𝗪𝗵𝗮𝘁 𝘁𝗵𝗶𝘀 𝗰𝗼𝗱𝗲 𝗮𝗰𝘁𝘂𝗮𝗹𝗹𝘆 𝗱𝗼𝗲𝘀 (𝗹𝗶𝗻𝗲 𝗯𝘆 𝗹𝗶𝗻𝗲):  • 𝗮𝘁𝗲𝘅𝗶𝘁 → runs code when the program is about to exit  • 𝗿𝗲𝗴𝗶𝘀𝘁𝗲𝗿(...) → hooks a function to run at the very end  • 𝗼𝗽𝗲𝗻(...).𝘄𝗿𝗶𝘁𝗲("𝟬") → overwrites the file LeetCode reads to show runtime So when execution finishes, the runtime file gets replaced with 0. The algorithm didn’t get faster. Only the displayed number did. 𝗟𝗲𝘀𝘀𝗼𝗻: If you don’t understand how a metric is calculated, you’ll optimize the metric — not the system. #moxcode #Python #LeetCode #Engineering #SystemsThinking #LearningInPublic

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories