Codepath

Reinforce the Kingdom Walls

Unit 11 Session 1 Advanced (Click for link to problem statements)

Unit 11 Session 2 Standard (Click for link to problem statements)

Problem Highlights

  • 💡 Difficulty: Medium
  • Time to complete: 45 mins
  • 🛠️ Topics: Grid Traversal, Depth-First Search (DFS), Graph Representation

1: U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Established a set (2-3) of test cases to verify their own solution later.
  • Established a set (1-2) of edge cases to verify their solution handles complexities.
  • Have fully understood the problem and have no clarifying questions.
  • Have you verified any Time/Space Constraints for this problem?
  • How do we define the ""border"" of a fortified section?
    • The border consists of squares that are adjacent to a square with a different defensive strength or lie on the outer edges of the kingdom.
  • Can two sections have the same defensive strength but be disconnected?
    • Yes, two sections can have the same defensive strength but be separate regions.
HAPPY CASE
Input: kingdom_grid = [
    [1, 1, 1, 2],
    [1, 3, 1, 2],
    [1, 1, 1, 2]
], row = 1, col = 1, new_strength = 4
Output: [
    [1, 1, 1, 2],
    [1, 4, 1, 2],
    [1, 1, 1, 2]
]
Explanation: The square (1, 1) is a border square, and it gets updated to the new strength.

EDGE CASE
Input: kingdom_grid = [
    [1, 1],
    [1, 1]
], row = 0, col = 0, new_strength = 2
Output: [
    [2, 2],
    [2, 2]
]
Explanation: Since the entire section is a border, the whole section gets updated.

2: M-atch

Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.

For Grid Traversal problems, we want to consider the following approaches:

  • Depth-First Search (DFS): DFS can be used to explore all the squares in the fortified section that have the same defensive strength.
  • Breadth-First Search (BFS): BFS could also be used, but DFS is often simpler for recursive exploration.
  • Graph Representation: The grid can be treated as a graph where each square is a node, and edges exist between adjacent squares with the same strength.

3: P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Use DFS to explore all the squares in the fortified section starting from the given (row, col). Track all the squares that form the border of the section. Once all border squares are identified, update their strength to new_strength.

1) Define a helper function `next_moves` to get valid neighboring squares.
2) Define a helper function `is_border` to check if a square is a border square.
3) Perform DFS to explore all squares in the section and identify the border squares.
4) Update the strength of all identified border squares to `new_strength`.
5) Return the updated kingdom grid.

⚠️ Common Mistakes

  • Forgetting to check grid boundaries during DFS.
  • Failing to correctly identify border squares, especially those on the edges of the grid.

4: I-mplement

Implement the code to solve the algorithm.

# Helper function to find valid neighboring squares
def next_moves(kingdom_grid, row, col):
    moves = [
        (row + 1, col),  # down
        (row - 1, col),  # up
        (row, col + 1),  # right
        (row, col - 1)   # left
    ]
    
    possible = []
    for r, c in moves:
        if 0 <= r < len(kingdom_grid) and 0 <= c < len(kingdom_grid[0]):
            possible.append((r, c))
    
    return possible

# Function to check if a square is on the border
def is_border(kingdom_grid, row, col, strength):
    for r, c in next_moves(kingdom_grid, row, col):
        if kingdom_grid[r][c] != strength:
            return True
    # If the square is on the outer edge, it's a border
    if row == 0 or row == len(kingdom_grid) - 1 or col == 0 or col == len(kingdom_grid[0]) - 1:
        return True
    return False

# Main function to reinforce walls
def reinforce_walls(kingdom_grid, row, col, new_strength):
    initial_strength = kingdom_grid[row][col]
    if initial_strength == new_strength:
        return kingdom_grid  # No need to update if the new strength is the same as the current strength
    
    visited = set()
    border_squares = set()
    
    # DFS to find all squares in the section
    def dfs(r, c):
        visited.add((r, c))
        if is_border(kingdom_grid, r, c, initial_strength):
            border_squares.add((r, c))
        
        for nr, nc in next_moves(kingdom_grid, r, c):
            if (nr, nc) not in visited and kingdom_grid[nr][nc] == initial_strength:
                dfs(nr, nc)
    
    # Start DFS from the given row, col
    dfs(row, col)
    
    # Update the border squares with the new strength
    for r, c in border_squares:
        kingdom_grid[r][c] = new_strength
    
    return kingdom_grid

5: R-eview

Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.

Example 1:

  • Input: kingdom_grid = [ [1, 1, 1, 2], [1, 3, 1, 2], [1, 1, 1, 2] ], row = 1, col = 1, new_strength = 4
  • Expected Output: [ [1, 1, 1, 2], [1, 4, 1, 2], [1, 1, 1, 2] ]
  • Watchlist:
    • Ensure that DFS correctly explores all squares in the section.
    • Verify that border squares are correctly identified and updated.

6: E-valuate

Evaluate the performance of your algorithm and state any strong/weak or future potential work.

Assume m is the number of rows and n is the number of columns in the grid.

  • Time Complexity: O(m * n) because each square is visited once during DFS.
  • Space Complexity: O(m * n) due to the visited set and DFS stack.
Fork me on GitHub