![]() |
VOOZH | about |
Given a string of odd length, print the string X format.
Examples :
Input: 12345 Output: 1 5 2 4 3 2 4 1 5 Input: geeksforgeeks Output: g s e k e e k e s g f r o f r s g k e e e e k g s
We strongly recommend you to minimize your browser and try this yourself first.
The idea is to use two variables in a single loop, the first variable 'i' goes from left to right and second variable 'j' goes from right to left. The upper part of Cross (or X) is printed before they meet. The central character is printed when they meet and lower part is printed after they cross each other. In the upper part str[i] is printed before str[j] and in the lower part, str[j] is printed before str[i].
Below is the implementation of above idea.
g s e k e e k e s g f r o f r s g k e e e e k g s
Time Complexity: O(len*len), where len is the length of the string.
Auxiliary Space: O(1).
Alternative Solution :
g s e k e e k e s g f r o f r s g k e e e e k g s
Time Complexity: O(len*len), where len is the length of the string.
Auxiliary Space: O(1).
Solution 3: This problem can also be solved by observing that the characters are printed along the left and right diagonals only if we enclose the pattern within a matrix. Now, if the length of the string is len then the pattern can be enclosed within a square matrix of order len.
So, run a nested loop of order len and fill the positions satisfying at the above two conditions with respective characters and the rest of the positions with blank spaces.
Below is the implementation of the above approach:
g s e k e e k e s g f r o f r s g k e e e e k g s
Time Complexity: O(len*len), where len is the length of the string.
Auxiliary Space: O(1).
This article is contributed by Dinesh T.P.D.