Checking if one string can be achieved from another with single tweak in JavaScript

We are required to write a JavaScript function that takes in two strings of characters lets call them str1 and str2.

The function should check whether we can form str2 from str1 by deleting exactly one character from str1. If we can do so the function should return true, false otherwise.

For example −

If the input strings are −

const str1 = 'chemistty';
const str2 = 'chemisty';

Then the output should be −

const output = true;

Approach

The solution involves checking if the length difference is exactly 1, then trying to remove each character from str1 to see if it matches str2.

Algorithm Steps

1. First, check if str1 is exactly one character longer than str2
2. Loop through each position in str1
3. For each position, create a new string by removing that character
4. Compare the result with str2
5. Return true if any match is found

Example

Following is the code −

const str1 = 'chemistty';
const str2 = 'chemisty';

const stringSimilarity = (str1 = '', str2 = '') => {
    if(str1.length - str2.length !== 1){
        return false;
    };
    
    for(let i = 0; i 

Output

true

Additional Examples

// Test with different cases
console.log(stringSimilarity('hello', 'hllo'));    // true (remove 'e')
console.log(stringSimilarity('world', 'word'));    // true (remove 'l')
console.log(stringSimilarity('test', 'best'));     // false (would need replacement)
console.log(stringSimilarity('abc', 'xyz'));       // false (completely different)
console.log(stringSimilarity('same', 'same'));     // false (no deletion needed)
true
true
false
false
false

How It Works

The function uses JavaScript's substring() method to create a new string by removing one character at position i. The expression str1.substring(0, i) + str1.substring(i + 1, str1.length) concatenates the part before position i with the part after position i, effectively removing the character at index i.

Conclusion

This approach efficiently determines if one string can be formed from another by removing exactly one character. The time complexity is O(n²) where n is the length of the longer string.

Updated on: 2026-03-15T23:19:00+05:30

134 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements