Magicsheet logo

Decode the Slanted Ciphertext

Medium
48%
Updated 6/1/2025

Asked by 2 Companies

Decode the Slanted Ciphertext

What is this problem about?

The Decode the Slanted Ciphertext interview question presents a specific geometric encoding. You are given a ciphertext string and the number of rows it was written in. The original text was written row by row into a matrix, but it is read out diagonally (slanted) to produce the ciphertext. You need to reconstruct the original string. This Decode the Slanted Ciphertext coding problem is a test of coordinate calculation and string simulation.

Why is this asked in interviews?

Amazon and Grammarly use this to evaluate a candidate's ability to visualize 2D structures and map them to 1D strings. It requires calculating the number of columns from the string length and the number of rows, and then determining the correct indices to jump through the ciphertext. It tests mathematical indexing over complex data structures.

Algorithmic pattern used

This utilizes the String, Simulation interview pattern.

  1. Matrix Dimensions: Calculate cols = ciphertext.length() / rows.
  2. Diagonal Traversal: The original string's i-th character is found at some slanted position. Specifically, for each starting column c from 0 to cols-1, you read characters at (0, c), (1, c+1), (2, c+2)... until you hit a boundary.
  3. Index Mapping: Convert these (r, c) coordinates back to 1D indices: index = r * cols + c.
  4. Trimming: Remove trailing spaces from the final result.

Example explanation

ciphertext = "ch ie at", rows = 3. Total length 12, so cols = 12 / 3 = 4. Matrix:

c h _ _
_ i e _
_ _ a t
  1. Start at Col 0: (0,0) 'c', (1,1) 'i', (2,2) 'a'. String: "cia".
  2. Start at Col 1: (0,1) 'h', (1,2) 'e', (2,3) 't'. String: "ciahet".
  3. Start at Col 2: (0,2) ' ', (1,3) ' '. String: "ciahet ". Trailing spaces removed: "ciahet".

Common mistakes candidates make

  • Column calculation: Miscalculating the width of the matrix.
  • Boundary errors: Trying to read past the last column when following a diagonal.
  • Trailing spaces: Forgetting that only trailing spaces should be removed, while spaces in the middle of the original text must stay.

Interview preparation tip

For matrix simulation problems, always write down the relationship between the 2D coordinate (r, c) and the flat index i. For a matrix with W columns, i = r * W + c.

Similar Questions