coding-interview|August 27, 2019|2 min read

Zigzag Pattern String Conversion - Leet Code Solution

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();
	}
}

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

Claude Code Skills — Build a Better Engineering Workflow with AI-Powered Code Reviews, Security Scans, and More

Claude Code Skills — Build a Better Engineering Workflow with AI-Powered Code Reviews, Security Scans, and More

Most developers use Claude Code like a search engine — ask a question, get an…

Building an AI Voicebot for Visitor Check-In — A Practical Guide to Handling the Messy Parts

Building an AI Voicebot for Visitor Check-In — A Practical Guide to Handling the Messy Parts

Every office lobby has the same problem: a visitor walks in, nobody’s at the…

Server Security Best Practices — Complete Hardening Guide for Production Systems

Server Security Best Practices — Complete Hardening Guide for Production Systems

Every breach post-mortem tells the same story: an unpatched service, a…

Staff Engineer Study Plan for MAANG Interviews — The Complete 12-Week Roadmap

Staff Engineer Study Plan for MAANG Interviews — The Complete 12-Week Roadmap

If you’re a Senior Engineer (L5) preparing for Staff (L6+) roles at MAANG…

XSS and CSRF Explained — The Complete Guide with Real Attack Examples and Defenses

XSS and CSRF Explained — The Complete Guide with Real Attack Examples and Defenses

XSS and CSRF have been in the OWASP Top 10 for over a decade. They’re among the…

OWASP Top 10 (2021) — Every Vulnerability Explained with Code

OWASP Top 10 (2021) — Every Vulnerability Explained with Code

The OWASP Top 10 is the industry standard for web application security risks. If…