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