
Grading Interviews, Part 3: Backend Developer — Algorithms, SQL, HTTP, and Design
🌐 Machine-translated from Russian. Show original
Designations: J — junior, M — middle, S — senior. The code is in Python, but interviewers usually allow any language you know.
In this part:
Algorithms and data structures#
J. What is the complexity of O(n), O(log n), O(n²)?#
How time (or memory) grows as input data grows. O(1) — does not depend on size (access to an array element by index, dictionary on average). O(log n) — binary search on a sorted array. O(n) — one pass through the list. O(n log n) — good sorts. O(n²) — nested loop over the same data. Key practical conclusion: at a million elements O(n²) — this is already a problem.
J. How is a dictionary (hash table) structured and why is searching in it fast?#
The key is converted by the hash function into a number by which the array cell is computed. Lookup, insertion, and deletion are on average O(1). Collisions (different keys in one cell) are resolved by chains or by open addressing. Hence the requirement: the key must be immutable and hashable (in Python — string, number, tuple, but not a list).
Problem J: two numbers with a given sum#
Find the indices of two elements whose sum equals target.
def two_sum(nums: list[int], target: int) -> tuple[int, int] | None:
seen: dict[int, int] = {} # значение → индекс
for i, x in enumerate(nums):
if target - x in seen:
return seen[target - x], i
seen[x] = i
return None
assert two_sum([2, 7, 11, 15], 9) == (0, 1)
assert two_sum([3, 3], 6) == (0, 1)
assert two_sum([1, 2], 10) is None
What they want to hear: "forehead" — two cycles, O(n²); with a dictionary — one pass, O(n) by time and O(n) by memory.
Problem J/M: proper parenthesis sequence#
def is_balanced(s: str) -> bool:
pairs = {")": "(", "]": "[", "}": "{"}
stack: list[str] = []
for ch in s:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
return not stack
assert is_balanced("([]{})")
assert not is_balanced("(]")
assert not is_balanced("((")
assert is_balanced("")
Stack is the classic structure for nesting. Note boundary cases: empty string, extra closing bracket, unclosed at the end.
Problem M: top-K of the most common words#
import heapq
import re
from collections import Counter
def top_words(text: str, k: int) -> list[tuple[str, int]]:
words = re.findall(r"[a-zа-яё0-9]+", text.lower())
counts = Counter(words)
return heapq.nlargest(k, counts.items(), key=lambda kv: kv[1])
print(top_words("Мама мыла раму, мама мыла пол", 2)) # [('мама', 2), ('мыла', 2)]
Discussion for middle+: Counter.most_common(k) does the same; heap gives O(n log k) instead of full sort O(n log n). What if the text is 100 GB of logs and doesn't fit in memory? We count in parts (map-reduce), and for an approximate answer — special structures like Count-Min Sketch.
M. Remove duplicates from the list while preserving order#
def unique(items: list) -> list:
return list(dict.fromkeys(items)) # словари в Python сохраняют порядок вставки
assert unique([3, 1, 3, 2, 1]) == [3, 1, 2]
SQL#
Let there be tables employees(id, name, department_id, salary, hired_at) and departments(id, name).
J. What types of JOIN are there?#
- INNER JOIN — only matching rows from both tables.
- LEFT JOIN — all rows of the left table; for those that do not match on the right — NULL.
- RIGHT JOIN —on the contrary (in practice, almost always rewrite as LEFT).
- FULL JOIN — all rows of both tables.
- CROSS JOIN — each line with each one.
A popular catch: a condition on the right table in WHERE after LEFT JOIN turns it into an inner join. The right table filter is placed in ON.
J. How is WHERE different from HAVING?#
WHERE filters rows before grouping, HAVING groups after it, and aggregates can be used in it.
-- отделы, где больше 5 сотрудников с зарплатой выше 500 000
SELECT d.name, COUNT(*) AS cnt
FROM employees e
JOIN departments d ON d.id = e.department_id
WHERE e.salary > 500000
GROUP BY d.name
HAVING COUNT(*) > 5;
J/M. Find duplicates#
SELECT name, COUNT(*)
FROM employees
GROUP BY name
HAVING COUNT(*) > 1;
M. Employee with maximum salary in each department#
SELECT department_id, name, salary
FROM (
SELECT e.*,
ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rn
FROM employees e
) t
WHERE rn = 1;
A clarifying question worth asking: what to do if two have the same maximum salary? Then RANK() or DENSE_RANK() will be reinstated instead of ROW_NUMBER() .
M. How does the index work and when won't it help?#
The usual index is the B-tree: a sorted structure where the search follows O(log n) instead of a full table view. The index speeds up reading but slows down writing and takes up space.
The index is not used or useless when:
- function above the column:
WHERE lower(email) = ...(an index by expression is needed); LIKE '%текст'with a percentage at the beginning;- composite index
(a, b), and filter only byb— column order is important; - the query selects most of the table — full viewing is cheaper;
- mismatch of types in a condition.
Validation — EXPLAIN ANALYZE in PostgreSQL.
M. What is a transaction and ACID?#
Atomicity — all or nothing. Consistency — data moves from one valid state to another. Isolation — parallel transactions do not interfere with each other (within the isolation level). Durability — acknowledgement is not lost in case of failure.
M/S. Insulation levels and anomalies#
| Level | Dirty Reading | Unique Reading | Phantoms |
|---|---|---|---|
| Read Uncommitted | possibly | possible | possible |
| Read Committed | no | possible | possible |
| Repeatable Read | no | no | possible according to the |
| Serializable | no | no | no |
Pros of the answer: PostgreSQL by default works in Read Committed, and Read Uncommitted behaves as Read Committed; on Repeatable Read, PostgreSQL does not allow phantoms. There is an anomaly of the lost update — it is resolved by SELECT ... FOR UPDATE, atomic UPDATE ... SET x = x + 1 , or optimistic locking by version.
M. What is the N+1 problem?#
Get a list of N orders with one request, and then in the loop for each — another request after client. In total, N+1 requests instead of one or two. Treated by JOIN by loading related data with a single request (WHERE id IN (...)) or using ORM tools (select_related, joinedload, Include).
HTTP and API#
J. HTTP Methods and Idempotency#
| Method | Purpose | Idempotential | Safe |
|---|---|---|---|
| GET | get | yes | yes |
| POST | create, perform action, | no | no |
| PUT | replace the whole | yes | no |
| PATCH | change part | not necessarily | not |
| DELETE | delete | no |
Idempotent — repetition of the request does not change the result. Therefore, GET and PUT can be safely retried in case of network failure, while POST cannot be used.
J. Main response codes#
- 2xx Success: 200 OK, 201 Created, 204 No Content.
- 3xx redirect: 301 permanently, 302/307 temporarily, 304 unchanged (cache).
- 4xx client error: 400 invalid request, 401 not authorized, 403 no rights, 404 not found, 409 conflict, 422 not validated, 429 too many requests.
- 5xx server error: 500, 502 poor response from upstream server, 503 unavailable, 504 gateway timeout.
A common mistake is to confuse 401 and 403: 401 — "who are you?", 403 — "we know you, but we can't."
M. Cookie session or JWT?#
Session: the server stores the state, the client only uses the identifier in the cookie (HttpOnly, Secure, SameSite). Easy to revoke — delete the session. JWT: signed token with data, the server stores nothing — convenient for many services, but difficult to revoke before expiration. Therefore, a short access token plus a refresh token that can be revoke. Storing tokens in localStorage is risky due to XSS.
M. What is CORS?#
A browser mechanism that prevents JavaScript from one source page (schema + domain + port) from reading responses from another unless the server explicitly allows it with Access-Control-Allow-Origin headers and others. For "complex" requests, the browser first sends a preliminary request OPTIONS. It's important to understand: CORS protects browser users, not your API — curl ignores it.
Design (middle+ and senior)#
M/S. Design a shortlink service#
The response plan awaited:
- Requirements: create a short link, follow it, statistics? How many links per day and clicks? Lifespan?
- API:
POST /links→{code};GET /{code}→ 301/302 to the original address. - Code generation: counter + encoding in base62 or random string with uniqueness check. Discuss collisions and predictability.
- Storage: table
code → urlwith a unique index. There are many more reads than records — cache (Redis) before the database. - Scale: read-to-read replicas, code sharding if there is a lot of data.
- Statistics: we do not write transitions synchronously to the main database — we send them to the queue and count them separately.
- Security: protection against spam and phishing, creation limits.
S. How to make a payment that cannot be made twice?#
The keyword is idempotency: the client sends Idempotency-Key, the server saves the result by key, and returns the same response on a repeat. Plus unique limitations in the database, status model of payment (created → processed → conducted/rejected), reconciliation with the bank or payment system, handling the "timeout, but money debited" situation. Detailed information about payments — series "Online payment on the website and app: banks and payment services of Kazakhstan."
S. Typical senior-level questions#
- Monolith or microservices for a new product — and why?
- How to reliably transfer data between services (queues, outbox pattern, repeats, deduplication)?
- How to roll out database schema changes without downtime?
- How would you limit the rate limiting: token bucket, where to store the meters?
- How do you conduct code reviews and what do you always check?
Next — questions for 1C developers: Interviews on upgrades, part 4: 1C developer — platform, queries, implementation, and performance.
Comments · 0
No comments yet.Sign in to comment, rate and see all comments.