Given a binary array A[] of dimension N, the duty is to test whether or not the array will be transformed right into a palindrome by flipping two bits in every operation.
Observe: The operation will be carried out any variety of occasions.
Examples:
Enter: A[] = {1, 0, 1, 0, 1, 1}
Output: Sure
Clarification: We are able to carry out the next operation:
Choose i = 2 and j = 4. Then {1, 0, 1, 0, 1, 1}→{1, 0, 0, 0, 0, 1} which is a palindrome.Enter: A[] = {0, 1}
Output: No
Method: The issue will be solved primarily based on the next remark:
Rely variety of 0s and 1s.
- If the worth of depend of 0s and 1s are odd then no palindrome will be made by performing operation on A[].
- In any other case, array A[] can transformed right into a palindrome after performing operation on array.
Observe the beneath steps to resolve the issue:
- Set zeros = 0 and ones = 0 to retailer the depend of variety of 0s and 1s within the array.
- After that iterate a loop from 0 to N-1 equivalent to:
- If A[i] = 0 increment the worth of zeros in any other case increment the worth of ones.
- If the worth of zeros and ones is odd then print “No” i.e. it isn’t doable to transform A to a palindrome by making use of the above operation any variety of occasions.
- In any other case, print “Sure”.
Beneath is the implementation of the above strategy.
Java
|
Time Complexity: O(N)
Auxiliary House: O(1)