I am trying to write a function that takes in an array of individual characters (eg.[‘a’,’b’,’d’]) and returns the first character that is missing (eg. ‘c’). I am not sure why my current function doesn’t work as described.
const alph = "abcdefghijklmnopqrstuvwxyz"; const findMissingLetter = (arr) => { arr.forEach((l, i, a) => { const ltrIdx = alph.indexOf(l); //a's index in the alph is 0 const arrNxtLtr = a[i+1]; //the next ltr after a is c if(arrNxtLtr !== alph[ltrIdx + 1]) return alph[ltrIdx + 1] //return the letter that is missing from the arr }) return -1 //return -1 if there is no missing char } console.log(findMissingLetter(['a','c']))
ps. I’ve seen similar approaches to solve this general problem, I am just simply wondering what I’ve done wrong with my function so I can learn.
Thank you!
Advertisement
Answer
If you simply want to find the first mismatch between two strings, then just compare them character by character until you find a mismatch or reach the end of the input string:
const alph = "abcdefghijklmnopqrstuvwxyz"; const findMissingLetter = (arr) => { for(let i=0; i<arr.length; i++) { if(arr[i] !== alph[i]) { return alph[i]; // found the first mismatch } } return -1 // return -1 if there is no missing char } console.log(findMissingLetter([]),"-1?"); console.log(findMissingLetter(['a']),"-1?"); console.log(findMissingLetter(['b']),"a?"); console.log(findMissingLetter(['a','b']),"-1?"); console.log(findMissingLetter(['a','c']),"b?");
And avoid forEach()
if you want to return from inside a loop as it was commented already.
And if the input string does not have to start at the beginning of the “big” string, locate it’s first character and do the comparison from there:
const alph = "abcdefghijklmnopqrstuvwxyz"; const findMissingLetter = (arr) => { if(arr.length===0) return -1; let start = alph.indexOf(arr[0]); for(let i=0; i<arr.length; i++) { if(arr[i] !== alph[start+i]) { return alph[start+i]; // found the first mismatch } } return -1 // return -1 if there is no missing char } console.log(findMissingLetter([]),"-1?"); console.log(findMissingLetter(['a']),"-1?"); console.log(findMissingLetter(['b']),"-1?"); console.log(findMissingLetter(['a','b']),"-1?"); console.log(findMissingLetter(['a','c']),"b?"); console.log(findMissingLetter(['b','c','e','f']),"d?");