~/coding-interview/leetcode-zigzag-pattern.md

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

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

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

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…