JavaScript subLength() Algorithm Challenge

Hi! I am currently practicing a couple of code challenges as part of the full-stack JS path.

I have a solution but I am not convinced this is the best way, how else could this be achieved?

Write a function subLength() that takes 2 parameters, a string and a single character. The function should search the string for the two occurrences of the character and return the length between them including the 2 characters. If there are less than 2 or more than 2 occurrences of the character the function should return 0.

subLength('Saturday', 'a'); // returns 6
subLength('summer', 'm'); // returns 2
subLength('digitize', 'i'); // returns 0
subLength('cheesecake', 'k'); // returns 0

MY SOLUTION:

function subLength(string, char) {
  let count = 0;
  let arr = [2, 3];

  for (let i = 0; i < string.length; i++) {
    if (string[i] === char) {
      arr.push(i);
      count++;
    }
  }

  if (count !== 2) return 0;

  return (arr[1] - arr[0]) + 1;
}

Thank you in advance!

I’m not sure I follow your example. The first two elements of the array never change yet they are arbitrarily implemented in your return.

Among the many ways we can accomplish this, the simplest I’ve yet devised is this…

const subLength = (x, c) => {
  const s = x.split(c);
  return s.length === 3 ? s[1].length + 2 : 0
}

It takes into account our understanding of string.split(). If there are exactly two splits, then the returned array will have length 3. The middle element will be the string between the two target chars so we just have to add 2 to its length.

Eg.

'summer'.split('m') === ['su', '', 'er']
1 Like