Fast Power Residue Plus Nearest-Source Grid Map
Trees & GraphsAuto-graded · 18 test casesLast updated
Combine square-and-multiply modular exponentiation with a multi-source BFS that labels every grid cell with its distance to the nearest source cell.
Write a single function that answers two unrelated questions and returns both answers together.
Task A: Power residue
Given integers base, exp and mod, compute (base ^ exp) mod mod.
expmay be as large as 10^18, so repeated multiplicationexptimes is far too slow. Your approach should take time proportional to the number of bits inexp.modis a positive integer, at most 10^9 + 7.- When
expis0, the answer is1 mod mod. In particular, whenmodis1the answer is always0. - A negative
baseshould be treated as its non-negative residue modulomod.
Task B: Distance to the nearest source
You are given a rectangular grid grid of 0s and 1s. A cell containing 1 is a source; a cell containing 0 is empty. Movement is allowed one step at a time to the four orthogonal neighbours (up, down, left, right), and there are no obstacles.
Produce a grid of the same shape in which each cell holds the minimum number of steps needed to reach any source starting from that cell.
- A source cell has distance
0. - If the grid contains no source at all, every cell gets the value
-1. - If the grid is empty (no rows), the distance grid is an empty list.
Return value
Return a dictionary with exactly two keys:
"power": the integer result of Task A."distances": the list of lists produced by Task B.
Constraints
0 <= exp <= 10^181 <= mod <= 10^9 + 7baseis an integer (it may be negative or larger thanmod).- The grid has at most 500 rows and 500 columns.
- Every grid entry is
0or1. - The grid may contain no sources, or consist only of sources.
Examples
Example 1
Input: power_and_nearest_source(2, 10, 1000, [[0, 0, 0], [0, 1, 0], [0, 0, 0]])
Output: {'power': 24, 'distances': [[2, 1, 2], [1, 0, 1], [2, 1, 2]]}
Example 2
Input: power_and_nearest_source(7, 0, 13, [[1, 0], [0, 1]])
Output: {'power': 1, 'distances': [[0, 1], [1, 0]]}
Example 3
Input: power_and_nearest_source(123, 1000000000000000000, 1, [[0, 0], [0, 0]])
Output: {'power': 0, 'distances': [[-1, -1], [-1, -1]]}
Hints
Hint 1
For the power part, inspect the bits of the exponent: square the running base at every step and multiply it into the answer only when the current bit is 1, reducing modulo `mod` each time.
Hint 2
Start the answer as `1 % mod` rather than `1` so that `mod = 1` and `exp = 0` need no special handling.
Hint 3
For the grid, do not search from each source separately. Put all sources into one queue at distance 0 and expand outward layer by layer; the first time a cell is reached gives its minimum distance.
Hint 4
Use `-1` in the distance grid as the marker for 'not reached yet', and set a cell's value when you enqueue it so it is never queued twice.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The two tasks are independent, so we solve each with its standard technique.
Task A: square-and-multiply
Write exp in binary. Then base^exp is the product of base^(2^i) over every bit position i where exp has a 1. We keep two values:
factor, which afterisquarings equalsbase^(2^i) mod mod;result, which accumulates the product of the factors for the set bits.
At each step, if the lowest bit of the remaining exponent is 1 we multiply result by factor; then we square factor and shift the exponent right. Every product is reduced modulo mod, which is valid because modular reduction commutes with multiplication.
Starting result at 1 % mod handles exp = 0 (answer 1 mod mod) and mod = 1 (answer 0). Reducing base % mod first handles negative or oversized bases, since Python's % returns a non-negative value for a positive modulus.
Task B: multi-source BFS
With no obstacles, the shortest path between two cells is their Manhattan distance, and we need the distance to the closest source. Running a separate search per source would be far too slow. Instead:
- Create a distance grid filled with
-1, which also serves as the "unvisited" marker. - Set every source to
0and push all of them onto one queue. - Pop cells in order; for each unvisited in-bounds neighbour, set its distance to the current distance plus one and enqueue it.
BFS handles cells in non-decreasing order of distance. Since all sources start at distance 0, a cell is first reached in the layer equal to its distance to the closest source, and it is never changed afterwards, so that value is the minimum. If there are no sources, the queue starts empty and every cell remains -1. An empty grid yields an empty list.
Complexity
- Task A: O(log exp) time, O(1) space.
- Task B: O(m * n) time, since each cell is enqueued once and checks four neighbours; O(m * n) space for the output and queue.
Reference solution
from collections import deque
from typing import Dict, List
def power_and_nearest_source(base: int, exp: int, mod: int, grid: List[List[int]]) -> Dict[str, object]:
result = 1 % mod
factor = base % mod
e = exp
while e > 0:
if e & 1:
result = (result * factor) % mod
factor = (factor * factor) % mod
e >>= 1
if not grid:
distances = []
else:
rows = len(grid)
cols = len(grid[0])
distances = [[-1] * cols for _ in range(rows)]
queue = deque()
for r in range(rows):
for c in range(cols):
if grid[r][c] == 1:
distances[r][c] = 0
queue.append((r, c))
while queue:
r, c = queue.popleft()
nxt = distances[r][c] + 1
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and distances[nr][nc] == -1:
distances[nr][nc] = nxt
queue.append((nr, nc))
return {"power": result, "distances": distances}