Concatenation of Zig-Zag String in n Rows | Practice | GeeksforGeeks

Given a string and number of rows ‘n’. Print the string formed by concatenating n rows when the input string is written in row-wise Zig-Zag fashion.
Example 1:
Input: 
str = "ABCDEFGH"
n = 2
Output: "ACEGBDFH"
Explanation: 
Let us write input string in 
Zig-Zag fashion in 2 rows.
A   C   E   G  
  B   D   F   H
Now concatenate the two rows and ignore 
spaces in every row. We get "ACEGBDFH"
Example 2:
Input: 
str = "GEEKSFORGEEKS"
n = 3
Output: GSGSEKFREKEOE
Explanation: 
Let us write input string in 
Zig-Zag fashion in 3 rows.
G       S       G       S
  E   K   F   R   E   K
    E       O       E
Now concatenate the two rows and ignore spaces
in every row. We get "GSGSEKFREKEOE"
Your Task:
You need not read input or print anything. Your task is to complete the function convert() which takes 2 arguments(string str, integer n) and returns the resultant string.
Expected Time Complexity: O(|str|).
Expected Auxiliary Space: O(|str|).
Constraints:
1 ≤ N ≤ 105
+9
siddharthahazra6 months ago
Hey here is official video editorial from GeeksforGeeks https://youtu.be/hwuUvJpQ1tI . Upvote this so that this remains on top. Thank you.
0
msandhiya82481 month ago
EASY SOLUTION IN C++ MIGHT HELP YOU
class Solution{
    public:
    string convert(string s, int n) {
        vector<string>v(n,"");
        if(n==1){
            return s;
        }
        int flag=1;
        int j=0;
        for(int i=0;i<s.length();i++){
            v[j]+=s[i];
            
            if(flag){
                j++;
            }
            else{
                j--;
            }
             if(j==0 or j==n-1){
                flag=!flag;
            }
           
            
        }
        string ans="";
        for(int i=0;i<n;i++){
             ans+=v[i];
        }
        return ans;
    }
};
0
chessnoobdj3 months ago
C++
string convert(string s, int k) {
        if(k == 1)
            return s;
        int n = s.size(), j = 0;
        vector <vector<char>> v(k);
        bool flg = true;
        for(int i=0; i<n; i++){
            v[j].push_back(s[i]);
            j += (flg == true) ? 1 : -1;
            if(j == 0 || j == k-1)
                flg = !flg;
        }
        string str = "";
        for(auto i:v){
            for(auto j:i)
                str += j;
        }
        return str;
    }
0
sinrepresion6 months ago
def convert(self, Str, n):
        row = 0
        direction = 1
        output = [""]*n
        
        for char in Str:
            output[row] = output[row]+char
            if row < n-1 and direction == 1:
                row += 1
            elif row > 0 and direction == -1:
                row -= 1  
            else:
                direction *= -1
                row += direction
                
        return "".join(output)
0
ggupta4be206 months ago
C++ code 
 
string convert(string str, int n)
 {   int iter=n;   string ans;   int i=0;
   if(n==1)   return str;
   while(iter>0&&i<str.length())   {       if(iter==1)       {           int tvl=i;           int top_add=1+(n-iter-1)*2;           while(tvl<str.length())           {               ans.push_back(str[tvl]);               tvl+=(top_add+1);           }           break;       }       else if(iter==n)       {           int bottom_add=1+(iter-2)*2;           int tvl=i;           while(tvl<str.length())           {               ans.push_back(str[tvl]);               tvl+=(bottom_add+1);           }           i++;           iter--;       }       else       {           int bottom_add=1+(iter-2)*2;           int top_add=1+(n-iter-1)*2;           int tvl=i;           while(tvl<str.length())           {               ans.push_back(str[tvl]);               tvl+=(bottom_add+1);
               if(tvl<str.length())               ans.push_back(str[tvl]);
               tvl+=(top_add+1);           }           i++;           iter--;       }   }   return ans;   }
 
I have used O(1) extra space and time complexity is still the length of the string.The idea is to calculate the number of charachters needed to skip in the given string to reach the next charachter of our present level.
0
shreysomu22116 months ago
//C++
class Solution{   public:   string convert(string s, int n) {       //code       if(n==1){           return s;       }       string res[n];       int CurRow=0,mod =1;       for(auto e:s){           res[CurRow].push_back(e);           if(CurRow==0)           mod = 1;           if(CurRow== n-1)           mod=-1;           CurRow+= mod;       }       s.clear();       for(auto e:res){           s.append(e);       }       return s;   }};
0
priyankamessage6 months ago
Hey all! Can anyone let me know why does this not work?
 string ans="";
 for(int i=0;i<n;i++)
 { 
   int j=i;
   while(j<=s.size()) {
      ans=ans+s[j];
       j=j+n; 
   } 
}
 return ans;
0
rishug7706 months ago
Python approach
       if(n==1):           return Str       m=len(Str)       d=dict()       for i in range(1,n+1):           d.update({i:''})       i=0       count=1       while(i<m):           while(i<m and count<=n):                   d[count]+=Str[i]                   i+=1                   count+=1           count-=2           while(i<m and count>=1):               d[count]+=Str[i]               i+=1               count-=1           count+=2       ans=''       for i in range(1,n+1):           ans+=d[i]       return ans
0
iliyazali446 months ago
def convert(self, s, n):       # code here       if n==1:           return s              ans=""       flag=""       cnt=0       v=[""]*n       for i in range(len(s)):           v[cnt]+=s[i]           if cnt==n-1:               flag="up"           if cnt==0:               flag="down"           if flag=="up":               cnt-=1           else:               cnt+=1              return "".join(v)
0
ksridharan8296 months ago
// easy implementation !!! //
class Solution{   public:   string convert(string s, int n) {              vector<char> map[n+1];              int ok = 0;       while (ok < s.size()){        for (int i = 1 ; i<=n and ok < s.size() ; i++,ok++){            map[i].push_back(s[ok]);        }           for (int i = n-1 ; i>1 and ok < s.size() ; i--,ok++){             map[i].push_back(s[ok]);        }               }              string ans;       for (int i = 1 ; i<= n ; i++){           for (auto x : map[i]){               ans += x;           }       }       return ans;   }};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.