Skip to content

Shell Problems

4 Shell LeetCode problems · Browse tasks by difficulty and choose your next practice problem.

Build text pipelines around explicit record rules

Shell problems reward choosing the right record separator and composing small tools. Word Frequency is a counting task only after deciding what counts as a word. If the input defines words as whitespace-separated tokens, convert whitespace runs into newlines, sort tokens, then count adjacent equal lines.

When to use it

Use line-oriented tools for line tasks and field-aware tools for columns. Word Frequency, Tenth Line, and Transpose File have different record models; a pipeline that works for whitespace tokens is not automatically a CSV parser.

Worked example

Two lines of input: red blue red blue red

  1. Normalize whitespace to one token per line and discard empty lines. The tokens are red, blue, red, blue, red.
  2. Sort the tokens, then run uniq -c. Sorting brings both blue tokens together and all three red tokens together.
  3. Sort the counts numerically in descending order. Use a secondary word key if ties need deterministic lexical order.

The frequency output is 3 red, then 2 blue. uniq -c alone would count separate runs instead of all occurrences.

Time and space

For n tokens, a comparison-sort pipeline generally requires O(n log n) comparisons, with additional cost for reading and comparing characters. External sort may spill to disk. A tenth-line task instead needs to read at most ten lines and can stop immediately afterward.

Mistakes to check

  • uniq only combines adjacent equal lines. Sorting first changes order, so do not use that pipeline when original record order must be preserved.
  • Choose numeric sorting for counts; lexical sorting places 10 before 2. Locale can also change the order of words.
  • Quote file paths and preserve backslashes when reading raw lines. Test empty input, fewer than ten lines, and a final line without a newline.

Further reading: GNU Coreutils: uniq and adjacent repeated lines

Guide reviewed .

All Shell problems