Minimum Distance Among Three Elements in Array

🚀 LeetCode Day Problem Solving 🚀 Day-44 📌 Problem: You are given an integer array nums. A tuple (i, j, k) is called good if: ✔ i, j, k are distinct ✔ nums[i] == nums[j] == nums[k] 👉 Distance of a good tuple: |i - j| + |j - k| + |k - i| 🎯 Goal: Find the minimum possible distance among all good tuples. If none exist → return -1. 🧠 Example: Input: nums = [1,2,1,1,3] ✅ Output: 6 📖 Explanation: Good tuple → (0,2,3) Distance = 2 + 1 + 3 = 6 💡 Key Insight: ✔ For same values, we only care about indices ✔ Sort indices for each number ✔ Try triplets of closest indices 👉 Important formula simplification: For sorted i < j < k Distance = (j-i) + (k-j) + (k-i) = 2*(k - i) ✔ So minimize → difference between farthest indices ⚡ Approach: ✔ Group indices by value (HashMap) ✔ For each value: - If size ≥ 3 → check consecutive triplets - Compute minimum distance 📊 Complexity Analysis: ⏱ Time Complexity: O(n) 📦 Space Complexity: O(n) 🧠 What I Learned: ✔ Grouping using HashMap ✔ Optimizing triplet computation ✔ Using math to simplify distance formula ✅ Day 44 Completed 🚀 Leveling up in Arrays + Hashing + Optimization 💪 #Leetcode #DSA #ProblemSolving #BitManipulation #CodingJourney #InterviewPreparation #Consistency #MilanSahoo 🚀

  • graphical user interface, application

To view or add a comment, sign in

Explore content categories