Home > Software engineering >  Codingbat challenge: sameEnds Stream API Solution
Codingbat challenge: sameEnds Stream API Solution

Time:06-10

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 ?

CodePudding user response:

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 < nums.length; 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.

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 .

CodePudding user response:

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);
}
  • Related