Zigzag Pattern String Conversion - Leet Code Solution

Gorav Singal

August 27, 2019

TL;DR

Simulate the zigzag by maintaining a list of StringBuffers (one per row) and a direction flag. Toggle direction at top/bottom boundaries, then concatenate all rows.

Zigzag Pattern String Conversion - Leet Code Solution

Problem Statement

The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

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

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

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

Solution

If you look the pattern, its going in two directions:

  • Top to bottom straight
  • Bottom to top with one incremented index

You need one flag to indicate whether you are going downward or going upward.

Algorithm

  • Maintain a flag to indicate whether you are going upward or downward. Reset boundaries are on 0-index and length-1 index.
  • Toggle the flag on reaching boundaries (top most, or bottom most)
  • Maintain a List of string(StringBuffer in Java). List length is equal to the number of rows asked.
  • Maintain a variable which will tell you in which stringbuffer(row num) to add the current character

Code

public class Q6_ZigZagConversion {
	private String str;
	
	public Q6_ZigZagConversion(String str) {
		this.str = str;
	}
	
	public String conversion(int numRows) {
		int l = this.str.length();
		List<StringBuffer> zigzag = new ArrayList<StringBuffer>();
		for (int i=0; i<numRows; i++) {
			zigzag.add(new StringBuffer());
		}
		
		boolean comingFromTop = true;
		int zig = 0;
		for (int i=0; i<l; i++) {
			zigzag.get(zig).append(this.str.charAt(i));
			
			if (zig == numRows-1) {
				comingFromTop = false;
			}
			else if (zig == 0) {
				comingFromTop = true;
			}
			zig = comingFromTop ? zig + 1 : zig - 1;
			zig = zig % numRows;
		}
		
		StringBuffer sb = new StringBuffer();
		for (int i=0; i<numRows; i++) {
			sb.append(zigzag.get(i));
		}
		
		return sb.toString();
	}
}
Share

Related Posts

Leetcode Solution - Best Time to Buy and Sell Stock

Leetcode Solution - Best Time to Buy and Sell Stock

Problem Statement You are given an array prices where prices[i] is the price of…

Binary Tree - Level Order Traversal

Binary Tree - Level Order Traversal

Problem Statement Given a Binary tree, print out nodes in level order traversal…

Four Sum - Leet Code Solution

Four Sum - Leet Code Solution

Problem Statement Given an array nums of n integers and an integer target, are…

Leetcode - Rearrange Spaces Between Words

Leetcode - Rearrange Spaces Between Words

Problem Statement You are given a string text of words that are placed among…

Leetcode - Maximum Non Negative Product in a Matrix

Leetcode - Maximum Non Negative Product in a Matrix

Problem Statement You are given a rows x cols matrix grid. Initially, you are…

Leetcode - Split a String Into the Max Number of Unique Substrings

Leetcode - Split a String Into the Max Number of Unique Substrings

Problem Statement Given a string s, return the maximum number of unique…

Latest Posts

AI Video Generation in 2025 — Models, Costs, and How to Build a Cost-Effective Pipeline

AI Video Generation in 2025 — Models, Costs, and How to Build a Cost-Effective Pipeline

AI video generation went from “cool demo” to “usable in production” in 2024-202…

AI Models in 2025 — Cost, Capabilities, and Which One to Use

AI Models in 2025 — Cost, Capabilities, and Which One to Use

Choosing the right AI model is one of the most impactful decisions you’ll make…

AI Image Generation in 2025 — Models, Costs, and How to Optimize Spend

AI Image Generation in 2025 — Models, Costs, and How to Optimize Spend

Generating one image with AI costs between $0.002 and $0.12. That might sound…

AI Coding Assistants in 2025 — Every Tool Compared, and Which One to Actually Use

AI Coding Assistants in 2025 — Every Tool Compared, and Which One to Actually Use

Two years ago, AI coding meant one thing: GitHub Copilot autocompleting your…

AI Agents Demystified — It's Just Automation With a Better Brain

AI Agents Demystified — It's Just Automation With a Better Brain

Let’s cut through the noise. If you read Twitter or LinkedIn, you’d think “AI…

Security Ticketing and Incident Response

Security Ticketing and Incident Response

The worst time to figure out your incident response process is during an…