A Flask-based API that analyzes and visualizes the time complexity of various algorithms. This tool measures execution times across different input sizes and returns the results along with visual graphs encoded in Base64 format.
- Python 3.x installed on your system
In project directory, create a virtual environment:
python -m venv .venvOn Windows (PowerShell):
.\.venv\Scripts\Activate.ps1On Windows (Command Prompt):
.\.venv\Scripts\activate.batOn Linux/Mac:
source .venv/bin/activateWith the virtual environment activated, install the required packages:
pip install flask numpy matplotlibVerify that Flask is installed correctly:
pip show flaskOr test with Python:
python -c "import flask; print(flask.__version__)"Once everything is installed, you can run the Flask app with:
python app.pyThe server will be available at http://localhost:3000
http://localhost:3000
GET /
Returns basic API information and available options.
Response Example:
{
"available_algorithms": ["bubble", "linear", "binary", "nested"],
"example": "/analyze?algo=bubble&n=1000&steps=10"
}GET /analyze
Analyzes the time complexity of a specified algorithm with given parameters.
Query Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
algo |
string | Yes | Algorithm key: bubble, linear, binary, nested |
n |
integer | Yes | Maximum input size (must be positive) |
steps |
integer | Yes | Step increment (must be positive, ≤ n) |
Available Algorithms:
| Key | Algorithm Name | Time Complexity |
|---|---|---|
bubble |
Bubble Sort | O(n²) |
linear |
Linear Search | O(n) |
binary |
Binary Search | O(log n) |
nested |
Nested Loops | O(n²) |
Request Example:
GET /analyze?algo=bubble&n=1000&steps=10
This will:
- Run Bubble Sort with input sizes: 10, 20, 30, ..., 1000
- Measure execution time for each input size
- Generate a time complexity graph
- Return all data in JSON format
Response Example:
{
"algo": "Bubble Sort",
"items": "1000",
"steps": "10",
"start_time": 1706450400000,
"end_time": 1706450403500,
"total_time_ms": 3500,
"time_complexity": "O(n²)",
"data_points": 100,
"path_to_graph": "C:/Users/.../graphs/bubble_sort_20260128_143025_a1b2c3d4.png",
"download_url": "/download/bubble_sort_20260128_143025_a1b2c3d4.png",
"graph_base64": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA..."
}Response Fields:
| Field | Type | Description |
|---|---|---|
algo |
string | Full name of the analyzed algorithm |
items |
string | Maximum input size (n value) |
steps |
string | Step increment used |
start_time |
integer | Unix timestamp in milliseconds when analysis started |
end_time |
integer | Unix timestamp in milliseconds when analysis completed |
total_time_ms |
integer | Total analysis duration in milliseconds |
time_complexity |
string | Theoretical time complexity (Big O notation) |
data_points |
integer | Number of data points collected |
path_to_graph |
string | Absolute file path where the graph image was saved |
download_url |
string | URL endpoint to download the saved graph |
graph_base64 |
string | Base64 encoded PNG image of the complexity graph |
Error Responses:
Missing Algorithm Parameter (400)
{
"error": "Missing required parameter: algo"
}Unknown Algorithm (400)
{
"error": "Unknown algorithm: quicksort",
"available_algorithms": ["bubble", "linear", "binary", "nested"]
}Invalid N Parameter (400)
{
"error": "Missing or invalid parameter: n (must be positive integer)"
}Invalid Steps Parameter (400)
{
"error": "Missing or invalid parameter: steps (must be positive integer)"
}Steps Greater Than N (400)
{
"error": "steps cannot be greater than n"
}GET /algorithms
Returns a list of all available algorithms with their details.
Response Example:
{
"algorithms": [
{
"key": "bubble",
"name": "Bubble Sort",
"complexity": "O(n²)"
},
{
"key": "linear",
"name": "Linear Search",
"complexity": "O(n)"
},
{
"key": "binary",
"name": "Binary Search",
"complexity": "O(log n)"
},
{
"key": "nested",
"name": "Nested Loops",
"complexity": "O(n²)"
}
]
}GET /download/<filename>
Downloads a saved graph image directly.
Request Example:
GET /download/bubble_sort_20260128_143025_a1b2c3d4.png
Response:
Returns the PNG file as a downloadable attachment.
Error Response (404):
{
"error": "File not found"
}GET /graphs
Returns a list of all saved graph images.
Response Example:
{
"graphs": [
{
"filename": "bubble_sort_20260128_143025_a1b2c3d4.png",
"download_url": "/download/bubble_sort_20260128_143025_a1b2c3d4.png"
},
{
"filename": "linear_search_20260128_143100_e5f6g7h8.png",
"download_url": "/download/linear_search_20260128_143100_e5f6g7h8.png"
}
],
"total": 2
}Analyze Bubble Sort:
curl "http://localhost:3000/analyze?algo=bubble&n=1000&steps=10"Analyze Linear Search:
curl "http://localhost:3000/analyze?algo=linear&n=5000&steps=100"Analyze Binary Search:
curl "http://localhost:3000/analyze?algo=binary&n=10000&steps=500"Analyze Nested Loops:
curl "http://localhost:3000/analyze?algo=nested&n=500&steps=10"import requests
import base64
# Make API request
response = requests.get(
'http://localhost:3000/analyze',
params={'algo': 'bubble', 'n': 1000, 'steps': 10}
)
data = response.json()
# Print results
print(f"Algorithm: {data['algo']}")
print(f"Time Complexity: {data['time_complexity']}")
print(f"Total Analysis Time: {data['total_time_ms']}ms")
# Save the graph image
if 'graph_base64' in data:
# Remove the data URL prefix
image_data = data['graph_base64'].split(',')[1]
with open('complexity_graph.png', 'wb') as f:
f.write(base64.b64decode(image_data))
print("Graph saved as complexity_graph.png")fetch('http://localhost:3000/analyze?algo=bubble&n=1000&steps=10')
.then(response => response.json())
.then(data => {
console.log('Algorithm:', data.algo);
console.log('Time Complexity:', data.time_complexity);
console.log('Total Time:', data.total_time_ms, 'ms');
// Display the graph in an img element
const img = document.createElement('img');
img.src = data.graph_base64;
document.body.appendChild(img);
});- Parameter Validation: The API validates all query parameters
- Input Size Generation: Creates a list of input sizes from
stepstonwithstepsincrement - Time Measurement: For each input size:
- Records start time
- Executes the algorithm
- Records end time
- Calculates execution duration
- Graph Generation: Creates a matplotlib plot showing input size vs. execution time
- Response Building: Packages all data including the Base64-encoded graph
- Compares adjacent elements and swaps if out of order
- Repeats until no swaps needed
- Worst case: n² comparisons
- Iterates through each element sequentially
- Returns when target is found
- Worst case: n iterations
- Works on sorted arrays
- Divides search space in half each iteration
- Very efficient for large datasets
- Two nested loops, each iterating n times
- Demonstrates quadratic time complexity
- Similar behavior to matrix operations
The generated graph includes:
- X-axis: Input size (n)
- Y-axis: Running time in seconds
- Title: Algorithm name and theoretical complexity
- Data Points: Actual measured times (connected by lines)
- Shaded Area: Visual representation of time growth
- Statistics Box: Average and maximum execution times
| Algorithm | Recommended Max N | Notes |
|---|---|---|
bubble |
5000 | Very slow for large inputs |
linear |
100000 | Scales linearly |
binary |
1000000 | Very fast, logarithmic growth |
nested |
2000 | Quadratic, avoid large inputs |
⚠️ Warning: Using very large values ofnwith O(n²) algorithms may cause long response times or timeouts.
complexity_visualizer/
│
├── app.py # Main Flask application
├── factorial.py # Algorithm implementations
├── graphs/ # Generated graph images
├── API_documentation.md # Detailed API documentation
├── install.md # Installation guide
├── README.md # This file
└── .venv/ # Virtual environment (created during setup)
- Flask - Web framework for the API
- NumPy - Numerical operations
- Matplotlib - Graph generation
Install all dependencies with:
pip install flask numpy matplotlibThis project is available for educational purposes.
Feel free to submit issues or pull requests to improve the project.
For questions or issues, please refer to the API documentation or check the application logs.