Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Program to convert a string to zigzag string of line count k in python
The zigzag string conversion arranges characters in a zigzag pattern across k lines. Starting from the top line, we move diagonally down until reaching the bottom (kth line), then move diagonally up back to the top, and repeat this pattern.
For example, if the input is s = "ilovepythonprogramming" and k = 5, the zigzag pattern looks like this:
Algorithm Steps
The algorithm works as follows ?
- Create a dictionary to store characters for each line
- Use a counter to track current line and delta for direction
- For each character, add it to the current line with its position
- Change direction when reaching top (line 0) or bottom (line k-1)
- Reconstruct the zigzag pattern by placing characters at their original positions
Implementation
from collections import defaultdict
class Solution:
def solve(self, s, k):
if k == 1:
return s
line = defaultdict(list)
cnt = 0
delta = 1
for i, c in enumerate(s):
line[cnt].append((c, i))
cnt += delta
if cnt == k:
delta = -1
cnt = k - 2
if cnt == 0:
delta = 1
ans = []
for i, c in line.items():
prefix = [" "] * len(s)
for x, y in c:
prefix[y] = x
ans.append("".join(prefix))
return "\n".join(ans)
# Test the solution
ob = Solution()
s = "ilovepythonprogramming"
k = 5
result = ob.solve(s, k)
print(result)
Output
i h r
l t o a
o y n o
v p p g
e r m i n g
How It Works
The algorithm uses a direction indicator (delta) to control the zigzag movement ?
-
delta = 1: Moving down (increasing line number) -
delta = -1: Moving up (decreasing line number) - Direction changes at boundaries: line 0 (top) and line k-1 (bottom)
- Each character is stored with its original position to maintain spacing
Example with Smaller Input
ob = Solution() s = "PAYPALISHIRING" k = 3 result = ob.solve(s, k) print(result)
P A H R A P L S I I G Y I N
Conclusion
The zigzag string conversion uses a direction-controlled traversal to distribute characters across k lines. The key insight is tracking the current line and changing direction at boundaries to create the characteristic zigzag pattern.
Advertisements
