Media.net interview questions & answers

20 real Media.net interview questions with full model answers — Coding, Technical, System design. Drawn from the same verified bank ChannelPulse drills from (61 Media.net questions in total).

CodingEasyMedia.netSoftware Engineer

1. Maximum Value of an Ordered Triplet I (LeetCode)

Model answer

The task

Given an array, choose indices \(i < j < k\) to maximize \((nums[i] - nums[j]) \times nums[k]\). Return 0 if no choice gives a positive value.

Key idea

While scanning from left to right, keep the largest value seen so far and the largest difference nums[i] - nums[j] formed so far. Treat each current value as nums[k] before updating those values, so the index order is preserved.

Approach

  1. Initialize the best answer, largest earlier value, and largest earlier difference to 0.
  2. For each value, use it as nums[k] to update the answer.
  3. Use it as nums[j] to update the best difference.
  4. Use it as a future nums[i] by updating the largest earlier value.
  5. Return the best answer.
from typing import List

class Solution:
    def maximumTripletValue(self, nums: List[int]) -> int:
        best_value = 0
        largest_before = 0
        largest_difference = 0

        for value in nums:
            # Use value as nums[k]; stored differences end before this index.
            best_value = max(best_value, largest_difference * value)

            # Use value as nums[j], paired with an earlier nums[i].
            largest_difference = max(
                largest_difference,
                largest_before - value,
            )

            # Use value as nums[i] for later indices.
            largest_before = max(largest_before, value)

        return best_value

Complexity:

  • Time: O(n), one pass through the array.
  • Space: O(1), only a few values are stored.

Common follow-ups

  • How would you return the indices too? Store the indices that produced the best earlier value and difference, and record them when the answer improves.
  • What if the array is processed as a stream? The same updates work online; only the running values need to be retained.
  • What if values can be negative? Revisit the zero initialization and track extrema carefully, since multiplying by a negative value can reverse which difference is best.
CodingEasyMedia.netSoftware Engineer

2. Remove Outermost Parentheses (LeetCode)

Model answer

The task

Given a balanced parentheses string, remove the outermost pair from each primitive balanced substring and return the remaining characters in order.

Key idea

Track the current nesting depth. An opening parenthesis is outermost when the depth is zero before it; a closing parenthesis is outermost when the depth is zero after it. Append only parentheses that are not outermost.

Approach

  1. Initialize the nesting depth to zero and an output buffer.
  2. For each opening parenthesis, append it if already inside a pair, then increase the depth.
  3. For each closing parenthesis, decrease the depth first, then append it if still inside a pair.
  4. Join the buffer and return the result.
class Solution:
    def removeOuterParentheses(self, s: str) -> str:
        depth = 0
        result = []

        for char in s:
            if char == "(":
                # Exclude an opening parenthesis at depth zero.
                if depth > 0:
                    result.append(char)
                depth += 1
            else:
                depth -= 1
                # Exclude a closing parenthesis that closes a primitive.
                if depth > 0:
                    result.append(char)

        return "".join(result)

Complexity:

  • Time: O(n), where n is the length of the string.
  • Space: O(n) for the output buffer.

Common follow-ups

  • Can this be done without a stack? Yes; the nesting-depth counter is sufficient because only the current depth matters.
  • What if the input may be unbalanced? Validate the depth never becomes negative and is zero at the end; define whether invalid input should raise an error or return a failure value.
  • How would you remove the outermost pair of a different bracket type? Use the same depth-based method if the input uses a single matching bracket type.
CodingEasyMedia.netSoftware Engineer

3. Minimum Time Visiting All Points (LeetCode)

Model answer

The task

Given points in a fixed order, find the least time needed to visit them in sequence. In one second, you may move one unit horizontally, vertically, or diagonally.

Key idea

Between two points, a diagonal step can reduce both coordinate differences at once. So the minimum time for a segment is the larger of the absolute horizontal and vertical differences; sum this over consecutive points.

Approach

  1. Initialize the total time to zero.
  2. For each pair of consecutive points, calculate the absolute differences in their x- and y-coordinates.
  3. Add the larger difference to the total.
  4. Return the total.
from typing import List

class Solution:
    def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
        total_time = 0

        for i in range(1, len(points)):
            previous = points[i - 1]
            current = points[i]

            dx = abs(current[0] - previous[0])
            dy = abs(current[1] - previous[1])

            # Diagonal moves reduce both coordinate differences together.
            total_time += max(dx, dy)

        return total_time

Complexity:

  • Time: O(n), where n is the number of points.
  • Space: O(1), using only a few variables.

Common follow-ups

  • What if only horizontal and vertical moves are allowed? Add the two coordinate differences for each segment.
  • What if points may be visited in any order? The problem becomes finding a shortest route, rather than summing consecutive distances.
  • What if movement costs differ by direction? Recalculate the best segment cost using the movement rules and costs.
CodingEasyMedia.netSoftware Engineer

4. Best Time to Buy and Sell Stock (LeetCode)

Model answer

The task

Given daily stock prices, find the greatest profit possible from one buy followed by one later sale. If no sale would make money, return zero.

Key idea

As we scan the prices, keep the lowest price seen so far. Treat each current price as a possible sale and update the best profit using the difference from that minimum.

Approach

  1. Initialize the minimum price to a value larger than any price and the best profit to zero.
  2. Visit each price in order.
  3. Update the minimum price with the current price.
  4. Check the profit from selling today and update the best profit.
  5. Return the best profit.
class Solution:
    def maxProfit(self, prices: list[int]) -> int:
        min_price = float("inf")
        best_profit = 0

        for price in prices:
            # The current price can be a new best day to buy.
            min_price = min(min_price, price)

            # Or it can be the day to sell after the cheapest earlier buy.
            best_profit = max(best_profit, price - min_price)

        return best_profit

Complexity:

  • Time: O(n), where n is the number of prices; each is processed once.
  • Space: O(1), since only a few variables are stored.

Common follow-ups

  • What if multiple buy-and-sell transactions are allowed? Sum the gains from every adjacent price increase.
  • What if a transaction fee is charged? Track the best holding and non-holding profits, incorporating the fee when selling.
  • What if at most k transactions are allowed? Use dynamic programming over the number of completed transactions and whether a share is currently held.
CodingEasyMedia.netSoftware Engineer

5. Climbing Stairs (LeetCode)

Model answer

The task

Count how many distinct ways there are to reach the top of a staircase with n steps when each move advances either one or two steps.

Key idea

To reach step i, the last move must come from step i - 1 or i - 2. Thus the number of ways to reach i is the sum of the ways to reach those two earlier steps. Only the previous two counts are needed, so there is no need to store a full table.

Approach

  1. Set the number of ways to reach step 0 to 1, representing the single empty sequence of moves.
  2. Set the number of ways to reach step 1 to 1.
  3. For each step from 2 through n, add the counts for the preceding two steps.
  4. Return the count for step n.
class Solution:
    def climbStairs(self, n: int) -> int:
        # Ways to reach steps 0 and 1.
        two_back = 1
        one_back = 1

        # Build the count using the two preceding results.
        for _ in range(2, n + 1):
            current = two_back + one_back
            two_back = one_back
            one_back = current

        return one_back

Complexity:

  • Time: O(n), since each step is processed once.
  • Space: O(1), since only two prior counts are retained.

Common follow-ups

  • What if each move can advance 1, 2, or 3 steps? Sum the counts for the previous three steps.
  • What if the result must be returned modulo a number? Apply the modulus after each addition.
  • What if some steps are forbidden? Set their ways count to zero and use dynamic programming for the allowed steps.
CodingEasyMedia.netSoftware EngineerTechnical Interview (Algorithms, DS)

6. Print all perfect cubes between L and R.

Model answer

// Input: L R (inclusive integer bounds). Prints each perfect cube in range.
const fs = require('fs');
const tokens = fs.readFileSync(0, 'utf8').trim().split(/\s+/);
if (tokens.length < 2 || !tokens[0]) process.exit(0);

let L = BigInt(tokens[0]);
let R = BigInt(tokens[1]);
if (L > R) [L, R] = [R, L];

// Floor of the integer cube root, including for negative values.
function floorCubeRoot(n) {
  if (n < 0n) return -ceilPositiveCubeRoot(-n);

  let lo = 0n;
  let hi = 1n;
  while (hi * hi * hi <= n) hi *= 2n;

  // Keep lo^3 <= n and hi^3 > n.
  while (hi - lo > 1n) {
    const mid = (lo + hi) / 2n;
    if (mid * mid * mid <= n) lo = mid;
    else hi = mid;
  }
  return lo;
}

function ceilPositiveCubeRoot(n) {
  const root = floorCubeRoot(n);
  return root * root * root === n ? root : root + 1n;
}

// ceil(cuberoot(L)) = -floor(cuberoot(-L)).
const firstRoot = -floorCubeRoot(-L);
const lastRoot = floorCubeRoot(R);
const result = [];

for (let root = firstRoot; root <= lastRoot; root++) {
  result.push(String(root * root * root));
}
console.log(result.join('\n'));
  • Find the first and last integer roots whose cubes lie in the inclusive range; this also handles negative cubes.
  • BigInt avoids floating-point rounding errors at range boundaries.

Complexity: O(log M + K) time, where M = max(|L|, |R|) and K is the number of cubes printed; O(K) space for output.

CodingMediumMedia.netSoftware Engineer

7. Minimum Total Space Wasted With K Resizing Operations (LeetCode)

Model answer

The task

Choose the array’s capacity over time, with at most k resizing operations, to minimize the total unused capacity. Each uninterrupted stretch uses capacity equal to the largest value in that stretch.

Key idea

Each resizing divides the array into consecutive segments, so at most k + 1 segments are needed. A segment’s wasted space is its length times its maximum value minus its sum; dynamic programming finds the cheapest partition.

Approach

  1. Precompute the wasted space for every contiguous segment.
  2. Let dp[i][s] be the minimum waste for the first i elements using exactly s segments.
  3. Set dp[0][0] = 0.
  4. For each segment count, try every possible final segment and extend the best partition before it.
  5. Return the minimum cost using between one and k + 1 segments.
class Solution:
    def minSpaceWastedKResizing(self, nums: list[int], k: int) -> int:
        n = len(nums)
        max_segments = min(n, k + 1)

        # waste[left][right] is the cost of one segment
        # containing nums[left:right + 1].
        waste = [[0] * n for _ in range(n)]
        for left in range(n):
            total = 0
            largest = 0
            for right in range(left, n):
                total += nums[right]
                largest = max(largest, nums[right])
                waste[left][right] = largest * (right - left + 1) - total

        # dp[i][segments]: minimum waste for the first i elements
        # using exactly "segments" non-empty segments.
        inf = float("inf")
        dp = [[inf] * (max_segments + 1) for _ in range(n + 1)]
        dp[0][0] = 0

        for segments in range(1, max_segments + 1):
            for end in range(segments, n + 1):
                for start in range(segments - 1, end):
                    if dp[start][segments - 1] != inf:
                        cost = dp[start][segments - 1] + waste[start][end - 1]
                        dp[end][segments] = min(dp[end][segments], cost)

        return min(dp[n][segments] for segments in range(1, max_segments + 1))

Complexity:

  • Time: O(n² · min(n, k + 1)) for the segment DP, plus O(n²) preprocessing.
  • Space: O(n² + n · min(n, k + 1)) for segment costs and DP states.

Common follow-ups

  • What if k = 0? The array must be one segment, so its capacity is the array maximum.
  • What if k >= n - 1? Each element can have its own segment, yielding zero waste.
  • Can the segment-cost table be avoided? Yes; compute each candidate segment’s sum and maximum while iterating, trading simpler storage for repeated work.
CodingMediumMedia.netSoftware Engineer

8. Recover Binary Search Tree (LeetCode)

Model answer

The task

Two values in a binary search tree have been swapped, leaving the tree invalid. Restore the tree by swapping those values back without changing its structure.

Key idea

An inorder traversal of a valid BST visits values in sorted order. The swapped values create one or two adjacent inversions; tracking the nodes around those inversions identifies the pair to swap.

Approach

  1. Traverse the tree in inorder using Morris traversal, which uses no recursion stack.
  2. Compare each visited node with the previously visited node.
  3. On the first inversion, remember the previous node; for every inversion, remember the current node.
  4. Swap the remembered nodes’ values after traversal. Morris traversal removes its temporary links as it proceeds.
class Solution:
    def recoverTree(self, root) -> None:
        first = second = previous = None

        def visit(node):
            nonlocal first, second, previous

            if previous is not None and previous.val > node.val:
                if first is None:
                    first = previous
                second = node

            previous = node

        current = root

        while current is not None:
            if current.left is None:
                visit(current)
                current = current.right
            else:
                # Find the inorder predecessor of current.
                predecessor = current.left
                while predecessor.right is not None and predecessor.right is not current:
                    predecessor = predecessor.right

                if predecessor.right is None:
                    # Create a temporary thread to return to current.
                    predecessor.right = current
                    current = current.left
                else:
                    # Remove the thread and visit current.
                    predecessor.right = None
                    visit(current)
                    current = current.right

        if first is not None and second is not None:
            first.val, second.val = second.val, first.val

Complexity:

  • Time: O(n), where n is the number of nodes visited.
  • Space: O(1) auxiliary space; Morris traversal uses temporary links instead of a stack.

Common follow-ups

  • Could recursion be used? Yes; recursive inorder traversal is simpler but uses O(h) call-stack space.
  • What if the swapped nodes are adjacent in inorder order? There is one inversion, and the same detection logic finds both nodes.
  • What if values can repeat? The inversion test may not uniquely identify the swapped nodes; the approach relies on the usual distinct-value BST assumption.
CodingMediumMedia.netSoftware Engineer

9. Count the Number of Square-Free Subsets (LeetCode)

Model answer

The task

Count the nonempty subsets whose product is square-free: no prime divides that product more than once. Return the count modulo \(10^9+7\).

Key idea

Represent each value’s prime factors as a bitmask. Two selected values can coexist only if their masks have no bits in common. Process each distinct square-free value once; its frequency gives the number of choices for which copy to select.

Approach

  1. Count occurrences of each value and handle 1 separately, since it contributes no prime factors.
  2. Build a prime-factor mask for each value from 2 through 30; skip values divisible by a prime square.
  3. Use DP indexed by masks of the ten primes up to 30. Initialize the empty selection at mask zero.
  4. For each valid value, transition only from a snapshot of the previous DP, so that value is selected at most once.
  5. Multiply by the number of ways to include or omit the ones, then subtract the empty subset.
from typing import List

class Solution:
    def squareFreeSubsets(self, nums: List[int]) -> int:
        MOD = 10**9 + 7
        primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
        freq = [0] * 31

        for value in nums:
            freq[value] += 1

        ones = freq[1]
        dp = [0] * (1 << len(primes))
        dp[0] = 1  # The empty selection among values other than 1.

        for value in range(2, 31):
            count = freq[value]
            if count == 0:
                continue

            mask = 0
            square_free = True

            for i, prime in enumerate(primes):
                if value % (prime * prime) == 0:
                    square_free = False
                    break
                if value % prime == 0:
                    mask |= 1 << i

            if not square_free:
                continue

            previous = dp[:]
            for used_mask, ways in enumerate(previous):
                if ways and (used_mask & mask) == 0:
                    combined = used_mask | mask
                    dp[combined] = (dp[combined] + ways * count) % MOD

        # Each selection can include any subset of the ones.
        return (sum(dp) * pow(2, ones, MOD) - 1) % MOD

Complexity:

  • Time: O(n + V · 2^P), where V is the value range and P is the number of relevant primes.
  • Space: O(2^P) for the DP states.

Common follow-ups

  • How do duplicates affect the count? For a value greater than one, choose at most one copy; its frequency counts the choice of copy.
  • Why process from a DP snapshot? It prevents selecting the same value more than once during its transition.
  • What changes for a larger value range? The number of prime-mask states grows exponentially with the number of relevant primes, so this DP may no longer be practical.
CodingMediumMedia.netSoftware Engineer

10. Queue Reconstruction by Height (LeetCode)

Model answer

The task

Reorder people, each described by a height and a count of people at least as tall who must stand ahead of them. Return an arrangement that satisfies every count.

Key idea

Process people from shortest to tallest. For each person, the unfilled positions will eventually be occupied by people at least as tall as them, so their count tells us which unfilled position to choose. A Fenwick tree tracks unfilled positions and finds the requested one efficiently.

Approach

  1. Sort by increasing height, breaking ties by decreasing count.
  2. Initialize a Fenwick tree with every queue position marked empty.
  3. For each person, select the (count + 1)-th empty position.
  4. Put the person there and mark the position filled.
  5. Return the completed queue.
from typing import List

class FenwickTree:
    def __init__(self, n: int) -> None:
        # Initially, every position is empty.
        # For an all-ones array, each Fenwick node stores its low bit.
        self.n = n
        self.tree = [0] + [i & -i for i in range(1, n + 1)]

    def add(self, index: int, delta: int) -> None:
        """Add delta to the value at the zero-based index."""
        i = index + 1
        while i <= self.n:
            self.tree[i] += delta
            i += i & -i

    def kth(self, k: int) -> int:
        """Return the zero-based index of the k-th available position."""
        index = 0
        bit = 1 << (self.n.bit_length() - 1)

        while bit:
            next_index = index + bit
            if next_index <= self.n and self.tree[next_index] < k:
                index = next_index
                k -= self.tree[next_index]
            bit >>= 1

        return index

class Solution:
    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
        n = len(people)
        queue = [None] * n
        empty_positions = FenwickTree(n)

        # Shorter people are placed first; for equal heights, place
        # the larger required count first.
        people.sort(key=lambda person: (person[0], -person[1]))

        for height, count in people:
            position = empty_positions.kth(count + 1)
            queue[position] = [height, count]
            empty_positions.add(position, -1)

        return queue

Complexity:

  • Time: O(n log n), from sorting and Fenwick tree operations.
  • Space: O(n), for the queue and Fenwick tree.

Common follow-ups

  • Can this be done without a Fenwick tree? Yes; inserting each person into a list takes O(n²) time in the worst case.
  • Why sort equal heights by decreasing count? It ensures each person with the same height is placed consistently with the required number ahead.
  • What if the input is invalid? Verify the returned arrangement by counting qualifying people before each person.
System designHardMedia.netSoftware EngineerTechnical Interview (Algorithms, DS, CS Fundamentals)

11. Design an efficient hash function for 10 million strings, each 10 characters long and drawn from A-Z, a-z, and 0-9, with no or minimal collisions.

Model answer

1. Requirements & scale

  • Accept exactly 10-character strings over A-Z, a-z, and 0-9; produce a compact key with no collisions within that domain.
  • Reject invalid or non-canonical inputs rather than silently mapping them to the same key.
  • This domain is small enough for an injective encoding: 62^10 = 839,299,365,868,340,224 < 2^60. Therefore, a 60-bit integer can represent every valid input uniquely.
  • For 10 million strings, encoded keys occupy about 10M × 8 = 80 MB when stored as 64-bit integers. Storing the original strings adds about 100 MB before database/index overhead.
  • As an illustrative peak, ingesting 10 million strings in one minute is about 167K strings/second. Each input is only 10 bytes; the raw input-plus-key transfer is roughly 180 MB total, excluding protocol overhead.

2. High-level architecture

The core should be a small, deterministic encoder library shared by ingestion and lookup paths. An API wrapper is useful if callers cannot run the library locally; it is not part of the mathematical requirement.

flowchart TD
  subgraph Client["Client"]
    C["Submit string"]
  end
  subgraph Edge["Edge CDN"]
    E["TLS and rate limits"]
  end
  subgraph LB["Load Balancer"]
    L["Route requests"]
  end
  subgraph Services["API / Services"]
    V["Validate alphabet and length"]
    H["Base-62 encode and mix"]
  end
  subgraph Cache["Cache"]
    K["Optional key lookup cache"]
  end
  subgraph Stores["Datastores"]
    D["Records keyed by 64-bit value"]
  end
  subgraph Queue["Message Queue"]
    Q["Optional async audit events"]
  end
  subgraph Workers["Workers"]
    W["Consume audit events"]
  end
  C -->|"10-character input"| E
  E -->|"validated transport"| L
  L -->|"request"| V
  V -->|"valid string"| H
  H -->|"encoded key"| K
  K -->|"cache miss or write"| D
  H -->|"optional event"| Q
  Q -->|"audit event"| W
Diagram

3. API design

  • POST /v1/keys:encode — validate a string and return its 64-bit encoded key.
  • POST /v1/keys:batchEncode — encode a batch to amortize network and request overhead.
  • GET /v1/records/{key} — retrieve a record by encoded key, if the service also owns record lookup.

Return the key as a decimal string or fixed-width hexadecimal string in JSON. JSON numbers cannot safely represent arbitrary 64-bit integers in JavaScript clients.

4. Data model & storage

  • Store the key as an unsigned 64-bit integer, or as signed int64: every encoded value is below 2^60, so it fits either representation.
  • A record table can use encoded_key as the primary key and retain the original 10-byte string when reversibility, auditing, or display is required.
  • Partition a large record store by a well-distributed mixed key, not by the raw input prefix. For 10 million rows, a single well-indexed store may suffice; shard only when measured capacity requires it.
  • Keep the encoder stateless. Cache only if profiling shows repeated lookups justify it; caching computed keys is unnecessary for correctness.

5. Deep dive

Map each permitted character to a distinct digit in [0, 61], using one fixed alphabet order, for example A-Z, then a-z, then 0-9. Process the string left to right:

h₀ = 0; hᵢ₊₁ = 62 × hᵢ + digit(cᵢ).

After 10 characters, h is the string's base-62 numeral interpreted as an integer. Since all inputs have the same length and each character has a unique digit, this mapping is injective: two different strings cannot produce the same value. The maximum value is 62^10 - 1, which fits in 60 bits. This is stronger than choosing a conventional 64-bit hash: it has zero collisions over the specified domain.

sequenceDiagram
  participant C as Client
  participant S as Encoder service
  participant D as Record store
  C->>S: Submit 10-character string
  S->>S: Validate length and alphabet
  S->>S: Accumulate h = 62h + digit
  S->>D: Read or write using unique key h
  D-->>S: Record or write result
  S-->>C: Return key as hex or decimal string
Diagram

The base-62 value preserves lexical ordering, which may concentrate related strings in nearby key ranges. If keys drive hash-table buckets or shard selection, apply a fixed bijective 64-bit permutation after encoding—for example, xor-shifts and multiplication by odd constants modulo 2^64. Each operation is reversible, so distinct inputs remain distinct, while the resulting key bits are more dispersed. Do not truncate the result. If a downstream interface requires 32 bits, collisions are unavoidable: 62^10 possible inputs cannot fit in 2^32 outputs.

6. Scale, bottlenecks & trade-offs

  • CPU: encoding takes 10 digit lookups and 10 multiply-add steps per input; it is cheap and has no shared state. Batch APIs reduce per-request overhead.
  • Distribution: base-62 encoding is collision-free but not automatically a good shard key for skewed or prefix-correlated data. Use the reversible mixer before selecting shard bits, and monitor per-shard load.
  • Correctness: use the same alphabet order and validation rules in every implementation. Add cross-language test vectors and reject malformed inputs before encoding.
  • Security: the mixer is for distribution, not cryptographic secrecy. If clients can deliberately target hash-table buckets, use a keyed, vetted hash for the bucket index or enforce rate limits; retain the injective key as the canonical identity.
  • Trade-off: direct encoding uses slightly more bits than a collision-prone short hash, but it avoids collision resolution and makes identity exact for this fixed domain. If the input domain later expands, revisit the encoding and version the key format rather than silently changing it.
TechnicalEasyMedia.netSoftware EngineerTechnical Interview (Algorithms, DS)

12. Do you know about cross-site scripting (XSS) attacks?

Model answer

Yes. Cross-site scripting (XSS) occurs when an application includes attacker-controlled content in a page in a way that lets a browser execute it as code. An attacker might use it to act as a victim, read accessible page data, or alter what the victim sees. HttpOnly cookies can reduce cookie theft, but they do not prevent an attacker from performing actions through the victim’s browser.

Common forms include:

  • Stored XSS: Malicious content is saved, then rendered for other users, such as in a comment.
  • Reflected XSS: Input in a request is immediately included in the response, such as in an error message.
  • DOM-based XSS: Client-side code puts untrusted data into an unsafe DOM sink, such as innerHTML.

I’d prevent it by treating all untrusted input as data:

  1. Encode output for its context—HTML text, attributes, URLs, and JavaScript each require appropriate handling. Prefer framework templating that escapes by default.
  2. Avoid unsafe DOM APIs. Use textContent instead of innerHTML for plain text. If rich HTML is required, sanitize it with a maintained allowlist-based sanitizer.
  3. Validate input for correctness, but don’t rely on input validation alone to prevent XSS.
  4. Add a Content Security Policy (CSP) as defense in depth, not as a substitute for safe rendering.
  5. Test stored, reflected, and DOM rendering paths, including unusual input and URL schemes.
flowchart LR
    A[Untrusted input] --> B{Safe handling?}
    B -->|Contextual encoding or sanitization| C[Rendered as data]
    B -->|Unsafe HTML or script sink| D[Browser may execute attacker code]
    E[CSP] -. Defense in depth .-> D
Diagram
TechnicalEasyMedia.netSoftware EngineerTechnical Interview (Algorithms, DS)

13. What are the different HTTP response codes?

Model answer

HTTP response codes are three-digit status codes grouped by their first digit:

  1. 1xx — Informational: The request is still in progress. Examples: 100 Continue, 101 Switching Protocols, 103 Early Hints.
  2. 2xx — Success: The request succeeded. Examples: 200 OK, 201 Created, 202 Accepted (queued for processing), 204 No Content.
  3. 3xx — Redirection: The client needs to use another resource or follow a redirect. Examples: 301 Moved Permanently, 302 Found, 304 Not Modified (use a cached response), 307 Temporary Redirect, 308 Permanent Redirect.
  4. 4xx — Client error: The request is invalid, unauthorized, or cannot be fulfilled as sent. Examples: 400 Bad Request, 401 Unauthorized (authentication required or failed), 403 Forbidden (not permitted), 404 Not Found, 409 Conflict, 429 Too Many Requests.
  5. 5xx — Server error: The server failed to complete an otherwise valid request. Examples: 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout.

The exact code matters to clients, caches, and monitoring. For example, 401 typically prompts authentication, 403 indicates access is denied, and 429 may include a Retry-After header. In an ad-serving system, correctly distinguishing 5xx failures from expected 4xx responses helps avoid retrying bad requests and helps measure service reliability.

TechnicalEasyMedia.netSoftware EngineerTechnical Interview (Web, Databases)

14. What is XMLHttpRequest?

Model answer

XMLHttpRequest (XHR) is a browser API for making HTTP requests from JavaScript without navigating away from the current page. Despite its name, it can transfer JSON, text, HTML, binary data, and other response types—not just XML.

A typical XHR request is asynchronous: the page starts the request, continues running, and handles the response through callbacks or event listeners. The API exposes the HTTP method, URL, request headers, response status, response body, and events such as load, error, and timeout.

const xhr = new XMLHttpRequest();
xhr.open("GET", "/api/profile", true); // true means asynchronous
xhr.responseType = "json";
xhr.timeout = 5000;

xhr.addEventListener("load", () => {
  if (xhr.status >= 200 && xhr.status < 300) {
    console.log(xhr.response);
  } else {
    console.error("HTTP error:", xhr.status);
  }
});

xhr.addEventListener("error", () => console.error("Network error"));
xhr.addEventListener("timeout", () => console.error("Request timed out"));
xhr.send();

XHR is an older, widely supported API. For most new code, fetch() is usually simpler and promise-based, though XHR still has capabilities such as upload-progress events that can be useful.

TechnicalMediumMedia.netSoftware EngineerTechnical Interview (Web, Databases)

15. How do sessions work and where are they stored?

The full question

How do sessions work and where are they stored? What alternatives are there for storing them? If the client disables cookies, how can the server recognize the session, and how do sessions persist across requests?

Model answer

A session is server-side state associated with a client across multiple HTTP requests. HTTP itself is stateless, so each request needs to carry a way for the server to identify the session.

  1. Typical cookie-based flow: After login, the server creates a random, hard-to-guess session ID and stores a record such as {userId, expiresAt, permissions} in a session store. It sends the ID to the browser in a cookie. The browser sends that cookie on later matching requests, and the server looks up the session.
  2. Where sessions are stored: They can live in process memory, a shared cache such as Redis, or a database. In-memory storage is simple but is lost on restart and does not naturally work across multiple servers. A shared store supports multiple application instances; TTLs and expiry cleanup control old sessions. Sticky load balancing can keep a client on one server, but it is less resilient than a shared store.
  3. If cookies are disabled: The server cannot identify the same client across requests unless the client sends some identifier by another mechanism. Common alternatives are an opaque session token in an Authorization header, or a signed token such as a JWT. The client must retain and resend it. Putting session IDs in URLs is generally unsafe because URLs can leak through logs, browser history, and referrer headers. IP address or user-agent matching is not a reliable substitute.
  4. Persistence across requests: The client presents the session ID/token on each request; the server validates it and retrieves or verifies the associated state. A session may expire after a fixed lifetime or an inactivity timeout, and logout should invalidate it. Rotate the session ID after authentication or privilege changes to reduce session-fixation risk.
sequenceDiagram
    participant B as Browser or client
    participant A as Application server
    participant S as Session store
    B->>A: Login credentials
    A->>S: Create session record
    S-->>A: Session ID
    A-->>B: Set session cookie or return token
    B->>A: Next request with ID or token
    A->>S: Load and validate session
    S-->>A: Session state
    A-->>B: Response
Diagram

A session ID is a credential: use HTTPS, keep it unpredictable, set appropriate cookie protections when using cookies, and never expose it in logs.

TechnicalMediumMedia.netSoftware EngineerTechnical Interview (Algorithms, DS)

16. What mechanisms would you need in order to use an in-memory database?

Model answer

To use an in-memory database reliably, I’d plan for more than simply putting data in RAM:

  1. Memory and data lifecycle: Estimate the working set, including keys, values, indexes, and allocator overhead. Define TTLs, eviction behavior, and what happens when capacity is reached. For a cache, make misses safe by falling back to the durable source of truth.
  2. Durability and recovery: Decide whether data is disposable or must survive restarts. If it must, enable an appropriate persistence mechanism—such as snapshots and/or an append-only log—and test restore time and data-loss limits. Keep backups outside the database host.
  3. Availability: Use replicas and automated failover where the workload requires them. Make clients handle reconnects, timeouts, and retryable errors safely; retries should be bounded and writes should be idempotent where possible.
  4. Consistency and cache correctness: Define how updates reach the in-memory copy: write-through, write-behind, or cache-aside. Specify invalidation or versioning so stale values do not persist beyond the acceptable window.
  5. Concurrency and access: Use the database’s atomic operations or transactions for updates that must not race. Apply authentication, network restrictions, encryption where required, and least-privilege access.
  6. Operations: Monitor memory use, hit rate, evictions, latency, replication lag, persistence health, and failovers. Load-test both the normal path and cold-cache or recovery scenarios.

A typical cache-aside setup might look like this:

flowchart LR
    A["Application"] -->|"Read key"| C["In-memory cache"]
    C -->|"Hit: return value"| A
    C -->|"Miss"| D["Durable database"]
    D -->|"Load value"| A
    A -->|"Set value with TTL"| C
    W["Update service"] -->|"Commit change"| D
    W -->|"Invalidate or refresh key"| C
Diagram

The main choice is whether the in-memory database is a cache or the primary store. For a cache, misses and eviction should be correct and inexpensive. If it is the primary store, persistence, replication, backup, and recovery become correctness requirements, not optional optimizations.

TechnicalMediumMedia.netSoftware EngineerTechnical Interview (Algorithms, DS)

17. How do sessions work in PHP, where are they stored, and how do stateless HTTP requests associate with the same user session?

Model answer

HTTP itself is stateless: each request is independent, and the server does not inherently know which earlier request came from the same user. PHP sessions add continuity by having the client send an opaque session identifier on later requests.

sequenceDiagram
    participant B as Browser
    participant P as PHP application
    participant S as Session storage
    B->>P: Request without session cookie
    P->>S: Create session and save data
    P-->>B: Response with session ID cookie
    B->>P: Next request with session ID cookie
    P->>S: Load data for that ID
    S-->>P: Session values
    P-->>B: Response
Diagram
  1. Start or resume a session: The application calls session_start(). PHP checks the request for its session ID, commonly in a cookie named PHPSESSID. If no valid ID is provided, PHP creates one.
  2. Store session data: Code reads and writes values through $_SESSION, for example $_SESSION['user_id'] = 42. By default, PHP stores session data on the server, commonly in files under the configured session.save_path. Applications can configure another backend, such as Redis or a custom session handler.
  3. Associate later requests: PHP sends the session ID to the browser in a Set-Cookie response header. The browser returns it in a Cookie request header. PHP uses that ID as a lookup key to load the corresponding server-side session data.
  4. Save updates: PHP typically reads session data when the session starts and writes changes when the request completes or the session is closed. The browser holds the identifier, not the session data itself.

The session ID is a bearer credential: someone who steals it may impersonate the user. Use HTTPS and cookie flags such as Secure, HttpOnly, and an appropriate SameSite; regenerate the ID after login or privilege changes; and set sensible expiration and cleanup policies. Avoid putting sensitive session contents in a client-controlled cookie unless they are protected appropriately.

TechnicalMediumMedia.netSoftware EngineerTechnical Interview (Web, Databases)

18. What should you consider when calling a third-party API that you do not own?

Model answer

When calling an API another team owns, I treat it as an unreliable dependency and make its contract explicit.

  1. Understand the contract: Confirm authentication, request/response schemas, error codes, rate limits, pagination, versioning, and deprecation policy. Check whether the API is synchronous and what its latency and availability expectations are.
  2. Protect availability: Set connection and total timeouts. Retry only transient failures, with exponential backoff, jitter, and a retry limit. Retry non-idempotent operations only when the API supports idempotency keys; otherwise a retry could create duplicate actions.
  3. Handle responses defensively: Validate status codes, content types, required fields, and response sizes. Treat upstream data as untrusted; handle malformed responses and unknown fields without crashing.
  4. Secure the integration: Keep credentials in a secrets manager, use TLS, least-privilege scopes, and rotation. Avoid logging tokens or personal data, and verify the provider’s data-retention and privacy terms.
  5. Make failures manageable: Use rate limiting and, where appropriate, a circuit breaker or fallback. Cache only when freshness and the provider’s terms allow it. Monitor latency, error rate, timeout rate, and quota consumption, and include a correlation ID in logs.
flowchart LR
    A[Application] -->|Validated request| B[Timeout and rate limit]
    B -->|Authenticated call| C[Third-party API]
    C -->|Response or error| D[Validate and classify]
    D -->|Success| E[Application result]
    D -->|Transient failure| F[Bounded retry or fallback]
    F --> E
Diagram

For example, if an ad-related provider times out, I would not let that stall the whole page request indefinitely: I’d enforce a deadline and return a safe fallback while recording the dependency failure.

TechnicalMediumMedia.netSoftware EngineerTechnical Interview (Web, Databases)

19. What are cookies, what would you store in them, where are they stored, and how can an end user view them?

Model answer

A cookie is a small name-value data item that a website asks the browser to store. The browser can send it back in later HTTP requests when its domain, path, and security rules match.

  • What to store: Common uses include a session identifier, a consent choice, or a small preference such as locale. Keep sensitive application state on the server and store only an opaque session ID in the cookie. Do not treat a cookie as secret or trust its contents unless they are appropriately signed and validated.
  • Where it is stored: The browser stores cookies for a site. A cookie may be persistent, with an expiry or Max-Age, or a session cookie that is generally removed when the browser session ends. Cookies are separate from server-side session data: the browser may hold the ID while the server holds the associated account/session record.
  • How it is sent: The browser normally includes applicable cookies in the Cookie request header. The server sets them with the Set-Cookie response header. Cookie attributes control behavior: Secure restricts transmission to HTTPS, HttpOnly prevents access from page JavaScript, SameSite helps limit cross-site sending, and Domain, Path, and expiry scope the cookie.
  • How a user can view them: In browser developer tools, open the Application tab in Chrome or Storage in Firefox and select Cookies for the site. Users can also inspect request and response headers in the Network panel. HttpOnly cookies are still visible in developer tools, but page JavaScript cannot read them through document.cookie.

For authentication cookies, a typical choice is Secure; HttpOnly; SameSite=Lax over HTTPS, adjusted to the application’s cross-site needs. Cookie-based authentication also requires considering CSRF protections.

TechnicalMediumMedia.netSoftware EngineerTechnical Interview (Algorithms, DS)

20. How is a website loaded?

Model answer

A typical website navigation follows this path:

flowchart TD
    A[User enters URL] --> B[Browser checks cache]
    B --> C[DNS resolves hostname]
    C --> D[Connect to server]
    D --> E[Send HTTP request]
    E --> F[CDN or origin returns HTML]
    F --> G[Parse HTML and fetch resources]
    G --> H[Build DOM and CSSOM]
    H --> I[Layout and paint]
    I --> J[Display page]
    G --> K[Run JavaScript]
    K --> H
Diagram
  1. Resolve the host: The browser checks relevant caches, then uses DNS to find an IP address for the hostname.
  2. Establish a connection: It connects to the server, often through a CDN or load balancer. HTTPS adds a TLS handshake to authenticate the server and establish encryption. HTTP/2 or HTTP/3 may be negotiated.
  3. Request the page: The browser sends an HTTP request with headers and, when applicable, cookies. A CDN, reverse proxy, or application server handles it and returns a status, headers, and body.
  4. Receive and parse HTML: As HTML arrives, the browser builds the DOM and discovers referenced CSS, JavaScript, images, and fonts. It requests those resources, potentially in parallel and from multiple origins.
  5. Render: The browser parses CSS into the CSSOM, combines it with the DOM, calculates layout, then paints and composites pixels to the screen. CSS and JavaScript can affect when rendering proceeds.
  6. Run application code: JavaScript can update the DOM, fetch API data, and attach event handlers. A single-page app may render or hydrate parts of the page after the initial HTML is displayed.

Caching can shorten several steps: the browser may reuse DNS results, connections, or cached resources, while a CDN may serve content without reaching the origin.

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