Moving Beyond Brute Force: Optimizing Sum of Distances 🚀 In software engineering, writing code that works is only the first step. Writing code that scales is where the real challenge lies. I recently tackled LeetCode 2615 (Sum of Distances), and it’s a perfect example of why understanding time complexity is crucial for a developer. The Problem: Given an array, for each element, calculate the sum of absolute differences ∣i−j∣ ∣i−j∣ for all other indices j j where the values are identical.The Developer’s Approach: 1️⃣ Identify the Bottleneck: A naive nested loop ( O(n2) O(n2 ) ) would attempt billions of operations for an input size of 105 105 , leading to a Time Limit Exceeded (TLE) error. We need an O(n) O(n) solution.2️⃣ Data Grouping: Use a HashMap to group indices of the same value. This narrows our focus only to relevant elements. 3️⃣ The Math Pivot (Prefix Sums): Instead of re-calculating distances for every index, we use mathematics. The total distance for any index can be split into: Left Side: (count_of_elements_on_left * current_index) - (sum_of_left_indices) Right Side: (sum_of_right_indices) - (count_of_elements_on_right * current_index) The Result: By maintaining a running prefix sum while iterating through the grouped indices, we transform a complex quadratic problem into a linear one. Key Takeaway: When you see "sum of absolute differences" in an array, think Prefix Sums. It’s one of the most powerful tools in a developer’s arsenal to turn inefficient logic into high-performance code. How do you approach optimization when you hit a performance wall? Let’s discuss in the comments! 💻✨ #SoftwareEngineering #Coding #Algorithms #Optimization #LeetCode #ProblemSolving #DeveloperMindset #CleanCode
Optimizing Sum of Distances with Prefix Sums
More Relevant Posts
-
Day#18 🚀 Solved: LeetCode 141 – Linked List Cycle | Fast & Slow Pointer Detecting cycles in a linked list is a classic problem — elegantly solved with two pointers: 👉 Must detect without modifying the list and ideally in O(1) space 🔹 Problem: Given the head of a singly linked list, determine if the list has a cycle. Return true if a cycle exists, else false Cannot modify the nodes 💡 Key Intuition – Fast & Slow Pointer (Floyd’s Tortoise & Hare) “Move one pointer twice as fast as the other. If a cycle exists, fast will eventually meet slow.” 🔄 Process: Initialize slow = head, fast = head Move slow 1 step at a time Move fast 2 steps at a time If fast meets slow → cycle exists If fast reaches null → no cycle 🔹 Pseudo Code: function hasCycle(head): slow = head fast = head while fast != null AND fast.next != null: slow = slow.next fast = fast.next.next if slow == fast: return true return false 🔍 Example: Input: 3 → 2 → 0 → -4 → back to 2 slow moves 1 step, fast moves 2 steps After a few iterations → slow = fast → cycle detected ✅ Input: 1 → 2 → 3 → null fast reaches null → no cycle ❌ 💡 Why this works: • Fast moves 2× → if there’s a cycle, it will eventually lap slow • Constant space → O(1) • Elegant and deterministic solution ⏱️ Complexity: • Time → O(n) ✅ • Space → O(1) ✅ 📌 Why Two Pointers? • Perfect for linked lists & sequences • Avoids extra memory like hash sets • Detects cycles in one pass 🧠 What I learned: • Fast & slow pointer technique is generalizable to other sequence problems (like Happy Numbers) • Key idea: difference in speeds ensures meeting inside cycles • Elegant solutions often combine simple pointers + math reasoning 🔁 Key takeaway: 👉 “Move fast, detect slow — cycles cannot hide.” #LeetCode #LinkedList #TwoPointers #Algorithms #DataStructures #SoftwareEngineering #CodingInterview #ProblemSolving #SDE
To view or add a comment, sign in
-
Most developers don’t have a coding problem. They have a thinking problem. And it shows up every time they write code that works… but doesn’t scale. Take this simple problem: Find two numbers that add up to a target. A lot of people solve it with nested loops. And yes, it works. But it’s O(n²). Now imagine running that on real data. Here’s where great developers think differently. Instead of repeatedly searching, they ask: “What if I store what I’ve already seen?” That one question introduces a hash map. Now the solution becomes: → One pass → O(n) time → Instant lookups Same problem. Completely different performance. This is the power of Hash Tables & Sets. They don’t just optimize your code, they change how you think. Once you understand this, you start spotting patterns everywhere: → Counting frequencies → Detecting duplicates → Finding pairs instantly → Grouping related data → Solving subarray problems And here’s the shift that separates good from great: You stop asking “How do I solve this?” And start asking “What should I store?” Because in many cases: The fastest solution isn’t about searching better… it’s about avoiding the search entirely. If this clicked for you, you’re thinking like a problem solver. #DataStructures #Algorithms #DSA #SoftwareEngineering #TechGrowth #CodingInterview #LearnToCode #web3
To view or add a comment, sign in
-
𝗠𝗼𝘀𝘁 𝗱𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀 𝘁𝗵𝗶𝗻𝗸 𝘁𝗵𝗲 𝗳𝗮𝘀𝘁𝗲𝘀𝘁 𝘀𝗼𝗿𝘁𝗶𝗻𝗴 𝗮𝗹𝗴𝗼𝗿𝗶𝘁𝗵𝗺 𝗶𝘀 𝗮𝗹𝘄𝗮𝘆𝘀 𝘁𝗵𝗲 𝗕𝗲𝘀𝘁 🤔 I used to think the same… until I noticed something interesting 👀 We learn that 𝗠𝗲𝗿𝗴𝗲 𝗦𝗼𝗿𝘁 (O(n log n)) is better than 𝗜𝗻𝘀𝗲𝗿𝘁𝗶𝗼𝗻 𝗦𝗼𝗿𝘁 (O(n²)). So naturally, Merge Sort should always win… right? Not really ❌ Here’s the twist 👇 For 𝘀𝗺𝗮𝗹𝗹 𝗶𝗻𝗽𝘂𝘁𝘀, a simple nested-loop algorithm like Insertion Sort can actually be 𝗳𝗮𝘀𝘁𝗲𝗿 than Merge Sort ⚡ Why? 🤔 Because: * Merge Sort uses recursion (function call overhead) 🔁 * It requires extra memory 🧠 * More operations even for tiny arrays 📊 While Insertion Sort: * Uses simple loops 🔄 * No recursion overhead 🚫 * Performs fewer operations when input is small or nearly sorted ⚡ 👉 That’s why many real-world systems don’t rely on just one algorithm. They combine both: * Use Merge Sort (or Quick Sort) for large inputs 🚀 * Switch to Insertion Sort when the data becomes small 🔁 Lesson learned: Big-O notation doesn’t tell the full story 📉 Sometimes, the “simpler” algorithm wins 💡 #DSA #Algorithms #Coding #SoftwareEngineering #ProblemSolving #TimeComplexity #BigO #ProblemSolving #CodeOptimization #TechLearning #DeveloperJourney #LeetCode
To view or add a comment, sign in
-
-
Day#16 🚀 Solved: LeetCode 186 – Reverse Words in a String II | In-Place Two-Pointer: A great follow-up to the classic reverse words problem — but with a twist: 🔹 Problem: Given a character array s, reverse the order of words in-place. 👉 No extra array allowed 👉 Words are separated by single spaces 👉 Input is a char array, not a string 💡 Key Intuition – Reverse Twice “Reverse the whole string, then reverse each word.” 🔄 Process: Reverse entire array Traverse and identify each word Reverse each word individually 🔹 Pseudo Code: function reverseWords(s): reverse(s, 0, n-1) start = 0 for i from 0 to n: if i == n or s[i] == ' ': reverse(s, start, i-1) start = i + 1 🔍 Example: Input: ["t","h","e"," ","s","k","y"] Step 1 → Reverse whole array 👉 "yks eht" Step 2 → Reverse each word 👉 "sky the" 💡 Why this works: • First reversal fixes word order • Second reversal fixes character order • No extra memory needed ⏱️ Complexity: • Time → O(n) • Space → O(1) ✅ 📌 Why Two Pointers? • Needed to reverse segments efficiently • Avoids extra memory usage • Enables in-place transformation 🧠 What I learned: • In-place problems require thinking in transformations • Two-pointer technique is extremely powerful for arrays/strings • Breaking problems into steps simplifies complex constraints • Small variations in problems can change the entire approach 🔁 Key takeaway: 👉 “Reverse globally, then fix locally.” #LeetCode #Strings #TwoPointers #Algorithms #DataStructures #SoftwareEngineering #CodingInterview #ProblemSolving #SDE
To view or add a comment, sign in
-
Things we learned on the job at Labsmart. Well covered by Lalitha Mangalam M worth a read for anyone building a SaaS today.
Ruby on Rails Developer@ Labsmart Healthcare Technologies | Passionate Singer | Driving Impact through Innovative Solutions
5 Things I now think about before writing a single line of code! Most backend bugs aren't written in the code. They're written 5 minutes before the coding — when nobody stops to think. Here's what I ask myself before I open the editor 👇 1. What does the data access pattern look like? The first question isn't "what do I store?", it's "how will it be read?" By ID? By date range? Sorted, paginated, filtered? The access pattern is the skeleton of your query design. Build the wrong skeleton and no amount of indexing will save you. I learned this the hard way. Now it's the first thing I ask. 2. Am I putting the code in the right place? Thin controllers, fat models, clean views — business logic, validations, and formatting in their separate concerns. Keep naming clean, intent obvious and no magic numbers. Before I write anything, I ask: does this belong here? Wrong layer today = impossible to test and maintain tomorrow. 3. Is there a hidden N+1 waiting to happen? Any time I'm fetching a list and doing something with each item — I pause. That's where N+1 queries hide. One query becomes 500 in prod. I think about batch fetching, eager loading, and query consolidation. 4. Who reads the error messages? Every endpoint I write will fail for someone, someday. I ask: when it does, will the error tell them what went wrong — or will it send them to me at 4pm on a Friday? Useful errors are part of the feature. Not an afterthought. 5. What does "done" actually mean for this feature? Not just "it works locally." Done means: it handles bad input, it doesn't silently drop data, and someone else can read it six months from now. Define done before you start — not after you ship. Older me would just open the editor and start typing. The present me spends 5 minutes thinking — and saves 5 hours debugging. 🔁 Repost if this helps someone on your team. Which of these do you think about before writing code? And what's missing from my list? Drop it below 👇 #BackendDevelopment #CleanCode #Coding #BestPractices
To view or add a comment, sign in
-
5 Things I now think about before writing a single line of code! Most backend bugs aren't written in the code. They're written 5 minutes before the coding — when nobody stops to think. Here's what I ask myself before I open the editor 👇 1. What does the data access pattern look like? The first question isn't "what do I store?", it's "how will it be read?" By ID? By date range? Sorted, paginated, filtered? The access pattern is the skeleton of your query design. Build the wrong skeleton and no amount of indexing will save you. I learned this the hard way. Now it's the first thing I ask. 2. Am I putting the code in the right place? Thin controllers, fat models, clean views — business logic, validations, and formatting in their separate concerns. Keep naming clean, intent obvious and no magic numbers. Before I write anything, I ask: does this belong here? Wrong layer today = impossible to test and maintain tomorrow. 3. Is there a hidden N+1 waiting to happen? Any time I'm fetching a list and doing something with each item — I pause. That's where N+1 queries hide. One query becomes 500 in prod. I think about batch fetching, eager loading, and query consolidation. 4. Who reads the error messages? Every endpoint I write will fail for someone, someday. I ask: when it does, will the error tell them what went wrong — or will it send them to me at 4pm on a Friday? Useful errors are part of the feature. Not an afterthought. 5. What does "done" actually mean for this feature? Not just "it works locally." Done means: it handles bad input, it doesn't silently drop data, and someone else can read it six months from now. Define done before you start — not after you ship. Older me would just open the editor and start typing. The present me spends 5 minutes thinking — and saves 5 hours debugging. 🔁 Repost if this helps someone on your team. Which of these do you think about before writing code? And what's missing from my list? Drop it below 👇 #BackendDevelopment #CleanCode #Coding #BestPractices
To view or add a comment, sign in
-
I didn’t break my code. I broke my environment. And that lesson changed how I build software forever. For the past few days, I was working on an OCR-based backend system. Everything looked correct - the logic, the APIs, the flow. But nothing worked. Errors kept changing: • “No module named paddle” • “set_optimization_level not found” • “NumPy ABI mismatch” • “PyMuPDF build failed” At first, I thought: my code is wrong. But the truth was harsher - and more important: 👉 In real-world systems, code is only 50% of the problem. The other 50% is environment, dependencies, and compatibility. Here’s what I learned (the hard way): 🔹 Version mismatch can break everything Even if your code is perfect, incompatible library versions will crash your system. 🔹 Python version matters more than you think Some ML libraries still don’t support newer versions (like 3.12). 🔹 Virtual environments are not optional If you don’t isolate dependencies, you’ll chase ghosts for hours. 🔹 NumPy 2.0 broke half the ML ecosystem Real-world lesson: “latest” is not always “stable”. After fixing everything, the system finally worked. Not because I wrote better code - but because I understood the system behind the code. 💡 Biggest takeaway: A good developer writes code. A great developer understands the environment it runs in. If you’re building in AI/ML or backend systems, remember this: 👉 Your real skill is not just solving problems - 👉 It’s debugging chaos. #SoftwareEngineering #BackendDevelopment #AI #MachineLearning #Debugging #Python #DeveloperJourney #BuildInPublic
To view or add a comment, sign in
-
#69DayStreak 🚀 110 LeetCode Problems Solved — Consistency + Pattern Mastery Today marks a solid milestone in my Data Structures & Algorithms journey: 110 problems solved on LeetCode with a 69-day streak and 83 active days in 2026. But more than the number, what matters is the pattern recognition I’m building every single day. 🧠 Problem Focus: Top K Frequent Elements (LeetCode 347) A classic Medium-level problem that tests your understanding of: Hashing Sorting with custom comparators Frequency-based decision making 💡 Approach: HashMap + Custom Sorting Instead of jumping straight to advanced optimizations, I focused on mastering the core logic first: ✔️ Build a frequency map using HashMap ✔️ Extract unique elements into a list ✔️ Sort using a custom comparator (descending frequency) ✔️ Return the top K elements This reinforces a key principle: 👉 Strong fundamentals beat premature optimization. ⚙️ Complexity Breakdown Time Complexity: O(n log n) Space Complexity: O(n) 📌 Note: This can be optimized to: O(n log k) using a Heap (PriorityQueue) O(n) using Bucket Sort …but clarity > cleverness when learning. 📊 Progress Snapshot Easy: 77 Medium: 32 Hard: 1 Total: 110 📈 What This Milestone Really Means This journey is helping me: Recognize problem patterns faster Improve time-space tradeoff decisions Write cleaner and more structured code Stay consistent even on low-motivation days Consistency is turning effort into skill. 💬 For Fellow Learners If you're learning DSA: Don’t rush to the most optimal solution First, understand why a solution works Then optimize it step by step #LeetCode #DataStructures #Algorithms #Java #DSA #CodingInterview #ProblemSolving #100DaysOfCode #SoftwareEngineering #TechGrowth #Consistency #LearningInPublic
To view or add a comment, sign in
-
-
🚀 Binary Search | Clean Thinking > Complex Code Just solved the classic Binary Search LeetCode Problem 704 with 100% test cases passing and optimal runtime. Here’s a structured breakdown of my approach 👇 🎯 Problem Goal Find the index of a target element in a sorted array using an efficient approach. 🧠 My Approach 1. Define the Search Space → Initialize low = 0, high = n - 1 2. Apply Binary Search Logic → Compute mid → Compare target with nums[mid] → Eliminate half of the search space each step 3. Maintain Clean Boundaries → Move low or high precisely to avoid infinite loops 4. Exit Condition → Return index if found → Else return -1 ⚡ What I Focused On • Writing minimal, readable code • Avoiding unnecessary conditions • Staying calm and methodical • Trusting fundamentals over shortcuts 💡 Key Takeaway Strong fundamentals + structured thinking = fast and reliable problem solving 📈 Outcome ✔️ 100% test cases passed ✔️ Optimal time complexity: O(log n) ✔️ Clean execution without overthinking Building this discipline every day. Small wins → Big growth 💪 #BinarySearch #DataStructures #ProblemSolving #LeetCode #CodingJourney #TechGrowth #Consistency #LearningInPublic
To view or add a comment, sign in
-
-
Not using Claude Code in 2026 is like ignoring Stack Overflow in 2016. You can survive. But everyone around you is moving faster. Most engineers open Claude Code and just type. They use maybe 5 commands. There are 93. Swipe through. Save this. 👇 The commands that change everything: → /plan — Read before you touch anything → /memory — Context that survives every session → /agents — Parallel sub-agents working simultaneously → /security-review — Audit before you push, not after → /simplify — 3 agents: architecture + duplicates + performance → "Think harder" — Force high effort on one turn → "Ultra think" — Maximum reasoning depth The CLI flags nobody uses: → claude --worktree — Isolated git worktree for parallel work → claude --model opus — Specify model at launch → claude --agents '{json}' — Define sub-agents at launch → claude --dangerously-skip-permissions — No permission prompts All 93 commands across 10 slides above. Bookmark this before you forget. 🔖 Follow Mohamed Khasim for more on Data Engineering + AI. Repost if this helps someone in your network. Which command are you trying first? Drop it below 👇 Credit: Charlie Hills 🦩 #ClaudeCode #AI #DataEngineering #Productivity #Anthropic #AITools #DeveloperTools #Coding
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