|
| 1 | +# 1182. [Shortest Distance to Target Color](<https://leetcode.com/problems/shortest-distance-to-target-color>) |
| 2 | + |
| 3 | +*All prompts are owned by LeetCode. To view the prompt, click the title link above.* |
| 4 | + |
| 5 | +*[Back to top](<../README.md>)* |
| 6 | + |
| 7 | +------ |
| 8 | + |
| 9 | +> *First completed : August 29, 2025* |
| 10 | +> |
| 11 | +> *Last updated : August 29, 2025* |
| 12 | +
|
| 13 | +------ |
| 14 | + |
| 15 | +> **Related Topics** : **[Array](<by_topic/Array.md>), [Binary Search](<by_topic/Binary Search.md>), [Dynamic Programming](<by_topic/Dynamic Programming.md>)** |
| 16 | +> |
| 17 | +> **Acceptance Rate** : **55.54 %** |
| 18 | +
|
| 19 | +------ |
| 20 | + |
| 21 | +> ## V1 Fuzzy Binary Search |
| 22 | +> |
| 23 | +> Stored where each color appeared in sorted order then used binary search to approximately find where the value would be. Checked for the min difference for the found index j +/- 1 in case the exact value wasn't found (min_distance(arr[j - 1:j+1]) inclusive). |
| 24 | +> |
| 25 | +
|
| 26 | +------ |
| 27 | + |
| 28 | +## Solutions |
| 29 | + |
| 30 | +- [m1182 v1.py](<../my-submissions/m1182 v1.py>) |
| 31 | +### Python |
| 32 | +#### [m1182 v1.py](<../my-submissions/m1182 v1.py>) |
| 33 | +```Python |
| 34 | +class Solution: |
| 35 | + def shortestDistanceColor(self, colors: List[int], queries: List[List[int]]) -> List[int]: |
| 36 | + indices = {1: [], 2: [], 3:[]} |
| 37 | + for i, c in enumerate(colors) : |
| 38 | + indices[c].append(i) |
| 39 | + |
| 40 | + return [ |
| 41 | + 0 if colors[i] == c else self._bin_search_closest(indices[c], i) |
| 42 | + for i, c in queries |
| 43 | + ] |
| 44 | + |
| 45 | + def _bin_search_closest(self, arr: List[int], target_indx: int) -> int : |
| 46 | + if not arr : |
| 47 | + return -1 |
| 48 | + l, r = 0, len(arr) - 1 |
| 49 | + |
| 50 | + while l < r : |
| 51 | + mid = (l + r) // 2 |
| 52 | + mid_val = arr[mid] |
| 53 | + if mid_val == target_indx : |
| 54 | + return 0 |
| 55 | + if mid_val > target_indx : |
| 56 | + r = mid - 1 |
| 57 | + continue |
| 58 | + l = mid + 1 |
| 59 | + |
| 60 | + # Fuzzy bound so check +/- 1 index to see if it's an approximation |
| 61 | + return min(abs(target_indx - x) for x in arr[max(0, l - 1):min(len(arr), r + 2)]) |
| 62 | +``` |
| 63 | + |
0 commit comments