Leetcode Problem 1182. Shortest Distance to Target Color

1182. Shortest Distance to Target Color

Leetcode Solutions

Approach: Binary Search

  1. Initialize a hashmap to store the indices for each color.
  2. Iterate over the colors array and append the index to the corresponding color's list in the hashmap.
  3. For each query (i, c): a. Check if color c is in the hashmap. If not, return -1. b. Perform a binary search on the list of indices for color c to find the closest index to i. c. If i is less than the first index in the list, return the distance to the first index. d. If i is greater than the last index in the list, return the distance to the last index. e. Otherwise, find the closest index on either side of i and return the minimum distance.
  4. Return the results of all queries as a list.
UML Thumbnail

Approach: Pre-computed Distances

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...