Day 6 of 90CF 800Codeforces

Way Too Long Words

Shorten every word longer than 10 letters to its first letter, the count of letters in between, and its last letter.

Pattern
Read words, abbreviate by length
Time box
15 min
Time
O(total length of all words)
Space
O(1) extra per word

Try it first — give it 15 minutes

0/4 revealed

Stuck? Take one hint at a time. The struggle is where the pattern sticks.

    The problem in plain English

    This is a Codeforces problem: read from standard input, print to standard output.

    The first line has a number n (1 ≤ n ≤ 100). Then come n lines, each with one word of lowercase letters, 1 to 100 letters long.

    A word is "too long" if it has more than 10 letters. Replace each too-long word with its first letter, the number of letters between the first and last, and its last letter. Print every word (shortened or not) on its own line, in the input order.

    Example: localization has 12 letters. Between l and n there are 10, so it becomes l10n. word has 4 letters, so it's printed as word.

    Building the intuition

    Split the problem into two small jobs.

    Job 1: one word. If len(word) <= 10, print it as is. Otherwise you need the first character, word[0], and the last, word[len − 1]. How many are in between? All of them minus those two: len − 2. For internationalization (20 letters) that's i + 18 + n = i18n.

    Job 2: many words. The first line tells you how many words follow. Read that count, then repeat job 1 that many times.

    That's the whole program. The care is in the details: "more than 10" means 11 or more, and the middle count is a number you turn into text.

    The optimal approach

    1. Read n.
    2. Repeat n times:
      • read a word;
      • if its length is more than 10, output word[0] + (length − 2) + word[length − 1];
      • otherwise output the word unchanged.
    3. Print each result on its own line.

    Reading the input

    The input is a number, then n words. The easiest way in every language is to read tokens (pieces separated by spaces or newlines):

    data = sys.stdin.read().split()   # ["4", "word", "localization", ...]
    n = int(data[0])
    words = data[1:n + 1]
    int n;
    cin >> n;
    string word;
    cin >> word;                      // reads one word; call it in a loop
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int n = Integer.parseInt(in.readLine().trim());
    String word = in.readLine().trim(); // one line = one word here
    const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean);
    const n = Number(data[0]);        // data[1] .. data[n] are the words

    trim() and split() throw away stray spaces and the \r that Windows line endings leave behind.

    The code

    Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.

    import sys
    
    
    def main():
        data = sys.stdin.read().split()  # every word and number, as a list of strings
        n = int(data[0])
        out = []
    
        for word in data[1:n + 1]:
            if len(word) > 10:  # "too long" means 11 letters or more
                # first letter + how many letters sit between the ends + last letter
                out.append(word[0] + str(len(word) - 2) + word[-1])
            else:
                out.append(word)
    
        print("\n".join(out))  # one print at the end is faster than n small prints
    
    
    main()

    Dry run

    wordlength> 10?Output
    word4Noword
    localization12Yesl + 10 + n = l10n
    internationalization20Yesi + 18 + n = i18n

    Complexity

    • Time: O(total length). We read each character once. At most 100 words of 100 letters.
    • Space: O(1) extra per word. We only look at the current word.

    Edge cases and traps

    • Exactly 10 letters. Not too long. abcdefghij stays as it is. Use > 10, not >= 10.
    • 11 letters. The shortest word that changes: abcdefghijk → a9k.
    • Length − 1 instead of − 2. The middle count leaves out both ends.
    • Adding a char to a number in C++ or Java. word[0] + (len − 2) adds character codes and prints a number. Convert the count with to_string / String.valueOf, or print the parts one after another.

    Say it in the interview

    "I read n, then n words. For each word longer than 10 characters I print its first character, then the length minus 2, then its last character. Shorter words go out unchanged. It's linear in the total input size."

    Follow-ups interviewers ask

    • "What if the threshold were a parameter k?" Replace 10 with k. Nothing else changes.
    • "How would you expand i18n back?" You can't uniquely. Many words share the same abbreviation, so you'd need a dictionary to check candidates against.

    Practise the same idea

    This is Day 6 of a free 90-day plan 🐸

    90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.

    Get the full roadmap — free