New: 214 pattern programs with tested code in C, C++, Java and Python Explore patterns

Rail Fence Zig-Zag String Pattern

The rail fence zig-zag string pattern writes a word down and up across a few rows, like a fence, and then reads it off row by row. With three rows, PAYPALISHIRING becomes PAHNAPLSIIGYIR. It is LeetCode problem 6, “ZigZag Conversion”, and the rail fence cipher from cryptography.

Quick answer: Each letter at index k goes on a rail. The pattern repeats every 2(rows βˆ’ 1) letters; within one repeat, position pos = k % cycle is on rail pos going down and cycle βˆ’ pos coming back up. Draw the letters on their rails, then join the rails top to bottom.

This program is part of the Wave Patterns collection.

Table of contents8 sections
  1. Output
  2. How the rail fence zig-zag string pattern works
  3. Program in C
  4. Program in C++
  5. Program in Java
  6. Program in Python
  7. Time and space complexity
  8. Frequently asked questions

Rail Fence Zig-Zag String Pattern output

Output (3 rails, “PAYPALISHIRING”):

P   A   H   N
 A P L S I I G
  Y   I   R
PAHNAPLSIIGYIR
Rail Fence Zig-Zag String Pattern layout diagram, row by row (3 rails, "PAYPALISHIRING")
How each row of the rail fence zig-zag string pattern is built (3 rails, “PAYPALISHIRING”). Blue cells are printed characters; grey dots are spaces.

How the rail fence zig-zag string pattern works

Going down three rails and back up to the top takes four steps: rails 0, 1, 2, 1, then 0 again. So the rail of any letter depends only on its index modulo 4, or 2(rows βˆ’ 1) in general. The program places each letter in its own column on the right rail to draw the zig-zag, and at the same time adds it to that rail’s string. Printing the rail strings one after another gives the encoded word.

  1. Set cycle = 2(rows βˆ’ 1).
  2. For each index k, work out pos = k % cycle and the rail: pos if pos < rows, otherwise cycle βˆ’ pos.
  3. Put the letter in column k of its rail and also add it to that rail’s text.
  4. Print the rails as lines, then print the rail texts joined together.

Key takeaways

  • The rail pattern repeats every 2(rows βˆ’ 1) letters.
  • Going up the rails is the mirror of going down: cycle βˆ’ pos.
  • Joining the rails top to bottom gives the LeetCode answer.
  • With one rail the cycle would be 0, so treat rows = 1 as a special case.

Rail Fence Zig-Zag String Pattern in C

#include <stdio.h>
#include <string.h>

int main(void) {
    char s[] = "PAYPALISHIRING";
    int rows = 3;
    int len = strlen(s);
    int cycle = 2 * (rows - 1);                     /* down and back up again */

    for (int r = 0; r < rows; r++) {                /* draw the zig-zag */
        for (int k = 0; k < len; k++) {
            int pos = k % cycle;
            int rail = pos < rows ? pos : cycle - pos;
            printf("%c", rail == r ? s[k] : ' ');
        }
        printf("\n");
    }
    for (int r = 0; r < rows; r++)                  /* read it row by row */
        for (int k = 0; k < len; k++) {
            int pos = k % cycle;
            if ((pos < rows ? pos : cycle - pos) == r)
                printf("%c", s[k]);
        }
    printf("\n");
    return 0;
}

Rail Fence Zig-Zag String Pattern in C++

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
    string s = "PAYPALISHIRING";
    int rows = 3;
    int len = s.length();
    int cycle = 2 * (rows - 1);                     // down and back up again
    vector<string> lines(rows, string(len, ' '));
    vector<string> read(rows);

    for (int k = 0; k < len; k++) {
        int pos = k % cycle;
        int rail = pos < rows ? pos : cycle - pos;
        lines[rail][k] = s[k];
        read[rail] += s[k];
    }
    for (const string &line : lines)                // draw the zig-zag
        cout << line << endl;
    for (const string &part : read)                 // read it row by row
        cout << part;
    cout << endl;
    return 0;
}

Rail Fence Zig-Zag String Pattern in Java

public class RailFenceZigzagString {
    public static void main(String[] args) {
        String s = "PAYPALISHIRING";
        int rows = 3;
        int len = s.length();
        int cycle = 2 * (rows - 1);                     // down and back up again
        char[][] lines = new char[rows][len];
        StringBuilder[] read = new StringBuilder[rows];
        for (int r = 0; r < rows; r++) {
            java.util.Arrays.fill(lines[r], ' ');
            read[r] = new StringBuilder();
        }

        for (int k = 0; k < len; k++) {
            int pos = k % cycle;
            int rail = pos < rows ? pos : cycle - pos;
            lines[rail][k] = s.charAt(k);
            read[rail].append(s.charAt(k));
        }
        for (char[] line : lines)                       // draw the zig-zag
            System.out.println(new String(line));
        StringBuilder result = new StringBuilder();     // read it row by row
        for (StringBuilder part : read)
            result.append(part);
        System.out.println(result);
    }
}

Rail Fence Zig-Zag String Pattern in Python

s = "PAYPALISHIRING"
rows = 3
cycle = 2 * (rows - 1)                          # down and back up again
lines = [[" "] * len(s) for _ in range(rows)]
read = [""] * rows

for k, ch in enumerate(s):
    pos = k % cycle
    rail = pos if pos < rows else cycle - pos
    lines[rail][k] = ch
    read[rail] += ch
for line in lines:                              # draw the zig-zag
    print("".join(line))
print("".join(read))                            # read it row by row

Time and space complexity

Each letter is placed once, so the program runs in O(len) time for a word of length len. Drawing the fence uses O(rows Γ— len) memory.

Frequently asked questions

What happens with rows = 1?

The cycle length becomes 0 and the remainder would divide by zero. Handle it first: with one rail, the output is the word itself.

Is this really used for encryption?

The rail fence cipher is a classic schoolbook cipher. It is easy to break, but it shows how changing the order of letters can hide a message.

How do I decode it again?

Work out how many letters each rail gets, cut the encoded text into those pieces, then read them back in zig-zag order.

This tutorial was drafted with AI assistance. Spotted a mistake? Tell us and we fix it. Read our editorial policy.

Quick check: can you predict the output?

Answer from the code, then check. Every answer comes from the real output above.

Pattern 6 of 12 in Wave Patterns

 

Still stuck? Ask AI to explain this code

Opens your favourite AI with this page, ready to explain every loop step by step.

Authored by

Ghanendra Yadav runs Pattern Programs from Bangalore, India. The site started in 2020 to help students practise loops and logic through pattern programs in C, C++, Java and Python. Every program published here is compiled and run before it goes live, and the output shown is the real output.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.