Decode the Slanted Ciphertext

medium string matrix simulation

Problem

An original string was encoded with a slanted transposition cipher: it was written diagonally (top-left to bottom-right) into a matrix with a fixed number of rows, empty cells padded with spaces, then read out row-by-row to form encodedText. Given encodedText and rows, recover the original string. The original has no trailing spaces, and the answer is unique.

InputencodedText = "ch ie pr", rows = 3
Output"cipher"
The 3×4 matrix reads "cipher" along its diagonals.
InputencodedText = "coding", rows = 1
Output"coding"
With one row the matrix is a single line, so the text is unchanged.

def decode_ciphertext(encoded_text, rows):
    n = len(encoded_text)
    cols = n // rows
    result = []
    for start in range(cols):
        r, c = 0, start
        while r < rows and c < cols:
            result.append(encoded_text[r * cols + c])
            r += 1
            c += 1
    return "".join(result).rstrip()
function decodeCiphertext(encodedText, rows) {
  const n = encodedText.length;
  const cols = Math.floor(n / rows);
  let result = "";
  for (let start = 0; start < cols; start++) {
    let r = 0, c = start;
    while (r < rows && c < cols) {
      result += encodedText[r * cols + c];
      r++;
      c++;
    }
  }
  return result.replace(/\s+$/, "");
}
String decodeCiphertext(String encodedText, int rows) {
    int n = encodedText.length();
    int cols = n / rows;
    StringBuilder result = new StringBuilder();
    for (int start = 0; start < cols; start++) {
        int r = 0, c = start;
        while (r < rows && c < cols) {
            result.append(encodedText.charAt(r * cols + c));
            r++;
            c++;
        }
    }
    return result.toString().replaceAll("\\s+$", "");
}
string decodeCiphertext(string encodedText, int rows) {
    int n = encodedText.size();
    int cols = n / rows;
    string result;
    for (int start = 0; start < cols; start++) {
        int r = 0, c = start;
        while (r < rows && c < cols) {
            result += encodedText[r * cols + c];
            r++;
            c++;
        }
    }
    while (!result.empty() && result.back() == ' ') result.pop_back();
    return result;
}
Time: O(n) Space: O(n)