Backend Developer (Junior Level) Interview Preparation Guide - FAANG Standards
This guide is based on general FAANG interview practices and may not reflect specific company procedures.
FAANG companies typically conduct 5-6 interview rounds for Backend Developer positions at Junior Level (1-2 years experience). The process begins with recruiter screening, followed by 2-3 technical coding rounds that test data structures, algorithms, and coding proficiency. As a junior developer, you'll encounter system design questions that focus on foundational concepts like API design and basic scalability principles. Behavioral rounds assess cultural fit and teamwork capabilities. The entire process emphasizes problem-solving approach, code quality, communication, and ability to work collaboratively.
Interview Rounds
Recruiter Phone Screen
What to Expect
Initial screening call with a recruiter to assess cultural fit, motivation, and basic qualifications. This round is non-technical and focuses on understanding your background, interest in the company, and career goals. The recruiter will explain the interview process and answer your questions about the role and company.
Tips & Advice
Be enthusiastic and genuine about your interest in backend development and the company. Have a clear 2-3 minute summary of your background ready. Research the company beforehand and ask thoughtful questions about the backend engineering team, tech stack, and growth opportunities. Be honest about your experience level as a junior developer. Prepare examples of projects or contributions you've made. Dress professionally even on a phone call (mindset matters). Take notes during the call.
Focus Topics
Career Motivation and Growth Mindset
Articulate why you want to work as a backend developer, what excites you about building server-side systems, and your learning objectives. Show eagerness to grow and willingness to work on challenging problems.
Practice Interview
Study Questions
Communication Skills and Clarity
Ability to articulate thoughts clearly, listen actively to recruiter's questions, and respond directly without over-complicating simple answers. Demonstrate professionalism and friendliness.
Practice Interview
Study Questions
Company Research and Role Understanding
Demonstrate knowledge of the company's backend infrastructure, products, technology choices, and engineering challenges. Show genuine interest by asking informed questions about how the backend team works, what technologies they use, and what impact the role would have.
Practice Interview
Study Questions
Background and Experience Summary
Ability to concisely communicate your software development background, relevant projects, technical skills, and why you're interested in backend development specifically. This includes explaining any internships, bootcamp experience, or self-taught projects.
Practice Interview
Study Questions
Technical Phone Screen - Coding Round 1
What to Expect
First technical coding interview conducted via phone or video call using an online collaborative coding platform (CoderPad, HackerRank, etc.). You'll be given 1-2 coding problems focused on data structures and algorithms to solve within 45 minutes. The interviewer will assess your problem-solving approach, coding ability, and communication during the process.
Tips & Advice
Start by clarifying the problem statement—ask about edge cases, input constraints, and expected output format. Don't jump into coding immediately. Explain your approach and time/space complexity before writing code. Write clean, readable code with meaningful variable names. Test your solution with examples before declaring it complete. If stuck, discuss your thinking and ask for hints rather than staying silent. Practice on LeetCode medium-difficulty problems. Get comfortable with your chosen language (Python, Java, Go, or Node.js). Leave time for optimization if your initial solution is brute force. Remember: the interviewer cares more about your thinking process than getting a perfect solution on the first try.
Focus Topics
Linked Lists
Ability to implement and manipulate linked lists including operations like insertion, deletion, reversal, and cycle detection. Understand pointers and memory concepts underlying linked lists.
Practice Interview
Study Questions
Clean Code and Communication
Write readable code with meaningful variable names, appropriate comments, and logical structure. Verbally communicate what you're doing while coding. Explain your reasoning for design choices.
Practice Interview
Study Questions
Problem Solving and Approach
Ability to break down a coding problem into smaller steps, identify the core challenge, and think through multiple approaches. Communicate your thinking clearly before and while coding. Recognize patterns and similar problems you've seen.
Practice Interview
Study Questions
Arrays and Strings
Master fundamental problems involving array manipulation, string processing, searching, sorting, and two-pointer techniques. Understand array indexing, iteration patterns, and common operations like reversing, merging, and filtering.
Practice Interview
Study Questions
Hash Tables and HashMaps
Proficiency with hash-based data structures for solving problems involving counting, frequency analysis, finding duplicates, or implementing caches. Understand collision handling, trade-offs between space and time complexity.
Practice Interview
Study Questions
Big-O Time and Space Complexity Analysis
Ability to analyze and articulate the time and space complexity of your solutions. Understand Big-O notation and how to identify dominant operations. Recognize when optimizations are needed and what trade-offs exist.
Practice Interview
Study Questions
Technical On-site Round 1 - Advanced Coding
What to Expect
Second coding interview conducted in-person or video (on-site round). You'll solve 1-2 more complex coding problems, often building on patterns from the phone screen but with higher difficulty. This round may involve multiple data structures combined or optimization challenges. Interviewers may ask follow-up questions or introduce new constraints to see how you adapt.
Tips & Advice
Expect problems that combine multiple concepts (e.g., hash table + graph traversal). Start with brute force solution if optimal solution isn't immediately clear, then optimize. Pay attention to interviewer hints—they indicate where you might be overcomplicating things. Test edge cases thoroughly before final submission. If you get stuck, walk through the problem step-by-step verbally rather than coding randomly. At junior level, showing you can debug and iterate is important. Don't panic if the problem seems harder—this round is designed to differentiate among candidates. Practice LeetCode hard problems and mix different data structures in single problems.
Focus Topics
Dynamic Programming Basics
Recognition of overlapping subproblems and optimal substructure. Ability to solve classic DP problems like fibonacci, coin change, and climbing stairs. Understanding memoization and tabulation.
Practice Interview
Study Questions
Sorting and Searching Algorithms
Deep understanding of different sorting algorithms (merge sort, quick sort, heap sort) and their complexities. Binary search and its variations. When to use each approach.
Practice Interview
Study Questions
Recursion and Backtracking
Ability to solve problems using recursive approaches. Understand backtracking patterns for exploring solution spaces. Know when recursion is appropriate versus iterative solutions.
Practice Interview
Study Questions
Problem Adaptation and Handling Constraints
Ability to modify your approach when interviewer introduces new constraints or edge cases. Demonstrate flexibility in thinking and comfort with iterating solutions.
Practice Interview
Study Questions
Graphs and Graph Algorithms
Understanding graph representations (adjacency list, matrix), traversal algorithms (BFS, DFS), and classic problems like shortest path, cycle detection, and connectivity. Apply graph concepts to real-world backend scenarios.
Practice Interview
Study Questions
Trees and Tree Traversal
Deep understanding of binary trees, binary search trees, and tree traversal methods (in-order, pre-order, post-order, level-order). Ability to solve problems involving tree manipulation, searching, and balancing.
Practice Interview
Study Questions
Technical On-site Round 2 - Backend-Specific Design and Coding
What to Expect
Third technical round focusing specifically on backend concepts. This may combine coding with system design thinking or focus on backend-specific problems like API design, database querying, or infrastructure challenges. You might be asked to design a simple REST API, optimize database queries, or explain how to scale a specific backend service. For junior level, the focus is on foundational thinking rather than complex distributed systems.
Tips & Advice
This round bridges pure coding and system design. You might solve a coding problem with a backend context (e.g., design an in-memory cache). For design components: start by understanding requirements and constraints, ask clarifying questions, and discuss trade-offs. Draw diagrams if helpful. At junior level, interviewers expect familiarity with basic concepts but not deep expertise. Be specific about technologies you've used (databases, caching, queues) but admit when you lack experience. Focus on clarity of thinking over perfect solutions. Discuss scalability concerns even if not solving massive scale problems.
Focus Topics
Caching Strategies and In-Memory Storage
Understanding caching mechanisms (HTTP caching, application-level caching with Redis/Memcached). Cache invalidation strategies, TTL, and when to cache. Performance implications.
Practice Interview
Study Questions
NoSQL Databases Basics
Basic understanding of NoSQL databases (MongoDB, DynamoDB, Cassandra) and when to use them. Understanding document model, trade-offs with relational databases, eventual consistency concepts.
Practice Interview
Study Questions
Authentication, Authorization, and Security Basics
Basic understanding of authentication methods (sessions, tokens, JWT), authorization patterns, and common security concerns (SQL injection, CSRF, XSS for APIs). Best practices for handling sensitive data.
Practice Interview
Study Questions
Basic System Design and Scalability
Foundational understanding of how systems scale including concepts like horizontal scaling, load balancing, caching, and database replication. Understand trade-offs between consistency, availability, and partition tolerance.
Practice Interview
Study Questions
RESTful API Design Principles
Understanding REST principles including resource-based URLs, HTTP methods (GET, POST, PUT, DELETE), status codes, and response formats. Design simple APIs with proper versioning, error handling, and documentation considerations.
Practice Interview
Study Questions
Relational Databases and SQL
SQL proficiency including SELECT queries, JOINs, aggregations, indexing, and basic optimization. Understanding normalized vs. denormalized schemas. Query performance considerations.
Practice Interview
Study Questions
Behavioral Interview - Culture and Teamwork
What to Expect
Behavioral interview assessing cultural fit, teamwork, communication, and how you handle challenges. Interviewer asks situational questions about your past experiences to understand how you work with others, handle failures, learn from mistakes, and contribute to teams. For junior level, focus is on coachability, collaboration, and learning mindset rather than leadership.
Tips & Advice
Prepare 5-7 concrete stories from your past projects using the STAR method (Situation, Task, Action, Result). Include examples of: collaborating with others, handling a mistake or failure, learning something new, overcoming a technical challenge, and receiving constructive feedback. For junior level, focus on showing coachability and willingness to learn. Be specific with numbers and outcomes when possible. Practice telling stories concisely (3-4 minutes each). Research the company's values (Amazon's leadership principles, Meta's values, etc.) and subtly align your stories with these values. Be authentic—FAANG companies can tell when answers are rehearsed versus genuine. Show self-awareness about areas where you're still learning.
Focus Topics
Initiative and Proactivity
Taking ownership of tasks, identifying problems before being asked, proposing improvements, and volunteering for new challenges. Balance with asking for help when needed.
Practice Interview
Study Questions
Communication and Clarity
Ability to explain technical concepts clearly, ask clarifying questions, listen actively, and communicate status/blockers. Both written (documentation, messages) and verbal communication.
Practice Interview
Study Questions
Learning from Failure and Mistakes
Ability to acknowledge mistakes without defensiveness, analyze what went wrong, and extract lessons for future improvement. Examples of bugs shipped, failed optimizations, or incorrect approaches you debugged.
Practice Interview
Study Questions
Coachability and Growth Mindset
Openness to feedback, willingness to learn from more experienced developers, asking good questions, and actively seeking to improve. Examples of implementing feedback or tackling unfamiliar technologies.
Practice Interview
Study Questions
Collaboration and Teamwork
Ability to work effectively with team members, communicate clearly, support colleagues, and contribute to collective goals. Stories about pair programming, code reviews, mentoring from senior developers, or collaborative problem-solving.
Practice Interview
Study Questions
Hiring Manager Round - Role Fit and Technical Depth
What to Expect
Final round with the hiring manager or senior team member. This is often a mix of behavioral and technical discussion. The manager assesses whether you'll be successful in the specific team, discusses the role's expectations, addresses any remaining concerns from previous rounds, and evaluates alignment with team needs. May discuss your background in more depth and how you'll grow in the role.
Tips & Advice
This is your best opportunity to learn about the role and show genuine enthusiasm for the specific team. Ask thoughtful questions about the team's priorities, technical challenges, learning opportunities, and support for junior developers. Revisit the job description and mention specific aspects exciting you. Expect questions about your technical capabilities in context of actual team projects. Be prepared to discuss how you'd approach learning your team's codebase and tech stack. Show interest in the team's culture and values. This round is also where manager assesses if they want to work with you daily. Be authentic and personable. Mention how you handle on-call rotations or incident response (even if limited experience). Ask about opportunities for growth and mentorship.
Focus Topics
Stack Familiarity and Technology Choices
Knowledge of team's technology stack (languages, frameworks, databases, cloud platform, CI/CD tools). Understanding why specific choices were made. Openness to learning new technologies.
Practice Interview
Study Questions
Production and Operational Awareness
Understanding of production systems, monitoring, incident response, and operational responsibilities of backend engineers. Comfortable discussing debugging, deployments, and troubleshooting.
Practice Interview
Study Questions
Growth Trajectory and Learning Orientation
Vision for your growth as backend developer, what you want to learn, and how you approach skill development. Show ambition without unrealistic expectations at junior level.
Practice Interview
Study Questions
Technical Background and Relevant Experience
Deep dive into projects you've worked on, specific technologies you've used, and depth of your backend experience. Technical discussions at level appropriate for junior role.
Practice Interview
Study Questions
Role-Specific Expectations and Team Fit
Understanding the specific backend challenges your team faces, technologies they use, and how you'd contribute. Articulate how your skills and learning approach match team needs.
Practice Interview
Study Questions
Frequently Asked Backend Developer Interview Questions
You have the filled table dp where dp[i][j] is the maximum path sum from the top-left to cell (i, j) in a grid with moves right and down. Show how to recover one path that achieves dp[m-1][n-1], and say what you do on ties.
Sample Answer
The idea
Every cell of the table was filled as dp[i][j] = grid[i][j] + max(dp[i-1][j], dp[i][j-1]). So the cell that an optimal path used just before (i, j) is the neighbour with the larger dp value. To recover the path, start at the bottom-right cell, repeatedly step to that larger neighbour, and stop at (0, 0); then reverse the list, because you collected the cells from the end. The grid itself is not needed: the table already contains the answer to "which neighbour won".
The choice has to compare dp values, not raw grid values. A neighbour with a big cell value can still be a bad place to come from if the best sum reaching it is small.
The rules, step by step
- Start at
(m-1, n-1)and record the cell. - In the first row, the only possible predecessor is the left neighbour; in the first column, the only one is the upper neighbour. Handle these before comparing: a negative index in Python wraps to the last row instead of failing at once, so the walk would read the wrong cells.
- Otherwise compare
dp[i-1][j]withdp[i][j-1]and step to the larger. - On a tie both neighbours lead to a path with the same optimal sum, so either is correct. Pick a fixed rule (here: prefer the cell above, with
prefer="left"as the alternative) so the same table always produces the same path. Which tie rule you choose changes the path, never the sum. - When the cell is
(0, 0), stop and reverse.
Code
The program fills the table, recovers the path with both tie rules, shows a table with a tie in the last cell, runs the common bug (comparing grid values) next to the correct walk-back, and checks everything against exhaustive enumeration of all paths.
import random
def fill(grid):
"""dp[i][j] = max sum of a right/down path from (0, 0) to (i, j)."""
m, n = len(grid), len(grid[0])
dp = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
dp[i][j] = grid[i][j]
else:
up = dp[i - 1][j] if i > 0 else None
left = dp[i][j - 1] if j > 0 else None
dp[i][j] = grid[i][j] + max(v for v in (up, left) if v is not None)
return dp
def recover(dp, prefer="up"):
"""Walk back from the bottom-right cell using only the filled table.
The cell we came from is the neighbour with the larger dp value; on a tie, `prefer` decides."""
i, j = len(dp) - 1, len(dp[0]) - 1
cells = [(i, j)]
while (i, j) != (0, 0):
if i == 0:
j -= 1 # first row: only the left neighbour exists
elif j == 0:
i -= 1 # first column: only the upper neighbour exists
elif dp[i - 1][j] > dp[i][j - 1]:
i -= 1
elif dp[i - 1][j] < dp[i][j - 1]:
j -= 1
elif prefer == "up":
i -= 1
else:
j -= 1
cells.append((i, j))
cells.reverse()
return cells
def all_optimal_paths(grid):
"""Every right/down path whose sum equals the maximum (exhaustive, for checking)."""
m, n = len(grid), len(grid[0])
found = []
def go(i, j, path, total):
path.append((i, j))
total += grid[i][j]
if (i, j) == (m - 1, n - 1):
found.append((total, tuple(path)))
else:
if i + 1 < m:
go(i + 1, j, path, total)
if j + 1 < n:
go(i, j + 1, path, total)
path.pop()
go(0, 0, [], 0)
best = max(t for t, _ in found)
return [p for t, p in found if t == best], best
def wrong_recover(grid):
"""The common bug: walk back comparing raw grid values instead of dp values."""
i, j = len(grid) - 1, len(grid[0]) - 1
cells = [(i, j)]
while (i, j) != (0, 0):
if i == 0:
j -= 1
elif j == 0:
i -= 1
elif grid[i - 1][j] >= grid[i][j - 1]:
i -= 1
else:
j -= 1
cells.append((i, j))
return cells[::-1]
def total(grid, cells):
return sum(grid[i][j] for i, j in cells)
grid = [[1, 3, 1],
[1, 5, 1],
[4, 2, 1]]
dp = fill(grid)
print("dp:")
for row in dp:
print(" ", row)
for rule in ("up", "left"):
p = recover(dp, rule)
print(f"tie rule {rule}: {p} sum {total(grid, p)}")
tied = [[0, 2, 1], [2, 0, 3], [1, 3, 0]]
dpt = fill(tied)
print("tie grid dp:", dpt)
print("tie grid, up :", recover(dpt, "up"))
print("tie grid, left:", recover(dpt, "left"))
paths, best = all_optimal_paths(tied)
print("optimal paths on the tie grid:", len(paths), "with sum", best)
trap = [[0, 0, 0],
[0, 0, 5],
[9, 1, 0]]
dpw = fill(trap)
pw = wrong_recover(trap)
print("grid-value walk-back on", trap, "gives", pw, "sum", total(trap, pw), "but dp says", dpw[-1][-1])
print("dp walk-back gives", recover(dpw), "sum", total(trap, recover(dpw)))
random.seed(36)
cases = bad = tie_cases = differ = 0
for _ in range(500):
m, n = random.randint(1, 5), random.randint(1, 5)
g = [[random.randint(-3, 3) for _ in range(n)] for _ in range(m)]
d = fill(g)
opt, best = all_optimal_paths(g)
pu, pl = recover(d, "up"), recover(d, "left")
cases += 1
bad += not (tuple(pu) in opt and tuple(pl) in opt and best == d[-1][-1] == total(g, pu) == total(g, pl))
tie_cases += len(opt) > 1
differ += pu != pl
print("seeded cases:", cases, "mismatches:", bad, "| cases with several optimal paths:", tie_cases, "| cases where the two tie rules differ:", differ)
print("1x1 grid:", recover(fill([[-4]])), " single row:", recover(fill([[2, -1, 3]])), " single column:", recover(fill([[2], [-1], [3]])))
Output:
dp:
[1, 4, 5]
[2, 9, 10]
[6, 11, 12]
tie rule up: [(0, 0), (0, 1), (1, 1), (2, 1), (2, 2)] sum 12
tie rule left: [(0, 0), (0, 1), (1, 1), (2, 1), (2, 2)] sum 12
tie grid dp: [[0, 2, 3], [2, 2, 6], [3, 6, 6]]
tie grid, up : [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)]
tie grid, left: [(0, 0), (1, 0), (2, 0), (2, 1), (2, 2)]
optimal paths on the tie grid: 2 with sum 6
grid-value walk-back on [[0, 0, 0], [0, 0, 5], [9, 1, 0]] gives [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)] sum 5 but dp says 10
dp walk-back gives [(0, 0), (1, 0), (2, 0), (2, 1), (2, 2)] sum 10
seeded cases: 500 mismatches: 0 | cases with several optimal paths: 76 | cases where the two tie rules differ: 76
1x1 grid: [(0, 0)] single row: [(0, 0), (0, 1), (0, 2)] single column: [(0, 0), (1, 0), (2, 0)]
Reading the output
- On the 3 x 3 grid the path is
(0,0), (0,1), (1,1), (2,1), (2,2)with sum 1 + 3 + 5 + 2 + 1 = 12, equal todp[2][2]. Both tie rules give the same path here because no tie is met on the way back. - On the tie grid (
[[0, 2, 1], [2, 0, 3], [1, 3, 0]]) the cell(2,2)hasdp[1][2] = dp[2][1] = 6. Preferring the cell above gives the route along the top and right edge; preferring the left gives the route down the left edge and along the bottom. Exhaustive enumeration finds exactly 2 optimal paths, and each rule produces one of them. - The bug demonstration: on
[[0, 0, 0], [0, 0, 5], [9, 1, 0]]the cell above the end holds 5 and the cell to its left holds 1, so comparing raw grid values steps up, but the best sum reaching the cell above is only 5 while the best sum reaching the left cell is 10 (through the 9). The raw-value walk-back ends with sum 5, whiledpsays 10, and the correct walk-back finds the path through the 9. - The random check uses 500 seeded grids from 1 x 1 to 5 x 5 with values from -3 to 3 (negatives and zeros included): both tie rules always return a legal optimal path, and in 76 of those cases there are several optimal paths and the two rules return different ones, so the tie handling is exercised, not just present.
Complexity
- Time
O(m + n)for the walk-back: every step moves up or left by one, so at mostm + n - 2steps. For a 1 x 1 grid there are 0 steps and the path is just(0, 0). - Space
O(m + n)for the returned list; no extra table, no recursion. - Filling the table itself is
O(mn).
Common mistakes
- Comparing grid values instead of
dpvalues (the bug shown above). - Forgetting the first row and first column and indexing with -1.
- Forgetting to reverse the collected cells.
- Returning the sum of the path computed from the grid and trusting it without comparing with
dp[m-1][n-1]in a test.
Running the code
docker run --rm -v "$PWD":/w -w /w python:3.12 python grid_path_recovery.py
Save the listing as grid_path_recovery.py; it uses only the standard library.
Design a benchmarking and cost-model framework to evaluate whether adding a CDN or edge caching will reduce both latency and network egress cost for a global API. Specify metrics to capture, traffic sampling methods, geographies to test, and how to calculate expected egress savings.
Sample Answer
Direct answer
Design it as a before-and-after natural experiment: pick real vantage points in the target geographies, measure baseline latency and egress cost per region for a representative traffic sample, roll a CDN (content delivery network, a globally distributed network of cache servers close to users) out to a subset or a canary region first, remeasure the same metrics from the same vantage points, and compute expected savings by extrapolating the measured cache-hit rate and latency change to full traffic, rather than estimating either number from first principles alone.
Structured elaboration
Metrics to capture, the same ones before and after so they are comparable: latency, p50, p95, and p99 (the 50th/95th/99th percentile response times, the point below which that percent of requests fall) response time, measured per target geography rather than averaged globally, since a global average can look fine while the actual EU or APAC users you are trying to help see no change; cost, origin bytes served, CDN edge bytes served, CDN request count, and total spend, broken out by region; cache effectiveness, hit ratio, cache hits divided by total requests, and separately byte hit ratio, bytes served from cache divided by total bytes, since these can diverge when large and small objects have different hit rates; and correctness or staleness, error rate plus a sample check that cached responses match origin, which catches a misconfigured cache serving stale or wrong content that a pure performance metric would miss.
Traffic sampling method: use real production traffic, not synthetic load alone, since real traffic carries the actual request-size distribution, cacheability mix, and geographic spread that matter. Sample a representative window covering both peak and off-peak, a CDN's benefit under load can look different from its benefit at low traffic, and stratify the sample by endpoint or content type so the benchmark is not dominated by whichever endpoint happens to be called most.
Geographies to test: at minimum one location inside each target region, EU, APAC, and the origin's own region as a control, using either real-user monitoring, measuring actual users' experience directly, or synthetic monitoring probes placed in those regions, since a benchmark run only from the origin region tells you nothing about the users this is meant to help.
Rollout and measurement design: canary the CDN to a subset of traffic or one region first, a smaller blast radius if something is misconfigured, run it long enough for the cache to reach steady state, since a freshly warmed cache understates the eventual hit rate, then compare the same metrics measured the same way before and after.
Calculating expected savings: origin bytes avoided, at the measured hit ratio rather than an assumed one, times the origin egress rate, minus the CDN's bandwidth cost for bytes now served at the edge, minus the CDN's per-request fee across all requests, the same shape used elsewhere for a numeric break-even, but driven by measured inputs instead of assumed ones once the canary has run.
Worked example
If a two-week canary in the EU region measures a steady-state byte-hit-ratio of 68% on 3 TB/month of EU-region egress, origin bytes avoided is 3 x 0.68 = 2.04 TB/month, and that measured 68%, not a guessed number, is what feeds the same before-and-after cost formula used to project savings for the remaining regions once the canary is judged successful.
Trade-offs and pitfalls
A canary run too short never reaches steady-state cache warmth, making the CDN look worse, a lower hit rate, than it will be at full rollout; define a minimum canary duration relative to the content's typical TTL (time-to-live) before drawing conclusions. Measuring only from the origin's own region, the easy default for most internal tooling, hides exactly the latency problem the CDN is meant to fix; the framework has to budget for real vantage points in the target geographies, sometimes meaning paying for a synthetic-monitoring service with presence there. Comparing average latency instead of percentiles hides tail regressions; a CDN misconfiguration that makes the worst 1% of requests much slower, a cold edge or a routing issue, can be invisible in an average while still hurting real users.
How do you keep a cross-functional team aligned and moving when the people involved are spread across time zones with little or no overlap in working hours?
Sample Answer
Direct answer
Keep alignment across time zones with three levers: shrink what actually needs real-time overlap by defaulting to async updates on a fixed template, protect a small deliberately scheduled overlap window for anything that truly needs live discussion, and make handoffs explicit in writing so context transfers cleanly across the boundary instead of depending on someone's memory.
Framework
Reduce dependence on overlap. Default to async status updates on a fixed cadence, and use written decision docs rather than requiring a live meeting for every decision. Most updates don't need a room, only genuinely ambiguous or high-stakes calls do.
Protect a deliberate overlap window. Negotiate a recurring block, even a short one, and rotate who takes the inconvenient time so the burden doesn't always fall on the same region.
Make handoffs explicit. When work crosses a time-zone boundary, produce a short written artifact rather than relying on a quick chat message. This matters most in ops-heavy, always-on contexts.
Worked example
Consider an on-call rotation providing 24/7 production coverage across three time zones (for example [Region A], [Region B], and [Region C]), where the two outer regions have little or no live overlap with each other.
- Shadow and overlap periods: the incoming region's on-call shadows the outgoing region's on-call for a short deliberate window at the shift boundary, even 15 to 30 minutes, to ask questions live before the outgoing engineer signs off.
- Written handoff template: a standard document filled at every handoff covering open incidents, any systems in a degraded state, changes deployed in the last shift, and explicit 'known risk' or 'do not touch' notes.
- Escalation expectations: a written policy defining what counts as page-worthy versus a handoff note, who the secondary on-call is in each region, and how long the incoming engineer has to acknowledge before it auto-escalates.
Result: even with zero live overlap between two of the three regions, the written handoff plus the short shadow window from the middle region means each incoming on-call starts already briefed, instead of reconstructing state from raw logs.
For non-ops roles the same mechanism applies with a different artifact, for example a design or product handoff might be a written decision log plus a recorded walkthrough rather than an incident handoff, but the principle (explicit written handoff over a live conversation) is the same.
Trade-offs and pitfalls
- Repeatedly scheduling occasional syncs at painful hours burns out whichever time zone draws the short straw. Rotate it deliberately.
- Async-only breaks down for genuinely ambiguous or high-stakes decisions. Some live channel for true emergencies still has to exist.
- A handoff template that's too heavy gets skipped under time pressure. Keep it short enough to fill in within a few minutes.
- Assuming a chat message counts as a handoff is the actual failure mode this whole approach is designed to prevent. The structured artifact is the point, not the tool it's written in.
Derive the time and space complexity of a typical backtracking algorithm in terms of the branching factor b and the maximum depth d. Then apply it to generating all permutations of n elements, all k-sized combinations, and N-Queens, and explain how pruning changes the practical cost.
Sample Answer
The idea in plain words
Backtracking builds an answer one decision at a time (choose, explore, undo). The decisions form a recursion tree: the root is "nothing chosen yet", each node has up to b children (the branching factor, the choices available at that step) and the tree is at most d levels deep (the maximum depth, the number of decisions in a full answer). A tree with branching factor b and depth d has at most 1 + b + b^2 + ... + b^d nodes, which is O(b^d). Why the sum is O(b^d): for b >= 2 it equals (b^(d+1) - 1) / (b - 1), which is at most b^d * b / (b - 1), and b / (b - 1) is at most 2. The last level alone holds b^d nodes, so the sum is within a factor of two of its final term. Big-O (O) is an upper bound on growth; Theta (used below) means the growth is bounded both above and below by the same expression, so Theta(n!) says the node count really is about n! up to a constant factor. Work per node is whatever the loop and the check cost, so time is O(b^d) multiplied by the per-node cost. Space is only O(d) for the recursion plus the current path, because the undo step means only one path is alive at once (storing every answer is extra, proportional to the output).
Pruning means abandoning a branch as soon as it cannot lead to a valid answer. It does not change the worst-case bound written in terms of b and d, but it can shrink the real tree by orders of magnitude.
Counted example
from itertools import combinations, permutations
from math import comb, factorial
def permutations_bt(n):
"""All orderings of 0..n-1. Returns (count, nodes visited, deepest level)."""
nodes = deepest = count = 0
used = [False] * n
path = []
def explore():
nonlocal nodes, deepest, count
nodes += 1
deepest = max(deepest, len(path))
if len(path) == n:
count += 1
return
for x in range(n):
if not used[x]:
used[x] = True; path.append(x) # choose
explore()
path.pop(); used[x] = False # undo
explore()
return count, nodes, deepest
def combinations_bt(n, k):
"""All k-subsets of 0..n-1, extending only with larger values (start index) so no subset repeats."""
nodes = count = 0
path = []
def explore(start):
nonlocal nodes, count
nodes += 1
if len(path) == k:
count += 1
return
for x in range(start, n):
path.append(x)
explore(x + 1)
path.pop()
explore(0)
return count, nodes
def combinations_pruned(n, k):
"""Same, but stop trying values that leave too few numbers to fill the remaining slots."""
nodes = count = 0
path = []
def explore(start):
nonlocal nodes, count
nodes += 1
if len(path) == k:
count += 1
return
need = k - len(path)
for x in range(start, n - need + 1): # prune: x must leave need-1 larger values
path.append(x)
explore(x + 1)
path.pop()
explore(0)
return count, nodes
def queens(n, mode):
"""Count solutions and nodes. mode: 'free' = any column per row, test only at the end;
'columns' = never reuse a column, diagonals tested at the end; 'full' = also reject a square attacked on a diagonal."""
nodes = solutions = 0
cols = []
def attacked(row, col):
return any(c == col or abs(c - col) == row - r for r, c in enumerate(cols))
def explore(row):
nonlocal nodes, solutions
nodes += 1
if row == n:
if mode == "full" or not any(attacked_pair(i) for i in range(n)):
solutions += 1
return
for col in range(n):
if mode == "columns" and col in cols:
continue
if mode == "full" and attacked(row, col):
continue
cols.append(col)
explore(row + 1)
cols.pop()
def attacked_pair(i):
return any(cols[j] == cols[i] or abs(cols[j] - cols[i]) == i - j for j in range(i))
explore(0)
return solutions, nodes
print("permutations of n elements: leaves, nodes visited, n!, sum of n!/(n-j)! for j=0..n")
for n in range(1, 7):
count, nodes, deepest = permutations_bt(n)
formula = sum(factorial(n) // factorial(n - j) for j in range(n + 1))
print(f" n={n}: leaves={count} nodes={nodes} n!={factorial(n)} formula={formula} deepest={deepest}")
assert permutations_bt(5)[0] == len(list(permutations(range(5))))
print("k-combinations of n=8: leaves, nodes (no pruning), nodes (with pruning), C(n,k)")
for k in (2, 4, 6):
c1, n1 = combinations_bt(8, k)
c2, n2 = combinations_pruned(8, k)
assert c1 == c2 == comb(8, k) == len(list(combinations(range(8), k)))
print(f" k={k}: leaves={c1} nodes={n1} pruned_nodes={n2} C(8,{k})={comb(8, k)}")
print("N-Queens: solutions and nodes visited by pruning level")
print(" n solutions free columns full")
for n in range(4, 9):
row = [queens(n, m) for m in ("columns", "full")]
free = queens(n, "free") if n <= 6 else (None, None)
free_nodes = free[1] if free[1] is not None else "-"
free_sol = free[0] if free[0] is not None else "-"
assert free[0] in (None, row[1][0]) and row[0][0] == row[1][0]
print(f" {n} {row[1][0]:>9} {free_nodes!s:>8} {row[0][1]:>7} {row[1][1]:>5}")
Output:
permutations of n elements: leaves, nodes visited, n!, sum of n!/(n-j)! for j=0..n
n=1: leaves=1 nodes=2 n!=1 formula=2 deepest=1
n=2: leaves=2 nodes=5 n!=2 formula=5 deepest=2
n=3: leaves=6 nodes=16 n!=6 formula=16 deepest=3
n=4: leaves=24 nodes=65 n!=24 formula=65 deepest=4
n=5: leaves=120 nodes=326 n!=120 formula=326 deepest=5
n=6: leaves=720 nodes=1957 n!=720 formula=1957 deepest=6
k-combinations of n=8: leaves, nodes (no pruning), nodes (with pruning), C(n,k)
k=2: leaves=28 nodes=37 pruned_nodes=36 C(8,2)=28
k=4: leaves=70 nodes=163 pruned_nodes=126 C(8,4)=70
k=6: leaves=28 nodes=247 pruned_nodes=84 C(8,6)=28
N-Queens: solutions and nodes visited by pruning level
n solutions free columns full
4 2 341 65 17
5 10 3906 326 54
6 4 55987 1957 153
7 40 - 13700 552
8 92 - 109601 2057
Reading the code. In permutations_bt, explore is the recursion; nonlocal nodes, deepest, count lets the inner function assign to the counters of the enclosing function instead of creating new local variables. Every call to explore is one node of the recursion tree, which is why nodes += 1 counts nodes. A node's path is its prefix: the choices made so far on the way down from the root.
In queens, one queen goes in each row, and cols[r] is the column of the queen in row r. Two queens in rows r and row share a diagonal exactly when the number of columns between them equals the number of rows between them, because a diagonal step moves one row and one column together. So abs(c - col) == row - r is the diagonal test and c == col is the column test. The three modes differ only in when they apply these tests: free applies none until all rows are filled, columns forbids reusing a column while placing and tests diagonals at the end, and full rejects an attacked square the moment it is considered. The - cells for free at n=7 and n=8 mean that search was not run: it visits 1 + n + ... + n^n nodes, which is 960,800 for n=7 and 19,173,961 for n=8.
Two small trees, printed by the shipped counting logic with a print added. The first is the permutation tree for three elements, indented by level; the second is the pruned 4-Queens tree, where each list holds the columns chosen in rows 0, 1, 2, ...
def show_permutation_tree(n):
"""Print every node of the permutation recursion tree, indented by level, with a level tally."""
used = [False] * n
path = []
per_level = [0] * (n + 1)
def explore():
per_level[len(path)] += 1
print(" " * len(path) + (str(path) if path else "[] (root)"))
for x in range(n):
if not used[x]:
used[x] = True; path.append(x)
explore()
path.pop(); used[x] = False
explore()
print("nodes per level:", per_level, "total", sum(per_level))
def show_queens_tree(n):
"""Print every node of the pruned N-Queens tree: the list holds the column chosen in each row so far."""
cols = []
def attacked(row, col):
return any(c == col or abs(c - col) == row - r for r, c in enumerate(cols))
nodes = 0
def explore(row):
nonlocal nodes
nodes += 1
print(" " * row + str(cols))
if row == n:
return
for col in range(n):
if not attacked(row, col):
cols.append(col)
explore(row + 1)
cols.pop()
explore(0)
print("nodes:", nodes)
show_permutation_tree(3)
print()
show_queens_tree(4)
Output:
[] (root)
[0]
[0, 1]
[0, 1, 2]
[0, 2]
[0, 2, 1]
[1]
[1, 0]
[1, 0, 2]
[1, 2]
[1, 2, 0]
[2]
[2, 0]
[2, 0, 1]
[2, 1]
[2, 1, 0]
nodes per level: [1, 3, 6, 6] total 16
[]
[0]
[0, 2]
[0, 3]
[0, 3, 1]
[1]
[1, 3]
[1, 3, 0]
[1, 3, 0, 2]
[2]
[2, 0]
[2, 0, 3]
[2, 0, 3, 1]
[3]
[3, 0]
[3, 0, 2]
[3, 1]
nodes: 17
The permutation tree has 1 node at level 0, 3 at level 1, 32 = 6 at level 2 and 32*1 = 6 at level 3, matching n!/(n-j)! for j = 0..3 and the 16 nodes printed for n=3 above. The 4-Queens tree has 17 nodes, the figure in the table: row 0 has four options, but [0] and [3] die after one more row or two, and only [1, 3, 0, 2] and [2, 0, 3, 1] reach depth 4, the two solutions.
Permutations of n elements
Branching factor shrinks as elements are used: n choices at the root, then n-1, and so on, depth n. Nodes at level j number n!/(n-j)!, so the total is the sum of those. The run prints 1957 nodes for n=6 (the formula gives the same), of which 720 = 6! are full answers. The total is n! times the sum of 1/i! for i = 0..n, and that sum approaches e (about 2.718), so the tree has about e times n! nodes (1957 against 720 times 2.718 = 1957 for n=6), and the time is Theta(n!) nodes, and O(n * n!) if each answer is copied out at O(n). Here the bound b^d = n^n is loose, and the real count n! is much smaller, because the used-flags prune repeats.
k-sized combinations of n
Each node extends with only larger values than the last pick (a start index), so no subset is produced twice. Leaves number C(n, k), and every node is a prefix of some subset. The unpruned search visits 163 nodes for n=8, k=4 where C(8,4) is 70 leaves. Adding the prune "stop when too few values remain to fill the slots" cuts it to 126, and for k=6 from 247 to 84. For 0 <= k <= n the pruned version visits at most (k+1) * C(n,k) nodes (when k > n the loop range is empty and it visits only the root), because every node lies on the path from the root to some leaf and such a path has at most k+1 nodes; copying each answer adds a factor of k, so producing all answers costs O(k * C(n,k)). The unpruned version has no such bound: it visits C(n,0) + C(n,1) + ... + C(n,k) nodes, and when k is close to n that is far more than the answers (n=20, k=19 gives 1,048,575 nodes for 20 answers, while the pruned version visits 210). The prune is what removes the dead branches.
N-Queens
Place one queen per row, so depth is n and the branching factor is n (a column). Allowing any column and checking only at the end visits 1 + n + n^2 + ... + n^n nodes: 341 for n=4 and 55,987 for n=6. Refusing a reused column leaves the permutation tree (1957 for n=6, but diagonals are still tested only at the end). Rejecting any square attacked by an earlier queen, row by row, prunes immediately: 153 nodes for n=6, 2057 for n=8, against 109,601 for the column-only version and 16,777,216 (8^8) leaves in the unpruned tree at n=8. The solution counts 2, 10, 4, 40, 92 for n=4..8 match the known values. No tidy closed-form bound exists for the pruned search, and the worst-case statement stays O(n!) nodes: the pruned search never reuses a column, so its tree is a part of the permutation tree.
Worst case versus typical behaviour
Worst-case bounds assume pruning never fires. Typical behaviour depends on how early the check fails, how tight the check is, and the order that choices are tried, and is measured by counting nodes as above. Problems where the constraint is only checkable at the end (subset-sum on negative numbers with no bound) stay near the worst case. State clearly: the bound is O(b^d), the practical cost is whatever the node counter says.
Common mistakes
- Quoting O(n!) for combinations (the pruned search is O(k * C(n,k)); the unpruned one visits C(n,0) + ... + C(n,k) nodes) or for N-Queens without saying it is a bound that pruning beats.
- Forgetting the cost of copying each answer (an extra factor of n for permutations).
- Counting the output list as recursion space, or ignoring the O(d) stack.
- Forgetting the undo step, which makes the shared path grow wrong.
Running the code
# Python 3.12, standard library only
python backtrack_cost.py
Write a function to find the index of the maximum element in an integer array and return both the value and index. Example: arr=[3,7,2,9,5] -> return (9, 3). Discuss performance, stability, and how you'd parallelize if the array is very large.
Sample Answer
Direct answer
Scan the array once, keeping the best value and its index seen so far, and only overwrite them when you see a value strictly greater than the current best. That single pass is O(n) time and O(1) extra space, and the strict inequality is exactly what makes the result stable: if the maximum value repeats, the first occurrence is what gets returned.
Structured elaboration
The scan. Initialize max_val, max_idx from index 0, then walk the rest of the array; update only on arr[i] > max_val, never >=. Using >= would silently return the last occurrence of the maximum instead of the first, a common accidental behavior change that has nothing to do with correctness of "find the max" in the loose sense, but does violate a stability guarantee if one is expected.
Stability. "Stable" here means: when the maximum value appears more than once, the answer is well-defined and consistent (earliest index), the same sense in which a stable sort keeps equal elements in their original relative order.
Parallelizing for a very large array. Split the array into P contiguous chunks. Each worker independently runs the exact same linear scan over its own chunk (the "map" step), producing a local (value, index) pair. Combine all P local results pairwise (the "reduce" step) with a combiner that itself must resolve ties: when two chunks' local maxima are equal, keep the one from the earlier chunk, or the parallel result can silently disagree with the sequential one depending on how many workers happened to be used, which is a real correctness bug, not a style nit.
Worked example
def index_of_max(arr):
if not arr:
raise ValueError("index_of_max() arg is an empty sequence")
max_val, max_idx = arr[0], 0
for i in range(1, len(arr)):
if arr[i] > max_val:
max_val, max_idx = arr[i], i
return max_val, max_idx
def _local_argmax(arr, lo, hi):
max_val, max_idx = arr[lo], lo
for i in range(lo + 1, hi):
if arr[i] > max_val:
max_val, max_idx = arr[i], i
return max_val, max_idx
def _combine(left, right):
return right if right[0] > left[0] else left # keep LEFT (earlier) index on a tie
def index_of_max_parallel(arr, num_chunks):
n = len(arr)
num_chunks = max(1, min(num_chunks, n))
chunk_size = -(-n // num_chunks) # ceil division
local_results = [_local_argmax(arr, s, min(s + chunk_size, n)) for s in range(0, n, chunk_size)]
combined = local_results[0]
for r in local_results[1:]:
combined = _combine(combined, r)
return combined
arr = [3, 7, 2, 9, 5]
print("arr:", arr)
print("index_of_max:", index_of_max(arr))
print()
tied = [5, 9, 3, 9, 1]
print("tied array:", tied)
print("index_of_max (first occurrence of max):", index_of_max(tied))
print()
big = [4, 2, 9, 9, 1, 7, 9, 3]
print("big =", big)
seq = index_of_max(big)
for nc in [1, 2, 3, 4, 8]:
par = index_of_max_parallel(big, nc)
print(f"num_chunks={nc}: sequential={seq} parallel={par} match={seq == par}")
Output:
arr: [3, 7, 2, 9, 5]
index_of_max: (9, 3)
tied array: [5, 9, 3, 9, 1]
index_of_max (first occurrence of max): (9, 1)
big = [4, 2, 9, 9, 1, 7, 9, 3]
num_chunks=1: sequential=(9, 2) parallel=(9, 2) match=True
num_chunks=2: sequential=(9, 2) parallel=(9, 2) match=True
num_chunks=3: sequential=(9, 2) parallel=(9, 2) match=True
num_chunks=4: sequential=(9, 2) parallel=(9, 2) match=True
num_chunks=8: sequential=(9, 2) parallel=(9, 2) match=True
arr=[3,7,2,9,5] returns (9, 3), matching the question's own example exactly. The tied array [5,9,3,9,1] (max value 9 appears at indices 1 and 3) returns (9, 1), confirming the first-occurrence tie-break. The parallel reduction was cross-checked against the sequential scan across five different chunk counts (1, 2, 3, 4, and 8 workers) on an array whose max value repeats three times, and every one agrees on (9, 2), the earliest occurrence, regardless of how the array was partitioned.
Trade-offs and pitfalls
The > versus >= choice is the sharpest interview signal here: state out loud which behavior you intend for ties, since both compile and both "work" in the sense of finding a maximum.
A parallel reduce needs a combiner that resolves ties consistently with the sequential definition, or different worker counts can legitimately return different indices for the exact same input, exactly the failure mode the cross-check above rules out by testing five different partitionings against one another.
For data spread across multiple machines rather than multiple cores of one machine, the reduce step becomes a real network round trip between workers, at which point this is the same map-reduce shape used for any associative aggregate (sum, max, count), nothing about index_of_max specifically changes that.
Given customers, orders, and order_items, write a query returning each customer's distinct product count using COUNT(DISTINCT product_id) across a join chain. Explain why a plain COUNT(*) or COUNT(order_item_id) after joining through orders can overcount compared to COUNT(DISTINCT), and how NULLs from an outer join affect each form.
Sample Answer
Joining through a one-to-many relationship (customer to orders to order_items) means a plain COUNT after the join counts item-rows, not distinct products; COUNT(DISTINCT product_id) is what actually answers "how many different products".
Structured elaboration
SELECT c.customer_id, COUNT(DISTINCT oi.product_id) AS unique_products_count
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
JOIN order_items oi ON oi.order_id = o.order_id
GROUP BY c.customer_id;
Once you join customers to orders to order_items, each customer can appear once per order-item row, not once per customer. A plain COUNT(*) or COUNT(oi.product_id) after this join counts rows in the joined result, which over-counts if the customer bought the same product more than once, or simply reflects total items purchased rather than distinct products. COUNT(DISTINCT product_id) deduplicates within each customer's group, correctly answering the "how many different products" question. Separately, an outer join can introduce NULL product_ids for customers with no purchases at all; COUNT(DISTINCT ...) already ignores NULLs, so this is handled for free.
Worked example
Given one customer with two orders, one order having two order_items (products 5 and 6) and the other having one order_item (product 5 again): COUNT(oi.product_id) returns 3 (three item-rows total), while COUNT(DISTINCT oi.product_id) correctly returns 2 (products 5 and 6, with the repeat of 5 not double-counted).
Now add a second customer with zero orders at all, reached only via the outer join. For that customer, oi.product_id comes back NULL. Side by side: COUNT(*) counts that NULL row anyway, wrongly showing 1 for a customer who has made no real purchases; COUNT(oi.product_id) correctly returns 0, since COUNT of a column never counts NULLs; and COUNT(DISTINCT oi.product_id) also correctly returns 0, for the same reason. So COUNT(*) is the one form that needs the outer join's NULLs actively guarded against (or avoided by counting a non-nullable column instead), while both COUNT(oi.product_id) and COUNT(DISTINCT oi.product_id) handle them safely without any extra work.
Trade-offs and pitfalls
This is a specific instance of a broader pattern: any COUNT taken after a one-to-many join needs to be checked against what grain the join actually produced, not the grain you're mentally picturing (customers, in this case) has become. COUNT(DISTINCT) is the fix here; the more general fix for other aggregate types (SUM, AVG) is pre-aggregating before joining, covered in the double-counting question.
Compare a contiguous array (or dynamic array) with a singly linked list for random access, insertion at the head, insertion at the tail, insertion in the middle given a pointer, and iteration. Give the cost of each and say which you would choose for a workload with frequent inserts and occasional reads.
Sample Answer
The idea in plain words
A dynamic array (Python list, C++ std::vector, Java ArrayList) keeps its elements side by side in one block of memory. That gives instant access by index (the address is start + index * element_size), but inserting near the front means shifting everything after it one slot to the right. A singly linked list scatters its elements in separate nodes, each pointing at the next. That gives instant insertion next to a node you already hold (change two pointers), but reaching the k-th element means following k pointers from the head.
The whole comparison follows from those two layouts: contiguous memory buys random access and cache-friendly scans, and linked nodes buy cheap local edits. "Cache-friendly" means this: the CPU keeps a small, very fast memory (the cache) and loads memory into it in blocks of about 64 bytes at a time, so when elements are neighbours, reading one has already loaded the next few. Nodes scattered across memory get no such help.
Cost table
| Operation | Dynamic array | Singly linked list |
|---|---|---|
| Random access by index | O(1) | O(n), follow k pointers |
| Insert at head | O(n), shift all elements | O(1) |
| Insert at tail | amortized O(1) | O(n) with only a head pointer; O(1) if a tail pointer is kept |
| Insert in the middle, given the position | O(n), shift the elements after it | O(1) given the node before it; finding that node is O(n) |
| Iterate over all elements | O(n), consecutive memory | O(n), one pointer follow per element |
Amortized O(1) means the cost averaged over a whole sequence of operations is constant, even though one call can be much more expensive. An append to a full array allocates a bigger block (typically double) and copies every element, which is O(n) for that one call. Doubling keeps the total small.
Measured with counted operations
The program counts element copies for the array and next-pointer follows for the list, so the numbers do not depend on machine speed. The helper measure(label, array_fn, list_fn) zeroes both counters, runs one operation on the array (the lambda is a one-line function that delays the call until measure is ready), runs the matching operation on the list, and records the two counters as one row of the table. So each printed row answers: how many element moves did the array need, and how many pointer hops did the list need, for this one operation on about 1000 elements.
import sys
class DynArray:
"""Growable array: doubles its capacity when full. `moves` counts element copies."""
def __init__(self):
self.cap, self.n, self.data, self.moves = 1, 0, [None], 0
def append(self, x):
if self.n == self.cap: # full: allocate double and copy everything
self.data = self.data + [None] * self.cap
self.moves += self.n
self.cap *= 2
self.data[self.n] = x
self.n += 1
def insert(self, i, x):
self.append(None) # make room (amortized O(1))
for j in range(self.n - 1, i, -1): # shift the tail one slot right
self.data[j] = self.data[j - 1]
self.moves += 1
self.data[i] = x
def get(self, i):
return self.data[i] # one step
class Node:
__slots__ = ("val", "next")
def __init__(self, val, next=None):
self.val, self.next = val, next
class LinkedList:
"""Singly linked list. `hops` counts next-pointer follows."""
def __init__(self):
self.head = None
self.hops = 0
def push_front(self, x):
self.head = Node(x, self.head)
def get(self, i):
node = self.head
for _ in range(i):
node = node.next
self.hops += 1
return node
def push_back(self, x): # no tail pointer: walk to the end
node = Node(x)
if not self.head:
self.head = node
return
cur = self.head
while cur.next:
cur = cur.next
self.hops += 1
cur.next = node
def insert_after(self, node, x): # given the node: no walk
node.next = Node(x, node.next)
N = 1000
arr, lst = DynArray(), LinkedList()
for i in range(N):
arr.append(i)
print(f"{N} appends to the doubling array copied {arr.moves} elements in total (capacity {arr.cap})")
for i in range(N - 1, -1, -1):
lst.push_front(i)
rows = []
def measure(label, array_fn, list_fn):
arr.moves, lst.hops = 0, 0
array_fn()
list_fn()
rows.append((label, arr.moves, lst.hops))
measure("random access, index 500", lambda: arr.get(500), lambda: lst.get(500))
measure("insert at head", lambda: arr.insert(0, -1), lambda: lst.push_front(-1))
mid = lst.get(500) # a pointer we already hold
measure("insert in middle, position 500", lambda: arr.insert(500, -2), lambda: lst.insert_after(mid, -2))
measure("insert at tail, no tail pointer", lambda: arr.append(-3), lambda: lst.push_back(-3))
print(f"{'operation (list of ~1000)':<34}{'array element moves':>20}{'list pointer hops':>19}")
for label, a, l in rows:
print(f"{label:<34}{a:>20}{l:>19}")
steps_array = sum(1 for _ in range(arr.n))
steps_list, node = 0, lst.head
while node:
steps_list += 1
node = node.next
print(f"iteration: the array loop takes {steps_array} steps and the list loop {steps_list} (one per element either way)")
n = 100_000
as_list = list(range(n))
appended = []
for v in range(n):
appended.append(v)
nodes = None
for v in reversed(range(n)):
nodes = Node(v, nodes)
node_bytes = sys.getsizeof(Node(0))
print(f"Python {sys.version.split()[0]}: list of {n} items: {sys.getsizeof(as_list)} bytes of references; "
f"{sys.getsizeof(appended)} bytes when grown by append; "
f"{n} linked nodes: {n * node_bytes} bytes ({node_bytes} per node)")
Run with Python 3.12.15, it prints:
1000 appends to the doubling array copied 1023 elements in total (capacity 1024)
operation (list of ~1000) array element moves list pointer hops
random access, index 500 0 500
insert at head 1000 0
insert in middle, position 500 501 0
insert at tail, no tail pointer 0 1001
iteration: the array loop takes 1003 steps and the list loop 1003 (one per element either way)
Python 3.12.15: list of 100000 items: 800056 bytes of references; 800984 bytes when grown by append; 100000 linked nodes: 4800000 bytes (48 per node)
How to read it:
- Resizing. 1000 appends to the doubling array copied 1023 elements in total (1 + 2 + 4 + ... + 512), about one copy per append. One single append can copy hundreds of elements, which is why the claim is amortized and not worst case. The cost that matters in latency-sensitive code is that spike: the append that triggers a resize is slow.
- Random access. The array needs one index calculation; the list followed 500 pointers to reach index 500.
- Insert at head. The array shifted 1000 elements; the list did no pointer follows at all.
- Insert in the middle. The array shifted 501 elements. The list inserted after a node the code already held (found by an earlier walk) with 0 hops. Without that held node, the list needs the walk first, and both structures are O(n).
- Insert at tail. With no tail pointer the list walked 1001 nodes; the array just appended.
- Iteration. Both loops take one step per element (1003 elements because three were inserted above). The difference in practice is hardware: the array's elements are neighbours in memory, so a scan is fast, while list nodes may be anywhere.
- Memory overhead per node. The list of 100000 references takes about 800 KB (8 bytes per slot, 800984 bytes when grown by append, which includes spare capacity). Linked nodes took 48 bytes each on this Python build, 4800000 bytes in total, six times more, because each node is an object with its own header plus a value reference and a next reference. In C on a 64-bit platform a node holding an
intis typically 16 bytes (4-byte value, padding, 8-byte pointer) against 4 bytes per array element, before the allocator's own per-allocation overhead. Padding means unused bytes the compiler inserts so the 8-byte pointer starts at an address divisible by 8. Allocator overhead means the bookkeeping the memory allocator (mallocin C) keeps for every separate allocation, so a node costs more than its own fields. The C program below prints both for a two-field node:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct node { int value; struct node *next; };
int main(void) {
struct node *a = malloc(sizeof *a);
struct node *b = malloc(sizeof *b);
printf("sizeof(struct node) = %zu (int 4 + padding 4 + pointer 8)\n", sizeof *a);
printf("usable bytes behind a 16-byte request (glibc): %zu\n", malloc_usable_size(a));
long gap = (char *)b - (char *)a;
printf("distance between two back-to-back nodes: %ld bytes\n", gap < 0 ? -gap : gap);
free(a);
free(b);
return 0;
}
Compiled with gcc in a python:3.12 (Debian, glibc) container, it prints:
sizeof(struct node) = 16 (int 4 + padding 4 + pointer 8)
usable bytes behind a 16-byte request (glibc): 24
distance between two back-to-back nodes: 32 bytes
The 16-byte node was placed 32 bytes after the previous one: in a long chain of such nodes each one uses 32 bytes, of which 4 hold the value and 8 hold the pointer; the other 20 are padding (4) and the allocator's header and rounding (16). This gap is specific to glibc; other allocators differ.
The choice for frequent inserts and occasional reads
Commit to the linked list when inserts happen at the head or next to nodes you already hold (an undo stack where each action is pushed on the front, a work queue where new jobs are added at the front, an LRU list (least recently used: the entries ordered by when they were last touched) where a touched entry is moved to the front, a text editor cursor), reads are rare, and the elements are large or must keep a stable address. Commit to the dynamic array when the inserts are appends, or inserts at an index you must search for first, because then the list's walk to the position costs O(n) anyway and the array's shift is a fast block move on contiguous memory. What would flip the decision: the reads become frequent, the data is small (list overhead dominates), or you need indexing.
If the inserts are at both ends, use a deque (a double-ended queue, usually built from a circular buffer or a list of fixed-size blocks) instead of either. A circular buffer is an array treated as a ring: a head index and a count, with indices wrapping around the end by using % capacity, so removing from the front just moves the head index forward and shifts nothing.
How one use case maps to the held-node case
A text editor shows it. The editor holds a reference to the node at the cursor. Typing a character is "insert after the node I already hold", which is the 0-hop row of the table. An array-backed text must shift everything after the cursor on every keystroke. The program types X then Y after abc in abcdef both ways:
hops = 0 # counts next-pointer follows made while searching from the head
class Node:
def __init__(self, ch, nxt=None):
self.ch, self.next = ch, nxt
def walk_to(head, k):
"""Return the k-th node by following next pointers from the head, counting each follow."""
global hops
node = head
for _ in range(k):
node = node.next
hops += 1
return node
def text_of(head):
out = []
while head:
out.append(head.ch)
head = head.next
return "".join(out)
# A text editor holding "abcdef" with the cursor after "c".
head = None
for ch in reversed("abcdef"):
head = Node(ch, head)
cursor = walk_to(head, 2) # node "c": found once by a walk, then kept
print(f"finding the cursor node from the head took {hops} pointer hops")
hops = 0
for typed in "XY": # each keystroke inserts right after the held node
cursor.next = Node(typed, cursor.next)
cursor = cursor.next # the cursor moves onto the new node
print(f"list after typing {typed!r}: {text_of(head)} (pointer hops: {hops})")
chars, moves = list("abcdef"), 0
pos = 3 # cursor position after "c"
for typed in "XY":
chars.append(None) # grow by one slot
for j in range(len(chars) - 1, pos, -1):
chars[j] = chars[j - 1] # shift the tail one slot right
moves += 1
chars[pos] = typed
pos += 1
print(f"array after typing {typed!r}: {''.join(chars)} (elements moved so far: {moves})")
# Chunked (unrolled) list: up to 4 elements per node.
CHUNK = 4
chunks = []
for v in range(10):
if not chunks or len(chunks[-1]) == CHUNK:
chunks.append([]) # a full chunk: start a new node
chunks[-1].append(v)
print("chunks:", chunks)
print(f"next pointers: {len(chunks)} for {sum(map(len, chunks))} elements, "
f"against {sum(map(len, chunks))} for a plain linked list")
print("with 64 elements per chunk, one 8-byte pointer is shared:", 8 / 64, "bytes per element")
Run with Python 3.12.15, it prints:
finding the cursor node from the head took 2 pointer hops
list after typing 'X': abcXdef (pointer hops: 0)
list after typing 'Y': abcXYdef (pointer hops: 0)
array after typing 'X': abcXdef (elements moved so far: 3)
array after typing 'Y': abcXYdef (elements moved so far: 6)
chunks: [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]]
next pointers: 3 for 10 elements, against 10 for a plain linked list
with 64 elements per chunk, one 8-byte pointer is shared: 0.125 bytes per element
The only pointer hops were the 2 spent finding the cursor node the first time; each keystroke after that reported 0 because the cursor node was kept between keystrokes (a version that walked from the head again before each keystroke would report 2 and then 3 more hops). The array moved 3 elements for the first keystroke and 3 more for the second. That is the whole reason the "frequent inserts" workload leans toward a list when the inserts cluster around a held position, and leans away once every insert first has to search for its position.
Chunked structures and streaming ingestion
For data that arrives continuously and whose size is unknown, a plain array has to copy everything on each resize, with a latency spike (one operation that is occasionally far slower than the usual, which the user sees as a stutter), and it needs one contiguous block. A chunked (unrolled) list stores several elements per node, for example 64 in a small array per node. The printout above shows the shape with a chunk size of 4: ten elements sit in three nodes, [0 1 2 3] [4 5 6 7] [8 9], so there are 3 next pointers instead of 10, and one 8-byte pointer shared by 64 elements is 0.125 bytes per element. The chunk size is a trade: a bigger chunk spreads the pointer and allocation overhead over more elements and scans faster, but an insert in the middle must shift more elements inside one chunk. Sizes of a few cache lines (a cache line is the 64-byte block mentioned above) are a typical starting point. Appends fill the last chunk or allocate a new one, no existing data is ever copied, and the per-node overhead is shared by many elements. It keeps most of the array's scan speed too. Block-based deques use the same idea.
Converting between the two
Array to list: one pass, O(n) time, n node allocations. List to array: one pass with a known length, O(n) time and one allocation, or amortized appends if the length is unknown. Do it once when the workload changes phase (build with inserts, then freeze into an array for many reads), rather than repeatedly.
Common mistakes
- Saying a linked list insertion is O(1) without saying that the node must already be in hand.
- Saying array insertion at the end is O(1) without the word amortized.
- Ignoring the per-node memory and allocation cost, and treating Big-O as the whole story.
- Forgetting that a tail pointer fixes tail insertion on a list, but not tail deletion in a singly linked list (that needs the predecessor).
Running the code
docker run --rm -v "$PWD":/w -w /w python:3.12 python array_vs_list.py
Save the listing as array_vs_list.py. It uses only the standard library.
Design an Attribute-Based Access Control (ABAC) system for a platform that requires dynamic, context-sensitive policies. Describe: a policy language/representation, how to source attributes (user, resource, environment), policy evaluation order and conflict resolution, caching for performance, attribute freshness guarantees, and how to interoperate with an existing RBAC system for backward compatibility.
Sample Answer
Direct answer
Represent policies in a declarative attribute-matching language, either structured JSON/YAML rule documents for simple deployments or a general policy language like Rego for real branching logic, evaluated by a policy decision point that pulls attributes from three distinct sources at request time: the identity provider for subject attributes, a resource metadata service for resource attributes (including sensitivity labels), and the request itself for environment context (time, network, tenant). Bridge the existing role-based access control (RBAC) system into attribute-based access control (ABAC) by treating a user's role as one more attribute a policy can reference, rather than replacing role assignments outright, so day-one interoperation is "add context-sensitive rules on top", not "migrate every existing permission".
Structured elaboration
Policy language and representation
- Use a declarative representation, not imperative code, so policies stay auditable and independently reviewable without reading application source: either a structured rule format (
{"effect": "allow", "condition": {...}}) for simple deployments, or a general policy language like Rego for real branching. - Each rule names the attributes it reads, a condition expression, an effect (Allow/Deny), and a priority, stored versioned and separate from the evaluator's own code, since a policy is data and data needs a change history.
Attribute sourcing (user, resource, environment)
- User attributes: sourced from the identity provider or directory at authentication time and embedded in or referenced by the session (role, department, clearance level).
- Resource attributes: sourced from the resource metadata store the application already maintains, for example a document's
tenant_idanddata_sensitivitylabel, fetched by resource id or attached as tags at write time so evaluation doesn't need a fresh lookup for static attributes. - Environment attributes: computed at request time and never stored (current time, calling network, device posture); these have no freshness question by construction, since they are generated fresh on every request.
- A policy information point (PIP) layer is the architectural name for the component responsible for fetching each attribute type from its actual source and handing it to the evaluator in one uniform shape, so the evaluator itself never needs to know whether an attribute came from the identity provider or the resource store.
Policy evaluation order and conflict resolution
- Multiple rules can match the same request with conflicting effects; resolve with an explicit combining algorithm, not "whichever rule happens to be listed first". Deny-overrides (any matching Deny wins regardless of how many Allows also matched) is the safe default, since it fails closed.
- Order rules by specificity within that combining algorithm (a rule naming an exact resource id can override a broader rule naming only a resource type), and keep an explicit documented default (deny if nothing matches), so "no rule mentions this case" can never silently mean allow.
Caching for performance
- Cache resource attributes, which change far less often than the request rate, with an explicit TTL and invalidate on write (evict a document's cache entry immediately when its sensitivity label changes, rather than waiting out the TTL).
- Cache full decisions per (subject, resource, action) tuple only when environment attributes are not part of the matched policy for that tuple, since an environment-dependent decision cannot be safely cached across requests without also caching the environment inputs, which defeats the purpose.
Attribute freshness guarantees
- State a different guarantee per attribute class rather than one blanket number: environment attributes are always fresh (computed per request); resource attributes are fresh within their cache TTL or immediately on a tracked write-path invalidation; user attributes are only as fresh as the identity provider's own session refresh cadence, often the loosest guarantee in the system (a role change may not take effect until the session token is refreshed), and that gap should be a stated, known property of the design, not a surprise found in an incident review.
RBAC interoperation for backward compatibility
- Do not replace the RBAC role-assignment tables. Expose "user has role X" as one more attribute the ABAC evaluator can read, a role-as-attribute bridge, so every existing RBAC-only permission check keeps working unmodified as a degenerate ABAC policy that only inspects the role attribute.
- New context-sensitive rules layer in incrementally alongside existing role checks (a rule such as "Allow if role=analyst AND resource.tenant_id == subject.tenant_id AND resource.data_sensitivity != 'restricted'" adds tenant and sensitivity context on top of a role check that already existed), the concrete migration path: RBAC is never ripped out, ABAC grows around it.
A second concrete domain this same design generalizes to: a data lake. The same policy language, attribute-sourcing model, conflict-resolution algorithm, and caching approach apply directly to a data lake serving analytics teams and external partners, with a different attribute set in place of the SaaS example's tenant_id: team (owning team), project, data_sensitivity, and data_location (a residency/region attribute). Two things shift in emphasis for this domain:
- Attribute sourcing leans harder on tag propagation through data lineage rather than a live per-request lookup, since a data lake's resource attributes (a table's sensitivity label) are set once by an ingestion pipeline and inherited by every downstream derived table, not attached at request time the way a SaaS request's
tenant_idis. - The conflict-resolution default must make inheritance itself narrow-only: a derived table produced by joining a confidential source with a public one must inherit AT LEAST confidential, never a diluted average of its inputs, mirroring the same fail-closed instinct as the deny-overrides default described above. Concretely, a table-materialization job that joins a
raw_customerstable (data_sensitivity=confidential) with aneventstable (data_sensitivity=internal) must propagate confidential to its output by default; an engineer can explicitly re-classify the result down to internal only as a deliberate, justified, logged action, never as the automatic result of inheriting the lower of its two sources' labels.
Worked example
Concrete rules for a multi-tenant SaaS platform, using the tenant_id and data_sensitivity attributes anchoring this scenario:
[
{
"id": "deny-cross-tenant",
"effect": "Deny",
"priority": 0,
"condition": {"attr": "resource.tenant_id", "op": "neq", "value_from": "subject.tenant_id"}
},
{
"id": "allow-analyst-same-tenant-nonrestricted",
"effect": "Allow",
"priority": 10,
"condition": {
"all": [
{"attr": "subject.role", "op": "eq", "value": "analyst"},
{"attr": "resource.tenant_id", "op": "eq", "value_from": "subject.tenant_id"},
{"attr": "resource.data_sensitivity", "op": "neq", "value": "restricted"}
]
}
}
]
Combining algorithm: deny-overrides. Trace two requests by hand:
Request A: subject.role=analyst, subject.tenant_id="acme", resource.tenant_id="acme", resource.data_sensitivity="internal".
deny-cross-tenant: isresource.tenant_id("acme") not equal tosubject.tenant_id("acme")? No, they're equal, rule does not match.allow-analyst-same-tenant-nonrestricted: role is analyst (true), tenant_id matches (true), sensitivity is not restricted (true), all three hold, rule matches, Allow.- No Deny matched, one Allow matched: decision = Allow, matched rule
allow-analyst-same-tenant-nonrestricted.
Request B: subject.role=analyst, subject.tenant_id="acme", resource.tenant_id="globex", resource.data_sensitivity="internal".
deny-cross-tenant: isresource.tenant_id("globex") not equal tosubject.tenant_id("acme")? Yes, rule matches, Deny.allow-analyst-same-tenant-nonrestricted: tenant_id condition fails (globex != acme), rule does not match.- Deny-overrides: decision = Deny, matched rule
deny-cross-tenant, regardless of evaluation order.
Trade-offs and pitfalls
- Deny-overrides is the safe default but can surprise policy authors who expect "the most specific rule wins" semantics; document the combining algorithm prominently, since a policy set with only Allow rules and an implicit default-deny reads very differently in your head than one where an explicit broad Deny rule can silently veto a much more specific Allow written afterward.
- Caching full decisions for policies that reference environment attributes is a classic bug pattern: caching a time-of-day-gated Allow past the boundary it was computed against serves a decision that is now wrong but looks like a correct cache hit; only cache full decisions for attribute combinations that exclude environment attributes.
- The role-as-attribute bridge is powerful precisely because it changes nothing about RBAC, but that also means it inherits every problem RBAC already had (role sprawl, stale role assignments); ABAC context rules layered on top narrow the blast radius of a stale role assignment, they do not fix the assignment itself.
- User-attribute freshness lagging behind an identity-provider session refresh is often the quietest gap in the whole design: a just-revoked role can still pass the role-as-attribute check until the session naturally refreshes, so any high-consequence role change needs an explicit session-invalidation step, not just an identity-provider record update.
Compare bubble, selection, insertion, merge, quick and heap sort: best, average and worst-case time, extra space, whether each is stable, and whether each is in place. When would you actually pick each one?
Sample Answer
The idea in plain words
Six sorts, four questions each. Two terms first. Stable means records with equal keys come out in the order they went in. In place means the sort rearranges the input using only a small amount of extra memory (a handful of variables, or a stack of about log n frames), not a second copy of the data.
The shape to remember: three simple sorts (bubble, selection, insertion) are O(n^2) in the worst case, and three are O(n log n) (merge, quick, heap) with different trade-offs: merge is stable but needs a buffer, quick is fastest on average but has an O(n^2) worst case, heap has the best guarantee on memory and time but is not stable and is cache-unfriendly.
How each of the six works
Big-O notation says how the work grows with n, the number of items. O(n) means roughly proportional to n, O(n^2) means that doubling n about quadruples the work, O(n log n) is slightly more than proportional to n, and O(1) means a fixed amount whatever n is.
- Bubble: sweep left to right, swapping any adjacent pair that is out of order. Each sweep carries the largest remaining item to the end, so after k sweeps the last k places are final. If a whole sweep makes no swap, the list is sorted and it stops.
- Selection: find the smallest item in the unsorted part, swap it into the next front position, repeat. It makes at most n - 1 swaps, but always scans everything that is left.
- Insertion: keep a sorted prefix. Take the next item and slide it left past every larger item in the prefix until it fits, like sorting a hand of playing cards.
- Merge: split the list in half, sort each half the same way, then merge the two sorted halves by repeatedly taking the smaller front item. The merged result needs a separate buffer.
- Quick: pick a pivot (here the last item), move everything smaller than it to its left and everything else to its right, which puts the pivot in its final place, then sort the two sides the same way. A good pivot splits the range about in half; a pivot that is the smallest or largest item splits it as unevenly as possible, which is the O(n^2) case.
- Heap: first arrange the array as a max-heap, a binary tree stored in the array where each parent is at least as large as its children (the children of index i are at 2i + 1 and 2i + 2). The largest item is then at index 0. Swap it with the last item of the heap part, shrink the heap by one, and
sift_down(push the new root down, swapping with its larger child, until it is at least as large as both children). Repeat until the heap is empty.
This program runs each of them on four items and prints the state after every step:
start = [3, 4, 1, 2]
def bubble(a):
a = a[:]
for end in range(len(a) - 1, 0, -1):
for i in range(end):
if a[i] > a[i + 1]:
a[i], a[i + 1] = a[i + 1], a[i]
print(" after pass ending at index", end, ":", a)
def selection(a):
a = a[:]
for i in range(len(a) - 1):
m = min(range(i, len(a)), key=lambda j: a[j])
a[i], a[m] = a[m], a[i]
print(f" position {i}: smallest of the rest is at index {m}, swap ->", a)
def insertion(a):
a = a[:]
for i in range(1, len(a)):
item, j = a[i], i - 1
while j >= 0 and a[j] > item:
a[j + 1] = a[j]
j -= 1
a[j + 1] = item
print(f" insert {item}: sorted prefix is now", a[:i + 1], "rest", a[i + 1:])
def merge(a):
if len(a) <= 1:
return a
mid = len(a) // 2
left, right = merge(a[:mid]), merge(a[mid:])
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
if right[j] < left[i]:
out.append(right[j]); j += 1
else:
out.append(left[i]); i += 1
out += left[i:] + right[j:]
print(" merge", left, "and", right, "->", out)
return out
def quick(a, lo, hi):
if lo >= hi:
return
pivot, i = a[hi], lo
before = a[lo:hi + 1]
for j in range(lo, hi):
if a[j] < pivot:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[hi] = a[hi], a[i]
print(f" part {before}, pivot {pivot} (its last item) lands at index {i} ->", a)
quick(a, lo, i - 1)
quick(a, i + 1, hi)
def heap(a):
a = a[:]
n = len(a)
def sift_down(root, size):
while 2 * root + 1 < size:
child = 2 * root + 1
if child + 1 < size and a[child] < a[child + 1]:
child += 1
if a[root] < a[child]:
a[root], a[child] = a[child], a[root]
root = child
else:
return
for s in range(n // 2 - 1, -1, -1):
sift_down(s, n)
print(" max-heap built (parent of index i is at (i-1)//2):", a)
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sift_down(0, end)
print(f" max moved to index {end}, heap part a[0:{end}] repaired ->", a)
print("start", start)
print("bubble"); bubble(start)
print("selection"); selection(start)
print("insertion"); insertion(start)
print("merge"); print(" result", merge(start))
print("quick"); q = start[:]; quick(q, 0, len(q) - 1); print(" result", q)
print("heap"); heap(start)
Output (python:3.12):
start [3, 4, 1, 2]
bubble
after pass ending at index 3 : [3, 1, 2, 4]
after pass ending at index 2 : [1, 2, 3, 4]
after pass ending at index 1 : [1, 2, 3, 4]
selection
position 0: smallest of the rest is at index 2, swap -> [1, 4, 3, 2]
position 1: smallest of the rest is at index 3, swap -> [1, 2, 3, 4]
position 2: smallest of the rest is at index 2, swap -> [1, 2, 3, 4]
insertion
insert 4: sorted prefix is now [3, 4] rest [1, 2]
insert 1: sorted prefix is now [1, 3, 4] rest [2]
insert 2: sorted prefix is now [1, 2, 3, 4] rest []
merge
merge [3] and [4] -> [3, 4]
merge [1] and [2] -> [1, 2]
merge [3, 4] and [1, 2] -> [1, 2, 3, 4]
result [1, 2, 3, 4]
quick
part [3, 4, 1, 2], pivot 2 (its last item) lands at index 1 -> [1, 2, 3, 4]
part [3, 4], pivot 4 (its last item) lands at index 3 -> [1, 2, 3, 4]
result [1, 2, 3, 4]
heap
max-heap built (parent of index i is at (i-1)//2): [4, 3, 1, 2]
max moved to index 3, heap part a[0:3] repaired -> [3, 2, 1, 4]
max moved to index 2, heap part a[0:2] repaired -> [2, 1, 3, 4]
max moved to index 1, heap part a[0:1] repaired -> [1, 2, 3, 4]
In the bubble lines the 4 travels to the end in the first sweep. In the insertion lines the part before "rest" is the sorted prefix. In the merge lines two sorted parts are combined into one. In the heap lines the array is the heap followed by the finished tail, and the tail grows by one item each step.
Terms used in the table and the picking guide: locality and cache behaviour describe how the CPU's small fast memory (the cache) works best when a program reads neighbouring memory addresses in order. Quicksort and merge sort sweep through neighbouring items, so they do that well; heap sort jumps between index i and 2i + 1, so it is described as cache-unfriendly. Median-of-three picks the middle value of the first, middle and last items as the pivot, which avoids the worst case on sorted input. A hybrid sort combines algorithms, for example quicksort that switches to insertion sort for tiny ranges, and introsort is quicksort that switches to heap sort when its recursion gets too deep, so its worst case stays O(n log n). The "stack of log n frames" is the recursion's bookkeeping memory: each recursive call keeps its position on a stack, and halving the range each time means about log2 n calls are active at once. An embedded system is a small device (a microcontroller) with very little memory.
The comparison
| Sort | Best | Average | Worst | Extra space | Stable | In place |
|---|---|---|---|---|---|---|
| Bubble (with early exit) | O(n) | O(n^2) | O(n^2) | O(1) | Yes | Yes |
| Selection | O(n^2) | O(n^2) | O(n^2) | O(1) | No (swap version) | Yes |
| Insertion | O(n) | O(n^2) | O(n^2) | O(1) | Yes | Yes |
| Merge | O(n log n) | O(n log n) | O(n log n) | O(n) for arrays | Yes | No |
| Quick (last-element pivot, as coded) | O(n log n) | O(n log n) | O(n^2) | O(log n) stack on average, O(n) stack worst case | No | Yes (apart from the stack) |
| Heap | O(n log n) | O(n log n) | O(n log n) | O(1) | No | Yes |
In the table, the best-case column is for a particular input: already sorted data for bubble with early exit and for insertion (one look at each neighbour, nothing to move); any input for merge sort (1024 comparisons on both the sorted and the reversed input below) and for selection sort (it scans everything whatever the input); an input whose pivots split the range near the middle for quicksort (sorted input is its worst case here, not its best); and an input with distinct keys for heap sort. The measuring program below implements all six on keys that count every comparison, and measures comparisons for n = 256 on random, already-sorted and reverse-sorted input. The quicksort uses the last element as the pivot, so the worst case is any sorted or reversed input, exactly as the table says. A randomized or median-of-three pivot removes that particular trigger but not the O(n^2) worst case in principle.
import random
C = {"cmp": 0, "moves": 0} # key comparisons, and swaps / shifts / writes
class K:
"""A key with a tag. Comparing keys counts one comparison; the tag is ignored."""
__slots__ = ("v", "tag")
def __init__(self, v, tag=0):
self.v, self.tag = v, tag
def __lt__(self, other):
C["cmp"] += 1
return self.v < other.v
def __gt__(self, other):
C["cmp"] += 1
return self.v > other.v
def bubble(a):
n = len(a)
for end in range(n - 1, 0, -1):
swapped = False
for i in range(end):
if a[i] > a[i + 1]:
a[i], a[i + 1] = a[i + 1], a[i]
C["moves"] += 1
swapped = True
if not swapped: # a full pass with no swap: already sorted
break
def selection(a):
n = len(a)
for i in range(n - 1):
m = i
for j in range(i + 1, n):
if a[j] < a[m]:
m = j
if m != i:
a[i], a[m] = a[m], a[i] # long-distance swap: this is what breaks stability
C["moves"] += 1
def insertion(a):
for i in range(1, len(a)):
item, j = a[i], i - 1
while j >= 0 and a[j] > item:
a[j + 1] = a[j]
C["moves"] += 1
j -= 1
a[j + 1] = item
def merge_sort(a):
if len(a) <= 1:
return a
mid = len(a) // 2
left, right = merge_sort(a[:mid]), merge_sort(a[mid:])
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
if right[j] < left[i]: # strict: ties take the left item first
out.append(right[j]); j += 1
else:
out.append(left[i]); i += 1
C["moves"] += 1
rest = left[i:] + right[j:]
C["moves"] += len(rest)
return out + rest
def quick(a, lo=0, hi=None):
"""Lomuto partition, LAST element as pivot, recurses on both sides."""
if hi is None:
hi = len(a) - 1
if lo >= hi:
return
pivot, i = a[hi], lo
for j in range(lo, hi):
if a[j] < pivot:
a[i], a[j] = a[j], a[i]
C["moves"] += 1
i += 1
a[i], a[hi] = a[hi], a[i]
C["moves"] += 1
quick(a, lo, i - 1)
quick(a, i + 1, hi)
def heap_sort(a):
n = len(a)
def sift_down(root, size):
while 2 * root + 1 < size:
child = 2 * root + 1
if child + 1 < size and a[child] < a[child + 1]:
child += 1
if a[root] < a[child]:
a[root], a[child] = a[child], a[root]
C["moves"] += 1
root = child
else:
return
for start in range(n // 2 - 1, -1, -1): # build a max-heap
sift_down(start, n)
for end in range(n - 1, 0, -1): # move the max to the end, shrink the heap
a[0], a[end] = a[end], a[0]
C["moves"] += 1
sift_down(0, end)
SORTS = [("bubble", bubble), ("selection", selection), ("insertion", insertion),
("merge", lambda a: a.__setitem__(slice(None), merge_sort(a))),
("quick", quick), ("heap", heap_sort)]
def measure(fn, values):
arr = [K(v) for v in values]
C["cmp"] = C["moves"] = 0
fn(arr)
assert [k.v for k in arr] == sorted(values)
return C["cmp"], C["moves"]
if __name__ == "__main__":
n = 256
rnd = random.Random(1)
inputs = {"random": [rnd.randint(0, 10**6) for _ in range(n)],
"sorted": list(range(n)),
"reversed": list(range(n, 0, -1))}
print(f"comparisons, n={n}")
print(f"{'':10s}" + "".join(f"{name:>10s}" for name in inputs))
for name, fn in SORTS:
row = [measure(fn, vals)[0] for vals in inputs.values()]
print(f"{name:10s}" + "".join(f"{c:10d}" for c in row))
inv = sum(1 for i in range(n) for j in range(i + 1, n) if inputs["random"][i] > inputs["random"][j])
print(f"\nrandom input: inversions={inv}")
for name, fn in SORTS[:3]:
print(f" {name:10s} swaps/shifts={measure(fn, inputs['random'])[1]}")
# Stability: keys 0..3, each tagged with its input position. Does any tie reorder?
print("\nstable?")
rnd = random.Random(9)
for name, fn in SORTS:
stable = True
for _ in range(200):
arr = [K(rnd.randint(0, 3), tag) for tag in range(12)]
fn(arr)
if any(x.v == y.v and x.tag > y.tag for x, y in zip(arr, arr[1:])):
stable = False
break
print(f" {name:10s} {stable}")
Run in a python:3.12 container (Python 3.12), it prints:
comparisons, n=256
random sorted reversed
bubble 32469 255 32640
selection 32640 32640 32640
insertion 16918 255 32640
merge 1733 1024 1024
quick 2544 32640 32640
heap 3292 3452 3106
random input: inversions=16667
bubble swaps/shifts=16667
selection swaps/shifts=247
insertion swaps/shifts=16667
stable?
bubble True
selection False
insertion True
merge True
quick False
heap False
Reading the measurements
- Bubble and insertion use only 255 comparisons on sorted input (n - 1: one look at each neighbour) and 32640 on reversed input, which is n(n - 1)/2. That is the O(n) best case and the O(n^2) worst case in numbers. On random input bubble does about twice the comparisons of insertion (32469 against 16918).
- Selection does 32640 comparisons whatever the input. It cannot exit early because it must scan all the remaining elements to be sure of the minimum. Its strength is the swap count: 247 swaps on the random input, at most n - 1 by construction, against 16667 for bubble.
- Inversions (pairs that are out of order) explain the other two: the random input has 16667 of them, and bubble's swap count and insertion's shift count are both exactly 16667. Each adjacent swap or shift removes exactly one inversion, which is why both are fast on nearly sorted data.
- Merge needs 1024 comparisons on sorted or reversed input and 1733 on random: it is O(n log n) in all cases (n/2 times log2 n is 1024).
- Quick needs 2544 comparisons on random input and 32640 on sorted or reversed input. That is the O(n^2) worst case of the pivot rule shipped.
- Heap needs 3106 to 3452 comparisons on all three inputs: it does not care about the input order, and it uses more comparisons than merge or quick on random data.
- Stability table: with equal keys tagged by input position, bubble, insertion and merge never reorder ties in 200 random trials; selection, quick and heap do. Selection reorders because its swap moves a far-away element into position and drops the displaced one at the other end; quick and heap swap across long distances for the same reason. A "no" is proved by one counterexample, and the trial found one for each; a "yes" comes from reading the code (bubble and insertion only move elements past strictly larger ones, merge takes the left element on a tie).
When you would actually pick each one
| Situation | Pick | Why |
|---|---|---|
| Few elements, or data that is already nearly sorted | Insertion | 255 comparisons on sorted input here, no extra memory, stable. It is also what hybrid sorts use for tiny ranges. |
| General in-memory array of numbers, no stability needed | Quick (with a random or median-of-three pivot) | In the measurements it needed the fewest comparisons on random input after merge, it works in place, and it has the best locality of the O(n log n) sorts. Guard the worst case with a hybrid (introsort). |
| Records with equal keys that must keep their order, linked lists, or data too large for memory | Merge | Stable, O(n log n) always, and its sequential merge pass fits lists and external files. The cost is the O(n) buffer. |
| A hard O(n log n) bound and O(1) memory (for example an embedded system) | Heap | The only one with both guarantees; the cost is no stability and poor cache behaviour. |
| Writes are very expensive (for example flash memory) | Selection | At most n - 1 swaps, the fewest of the six. |
| Teaching, or checking "is this already sorted" | Bubble with early exit | One pass over sorted data. It is almost never the right production choice. |
In real code, call the language's built-in sort. Python's sorted and list.sort are stable and O(n log n) in the worst case, and are O(n) on already-sorted input, which none of merge, quick or heap sort above achieve.
Edge cases and common mistakes
- Saying quicksort is O(n log n) without naming the pivot rule: the worst case depends on it.
- Calling merge sort in place: the array version needs an O(n) buffer.
- Saying quicksort uses O(1) space: the recursion stack is O(log n) on average, and O(n) in the worst case unless you recurse into the smaller side and turn the larger side into a loop (recursing into both sides, even smaller side first, still nests n calls deep on a sorted input with this pivot rule). With this simple recursion, a sorted input of about a thousand elements raises
RecursionErrorin CPython, whose default limit is 1000 nested calls. - Forgetting that bubble's O(n) best case depends on the early-exit flag; without it bubble does n(n - 1)/2 comparisons on every input.
- Treating "stable" as a free bonus: stability matters for multi-key sorting and tie-ordered output, and it is why unstable sorts are fine only when equal keys are indistinguishable.
Running the code
Save the program as sort_compare.py and run:
python sort_compare.py
Standard library only (random); no install or config needed.
You're joining a new team. Walk me through your 30/60/90-day plan for proactively soliciting feedback to ramp up quickly: who you'd ask, what specific questions you'd use, and how you'd track that you're actually acting on what you hear.
Sample Answer
Direct answer
Treat the first ninety days as three distinct feedback phases rather than one long ramp: the first thirty days is mostly listening and asking calibrated questions of a wide set of people, the next thirty is testing that understanding through visible small contributions and targeted follow-up questions, and the last thirty is asking for a harder, more evaluative read now that there's real work to point to. At each phase, write down what you heard and what you changed because of it, so the loop is visible, not just felt.
Structured elaboration
- Days one to thirty: who and what. Talk to your manager (what does success look like at thirty, sixty, and ninety days, what's the biggest risk if this goes wrong), two or three peers doing similar work (what do you wish someone had told you when you started, what's the thing that trips people up here), and, if relevant, a couple of people upstream or downstream of your work (what do you actually need from this role that isn't written down anywhere). Questions here are deliberately open and low-stakes: "what should I be paying attention to that I don't know to ask about yet?"
- Days thirty-one to sixty: who and what. After producing something real, a first change, a first analysis, a first design, a first proposal, ask more targeted questions of whoever reviewed it: "was this the right level of detail," "did I miss context I should have had," "is there a pattern in what you're correcting that I should watch for?" This is also when to bring a specific check-in back to your manager: "here's what I've done, here's what I'm still unsure about."
- Days sixty-one to ninety: who and what. Ask for a more evaluative read, since there's now enough of a track record for the answer to be specific rather than generic: "if you were coaching me for the next quarter, what's the one thing I should focus on?" Ask this of your manager and at least one peer whose judgment you trust, since a manager's view and a peer's view often surface different things.
- Tracking that you're acting on it. Keep a simple running log, one line per piece of feedback: what was said, who said it, and what you changed or decided not to change and why. Bring this log into one-on-one check-ins with your manager (a regular short meeting between you and your manager), especially around the day-thirty and day-sixty marks, so your manager sees the pattern, not just individual points, and so you have to be honest with yourself about whether you actually followed through.
Worked example
The questions above stay constant, but what "producing something real" means in days thirty-one to sixty varies by the kind of work. For someone in a data-facing role, the first real deliverable is often getting the data model and who-needs-what-from-it right, so the targeted day-forty-five question becomes, "does my understanding of how this data actually gets used match reality," checked against a specific report or query. For someone in a design role, early feedback is often more about building credibility through a couple of small, well-executed pieces of work before asking for a harder critique, since a design opinion carries more weight once colleagues have seen competent delivery. For someone building technical proposals, such as an architecture document, a natural day-forty-five checkpoint is asking for feedback specifically on the early proposal itself and on communication style, since how something is proposed matters as much as what's proposed when you're new to a team. In every case, the log entry looks the same: what was said, what changed.
Trade-offs and pitfalls
Asking only your manager and skipping peers misses the day-to-day texture a manager doesn't see. Asking the same broad question the whole ninety days, instead of narrowing it as you get more context and more real work to point to, wastes the growing specificity available to you. Collecting feedback but never visibly acting on it reads as performative rather than genuinely coachable. And waiting until day ninety to ask for anything evaluative wastes the early window when small corrections are cheapest to make.
Recommended Additional Resources
- LeetCode - Focus on Medium difficulty problems for junior level, especially arrays, trees, graphs, and hash tables
- System Design Primer - Great for understanding foundational concepts of scalable systems
- Cracking the Coding Interview by Gayle Laakmann McDowell - Classic preparation book covering data structures, algorithms, and behavioral questions
- SQL Tutorial and Practice (Mode Analytics SQL Tutorial, HackerRank SQL) - Essential for backend roles involving databases
- Designing Data-Intensive Applications by Martin Kleppmann - Deep dive into distributed systems and scalability
- Backend Engineering Basics courses on platforms like Coursera, Udemy focusing on APIs, databases, and system design
- RESTful API Design Best Practices - Understand REST principles deeply for API design questions
- CoderPad and HackerRank - Practice platforms matching actual interview environments
- STAR Method for Behavioral Interviews - Resources on telling structured stories about your experience
- Mock Interview Platforms - InterviewKickstart, Exponent, or peer mock interviews for realistic practice
Search Results
Last-Minute Coding Interview Tips to Help In Your Interview
Backend Engineering Course. Ace the toughest backend interviews with this focused & structured Backend Interview Prep course taught by FAANG+ engineers.
Meta Software Engineer Interview (questions, process, prep)
Ace the Meta software engineer interviews with this preparation guide. See updates to the interview process, example coding interview questions and ...
Top 50+ Software Engineering Interview Questions and Answers
To do well in interviews, you need to understand core concepts, Software Development Models, Software Project Management, Software metrics, Software ...
Top 70 Coding Interview Questions and Answers for 2026
This article will discuss the top 70 coding interview questions you should know to crack those interviews and get your dream job.
How to Become a Backend Developer: A Practical Guide to Building ...
Practice Whiteboard or Online Coding Tests: Platforms like LeetCode or HackerRank help prepare you for live technical interviews.
Meta Data Engineer Interview Guide | Sample Questions (2025)
You'll do 4 interviews: 3 technical and 1 behavioral. There's also a lunch break. (Yay!) Rounds usually include SQL, coding, data modeling, and product sense.
This interview preparation guide was generated using AI-powered research from the sources listed above. While we strive for accuracy, we recommend verifying critical information from official company sources.
Want to create your own tailored preparation guide using our deep research?
Get Started for FreeInterview-Ready Courses
Visual-first, interactive, structured learning paths
Browse Backend Developer jobs
AI-enriched listings across hundreds of company career pages
Explore Jobs