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
Optimizing LeetCode 1390: Four Divisors with Square Root Optimization
More Relevant Posts
-
🎯 #LeetcodePotd | Problem Solved with 99%+ Runtime Performance Sometimes the smartest solution isn’t fancy — it’s structured thinking: Just solved LeetCode 1984 – Minimum Difference Between Highest and Lowest of K Scores ✅ And honestly? This is a perfect example of how sorting + sliding window = instant clarity. 🧠 Problem in Simple Words You’re given student scores. Pick k students such that the difference between the highest and lowest score is as small as possible. 👉 Goal: Minimize (max − min) among any group of size k. 💡 Key Insight (Beginner Friendly) If the array is sorted, then: Any group of k students will be contiguous The difference becomes: nums[i + k − 1] − nums[i] So instead of brute force chaos, we: Sort the array Slide a window of size k Track the minimum difference Clean. Efficient. Scalable. ⏱️ Complexity Analysis Time Complexity: O(n log n) (sorting dominates) Space Complexity: O(1) (ignoring sorting internals) 📊 Submission Stats ✔ Accepted: 118 / 118 test cases ⚡ Runtime: 7 ms 🔥 Beats 99.17% of submissions 💾 Memory: 47.15 MB 🧠 Takeaway Sort first. Think visually. Then optimize. On to the next one. Consistency > motivation. 💪 #LeetCode #DSA #Java #ProblemSolving #Algorithms #SlidingWindow #Sorting #CodingJourney #BeginnersInTech #100DaysOfCode #SoftwareEngineering #InterviewPrep
To view or add a comment, sign in
-
-
✏️ DSA Diary Day 14/100 📊➗: Solving LeetCode’s “Maximum Dot Product of Two Subsequences” 🚀✨ Today I worked on a Dynamic Programming + Recursion + Optimization problem on LeetCode 🔥👇 👉 Maximum Dot Product of Two Subsequences This problem is a great example of how DP helps handle complex choices efficiently 🧠💡 🔹 My Approach 🛠️🧠 I used Recursion + Memoization (Top-Down DP) 🔁👇 🔸 Step 1: Define DP State 📌 dp(i, j) = Maximum dot product using elements from nums1[i…] elements from nums2[j…] 🔸 Step 2: Choices at Each Step 🔍 At every (i, j) position, we have 4 options: 1️⃣ Take both elements & continue nums1[i] * nums2[j] + dp(i+1, j+1) 2️⃣ Take both & stop here nums1[i] * nums2[j] 3️⃣ Skip nums1[i] dp(i+1, j) 4️⃣ Skip nums2[j] dp(i, j+1) We take the maximum of all these options 🔝✨ 🔸 Step 3: Memoization 🧠 To avoid recomputation, I used a 2D memo array This reduces time complexity from exponential → O(n*m) 🚀 🔸 Why NEG_INF? ⚠️ To ensure at least one pair is selected, I returned a very small value when indices go out of bounds. 🔹 Key Learnings 📚✨ ✅ DP is perfect for subsequence + optimization problems ✅ Always consider all possible choices ✅ Memoization saves massive computation time ✅ Handling negative values carefully is crucial ✅ Clean recursion = clear logic 🧠💯 🔥 This problem felt like a perfect mix of: 📊 Arrays + 🔁 Recursion + 🧠 DP + 📈 Optimization #LeetCode 🚀 #Java ☕ #DSA 🧠 #DynamicProgramming 📊 #ProblemSolving 💡 #CodingChallenge 💻 #100DaysOfCode 🔥 #DSADiaryByRethanya ✨ #Recursion 🔁 #Memoization 🧩 #LearnInPublic 📢 #TechJourney 🚀
To view or add a comment, sign in
-
-
Unification: Runtime Value (Erlang) vs. Compile-Time Type (Rust) How do you ensure two separate parts of your system "agree" with each other? It comes down to what you are unifying and when you do it. 🟢 Erlang: Unification by Value (Runtime) In Erlang, unification is a dynamic check performed at the moment of execution. By reusing the same variable name (Message) in the function head, the VM enforces value equality. The function will only execute if the incoming message is identical to the one already stored in the state. This allows the system to unify actual data points on the fly at the call site. 🦀 Rust: Unification by Type (Compile-Time) In Rust, unification is a structural constraint handled during the build. By using Associated Types, you prove to the compiler that the Message and the Store share a compatible identity. You aren't checking if the IDs are the same value; you are proving they are the same type. If you try to use a "UUID-based Message" with an "Integer-based Store," the code won't even compile. #Programming #RustLang #Erlang #Haskell #ComputerScience #SoftwareArchitecture #Backend #Types
To view or add a comment, sign in
-
-
🏎️ Day 4 of The Product-Engineer-Max Challenge > Reflections: - Rust’s ownership model replaces garbage collection with compile-time guarantees - Memory safety is enforced before runtime, not patched after crashes - Ownership is not about syntax, it’s about clear responsibility for memory - Stack memory is fast, predictable, and scope-bound - Heap memory is flexible but requires explicit ownership tracking - Rust decides safety based on where data lives (stack vs heap) - Every value has exactly one owner at any point in time - Moves are the default; copies are explicit and intentional - The Copy trait explains why primitives behave differently than String - Passing values to functions is conceptually the same as assignment - Ownership can be transferred, borrowed immutably, or borrowed mutably - Borrowing lets you use data without owning it - Immutable references are unlimited; mutable references are exclusive - Rust prevents data races by design, not by convention - Reference scopes end at last use, not at block boundaries - Dangling pointers are impossible in safe Rust - The compiler rejects references to data that won’t live long enough - Lifetimes exist to prove validity, not to confuse developers - Slices solve the “index out of sync” problem - Returning a slice ties data and logic together safely - &str is more powerful than String for APIs - String literals are already slices - Designing functions around &str improves flexibility and correctness - Slices generalize beyond strings to arrays and collections Progress till Now: - LeetCode | 9q Mastery | https://lnkd.in/g46vGtfU - CodeForces | 12q Mastery | https://lnkd.in/gWcjPeaW - Whack-A-Mole | Java Game Dev | https://lnkd.in/giq8PCEy - C++ STL | https://lnkd.in/gVQzFMhm Coding_is_meditation #ProductEngineer #RustLang #SystemsProgramming #MemoryManagement #SoftwareEngineering #BackendDevelopment #EngineeringMindset #LearnBuildShip #CareerJourney #TechLeadership
To view or add a comment, sign in
-
-
🚀 𝑫𝒂𝒚 7 𝒐𝒇 𝑴𝒚 𝑳𝒆𝒆𝒕𝑪𝒐𝒅𝒆 𝑱𝒐𝒖𝒓𝒏𝒆𝒚 | 𝑫𝑺𝑨 – 𝑺𝒕𝒂𝒄𝒌 (𝑱𝒂𝒗𝒂) Continuing my daily DSA practice with LeetCode 📘 Today was all about using stacks to solve real-world array problems efficiently and understanding the concept of Next Smaller Element. 🔹 𝑷𝒓𝒐𝒃𝒍𝒆𝒎 𝑺𝒐𝒍𝒗𝒆𝒅 𝑻𝒐𝒅𝒂𝒚: 𝑭𝒊𝒏𝒂𝒍 𝑷𝒓𝒊𝒄𝒆𝒔 𝑾𝒊𝒕𝒉 𝒂 𝑺𝒑𝒆𝒄𝒊𝒂𝒍 𝑫𝒊𝒔𝒄𝒐𝒖𝒏𝒕 𝒊𝒏 𝒂 𝑺𝒉𝒐𝒑 (https://lnkd.in/gNZSzHNQ) 🔹 Key Concept Used: Monotonic Stack (Next Smaller or Equal Element to the Right) 🔹 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 𝐀𝐧𝐚𝐥𝐲𝐬𝐢𝐬: Time Complexity: O(n) Space Complexity: O(n) 🔹 What I’m Learning: • Stack helps avoid unnecessary nested loops • Index-based stack usage simplifies discount calculation • Recognizing patterns like “next smaller element” is crucial • Clean logic + practice = faster problem solving Solving one problem a day and strengthening fundamentals step by step. Consistency over intensity.🚀 #LeetCode #DSA #Stacks #Java #ProblemSolving #DailyCoding #Consistency #LearningJourney #BackendDeveloper #2026Goals
To view or add a comment, sign in
-
-
🚀 Coding Spotlight: How to Find Numbers With Exactly Four Divisors! 🚀 The Challenge: Given an array of integers, for each number, we want to check if it has exactly four divisors. If it does, sum those divisors. Finally, add up all such sums for the entire array. Leetcode Problem:https://lnkd.in/ggkjSaca How Does the Logic Work? Let’s walk through it: 1. Loop Over Possible Divisors For each number, loop i from 1 up to the square root of num: If num % i == 0: That means i is a divisor. So is j = num / i (because i * j = num). 2. Handle Perfect Squares If i == j: This only happens if num is a perfect square (e.g., 4, 9, 16). In this case, only count i once as a divisor and add it to the sum. 3. Handle Distinct Divisor Pairs If i != j: Both i and j are distinct divisors. Count both and add both to the sum. 4. Early Exit for Efficiency If at any time count > 4: We can immediately return 0 because we only care about numbers with exactly 4 divisors. This saves time by avoiding unnecessary checks for numbers with many divisors. 5. Final Check After finishing the loop: If the count is exactly 4, return the sum. Otherwise, return 0. Why Return Early When count > 4? Performance Boost: As soon as we know a number has more than four divisors, we don’t need to keep checking. This keeps our algorithm fast, especially for large numbers with many divisors. Accurate Results: We only care about numbers with exactly four divisors, so anything else can be skipped! #Java #Coding #Algorithms #LeetCode #ProblemSolving #DataStructures #Tech #Programming #EfficientCode #NumberTheory #Developer #LearnToCode #SoftwareEngineering
To view or add a comment, sign in
-
-
𝗧𝗵𝗶𝗻𝗸𝗶𝗻𝗴 𝗕𝗲𝘆𝗼𝗻𝗱 𝘁𝗵𝗲 𝗗𝗶𝘃𝗶𝘀𝗶𝗼𝗻 𝗢𝗽𝗲𝗿𝗮𝘁𝗼𝗿 I recently tackled the "Product of Array Except Self" problem. My first instinct? Use the division operator. It’s quick, but it's brittle, especially if your data contains a zero. I challenged myself to find a more robust way and discovered the Prefix & Suffix product pattern. Instead of looking at the whole array at once, you calculate the product of everything to the left, then everything to the right. The Results: Logic: O(n) time complexity. Efficiency: O(1) extra space (excluding the output array). Reliability: Handles zeros perfectly without crashing. It’s a powerful reminder that sometimes the most obvious tool isn't the most effective one. I'm learning how to write code that doesn't just work, but scales. #Java #LeetCode #SoftwareEngineering #ProblemSolving #Algorithms #CleanCode #GrowthMindset
To view or add a comment, sign in
-
-
🔥 LeetCode Daily | Hard Problem Cracked (1458: Max Dot Product of Two Subsequences) 🔥 Another day, another reminder that real problem-solving begins where shortcuts fail. Today’s challenge wasn’t about syntax or speed — it was about decision-making under constraints. With negative numbers in play, greedy approaches collapse fast. The only way forward? Clean, well-structured Dynamic Programming. 🧠 What made this problem interesting: • Choosing take vs skip at every index • Handling negative values without breaking the logic • Ensuring subsequences remain non-empty (the real twist) ⚙️ Approach: Dynamic Programming to track the best possible dot product at each state while preserving order and maximizing value. 📊 Complexity: • Time: O(n × m) • Space: O(n × m) 💡 Lesson learned: Hard problems don’t test how fast you code. They test how clearly you think when the obvious approach fails. Consistency + fundamentals = inevitable progress. On to the next challenge. 🚀 #LeetCode #LeetCodeDaily #HardProblems #DynamicProgramming #DP #DataStructures #Algorithms #DSA #ProblemSolving #CodingInterview #InterviewPreparation #CompetitiveProgramming #Java #JavaDeveloper #SoftwareEngineering #ComputerScience #TechCareers #DeveloperJourney #100DaysOfCode #DailyCoding #ConsistencyWins
To view or add a comment, sign in
-
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development