You are given an array of integers colors, in which each element is either 0, 1 or 2. You are also given some queries. Each query consists of two integers index and color. For each query, find the shortest distance from the given index to a cell of the given color. If there is no such color in the array, return -1.
Return an array ans of the same length as queries, where ans[i] is the answer to the ith query.
Example 1:
Input: colors = [1,1,2,1,3,2,2,3,3], queries = [[1,3],[2,2],[6,1]] Output: [3,0,3] Explanation: Closest distance from index 1 to color 3 is 3. Closest distance from index 2 to color 2 is 0. Closest distance from index 6 to color 1 is 3.
Example 2:
Input: colors = [1,2], queries = [[0,3]] Output: [-1] Explanation: There is no color 3 in the array colors.
Constraints:
1 <= colors.length <= 5 * 1040 <= colors[i] <= 21 <= queries.length <= 104queries[i].length == 20 <= queries[i][0] < colors.length0 <= queries[i][1] <= 2When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force method means we will check every possible distance for each position. We will look at every possible position around the target position and compute the distances until we find a color match.
Here's how the algorithm would work step-by-step:
def shortest_distance_brute_force(colors, target_color):
results = []
for start_position in range(len(colors)):
distance = 1
found = False
# If the starting position is already the target color, the distance is zero.
if colors[start_position] == target_color:
results.append(0)
continue
while not found:
left_index = start_position - distance
right_index = start_position + distance
# Check left index
if left_index >= 0:
# Check if the color matches at the left index
if colors[left_index] == target_color:
results.append(distance)
found = True
continue
# Check right index
if right_index < len(colors):
# Check if the color matches at the right index
if colors[right_index] == target_color:
results.append(distance)
found = True
continue
#If neither left or right finds target, increase search radius.
distance += 1
#If no target is found, distance becomes array bounds.
if left_index < 0 and right_index >= len(colors):
results.append(-1)
found = True
return resultsThe most efficient way to find the shortest distance is to remember the locations of each color as we go. Then, for each spot, we can quickly check which color is closest by comparing distances to the nearest locations of each target color.
Here's how the algorithm would work step-by-step:
def shortest_distance_to_target_color(colors, queries):
color1_indices = []
color2_indices = []
color3_indices = []
# Store indices of each color
for index, color in enumerate(colors):
if color == 1:
color1_indices.append(index)
elif color == 2:
color2_indices.append(index)
else:
color3_indices.append(index)
result = []
for query_index, target_color in queries:
# Find closest index for target color
if target_color == 1:
indices = color1_indices
elif target_color == 2:
indices = color2_indices
else:
indices = color3_indices
min_distance = float('inf')
if not indices:
result.append(-1)
continue
# Calculate shortest distance
for index_value in indices:
distance = abs(index_value - query_index)
min_distance = min(min_distance, distance)
result.append(min_distance)
return result| Case | How to Handle |
|---|---|
| Empty colors array | Return an empty result array since there are no colors to check. |
| Empty queries array | Return an empty result array as there are no queries to process. |
| No occurrence of the target color in the colors array | Return -1 for that query since the target color is not present. |
| Large colors array with few target color occurrences, leading to potentially long search | Binary search should be used for optimal lookup performance after pre-processing and storing the target color indices. |
| All elements in the colors array are the same color (the target color) | All query results will be 0, since the nearest color is always the current index. |
| Query index is at the very beginning or very end of the colors array | Handle boundary conditions correctly when calculating distances. |
| Integer overflow when calculating distances for very large arrays | Ensure that the data type used for distance calculations (e.g., int) can accommodate large differences in indices, or use long if necessary. |
| Query index out of bounds | Return an appropriate error value or throw an exception if the query index is outside the valid range [0, colors.length - 1]. |