Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Create: 0006-zigzag-conversion.cpp
  • Loading branch information
SahilK-027 authored Feb 15, 2023
commit 987ad0a8fb1d4f761fdd29cd07979bc42b60b2b5
30 changes: 30 additions & 0 deletions cpp/0006-zigzag-conversion.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
For each row the next chracter is at index 2 * (n -1) and
For middle rows there will be extra characters
Time: O(n)
Space: O(1)
*/
class Solution {
public:
string convert(string s, int n) {
// Edge case
if(n == 1) return s;
// Other cases
// Take string to store answer
string ans = "";
// We are going to traverse each row
for(int row = 0; row < n ; row++){
// for each row the next chracter is at index 2 * (n -1)
int increment = 2 * (n -1);
// For first and last rows
for(int i = row; i < s.length(); i+= increment){
ans += s[i];
// For middle rows there will be extra characters
if(row > 0 && row < n-1 && i+increment - 2 * row < s.length()){
ans += s[i+increment - 2 * row];
}
}
}
return ans;
}
};