The Wayback Machine - https://web.archive.org/web/20210911092605/https://www.geeksforgeeks.org/minimum-steps-to-reach-a-given-index-in-the-array-based-on-given-conditions/
Skip to content
Related Articles

Related Articles

Improve Article

Minimum steps to reach a given index in the Array based on given conditions

  • Last Updated : 10 Sep, 2021

Given an array arr[ ] of size N consisting of integers -1, 0, 1 only and an array q[ ] consisting of queries. In the array arr[ ], -1 signifies that any index to the left of it is reachable and 1 signifies that any index to the right of it is reachable from that index. The index in a particular query is not directly reachable but all other indices are reachable. Find the minimum number of steps required to reach any index from it’s neighboring index (whichever is nearest) for each query and finally return the array of results. If any index is not reachable, return -1.

Examples:

Input: arr[ ] = {0,  0, -1,  0,  1,  0,  0, 1, 1, -1, 0}, q[ ] = {3, 6}
Output: result[ ] = {6,  2}
Explanation: There is only 1 way to reach index 3, i.e. from index 9. Therefore minimum distance= 9-3=6
The shortest path to reach index 6 is via index 4. Therefore minimum distance=6-4=2
result[ ]={6, 2}

Input: arr[ ] = {-1, 0, 0, 0, 1}, q[ ] = {2, 0}
Output: result[ ] = {-1, 0}

Approach: The idea is to store the indices of nearest 1 from the left side and nearest -1 from the right side and then while traversing the array q[] for each query q[i], check for the distance from both sides and store the minimum one. Follow the steps to solve the problem:



  • Initialize the vectors result[], v1[] and v2[] to store the result for each query, and the nearest 1 and -1.
  • Initialize the variables last_1 and last_m1 as -1 to store the latest 1 and -1.
  • Iterate over the range [0, N] using the variable i and perform the following tasks:
    • Push the value of last_1 in the vector v2[].
    • If arr[i] is equal to 1, then set the value of last_1 as i.
  • Iterate over the range [N-1, 0] using the variable i and perform the following tasks:
    • Push the value of last_m1 in the vector v2[].
    • If arr[i] is equal to -1, then set the value of last_m1 as i.
  • Reverse the vector v1[].
  • Iterate over the range [0, M] using the variable i and perform the following tasks:
    • If v1[q[i]] and v2[q[i]] are not equal to -1, then set the value result[i] as the minimum of abs(v1[q[i]] – q[i]) or abs(v2[q[i]] – q[i]).
    • Else if, v1[q[i]] is not equal to -1, then set the value result[i] as abs(v1[q[i]] – q[i]).
    • Else if, v2[q[i]] is not equal to -1, then set the value result[i] as abs(v2[q[i]] – q[i]).
    • Else, set the value of result[i] as -1.
  • After performing the above steps, print the vector result[] as the answer.

Below is the implementation of the above approach.

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to return the min distance
// from neighboring index
vector<int> res(int arr[], int q[], int n, int m)
{
    // Vectors result, v1 and v2 to
    // store the minimum distance, index
    // of -1 and 1 respectively
    vector<int> result, v1, v2;
  
    // Variables to store the last
    // position of -1 and 1
    int last_m1 = -1, last_1 = -1;
  
    // Traverse over the array arr[]
    // to store the index of 1
    for (int i = 0; i < n; i++) {
        v2.push_back(last_1);
        if (arr[i] == 1)
            last_1 = i;
    }
  
    // Traverse over the array arr[]
    // to store the index of -1
    for (int i = n - 1; i >= 0; i--) {
        v1.push_back(last_m1);
        if (arr[i] == -1)
            last_m1 = i;
    }
  
    // Reverse v1 to get the original order
    reverse(v1.begin(), v1.end());
  
    // Traverse over the array q[]
    for (int i = 0; i < m; i++) {
  
        if (v1[q[i]] != -1 and v2[q[i]] != -1)
            result.push_back(
                min(abs(v1[q[i]] - q[i]),
                    abs(v2[q[i]] - q[i])));
        else if (v1[q[i]] != -1)
            result.push_back(
                abs(v1[q[i]] - q[i]));
        else if (v2[q[i]] != -1)
            result.push_back(
                abs(v2[q[i]] - q[i]));
        else
            result.push_back(-1);
    }
  
    // Finally return the vector of result
    return result;
}
  
// Driver Code
int main()
{
    // Input
    int arr[] = { -1, 0, 0, 1, -1, 1,
                  1, 0, 0, 1, -1, 0 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // Query
    int q[] = { 1, 5, 10 };
    int m = sizeof(q) / sizeof(q[0]);
  
    // Function call to find the minimum distance
    vector<int> x = res(arr, q, n, m);
  
    // Print the resultant vector
    for (auto y : x)
        cout << y << " ";
  
    return 0;
}
Output
3 2 1 

Time Complexity: O(N+M) where N is the size of arr[ ] and M is the size of q[ ]
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :