LeetCode 3488 Closest Equal Element Queries Optimized Solution

🧠 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

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories