LeetCode Daily Challenge: Minimize Gap Between Triplets

🚀 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

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories