Skip to content

Commit 5873c48

Browse files
authored
Merge pull request #2250 from SahilK-027/main
Create: 0006-zigzag-conversion.cpp
2 parents d69cd3d + 987ad0a commit 5873c48

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

cpp/0006-zigzag-conversion.cpp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/*
2+
For each row the next chracter is at index 2 * (n -1) and
3+
For middle rows there will be extra characters
4+
Time: O(n)
5+
Space: O(1)
6+
*/
7+
class Solution {
8+
public:
9+
string convert(string s, int n) {
10+
// Edge case
11+
if(n == 1) return s;
12+
// Other cases
13+
// Take string to store answer
14+
string ans = "";
15+
// We are going to traverse each row
16+
for(int row = 0; row < n ; row++){
17+
// for each row the next chracter is at index 2 * (n -1)
18+
int increment = 2 * (n -1);
19+
// For first and last rows
20+
for(int i = row; i < s.length(); i+= increment){
21+
ans += s[i];
22+
// For middle rows there will be extra characters
23+
if(row > 0 && row < n-1 && i+increment - 2 * row < s.length()){
24+
ans += s[i+increment - 2 * row];
25+
}
26+
}
27+
}
28+
return ans;
29+
}
30+
};

0 commit comments

Comments
 (0)