Open In App

Minimum distance to target value from each index in given Array

Last Updated : 21 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • The function takes in three parameters: words, a vector of strings; target, a string; and startIndex, an integer.
  • The first line of the function assigns the size of the words vector to the variable n.
  • The variable rightDistance is initialized to 0. This variable will be used to keep track of how many words to the right of the startIndex position have been checked before finding the target.
  • The function enters a for-loop that will continue indefinitely (since true is used as the loop condition).
  • Inside the for-loop, the function first checks if rightDistance is equal to n. If it is, it means that the entire vector has been searched without finding the target, so the function returns -1 to indicate that the target was not found.
  • If rightDistance is not equal to n, the function checks if the word at the current position, words[i], is equal to the target. If it is, the function breaks out of the loop.
  • If words[i] is not equal to the target, the function increments rightDistance and moves to the next position to the right using the formula (i+1) % n.
  • After the loop breaks, the function initializes leftDistance to 0. This variable will be used to keep track of how many words to the left of the startIndex position have been checked before finding the target.
  • The function enters a second for-loop that is identical to the first one, except that it searches for the target by moving to the left using the formula (i-1+n) % n.
  • Once the second for-loop breaks, the function checks if rightDistance is less than or equal to leftDistance. If it is, the function returns rightDistance, which represents the distance between the startIndex position and the closest occurrence of the target to the right. 
  • If leftDistance is less than rightDistance, the function returns leftDistance, which represents the distance between the startIndex position and the closest occurrence of the target to the left

Below is the implementation for the above approach:

C++




// 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;
}


Java




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));
    }
}


Python3




# 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#




// 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));
    }
}


Javascript




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)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads