🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/gExeYEjW 💡 My thought process: The distance formula simplifies to 2 × (k − i) when indices are sorted in order (i < j < k). This means the problem is about finding three occurrences of the same value while minimizing the gap between the first and third indices. Instead of saving all indices for each value, the approach only keeps track of the last two occurrences of every number using a hash map. For each element, the map holds a pair {prev2, prev1}, where prev1 is the most recent index and prev2 is the one before that. While going through the array for the current index i: If the element has been seen before, get its last two indices. If a valid prev2 exists, calculate the distance using 2 × (i − prev2). This forms a triplet using prev2, prev1, and the current index. Update the answer with the minimum value obtained. Shift the indices forward by setting prev2 to prev1 and prev1 to i. If the element appears for the first time, set its entry to {-1, i}, indicating that only one occurrence has been seen so far. This method ensures that only consecutive triplets of occurrences are considered. This is enough because any non-consecutive triplet would result in a larger distance. The algorithm runs in O(n) time and O(n) space, while avoiding the extra cost of storing full index lists. 👉 My Solution: https://lnkd.in/gBFCq7QW If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari
LeetCode Daily Challenge: Minimize Gap Between Triplets
More Relevant Posts
-
🚀 Day 29/50 – LeetCode Challenge 🧩 Problem: Swap Nodes in Pairs Today’s problem focused on swapping nodes of a linked list in pairs, which helped strengthen concepts of pointer manipulation and linked list traversal. 📌 Problem Summary: Given a linked list, swap every two adjacent nodes and return the modified list. You must not modify node values, only change the links. 🔍 Approach Used (My Implementation) ✔ Used a dummy node to handle edge cases easily ✔ Maintained two pointers: prev → points to node before the pair cur → points to the first node of the pair ✔ For each pair: Stored next pair using npn = cur.next.next Identified second node → second = cur.next ✔ Swapped nodes by updating pointers: second.next = cur cur.next = npn prev.next = second ✔ Moved pointers forward: prev = cur cur = npn ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) 💡 Key Learning ✔ Importance of dummy node in linked list problems ✔ Mastering pointer manipulation ✔ Handling edge cases in linked lists ✔ Writing clean and efficient in-place solutions This problem really improved my confidence in working with linked list pointer operations. Consistency builds strong fundamentals 🚀 🔗 Problem Link: https://lnkd.in/gDjVrGur #50DaysOfLeetCode #LeetCode #DSA #LinkedList #ProblemSolving #CodingJourney #FutureAIEngineer #Consistency
To view or add a comment, sign in
-
-
Spent some time solving 3 really interesting LeetCode contest problems today, and each one reinforced a different core DSA pattern. What I enjoyed most was how these seemingly small problems were actually testing pattern recognition more than implementation. 1) Mirror Frequency Distance This problem was all about symmetry and frequency mapping. Approach That I Used: Count the frequency of each character in the string. Map each character to its mirror counterpart: a ↔ z, b ↔ y 0 ↔ 9, 1 ↔ 8 Iterate through only half the range to avoid double counting. Sum the absolute frequency differences for every mirror pair. 2) Integers With Multiple Sum of Two Cubes This one immediately reminded me of the Ramanujan number (1729) concept. Approach That I Used: Generate all valid cube pairs (a, b) where: a³ + b³ ≤ n Store the frequency of each generated sum in a hashmap. Any number appearing 2+ times has multiple distinct cube representations. Return all such integers in sorted order. 3) Minimum Increments to Maximize Special Indices The most interesting one of the three because it involved DP state compression. & it took me an hour to do this question Approach: Treat every valid index as a candidate peak. Compute the cost required to make it greater than both neighbors. Maintain two rolling states: choose current index as peak skip current index Optimize first for: maximum number of peaks minimum cost among those choices Biggest learning from today: Contest questions often look implementation-heavy, but the real skill lies in identifying the hidden reusable pattern: frequency symmetry pair generation DP The more patterns we recognize, the faster we grow as problem solvers. Consistency is the real game changer. #LeetCode #DSA #DynamicProgramming #CompetitiveProgramming #ProblemSolving #C++ #CodingJourney #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/gZ52pSZR 💡 My thought process: The solution operates in two separate passes: 1. Left-to-Right Pass: For each element at index "i", calculate the distance to all previous occurrences of that value. If a value has appeared "k" times before, the sum of distances is found using this formula: (count * current_index) - (sum of previous_indices). By storing the count and the running sum of indices in a hash map, we can compute this in constant time. 2. Right-to-Left Pass: The same logic is applied in reverse to calculate the distance from the current index to all future occurrences. In this case, the formula changes to: (sum of future_indices) - (count * current_index). By adding the results from both directions, the code captures the total absolute difference for every identical pair without the performance cost of a nested loop. 👉 My Solution: https://lnkd.in/gfEc7Kis If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/g9SGp2Qa 💡 My thought process: First, create a mapping from each value to a sorted list of its indices using a map<int, vector<int>>. This allows for easy lookup of all positions where a value occurs. For each query index idx, it retrieves the corresponding value num. If that value appears only once, the result is -1 because no valid pair exists. In case of multiple occurrences, we use binary search on the index list of num: * upper_bound finds the next occurrence that is strictly greater than idx. * lower_bound locates the current position and checks the previous occurrence. It calculates distances in both directions: * Forward distance: either direct (next - idx) or circular wrap (n - (idx - first)). * Backward distance: either direct (idx - prev) or circular wrap (n - (last - idx)). The minimum of these distances is stored as the answer. 👉 My Solution: https://lnkd.in/gjmKVa3y If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari
To view or add a comment, sign in
-
-
Day 2: Leetcode – 704. Binary Search Today’s problem looked straightforward, but it exposed how small mistakes in control flow can completely break the logic. The Key Insight: Binary search isn’t just about comparing values — it’s about maintaining the correct search space and letting the loop run until it’s fully exhausted. Returning too early can silently ruin the entire algorithm. My Mistake: I placed return -1 inside the loop, which caused the function to exit after just one iteration if the target wasn’t found immediately. The code compiled fine but the logic was wrong — a good reminder that passing compilation doesn’t mean correctness. My Approach: Initialize low = 0 and high = n-1 Calculate mid each iteration Compare nums[mid] with target Adjust search space accordingly Only return -1 after the loop ends Takeaway: Binary search is simple in theory but demands discipline in implementation. One misplaced return or bracket can turn a correct idea into a faulty solution. Day 2 Completed #LeetCode #DSA #BinarySearch #Learning #CodingJourney
To view or add a comment, sign in
-
-
🚀 Another Clean 0 ms Solution – Convert BST to Greater Sum Tree | 215/215 Test Cases Passed Just solved the "Convert BST to Greater Sum Tree" problem with a perfect score! Problem: Given a Binary Search Tree (BST), convert it into a Greater Sum Tree where each node’s value is replaced by the sum of all values greater than or equal to it in the original BST. In other words, every node should contain the sum of itself and all nodes to its "right" in sorted order. My Approach: The key insight here is to use Reverse Inorder Traversal (Right → Root → Left). This allows us to visit nodes in decreasing order. I maintained a global sum variable that keeps accumulating values as we traverse: Recurse on the right subtree first (larger values) Add the current node’s value to the running sum Update the node’s value with this cumulative sum Then recurse on the left subtree This elegant in-place transformation ensures we modify the tree correctly without using any extra space for storing node values. Submission Highlights: ✅ 215 / 215 test cases passed ✅ Runtime: 0 ms → Beats 100.00% of all submissions ✅ Memory: 34.92 MB → Beats 77.73% It always feels great when your code not only gets accepted but also runs at the fastest possible time. This problem is a beautiful combination of BST properties and clever traversal technique. Solving it efficiently reminded me how small optimizations in thinking can lead to big performance gains. Problems like these keep the coding journey exciting and push us to think deeper. Would love to hear from the community — what's your favorite BST problem or traversal trick? Drop your thoughts in the comments 👇 #DSA #LeetCode #BinarySearchTree #GreaterSumTree #DataStructures #Algorithms #CodingJourney #ProblemSolving #CompetitiveProgramming #Tech #KeepLearning
To view or add a comment, sign in
-
-
🚀 Day 26 of 100 Days LeetCode Challenge Problem: Equal Sum Grid Partition II Today’s problem is an advanced version of Day 25 with an extra twist 🔥 👉 Now we can remove (discount) at most one cell to balance the partition. 💡 Key Insight: We need: A horizontal OR vertical cut Two non-empty parts Equal sum OR can be made equal by removing one cell 🔍 Core Approach: 1️⃣ Total Sum Check Let total = sum of all elements 2️⃣ Try All Possible Cuts 👉 For each horizontal & vertical cut: Compute: Left/Top sum Right/Bottom sum 3️⃣ Check Two Cases: ✅ Case 1: Equal directly If both sums equal → return true ✅ Case 2: Difference can be fixed Let diff = |sum1 - sum2| Check if there exists a cell with value = diff In the larger partition 👉 Removing that one cell balances both sides ⚠️ Important Constraint: After removing a cell → the section must still be connected So avoid removing a “critical” cell that breaks connectivity 🔥 What I Learned Today: Small constraint changes → big increase in complexity Problem-solving requires checking multiple scenarios Combining prefix sums + validation logic is powerful 📈 Challenge Progress: Day 26/100 ✅ Beyond basics now! LeetCode, Prefix Sum, Matrix, Partition Problem, Graph Connectivity, Optimization, DSA Practice, Coding Challenge, Problem Solving #100DaysOfCode #LeetCode #DSA #CodingChallenge #PrefixSum #Matrix #ProblemSolving #TechJourney #ProgrammerLife #SoftwareDeveloper #CodingLife #LearnToCode #Developers #Consistency #GrowthMindset #InterviewPrep
To view or add a comment, sign in
-
-
Day -55 Minimum Distance of Good Triplet Today I solved an interesting problem on arrays We need to find 3 indices (i, j, k) such that: nums[i] = nums[j] = nums[k] Distance = |i - j| + |j - k| + |k - i| is minimum Key Insight: If we sort indices (i < j < k), the formula simplifies to: Distance = 2 × (k - i) Find 3 same elements with minimum index gap Approach: Store indices of each number For each group, check consecutive triplets Pick the minimum distance Why it works? Closest 3 indices always give minimum distance. Time Complexity: O(n) Simple idea, powerful optimization! #LeetCode #DSA #Coding #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 10/100 — LeetCode Challenge Solved 3Sum The brute force approach is simple: Try all triplets → O(n³) But that’s not scalable. 💡 Optimized Approach: 1) First, sort the array 2) Fix one element 3) Use two pointers to find the remaining pair 👉 This reduces the complexity significantly. Also handled duplicates carefully to avoid repeated triplets. 🧠 Time Complexity: O(n²) 💾 Space Complexity: O(1) (ignoring output) 💡 What I learned: Sometimes optimization is not about complex logic, but about: 1) Sorting 2) Using patterns like two pointers 3) Eliminating unnecessary work This problem felt like a step up from previous ones. Staying consistent. #LeetCode #DSA #100DaysOfCode #Cpp #TwoPointers #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 91 of LeetCode Problem Solving Journey — 100 Days LeetCode Challenge Today, I solved LeetCode #209 — Minimum Size Subarray Sum using C++, under the guidance of Trainer NEKAL SINGH SALARIA Singh at REGex Software Services. 🔍 Problem Summary: Given an array of positive integers nums and a target value target, return the minimal length of a contiguous subarray whose sum is greater than or equal to target. If no such subarray exists, return 0. 🧠 Approach Used (Sliding Window): I used the sliding window technique to efficiently find the minimum length: Initialize two pointers → left = 0 and sum = 0 Expand the window by moving right and adding elements to sum While sum >= target: Update minimum length Shrink the window from the left by subtracting nums[left] Move left forward This approach dynamically adjusts the window to find the smallest valid subarray. 📚 Key Learnings of the Day ✔ Sliding window is powerful for subarray problems ✔ Expanding and shrinking window helps optimize search ✔ Works efficiently when all numbers are positive ✔ Avoids nested loops and reduces complexity ⏱ Complexity • Time Complexity: O(n) • Space Complexity: O(1) 💡 Optimization Insight: The brute-force approach takes O(n²), but sliding window reduces it to O(n) by maintaining a dynamic range. Getting closer to the finish line — see you on Day 92 🚀 #Day91 #100DaysLeetCodeChallenge #LeetCode #RegexSoftwareServices #NekalSingh #ProblemSolving #DSA #CPlusPlus #CodingChallenge #ProgrammingJourney #SlidingWindow #KeepGrowing
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