Optimizing LeetCode 1390: Four Divisors with Square Root Optimization

Optimization Matters: How I solved LeetCode 1390 (Four Divisors) 🚀 When solving algorithmic problems, the difference between a "working" solution and an "accepted" solution usually comes down to one thing: Time Complexity. The Challenge: The problem asks for the sum of divisors of numbers that have exactly four divisors. With values up to 10⁵and an array size of 10⁴, a brute-force approach (checking every number from 1 to n for every element) would result in O(N×M) complexity. In the worst case, that's 10⁹ operations—way too slow for most environments. My Evolution of Logic: Initially, I considered a simple linear scan for divisors. However, I realized I needed a more mathematical approach to stay within the time limits. The Optimized Approach: I shifted to a Square Root of x optimization. Here’s why it works: Divisor Pairs: Divisors always appear in pairs. For a number x, if i is a divisor, then x/i is also a divisor. One will always be < √xand the other will be >=√x Efficiency: By only iterating up to √x, I reduced the operations per number from 100,000 to just 316. The Logic: Loop from 1 to √x If (x% i == 0), identify if it’s a perfect square (i == x/i) or a distinct pair. Early Exit: If the divisor count exceeds 4, I immediately break the loop. This "pruning" saves significant CPU cycles. Only if the final count is exactly 4, do I add the sum to the total. Key Takeaway: Writing code that works is the first step, but writing code that is performant is the goal. This approach brought the complexity down to O(N√M}), making the solution run almost instantly. #SoftwareEngineering #Coding #Optimization #Java #LeetCode #DSA #ContinuousLearning #DailyCoding #LeetCodeChallenge

  • text

To view or add a comment, sign in

Explore content categories