Implement a Memory Based Sparse File Class

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2025-05-07

Problem Statement

Design and implement a SparseFile class that simulates a file in memory, efficiently storing only non-zero data blocks.


This class should support basic file-like operations — read, write, seek, and getSize — while minimizing memory usage by avoiding storage of uninitialized (zero-filled) regions.


🔹 Problem Context


In a typical file, uninitialized or zero-filled regions still occupy physical storage.


However, in systems like Linux or cloud storage (e.g., AWS S3 sparse objects), files can be sparse — meaning only written regions consume memory/disk, and unwritten parts are treated as zeros.


Your task is to model this behavior in-memory using an object-oriented approach.


✅ Functional Requirements


🧱 Core Operations


Write(offset, data)

•Writes data (string or bytes) starting at the given offset.
•Overwrites existing content if overlapping data is written again.

Read(offset, length)

•Reads length bytes starting from the given offset.
•Returns zero bytes (or '\0' characters) for unwritten regions.

GetSize()

•Returns the logical file size (highest written byte + 1).
•Does not include physically unused zero regions.

Truncate(newSize)

•Resizes the file.
•If the new size is smaller, data beyond it is discarded.
•If larger, new unwritten regions are zero-filled (sparse).

Seek(offset) (optional)

•Moves a virtual file pointer for sequential read/write simulation.


⚙️ Non-Functional Requirements


RequirementDescription


Memory Efficiency

Should not store large zero-filled areas.


Performance

Reads/writes should be O(log N) or better for N sparse blocks.


Extensibility

Easy to modify for future persistence (e.g., disk-based version).


Integrity

Handle overlapping writes and invalid reads gracefully.


Thread Safety (Optional)

Can be extended to support concurrent reads/writes.


🧩 Example Usage

1 2file = SparseFile() 3 4file.write(0, "Hello") 5file.write(1000, "World") 6 7print(file.read(0, 10)) # Output: "Hello\0\0\0\0\0" 8print(file.read(995, 10)) # Output: "\0\0\0\0\0World" 9print(file.getSize()) # Output: 1005


🧠 Explanation:

•Only two blocks (offset 0–4 and 1000–1004) are stored in memory.
•The space between them (995 bytes) is represented logically as zeros, but not stored.


🧩 Core Classes and Responsibilities


Class / InterfaceDescription


SparseFile

The main class representing an in-memory sparse file. Handles read/write/truncate operations.


SparseBlock

Represents a contiguous non-zero data block with attributes like start offset and data.


BlockManager

Maintains an ordered structure (e.g., TreeMap or sorted list) of SparseBlocks for efficient lookup.


MemoryAllocator (Optional)

Manages memory allocation for blocks and merges adjacent ones.


⚙️ Data Structure Design


•Use a sorted map (TreeMap or OrderedDict) keyed by block start offset.
•Each entry stores:
1 2{ 3 start_offset: SparseBlock(start_offset, data) 4}
•For read/write:
•Find the relevant block(s) by offset using binary search or map lookup.
•Merge adjacent blocks if new writes bridge two existing ones.


🧱 Design Patterns to Consider


•Composite Pattern → Treat multiple data blocks as a single logical file.
•Flyweight Pattern → Avoid duplicating zero regions (logical zeros).
•Iterator Pattern → For sequential read support using seek().
•Strategy Pattern (optional) → To allow different storage backends (e.g., memory, disk, hybrid).


🧾 Class Diagram (Text Form)

1 2┌─────────────────────┐ 3│ SparseFile │ 4│ ─────────────────── │ 5│ - blocks: Map<int, SparseBlock> │ 6│ + write(offset, data) │ 7│ + read(offset, length): str │ 8│ + getSize(): int │ 9│ + truncate(size) │ 10└───────────┬────────────────────┘ 11 │ 12 ▼ 13┌─────────────────────┐ 14│ SparseBlock │ 15│ ─────────────────── │ 16│ - startOffset: int │ 17│ - data: bytes │ 18│ + getEndOffset(): int│ 19└─────────────────────┘


🧠 Algorithmic Details


📝 Write Operation


1.Find existing blocks overlapping with the new data range.
2.Merge overlapping or adjacent blocks.
3.Insert or replace the merged block in the ordered structure.


📖 Read Operation


1.Find all blocks that intersect with the requested range.
2.Concatenate data from blocks and fill missing regions with zero bytes.


✂️ Truncate Operation


•Remove or trim blocks beyond the new size.


📊 Example Execution


Write:

1 2write(0, "ABC") 3write(10, "XYZ")


Internal Representation:

1 2blocks = { 3 0: SparseBlock(0, "ABC"), 4 10: SparseBlock(10, "XYZ") 5}


Read(0, 15) → "ABC\0\0\0\0\0\0XYZ\0\0"


🔮 Extensions


•Support persistent storage by serializing SparseBlocks to disk.
•Add compression for blocks.
•Implement thread-safe synchronization for concurrent access.
•Support random access streams via file pointer.


💬 Interview Prompt Summary

Design and implement a SparseFile class that represents an in-memory file storing only non-zero data blocks efficiently.
The class should support file-like operations (read, write, truncate, getSize) while minimizing memory usage for sparse regions.
Emphasize data structure choices, merging logic, and extensibility.


Solution

Comments