Skip to main content
Back to problems
#6
Medium Algorithms

Zigzag conversion

String
53.6% acceptance
Jan 12, 2026
9265
15858
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: string convert(string s, int numRows);

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn convert(s: String, num_rows: i32) -> String {
    // Edge case: if num_rows is 1 or s is too short, return original string
    if num_rows == 1 || num_rows >= s.len() as i32 {
      return s;
    }
    
    // Create a vector of strings for each row
    let mut rows: Vec<String> = vec![String::new(); num_rows as usize];
    
    let mut current_row = 0;
    let mut going_down = false;
    
    // Iterate through each character in the string
    for ch in s.chars() {
      rows[current_row].push(ch);
      
      // Change direction when we reach the first or last row
      if current_row == 0 || current_row == num_rows as usize - 1 {
        going_down = !going_down;
      }
      
      // Move to the next row
      if going_down {
        current_row += 1;
      } else {
        current_row -= 1;
      }
    }
    
    // Concatenate all rows
    rows.into_iter().collect()
  }
}