Skip to main content
Back to problems
#2075
Medium Algorithms

Decode the slanted ciphertext

String Simulation
50.3% acceptance
Feb 25, 2026
269
69
A string originalText is encoded using a slanted transposition cipher to a string encodedText with the help of a matrix having a fixed number of rows rows. originalText is placed first in a top-left to bottom-right manner. encodedText is then formed by appending all characters of the matrix in a row-wise fashion. For example, if originalText = "cipher" and rows = 3, then encodedText = "ch ie pr". Given the encoded string encodedText and number of rows rows, return the original string originalText. Note: originalText does not have any trailing spaces ' '. The test cases are generated such that there is only one possible originalText.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn decode_ciphertext(encoded_text: String, rows: i32) -> String {
    if rows == 1 {
      return encoded_text;
    }
    let rows = rows as usize;
    let enc: Vec<char> = encoded_text.chars().collect();
    let len = enc.len();
    if len == 0 {
      return String::new();
    }
    let cols = len / rows;
    // Read diagonals: diagonal starting at column c reads (r, c+r) for r=0..rows
    let mut result = Vec::new();
    for c in 0..cols {
      for r in 0..rows {
        let col = c + r;
        if col >= cols {
          break;
        }
        result.push(enc[r * cols + col]);
      }
    }
    // Trim trailing spaces
    while result.last() == Some(&' ') {
      result.pop();
    }
    result.into_iter().collect()
  }
}