-- Solved: Sum of Distances (LeetCode 2615) -- Today I worked on a problem that looks simple at first… but quickly punishes brute force thinking. -- Problem Insight For each index, calculate the sum of distances to all other indices with the same value. -- Mistake I Made - I initially tried comparing every element with every other element having the same value. - It worked for small cases but completely breaks for large inputs. -- Key Optimization The breakthrough came when I realized: - Instead of comparing every pair, group indices by value - Use prefix sums to compute distances efficiently - This reduces the complexity to O(n) Always question: “Can I reuse previous computations?” - Every problem like this improves how I think about scaling solutions. - Less brute force, more structure. #DSA #LeetCode #ProblemSolving #CodingJourney #SoftwareEngineering #Optimization #algorithm
Sum of Distances LeetCode 2615 Optimization
More Relevant Posts
-
🚀 Day 11 of My LeetCode Journey Today’s problem: Container With Most Water This problem looked tricky at first, but the solution turned out to be a clean application of the Two Pointer technique. 💡 Key Idea: Start with two pointers at both ends Calculate area using width × minimum height Move the pointer with smaller height to maximize area 🔍 Instead of brute force O(n²), optimized it to O(n) 🚀 ⚡ Result: Accepted ⏱️ Runtime: 60 ms 🧠 What I Learned: Two Pointers can drastically reduce complexity Always think about optimizing from both ends Logic > brute force #LeetCode #DSA #CodingJourney #100DaysOfCode #TwoPointers #Algorithms #ProblemSolving
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🧩 Problem: Minimum Absolute Distance Between Mirror Pairs You are given an integer array nums. 🎯 Goal Find the minimum distance between indices i and j such that: One number is the mirror (reverse) of the other i.e., nums[i] == reverse(nums[j]) If no such pair exists, return -1. 🧠 Key Intuition A “mirror pair” means: Reverse the digits of a number Remove leading zeros after reversing Compare with another number Example: 120 → 021 → 21 Efficient idea: While iterating, store the index of reversed numbers For each number: Compute its mirror (reverse) Check if we've already seen its pair This avoids checking all pairs O(n²) 🛠 Approach 1️⃣ Traverse the array 2️⃣ For each number: Convert to string Reverse it Remove leading zeros Convert back to integer → rev 3️⃣ Check in map: If current number exists in map → update answer 4️⃣ Store: map[rev] = current index 5️⃣ Keep track of minimum distance 📈 Complexity Analysis Time Complexity: O(n × d) (d = number of digits) Space Complexity: O(n) 🔗 Problem https://lnkd.in/d_KcNEqb 💻 Solution https://lnkd.in/dvcVRvTu #LeetCode #Cpp #DSA #Algorithms #HashMap #Strings #ProblemSolving #CodingChallenge #LeetCodeDailyChallenge #CompetitiveProgramming #CodingJourney
To view or add a comment, sign in
-
Day 3: LeetCode – 74. Search a 2D Matrix Today I solved a problem that looks like a 2D matrix question but is actually a binary search problem in disguise. Key Insight: Although the input is a matrix, the constraints ensure it behaves like a single sorted array. That allows us to apply binary search across the entire matrix in O(log(m × n)) time. My Approach: • Treated the matrix as a single sorted list • Applied binary search on the range [0 … m×n − 1] • Converted the mid index back to matrix coordinates using: – row = mid / n – col = mid % n • Compared the value at that position with the target and adjusted the search range Takeaway: A shift in perspective can simplify seemingly complex problems. Recognizing hidden patterns is as important as knowing algorithms. Day 3 completed. #DSA #LeetCode #BinarySearch #ProblemSolving
To view or add a comment, sign in
-
-
LeetCode Daily | Day 84 🔥 LeetCode POTD – 1559. Detect Cycles in 2D Grid (Medium) ✨ 📌 Problem Insight Given a 2D grid of characters: ✔ Move in 4 directions (up, down, left, right) ✔ Only move to cells with same value ✔ Detect a cycle of length ≥ 4 ✔ Cannot go back to immediate previous cell 🔍 Initial Thinking – Brute DFS ⚙️ 💡 Idea: ✔ Start DFS from every cell ✔ Track visited path ⚠️ Concern: ✔ Might revisit parent → false cycle ✔ Need a way to avoid backtracking confusion 💡 Key Observation 🔥 ✔ This is graph cycle detection in a grid ✔ While moving, track parent cell ✔ If we reach a visited cell ≠ parent → cycle found ✅ 🚀 Optimized Approach ✔ Use DFS with: → visited matrix → parent tracking (px, py) ✔ For each neighbor: → If not visited → continue DFS → If visited and not parent → cycle exists 🔧 Core Idea ✔ Grid = graph ✔ Same values = connected component ✔ Cycle detection = revisit node (not parent) ⏱ Complexity ✔ Time: O(m × n) ✔ Space: O(m × n) 🧠 Key Learning ✔ Always track parent in DFS cycle problems ✔ Grid problems often map to graph concepts ✔ Avoid false cycles by ignoring immediate back edge 🚀 Takeaway When dealing with grids, think like a graph — a small tweak like tracking parent turns a tricky problem into a standard cycle detection pattern ⚡ #LeetCode #DSA #Algorithms #GraphTheory #CPlusPlus #CodingJourney
To view or add a comment, sign in
-
-
-- Solved LeetCode 100: Same Tree -- Today I worked on the classic binary tree problem “Same Tree”, and it turned out to be a great exercise in strengthening recursion fundamentals -- Problem Summary: -- Given two binary trees, determine whether they are identical in both structure and node values. -- Approach (Recursive DFS): At each node, I focused on 3 key checks: • If both nodes are NULL → trees match at this point • If one is NULL → structure mismatch • If values differ → not the same If all checks pass, recursively compare left and right subtrees. -- Complexity: Time: O(n) – visiting every node once Space: O(h) – recursion stack (depends on tree height) Consistency > Complexity. #LeetCode #DSA #Recursion #BinaryTree #CodingJourney #SoftwareEngineering #algorithm
To view or add a comment, sign in
-
-
🚀 Day 34/150 of hashtag#150DaysOfDSA 📌 Task: Search Insert Position Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity. #150DaysOfCode #DSA #CPP #Algorithms #CodingJourney #LeetCode #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 87 of #100DaysOfCode 🧠 Problem Solved: 1855. Maximum Distance Between a Pair of Values Today’s problem tested my understanding of two-pointer technique on sorted (non-increasing) arrays. 💡 Key Insight: Instead of checking all pairs (which would be slow), we can efficiently move pointers to maximize the distance while maintaining the condition: 👉 nums1[i] ≤ nums2[j] ⚡ Approach Used: - Start with two pointers at the beginning - Expand the right pointer to maximize distance - Adjust the left pointer only when the condition breaks - Track the maximum distance throughout 📈 Result: - Optimized from brute force O(n²) → O(n) - Efficient and clean logic 🔥 What I Learned: - How sorted properties help reduce complexity - Smart pointer movement is key to greedy problems - Avoid brute force when patterns exist Consistency > Motivation 💯 #Day87 #LeetCode #DataStructures #Algorithms #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 𝐃𝐚𝐲 𝟒𝟖/𝟏𝟎𝟎 – #𝟏𝟎𝟎𝐃𝐚𝐲𝐬𝐎𝐟𝐋𝐞𝐞𝐭𝐂𝐨𝐝𝐞 Almost halfway to the century mark! Today’s challenge was all about array reorganization and interleaving, and I’m keeping the streak alive with another 𝟎𝐦𝐬 (𝐁𝐞𝐚𝐭𝐬 𝟏𝟎𝟎%) solution! ✅ 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝: Shuffle the Array 🧠 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐭𝐚𝐭𝐞𝐦𝐞𝐧𝐭: Given an array nums consisting of $2n$ elements in the form $[x_1, x_2, ..., x_n, y_1, y_2, ..., y_n]$, return the array in the form $[x_1, y_1, x_2, y_2, ..., x_n, y_n]$. 💡 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 𝐔𝐬𝐞𝐝: • 𝐒𝐢𝐧𝐠𝐥𝐞 𝐏𝐚𝐬𝐬 𝐈𝐭𝐞𝐫𝐚𝐭𝐢𝐨𝐧: Since the array is split into two halves of size $n$, I iterated from $0$ to $n-1$. • 𝐏𝐚𝐢𝐫𝐞𝐝 𝐈𝐧𝐬𝐞𝐫𝐭𝐢𝐨𝐧: In each step of the loop, I simultaneously picked the element from the first half ($i$) and its corresponding element from the second half ($i+n$). • 𝐕𝐞𝐜𝐭𝐨𝐫 𝐏𝐮𝐬𝐡: I used ans.push_back(nums[i]) followed by ans.push_back(nums[i+n]) to interleave the elements in the required order. 📊 𝐓𝐢𝐦𝐞 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲: $O(n)$ — We process the $2n$ elements in a single linear pass. 🗂 𝐒𝐩𝐚𝐜𝐞 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲: $O(n)$ — To store the $2n$ shuffled elements in a new result vector. ✔️ 𝐒𝐭𝐚𝐭𝐮𝐬: Accepted (𝟎𝐦𝐬 - 𝐁𝐞𝐚𝐭𝐬 𝟏𝟎𝟎%) 📍 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠: This problem highlights the importance of index mapping. By identifying the relationship between the two halves of the array ($i$ and $i+n$), we can perform the transformation efficiently without complex swaps. 𝟒𝟖/𝟏𝟎𝟎 𝐜𝐨𝐦𝐩𝐥𝐞𝐭𝐞. Small steps every day lead to big results! 🚀 #LeetCode #DSA #CodingJourney #ProblemSolving #Consistency #100DaysOfCode #Cpp #Algorithm #SoftwareEngineering #NavneetRaj
To view or add a comment, sign in
-
-
LeetCode Weekly Contest 496 Recap - My Approach & Learnings Sharing a quick breakdown of today’s contest problems and what I learned 🔹 Q1. Mirror Frequency Distance * Count frequency of characters using a hash table * For each character, find its mirror counterpart * Use a visited set to avoid double counting * Accumulate absolute difference of frequencies --- 🔹 Q2. Integers With Multiple Sum of Two Cubes * Key insight: although n goes up to (10^9), cube roots are <= 1000 * Generate all pairs (i, j) where i < j * Store i^3 + j^3 frequencies in a hashmap * Keep values appearing at least twice in a vector * Sort results and use binary search (upper_bound) for queries of n. * Optimized by using static precomputation, so calculation happens only once, subsequent test cases run in O(log n) --- 🔹 Q3. Minimum Increase to Maximize Special Indices * DP-based thinking (index as state) * For each index: * Compute operations needed to make it a peak * Two choices: * Take -> add cost, move to i+2 (skip adjacent) * Skip -> move to i+1 * return the value having * the recursive function return a pair of {maximum peaks , minimum operations} , as the goal is maximize number of peaks with minimize operations --- 🔹 Q4. Minimum Operations to Achieve At Least K Peaks * Tried recursive + memoized DP * State included: * index, prev (peak or not), k, firstTaken (to handle circular constraint) * Faced Memory Limit Exceeded due to large state space: * (O(n * k * 2 * 2)) -> too big (~10^8 states) Need further optimization. edit- upsloved just had to remove the firstaken and prev(peak, not peak) from the dp states. and it ran successfully. approach still remains the same with tc= o(n*k) which is a borderline accepted. Curious how others approached Q4, especially optimized DP or greedy solutions. #LeetCode #CompetitiveProgramming #DSA #Coding #Algorithms
To view or add a comment, sign in
-
-
🚀 Day 89/100 – Permutations II 🧠 Problem: Given an array that may contain duplicates, return all unique permutations ✔️ No duplicate permutations ✔️ Order doesn’t matter 💡 Core Idea 🔥 Classic Backtracking + Duplicate Handling 👉 Sort the array first 👉 Use a used[] array 👉 Skip duplicates using condition: if(i > 0 && nums[i] == nums[i-1] && !used[i-1]) continue; ⚡ This ensures only unique permutations are generated 📚 Key Learnings Backtracking with pruning Handling duplicates efficiently Importance of sorting before recursion ⏱️ Complexity Time Complexity: O(n! ) Space Complexity: O(n) #100DaysOfCode #Day89 #LeetCode #DSA #Backtracking #Algorithms #ProblemSolving #CodingJourney #Consistency
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