Shortest Distance to Target String in Circular Array

🚀 Day 29/30 – DSA Challenge 📌 LeetCode Problem – Shortest Distance to Target String in a Circular Array 📝 Problem Statement You are given: A circular array of strings words[] A target string target A starting index startIndex Return the minimum distance required to reach any occurrence of target. 👉 You can move left or right in circular manner. 📌 Example Input: words = ["hello","i","am","leetcode","hello"] target = "hello" startIndex = 1 Output: 1 💡 Key Insight Since the array is circular, distance is: min(|i - startIndex|, n - |i - startIndex|) 👉 Either go directly 👉 Or wrap around 🔥 Optimal Approach 🧠 Idea Loop through all indices Check where words[i] == target Calculate circular distance Keep minimum 🚀 Algorithm 1️⃣ Initialize minDist = ∞ 2️⃣ For each index i: If match found Compute: dist = Math.min(Math.abs(i - startIndex), n - Math.abs(i - startIndex)); 3️⃣ Update minimum 4️⃣ If no match → return -1 ✅ Java Code (Optimal O(n)) class Solution {   public int closestTarget(String[] words, String target, int startIndex) {           int n = words.length;     int minDist = Integer.MAX_VALUE;     for (int i = 0; i < n; i++) {       if (words[i].equals(target)) {         int diff = Math.abs(i - startIndex);         int dist = Math.min(diff, n - diff);         minDist = Math.min(minDist, dist);       }     }     return minDist == Integer.MAX_VALUE ? -1 : minDist;   } } ⏱ Complexity Time Complexity: O(n) Space Complexity: O(1) 📚 Key Learnings – Day 29 ✔ Circular array problems need special distance handling ✔ Always consider wrap-around cases ✔ Math-based optimization simplifies logic ✔ String comparison using .equals() is important Circular thinking. Simple math. Clean solution. Day 29 completed. Consistency continues 💪🔥 #30DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #Arrays #LeetCode

  • graphical user interface, text, application, chat or text message

To view or add a comment, sign in

Explore content categories