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

Difficulty: Easy


Problem Description

Given a text file file.txt, print just the 10th line of the file.


Key Insights

  • The task requires reading a file and extracting a specific line, which involves handling file I/O operations.
  • If the file contains fewer than 10 lines, no output should be produced.
  • There are multiple approaches to solve this problem, including using shell commands and programming languages.

Space and Time Complexity

Time Complexity: O(n), where n is the number of lines in the file, as we may need to read through the file until we reach the 10th line.
Space Complexity: O(1), as we only need a constant amount of space to store the current line.


Solution

The solution involves reading the file line by line until the 10th line is reached. Different programming languages and shell commands can be employed for this purpose. The algorithm typically iterates through the file, counting lines, and prints the line when the count reaches 10. If fewer than 10 lines exist, the solution handles that case gracefully by not producing any output.


Code Solutions

# Python solution using line iteration
def print_tenth_line():
    with open('file.txt', 'r') as file:
        for i, line in enumerate(file):
            if i == 9:  # line index 9 corresponds to the 10th line
                print(line.strip())
                break  # exit after printing the 10th line
← Back to All Questions