Baidu interview questions & answers

20 real Baidu interview questions with full model answers — Coding, Technical. Drawn from the same verified bank ChannelPulse drills from (32 Baidu questions in total).

CodingMediumBaiduFrontend EngineerFirst Round

1. How would you implement a three-column layout using flex, position, and float?

The full question

How would you implement a three-column layout using flex, position, and float? Share the code.

Model answer

Below is a complete JavaScript example that creates three separate three-column layouts: Flexbox, positioning, and floats. Each layout has a fixed-width left and right column with a flexible center column.

// Add the styles for all three layout techniques.
const style = document.createElement("style");
style.textContent = `
  * { box-sizing: border-box; }
  body { font-family: sans-serif; margin: 24px; }
  .demo { margin: 0 0 32px; }
  .row { min-height: 120px; }
  .left, .right { width: 180px; padding: 16px; background: #e8eef8; }
  .center { padding: 16px; background: #f4f4f4; }

  /* Flexbox: the center column grows to fill available space. */
  .flex-row { display: flex; }
  .flex-row .center { flex: 1; }

  /* Positioning: reserve space for the absolutely positioned side columns. */
  .position-row { position: relative; padding: 0 180px; }
  .position-row .left,
  .position-row .right { position: absolute; top: 0; bottom: 0; }
  .position-row .left { left: 0; }
  .position-row .right { right: 0; }

  /* Floats: the center occupies the space between the floated columns. */
  .float-row::after { content: ""; display: block; clear: both; }
  .float-row .left { float: left; }
  .float-row .right { float: right; }
  .float-row .center { overflow: hidden; }

  @media (max-width: 640px) {
    .flex-row { flex-direction: column; }
    .flex-row .left, .flex-row .right { width: 100%; }
    .position-row { padding: 0; }
    .position-row .left, .position-row .right {
      position: static; width: 100%;
    }
    .float-row .left, .float-row .right {
      float: none; width: 100%;
    }
  }
`;
document.head.appendChild(style);

// Create the same three-column content for each layout demonstration.
function createDemo(title, layoutClass) {
  const section = document.createElement("section");
  section.className = "demo";
  section.innerHTML = `
    <h2>${title}</h2>
    <div class="row ${layoutClass}">
      <aside class="left">Left column</aside>
      <main class="center">Center column</main>
      <aside class="right">Right column</aside>
    </div>
  `;
  document.body.appendChild(section);
}

createDemo("Flexbox", "flex-row");
createDemo("Positioning", "position-row");
createDemo("Floats", "float-row");
  • Flexbox is the most straightforward modern choice for this layout; flex: 1 lets the center use remaining space.
  • Positioning takes the side columns out of normal flow, so the parent must reserve their width.
  • Floats require clearing; overflow: hidden also establishes a block formatting context for the center.
CodingMediumBaiduSoftware Engineer

2. Longest Substring with At Least K Repeating Characters (LeetCode)

Model answer

The task

Find the length of the longest contiguous part of a string in which every character appears at least k times.

Key idea

For a window with a fixed number of distinct characters, use a sliding window and track how many characters meet the frequency threshold. Try each possible distinct-character count; for a fixed count, the window moves only forward.

Approach

  1. Return the full string length when k <= 1.
  2. Count the distinct characters in the string; try each value from 1 up to that count as the window’s target.
  3. Expand the window one character at a time, tracking each character’s frequency and how many distinct characters meet k.
  4. If the window has too many distinct characters, move its left edge forward until it meets the target.
  5. Record the longest window where every distinct character meets the threshold.
class Solution:
    def longestSubstring(self, s: str, k: int) -> int:
        if k <= 1:
            return len(s)

        n = len(s)
        best = 0

        # Try every possible number of distinct characters in a valid window.
        for target_unique in range(1, len(set(s)) + 1):
            counts = {}
            left = 0
            unique = 0
            at_least_k = 0

            for right, char in enumerate(s):
                counts[char] = counts.get(char, 0) + 1

                if counts[char] == 1:
                    unique += 1
                if counts[char] == k:
                    at_least_k += 1

                # Keep the window's distinct-character count within the target.
                while unique > target_unique:
                    removed = s[left]
                    if counts[removed] == k:
                        at_least_k -= 1
                    counts[removed] -= 1
                    if counts[removed] == 0:
                        unique -= 1
                    left += 1

                if unique == target_unique and at_least_k == target_unique:
                    best = max(best, right - left + 1)

        return best

Complexity:

  • Time: O(D · n), where D is the number of distinct characters; each pass scans the string.
  • Space: O(D) for the character-frequency map.

Common follow-ups

  • Can divide and conquer solve it? Yes: split at a character occurring fewer than k times in the current substring, then solve the resulting parts.
  • What if the character set is large? The sliding-window method still works, but its time grows with the number of distinct characters.
  • How would you return the substring, not just its length? Store the best window’s start and end indices whenever updating best.
CodingMediumBaiduSoftware Engineer

3. Out of Boundary Paths (LeetCode)

Model answer

The task

Count the ways to leave an m × n grid from a given starting cell using at most maxMove moves. Return the count modulo \(10^9+7\).

Key idea

Use dynamic programming to track how many ways reach each cell after a given number of moves. When a move goes outside the grid, add that path to the answer instead of storing it in the next state.

Approach

  1. Initialize a grid of path counts with one way at the starting cell.
  2. For each allowed move, create a fresh grid for paths that remain inside.
  3. Send each cell’s paths in all four directions.
  4. Add paths that leave the grid to the answer; add in-bounds paths to the fresh grid.
  5. Return the accumulated answer modulo \(10^9+7\).
class Solution:
    def findPaths(
        self,
        m: int,
        n: int,
        maxMove: int,
        startRow: int,
        startColumn: int,
    ) -> int:
        mod = 10**9 + 7
        directions = ((1, 0), (-1, 0), (0, 1), (0, -1))

        # ways[r][c] counts paths reaching (r, c) after the current moves.
        ways = [[0] * n for _ in range(m)]
        ways[startRow][startColumn] = 1
        escaped = 0

        for _ in range(maxMove):
            next_ways = [[0] * n for _ in range(m)]

            for row in range(m):
                for col in range(n):
                    count = ways[row][col]
                    if count == 0:
                        continue

                    for dr, dc in directions:
                        nr, nc = row + dr, col + dc

                        if 0 <= nr < m and 0 <= nc < n:
                            next_ways[nr][nc] = (
                                next_ways[nr][nc] + count
                            ) % mod
                        else:
                            escaped = (escaped + count) % mod

            ways = next_ways

        return escaped

Complexity:

  • Time: \(O(\text{maxMove} \cdot m \cdot n)\), processing each cell and its four neighbors per move.
  • Space: \(O(m \cdot n)\), storing the current and next path-count grids.

Common follow-ups

  • What if paths must leave on exactly the final move? Accumulate exits only during the final iteration.
  • Can space be reduced further? Rolling grids already use space proportional to the number of cells.
  • What if moves have different allowed directions? Replace the four-direction list with the permitted transitions.
CodingMediumBaiduSoftware Engineer

4. Length of Longest Fibonacci Subsequence (LeetCode)

Model answer

The task

Given a strictly increasing array, find the length of its longest subsequence in which each term after the first two is the sum of the previous two. Return 0 if no such subsequence has length at least three.

Key idea

For each pair of ending values, dynamic programming stores the longest Fibonacci-like subsequence ending with that pair. The previous value is determined by subtraction, and a hash map lets us check whether it appears before the pair.

Approach

  1. Map each array value to its index.
  2. Initialize the DP table so every pair has length 2.
  3. For each pair of indices (i, j), look for arr[j] - arr[i] at an index k < i.
  4. If found, extend the subsequence ending at (k, i) and update the best length.
  5. Return the best length if it is at least 3; otherwise return 0.
from typing import List

class Solution:
    def lenLongestFibSubseq(self, arr: List[int]) -> int:
        n = len(arr)
        index = {value: i for i, value in enumerate(arr)}

        # dp[i][j] is the longest sequence ending with arr[i], arr[j].
        dp = [[2] * n for _ in range(n)]
        longest = 0

        for j in range(n):
            for i in range(j):
                previous = arr[j] - arr[i]
                k = index.get(previous)

                # The previous term must occur before arr[i].
                if k is not None and k < i:
                    dp[i][j] = dp[k][i] + 1
                    longest = max(longest, dp[i][j])

        return longest if longest >= 3 else 0

Complexity:

  • Time: O(n²), for examining every index pair.
  • Space: O(n²), for the dynamic programming table.

Common follow-ups

  • How would you reduce memory? Store only the DP states needed for future transitions, though the straightforward table is simpler.
  • What if the array is not sorted? Sort it first if reordering is allowed; otherwise, the subsequence order must be preserved.
  • What if the task asks for the sequence itself? Store predecessor information for each DP state and backtrack from the longest one.
CodingMediumBaiduSoftware Engineer

5. Arithmetic Slices (LeetCode)

Model answer

The task

Count the contiguous subarrays of length at least three whose consecutive differences are all equal.

Key idea

When a new number continues an arithmetic run, it extends every valid slice ending at the previous number and creates one new slice. Track how many valid slices end at the current position and add that count to the total.

Approach

  1. Return zero if the array has fewer than three elements.
  2. Scan from the third element onward.
  3. Compare the current difference with the preceding difference.
  4. If they match, increment the count of slices ending here and add it to the answer.
  5. Otherwise, reset the ending count to zero.
from typing import List

class Solution:
    def numberOfArithmeticSlices(self, nums: List[int]) -> int:
        # A slice needs at least three elements.
        if len(nums) < 3:
            return 0

        total = 0
        ending_here = 0

        for i in range(2, len(nums)):
            current_diff = nums[i] - nums[i - 1]
            previous_diff = nums[i - 1] - nums[i - 2]

            if current_diff == previous_diff:
                # Extend all arithmetic slices ending at i - 1,
                # and add the new length-three slice.
                ending_here += 1
                total += ending_here
            else:
                # No arithmetic slice ending here can cross this break.
                ending_here = 0

        return total

Complexity:

  • Time: O(n), where n is the number of array elements; each element is checked once.
  • Space: O(1), using only a few counters.

Common follow-ups

  • What if slices of length two count? Every adjacent pair would qualify, so add the number of adjacent pairs separately.
  • What if the array is streamed? Keep the previous two values, the current run’s ending count, and the total; update them as values arrive.
  • How would you return the slices, not just their count? Track each arithmetic run’s boundaries, then enumerate its qualifying subarrays; the output can be quadratic in the run length.
CodingMediumBaiduFrontend EngineerFirst Round

6. How can inheritance be implemented in JavaScript using ES5 and ES6?

The full question

How can inheritance be implemented in JavaScript using ES5 and ES6? Write the code.

Model answer

// ES5-style inheritance: call the parent constructor and link prototypes.
function Animal(name) {
  this.name = name;
}

Animal.prototype.speak = function () {
  return `${this.name} makes a sound`;
};

function Dog(name, breed) {
  Animal.call(this, name); // Initialize this instance's Animal fields.
  this.breed = breed;
}

Dog.prototype = Object.create(Animal.prototype); // Inherit instance methods.
Dog.prototype.constructor = Dog; // Restore the expected constructor reference.
Dog.prototype.speak = function () {
  return `${this.name} barks`;
};

const es5Dog = new Dog("Milo", "collie");
console.log(es5Dog.speak()); // Milo barks
console.log(es5Dog instanceof Animal); // true

// ES6 class syntax: extends links prototypes; super initializes the parent.
class AnimalES6 {
  constructor(name) {
    this.name = name;
  }

  speak() {
    return `${this.name} makes a sound`;
  }
}

class DogES6 extends AnimalES6 {
  constructor(name, breed) {
    super(name); // Must run before using this in a derived constructor.
    this.breed = breed;
  }

  speak() {
    return `${this.name} barks`;
  }
}

const es6Dog = new DogES6("Milo", "collie");
console.log(es6Dog.speak()); // Milo barks
console.log(es6Dog instanceof AnimalES6); // true
  • In ES5, Animal.call(this, ...) inherits instance initialization; Object.create(...) establishes the prototype chain.
  • ES6 extends and super provide clearer syntax for the same prototype-based model.
  • Resetting Dog.prototype.constructor in the ES5 version avoids leaving it pointing at Animal.

Complexity: Instance construction is O(1) aside from initializing fields. Method lookup is O(1) on average and O(depth) in the worst case for a prototype chain of depth depth.

CodingMediumBaiduSoftware Engineer

7. Integer Replacement (LeetCode)

Model answer

The task

Find the fewest operations needed to reduce a positive integer to 1. An operation halves an even value, or adds or subtracts 1 from an odd value.

Key idea

For odd values, choose the adjustment that creates more trailing zero bits, allowing more divisions by 2. The exception is 3: subtracting 1 reaches 2 directly, while adding 1 takes longer.

Approach

  1. Keep a counter for the operations.
  2. While the value is greater than 1, halve it if it is even.
  3. If it is odd and equals 3, or its last two bits are 01, subtract 1.
  4. Otherwise, add 1. This gives a value divisible by 4.
  5. Count each operation and return the total.
class Solution:
    def integerReplacement(self, n: int) -> int:
        operations = 0

        while n > 1:
            if n % 2 == 0:
                n //= 2
            elif n == 3 or n % 4 == 1:
                # Removing the final 1 bit exposes a useful even value.
                n -= 1
            else:
                # For odd n > 3 ending in binary 11, this creates
                # a value divisible by 4.
                n += 1

            operations += 1

        return operations

Complexity:

  • Time: O(log n), since each operation quickly reduces the number of bits.
  • Space: O(1), using only a fixed amount of extra storage.

Common follow-ups

  • Can this be solved with memoization? Yes; recursively compute the minimum for smaller values, though the iterative greedy method uses less space.
  • Why does the n == 3 exception matter? Subtracting reaches 2, then 1, in two operations.
  • What about very large inputs? Use an integer type that can represent the input and its increment; Python integers handle this automatically.
CodingMediumBaiduFrontend EngineerFirst Round

8. Implement a function so that plus(1)(2)(3)(4) evaluates to 8.

Model answer

There is an inconsistency in the example: ordinary addition gives 1 + 2 + 3 + 4 = 10, not 8. The implementation below provides standard curried addition; convert the returned function to a number to observe the result.

function plus(value) {
  let total = value;

  function next(addend) {
    total += addend;
    return next;
  }

  // Allows numeric coercion, e.g. Number(plus(1)(2)(3)(4)).
  next[Symbol.toPrimitive] = () => total;
  return next;
}

console.log(Number(plus(1)(2)(3)(4))); // 10
  • Each call adds its argument and returns the same callable function, enabling chaining.
  • If 8 is required, the intended operation needs clarification; standard addition cannot produce that result for these inputs.

Complexity: O(k) time and O(1) additional space for k chained calls.

CodingMediumBaiduFrontend EngineerFirst Round

9. Write a program that flattens an array, removes duplicate elements, and returns the remaining elements in ascending order.

Model answer

function flattenUniqueSorted(array) {
  // Flatten nested arrays, keep each value once, then sort numerically.
  return [...new Set(array.flat(Infinity))].sort((a, b) => a - b);
}

console.log(flattenUniqueSorted([3, [1, [2, 3]], 1])); // [1, 2, 3]
  • flat(Infinity) handles arrays nested to any depth; Set removes duplicates.
  • The comparator sorts numbers in ascending order rather than lexicographically.

Complexity: O(n log n) time for n flattened elements; O(n) space.

CodingHardBaiduSoftware Engineer

10. Design In-Memory File System (LeetCode)

Model answer

The task

Build an in-memory file system that supports listing paths, creating directories, appending text to files, and reading file contents.

Key idea

Represent directories and files as nodes in a trie, with each node mapping names to children. Mark file nodes explicitly and store their content in chunks so repeated appends don’t repeatedly copy the existing contents.

Approach

  1. Split paths into their non-empty components; the root corresponds to no components.
  2. Use a traversal helper to find a node, optionally creating missing nodes along the way.
  3. For a listing, return the file’s name if the path is a file; otherwise return its children’s names in sorted order.
  4. Create directories by traversing the path with node creation enabled.
  5. For file writes, create the path as needed, mark the final node as a file, and append the new chunk.
  6. For reads, join the file’s stored chunks.
class Node:
    def __init__(self):
        self.children = {}
        self.is_file = False
        self.content = []

class FileSystem:
    def __init__(self):
        self.root = Node()

    @staticmethod
    def _parts(path):
        return [part for part in path.split("/") if part]

    def _walk(self, path, create=False):
        node = self.root

        for part in self._parts(path):
            if part not in node.children:
                if not create:
                    return None
                node.children[part] = Node()
            node = node.children[part]

        return node

    def ls(self, path):
        node = self._walk(path)
        if node.is_file:
            return [self._parts(path)[-1]]
        return sorted(node.children)

    def mkdir(self, path):
        self._walk(path, create=True)

    def addContentToFile(self, filePath, content):
        node = self._walk(filePath, create=True)
        node.is_file = True
        node.content.append(content)

    def readContentFromFile(self, filePath):
        node = self._walk(filePath)
        return "".join(node.content)

Complexity:

  • Time: ls takes O(d + k log k), where d is the path depth and k is the number of children listed. Other operations take O(d), excluding the cost of reading or appending content.
  • Space: O(n + c), where n is the number of trie nodes and c is the total stored file content.

Common follow-ups

  • How would you support deleting files or directories? Remove the node, ensuring directories are empty if required.
  • How would you support moving or renaming paths? Detach the node from its parent and attach it under the new parent.
  • How would you support very large files? Store content in external or chunked storage rather than keeping all text in memory.
TechnicalEasyBaiduFrontend EngineerFirst Round

11. What is the MVVM pattern?

Model answer

MVVM stands for Model–View–ViewModel, a UI architecture that separates application data and logic from presentation.

  • Model: The data and domain logic, such as a search query or result list.
  • View: The UI that displays state and captures user input.
  • ViewModel: The presentation layer between them. It exposes view-ready state and actions, and coordinates updates.

In Vue, a component’s reactive state and methods often play the ViewModel role. Template bindings render that state, while events call methods that update it. Vue’s reactivity system propagates changes back to the view, so developers usually do not manually update the DOM.

flowchart LR
  U[User input] --> V[View]
  V -->|events| VM[ViewModel]
  VM -->|read or update| M[Model]
  M -->|reactive state| VM
  VM -->|bindings| V
Diagram

For example, a search box can bind its value to query; a ViewModel action submits the query, updates results, and the template renders the new results. MVVM is a useful mental model, not a requirement that every Vue application use a separate class named ViewModel.

TechnicalEasyBaiduFrontend EngineerFirst Round

12. What are the differences between let, const, and var in JavaScript?

Model answer

  1. var is function-scoped (or global-scoped), can be redeclared, and is hoisted with the value undefined. This means it can be accessed before its declaration without a ReferenceError, though the value may be surprising.
  2. let is block-scoped, can be reassigned, but cannot be redeclared in the same scope. It is hoisted but inaccessible in the temporal dead zone before its declaration.
  3. const is also block-scoped and has the same temporal dead zone behavior as let. Its binding cannot be reassigned, and it must be initialized when declared. For objects and arrays, the binding is fixed but the contents can still be mutated.
const settings = { theme: "light" };
settings.theme = "dark"; // Allowed: the object is still mutable.
// settings = {};         // TypeError: the const binding cannot be reassigned.

For modern frontend code, I use const by default and let when reassignment is needed. I avoid var because function scoping and redeclaration make code harder to reason about.

TechnicalEasyBaiduFrontend EngineerFirst Round

13. What is the role of the Symbol data type in JavaScript?

Model answer

Symbol is a primitive type used to create unique values, often as object property keys. Two symbols with the same description are still distinct:

const first = Symbol("id");
const second = Symbol("id");

console.log(first === second); // false

const record = { [first]: 42 };
console.log(record[first]); // 42

Key uses include:

  • Avoiding key collisions: a symbol-keyed property will not accidentally overwrite a string-keyed property with the same description.
  • Supporting built-in protocols: well-known symbols such as Symbol.iterator let objects define behavior used by language features like for...of.
  • Sharing named symbols intentionally: Symbol.for("name") looks up or creates a symbol in the global symbol registry; unlike Symbol("name"), calls with the same key return the same symbol.

Symbol-keyed properties are not included by Object.keys() or JSON.stringify(). Use Object.getOwnPropertySymbols() or Reflect.ownKeys() when you need to inspect them.

TechnicalEasyBaiduFrontend EngineerFirst Round

14. What is the difference between fixed and absolute positioning?

Model answer

  • position: fixed positions an element relative to the viewport, so it normally stays in the same place while the page scrolls. It is removed from normal document flow, so it does not reserve space where it would otherwise appear.
  • position: absolute positions an element relative to its nearest ancestor that establishes a positioning context—typically an ancestor with position: relative, absolute, or fixed. If there is no such ancestor, it uses the initial containing block. It is also removed from normal flow.
  • Important caveat: properties such as transform on an ancestor can establish a containing block for fixed-position descendants, changing the usual viewport behavior.

Use fixed for viewport-attached UI such as a persistent toolbar; use absolute for elements positioned within a component, such as a badge inside a card.

TechnicalEasyBaiduFrontend EngineerFirst Round

15. What is the purpose of the key attribute in Vue loops?

Model answer

The key attribute gives Vue a stable identity for each item in a v-for list. Vue uses it during virtual-DOM diffing to match old and new nodes, deciding which nodes to reuse, move, create, or remove.

<li v-for="user in users" :key="user.id">
  {{ user.name }}
</li>

Use a unique, stable primitive such as a database ID. If items can be inserted, deleted, or reordered, avoid using the array index: Vue may reuse a node for a different item, causing incorrect component state or preserving the wrong input value. Do not use a newly created object as a key, since object identity is unstable. Keys are especially important for stateful child components and form controls; they are not a substitute for correct data updates.

TechnicalEasyBaiduFrontend EngineerFirst Round

16. What are the basic data types in JavaScript?

Model answer

JavaScript has seven primitive types and one broad object type:

  • undefined — a value not assigned, or a missing property/result.
  • null — an intentional absence of a value.
  • boolean — true or false.
  • number — integers and floating-point values, including NaN and Infinity.
  • bigint — integers larger than the safe range of number, written with an n suffix, such as 123n.
  • string — text.
  • symbol — unique identifiers, often used as object keys.
  • object — compound values such as plain objects, arrays, dates, maps, and sets. Functions are callable objects.

A common gotcha: typeof null returns "object" for historical reasons, even though null is a primitive.

TechnicalMediumBaiduFrontend EngineerFirst Round

17. How does browser caching work, which request headers control it, what values can Cache-Control take, and how does strong caching differ from condit…

The full question

How does browser caching work, which request headers control it, what values can Cache-Control take, and how does strong caching differ from conditional caching?

Model answer

The browser cache stores responses and decides whether it can reuse them. A response can be reused without contacting the server while it is fresh; once stale, the browser may validate it with the server before reusing it.

Headers that control caching

  • Cache-Control is the main modern directive header. It can be sent on requests and responses; response directives are especially important for deciding how a response may be stored and reused.
  • Expires provides an absolute expiration date. Cache-Control: max-age generally takes precedence when both are present.
  • ETag supplies a validator. The browser can later send it in If-None-Match.
  • Last-Modified supplies a timestamp validator. The browser can later send it in If-Modified-Since.
  • Vary tells caches which request headers affect the representation, such as Accept-Encoding or Accept-Language.
  • Date helps caches calculate response age. Pragma: no-cache is a legacy compatibility header.

Common Cache-Control values

  • Freshness: max-age=seconds; for shared caches, s-maxage=seconds.
  • Storage policy: no-store prevents storage; private restricts storage to private caches; public allows shared-cache storage where otherwise restricted.
  • Revalidation: no-cache allows storage but requires validation before reuse; must-revalidate requires validation after a response becomes stale.
  • Other directives: immutable indicates a response will not change while fresh; stale-while-revalidate and stale-if-error permit serving stale content in specified cases.

no-cache does not mean “do not store”; that is no-store.

Strong caching versus conditional caching

In frontend terminology, strong caching means reusing a fresh response directly, with no network request. For example, Cache-Control: max-age=3600 lets a cached response be reused for an hour, subject to applicable cache rules.

With conditional caching, the cached response is stale, so the browser sends a validator. If unchanged, the server returns 304 Not Modified and the browser reuses its stored body; if changed, the server returns a new representation, typically with 200 OK.

flowchart TD
  A[Request resource] --> B{Fresh cached response?}
  B -->|Yes| C[Reuse locally]
  B -->|No| D[Send conditional request]
  D --> E{Resource changed?}
  E -->|No| F[304: reuse cached body]
  E -->|Yes| G[200: store new response]
Diagram

For frequently updated content, validators can reduce bandwidth while keeping results current. For versioned static assets, long max-age values and content-hashed filenames make strong caching effective; deploys use new filenames when content changes.

TechnicalMediumBaiduFrontend EngineerFirst Round

18. How is two-way data binding implemented in Vue, and how does the implementation differ between versions 2.0 and 3.0?

Model answer

Vue’s two-way binding is best understood as one-way state flow plus an update path: state is passed to the view, and user input triggers an update to that state. v-model provides syntax for wiring those two directions together.

Reactivity and rendering

  • Vue 2: Vue observes existing object properties with Object.defineProperty getters and setters. Reading a property during rendering records a dependency; setting it notifies dependent watchers, which schedule updates. Because properties are instrumented up front, adding or deleting object keys later is not detected automatically; use Vue.set/this.$set or replace the object. Array index assignment and direct length changes also have caveats.
  • Vue 3: Vue uses Proxy for reactive objects and Reflect for underlying operations. Proxy traps can observe property additions, deletions, and array operations. ref() provides reactive .value access for primitives and objects, with unwrapping in templates. Effects track dependencies when values are read and are triggered when relevant values change.

What v-model compiles to

For a native input, Vue binds the current value and listens for the appropriate input/change event. The event handler reads the new value and assigns it back to the expression; modifiers such as .trim or .number adjust that handling.

For a custom component, it is a prop plus an update event:

  • Vue 2 default: roughly :value="x" plus @input="x = $event". A component could customize the prop/event pair with its model option.
  • Vue 3 default: roughly :modelValue="x" plus @update:modelValue="x = $event". Components can emit update:modelValue when their internal value changes. Named models, such as v-model:title, map to a named prop and update:title event; multiple models are supported.
flowchart LR
  S[Reactive state] -->|render value| V[Input or component]
  V -->|input or update event| U[Update handler]
  U -->|write state| S
Diagram

The key version difference is the reactivity mechanism (Object.defineProperty versus Proxy) and the component model contract (value/input versus modelValue/update:modelValue).

TechnicalMediumBaiduFrontend EngineerFirst Round

19. How do XSS and CSRF attacks work, and how can they be prevented?

Model answer

XSS and CSRF exploit different trust assumptions: XSS runs attacker-controlled code in a trusted page, while CSRF tricks a browser into sending an authenticated request.

XSS

An attacker injects JavaScript through content the application renders. The browser executes it under the site’s origin, so it may read page data, alter the UI, or make authenticated requests. Common forms are stored XSS, reflected XSS, and DOM-based XSS.

flowchart LR
  A[Attacker-controlled input] --> B[Unsafe rendering or DOM sink]
  B --> C[Script executes in trusted origin]
  C --> D[Read data or send requests]
Diagram

Prevention:

  • Prefer framework text interpolation and safe DOM APIs; avoid innerHTML, eval, and similar unsafe sinks.
  • Contextually encode untrusted data when producing HTML, attributes, URLs, or JavaScript. Sanitize only when rich HTML is a real requirement, using a maintained sanitizer.
  • Use a restrictive Content Security Policy as defense in depth; avoid relying on CSP instead of fixing unsafe rendering.
  • Treat user-generated content and third-party data as untrusted, including data returned by your own APIs.

CSRF

If a user is signed in with cookies, a malicious site can cause their browser to submit a request to your site. The browser may attach the session cookie automatically, making the request appear authenticated.

sequenceDiagram
  participant U as User browser
  participant M as Malicious site
  participant A as Application
  U->>A: Sign in; browser stores session cookie
  U->>M: Visit malicious page
  M->>U: Trigger cross-site request
  U->>A: Send request with eligible cookie
Diagram

Prevention:

  • Use SameSite=Lax or Strict cookies where compatible; use Secure and HttpOnly for session cookies as appropriate.
  • Require a CSRF token on state-changing requests, and validate Origin or Referer as an additional check.
  • Keep GET and other safe methods free of state changes.
  • CORS alone is not a CSRF defense: it generally controls reading responses, not whether a browser can send a request. XSS can often defeat CSRF protections, so prevent both.
TechnicalMediumBaiduFrontend EngineerFirst Round

20. How does Vue Router implement routing, and what are the differences between Hash mode and History mode?

Model answer

Vue Router maps the browser’s current URL to a route record, then renders the matched component through <router-view>. Navigation can happen through links, programmatic calls such as router.push(), or browser back/forward actions. The router resolves the target, runs applicable navigation guards, updates the URL and current route, and renders the new view. Route components can also be lazy-loaded.

Hash mode

  • Stores the route after #, for example https://example.com/#/search.
  • Uses the fragment portion of the URL; browsers emit hashchange when it changes.
  • The fragment is not sent to the server, so direct navigation usually does not require server-side route fallback configuration.
  • Useful when server configuration cannot be changed, but URLs include a hash.

History mode

  • Uses clean paths, for example https://example.com/search.
  • Uses the History API (pushState/replaceState) and listens for popstate for browser history navigation.
  • The server must serve the application entry point for valid client-side routes. Without this fallback, refreshing or directly opening /search may return a server 404.
  • Provides cleaner URLs, but requires deliberate server and deployment configuration.
sequenceDiagram
  participant U as User
  participant R as Vue Router
  participant B as Browser URL
  participant S as Server
  U->>R: Navigate to route
  R->>R: Match route and run guards
  alt Hash mode
    R->>B: Update URL fragment
    B-->>R: hashchange
  else History mode
    R->>B: pushState URL path
    B-->>R: popstate on back or forward
    Note over S,B: Direct requests need an SPA fallback
  end
  R->>R: Set current route and render router-view
Diagram

Both modes support route matching, nested routes, guards, and programmatic navigation. The main distinction is how the URL is represented and what the server must do for direct requests.

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