Similar Problems

Similar Problems not available

Shortest Distance To Target Color - Leetcode Solution

Companies:

LeetCode:  Shortest Distance To Target Color Leetcode Solution

Difficulty: Medium

Topics: dynamic-programming binary-search array  

The "Shortest Distance to Target Color" problem on LeetCode asks you to find the shortest distance between each element in an array and a target color. The array contains a series of colors represented by integers, and the target color is also an integer value.

Here is a detailed solution to the problem:

  1. Create a dictionary that maps each color to its indices in the array.
color_indices = {}
for i, color in enumerate(colors):
    if color not in color_indices:
        color_indices[color] = []
    color_indices[color].append(i)
  1. Iterate through the array, and for each element find the nearest index of the target color.
result = []
for i, color in enumerate(colors):
    if color == targetColor:
        result.append(0)
    elif targetColor not in color_indices:
        result.append(-1)
    else:
        distances = [abs(i-j) for j in color_indices[targetColor]]
        result.append(min(distances))
  1. Return the result list.
return result

The solution works by first creating a dictionary that maps each color to its indices in the array. Then, for each element in the array, it checks whether the color matches the target color. If it does, it adds 0 to the result list. If it doesn't, it checks whether the target color is even present in the array. If it isn't, it adds -1 to the result list. Otherwise, it calculates the distances between the current element and all the indices of the target color in the array, and adds the minimum distance to the result list.

Overall, this solution has a time complexity of O(n), where n is the length of the array, because it only iterates through the array once. The space complexity depends on the number of unique colors in the array, but it's at most O(n) as well.

Shortest Distance To Target Color Solution Code

1