We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Length of Longest V-Shaped Diagonal Segment

Number: 3733

Difficulty: Hard

Paid? No

Companies: Visa


Problem Description

Given a 2D integer matrix called grid, where each element is one of 0, 1, or 2, we want to find the longest “V‐shaped” diagonal segment. A V-shaped diagonal segment is defined as follows:

  • It must start with a 1.
  • The subsequent elements must follow the repeating pattern: 2, 0, 2, 0, …
  • The segment travels in one of the four diagonal directions (top-left to bottom-right, bottom-right to top-left, top-right to bottom-left, or bottom-left to top-right) and, optionally, makes at most one 90-degree clockwise turn to another diagonal direction while maintaining the same sequence. Return the length of the longest valid V-shaped diagonal segment. If none exists, return 0.

Key Insights

  • The segment must be a contiguous path following a specific alternating sequence starting with 1.
  • Four possible initial diagonal directions exist; a valid segment may be entirely straight or contain one clockwise 90-degree turn.
  • At any point along the first diagonal leg (after starting at a cell with value 1), we can choose to make the turn. The new direction is determined by rotating the initial direction clockwise.
  • The expected value for each step in the sequence is determined by its index (first element must be 1, and for subsequent indices: odd index expects 2, even index expects 0).
  • A brute-force simulation from every valid starting cell in all 4 directions (and trying to turn at every possible position) works conceptually and can be optimized by dynamic programming or memoization if needed.

Space and Time Complexity

Time Complexity: O(n * m * L) in the worst-case, where L is the maximum possible length of the segment (diagonal traversal steps). In practice, L is bounded by min(n, m) so overall roughly O(n * m * min(n, m)). Space Complexity: O(1) additional space apart from the grid (or O(n*m) if memoization/precomputation is used).


Solution

We approach the problem by simulating the V-shaped segments from every cell that has the starting value 1. For each starting cell, we try each of the 4 diagonal directions.

  1. Follow the initial direction while checking if each value in the grid matches the expected sequence value (1, then alternating 2 and 0).
  2. For each step along this initial leg, attempt a turn (if not already turned) by computing the new “turned” direction – which is the clockwise rotation of the current initial direction – and simulate the rest of the segment.
  3. The expected sequence continues seamlessly, meaning that the next step after turning should match the next expected value.
  4. Throughout the simulation, update the maximum length found. By trying every possible valid starting cell, every initial direction, and every possible turn point along the way, we guarantee that we find the longest valid segment.

The key data structures are simple loop variables and indices; the algorithmic approach is simulation with an optional branch for the turn. Important tricks include:

  • Correctly computing the expected value based on the step index.
  • Maintaining boundaries and grid validity.
  • Handling the case where no turn is taken (a straight diagonal segment is valid).

Code Solutions

# Python solution for Length of Longest V-Shaped Diagonal Segment

def longestVShape(grid):
    n, m = len(grid), len(grid[0])
    # Define four diagonal directions
    directions = [(1, 1), (1, -1), (-1, -1), (-1, 1)]
    # Mapping for clockwise turn: (dr, dc) -> (new_dr, new_dc)
    cw_rotate = {
        (1, 1): (1, -1),
        (1, -1): (-1, -1),
        (-1, -1): (-1, 1),
        (-1, 1): (1, 1)
    }
    
    # Helper function to check if coordinate is inside grid
    def in_bounds(x, y):
        return 0 <= x < n and 0 <= y < m
    
    # Function to simulate a path starting from cell (x, y) in direction (dr, dc),
    # with expected sequence starting at given index.
    # Expected value at index 0: must be 1; afterwards: odd -> 2, even -> 0.
    def simulate(x, y, dr, dc, start_index):
        length = 0
        i = start_index
        while in_bounds(x, y):
            expected = 1 if i == 0 else (2 if i % 2 == 1 else 0)
            if grid[x][y] != expected:
                break
            length += 1
            x += dr
            y += dc
            i += 1
        return length  # how many cells of the sequence we collected
    
    best = 0
    # Iterate over every cell as potential starting cell
    for i in range(n):
        for j in range(m):
            if grid[i][j] != 1:
                continue  # must start with 1
            # Try every initial diagonal direction
            for dr, dc in directions:
                # Simulate straight segment along the direction, trying optional turn along the path.
                current_x, current_y = i, j
                current_step = 0  # sequence index; 0 expects to see value 1 already matching starting cell
                # We simulate the first leg step by step
                while in_bounds(current_x, current_y):
                    expected = 1 if current_step == 0 else (2 if current_step % 2 == 1 else 0)
                    if grid[current_x][current_y] != expected:
                        break
                    # Straight segment candidate (no turn taken)
                    best = max(best, current_step + 1)
                    
                    # Try to turn at this cell (allowed if current_step >= 0; turning at starting cell is allowed)
                    new_dr, new_dc = cw_rotate[(dr, dc)]
                    turn_x = current_x + new_dr
                    turn_y = current_y + new_dc
                    # Simulate second leg from the turning point.
                    if in_bounds(turn_x, turn_y):
                        # Next expected value is for index current_step+1.
                        additional = simulate(turn_x, turn_y, new_dr, new_dc, current_step + 1)
                        best = max(best, current_step + 1 + additional)
                    # Move to next cell in the initial direction
                    current_x += dr
                    current_y += dc
                    current_step += 1
    return best

# Example usage:
grid1 = [[2,2,1,2,2],
         [2,0,2,2,0],
         [2,0,1,1,0],
         [1,0,2,2,2],
         [2,0,0,2,2]]
print(longestVShape(grid1))  # Expected output: 5
← Back to All Questions