#2075

Decode the Slanted Ciphertext

Medium
StringSimulationMatrix ManipulationZigzag Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution builds the matrix directly from the encoded text and reconstructs the original text in a single pass, avoiding unnecessary iterations. This approach is efficient and straightforward.

⚙️

Algorithm

4 steps
  1. 1Step 1: Calculate the number of columns needed using the length of encodedText and the number of rows.
  2. 2Step 2: Create a 2D matrix to hold the characters.
  3. 3Step 3: Fill the matrix in a zigzag pattern using a single loop.
  4. 4Step 4: Read the matrix row-wise to reconstruct the original text.
solution.py21 lines
1# Full working Python code
2
3def decodeSlantedCiphertext(encodedText: str, rows: int) -> str:
4    n = len(encodedText)
5    cols = (n + rows - 1) // rows
6    matrix = [[' ' for _ in range(cols)] for _ in range(rows)]
7    index = 0
8
9    # Fill the matrix in a zigzag manner
10    for diag in range(rows + cols - 1):
11        for r in range(rows):
12            c = diag - r
13            if c >= 0 and c < cols:
14                if index < n:
15                    matrix[r][c] = encodedText[index]
16                    index += 1
17
18    # Read the matrix row-wise to form the original text
19    originalText = ''.join(''.join(row) for row in matrix).rstrip()
20    return originalText
21

Complexity note: The time complexity is O(n) because we traverse the encoded text once to fill the matrix and then read it. The space complexity is O(n) due to the storage of the matrix.

  • 1Understanding how to fill a matrix in a zigzag pattern is crucial for solving this problem.
  • 2Recognizing the relationship between the number of rows, columns, and the length of the encoded text helps in efficient reconstruction.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.