KatInterview

408. Valid Word Abbreviation

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to validate if a given string abbr is a valid abbreviation of another string word. The rules for abbreviation are specific: we can replace non-adjacent, non-empty substrings of word with their lengths. These lengths must not have leading zeros. We need to process abbr and see if it can be mapped back to word according to these rules.

Solution

Valid Word Abbreviation in Python

class Solution:
    def validWordAbbreviation(self, word: str, abbr: str) -> bool:
        i, j = 0, 0 # i for word, j for abbr
        n, m = len(word), len(abbr)
        
        while j < m:
            if abbr[j].isdigit():
                # Leading zero check
                if abbr[j] == '0':
                    return False
                
                num = 0
                # Parse the number
                while j < m and abbr[j].isdigit():
                    num = num * 10 + int(abbr[j])
                    j += 1
                
                # Advance word pointer
                i += num
            else:
                # Character match. Check if word pointer is out of bounds.
                if i >= n or word[i] != abbr[j]:
                    return False
                i += 1
                j += 1
        
        # After iterating through abbr, word pointer must be at the end of word.
        return i == n

Valid Word Abbreviation in Java

class Solution {
    public boolean validWordAbbreviation(String word, String abbr) {
        int i = 0; // pointer for word
        int j = 0; // pointer for abbr
        int n = word.length();
        int m = abbr.length();

        while (j < m) {
            if (Character.isDigit(abbr.charAt(j))) {
                // Leading zero check
                if (abbr.charAt(j) == '0') {
                    return false;
                }
                
                int num = 0;
                // Parse the number
                while (j < m && Character.isDigit(abbr.charAt(j))) {
                    num = num * 10 + (abbr.charAt(j) - '0');
                    j++;
                }
                // Advance word pointer
                i += num;
            } else {
                // Character match. Check if word pointer is out of bounds.
                if (i >= n || word.charAt(i) != abbr.charAt(j)) {
                    return false;
                }
                i++;
                j++;
            }
        }
        
        // After iterating through abbr, word pointer must be at the end of word.
        return i == n;
    }
}

Valid Word Abbreviation in C++

class Solution {
public:
    bool validWordAbbreviation(string word, string abbr) {
        int i = 0; // pointer for word
        int j = 0; // pointer for abbr
        int n = word.length();
        int m = abbr.length();

        while (j < m) {
            if (isdigit(abbr[j])) {
                // Leading zero check
                if (abbr[j] == '0') {
                    return false;
                }
                
                int num = 0;
                // Parse the number
                while (j < m && isdigit(abbr[j])) {
                    num = num * 10 + (abbr[j] - '0');
                    j++;
                }
                // Advance word pointer
                i += num;
            } else {
                // Character match. Check if word pointer is out of bounds.
                if (i >= n || word[i] != abbr[j]) {
                    return false;
                }
                i++;
                j++;
            }
        }
        
        // After iterating through abbr, word pointer must be at the end of word.
        return i == n;
    }
};

Valid Word Abbreviation in TypeScript

function validWordAbbreviation(word: string, abbr: string): boolean {
    let i = 0; // pointer for word
    let j = 0; // pointer for abbr
    const n = word.length;
    const m = abbr.length;

    while (j < m) {
        // Check if current character in abbr is a digit
        if (abbr[j] >= '0' && abbr[j] <= '9') {
            // Leading zero check
            if (abbr[j] === '0') {
                return false;
            }

            let num = 0;
            // Parse the multi-digit number
            while (j < m && abbr[j] >= '0' && abbr[j] <= '9') {
                num = num * 10 + Number(abbr[j]);
                j++;
            }
            // Advance word pointer by the parsed number
            i += num;
        } else {
            // Character match. Check if word pointer is out of bounds.
            if (i >= n || word[i] !== abbr[j]) {
                return false;
            }
            i++;
            j++;
        }
    }

    // After iterating through abbr, word pointer must be at the end of word.
    return i === n;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.