Given the task sameEnds from CodingBat:
Return true if the group of
Nnumbers at the start and end of the array are the same. For example, with{5, 6, 45, 99, 13, 5, 6}, the ends are the same forn=0andn=2, and false forn=1andn=3. You may assume thatnis in the range0..nums.lengthinclusive.sameEnds([5, 6, 45, 99, 13, 5, 6], 1) → false sameEnds([5, 6, 45, 99, 13, 5, 6], 2) → true sameEnds([5, 6, 45, 99, 13, 5, 6], 3) → false
My solution to this problem passes the vast majority of the tests, but not all of them:
public boolean sameEnds(int[] nums, int len) {
if (nums.length >= len * 2) {
for (int i = 0, j = nums.length - 1 ; i < len && len > 0; i++, j--) {
if (nums[i] != nums[j]) {
return false;
}
}
}
return true;
}
My questions are the following:
- What can be done in order to fix my solution?
- Is it possible to solve this task using Stream API ?
lenfrom being greater thannums.length / 2. The start and end can overlap.