🚀 Day 54 of 100 Days LeetCode Challenge Problem: Sum of Distances Day 54 is a smart prefix sum + hashmap optimization problem 🔥 💡 Key Insight: For each index i, we need: 👉 Sum of distances to all indices having the same value Brute force would be: O(n²) ❌ Too slow 🔍 Core Approach (Optimized): 1️⃣ Group Indices by Value Use a HashMap: value → list of indices Example: 1 → [0, 3, 5] 2️⃣ Use Prefix Sums For each index list: Compute prefix sums of positions 👉 This allows distance calculation in: O(1) per index 3️⃣ Distance Formula For position idx inside a group: 👉 Left contribution: idx * countLeft - sumLeft 👉 Right contribution: sumRight - idx * countRight Add both for total distance ✅ 💡 Why This Works: Instead of recalculating distances repeatedly: ⚡ Prefix sums reuse previous computations efficiently 🔥 Time Complexity: O(n) Efficient and scalable 🚀 🔥 What I Learned Today: Prefix sums are powerful beyond arrays Grouping similar values simplifies complex problems Math-based optimization can remove nested loops entirely 📈 Challenge Progress: Day 54/100 ✅ More than halfway done! LeetCode, Prefix Sum, HashMap, Arrays, Optimization, Distance Calculation, DSA Practice, Problem Solving #100DaysOfCode #LeetCode #DSA #CodingChallenge #PrefixSum #Hashing #Arrays #ProblemSolving #TechJourney #ProgrammerLife #SoftwareDeveloper #CodingLife #LearnToCode #Developers #Consistency #GrowthMindset #InterviewPrep
Sum of Distances LeetCode Challenge with Prefix Sums and HashMap
More Relevant Posts
-
🚀 Day 41 of 100 Days LeetCode Challenge Problem: Minimum Distance Between Three Equal Elements I Day 41 is a clean hashing + index tracking + greedy observation problem 🔥 💡 Key Insight: We need three indices (i, j, k) such that: 👉 nums[i] == nums[j] == nums[k] And minimize: 👉 |i - j| + |j - k| + |k - i| 🔍 Simplification Trick: If we sort indices → i < j < k, then: 👉 Distance becomes: (j - i) + (k - j) + (k - i) = 2 * (k - i) 🔥 So we only need to: 👉 Minimize (k - i) for any 3 equal elements 🔍 Core Approach: 1️⃣ Group Indices by Value Use a hashmap: value → list of indices 2️⃣ Check Each Group If size ≥ 3: Slide window of size 3 Compute k - i 3️⃣ Track Minimum Distance Answer = 2 * (k - i) 👉 If no valid triplet → return -1 🔥 What I Learned Today: Simplifying formulas can reduce complexity drastically Hashing helps group related data efficiently Sliding window works even on index lists 📈 Challenge Progress: Day 41/100 ✅ Beyond halfway to 50! LeetCode, HashMap, Arrays, Greedy, Sliding Window, Optimization, DSA Practice, Coding Challenge, Problem Solving #100DaysOfCode #LeetCode #DSA #CodingChallenge #Hashing #Arrays #ProblemSolving #TechJourney #ProgrammerLife #SoftwareDeveloper #CodingLife #LearnToCode #Developers #Consistency #GrowthMindset #InterviewPrep
To view or add a comment, sign in
-
-
🚀 LeetCode Day Problem Solving 🚀 Day-83 📌 Problem: Find the smallest common element present in both sorted arrays 🔥 If no common element exists → return -1 🧠 Example: Input: nums1 = [1,2,3] nums2 = [2,4] ✅ Output: 2 💡 Why? Common elements are: [[2]] Smallest common element = 2 ✅ 💡 Key Insight (Very Important 🔥): 👉 Both arrays are already SORTED ⚡ So instead of brute force checking every pair ❌ We can use: #️⃣ Two Pointer Technique 🚀 ⚡ Core Idea: Maintain pointers: ✔ i for nums1 ✔ j for nums2 Case 1️⃣: If: [nums1[i] = nums2[j]] ✅ Found smallest common element immediately because arrays are sorted 🔥 Case 2️⃣: If: [nums1[i] < nums2[j]] 👉 Move i forward because smaller value cannot match future larger values Case 3️⃣: If: [nums1[i] > nums2[j]] 👉 Move j forward 🧠 Why This Works? Since arrays are sorted: ✔ Once a smaller value is skipped, it can never become useful later So we eliminate unnecessary comparisons efficiently ⚡ ⚡ Algorithm: 1️⃣ Initialize: ✔ i = 0 ✔ j = 0 2️⃣ Traverse both arrays: ✔ If equal → return value ✔ Else move pointer with smaller value 3️⃣ If traversal ends → return -1 🔥 Example Walkthrough: nums1 = [1,2,3,6] nums2 = [2,3,4,5] Step 1: Compare: [1 \text{ and } 2] 1 < 2 👉 Move first pointer Step 2: Compare: [2 \text{ and } 2] ✅ Match found Answer = 2 📊 Complexity Analysis: ⏱ Time Complexity: [O(n+m)] where n and m are array sizes 📦 Space Complexity: O(1) 🧠 What I Learned: ✔ Two Pointer Technique ✔ Efficient traversal of sorted arrays ✔ Avoiding brute force comparisons 🔥 Day 83 Completed! Sorted arrays often unlock elegant linear-time solutions 💪 #Leetcode #DSA #ProblemSolving #BitManipulation #CodingJourney #InterviewPreparation #Consistency #MilanSahoo 🚀
To view or add a comment, sign in
-
-
🚀 Day 42 of 100 Days LeetCode Challenge Problem: Minimum Distance Between Three Equal Elements II Day 42 builds on Day 41—but now expects a more optimized and scalable solution 🔥 💡 Key Insight: Same observation holds: 👉 For sorted indices i < j < k Distance = 2 * (k - i) So again, we aim to: 👉 Minimize the gap between first and third occurrence 🔍 What’s Different Here? Larger constraints → need efficient single-pass processing Avoid storing large lists unnecessarily 🔍 Core Approach (Optimized): 1️⃣ Use HashMap with Sliding Tracking For each value: Track last two occurrences dynamically 2️⃣ When Third Occurrence Found: Compute: k - i using stored indices Update minimum 3️⃣ Shift Window Move forward: Drop oldest index Keep last two for next computation 👉 This avoids storing full index lists 🔥 Why This Works: Only 3 indices matter at a time Sliding window over occurrences = optimal 👉 If no valid triplet → return -1 🔥 What I Learned Today: Same problem → better constraints = better optimization Sliding window can be applied on index occurrences Space optimization is as important as time 📈 Challenge Progress: Day 42/100 ✅ Strong progress continues! LeetCode, HashMap, Sliding Window, Arrays, Optimization, Greedy, DSA Practice, Coding Challenge, Problem Solving #100DaysOfCode #LeetCode #DSA #CodingChallenge #Hashing #SlidingWindow #Optimization #ProblemSolving #TechJourney #ProgrammerLife #SoftwareDeveloper #CodingLife #LearnToCode #Developers #Consistency #GrowthMindset #InterviewPrep
To view or add a comment, sign in
-
-
💡 LeetCode Daily — Problem Solved: Consecutive Numbers Sum (Hard) This one looked like a brute-force playground… but turned out to be a math + observation driven problem. At first glance, the idea is simple: 👉 Try all possible consecutive sequences and check if they sum to n But that approach quickly becomes inefficient. So I reframed the problem. 🔍 Simple Visualization Instead of thinking in terms of sequences, I shifted to equation form: If a number n can be written as: -> k consecutive numbers starting from x, then: n = x + (x+1) + (x+2) + ... + (x+k-1) Which simplifies to: 👉 n = kx + k(k-1)/2 Now the problem becomes: Find values of k such that (n - k*(k-1)/2) is divisible by k That’s it. No need to build sequences. ⚙️ My Approach Iterate over possible values of k. Use the formula to avoid constructing arrays. Check divisibility condition. Count valid cases. Also used: Clean arithmetic instead of simulation. Focus on constraints to limit iterations. 🧠 What I Learned Hard problems aren’t always about complex code. Sometimes they’re about: Translating problems into math. Eliminating unnecessary work. Seeing structure where others see loops. 📊 Consistency Snapshot Total active days: 76 Max streak: 69 days Still working on thinking faster, not just coding faster. #LeetCode #DSA #ProblemSolving #MathThinking #Consistency #DailyCoding
To view or add a comment, sign in
-
-
🌟 Day 4 of #30DaysOfLeetCode 🌟 🔍🎯 Problem: Binary Search Today’s problem introduced one of the most important searching algorithms in DSA — Binary Search. It was exciting to see how efficiently we can search in a sorted array. 🚀 🧩 Problem Breakdown Input: Sorted integer array and a target value Output: Index of the target element or -1 if not found Objective: Find the target using an efficient O(log n) approach 🛠️ Solution Breakdown 1️⃣ Initialized left and right pointers 2️⃣ Found the middle element using mid = left + (right - left) / 2 3️⃣ Compared the target with the middle element and updated pointers accordingly 🔑 Key Points • Binary Search works only on sorted arrays • Divide and conquer reduces search time significantly • Optimized searching is much faster than linear search 📊 Complexity Analysis Time Complexity: O(log n) Space Complexity: O(1) ✨ Key Takeaway Today I learned how powerful optimization can be. A small change in approach can drastically improve performance. 💯 #LeetCode #30DaysOfLeetCode #CodingPractice #DSA #ProblemSolving #BinarySearch #CProgramming
To view or add a comment, sign in
-
-
💡 LeetCode Daily — Problem Solved: Rotate Function (Medium). Today’s problem looked mathematical at first glance… but the real trick was pattern recognition + optimization. At face value, rotating the array and recalculating the function every time feels natural. But that leads straight into an O(n²) trap — not scalable. So I stepped back and asked: 👉 What actually changes when we rotate the array? 🔍 Key Insight (Simple Visualization). Instead of recomputing everything: Each rotation shifts elements, but the total sum stays constant. Only the weight contribution of elements changes. That leads to a powerful relation: Next rotation value can be derived from the previous one using a formula — no need to rebuild from scratch. ⚙️ My Approach Compute initial value F(0) using a loop. Use accumulate() (STL) to get total sum efficiently. Derive next values using a rolling formula. Track maximum along the way. This reduces complexity to O(n) — clean and efficient. 📊 Consistency Snapshot Total active days on LeetCode: 75 Max streak: 68 days 🧠 What I Took Away This problem wasn’t about rotations. It was about: Breaking brute-force thinking. Finding relationships between consecutive states. Trusting math over simulation. Sometimes, optimization isn’t about writing better code — it’s about seeing the problem differently. Still learning. Still refining how I think. #LeetCode #DSA #ProblemSolving #CPP #STL #DailyCoding #Consistency
To view or add a comment, sign in
-
-
🚀 #LeetCode Day Problem Solving 🚀 Day-63 📌 Problem: Find the smallest common element present in both sorted arrays 🔥 If no common element exists → return -1 🧠 Example: Input: nums1 = [1,2,3] nums2 = [2,4] ✅ Output: 2 💡 Why? Common elements are: [[2]] Smallest common element = 2 ✅ 💡 Key Insight (Very Important 🔥): 👉 Both arrays are already SORTED ⚡ So instead of brute force checking every pair ❌ We can use: #️⃣ Two Pointer Technique 🚀 ⚡ Core Idea: Maintain pointers: ✔ i for nums1 ✔ j for nums2 Case 1️⃣: If: [nums1[i] = nums2[j]] ✅ Found smallest common element immediately because arrays are sorted 🔥 Case 2️⃣: If: [nums1[i] < nums2[j]] 👉 Move i forward because smaller value cannot match future larger values Case 3️⃣: If: [nums1[i] > nums2[j]] 👉 Move j forward 🧠 Why This Works? Since arrays are sorted: ✔ Once a smaller value is skipped, it can never become useful later So we eliminate unnecessary comparisons efficiently ⚡ ⚡ Algorithm: 1️⃣ Initialize: ✔ i = 0 ✔ j = 0 2️⃣ Traverse both arrays: ✔ If equal → return value ✔ Else move pointer with smaller value 3️⃣ If traversal ends → return -1 🔥 Example Walkthrough: nums1 = [1,2,3,6] nums2 = [2,3,4,5] Step 1: Compare: [1 \text{ and } 2] 1 < 2 👉 Move first pointer Step 2: Compare: [2 \text{ and } 2] ✅ Match found Answer = 2 📊 Complexity Analysis: ⏱ Time Complexity: [O(n+m)] where n and m are array sizes 📦 Space Complexity: O(1) 🧠 What I Learned: ✔ Two Pointer Technique ✔ Efficient traversal of sorted arrays ✔ Avoiding brute force comparisons 🔥 Day 63 Completed! Sorted arrays often unlock elegant linear-time solutions 💪 #Leetcode #DSA #ProblemSolving #BitManipulation #CodingJourney #InterviewPreparation #Consistency
To view or add a comment, sign in
-
-
Day 113 on LeetCode — Combination Sum 🔁🎯✅ Another strong recursion + backtracking problem that really tested decision tree thinking 💯 🔹 Problem: Find all unique combinations whose sum equals the target. Key twist: • Same element can be chosen multiple times • Need all valid combinations 🔹 Approach Used: At every index, I explored 3 possibilities: • Take current element once • Take current element multiple times • Exclude current element To avoid duplicate combinations: • Used a set<vector<int>> 🔹 Recursive Flow: • If target == 0 → valid combination found • If: • index goes out of bounds OR • target becomes negative → stop recursion 💡 Core idea: Generate all possible valid paths using recursion + backtracking. 🔹 Concepts Used: • Recursion • Backtracking • Include / Exclude pattern • Decision tree exploration • Duplicate handling using set This problem honestly showed me how quickly recursion trees can explode 😅 But compared to earlier days: • Recursive calls feel more understandable now • Backtracking flow feels less confusing • I’m starting to visualize choices better ⚡ Complexity: • Time Complexity: Exponential • Space Complexity: Recursive stack + stored combinations 💡 Biggest takeaway: Optimization can come later. Right now the focus is: • Building logic independently • Understanding recursive flow • Learning how decisions branch recursively 🔥 Slowly turning recursion from fear into familiarity. #LeetCode #DSA #Algorithms #DataStructures #Recursion #Backtracking #CombinationSum #ProblemSolving #Coding #Programming #Cpp #SoftwareEngineering #ComputerScience #CodingPractice #DeveloperLife #TechJourney #CodingDaily #Consistency #100DaysOfCode #BuildInPublic #AlgorithmPractice #CodingSkills #Developers #TechCommunity
To view or add a comment, sign in
-
-
🚀 Day 52 of 100 Days LeetCode Challenge Problem: Minimize Hamming Distance After Swap Operations Day 52 is a powerful Graph + Union Find (DSU) + Frequency Matching problem 🔥 💡 Key Insight: Allowed swaps create connected components. 👉 Any indices within the same connected component can be rearranged freely. So instead of individual swaps: ⚡ Think in terms of groups of interchangeable indices 🔍 Core Approach: 1️⃣ Build Connected Components Use Disjoint Set Union (DSU / Union Find) For every allowed swap [a, b]: union(a, b) 👉 All connected indices belong to the same group 2️⃣ Group Source Values For each component: Count frequencies of values in source Example: component → {1:2, 3:1} 3️⃣ Match with Target Traverse target values in same component If value exists in frequency map: Decrease count ✅ Else: Hamming distance increases ❌ 💡 Why This Works: Inside a connected component: 👉 We can permute values however we want So the goal becomes: Maximize matches within each component 🔥 Time Complexity: Efficient with: DSU + HashMap 🔥 What I Learned Today: Swap operations often imply graph connectivity DSU is extremely powerful for grouping problems Frequency matching helps minimize mismatches optimally 📈 Challenge Progress: Day 52/100 ✅ Strong consistency continues! LeetCode, Union Find, DSU, Graph Theory, HashMap, Arrays, Optimization, DSA Practice, Problem Solving #100DaysOfCode #LeetCode #DSA #CodingChallenge #UnionFind #GraphTheory #Hashing #ProblemSolving #TechJourney #ProgrammerLife #SoftwareDeveloper #CodingLife #LearnToCode #Developers #Consistency #GrowthMindset #InterviewPrep
To view or add a comment, sign in
-
-
📱 LeetCode 17 – Letter Combinations of a Phone Number | Mastering Backtracking Solved a classic recursion problem today that perfectly demonstrates the power of backtracking and combination building. The challenge: given a string of digits (2–9), generate all possible letter combinations based on the traditional phone keypad mapping. 💡 Key Insight: Each digit maps to multiple characters, and the goal is to explore all possible combinations by picking one character from each digit. This naturally leads to a backtracking approach, where: We build combinations step by step Explore all possibilities recursively Backtrack to try different paths ⚙️ Approach: Use a mapping of digits → letters Traverse the input using recursion Append characters and move forward Store the result when a valid combination is formed 🚀 Complexity: Time: O(4ⁿ) Space: O(n) (recursion stack) 📌 What I learned: How to think in terms of recursion trees Efficiently generating combinations Writing clean and structured backtracking code Problems like this build a strong foundation for tackling advanced topics like DFS, recursion, and combinatorial algorithms. #LeetCode #DSA #Backtracking #Recursion #ProblemSolving #CodingJourney #SoftwareEngineering
To view or add a comment, sign in
-