* * @param {string} stringOne * @param {string} stringTwo * @returns {bool} * Optimal Solution * Time O(n) - Space O(1) - where n is the length of the shorter string
(stringOne, stringTwo)
| 8 | */ |
| 9 | |
| 10 | function oneEdit(stringOne, stringTwo) { |
| 11 | const lengthOne = stringOne.length; |
| 12 | const lengthTwo = stringTwo.length; |
| 13 | if (Math.abs(lengthOne - lengthTwo) > 1) return false; |
| 14 | |
| 15 | let madeEdit = false; |
| 16 | let indexOne = 0; |
| 17 | let indexTwo = 0; |
| 18 | |
| 19 | while (indexOne < lengthOne && indexTwo < lengthTwo) { |
| 20 | if (stringOne[indexOne] !== stringTwo[indexTwo]) { |
| 21 | if (madeEdit) return false; |
| 22 | madeEdit = true; |
| 23 | if (lengthOne > lengthTwo) { |
| 24 | indexOne++; |
| 25 | } else if (lengthTwo > lengthOne) { |
| 26 | indexTwo++; |
| 27 | } else { |
| 28 | indexTwo++; |
| 29 | indexOne++; |
| 30 | } |
| 31 | } else { |
| 32 | indexOne++; |
| 33 | indexTwo++; |
| 34 | } |
| 35 | } |
| 36 | return true; |
| 37 | } |
| 38 | |
| 39 | // Time O(n + m) |
| 40 | // Space O(n) |