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
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

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.
- Set
cycle = 2(rows β 1). - For each index
k, work outpos = k % cycleand the rail:posifpos < rows, otherwisecycle β pos. - Put the letter in column
kof its rail and also add it to that rail’s text. - 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 = 1as 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 rowTime 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.






