Coursera interview questions & answers

14 real Coursera interview questions with full model answers — Coding, System design. Drawn from the same verified bank ChannelPulse drills from (14 Coursera questions in total).

CodingEasyCourseraSoftware Engineer

1. N-th Tribonacci Number (LeetCode)

Model answer

The task

Compute the nth Tribonacci number, where the first three values are 0, 1, and 1. Each later value is the sum of the previous three.

Key idea

Keep only the three most recent values. Updating them from left to right computes each term once and avoids storing the entire sequence.

Approach

  1. If n is less than 3, return its initial Tribonacci value.
  2. Initialize the three rolling values to 0, 1, and 1.
  3. Repeat from index 3 through n, replacing the oldest value with the sum of the three.
  4. Return the newest value.
class Solution:
    def tribonacci(self, n: int) -> int:
        # The three base values are T0, T1, and T2.
        if n < 3:
            return [0, 1, 1][n]

        a, b, c = 0, 1, 1

        # After each iteration, (a, b, c) holds
        # the three latest values in the sequence.
        for _ in range(3, n + 1):
            a, b, c = b, c, a + b + c

        return c

Complexity:

  • Time: O(n), because each term up to n is computed once.
  • Space: O(1), because only three values are stored.

Common follow-ups

  • How could you compute the value recursively with memoization? Cache previously computed terms to avoid repeating work.
  • How can the computation be made faster for very large n? Use matrix exponentiation to evaluate the recurrence in O(log n) matrix multiplications.
  • What if each term depends on the previous k terms? Maintain a rolling window of k values and update its sum as the window advances.
CodingMediumCourseraFrontend EngineerJavaScript Problem Solving

2. Implement the publisher-subscriber (observable) design pattern in three different variations.

Model answer

// Variation 1: One publisher with a list of subscribers.
class Publisher {
  constructor() {
    this.subscribers = new Set();
  }

  subscribe(callback) {
    this.subscribers.add(callback);
    return () => this.subscribers.delete(callback); // unsubscribe
  }

  publish(value) {
    // Copy first so subscribers can safely unsubscribe while being notified.
    for (const callback of [...this.subscribers]) callback(value);
  }
}

const publisher = new Publisher();
const unsubscribe = publisher.subscribe(value => console.log("Value:", value));
publisher.publish("course updated");
unsubscribe();

// Variation 2: Topic-based pub/sub for multiple event types.
class EventBus {
  constructor() {
    this.topics = new Map();
  }

  subscribe(topic, callback) {
    if (!this.topics.has(topic)) this.topics.set(topic, new Set());
    const subscribers = this.topics.get(topic);
    subscribers.add(callback);

    return () => {
      subscribers.delete(callback);
      if (subscribers.size === 0) this.topics.delete(topic);
    };
  }

  publish(topic, value) {
    for (const callback of [...(this.topics.get(topic) || [])]) {
      callback(value);
    }
  }
}

const events = new EventBus();
events.subscribe("enrollment", event => console.log("Enrollment:", event));
events.publish("enrollment", { courseId: "c-42", userId: "u-7" });

// Variation 3: Observable stream with next, error, complete, and teardown.
class Observable {
  constructor(start) {
    this.start = start;
  }

  subscribe(observerOrNext) {
    const observer = typeof observerOrNext === "function"
      ? { next: observerOrNext }
      : observerOrNext;

    let closed = false;
    const safeObserver = {
      next: value => {
        if (!closed) observer.next?.(value);
      },
      error: error => {
        if (closed) return;
        closed = true;
        observer.error?.(error);
        teardown?.();
      },
      complete: () => {
        if (closed) return;
        closed = true;
        observer.complete?.();
        teardown?.();
      }
    };

    const teardown = this.start(safeObserver) || (() => {});
    return {
      unsubscribe() {
        if (!closed) {
          closed = true;
          teardown();
        }
      }
    };
  }
}

const timer = new Observable(observer => {
  let count = 0;
  const id = setInterval(() => {
    observer.next(count++);
    if (count === 3) observer.complete();
  }, 500);

  return () => clearInterval(id); // teardown on complete or unsubscribe
});

timer.subscribe({
  next: value => console.log("Tick:", value),
  complete: () => console.log("Stream complete")
});
  • Publisher/subscriber: one publisher broadcasts values to registered callbacks.
  • Topic pub/sub: subscribers select named event topics, which decouples producers from consumers.
  • Observable: a subscription receives a stream lifecycle (next, error, complete) and can clean up its producer.
  • Each variation returns or supports an unsubscribe mechanism to avoid stale listeners.
CodingMediumCourseraFrontend EngineerMachine coding

3. Create a queueable progress bar by dynamically creating the bars at runtime in JavaScript, using setTimeout and setInterval with dynamic durations.

Model answer

class QueueableProgressBars {
  constructor(container = null, intervalMs = 20) {
    // Create a container at runtime if the caller did not provide one.
    this.container = container || document.createElement("div");
    if (!container) document.body.appendChild(this.container);

    this.intervalMs = intervalMs;
    this.queue = [];
    this.running = false;
  }

  enqueue(durationMs) {
    if (!Number.isFinite(durationMs) || durationMs < 0) {
      throw new RangeError("Duration must be a non-negative number");
    }

    this.queue.push(durationMs);
    this.startNext();
  }

  startNext() {
    if (this.running || this.queue.length === 0) return;

    this.running = true;
    const durationMs = this.queue.shift();

    // Create each bar dynamically when its turn begins.
    const bar = document.createElement("div");
    Object.assign(bar.style, {
      width: "0%",
      height: "16px",
      margin: "8px 0",
      backgroundColor: "#2d8cff",
      transition: "none"
    });
    this.container.appendChild(bar);

    const startedAt = Date.now();
    const interval = setInterval(() => {
      const elapsed = Date.now() - startedAt;
      const progress = durationMs === 0
        ? 100
        : Math.min(100, (elapsed / durationMs) * 100);
      bar.style.width = `${progress}%`;

      if (progress >= 100) {
        clearInterval(interval);
        this.running = false;

        // Use a timeout to schedule the next queued bar.
        setTimeout(() => this.startNext(), 0);
      }
    }, this.intervalMs);
  }
}

// Example: bars run sequentially, each with its own duration.
const progressBars = new QueueableProgressBars();
progressBars.enqueue(1200);
progressBars.enqueue(700);
progressBars.enqueue(1800);
  • Each call to enqueue adds a duration to a FIFO queue; bars are created only when they start.
  • setInterval updates the active bar, while setTimeout schedules the next one after completion.
  • Complexity: O(1) queue work per bar, plus O(duration / interval) progress updates; O(number of queued bars) space.
CodingMediumCourseraSoftware Engineer

4. Rank Teams by Votes (LeetCode)

Model answer

The task

Given ballots that list the same teams in preference order, rank teams by how often they appear in each position. Break any remaining tie alphabetically.

Key idea

For each team, count its votes at every position. Compare teams by their count vectors from first position to last, in descending order, using alphabetical order as the final tie-breaker.

Approach

  1. Get the teams and number of positions from the first ballot.
  2. Create a count vector for each team.
  3. For every ballot, increment the count for each team at its position.
  4. Sort teams by their count vectors, highest counts first, then alphabetically.
  5. Return the sorted team names as a string.
class Solution:
    def rankTeams(self, votes: list[str]) -> str:
        teams = votes[0]
        positions = len(teams)

        # counts[team][position] stores votes for that team at that rank.
        counts = {team: [0] * positions for team in teams}

        for ballot in votes:
            for position, team in enumerate(ballot):
                counts[team][position] += 1

        # Negate counts so Python's ascending sort puts larger counts first.
        ranked = sorted(
            teams,
            key=lambda team: tuple(-count for count in counts[team]) + (team,),
        )

        return "".join(ranked)

Complexity:

  • Time: O(V · T + T² log T), where V is the number of ballots and T is the number of teams.
  • Space: O(T²) for the per-team position counts.

Common follow-ups

  • What if teams can have different numbers of positions? Define how missing positions should be counted, then normalize ballots before tallying.
  • How would you rank a very large number of ballots? Tally counts incrementally as ballots arrive; the final sort is still needed for the ranking.
  • What if alphabetical order is replaced by a custom priority? Use that priority as the final sort tie-breaker.
CodingMediumCourseraSoftware Engineer

5. Minimum Moves to Equal Array Elements (LeetCode)

Model answer

The task

Find the fewest operations needed to make every array value equal, where one operation increases all but one element by one.

Key idea

Increasing all but one element has the same effect on the differences between elements as decreasing the excluded element by one. So instead, imagine reducing elements until they all match the minimum value. The required moves are the sum of each element’s difference from that minimum.

Approach

  1. Find the smallest array value.
  2. For each value, count how many decrements would bring it to that minimum.
  3. Add those differences; their total is the minimum number of moves.
  4. Return the total.
from typing import List

class Solution:
    def minMoves(self, nums: List[int]) -> int:
        # Each original move is equivalent, in relative values,
        # to decrementing the one element that was left out.
        minimum = min(nums)
        return sum(value - minimum for value in nums)

Complexity:

  • Time: O(n), to find the minimum and sum the differences.
  • Space: O(1), excluding the input; only a few variables are used.

Common follow-ups

  • What if the operation decreases all but one element? The answer becomes the sum of each value’s difference from the maximum.
  • What if you can change one element by an arbitrary amount per operation? The answer depends on the allowed target and operation cost; this formula no longer necessarily applies.
  • How would you handle a stream of values? Maintaining the sum and minimum supports computing the result once the stream is complete, but a newly lowered minimum requires adjusting the accumulated differences.
CodingMediumCourseraSoftware Engineer

6. Highest Grade For Each Student (LeetCode)

Model answer

The task

For each student, return the course where they earned their highest grade. If multiple courses share that grade, choose the one with the smallest course ID.

Key idea

Rank each student’s enrollments by grade descending, then course ID ascending. The top-ranked row for each student is the required result.

Approach

  1. Use ROW_NUMBER() to rank rows within each student’s enrollments.
  2. Order each ranking by grade from highest to lowest.
  3. Break grade ties by ordering course IDs from smallest to largest.
  4. Keep only the first row per student and sort the results by student ID.
WITH ranked_enrollments AS (
    SELECT
        student_id,
        course_id,
        grade,
        ROW_NUMBER() OVER (
            PARTITION BY student_id
            ORDER BY grade DESC, course_id ASC
        ) AS row_num
    FROM Enrollments
)
SELECT
    student_id,
    course_id,
    grade
FROM ranked_enrollments
WHERE row_num = 1
ORDER BY student_id;

Complexity:

  • Time: O(n log n), typically due to ordering enrollment rows for the window function.
  • Space: O(n) in the worst case for ranking or sorting intermediate rows.

Common follow-ups

  • What if all courses tied for the highest grade should be returned? Use RANK() instead of ROW_NUMBER() and filter for rank 1.
  • How would you handle students with no enrollments? Start from a Students table and LEFT JOIN the selected enrollment rows.
  • Can an index help? An index on (student_id, grade DESC, course_id ASC) may help, depending on the database’s query planner and index support.
CodingMediumCourseraSoftware Engineer

7. Minimum Increment to Make Array Unique (LeetCode)

Model answer

The task

Given an integer array, make every value distinct by incrementing values as needed. Return the smallest total number of increments.

Key idea

Process values in sorted order. For each one, keep it if it is greater than the previous assigned value; otherwise raise it to the next available value. This greedy choice is optimal because assigning a value any higher would only add unnecessary increments.

Approach

  1. Sort the array.
  2. Track the smallest value that can be assigned next.
  3. For each number, raise it to that value if necessary and add the increase to the total.
  4. Advance the next available value.
class Solution:
    def minIncrementForUnique(self, nums: list[int]) -> int:
        nums.sort()

        moves = 0
        next_value = 0

        for number in nums:
            assigned = max(number, next_value)
            moves += assigned - number
            next_value = assigned + 1

        return moves

Complexity:

  • Time: O(n log n), due to sorting.
  • Space: O(n) in the worst case for Python's sorting implementation.

Common follow-ups

  • What if the array is already sorted? The scan takes O(n); sorting is no longer needed.
  • Can counting replace sorting? Yes, when the value range is small, a frequency array can process values in order.
  • What if increments have different costs? The greedy assignment may no longer be optimal; the cost model must be analyzed separately.
CodingMediumCourseraSoftware Engineer

8. Given a 2D board of characters and a word, find if the word exists in the grid.

The full question

Given a 2D board of characters and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

For example, given the following board:

Model answer

function exists(board, word) {
  if (word.length === 0) return true;
  if (!board.length || !board[0].length) return false;

  const rows = board.length;
  const cols = board[0].length;
  if (word.length > rows * cols) return false;

  const visited = Array.from({ length: rows }, () =>
    Array(cols).fill(false)
  );

  function search(row, col, index) {
    if (index === word.length) return true;

    if (
      row < 0 || row >= rows ||
      col < 0 || col >= cols ||
      visited[row][col] ||
      board[row][col] !== word[index]
    ) {
      return false;
    }

    visited[row][col] = true;

    const found =
      search(row + 1, col, index + 1) ||
      search(row - 1, col, index + 1) ||
      search(row, col + 1, index + 1) ||
      search(row, col - 1, index + 1);

    visited[row][col] = false; // Backtrack so other paths can reuse this cell.
    return found;
  }

  for (let row = 0; row < rows; row++) {
    for (let col = 0; col < cols; col++) {
      if (search(row, col, 0)) return true;
    }
  }

  return false;
}
  • Start a depth-first search from every cell matching the first character.
  • Mark each cell while exploring its path; unmark it when backtracking so a cell cannot be reused within one path.
  • Complexity: O(R × C × 4^L) time in the worst case, where L is the word length; O(R × C + L) space for the visited matrix and recursion stack.
CodingHardCourseraSoftware Engineer

9. Text Justification (LeetCode)

Model answer

The task

Format a sequence of words into lines of a fixed width. Fully justify each line except the final line, which is left-justified.

Key idea

Greedily place as many words as possible on each line, counting at least one space between adjacent words. Once a line is chosen, distribute its remaining spaces as evenly as possible; any extras go into the leftmost gaps.

Approach

  1. Start a line with the next unformatted word and keep adding words while they fit with one space between each pair.
  2. If the line is the final line, or contains just one word, join with single spaces and pad on the right.
  3. Otherwise, divide the available spaces evenly across the gaps.
  4. Give one additional space to each of the leftmost gaps until the remainder is used.
  5. Repeat until all words are formatted.
from typing import List

class Solution:
    def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
        result = []
        i = 0

        while i < len(words):
            # Find the largest group of words that fits on this line,
            # counting one mandatory space between each pair.
            j = i
            letters = 0

            while j < len(words) and letters + len(words[j]) + (j - i) <= maxWidth:
                letters += len(words[j])
                j += 1

            gaps = j - i - 1
            is_last_line = j == len(words)

            if is_last_line or gaps == 0:
                # The final line and single-word lines are left-justified.
                line = " ".join(words[i:j])
                line += " " * (maxWidth - len(line))
            else:
                total_spaces = maxWidth - letters
                spaces_per_gap, extra_spaces = divmod(total_spaces, gaps)

                parts = []
                for gap in range(gaps):
                    parts.append(words[i + gap])
                    # Earlier gaps receive any leftover spaces.
                    spaces = spaces_per_gap + (1 if gap < extra_spaces else 0)
                    parts.append(" " * spaces)

                parts.append(words[j - 1])
                line = "".join(parts)

            result.append(line)
            i = j

        return result

Complexity:

  • Time: O(n + L × W), where n is the total number of input characters, L is the number of output lines, and W is the line width.
  • Space: O(L × W) for the returned lines; O(W) additional space to build a line.

Common follow-ups

  • What if words may be hyphenated? Split long words into width-limited pieces before packing.
  • What if the last line must also be fully justified? Apply the regular gap-distribution rule to it.
  • How can this handle a streaming word source? Buffer words for the current line, then emit it as soon as the next word no longer fits.
CodingHardCourseraSoftware Engineer

10. Special Binary String (LeetCode)

Model answer

The task

Rearrange the special binary string by swapping adjacent special substrings to obtain the lexicographically largest possible string. A special string has balanced counts of 1s and 0s, with no prefix containing more 0s than 1s.

Key idea

A special string splits into top-level pieces, each shaped like 1 + interior + 0. Recursively maximize each interior, then sort the resulting pieces in descending lexicographic order; placing the largest piece first gives the largest result.

Approach

  1. Scan the string while tracking the balance: add one for 1, subtract one for 0.
  2. Whenever the balance returns to zero, a complete top-level piece has been found.
  3. Recursively process the substring inside that piece’s outer 1 and 0.
  4. Collect the rebuilt pieces, sort them in descending order, and concatenate them.
class Solution:
    def makeLargestSpecial(self, s: str) -> str:
        def maximize(text: str) -> str:
            pieces = []
            start = 0
            balance = 0

            for i, bit in enumerate(text):
                balance += 1 if bit == "1" else -1

                # The current prefix is a complete special substring.
                if balance == 0:
                    interior = maximize(text[start + 1:i])
                    pieces.append("1" + interior + "0")
                    start = i + 1

            # Larger special pieces must come first.
            pieces.sort(reverse=True)
            return "".join(pieces)

        return maximize(s)

Complexity:

  • Time: O(n² log n) in the worst case, accounting for recursive string construction and sorting.
  • Space: O(n²) in the worst case for intermediate strings; recursion uses up to O(n) stack space.

Common follow-ups

  • Why sort in descending lexicographic order? The top-level pieces are interchangeable, and putting the largest piece first maximizes the concatenation.
  • Can the sorting be done by length instead? No; lexicographic order, not length, determines which piece should come first.
  • What changes for a different ordering goal? Keep the same decomposition and recursion, but order the rebuilt pieces according to the desired comparison rule.
CodingHardCourseraSoftware Engineer

11. Number of Music Playlists (LeetCode)

Model answer

The task

Count ordered playlists of a given length that include every song, while preventing a song from being replayed until at least k other songs have appeared. Return the count modulo \(10^9+7\).

Key idea

Use dynamic programming based on playlist length and how many distinct songs have been used. When adding a song, it is either new or one of the already-used songs that is eligible to replay.

Approach

  1. Let dp[length][used] count playlists of that length containing exactly used distinct songs.
  2. Initialize dp[0][0] = 1.
  3. To add a new song, choose from the n - used + 1 songs not yet used.
  4. To replay a song, choose from the used - k eligible songs, if that number is positive.
  5. Return the count for the full length with all songs used.
class Solution:
    def numMusicPlaylists(self, n: int, goal: int, k: int) -> int:
        mod = 10**9 + 7
        dp = [[0] * (n + 1) for _ in range(goal + 1)]
        dp[0][0] = 1

        for length in range(1, goal + 1):
            for used in range(1, n + 1):
                # Add a song that has not appeared in the playlist yet.
                new_song_choices = n - used + 1
                dp[length][used] += (
                    dp[length - 1][used - 1] * new_song_choices
                )

                # Replay a previously used song, if it is eligible.
                replay_choices = max(used - k, 0)
                dp[length][used] += (
                    dp[length - 1][used] * replay_choices
                )

                dp[length][used] %= mod

        return dp[goal][n]

Complexity:

  • Time: O(goal · n), processing each state once.
  • Space: O(goal · n), storing the DP table.

Common follow-ups

  • Can you reduce memory? Keep only the previous and current length rows, since each transition uses only the preceding row.
  • What if k = 0? Every previously used song is eligible for replay, so the same recurrence applies.
  • How would you count playlists using exactly m distinct songs? Return the DP state for m instead of requiring all n songs.
CodingHardCourseraFrontend EngineerData Structure & Algorithms

12. Given words and a line length of N characters, arrange the words into lines so that words that do not fit move to the next line, and distribute the…

The full question

Given words and a line length of N characters, arrange the words into lines so that words that do not fit move to the next line, and distribute the remaining spaces.

Model answer

function fullJustify(words, maxWidth) {
  if (!Number.isInteger(maxWidth) || maxWidth < 1) {
    throw new RangeError("maxWidth must be a positive integer");
  }
  for (const word of words) {
    if (word.length > maxWidth) {
      throw new RangeError(`Word exceeds line width: ${word}`);
    }
  }

  const lines = [];
  let start = 0;

  while (start < words.length) {
    // Greedily fit as many words as possible, including one space between each.
    let end = start;
    let letters = 0;
    while (
      end < words.length &&
      letters + words[end].length + (end - start) <= maxWidth
    ) {
      letters += words[end].length;
      end++;
    }

    const wordCount = end - start;
    const isLastLine = end === words.length;

    if (isLastLine || wordCount === 1) {
      // Last lines and single-word lines are left-justified.
      const text = words.slice(start, end).join(" ");
      lines.push(text + " ".repeat(maxWidth - text.length));
    } else {
      const gaps = wordCount - 1;
      const spaces = maxWidth - letters;
      const spacesPerGap = Math.floor(spaces / gaps);
      const extraSpaces = spaces % gaps;

      let line = "";
      for (let i = 0; i < gaps; i++) {
        // Assign leftover spaces to the leftmost gaps.
        const gapWidth = spacesPerGap + (i < extraSpaces ? 1 : 0);
        line += words[start + i] + " ".repeat(gapWidth);
      }
      line += words[end - 1];
      lines.push(line);
    }

    start = end;
  }

  return lines;
}

// Example:
console.log(fullJustify(
  ["Design", "learning", "experiences", "for", "everyone"],
  16
));
  • Greedily collect the largest group of words that fits within maxWidth.
  • For regular lines, divide spaces evenly; any remainder goes to the leftmost gaps.
  • The final line and single-word lines are left-justified and padded to exactly maxWidth.
  • Complexity: O(total output characters); O(total output characters) space for the returned lines.
CodingHardCourseraSoftware Engineer

13. Reaching Points (LeetCode)

Model answer

The task

Determine whether a starting pair can be transformed into a target pair by repeatedly adding one coordinate to the other.

Key idea

Reverse the process: subtract the smaller target coordinate from the larger one. Batch repeated subtractions with modulo, as in the Euclidean algorithm. When one coordinate reaches its starting value, check whether the other differs from its start by a multiple of it.

Approach

  1. While both target coordinates are at least their starting values, check whether either coordinate has reached its starting value.
  2. If the first coordinate is fixed, test whether the second can be reduced to its start by repeated subtraction.
  3. Apply the symmetric check if the second coordinate is fixed.
  4. Otherwise, reduce the larger coordinate modulo the smaller.
  5. If either coordinate drops below its start, the target is unreachable.
class Solution:
    def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:
        while tx >= sx and ty >= sy:
            if tx == sx:
                return (ty - sy) % sx == 0

            if ty == sy:
                return (tx - sx) % sy == 0

            if tx > ty:
                tx %= ty
            else:
                ty %= tx

        return False

Complexity:

  • Time: O(log(max(tx, ty))) modulo steps, as in the Euclidean algorithm.
  • Space: O(1), using only a fixed number of variables.

Common follow-ups

  • What if coordinates can be zero? Handle zero divisors explicitly; modulo-based checks assume positive coordinates.
  • Can you provide a forward search? It branches and may grow rapidly, so reversing with modulo is much more efficient.
  • Why use modulo instead of subtracting once? It batches many identical reverse steps into one operation.
System designHardCourseraFrontend EngineerSystem Design

14. Design an artifact library that stores components as micro-frontends that can be imported or pruned.

The full question

Design an artifact library that stores components as micro-frontends that can be imported or pruned. Design its tables, relationships, and request and response API contracts.

Model answer

1. Requirements & scale

Functional requirements

  • Publish immutable, versioned micro-frontend artifacts with manifests, entry points, framework compatibility, and dependency metadata.
  • Let consumers browse/search artifacts, import a specific version, and prune unused components from a build.
  • Resolve transitive dependencies, reject incompatible or vulnerable versions, and retain build provenance for rollback.

Non-functional requirements

  • Artifact metadata reads should be highly available and typically finish in under 200 ms; builds may be asynchronous.
  • Published artifacts must be immutable, integrity-checked, access-controlled, and safe to distribute through a CDN.
  • Pruning must preserve required dependencies and produce a reproducible result for a given manifest and input set.

Back-of-the-envelope: Assume 5,000 teams, 20,000 artifacts, and 10 versions per artifact: 200,000 version records. At 100,000 imports/builds per day, average build traffic is about 1.2 requests/second; allow 10x peak, or 12 requests/second. If each artifact averages 2 MB, versioned blobs occupy about 400 GB before replication. Metadata is small relative to bundles; CDN delivery, rather than API traffic, dominates bandwidth.

2. High-level architecture

flowchart TD
  subgraph Client
    UI["Library UI"]
    CLI["Import and build client"]
  end
  subgraph EdgeCDN["Edge and CDN"]
    WAF["WAF and rate limits"]
    CDN["Artifact CDN"]
  end
  subgraph LoadBalancer["Load Balancer"]
    LB["API gateway"]
  end
  subgraph APIServices["API and Services"]
    Catalog["Catalog service"]
    Resolver["Dependency resolver"]
    BuildAPI["Import and prune API"]
    Auth["Auth and policy"]
  end
  subgraph Cache["Cache"]
    Redis["Redis metadata and jobs"]
  end
  subgraph Datastores["Datastores"]
    SQL["PostgreSQL metadata"]
    Blob["Object storage"]
    Search["Search index"]
  end
  subgraph MessageQueue["Message Queue"]
    Queue["Build queue"]
  end
  subgraph Workers["Workers"]
    Worker["Isolated build workers"]
    Scanner["Artifact scanner and signer"]
  end
  UI -->|"browse and search"| WAF
  CLI -->|"import, prune, publish"| WAF
  WAF --> LB
  LB --> Auth
  Auth --> Catalog
  Auth --> BuildAPI
  Catalog -->|"metadata and dependencies"| SQL
  Catalog -->|"search query"| Search
  Catalog -->|"hot metadata"| Redis
  BuildAPI --> Resolver
  Resolver -->|"dependency graph"| SQL
  BuildAPI -->|"enqueue job"| Queue
  Queue --> Worker
  Worker -->|"resolved blobs"| Blob
  Worker -->|"artifact validation"| Scanner
  Scanner -->|"signed version metadata"| SQL
  Worker -->|"job status"| Redis
  CLI -->|"download by digest"| CDN
  CDN -->|"origin fetch"| Blob
Diagram

3. API design

All endpoints require an authenticated team identity. Use an Idempotency-Key for mutations and return a requestId for tracing.

  • GET /v1/artifacts?query=...&framework=react — paginated catalog results with name, latest compatible version, owner, and description.
  • GET /v1/artifacts/{artifactId}/versions/{version} — immutable manifest, dependency list, entry points, and integrity digest.
  • POST /v1/imports — body: {"artifact":"course-card","version":"^2.1.0","framework":"react","target":"./src/artifacts"}. Return 202 with {"jobId":"...","status":"queued"}.
  • POST /v1/prunes — body: {"manifestId":"...","usedComponents":["course-card/Compact"],"lockfileDigest":"sha256:..."}. Return 202 with a job ID; the job calculates the dependency closure and emits a reduced bundle and updated lockfile.
  • GET /v1/jobs/{jobId} — return queued, running, succeeded, or failed; on success include output URL, digest, removed component count, and warnings. On failure include a stable error code and actionable message.
  • POST /v1/artifacts — publish a manifest and bundle using a pre-signed upload URL; publication succeeds only after validation and signing.

4. Data model & storage

Use PostgreSQL for transactional metadata and relationships, object storage for immutable bundles, Redis for short-lived job/status caching, and a search index for catalog queries.

  • artifacts(id, team_id, name, visibility, created_at); unique (team_id, name).
  • artifact_versions(id, artifact_id, version, manifest_digest, blob_key, framework, integrity, status, published_at); unique (artifact_id, version).
  • dependencies(version_id, dependency_artifact_id, version_range, optional) records declared edges. Resolve ranges to exact versions in a build lockfile.
  • components(id, version_id, export_name, entry_point, size_bytes) identifies independently importable exports.
  • build_jobs(id, team_id, type, input_digest, status, output_digest, error_code, created_at) supports retries and auditability.

Foreign keys connect versions to artifacts, dependencies to versions, and components to versions. Partition job history by creation month; index artifact name and version. Store bundles under content-addressed keys such as sha256/{digest} so retries and identical outputs deduplicate safely.

5. Deep dive

Pruning must be dependency-aware, not just text-based deletion. Each published manifest declares component exports and their internal imports. The worker starts from the requested used exports, walks the import graph, and retains the transitive closure. It then resolves external dependencies against the lockfile, checks framework and peer-dependency constraints, and emits only reachable modules plus required shared runtime code. If an export has dynamic imports that cannot be statically resolved, retain the referenced chunk or fail with a warning rather than silently breaking the application.

sequenceDiagram
  participant C as Client
  participant A as API
  participant R as Resolver
  participant Q as Queue
  participant W as Worker
  participant S as Storage
  C->>A: POST prune with used exports and lockfile digest
  A->>R: Validate versions and resolve dependency graph
  R-->>A: Graph and compatibility result
  A->>Q: Enqueue idempotent build job
  A-->>C: 202 jobId
  Q->>W: Deliver job
  W->>S: Fetch immutable input bundles
  W->>W: Compute reachable closure and create output
  W->>S: Store output by content digest
  W-->>A: Record status, digest, and warnings
  C->>A: GET job status
  A-->>C: Succeeded with output URL and digest
Diagram

6. Scale, bottlenecks & trade-offs

  • Serve immutable bundles from a CDN with long-lived cache headers; APIs use short TTLs for catalog metadata. Purging is needed only for mutable aliases such as latest, never versioned blobs.
  • PostgreSQL is authoritative for publication and dependency metadata. Replicate reads, but send writes to the primary; tolerate slightly stale catalog reads while keeping version resolution consistent.
  • Queue builds asynchronously and cap worker concurrency per team. Retry transient failures with backoff; dead-letter repeated failures. Workers run in isolated, resource-limited environments and never execute published code during metadata reads.
  • The dependency graph and bundler are the main bottlenecks. Cache results by input digest, resolved lockfile, and toolchain version; invalidate naturally when any digest changes.
  • Prefer availability for browsing and downloads of published immutable versions, but fail closed on authorization, signature, or dependency-integrity checks. This trades some build availability for supply-chain safety.

Practice these out loud, don't memorise them

Reading an answer is not the same as being able to give one under pressure. ChannelPulse plays the interviewer, asks the follow-ups, and scores each answer with feedback and a model answer so you can hear the gap between what you said and what lands.

Get ChannelPulse Browse all questions