Saturday, January 4, 2020

Leetcode solution 6: ZigZag Conversion


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:
string convert(string s, int numRows);
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
 Problem link

Video Tutorial

You can find the detailed video tutorial here

Thought Process

It's a very good implementation problem, by simply simulating each character in the string to each row, it would take extra O(N) space to hold up the array where N is the string size. However, there is definitely a difference between a good and poor implementation.

There is also a math formula we can use, please see attached pdf for solutions.

Solutions

Simulation poor implementation

Time Complexity: O(N) where N is the string size
Space Complexity: O(N) since we used an extra array to store each character in the string

Simulation good implementation

Time Complexity: O(N) where N is the string size
Space Complexity: O(N) since we used an extra array to store each character in the string

References

No comments:

Post a Comment