- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 57 lines of Python from the credited upstream file 2257.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def countUnguarded(3 self,4 m: int,5 n: int,6 guards: list[list[int]],7 walls: list[list[int]],8 ) -> int:9 ans = 010 grid = [[0] * n for _ in range(m)]11 left = [[0] * n for _ in range(m)]12 right = [[0] * n for _ in range(m)]13 up = [[0] * n for _ in range(m)]14 down = [[0] * n for _ in range(m)]15 16 for row, col in guards:17 grid[row][col] = 'G'18 19 for row, col in walls:20 grid[row][col] = 'W'21 22 for i in range(m):23 lastCell = 024 for j in range(n):25 if grid[i][j] == 'G' or grid[i][j] == 'W':26 lastCell = grid[i][j]27 else:28 left[i][j] = lastCell29 lastCell = 030 for j in range(n - 1, -1, -1):31 if grid[i][j] == 'G' or grid[i][j] == 'W':32 lastCell = grid[i][j]33 else:34 right[i][j] = lastCell35 36 for j in range(n):37 lastCell = 038 for i in range(m):39 if grid[i][j] == 'G' or grid[i][j] == 'W':40 lastCell = grid[i][j]41 else:42 up[i][j] = lastCell43 lastCell = 044 for i in range(m - 1, -1, -1):45 if grid[i][j] == 'G' or grid[i][j] == 'W':46 lastCell = grid[i][j]47 else:48 down[i][j] = lastCell49 50 for i in range(m):51 for j in range(n):52 if (grid[i][j] == 0 and left[i][j] != 'G' and right[i][j] != 'G' and53 up[i][j] != 'G' and down[i][j] != 'G'):54 ans += 155 56 return ans57