Zigzag Conversion LeetCode Solution

Last updated on July 15th, 2024 at 12:54 am

Here, We see Zigzag Conversion LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.

List of all LeetCode Solution

Topics

String

Companies

Level of Question

Medium

Zigzag Conversion LeetCode Solution

Zigzag Conversion LeetCode 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"
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

Example 3:
Input: s = "A", numRows = 1
Output: "A"

1. Zigzag Conversion Leetcode Solution C++

class Solution {
public:
    string convert(string s, int numRows) {

        if (numRows == 1) return s;

        string ret;
        int n = s.size();
        int cycleLen = 2 * numRows - 2;

        for (int i = 0; i < numRows; i++) {
            for (int j = 0; j + i < n; j += cycleLen) {
                ret += s[j + i];
                if (i != 0 && i != numRows - 1 && j + cycleLen - i < n)
                    ret += s[j + cycleLen - i];
            }
        }
        return ret;
    }
};

1.1 Explanation

  1. Edge Case: If numRows is 1, return the original string s.
  2. Initialize: Create an empty string ret to store the result. Calculate cycleLen, which is the length of one cycle in the zigzag pattern.
  3. Nested Loops:
    • Outer loop: Iterate through each row from 0 to numRows – 1.
    • Inner loop: Iterate through the string s in steps of cycleLen.
    • Add characters to ret from the main column (s[j + i]) and the diagonal column (s[j + cycleLen – i]) if applicable.

1.2 Time Complexity

  • O(n).

1.3 Space Complexity

  • O(n).

2. Zigzag Conversion Leetcode Solution Java

class Solution {
    public String convert(String s, int numRows) {

        if (numRows == 1) return s;

        StringBuilder ret = new StringBuilder();
        int n = s.length();
        int cycleLen = 2 * numRows - 2;

        for (int i = 0; i < numRows; i++) {
            for (int j = 0; j + i < n; j += cycleLen) {
                ret.append(s.charAt(j + i));
                if (i != 0 && i != numRows - 1 && j + cycleLen - i < n)
                    ret.append(s.charAt(j + cycleLen - i));
            }
        }
        return ret.toString();
    }
}

2.1 Explanation

  1. Edge Case: If numRows is 1, return the original string s.
  2. Initialize: Create a StringBuilder ret to store the result. Calculate cycleLen, which is the length of one cycle in the zigzag pattern.
  3. Nested Loops:
    • Outer loop: Iterate through each row from 0 to numRows – 1.
    • Inner loop: Iterate through the string s in steps of cycleLen.
    • Add characters to ret from the main column (s.charAt(j + i)) and the diagonal column (s.charAt(j + cycleLen – i)) if applicable.

2.2 Time Complexity

  • O(n).

2.3 Space Complexity

  • O(n).

3. Zigzag Conversion Leetcode Solution JavaScript

var convert = function(s, numRows) {
    if (numRows === 1 || s.length < numRows) return s;

    let rows = [];
    let converted = '';
    let reverse = false;
    let count = 0;

    for (let i = 0; i < numRows; i++) rows[i] = [];
    for (let i = 0; i < s.length; i++) {
        rows[count].push(s[i]);
        reverse ? count-- : count++;
        if (count === numRows - 1 || count === 0) reverse = !reverse;
    }
    return rows.reduce((converted, cur) => converted + cur.join(''), '');
};

3.1 Explanation

  1. Edge Case: If numRows is 1 or the length of s is less than numRows, return the original string s.
  2. Initialize: Create an array rows to store characters for each row. Create a variable converted to store the final result. Initialize reverse to handle the direction change in the zigzag pattern and count to track the current row.
  3. Fill Rows:
    • Iterate through each character in the string s.
    • Push characters into the corresponding row in rows.
    • Change direction (reverse) when reaching the top or bottom row.
  4. Join Rows: Combine all rows into the final result string using reduce.

3.2 Time Complexity

  • O(n).

3.3 Space Complexity

  • O(n).

4. Zigzag Conversion Leetcode Solution Python

class Solution:
    def convert(self, s: str, numRows: int) -&gt; str:
        if numRows == 1:
            return s
            
        row_arr = [""] * numRows
        row_idx = 1
        going_up = True

        for ch in s:
            row_arr[row_idx-1] += ch
            if row_idx == numRows:
                going_up = False
            elif row_idx == 1:
                going_up = True
            
            if going_up:
                row_idx += 1
            else:
                row_idx -= 1
        
        return "".join(row_arr)

4.1 Explanation

  1. Edge Case: If numRows is 1, return the original string s.
  2. Initialize: Create a list row_arr to store strings for each row. Initialize row_idx to track the current row and going_up to handle the direction change in the zigzag pattern.
  3. Fill Rows:
    • Iterate through each character in the string s.
    • Add characters to the corresponding row in row_arr.
    • Change direction (going_up) when reaching the top or bottom row.
  4. Join Rows: Combine all rows into the final result string using “”.join.

4.2 Time Complexity

  • O(n).

4.3 Space Complexity

  • O(n).
Scroll to Top