Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Codingbat challenge: sameEnds Stream API Solution

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading