I have been asked this question in the technical interview for JavaScript today and I failed but I am still unable to find a solution. The question and the solution I came up with is in the following. I achieved to pass some of the test cases but code still does not work in every circumstances. if somebody helps me to solve it in an efficient way, I'd appreciate.
You are given a String, input, comprised of alphabetical letters with varying case.
These letters should create pairs with one another, based on case. For example, the letter 'N forms a "matching pair' with the letter 'a', in that order.
Rules:
- The first letter must be upper-case.
- Every upper-case letter must be followed by its lower-case version or any upper-case letter.
- When an upper-case letter is followed by its lower-case version, those two letters are considered a "matching pair and can then be disregarded from further match consideration.
- If any of these rules are broken or a lower-case letter is encountered that does not create a "matching pair' with its nearest un-matched left neighbour, that letter and all following letters are considered "un-matched".
Output: Your method should return the zero-based index of the last matching lower-case letter, or -1 if no pairs exist.
Limits: 0 < input length < 10,000 characters The optimal method has a running time of O(input length).
Sample input #1
ABba Sample output #1
3 This is what i have done but it does not work for every test cases;
function stringMatch(str){ let word=str.split("") let lastIndex; if (word[0]===word[0].toUpperCase()){ for(let i=0;i<word.length;i++){ if(word[i]===word[i].toUpperCase()){ if(word[i].toLowerCase()===word[i+1] || word[i+1]===word[i+1].toUpperCase() ){ lastIndex=i } else{ return -1 } } else{ lastIndex=i } } return lastIndex } }