Kuaishou interview questions & answers

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

CodingEasyKuaishouSoftware EngineerFirst Round

1. Reverse the words in the sentence “today is wednesday!” so that it becomes “wednesday is today!”

Model answer

function reverseWords(sentence) {
  // Split on whitespace, reverse the word order, and join with single spaces.
  return sentence.trim().split(/\s+/).reverse().join(" ");
}

console.log(reverseWords("today is wednesday!")); // "wednesday! is today"

To match the requested output exactly—"wednesday is today!"—the exclamation mark must remain at the end of the sentence rather than attached to the last word. Here is an implementation that preserves trailing punctuation:

function reverseWordsPreservingTrailingPunctuation(sentence) {
  const match = sentence.match(/^(.*?)([!?.]+)?$/);
  const words = match[1].trim().split(/\s+/).reverse();
  const punctuation = match[2] || "";

  words[words.length - 1] += punctuation;
  return words.join(" ");
}

console.log(reverseWordsPreservingTrailingPunctuation("today is wednesday!"));
// "wednesday is today!"
  • The second version treats final punctuation as sentence-level punctuation and attaches it to the final word after reversal.
  • It assumes the input contains at least one word.

Complexity: Time O(n); space O(n).

CodingMediumKuaishouSoftware EngineerSecond Round

2. Given a binary tree whose nodes store numbers, find the lowest common ancestor of two numbers.

Model answer

function lowestCommonAncestor(root, p, q) {
  // Assumes each target number identifies one node (values are unique).
  function search(node) {
    if (node === null) return { ancestor: null, foundP: false, foundQ: false };

    const left = search(node.left);
    const right = search(node.right);
    const isP = node.value === p;
    const isQ = node.value === q;

    const foundP = isP || left.foundP || right.foundP;
    const foundQ = isQ || left.foundQ || right.foundQ;

    // A child may already contain both targets; otherwise this node is
    // the LCA if the targets have been found across its subtree.
    const ancestor = left.ancestor ?? right.ancestor ??
      (foundP && foundQ ? node : null);

    return { ancestor, foundP, foundQ };
  }

  const result = search(root);
  // Return null if either target is absent from the tree.
  return result.foundP && result.foundQ ? result.ancestor : null;
}

// Example node shape: { value: 5, left: null, right: null }
  • A post-order traversal reports whether each subtree contains p and q. The first node whose subtree contains both is their lowest common ancestor.
  • This version returns null when either value is absent. If values can repeat, pass node references (or unique IDs) instead of numbers.

Complexity: Time O(n); recursion space O(h), where h is tree height.

CodingMediumKuaishouSoftware EngineerSecond Round

3. Given a sorted array that has been cyclically shifted left by an unknown k, find the position of a number m.

Model answer

function searchRotated(nums, m) {
  let left = 0;
  let right = nums.length - 1;

  while (left <= right) {
    const mid = left + Math.floor((right - left) / 2);

    if (nums[mid] === m) return mid;

    // If the left, middle, and right values are equal, we cannot tell
    // which half is sorted; shrink the search range safely.
    if (nums[left] === nums[mid] && nums[mid] === nums[right]) {
      left++;
      right--;
    } else if (nums[left] <= nums[mid]) {
      // The left half is sorted.
      if (nums[left] <= m && m < nums[mid]) {
        right = mid - 1;
      } else {
        left = mid + 1;
      }
    } else {
      // The right half is sorted.
      if (nums[mid] < m && m <= nums[right]) {
        left = mid + 1;
      } else {
        right = mid - 1;
      }
    }
  }

  return -1;
}
  • At each step, at least one half is sorted; check whether m lies in that half and discard the other half.
  • The code supports duplicates. With distinct values, the search is O(log n); duplicates can make the worst case O(n).
  • Complexity: O(log n) average time with duplicates (worst-case O(n)); O(1) extra space.
CodingMediumKuaishouSoftware EngineerSecond Round

4. Given n stairs and the ability to take either 1 or 2 steps at a time, how many ways are there to climb the stairs?

Model answer

function climbStairs(n) {
  if (!Number.isInteger(n) || n < 0) {
    throw new RangeError("n must be a non-negative integer");
  }

  // There is one way to stay at the ground floor.
  let oneStepBefore = 1n;
  if (n === 0) return oneStepBefore;

  let twoStepsBefore = 1n;
  for (let step = 2; step <= n; step++) {
    const current = oneStepBefore + twoStepsBefore;
    twoStepsBefore = oneStepBefore;
    oneStepBefore = current;
  }

  return oneStepBefore;
}

// Example: climbStairs(5) returns 8n.
  • Let ways[i] be the number of ways to reach step i. The final move is either one step from i - 1 or two steps from i - 2, so ways[i] = ways[i - 1] + ways[i - 2].
  • Keep only the previous two values, using BigInt so the result does not overflow JavaScript's safe integer range.

Complexity: Time O(n); space O(1).

CodingMediumKuaishouSoftware EngineerFirst Round

5. Given an array, find the contiguous subsequence with the maximum sum and return that sum.

Model answer

function maxSubarraySum(nums) {
  if (nums.length === 0) {
    throw new Error("Input array must not be empty");
  }

  // The best subarray ending here either extends the previous one or starts here.
  let current = nums[0];
  let best = nums[0];

  for (let i = 1; i < nums.length; i++) {
    current = Math.max(nums[i], current + nums[i]);
    best = Math.max(best, current);
  }

  return best;
}

console.log(maxSubarraySum([-2, 1, -3, 4, -1, 2, 1, -5, 4])); // 6
  • This is Kadane’s algorithm; it handles arrays containing only negative numbers.
  • The example’s maximum-sum contiguous subsequence is [4, -1, 2, 1].

Complexity: Time O(n); space O(1).

TechnicalEasyKuaishouSoftware EngineerSecond Round

6. What are the differences between multiprocessing and multithreading?

Model answer

Core difference

A process is an independently scheduled program instance with its own virtual address space. A thread is an execution path inside a process; threads share that process's heap and resources, but each has its own stack and registers.

AspectMultiprocessingMultithreading
MemorySeparate address spaces; data must be communicated explicitlyShared address space; objects can be shared directly
IsolationStronger: a crash or memory bug is less likely to corrupt another processWeaker: a thread bug can affect the entire process
CommunicationIPC such as sockets, pipes, or shared memoryShared data, protected with locks, atomics, or other synchronization
Creation and switchingUsually more resource-intensiveUsually cheaper, though context switches and synchronization still cost time
ParallelismCan use multiple CPU coresCan use multiple cores when the runtime and workload permit it
Typical useIndependent services, fault isolation, CPU-heavy workersConcurrent work within one application, I/O handling, shared-state tasks
flowchart LR
  subgraph P1["Multiprocessing"]
    A["Process A memory"]
    B["Process B memory"]
    A -->|"IPC: socket, pipe, or shared memory"| B
  end
  subgraph P2["Multithreading"]
    C["Thread 1"]
    D["Thread 2"]
    E["Shared process heap"]
    C --> E
    D --> E
  end
Diagram

Practical considerations

  • CPU-bound work: Processes are a good choice when isolation or runtime constraints prevent effective parallel threads. Threads can also run CPU work in parallel in languages such as Java and C++, subject to the runtime and synchronization overhead.
  • I/O-bound work: Threads or asynchronous I/O can overlap waiting on network or disk. Processes can do this too, but have more communication and resource overhead.
  • Correctness: Shared memory makes thread communication fast, but introduces races and deadlocks. Process isolation reduces accidental sharing, but IPC requires explicit protocols and error handling.
  • Language/runtime matters: Java and C++ support real parallel threads. In CPython, the GIL limits parallel execution of Python bytecode for CPU-bound threads; multiprocessing is a common way to use multiple cores for that workload.

I would choose based on the workload, isolation requirements, and communication pattern—not assume one model is always faster. In a service handling short-video requests, for example, separate processes can isolate failure-prone components, while threads within a service can handle concurrent requests that share local caches.

TechnicalEasyKuaishouSoftware EngineerFirst Round

7. What are the differences between left join, right join, and inner join?

Model answer

Assume tables A and B are joined with a condition such as A.id = B.a_id:

  • INNER JOIN returns only rows with a match in both tables. Rows without a match are excluded.
  • LEFT JOIN returns every row from the left table (A) and matching rows from B. For an A row with no match, the B columns are NULL.
  • RIGHT JOIN returns every row from the right table (B) and matching rows from A. For a B row with no match, the A columns are NULL.
-- Only matching rows
SELECT * FROM A INNER JOIN B ON A.id = B.a_id;

-- All A rows, with B data when available
SELECT * FROM A LEFT JOIN B ON A.id = B.a_id;

-- All B rows, with A data when available
SELECT * FROM A RIGHT JOIN B ON A.id = B.a_id;

A RIGHT JOIN can usually be rewritten as a LEFT JOIN by swapping the table order. Be careful with filters on the optional side of an outer join: putting a condition on B in the WHERE clause can remove rows where B is NULL, making a LEFT JOIN behave like an inner join.

TechnicalEasyKuaishouSoftware EngineerFirst Round

8. What are precision and recall in machine learning?

Model answer

Precision and recall evaluate different aspects of a classifier’s positive predictions.

  • Precision = TP / (TP + FP): Of the items predicted positive, what fraction are actually positive?
  • Recall = TP / (TP + FN): Of all actually positive items, what fraction did the model find?

For example, in a content-moderation classifier, high precision means few acceptable videos are incorrectly flagged; high recall means few violating videos are missed. Raising the decision threshold often improves precision but reduces recall, so the right balance depends on the cost of false positives versus false negatives.

TechnicalMediumKuaishouSoftware EngineerSecond Round

9. How is inter-process communication implemented in Java and C++?

Model answer

IPC is implemented through operating-system primitives and a protocol both processes agree on. The right mechanism depends on whether the processes are on the same host, whether they need streaming or message boundaries, and whether low latency or simple deployment matters.

Java

  • Sockets: ServerSocket/Socket provide TCP communication between processes on one host or across a network. For local communication, Java also supports Unix domain sockets in modern JDKs. Applications define framing and serialize messages, for example with Protocol Buffers.
  • Pipes and process streams: ProcessBuilder launches a subprocess. The parent communicates through the child's standard input, output, and error streams. This is useful for a parent coordinating a worker process.
  • Shared memory: FileChannel.map() creates a memory-mapped region that processes can map to the same file. Coordinate access with OS-level synchronization or a carefully designed atomic protocol; Java object references themselves cannot simply be shared across process boundaries.
  • Remote invocation: RMI offers Java-to-Java remote calls, but explicit RPC over sockets or HTTP/gRPC is more common in distributed services because it supports language interoperability and clearer operational boundaries.

C++

  • Sockets: Use platform socket APIs such as POSIX sockets or Winsock. TCP is stream-oriented, so the application must add message framing; UDP preserves datagrams but does not guarantee delivery or ordering.
  • Pipes: POSIX anonymous pipes commonly connect related processes; named pipes/FIFOs can connect processes independently. Windows provides named pipes as well.
  • Shared memory: POSIX shm_open plus mmap, System V shared memory, or Windows file mappings expose a shared region. Pair it with semaphores, mutexes, or atomics that are explicitly usable across processes.
  • Message queues: POSIX or System V queues provide message-oriented communication. Libraries such as Boost.Interprocess can make shared-memory structures and synchronization more convenient.
sequenceDiagram
  participant A as Process A
  participant OS as Operating system
  participant B as Process B
  A->>OS: Open IPC endpoint or map shared region
  B->>OS: Connect or map same endpoint
  A->>OS: Send framed message or update shared data
  OS->>B: Deliver bytes or expose shared data
  B->>OS: Send response or signal synchronization
  OS->>A: Deliver response or wake waiting process
Diagram

Design details that matter

  • Define the protocol: Agree on message format, framing, versioning, timeouts, and error behavior. TCP delivers a byte stream, not application messages, so include lengths or delimiters.
  • Handle lifecycle and failures: Detect peer closure, bound queues and buffers, and decide how to retry without duplicating non-idempotent work.
  • Protect shared state: Use locks, semaphores, or atomics with clear ownership and ordering rules. Shared memory is fast, but it does not provide synchronization automatically.
  • Apply access controls: Restrict socket permissions, pipe paths, and shared-memory access; validate and limit incoming data.

For a simple local parent/worker tool, I would start with process streams. For a service boundary or cross-host communication, I would usually choose a versioned RPC protocol over sockets. I would use shared memory only when measured throughput or latency justifies its extra synchronization complexity.

TechnicalMediumKuaishouSoftware EngineerFirst Round

10. What is SQL partitioning?

Model answer

SQL partitioning divides one logical table into smaller, manageable pieces called partitions. The database routes a query to the relevant partitions when it can use the partition key, reducing the data scanned and making maintenance—such as dropping old data—easier. The table is still queried as one logical table.

flowchart LR
    Q["Query with date filter"] --> T["Logical events table"]
    T --> P1["Partition: January"]
    T --> P2["Partition: February"]
    T --> P3["Partition: March"]
    Q -. "prunes unused partitions" .-> P2
Diagram

Common partitioning strategies:

  • Range: divide values into ranges, such as one partition per month of event time. Useful for time-series data and retention.
  • List: assign explicit values to partitions, such as region or status.
  • Hash: hash a key to distribute rows more evenly across a fixed number of partitions.
  • Composite: combine strategies, for example, range by month and hash by user ID within each month.

For example, a high-volume short-video event table could be range-partitioned by event_date. Queries scoped to a date range can scan only the corresponding partitions, and expired data can be removed by dropping old partitions instead of deleting rows individually.

Partitioning is not the same as sharding: partitions are commonly managed within one database system, while sharding distributes data across separate database instances. Partitioning also does not guarantee faster queries; the query needs a usable predicate on the partition key, and too many tiny partitions can add planning and management overhead.

TechnicalMediumKuaishouSoftware EngineerSecond Round

11. What is your level of understanding of machine learning, and have you studied loss functions?

Model answer

I have a solid working understanding of machine-learning fundamentals, including supervised learning, training and validation, overfitting, and how the loss function connects model predictions to the optimization objective. I have studied several loss functions and would choose one based on the task and the costs of different errors.

  • Regression: Mean squared error penalizes large errors more strongly; mean absolute error is more robust to outliers. Huber loss combines aspects of both.
  • Classification: Binary cross-entropy is common for binary predictions, and categorical cross-entropy for multi-class predictions. Class weighting or focal loss can help when classes are highly imbalanced.
  • Ranking and retrieval: Pairwise losses, such as hinge or pairwise logistic loss, train relative ordering; contrastive or triplet losses can learn embeddings for retrieval.

I also understand that the loss is only a proxy for the outcome we care about. For example, in a recommendation or short-video feed, a model might optimize a weighted multi-task objective for watch time, completion, likes, and negative feedback, while evaluation should also include ranking metrics and online guardrails. I would check label quality, class balance, calibration, and train/validation leakage rather than assuming a lower training loss means a better product.

I would describe myself as comfortable reasoning about these choices and discussing how they affect training. For specialized model design or tuning, I would validate assumptions with experiments and collaborate with an ML specialist.

TechnicalMediumKuaishouSoftware EngineerSecond Round

12. What socket libraries are used for network communication in Java and C++?

Model answer

In Java and C++, the choice depends on whether I need low-level control or a higher-level networking framework.

  • Java: The standard library provides java.net.Socket and ServerSocket for TCP, and DatagramSocket for UDP. For non-blocking, multiplexed I/O, I use Java NIO (SocketChannel, ServerSocketChannel, and Selector). Frameworks such as Netty build on these APIs and are common for high-throughput asynchronous services; OkHttp is a higher-level choice for HTTP clients.
  • C++: On Linux and other Unix-like systems, the usual low-level interface is the POSIX sockets API (socket, bind, listen, accept, connect, send, and recv). On Windows, the equivalent is Winsock. For portable asynchronous networking, Boost.Asio or standalone Asio are common; libevent and libuv are other event-driven options.
  • Practical choice: For a simple TCP service, the native socket API is enough. For production services that need asynchronous I/O, connection management, TLS, or protocol support, I would generally choose a maintained framework such as Netty or Asio rather than reimplementing those concerns.

Regardless of library, I account for partial reads and writes, timeouts, connection closure, backpressure, and framing: TCP provides a byte stream, not message boundaries.

TechnicalMediumKuaishouSoftware EngineerSecond Round

13. When a = b, where might the value of b be obtained from: a register, cache, memory, or external storage?

Model answer

It depends on where b is stored and whether its value is already available to the CPU. A compiler may keep it in a register; otherwise, the CPU loads it from memory, usually finding the relevant cache line in cache first. On a cache miss, it fetches from main memory. External storage is involved only in cases such as memory-mapped files or paging, not as the normal source for an ordinary variable assignment.

So a = b describes the operation, not a fixed location: the value may be in a register or cache, or need to be loaded from RAM, depending on compiler decisions and the current cache state.

TechnicalMediumKuaishouSoftware EngineerSecond Round

14. When memory is extremely limited, how can you find the position of a number m among a large number of values?

Model answer

If the values are sorted and I need the position of m, I would use binary search rather than store or copy the values. It keeps only a few indices, so auxiliary space is O(1), and takes O(log n) comparisons.

If the values are unsorted, exact search generally requires checking all values, which is O(n) time. With extremely limited memory, scan the input as a stream and keep only the current index and best result; if the input cannot be reread, make that pass while retaining the target’s position if found.

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