Python3 - Optimized BFS Algorithm
\n# Code\n\nfrom bisect import bisect_left, bisect_right\nfrom collections import deque\n\nclass Solution:\n    def minReverseOperations(self, n, p, banned_vals
\n# Code\n```\nfrom bisect import bisect_left, bisect_right\nfrom collections import deque\n\nclass Solution:\n    def minReverseOperations(self, n, p, banned_vals, K):\n        remaining = [[], []]\n        banned = set(banned_vals)\n        for u in range(n):\n            if u != p and u not in banned:\n                remaining[u & 1].append(u)\n\n        for i in range(2):\n            remaining[i].sort()\n\n        queue = deque([p])\n        dist = [-1] * n\n        dist[p] = 0\n        while queue:\n            node = queue.popleft()\n            lo = max(node - K + 1, 0)\n            lo = 2 * lo + K - 1 - node\n            hi = min(node + K - 1, n - 1) - (K - 1)\n            hi = 2 * hi + K - 1 - node\n\n            idx_lo = bisect_left(remaining[lo % 2], lo)\n            idx_hi = bisect_right(remaining[lo % 2], hi)\n\n            for idx in range(idx_lo, idx_hi):\n                nei = remaining[lo % 2][idx]\n                queue.append(nei)\n                dist[nei] = dist[node] + 1\n\n            del remaining[lo % 2][idx_lo:idx_hi]\n        \n        return dist\n```
['Python3']