Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Strings

Zigzag Conversion

Medium · Strings · Asked at Amazon, Microsoft, Adobe, Paytm

Write the string in a zigzag on k rows — down the rows, then diagonally back up, then down again — and print the rows read left to right, one after another. For PAYPALISHIRING with 3 rows:

P   A   H   N
A P L S I I G
Y   I   R

gives PAHNAPLSIIGYIR.

Input

First line: the string. Second line: k.

Output

The zigzag string.

Constraints

Walk through the string keeping the current row and direction; append each character to its row and flip direction at the top and bottom rows. With k = 1 the string is unchanged.

Example 1

Input

PAYPALISHIRING
3

Output

PAHNAPLSIIGYIR

Example 2

Input

PAYPALISHIRING
4

Output

PINALSIGYAHRPI

Hints

  1. You do not need the 2-D picture — only which row each character lands in.
  2. The row goes 0, 1, …, k − 1, k − 2, …, 1, 0, 1, … — bouncing between the top and bottom.

Approach

Keep k row buffers, the current row and a direction. For each character append it to its row; reverse the direction when you are on row 0 or row k − 1, then move one row. Finally join the rows. With k = 1 there is no bouncing, so return the string as it is (otherwise the direction logic would step out of range).

Complexity: O(n) time · O(n) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    string s;
    int k;
    cin >> s >> k;
    if (k == 1) {
        cout << s << "\n";
        return 0;
    }
    vector<string> rows(k);
    int row = 0, dir = 1;
    for (char c : s) {
        rows[row] += c;
        if (row == 0) dir = 1;
        else if (row == k - 1) dir = -1;
        row += dir;
    }
    string out;
    for (auto &x : rows) out += x;
    cout << out << "\n";
    return 0;
}

Python solution

import sys

s, k = sys.stdin.read().split()[:2]
k = int(k)
if k == 1:
    print(s)
else:
    rows = [[] for _ in range(k)]
    row, d = 0, 1
    for c in s:
        rows[row].append(c)
        if row == 0:
            d = 1
        elif row == k - 1:
            d = -1
        row += d
    print("".join("".join(x) for x in rows))

Java solution

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s = br.readLine().trim();
        int k = Integer.parseInt(br.readLine().trim());
        if (k == 1) {
            System.out.println(s);
            return;
        }
        StringBuilder[] rows = new StringBuilder[k];
        for (int i = 0; i < k; i++) rows[i] = new StringBuilder();
        int row = 0, dir = 1;
        for (char c : s.toCharArray()) {
            rows[row].append(c);
            if (row == 0) dir = 1;
            else if (row == k - 1) dir = -1;
            row += dir;
        }
        StringBuilder out = new StringBuilder();
        for (StringBuilder x : rows) out.append(x);
        System.out.println(out);
    }
}

Solve Zigzag Conversion online · All practice problems