Open In App

Minimum distance to target value from each index in given Array

Given an array of words[] that is arranged in a circular manner and a target string that needs to be found. The circular arrangement means that the array’s end is connected to the beginning of the array. To move from one word to another, you can either move to the next or the previous word from the current word in one step at a time, the task is to find the shortest distance required to reach the target string starting from the ‘startIndex’ in the circular array. If the target string is not present in the ‘words’ array, return -1.

Examples:



Input: words = [“hello”, “i”, “am”, “GeekGorGeek”, “hello”], target = “hello”, startIndex = 1
Output: 1
Explanation: We start from index 1 and can reach “hello” by

  • moving 3 units to the right to reach index 4.
  • moving 2 units to the left to reach index 4.
  • moving 4 units to the right to reach index 0.
  • moving 1 unit to the left to reach index 0.

The shortest distance to reach “hello” is 1.



Input: words = [“i”, “love”, “GFG”], target = “eat”, startIndex = 0
Output: -1
Explanation: Since “eat” does not exist in words, we return -1.

Approach: To solve the problem follow the below idea:

The first search moves to the right of the startIndex, while the second search moves to the left. The distances between the target and the startIndex are calculated for both searches, and the minimum distance is returned as the result. If the target is not found within the array, the method returns -1.

Below is the implementation for the above approach:

Below is the implementation for the above approach:




// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
int circularTarget(vector<string>& words, string target,
                   int startIndex)
{
 
    // Get the size of the vector of
    // words
    int n = words.size();
 
    // Initialize the distance to the
    // right to 0
    int rightDistance = 0;
 
    // Loop indefinitely until the target is
    // found or the entire vector is searched
    for (int i = startIndex; true; i = (i + 1) % n) {
 
        // Check if the entire vector has
        // been searched without finding
        // the target
        if (rightDistance == n) {
            return -1;
        }
 
        // Check if the current word is
        // equal to the target
        if (words[i] == target) {
 
            // Break out of the loop if
            // the target is found
            break;
        }
        else {
 
            // Increment the distance to
            // the right and move to
            // the next position
            rightDistance++;
        }
    }
 
    // Initialize the distance
    // to the left to 0
    int leftDistance = 0;
 
    // loop indefinitely until the target
    // is found or the entire
    // vector is searched
    for (int i = startIndex; true; i = (i - 1 + n) % n) {
 
        // Check if the current word is
        // equal to the target
        if (words[i] == target) {
 
            // Break out of the loop if
            // the target is found
            break;
        }
        else {
 
            // Increment the distance to the
            // left and move to the
            // previous position
            leftDistance++;
        }
    }
 
    // Return the minimum distance between
    // the start index and the target
    // to the left and right
    return rightDistance <= leftDistance ? rightDistance
                                         : leftDistance;
}
 
// Drivers code
int main()
{
    vector<string> words{ "hello", "i", "am", "GeekGorGeek",
                          "hello" };
    string target = "hello";
    int startIndex = 1;
 
    // Function Call
    cout << circularTarget(words, target, startIndex);
    return 0;
}




import java.util.*;
 
public class GFG {
    public static int circularTarget(List<String> words,
                                     String target,
                                     int startIndex)
    {
        // Get the size of the list of words
        int n = words.size();
 
        // Initialize the distance to the right to 0
        int rightDistance = 0;
 
        // Loop indefinitely until the target is found or
        // the entire list is searched
        for (int i = startIndex; true; i = (i + 1) % n) {
            // Check if the entire list has been searched
            // without finding the target
            if (rightDistance == n) {
                return -1;
            }
 
            // Check if the current word is equal to the
            // target
            if (words.get(i).equals(target)) {
                // Break out of the loop if the target is
                // found
                break;
            }
            else {
                // Increment the distance to the right and
                // move to the next position
                rightDistance++;
            }
        }
 
        // Initialize the distance to the left to 0
        int leftDistance = 0;
 
        // Loop indefinitely until the target is found or
        // the entire list is searched
        for (int i = startIndex; true;
             i = (i - 1 + n) % n) {
            // Check if the current word is equal to the
            // target
            if (words.get(i).equals(target)) {
                // Break out of the loop if the target is
                // found
                break;
            }
            else {
                // Increment the distance to the left and
                // move to the previous position
                leftDistance++;
            }
        }
 
        // Return the minimum distance between the start
        // index and the target to the left and right
        return Math.min(rightDistance, leftDistance);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        List<String> words = Arrays.asList(
            "hello", "i", "am", "GeekGorGeek", "hello");
        String target = "hello";
        int startIndex = 1;
 
        // Function call
        System.out.println(
            circularTarget(words, target, startIndex));
    }
}




# Python code for the above approach:
 
 
def circularTarget(words, target, startIndex):
    # Get the size of the vector of words
    n = len(words)
 
    # Initialize the distance to the
    # right to 0
    rightDistance = 0
 
    # Loop indefinitely until the target is
    # found or the entire vector is searched
    for i in range(startIndex, n + startIndex):
 
        # Check if the entire vector has
        # been searched without finding
        # the target
        if rightDistance == n:
            return -1
 
        # Check if the current word is
        # equal to the target
        if words[i % n] == target:
 
            # Break out of the loop if
            # the target is found
            break
        else:
 
            # Increment the distance to
            # the right and move to
            # the next position
            rightDistance += 1
 
    # Initialize the distance
    # to the left to 0
    leftDistance = 0
 
    # loop indefinitely until the target
    # is found or the entire
    # vector is searched
    for i in range(startIndex, startIndex - n, -1):
 
        # Check if the current word is
        # equal to the target
        if words[i % n] == target:
 
            # Break out of the loop if
            # the target is found
            break
        else:
 
            # Increment the distance to the
            # left and move to the
            # previous position
            leftDistance += 1
 
    # Return the minimum distance between
    # the start index and the target
    # to the left and right
    return min(rightDistance, leftDistance)
 
 
# Driver Code
words = ["hello", "i", "am", "GeekGorGeek", "hello"]
target = "hello"
startIndex = 1
 
# Function call
print(circularTarget(words, target, startIndex))




// C# code for the above approach:
using System;
using System.Collections.Generic;
 
class GFG {
    static int CircularTarget(List<string> words,
                              string target, int startIndex)
    {
 
        // Get the size of the list of words
        int n = words.Count;
 
        // Initialize the distance to the
        // right to 0
        int rightDistance = 0;
 
        // Loop indefinitely until the target is
        // found or the entire list is searched
        for (int i = startIndex; true; i = (i + 1) % n) {
 
            // Check if the entire list has
            // been searched without finding
            // the target
            if (rightDistance == n) {
                return -1;
            }
 
            // Check if the current word is
            // equal to the target
            if (words[i] == target) {
 
                // Break out of the loop if
                // the target is found
                break;
            }
            else {
 
                // Increment the distance to
                // the right and move to
                // the next position
                rightDistance++;
            }
        }
 
        // Initialize the distance
        // to the left to 0
        int leftDistance = 0;
 
        // loop indefinitely until the target
        // is found or the entire
        // list is searched
        for (int i = startIndex; true;
             i = (i - 1 + n) % n) {
 
            // Check if the current word is
            // equal to the target
            if (words[i] == target) {
 
                // Break out of the loop if
                // the target is found
                break;
            }
            else {
 
                // Increment the distance to the
                // left and move to the
                // previous position
                leftDistance++;
            }
        }
 
        // Return the minimum distance between
        // the start index and the target
        // to the left and right
        return rightDistance <= leftDistance ? rightDistance
                                             : leftDistance;
    }
 
    static void Main()
    {
        List<string> words
            = new List<string>{ "hello", "i", "am",
                                "GeekGorGeek", "hello" };
        string target = "hello";
        int startIndex = 1;
 
        // Function Call
        Console.WriteLine(
            CircularTarget(words, target, startIndex));
    }
}




function circularTarget(words, target, startIndex) {
    // Get the size of the array of words
    const n = words.length;
 
    // Initialize the distance to the right to 0
    let rightDistance = 0;
 
    // Loop indefinitely until the target is found or the entire array is searched
    for (let i = startIndex; true; i = (i + 1) % n) {
        // Check if the entire array has been searched without finding the target
        if (rightDistance === n) {
            return -1;
        }
 
        // Check if the current word is equal to the target
        if (words[i] === target) {
            // Break out of the loop if the target is found
            break;
        } else {
            // Increment the distance to the right and move to the next position
            rightDistance++;
        }
    }
 
    // Initialize the distance to the left to 0
    let leftDistance = 0;
 
    // Loop indefinitely until the target is found or the entire array is searched
    for (let i = startIndex; true; i = (i - 1 + n) % n) {
        // Check if the current word is equal to the target
        if (words[i] === target) {
            // Break out of the loop if the target is found
            break;
        } else {
            // Increment the distance to the left and move to the previous position
            leftDistance++;
        }
    }
 
    // Return the minimum distance between the start index and the target to the left and right
    return rightDistance <= leftDistance ? rightDistance : leftDistance;
}
 
// Driver code
const words = ["hello", "i", "am", "GeekGorGeek", "hello"];
const target = "hello";
const startIndex = 1;
 
// Function call
console.log(circularTarget(words, target, startIndex));

Output
1

Time Complexity:  O(n), where n is the length of the input array of “words”.
Auxiliary Space: O(1)


Article Tags :