#195

Tenth Line

Easy
ShellFile I/OEnumeration
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of reading through the entire file, we can use a more efficient method by leveraging built-in functions that directly access the 10th line if it exists, reducing unnecessary reads.

⚙️

Algorithm

4 steps
  1. 1Step 1: Open the file for reading.
  2. 2Step 2: Use a buffer to read lines efficiently.
  3. 3Step 3: Read lines until the 10th line is reached or end of file.
  4. 4Step 4: If the 10th line is reached, print it; otherwise, handle the case where there are fewer than 10 lines.
solution.py8 lines
1# Full working Python code
2with open('file.txt', 'r') as file:
3    for i, line in enumerate(file):
4        if i == 9:
5            print(line.strip())
6            break
7    else:
8        print('File has less than 10 lines.')

Complexity note: The time complexity remains O(n) as we still need to read lines, but we handle fewer lines in memory. Space complexity is O(1) as we only store a few variables.

  • 1Reading files line by line is efficient for large files.
  • 2Always handle edge cases, like fewer than 10 lines.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.