Decode the Slanted Ciphertext — LeetCode 2075 Python Solution

MediumStringSimulation
Problem
#2075
Pattern
Hash Map
Reading time
2 min

The problem

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.

Example

Input
encodedText = "ch ie pr", rows = 3
Output
"cipher"
Explanation
This is the same example described in the problem description.

Python solution

Python
class Solution:
    def decodeCiphertext(self, encodedText: str, rows: int) -> str:
        ans = []
        cols = len(encodedText) // rows
        for j in range(cols):
            x, y = 0, j
            while x < rows and y < cols:
                ans.append(encodedText[x * cols + y])
                x, y = x + 1, y + 1
        return ''.join(ans).rstrip()

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the length of the string encodedText auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2075. Decode the Slanted Ciphertext is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2075. Decode the Slanted Ciphertext?
LeetCode 2075. Decode the Slanted Ciphertext is rated Medium on LeetCode.
What is the time complexity of LeetCode 2075. Decode the Slanted Ciphertext?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2075. Decode the Slanted Ciphertext?
The Python solution on this page uses O(n), where n is the length of the string encodedText auxiliary space.
What topics does LeetCode 2075. Decode the Slanted Ciphertext cover?
LeetCode 2075. Decode the Slanted Ciphertext is tagged String and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview