LC-TEST-14 — Algorithm Test (V1)

🌍 Why This Document Exists

This is not a LeetCode solution dump.

This is a real-world algorithm thinking gym.

You will train:

  • 🧠 Problem decomposition
  • 📊 Data processing at scale
  • ⏱ Time & space complexity awareness
  • 🔁 Iteration, recursion, sliding windows
  • 🧮 Hash maps, sets, heaps, stacks
  • 🧵 Real production-like constraints

Inspired by Google, AWS, Microsoft, OpenAI interviews.


🏆 Python Logic Olympics — Real World Edition (20 Problems)

Difficulty increases gradually. Do not open solutions too early.


🟢 Problem 1 — Log Entry Counter (Warm-Up)

You receive API logs per minute:

logs = [12, 0, 7, 3, 9, 0, 15]

Each number represents requests in that minute.

Task: Count the total number of requests without using sum().

✅ Solution
total = 0
for x in logs:
    total += x
print(total)

🟢 Problem 2 — Healthy Server Detection

Each server sends a heartbeat signal:

heartbeat = [True, True, False, True, True]

A server is healthy only if no False exists.

Task: Return True if the system is healthy, else False.

✅ Solution
healthy = True
for h in heartbeat:
    if not h:
        healthy = False
        break
print(healthy)

🟢 Problem 3 — Unique User IDs

User login stream:

users = [101, 203, 101, 405, 203, 999]

Task: Return the number of unique users.

✅ Solution
unique = set()
for u in users:
    unique.add(u)
print(len(unique))

🟡 Problem 4 — First Repeated Transaction

Transactions arrive in order:

tx = ["A12", "B33", "C90", "B33", "D10"]

Task: Return the first repeated transaction ID.

✅ Solution
seen = set()
for t in tx:
    if t in seen:
        print(t)
        break
    seen.add(t)

🟡 Problem 5 — Sliding Window CPU Alert

CPU usage per second:

cpu = [40, 60, 80, 90, 30, 20, 85]

Task: Detect if any 3 consecutive seconds exceed 200 total usage.

✅ Solution
for i in range(len(cpu) - 2):
    if cpu[i] + cpu[i+1] + cpu[i+2] > 200:
        print(True)
        break
else:
    print(False)

🟡 Problem 6 — Rate Limiter

Requests arrive with timestamps (seconds):

requests = [1, 1, 1, 2, 2, 3, 10]

Rule: Max 3 requests per second.

Task: Return timestamps that violate the rule.

✅ Solution
from collections import defaultdict

count = defaultdict(int)
violations = []

for r in requests:
    count[r] += 1
    if count[r] > 3:
        violations.append(r)

print(violations)

🟡 Problem 7 — Most Frequent Error Code

System errors:

errors = [500, 404, 500, 403, 404, 500]

Task: Return the most frequent error code.

✅ Solution
freq = {}
for e in errors:
    freq[e] = freq.get(e, 0) + 1

print(max(freq, key=freq.get))

🟡 Problem 8 — Data Chunking

Large dataset needs batching:

data = list(range(10))
batch_size = 3

Task: Split data into batches of size batch_size.

✅ Solution
batches = []
for i in range(0, len(data), batch_size):
    batches.append(data[i:i+batch_size])
print(batches)

🔵 Problem 9 — Valid JSON Brackets

Incoming JSON stream (simplified):

s = "{[()()]}"

Task: Check if brackets are valid.

✅ Solution
stack = []
pairs = {')':'(', ']':'[', '}':'{'}

for c in s:
    if c in '([{':
        stack.append(c)
    else:
        if not stack or stack.pop() != pairs[c]:
            print(False)
            break
else:
    print(len(stack) == 0)

🔵 Problem 10 — Longest Continuous Uptime

Service status:

status = [1,1,0,1,1,1,0,1]

1 = up, 0 = down

Task: Find longest continuous uptime.

✅ Solution
max_up = cur = 0
for s in status:
    if s == 1:
        cur += 1
        max_up = max(max_up, cur)
    else:
        cur = 0
print(max_up)

🔵 Problem 11 — Merge Sorted Event Streams

a = [1,3,5]
b = [2,4,6]

Task: Merge into sorted order without sort().

✅ Solution
i = j = 0
res = []

while i < len(a) and j < len(b):
    if a[i] < b[j]:
        res.append(a[i]); i += 1
    else:
        res.append(b[j]); j += 1

res.extend(a[i:])
res.extend(b[j:])
print(res)

🔵 Problem 12 — Anomaly Score Detection

scores = [10, 12, 11, 50, 13]

Rule: An anomaly is > 2× average.

✅ Solution
avg = sum(scores) / len(scores)
print([x for x in scores if x > 2 * avg])

🔴 Problem 13 — LRU Cache Simulation

Capacity = 2 Access pattern:

access = ["A","B","A","C","B"]

Task: Simulate LRU eviction.

✅ Solution
cache = []
cap = 2

for x in access:
    if x in cache:
        cache.remove(x)
    elif len(cache) == cap:
        cache.pop(0)
    cache.append(x)

print(cache)

🔴 Problem 14 — Top-K Frequent Events

events = ["login","pay","login","logout","login","pay"]
k = 2
✅ Solution
from collections import Counter
print([x for x,_ in Counter(events).most_common(k)])

🔴 Problem 15 — Shortest Error Window

logs = ["OK","ERR","OK","ERR","ERR","OK"]

Task: Smallest subarray containing 2 ERR.

✅ Solution
left = 0
err = 0
best = float("inf")

for right in range(len(logs)):
    if logs[right] == "ERR":
        err += 1
    while err >= 2:
        best = min(best, right - left + 1)
        if logs[left] == "ERR":
            err -= 1
        left += 1

print(best)

🔴 Problem 16 — Task Scheduling (Greedy)

Tasks with deadlines:

tasks = [(3,10),(1,5),(2,7)]

(duration, deadline)

✅ Solution
tasks.sort(key=lambda x: x[1])
time = 0

for d, dead in tasks:
    time += d
    if time > dead:
        print(False)
        break
else:
    print(True)

🔴 Problem 17 — Dependency Resolution (Graph)

deps = {"A":["B"],"B":["C"],"C":[]}

Detect cycles.

✅ Solution
vis = set()
path = set()

def dfs(n):
    if n in path: return True
    if n in vis: return False
    path.add(n)
    for nei in deps[n]:
        if dfs(nei): return True
    path.remove(n)
    vis.add(n)
    return False

print(any(dfs(x) for x in deps))

🔴 Problem 18 — API Burst Detection

Requests timestamps:

t = [1,2,3,3,3,3,4]

Burst = 4 in same second.

✅ Solution
from collections import Counter
print(any(v >= 4 for v in Counter(t).values()))

🔴 Problem 19 — Median of Data Stream

Stream:

nums = [5,15,1,3]
✅ Solution
import heapq
low, high = [], []

for n in nums:
    heapq.heappush(low, -n)
    heapq.heappush(high, -heapq.heappop(low))
    if len(high) > len(low):
        heapq.heappush(low, -heapq.heappop(high))

    if len(low) > len(high):
        print(-low[0])
    else:
        print((-low[0] + high[0]) / 2)

🔴 Problem 20 — Distributed Log Consistency

Multiple replicas send logs:

replicas = [
  ["A","B","C"],
  ["A","C"],
  ["A","B","C","D"]
]

Task: Find logs present in all replicas.

✅ Solution
common = set(replicas[0])
for r in replicas[1:]:
    common &= set(r)
print(list(common))

🎯 Final Advice

If you can explain these aloud:

  • You can pass FAANG Python interviews
  • You understand real engineering logic
  • You are no longer memorizing — you are thinking

Previous
Next