We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Tenth Line

Number: 195

Difficulty: Easy

Paid? No

Companies: Adobe


Problem Description

Given a text file file.txt, output only the 10th line. If the file contains less than 10 lines, no output is expected (or an empty output depending on implementation). There are multiple valid strategies to solve this problem using shell scripting.


Key Insights

  • Utilize built-in text processing commands available in Unix/Linux shells.
  • Common solutions include using sed (sed -n '10p'), awk (awk 'NR==10'), or combination of head and tail commands.
  • Consider edge cases where the file may have fewer than 10 lines.

Space and Time Complexity

Time Complexity: O(n) in the worst-case scenario, where n is the number of lines processed. Space Complexity: O(1) since we only need to track the current line number during processing.


Solution

This problem can be approached by directly reading the file line by line and outputting the 10th line. In shell, commands such as sed, awk, or the head-tail combination are used for a succinct solution. The algorithm involves:

  1. Iterating over each line of the file.
  2. Keeping a counter until the 10th line is reached.
  3. Printing the 10th line (if exists) and stopping further processing. The main trick is to minimize memory usage by processing lines sequentially and terminating early if possible.

Code Solutions

# Open the file in read mode
with open("file.txt", "r") as file:
    # Iterate over each line with a counter starting from 1
    for line_number, line in enumerate(file, start=1):
        # Check if the current line is the 10th line
        if line_number == 10:
            # Print the 10th line and exit the loop
            print(line.rstrip())
            break
← Back to All Questions