Tenth Line solution and explanation
9 more videos on this problem
Leetcode - Shell Scripting - 195 - Tenth LineThe Polyglot Programmer · 7:38 · 1K views
Leetcode 195 - Tenth Line | Solving problems using bashDaigen B. River · 6:24 · 634 views
Leetcode 195. Tenth Line SolutionTechZoo · 2:34 · 567 views
Leetcode 195. Tenth LineHan · 1:22 · 176 views
LeetCode | Tenth Line | Bash Command | SDPro Coder · 0:45 · 165 views
Leetcode solving: 195. Tenth LineMath Geeks · 1:00 · 88 views
Tenth Line #leetcode #bash #easyWinEi · 1:16 · 68 views
Tenth Line Solution using Bash in LeetCodeCode and chess · 1:21 · 41 views
Leetcode 195. Tenth Line in Python | Python Leetcode | Python Coding Tutorial | Python Coding ASMRCode is Art · 0:54 · 37 views
No Sound Leetcode 195: Tenth LineExtremeProgrammer · 0:18 · 26 views
The problem
Given a text file file.txt, print just the 10th line of the file.
Example:
Assume that file.txt has the following content:
Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8 Line 9 Line 10
Your script should output the tenth line, which is:
Line 10
1. If the file contains less than 10 lines, what should you output?
2. There's at least three different solutions. Try to explore all possibilities.
Approach overview
Problem Overview: The task is simple: read a file named file.txt and output only the tenth line. If the file has fewer than ten lines, nothing should be printed. The challenge mainly tests familiarity with shell text-processing utilities and basic file iteration.
Approach 1: Line-by-Line Reading (O(n) time, O(1) space)
This approach reads the file sequentially and keeps track of the current line number. You iterate through each line, increment a counter, and print the line when the counter reaches 10. The key insight is that you never need to store the entire file in memory—only the current line and the counter. This makes the method memory efficient and practical even for very large files. Languages like Python, Java, C++, or JavaScript typically implement this with a loop over file input streams or buffered readers. The scan stops as soon as the tenth line is found, which keeps the logic simple and efficient for general file processing tasks.
Approach 2: Using Shell Commands (O(n) time, O(1) space)
Shell utilities are optimized for line-based text processing. Tools like sed, awk, and combinations of head and tail can extract a specific line directly from the command line. For example, sed -n '10p' file.txt prints only the tenth line, while awk 'NR==10' checks the current record number and outputs the matching line. Another option is head -n 10 file.txt | tail -n 1, which first truncates the file to the first ten lines and then selects the last of them. These utilities internally iterate through the file once, giving an overall time complexity of O(n) and constant memory usage. This approach is common in command-line scripting and log analysis.
Recommended for interviews: Interviewers usually expect familiarity with standard shell tools like sed or awk. Showing the line-by-line iteration demonstrates understanding of the underlying logic, but the shell command solution shows practical command-line proficiency. Both run in linear time with constant memory, but the shell approach is typically considered the most idiomatic for this problem.
Approach 1: Line-by-Line Reading
The line-by-line reading approach involves iterating through each line in the file until the 10th line is reached. If the file has less than 10 lines, the script should handle this scenario gracefully, typically by not outputting anything or by printing a message that indicates the file is too short.
def print_tenth_line():
try:
with open('file.txt', 'r') as f:
lines = f.readlines()
if len(lines) >= 10:
print(lines[9].strip())
except FileNotFoundError:
pass # Handle file not found errors
print_tenth_line()import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TenthLine {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line;
int count = 0;
while ((line = br.readLine()) != null) {
if (++count == 10) {
System.out.println(line);
return;
}
}
} catch (IOException e) {
e.printStackTrace(); // Handle file not found or read errors
}
}
}#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("file.txt");
if (!file) return 1; // File not found
std::string line;
int count = 0;
while (std::getline(file, line)) {
if (++count == 10) {
std::cout << line << std::endl;
return 0;
}
}
// If we got here, the file had fewer than 10 lines
return 0;
}const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) return;
const lines = data.split('\n');
if (lines.length >= 10) {
console.log(lines[9]);
}
});#include <stdio.h>
#define TARGET_LINE 10
int main() {
FILE *file = fopen("file.txt", "r");
if (!file) return 1; // File not found
char line[256];
int count = 0;
while (fgets(line, sizeof(line), file)) {
if (++count == TARGET_LINE) {
printf("%s", line);
fclose(file);
return 0;
}
}
// If we reach here, there were less than 10 lines
fclose(file);
return 0;
}using System;
using System.IO;
class Program {
static void Main() {
try {
using (StreamReader sr = new StreamReader("file.txt")) {
string line;
int count = 0;
while ((line = sr.ReadLine()) != null) {
if (++count == 10) {
Console.WriteLine(line);
return;
}
}
}
} catch (Exception e) {
Console.WriteLine(e.Message); // Handle file not found or read errors
}
}
}The Python solution reads all lines at once using readlines() into a list, which allows direct access to the 10th element if it exists. An exception is caught if the file does not exist.
Time Complexity: O(n) due to reading all lines.
Space Complexity: O(n) as all lines are stored in memory.
Approach 2: Using Shell Commands
Some programming languages allow shell commands to be executed directly. This approach uses shell utilities to find the 10th line. This is often the most concise solution, leveraging built-in shell tools, if the environment allows it.
import os
def print_tenth_line():
os.system("sed -n '10p' file.txt")
print_tenth_line()const { exec } = require('child_process');
exec("sed -n '10p' file.txt", (error, stdout, stderr) => {
if (error) return;
console.log(stdout);
});In this Python code, the os.system function is used to execute a shell command. The command uses sed to print just the 10th line from the file. This is efficient and leverages shell capabilities.
Time Complexity: O(n) due to the reading operation.
Space Complexity: O(1) as it's handled by the shell tool, not Python itself.
Approach 3: sed
# Read from the file file.txt and output the tenth line to stdout.
sed -n 10p file.txtComplexity comparison
| Approach | Complexity |
|---|---|
| Line-by-Line Reading | Time Complexity: O(n) due to reading all lines. |
| Using Shell Commands | Time Complexity: O(n) due to the reading operation. |
| sed | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Line-by-Line Reading | O(n) | O(1) | When implementing the logic in general-purpose languages like Python, Java, or C++ |
| Shell Commands (sed / awk / head+tail) | O(n) | O(1) | Best for shell scripting, quick command-line processing, and typical interview expectations for shell problems |
Frequently asked questions
Is Tenth Line easy or hard?
Tenth Line is classified as an Easy problem. The challenge is not algorithmic complexity but familiarity with shell tools like sed, awk, and basic file iteration.
Tenth Line Python/Java solution
In Python or Java, open the file and iterate through each line while counting. When the counter reaches 10, print the line and stop reading further. This approach keeps memory usage constant because the entire file is never loaded into memory.
How to solve Tenth Line in O(n)?
Read the file sequentially and stop once the tenth line is encountered. In shell, commands like `sed -n '10p' file.txt` or `awk 'NR==10' file.txt` accomplish this with a single pass. The scan ensures linear time complexity and constant space.
What is the best approach for Tenth Line?
Using shell utilities like sed or awk is the most direct and idiomatic solution. A command such as `sed -n '10p' file.txt` prints the tenth line without extra processing. It scans the file once, resulting in O(n) time and O(1) space.
Is Tenth Line asked at Google/Amazon/Meta?
Tenth Line is mainly a practice problem for shell scripting and command-line data processing. Similar tasks involving sed, awk, and file parsing can appear in system or DevOps interviews at companies like Amazon or Google.
What data structure is used in Tenth Line?
No complex data structure is required. The solution simply processes a file stream line by line while maintaining a counter for the current line number.
What is the time complexity of Tenth Line?
Both common approaches run in O(n) time where n is the number of lines in the file. The program or command must read lines sequentially until it reaches the tenth line. Memory usage remains O(1) because only one line is processed at a time.
