Skip to content

Improve Zig Zag conversion#13

Merged
jusexton merged 2 commits into
jusexton:mainfrom
ChocolateLoverRaj:better-zigzag-contribute
May 7, 2026
Merged

Improve Zig Zag conversion#13
jusexton merged 2 commits into
jusexton:mainfrom
ChocolateLoverRaj:better-zigzag-contribute

Conversation

@ChocolateLoverRaj
Copy link
Copy Markdown
Contributor

Single allocation, no reallocations

This takes advantage of each character always being 1 byte, which is guaranteed by the LeetCode constraints.

Instead of actually constructing a zigazag this code just finds the Math pattern behind every row to construct the final output.

Single allocation, no reallocations

This takes advantage of each character always being 1 byte, which is
guaranteed by the LeetCode constraints.
@jusexton
Copy link
Copy Markdown
Owner

Hey @ChocolateLoverRaj! Thanks for the allocation improvement. Once the linting issues are fixed it would also be nice to reuse the logic for the top and bottom rows. Something like this:

fn append(o: &mut String, bytes: &[u8], start: usize, step: usize) {
    let mut i = 0;
    while let Some(&c) = bytes.get(start + i * step) {
        o.push(c as char);
        i += 1;
    }
}

let num_rows = num_rows as usize;
let bytes = s.as_bytes();
let step = match num_rows {
    1 => 1,
    n => n * 2 - 2,
};
let mut o = String::with_capacity(s.len());

// Top row
append(&mut o, bytes, 0, step);

// Middle row

// Bottom row
if num_rows > 1 {
    append(&mut o, bytes, num_rows - 1, step);
}

@jusexton jusexton merged commit bd1012b into jusexton:main May 7, 2026
1 check passed
@jusexton
Copy link
Copy Markdown
Owner

jusexton commented May 7, 2026

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants