Given two integers M and N the duty is to assemble a binary palindromic string consisting of M occurrences of 0s and N occurrences of 1s.
Examples:
Enter: M = 4, N = 3
Output: 0011100
Rationalization: The string 0011100 is palindrome containing
4 occurrences of ‘0’ and three occurrences of ‘1’.Enter: M = 3, N = 3
Output: -1
Method:
For the string to be a palindrome, atleast one amongst M and N must be even, in any other case if each M and N are odd then string cannot be a palindrome.
Observe the under steps to unravel the issue:
- If each M and N are odd then print -1.
- If N is Even, print ‘1’ N/2 occasions, then print ‘0’ M occasions, then once more print ‘1’ N/2 occasions.
- If M is Even, print ‘0’ M/2 occasions, then print ‘1’ N occasions, then once more print ‘0’ M/2 occasions.
Beneath is the implementation of the above strategy:
C++
|
Time Complexity: O(M+N)
Auxiliary Area: O(1)