🧠 LeetCode POTD — From TLE to Optimized Thinking 3488. Closest Equal Element Queries At first, the approach felt straightforward. For each query: 👉 Start from the given index 👉 Expand left and right (circularly) 👉 Find the closest same element ━━━━━━━━━━━━━━━━━━━ 💥 The problem? This works… but doesn't scale. If there are q queries and n elements: → Each query can take O(n) → Total = O(n × q) 👉 This leads to TLE for large inputs. ━━━━━━━━━━━━━━━━━━━ 💡 So what's the issue? We are repeating the same work again and again for every query. ━━━━━━━━━━━━━━━━━━━ 📌 Better Approach: Preprocess the array. 👉 Use a map: value → list of indices Example: nums = [1, 2, 1, 3, 1] → 1 → [0, 2, 4] Now for each query: Get all indices of that value If only one occurrence → answer = -1 Else: 👉 Use binary search to find the closest index 👉 Check neighbors (left & right) 📌 Since the array is circular: Distance = min(|i - j|, n - |i - j|) ━━━━━━━━━━━━━━━━━━━ 💡 Complexity now: → Preprocessing: O(n) → Each query: O(log n) 👉 Total: O(n + q log n) ━━━━━━━━━━━━━━━━━━━ 📌 What I liked about this problem: The solution isn't complicated. The key is realizing: 👉 "This is not a single query problem." Once you see that, the shift from brute force → optimized becomes obvious. ✅ Sometimes optimization is not about faster code ✅ It's about not repeating the same work Curious if someone solved it differently 👀 #LeetCode #DataStructures #ProblemSolving #SoftwareEngineering #DSA #C++ #Java #SDE
LeetCode 3488 Closest Equal Element Queries Optimized Solution
More Relevant Posts
-
🚀 Day 76 — Slow & Fast Pointer (Find the Duplicate Number) Continuing the cycle detection pattern — today I applied slow‑fast pointers to an array problem where the values act as pointers to indices. 📌 Problem Solved: - LeetCode 287 – Find the Duplicate Number 🧠 Key Learnings: 1️⃣ The Problem Twist Given an array of length `n+1` containing integers from `1` to `n` (inclusive), with one duplicate. We must find the duplicate without modifying the array and using only O(1) extra space. 2️⃣ Why Slow‑Fast Pointer Works Here - Treat the array as a linked list where `i` points to `nums[i]`. - Because there’s a duplicate, two different indices point to the same value → a cycle exists in this implicit linked list. - The duplicate number is exactly the entry point of the cycle (same logic as LeetCode 142). 3️⃣ The Algorithm in Steps - Phase 1 (detect cycle): `slow = nums[slow]`, `fast = nums[nums[fast]]`. Wait for them to meet. - Phase 2 (find cycle start): Reset `slow = 0`, then move both one step at a time until they meet again. The meeting point is the duplicate. 4️⃣ Why Not Use Sorting or Hashing? - Sorting modifies the array (not allowed). - Hashing uses O(n) space (not allowed). - Slow‑fast pointer runs in O(n) time and O(1) space — perfect for the constraints. 💡 Takeaway: This problem beautifully demonstrates how the slow‑fast pattern transcends linked lists. Any structure where you can define a “next” function (here: `next(i) = nums[i]`) can be analyzed for cycles. Recognizing this abstraction is a superpower. No guilt about past breaks — just another pattern mastered, one day at a time. #DSA #SlowFastPointer #CycleDetection #FindDuplicateNumber #LeetCode #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
To view or add a comment, sign in
-
**Day 109 of #365DaysOfLeetCode Challenge** Today’s problem: **132 Pattern (LeetCode 456)** This problem looks tricky at first because it asks for a hidden subsequence: Find indices `i < j < k` such that: `nums[i] < nums[k] < nums[j]` That forms the **132 pattern** 💡 **Core Idea: Use a Monotonic Stack** Instead of checking all triplets (**O(n³)** ❌), we scan from **right to left**. Why reverse? Because while moving backward: * We try to build possible `3` values using a stack * Track the best possible `2` using a variable called `third` 👉 If we ever find a number smaller than `third`, then: `nums[i] < third < nums[j]` 📌 **Approach:** * Traverse from end to start * Maintain decreasing stack * Pop smaller elements and update `third` * If current number < `third` → return true ⚡ **Time Complexity:** O(n) ⚡ **Space Complexity:** O(n) **What I learned today:** Some array problems become much easier when traversed **backward instead of forward**. 💭 **Key Takeaway:** When the problem asks for hidden order relations: 👉 Think stacks 👉 Think reverse traversal 👉 Think maintaining candidates dynamically This was a great reminder that brute force is rarely the final answer #LeetCode #DSA #MonotonicStack #Arrays #CodingChallenge #ProblemSolving #Java #TechJourney #Consistency
To view or add a comment, sign in
-
-
𝗪𝗲 𝗿𝗲𝗽𝗹𝗮𝗰𝗲𝗱 𝗚𝘂𝗮𝘃𝗮 𝗜𝗺𝗺𝘂𝘁𝗮𝗯𝗹𝗲𝗠𝗮𝗽 𝘄𝗶𝘁𝗵 𝗝𝗮𝘃𝗮 𝗠𝗮𝗽.𝗼𝗳. 𝗔𝗻𝗱 𝘁𝗵𝗲 𝘀𝘆𝘀𝘁𝗲𝗺 𝗯𝗿𝗼𝗸𝗲. 💥 The code still compiled ✅ Nothing looked suspicious 👀 It was a small refactor 🔧 But after the change, behavior was different. Tests started failing ❌ Output changed 📦 Part of the system behaved differently ⚠️ At first glance, this looked strange. We replaced one immutable map with another immutable map. So why did anything break? Because the system had a hidden dependency 🧠 It turned out part of our logic was relying on iteration order. Not explicitly. Not by design. Just implicitly, through how the map was being used. And that was the real problem. Nobody on the team expected that a map would become part of the behavior in that way 🤯 But it already had. So the issue was not just "Guava vs JDK". The issue was that we changed a piece of code without fully understanding what the surrounding system had started to depend on. The quick fix was simple: use LinkedHashMap and restore deterministic ordering ⚡ But the more interesting lesson was not about LinkedHashMap. The real lesson was this: When you replace something that looks equivalent, you may still be changing behavior. Same shape of API does not mean same semantics ❗ Same return type does not mean same guarantees ⚠️ And "it worked before" does not mean the dependency was valid. It may simply have been hidden. That is why before replacing a method, collection, or utility, it is worth understanding 2 things: 1️⃣ The behavior of the thing you are introducing 2️⃣ The behavior your system already depends on #java #springboot #backend #softwareengineering #refactoring #engineering #distributedsystems
To view or add a comment, sign in
-
-
I hit a strange realization today. Not a new concept. Not a new framework. Just something I’ve already used in production. But still… *I couldn’t explain it cleanly. We often say “I know this.” But do we really? Today’s trigger was a simple API design scenario in Spring Framework: 👉 Upload a file + send structured JSON data in the same request Sounds basic, right? But when I tried to break it down clearly— the *why*, the *how*, the *right annotation*— there was hesitation. --- Then the clarity came back: * `@RequestParam` → key-value inputs * `@PathVariable` → resource identity * `@RequestBody` → pure JSON payload * `@RequestPart` → **multipart boundary where file + structured data meet That moment reminded me of something deeper: > “Exposure creates familiarity. > But only articulation proves understanding.” In real systems, this gap shows up everywhere: * You’ve seen the pattern, but can’t justify it * You’ve fixed the bug, but can’t explain root cause * You’ve used the annotation, but don’t know *why it exists* At scale, this matters. Because senior engineering is not about: ❌ Writing more code It’s about: ✔ Explaining decisions clearly ✔ Designing with intent ✔ Debugging with first-principles thinkin --- **Today wasn’t about learning something new. It was about realizing what I hadn’t fully understood.** And that’s a different kind of progress. #SoftwareEngineering #Java #SpringBoot #SystemDesign #Backend #EngineeringMindset
To view or add a comment, sign in
-
Beginning this journey to learn in public and stay consistent with Problem :- Contains Duplicate (LeetCode 217) Problem Statement :- Given an integer array, return true if any value appears at least twice, otherwise return false. Approach 1 :- Brute Force (Nested Loops) i - Compare every element with others ii - Time Complexity:- O(n²) => because of nested loops iii - Simple but inefficient for large inputs class Solution { public boolean containsDuplicate(int[] nums) { for (int i = 0; i < nums.length - 1; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] == nums[j]) return true; } } return false; } } Approach 2 :- Optimized (Sorting) Sort array → check adjacent elements Time Complexity:- O(n log n) class Solution { public boolean containsDuplicate(int[] nums) { Arrays.sort(nums); for (int i = 1; i < nums.length; i++) { if (nums[i] == nums[i - 1]) return true; } return false; } } Key Learning: Start with brute force → then optimize. How would you optimize this further? One problem. Every day. No shortcuts, just consistency. #LeetCode #Java #DSA #CodingChallenge #SoftwareEngineering #Arrays #Sorting
To view or add a comment, sign in
-
-
🧠 LeetCode POTD — The Bug Wasn’t Logic… It Was Leading Zeros 3761. Minimum Absolute Distance Between Mirror Pairs At first glance, this problem looked simple. Find two indices (i, j) such that: 👉 reverse(nums[i]) == nums[j] and return the minimum distance. My first instinct was straightforward: 👉 Store all numbers in a map 👉 Reverse the current number 👉 Check if it already exists Simple enough. 💥 But then one small edge case caused issues: Leading zeros Example: 120 → 21 Not 021 So if you think in strings, it’s easy to make mistakes. 💡 The cleaner approach: Instead of storing original numbers first, 👉 Reverse each number mathematically 👉 Store the reversed value with its latest index 👉 If current number already exists in map, we found a mirror pair Why this works: If we process: 120 We store: 21 Later when 21 appears, we instantly know it matches. 📌 Best part: Mathematical reversal automatically handles leading zeros. 120 → 21 300 → 3 101 → 101 No extra checks needed. 💡 What I liked about this problem: The challenge wasn’t data structures. It was noticing that a small representation detail changes the whole solution. Sometimes bugs are not in algorithms. They’re hidden inside edge cases. Curious — did anyone else first think of using strings here? 👀 #LeetCode #ProblemSolving #HashMap #SoftwareEngineering #DSA #SDE #Java #C++
To view or add a comment, sign in
-
-
🔥 Day 552 of #750DaysOfCode 🔥 🔐 LeetCode 2075: Decode the Slanted Ciphertext (Medium) Today’s problem looked tricky at first, but once the pattern clicked, it became super elegant 😄 🧠 Problem Understanding We are given an encoded string that was: Filled diagonally (↘) into a matrix Then read row-wise (→) 👉 Our task is to reverse this process and recover the original text. 💡 Key Insight If encoding is: ➡️ Fill diagonally ➡️ Read row-wise Then decoding is: ➡️ Read diagonally from row-wise string ⚙️ Approach ✅ Step 1: Calculate number of columns cols = encodedText.length() / rows; ✅ Step 2: Traverse diagonals starting from each column for (int startCol = 0; startCol < cols; startCol++) { int row = 0, col = startCol; while (row < rows && col < cols) { result.append(encodedText.charAt(row * cols + col)); row++; col++; } } ✅ Step 3: Remove trailing spaces 🚀 Complexity Time: O(n) Space: O(n) 🧠 What I Learned How to reverse matrix-based encoding patterns Converting 2D traversal → 1D index mapping Importance of pattern recognition in problems 📌 Takeaway Not every problem needs heavy logic. Sometimes, it's just about seeing the pattern correctly 👀 #LeetCode #DSA #Java #CodingJourney #ProblemSolving #Algorithms #SoftwareEngineering #100DaysOfCode #750DaysOfCode
To view or add a comment, sign in
-
-
Problem :- Two Sum (LeetCode 1) Problem Statement :- Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to the target. Assume exactly one solution exists, and you may not use the same element twice. Approach 1 :- Brute Force => Nested Loop i - Check every pair of elements ii - If nums[i] + nums[j] == target => return indices iii - Time Complexity : O(n²) class Solution { public int[] twoSum(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { return new int[]{i, j}; } } } return new int[]{}; } } Approach 2 :- Optimal => HashMap i - Store number and its index in a HashMap ii - For each element, check if (target - current) exists iii - Time Complexity : O(n) class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { return new int[]{map.get(complement), i}; } map.put(nums[i], i); } return new int[]{}; } } Key Takeaway :- Instead of checking every pair, we store previously seen elements and directly find the required complement efficiently. #Java #DSA #LeetCode #CodingJourney #LearnInPublic #SoftwareEngineering #HashMap
To view or add a comment, sign in
-
-
🚀 LeetCode 207 – Course Schedule | From Multiple Approaches → Cleaner Thinking While working on graph problems, I revisited Course Schedule and explored multiple implementations in Java — not just to solve it, but to understand why each approach works. 🔍 Core Idea Courses + prerequisites → Directed Graph Goal → Check if graph has a cycle 👉 If cycle exists → ❌ cannot finish all courses 👉 If no cycle → ✅ valid ordering exists (DAG) 💡 Approach 1: BFS (Kahn’s Algorithm) Build graph + compute in-degree Process nodes with in-degree = 0 Count processed nodes ✔ Intuitive (layer-by-layer removal) ✔ Great for topological sorting ❗ Slight overhead (separate passes) 💡 Approach 2: DFS (Visited + Recursion Stack) Track visited[] and recStack[] Detect back-edge → cycle ✔ Strong conceptual clarity ✔ Useful for many graph problems ❗ Extra space for 2 arrays 💡 Approach 3: Optimized BFS (Single Pass) ⭐ Build graph + in-degree together Use ArrayDeque for performance No extra passes ✔ Cleaner ✔ More efficient in practice ✔ Interview-friendly 💡 Approach 4: DFS with State Array (Latest Submission) 🔥 // 0 = unvisited, 1 = visiting, 2 = visited Replace visited[] + recStack[] with single state[] Detect cycle when visiting a node already in state = 1 ✔ Same time complexity → O(V + E) ✔ Reduced space usage ✔ Cleaner logic (less bookkeeping) 🔥 What Changed My Understanding Same problem. Same complexity. But different implementations gave me: Better control over graph traversal patterns Clear understanding of cycle detection Ability to optimize space without changing logic 📌 Takeaway Don’t stop at “Accepted” ✅ Push further: Try another approach Optimize space or structure Compare trade-offs That’s where real growth happens. #Java #DSA #Graphs #LeetCode #TopologicalSort #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
-
Day 71/100 Completed ✅ 🚀 Solved LeetCode – Reshape the Matrix (Java) ⚡ Implemented an efficient matrix transformation approach by mapping elements from the original matrix to the reshaped matrix using a single traversal. Instead of creating intermediate structures, used index manipulation (count / c, count % c) to place elements correctly while maintaining row-wise order. 🧠 Key Learnings: • Understanding how to map 2D indices into a linear traversal • Efficiently converting between different matrix dimensions • Handling edge cases where reshape is not possible • Writing clean and optimized nested loop logic 💯 This problem strengthened my understanding of matrix traversal and index mapping techniques, which are very useful in array and grid-based problems. 🔗 Profile: https://lnkd.in/gaJmKdrA #leetcode #datastructures #algorithms #java #matrix #arrays #problemSolving #100DaysOfCode 🚀
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