VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-shortest-distance-to-target-color/

⇱ Find Shortest Distance to Target Color - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find Shortest Distance to Target Color

Last Updated : 23 Jul, 2025

Given an array colors, in which there are three colors: 1, 2 and 3. You are also given some queries. Each query consists of two integers i and c, return the shortest distance between the given index i and the target color c. If there is no solution return -1.

Examples:

Input: colors = [1, 1, 2, 1, 3, 2, 2, 3, 3], queries = [[1, 3], [2, 2], [6, 1]]
Output: [3, 0, 3]
Explanation:  The nearest 3 from index 1 is at index 4 (3 steps away). The nearest 2 from index 2 is at index 2 itself (0 steps away). The nearest 1 from index 6 is at index 3 (3 steps away).

Input:  colors = [2, 1, 1, 3, 2, 3, 1, 3, 3] queries = [[1, 2], [5, 3], [7, 1]]
Output: [1, 0, 1]

Explanation:  The nearest 2 from index 1 is at index 0 (1 steps away). The nearest 3 from index 5 is at index 5 itself (0 steps away). The nearest 1 from index 7 is at index 6 (1 steps away).

Approach: To solve the problem, follow the below idea:

The problem can be solved by precomputation the minimum distance to the colors 1, 2 and 3 on the right as well as on the left. For each index i, we can store the minimum distance of color 1, 2 and 3 on the right and on the left and return the minimum between them. We can maintain 2 2D arrays of size N * 3, left[][] and right[][] such that left[i][j] stores the nearest index with color j + 1 on the left of index i(including i) and right[i][j] stores the nearest index with color j + 1 to the right of index i(including index i).

Step-by-step algorithm:

  • Initialize 2D array left[][] and right[][] of size N X 3.
  • Initialize the first column of left according to the first color in the input array.
  • Initialize the last column of right according to the last color in the input array.
  • For all indices i > 0,
    • Copy the values from the previous indices, left[i][j] = left[i - 1][j]
    • Update the current color in left, left[i][color[i] - 1] = i;
  • For all indices i < N - 1,
    • Copy the values from the next indices, right[i][j] = right[i + 1][j]
    • Update the current color in right, right[i][color[i] - 1] = i;
  • For each query, return the minimum of left[] and right[].

Below is the implementation of above approach:


Output
[1, 0, 1]

Time Complexity: O(N + Q * log(N)), where N is number of the elements in the input array and and Q is the number of queries.
Auxiliary Space: O(N)

Comment
Article Tags: