public class symm
{
/*
* Returns true if array A is symmetric.
* Returns false otherwise.
* n is the number of elements A contains.
*
* The running time of your algorithm is O( ).
* You may add a brief explanation here if you wish.
*/
public static boolean symmetric( int[] A, int n )
{
return symmHelper(A, n, 0);
}
private static boolean symmHelper(int[] A, int n, int i) {
if(n==1)
return true;
if((n==2) && (A[i] == A[n-1-i]))
return true;
if((i == n-1-i) && (A[i] == A[n-1-i] ))
return true;
if(A[i] == A[n-1-i] && i < n/2 )
return symmHelper(A, n, i+1);
return false;
}
}
Test cases: I passed all the tests ecxept the fitst on I get no whenever I run it, I think the problem is that there are two 2s in the middle. And I'm not really sure about the code, I think it can be simplified. Is the running time o(log n)?
5 8 2 2 8 5 YES
10 7 50 16 20 16 50 7 10 YES
5 8 5 YES
1000 1000 YES
6000 YES
10 7 50 16 20 16 50 7 1000 NO
10 7 50 16 20 16 50 700 10 NO
10 7 50 16 20 16 5000 7 10 NO
10 7 50 16 20 1600 50 7 10 NO
10 7 50 16 1600 50 7 10 NO
if(A[i] == A[n-1-i] && i < n/2 )
That line right there is the problem. Because you're using an even number > 2 of values, when it gets to this line it skips over it because at that point i = n/2, rather than being less than it. So the function skips that and continues on to return false. Change it to this and you should be fine:
if(A[i] == A[n-1-i] && i <= n/2 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With