0

Given the task sameEnds from CodingBat:

Return true if the group of N numbers 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 for n=0 and n=2, and false for n=1 and n=3. You may assume that n is in the range 0..nums.length inclusive.

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:

  1. What can be done in order to fix my solution?
  2. Is it possible to solve this task using Stream API ?
2
  • What test cases are failing? Commented Jun 9, 2022 at 20:12
  • The spec doesn't prohibit len from being greater than nums.length / 2. The start and end can overlap. Commented Jun 9, 2022 at 20:12

2 Answers 2

1

You can use allMatch() operation in order to implement it with streams.

This solution passes all test cases on CodingBat:

public boolean sameEnds(int[] nums, int len) {
    return java.util.stream.IntStream.range(0, len)
        .allMatch(n -> nums[n] == nums[nums.length - (len - n)]);
}

A fix to your imperative solution might look like this:

public boolean sameEnds(int[] nums, int len) {
    for (int i = 0, j = nums.length - 1 - (len - 1); i < len; i++, j++) {
        if (nums[i] != nums[j]) {
            return false;
        }
    }
    return true;
}

I removed the wrapping if condition because when nums.length >= len * 2 is evaluated to false it means that subarrays that need to be compared overlap, but it doesn't automatically mean that these subarrays are equal.

Condition len > 0 is redundant because it is guaranteed to be in the range [0,nums.length].

Variable j that denotes position in the tail subarray has been initialized to nums.length - 1 - (len - 1) - last valid index minus subarray's length. And the so-called increment statement of the for loop was changed from j-- to j++.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the built in method Arrays.equals if you are using Java 9 or higher:

public boolean sameEnds(int[] nums, int len) {
    return Arrays.equals(nums, 0, len, nums, nums.length - len, nums.length);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.