Optimize LeetCode 319 with Math.sqrt() for O(1) Time Complexity

Day 8 of Daily DSA 🚀 Solved LeetCode 319: Bulb Switcher 💡 Initially, the brute-force idea was to simulate all rounds using loops — but that leads to O(n) time complexity. 🔍 Key Insight (Math wins here): A bulb ends up ON only if it is toggled an odd number of times. This happens only for perfect squares, because only perfect squares have an odd number of divisors. So instead of looping till n, we can directly count perfect squares using: return (int) Math.sqrt(n); Why Math.sqrt() over loop? ✅ Reduces time complexity from O(n) → O(1) ✅ Cleaner & more readable code ✅ Much faster for large inputs Complexity: • Time: O(1) • Space: O(1) LeetCode Stats: • Runtime: 0 ms (Beats 100%) • Memory: 42.25 MB This problem is a great reminder that sometimes math is the real optimization 🧠✨ #DSA #LeetCode #Java #MathOptimization #ProblemSolving #DailyCoding #Consistency

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories