Minimum Distance Between Three Equal Elements Thought process 🤔 Brute force: Run 3 loops, pick every (i, j, k), check if elements are equal, and calculate the absolute difference of indices. Keep updating the minimum. Simple approach, but yeah… O(n³) is too slow when input size grows 😅 How to optimize:: We only care about indices where values are the same, so instead of checking every triplet, let’s store them.. Use a map For each elem, store all its indices Then check only valid triplets from those indices, compute distances for valid groups and track the mini. O(n) time 💡 #leetcode #potd #programming #dsa #developer #softwareengineer #datastructures #algorithms
Optimize Minimum Distance Between Three Equal Elements
More Relevant Posts
-
Recover the Tree ?? by providing water! Approach (Recover BST) Do inorder traversal (BST should be sorted) Track previous node If order breaks (prev > current), it’s a violation First violation: first = prev middle = current Second violation (if exists): last = current Time Complexity: O(n) → you traverse all nodes once using inorder Space Complexity: O(h) → recursion stack (h = height of tree) Worst case (skewed tree): O(n) Best case (balanced tree): O(log n) #LeetCode #DSA #DataStructures #Algorithms #Coding #Programming #binarysearchtree
To view or add a comment, sign in
-
-
🚀 Day 9 of #100DaysOfCode Today’s LeetCode problem: Rotate Function (Medium) At first, the problem looks like a simulation — rotate the array every time and calculate the value again. But doing that would be O(n²)… not efficient. 💡 What is the question really asking? We are given an array and a function: F(k) = sum of (index * value) after rotating the array k times. We need to find the maximum value of F(k). 🧠 Key Insight (Game Changer): Instead of recalculating everything after each rotation, we observe a pattern: When we move from F(k) → F(k+1), 👉 Every element contributes +sum of array 👉 Except one element (the last rotated one), which contributes −n * value So the transition becomes: 👉 F(k+1) = F(k) + sum - n * last_element ⚡ Why this is powerful? Each element is effectively added once in the transitions, except the element that “wraps around” — it gets subtracted by n times. This reduces complexity from O(n²) → O(n) 🔥 #LeetCode #DSA #CodingJourney #ProblemSolving #100DaysOfCode #TUF #GFG #programming
To view or add a comment, sign in
-
-
Solved today’s LeetCode Daily and it made me pause 👇 “XOR After Range Multiplication Queries I” At first glance, it looks like: Segment Tree? Lazy Propagation? Some heavy optimization? 🤯 But the reality? Sometimes… brute force wins. --- Given constraints were small. And that completely changes the game. So instead of overengineering: ✔️ Just simulate each query ✔️ Jump with k steps ✔️ Apply multiplication (mod 1e9+7) ✔️ Take final XOR And that’s it. --- The interesting part 👇 As developers, we are trained to think: “Optimize first” But problems like this remind us: 👉 Understand constraints before choosing approach Because honestly, A simple O(n * q) solution can beat an overcomplicated design any day. --- What I learned today: • Not every problem needs advanced DS • Constraints are part of the problem statement for a reason • Simplicity is underrated --- Consistency check ✅ One more problem done. --- Curious 👇 Comment your approach. #LeetCode #DSA #Programming #Coding #Developers #ProblemSolving #Rust
To view or add a comment, sign in
-
-
Subtree of another tree Approach: If subRoot is null - return true If root is null - return false If values match - check isIdentical(root, subRoot) If identical - return true Else - check left and right: isSubtree(root.left, subRoot) isSubtree(root.right, subRoot) Return true if found anywhere, otherwise false TC: O(N*M) -- n =no. of nodes in root, m = no. nodes in subRoot (worst case) SC: O(h) -- height of tree ( O(N) -- skewed tree || O(logN) -- balanced tree) #coding #programming #DSA #Consistency #Leetcode #CodingJourney
To view or add a comment, sign in
-
-
🧠 One small mistake can break your entire logic. Today I learned this while solving a grid problem 👇 💻 LeetCode #1559 — Detect Cycles in 2D Grid At first glance, it looks like a simple DFS problem… But there’s a catch ⚠️ 🔍 Common mistake developers make: 👉 “If I visit an already visited cell → cycle exists” Sounds correct… but it’s NOT ❌ 🚀 My Approach (DFS + Parent Tracking): Traverse the grid using DFS Move in 4 directions (up, down, left, right) Only move to cells with the same character 👉 While moving, I track the parent cell 💡 Key Logic: If I reach a cell that is: Already visited AND not the parent 👉 Then a cycle exists ✅ ⚙️ Why parent check is important? Because going back to the previous cell is normal 👉 It should NOT be treated as a cycle 🧠 Takeaway: In DSA, logic rarely fails… 👉 Edge cases do 🔥 The difference between wrong and correct solution is often just one condition Have you ever fixed your solution by changing just 1 line? 😄 #LeetCode #DSA #Algorithms #Programming #Debugging #ProblemSolving #Developers #CodingJourney
To view or add a comment, sign in
-
-
LCA - Lowest Common Ancestor of binary tree Approach: If current node is null, return null If current node is p or q, return current node Recursively search left and right If both sides return non-null → current node is LCA Otherwise → return the non-null side TC = O(n) SC = O(h) - depends on tree height (recursion stack) O(logn) - balanced tree O(n) - skewed tree #dsa #leetcode #consistency #coding #programming
To view or add a comment, sign in
-
-
Binary tree right side view Approach: - Keep a level variable - If level == result.size(), add current node (first node of that level) - Traverse right first, then left Time: O(n) Space: O(h) (worst: O(n), best: O(log n)) #Algorithms #DSA #LeetCode #coding #Programming
To view or add a comment, sign in
-
-
49 of #100DaysOfCode Solved Next Greater Element II (LeetCode 503) using a Monotonic Stack + Circular Traversal approach 🔁 💡 Approach: Since the array is circular, we iterate 2 × n times to simulate wrapping around. Use a stack to store indices whose next greater element hasn’t been found yet. Traverse from left to right: If the current element is greater than the element at the index on top of the stack → update result. Keep popping until the stack condition breaks. Only push indices during the first pass (i < n) to avoid duplicates. ⚡ Key Insight: Using a monotonic decreasing stack helps us efficiently track elements waiting for their next greater value — reducing unnecessary comparisons. 📊 Complexity: Time Complexity: O(n) Space Complexity: O(n) #LeetCode #DSA #Coding #Cpp #Programming #Stack #InterviewPrep
To view or add a comment, sign in
-
-
64 of #100DaysOfCode 🚀 Solved LeetCode 46 – Permutations using the Recursion and in-place backtracking (swap) approach. 🔹 Instead of using extra space like visited[], I used swapping to generate permutations efficiently. 🔹 Fixed each index and tried all possible elements using recursion. 🔹 Backtracking (swap back) helped explore all possibilities without extra memory. 💡 Key Learning: Backtracking becomes more powerful when optimized with in-place operations — cleaner and faster! ⚙️ Time Complexity: O(n × n!) 📦 Space Complexity: O(n) (recursion stack) #leetcode #dsa #cpp #backtracking #codingjourney #programming #100daysofcode
To view or add a comment, sign in
-
-
Solved another interesting array problem today: Segregate 0s and 1s in-place using the Two Pointer Approach. Problem Given an array containing only 0s and 1s, rearrange it so that all 0s come on the left side and all 1s come on the right side. Approach 1. I used the two pointer technique: 2. One pointer starts from the beginning 3. Another pointer starts from the end 4. Move pointers inward based on correct placement 5. Swap only when needed Why this approach? Time Complexity: O(n) Space Complexity: O(1) Efficient because it modifies the array in-place Learning This problem is a great example of how two pointers can help optimize array manipulation problems without using extra memory. #DSA #Coding #CPP #Programmers #SoftwareDeveloper #TwoPointers #ProblemSolving #DataStructures #Algorithms
To view or add a comment, sign in
-
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