Skip to main content
added 277 characters in body
Source Link
Dmitrii Bychenko
  • 187.5k
  • 20
  • 178
  • 231
 a, b, ..... y, z ^ ...... ^ <- moving first ^ ...... ^ <- moving last 

We can combine both conditions into if and have just one loop:

 int result = 0; for (int i = 0; i < A.length; ++i) if (A[i] != A[A.length - 1] || A[0] != A[A.length - 1 - i]) { result = A.length - i - 1; break; }  
 a, b, ..... y, z ^ ...... ^ <- moving first ^ ...... ^ <- moving last 
 a, b, ..... y, z ^ ...... ^ <- moving first ^ ...... ^ <- moving last 

We can combine both conditions into if and have just one loop:

 int result = 0; for (int i = 0; i < A.length; ++i) if (A[i] != A[A.length - 1] || A[0] != A[A.length - 1 - i]) { result = A.length - i - 1; break; }  
deleted 4 characters in body
Source Link
Dmitrii Bychenko
  • 187.5k
  • 20
  • 178
  • 231

Edit: Let's proof that at least one of the indexes is either 0 or length - 1. Let's do it by the contradiction. Suppose we have a solution like

Edit: Let's proof that at least one of the indexes is either 0 or length - 1. Let's do it by the contradiction. Suppose we have a solution like

Edit: Let's proof that at least one of the indexes is either 0 or length - 1. Let's do it by contradiction. Suppose we have a solution like

added 6 characters in body
Source Link
Dmitrii Bychenko
  • 187.5k
  • 20
  • 178
  • 231

Items to the left of c must be d, otherwise we can take a or b indexes and have an improved solution. Items to right of d must be c or we can once again push last index to the right and have a better solution. So we have

Items to the left of c must be d, otherwise we can take a or b indexes and have an improved solution. Items to right of d must be c or we can once again push last to the right and have a better solution. So we have

Items to the left of c must be d, otherwise we can take a or b indexes and have an improved solution. Items to right of d must be c or we can once again push last index to the right and have a better solution. So we have

added 25 characters in body
Source Link
Dmitrii Bychenko
  • 187.5k
  • 20
  • 178
  • 231
Loading
added 289 characters in body
Source Link
Dmitrii Bychenko
  • 187.5k
  • 20
  • 178
  • 231
Loading
added 289 characters in body
Source Link
Dmitrii Bychenko
  • 187.5k
  • 20
  • 178
  • 231
Loading
Source Link
Dmitrii Bychenko
  • 187.5k
  • 20
  • 178
  • 231
Loading