Magicsheet logo

Valid Word Abbreviation

Easy
86.9%
Updated 6/1/2025

Valid Word Abbreviation

What is this problem about?

The "Valid Word Abbreviation" interview question asks you to determine if a given string abbr is a valid abbreviation of another string word. An abbreviation is formed by replacing any number of non-adjacent, non-empty substrings with their lengths. For example, "substitution" could be abbreviated as "s10n" or "sub4u4".

Why is this asked in interviews?

Meta and Apple frequently use the "Valid Word Abbreviation" coding problem to test a candidate's string parsing and pointer management skills. It’s a "Two Pointers interview pattern" problem that requires careful handling of numeric strings and ensuring they don't have leading zeros, which is a common tricky constraint.

Algorithmic pattern used

The "Two Pointers" technique is used here. One pointer i iterates through the word, and another pointer j iterates through the abbr. When abbr[j] is a letter, it must match word[i]. When abbr[j] is a digit, you parse the entire number, ensure it doesn't start with '0', and then skip that many characters in the word by incrementing i.

Example explanation

Word: "apple", Abbr: "a2e"

  1. word[0] is 'a', abbr[0] is 'a'. Match! i=1, j=1.
  2. abbr[1] is '2' (a digit).
  3. Parse number: 2. (Starts with '2', not '0').
  4. Skip 2 in word: i becomes 1 + 2 = 3. j becomes 2.
  5. word[3] is 'l', abbr[2] is 'e'.
  6. 'l' does not match 'e'.
  7. Result: Invalid abbreviation.

Common mistakes candidates make

The most frequent mistake is not checking for leading zeros in the numbers within the abbreviation (e.g., "a01" is invalid). Another is forgetting to check if the total length represented by the abbreviation matches the actual length of the word. Candidates also often run into "index out of bounds" errors if the numeric skip moves the word pointer past the end of the string.

Interview preparation tip

For the "Valid Word Abbreviation" coding problem, be extra careful with the numeric parsing. Use a while loop to read multi-digit numbers like "12" and convert them to an integer before adding them to your word pointer. Always check the final values of both pointers to ensure you've consumed both strings entirely.

Similar Questions