Skip to content

Instantly share code, notes, and snippets.

@njoyaabdel
njoyaabdel / api_integration.py
Created April 8, 2026 21:55
API integration with the catfact.ninja public API. Handles network errors, timeouts, bad HTTP responses, and invalid JSON under a unified APIError exception. Returns a clean 4-field JSON-ready dict. Includes comments on how this would be structured in a larger backend project.
import requests
class APIError(Exception):
pass
def fetch_cat_fact():
url = "https://catfact.ninja/fact"
headers = {"accept": "application/json"}
@njoyaabdel
njoyaabdel / rate_time_limiter.py
Created April 8, 2026 21:54
Simple rate limiter that processes (timestamp, userId) events and allows or blocks each one based on a configurable time window. O(n) solution using a dictionary to track the last allowed timestamp per user.
def process_events(events: list[tuple[int, str]], window=10):
last_seen = {}
result = []
for timestamp, user_id in events:
if user_id not in last_seen:
result.append(True)
last_seen[user_id] = timestamp
else:
if timestamp - last_seen[user_id] >= window:
@njoyaabdel
njoyaabdel / find_pairs_algorithm.py
Created April 8, 2026 21:48
Find all unique pairs in an integer array that sum to a target value. O(n) solution using a set for complement lookup and tuple normalization to handle duplicates.
def find_pairs(arr: list, target: int):
if not arr or len(arr) < 2:
return []
# x+y=target
# y=target-x
seen = set()
result = []
for x_num in arr: