Skip to content
Advertisement

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.

JavaScript

My solution to this problem passes the vast majority of the tests, but not all of them:

JavaScript

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 ?

Advertisement

Answer

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

This solution passes all test cases on CodingBat:

JavaScript

A fix to your imperative solution might look like this:

JavaScript

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++.

Advertisement