MCPcopy Create free account
hub / github.com/betomoedano/JavaScript-Coding-Interview-Questions / isOneOrLessAway

Function isOneOrLessAway

strings/one-away.js:20–44  ·  view source on GitHub ↗
(str1, str2)

Source from the content-addressed store, hash-verified

18 * @return {boolean} True if strings are 0 or 1 edit apart, otherwise false
19 */
20export function isOneOrLessAway(str1, str2) {
21 // if lengths differ by more than 1 then can't be true
22 if (Math.abs(str1.length - str2.length) > 1) {
23 return false;
24 }
25
26 let isEdited = false;
27 for (let i = 0, j = 0; i < str1.length && j < str2.length; ++i, ++j) {
28 if (str1[i] !== str2[j]) {
29 if (isEdited) {
30 // second edit
31 return false;
32 }
33
34 if (str1.length > str2.length) {
35 --j; // decrease j, we are deleting char from str1
36 } else if (str1.length < str2.length) {
37 --i; // decrease i, we are deleting char from str2
38 }
39 isEdited = true;
40 }
41 }
42
43 return true;
44}
45
46// Time O(n + m)
47// Space O(max(n + m))

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected