C++ | String traversal | Tried to explain | Beats 99%
Intuition & Approach\n Describe your first thoughts on how to solve this problem. \nIntuition was a bit difficult to come up at the first, but once you actually
# Intuition & Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nIntuition was a bit difficult to come up at the first, but once you actually write down the example on the paper and start traversing, you will notice that there are 2 ways:\n\n1. By simply making the 2D matrix wit the given string, and traverse it.\n2. **(This way)** By not using extra space, and instead of traversing row-wise in a formed matrix, traverse col-wise (with a increment value based on `#of column`) in the encoded string.\n\nInitially I struggled with finding a way to compute column number for Way2, but later realized that since the string length is actuall rows*col, so just divide it by rows, and we will have `#of column` and then `incValue`.\n# Complexity\n- Time complexity: O(N) -> String length\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    string decodeCiphertext(string &encText, int rows) {\n        if(rows == 1)   return encText; // base case\n\n        // first find number of colummns.\n        int numCol = encText.length()/rows;\n\n        /*\n         * There are 2 ways to solve this question.\n         * 1. By simply making the 2D matrix wit the given string, and traverse it.\n         * 2. (This way) By not using extra space, and instead of traversing row-wise \\\n         *      in a formed matrix, traverse col-wise in the encoded string.\n         */\n\n        int incValue = numCol + 1;  // column-wise access requires this increment at each index.\n        int n = encText.length();\n        string retStr;\n\n        for(int i = 0; i < numCol; i++) // for each starting index at row = 1\n        {\n            for(int j = i; j < n; j += incValue)    // access all column values.\n            {\n                retStr.push_back(encText[j]);\n            }\n        }\n\n        // now trim whitespaces from the end, because we cannot elimiate it in above\\\n            for loop, because starting space in first row, could be an end, or a start of \\\n            another substring with a space, so let it continue, and trim spaces at the end.\n\n        int idx = retStr.length()-1;\n        while(idx >= 0 && retStr[idx] == \' \')\n            idx--;\n\n        return retStr.substr(0, idx+1);\n    }\n};\n```
['C++']