Finding missing letter in a string - JavaScript

We have a string of length m that contains first m letters of the English alphabets, but somehow, one element went missing from the string. So, now the string contains,

m-1 letters

We are required to write a function that takes in one such string and returns the missing element from the string.

Example

Following is the code ?

const str = "acdghfbekj";
const missingCharacter = str => {
    // to make the function more consistent
    const s = str.toLowerCase();
    for(let i = 97; ; i++){
        if(s.includes(String.fromCharCode(i))){
            continue;
        };
        return String.fromCharCode(i);
    };
    return false;
};
console.log(missingCharacter(str));

Output

Following is the output in the console ?

i

How It Works

The function starts checking from ASCII code 97 (which is 'a') and continues until it finds a character that is not present in the string. Here's the breakdown:

  • ASCII code 97 = 'a' (present in string)
  • ASCII code 98 = 'b' (present in string)
  • ASCII codes continue until 105 = 'i' (missing from string)

Alternative Approach Using Set

Here's a more efficient approach using a Set for faster lookups:

const str = "acdghfbekj";
const missingCharacterSet = str => {
    const charSet = new Set(str.toLowerCase());
    
    for(let i = 97; i 

i

Comparison

Method Time Complexity Space Complexity
Using includes() O(n²) O(1)
Using Set O(n) O(n)

Conclusion

Both approaches effectively find the missing character by iterating through ASCII codes. The Set-based method is more efficient for larger strings, while the includes() method uses less memory.

Updated on: 2026-03-15T23:18:59+05:30

742 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements