WeRide interview questions & answers

10 real WeRide interview questions with full model answers — Coding. Drawn from the same verified bank ChannelPulse drills from (10 WeRide questions in total).

CodingEasyWeRideSoftware Engineer

1. Count Binary Substrings (LeetCode)

Model answer

The task

Count nonempty substrings of a binary string that contain the same number of 0s and 1s, with all the 0s and 1s grouped into consecutive runs.

Key idea

For each pair of neighboring runs, the number of valid substrings they contribute is the length of the shorter run. Track the previous run’s length and the current run’s length, adding the smaller whenever a run ends.

Approach

  1. Start with the first run and set both run lengths to one.
  2. Scan the string from left to right.
  3. If the current character matches the previous one, extend the current run.
  4. Otherwise, add the smaller run length to the answer, then shift the current run into the previous-run count and start a new run.
  5. Add the final pair’s contribution after the scan.
class Solution:
    def countBinarySubstrings(self, s: str) -> int:
        previous_run = 0
        current_run = 1
        total = 0

        for i in range(1, len(s)):
            if s[i] == s[i - 1]:
                current_run += 1
            else:
                total += min(previous_run, current_run)
                previous_run = current_run
                current_run = 1

        # Account for the final pair of neighboring runs.
        total += min(previous_run, current_run)
        return total

Complexity:

  • Time: O(n), where n is the string length; each character is processed once.
  • Space: O(1), using only a few counters.

Common follow-ups

  • How would you return the actual substrings? Track each run boundary and enumerate the valid lengths, though output size can be large.
  • What if the input alphabet has more than two characters? The equal-sized neighboring-run rule applies to adjacent runs of two different characters; clarify the exact validity condition first.
  • How would you handle a stream of characters? Maintain the two run counts and update the total when a run transition is observed; finalize the last pair when the stream ends.
CodingMediumWeRideSoftware Engineer

2. Detect Cycles in 2D Grid (LeetCode)

Model answer

The task

Determine whether a rectangular grid contains a cycle made of cells with the same character. A cycle can move only between horizontally or vertically adjacent cells.

Key idea

Treat each cell as a graph vertex, with edges only to adjacent cells holding the same character. During graph traversal, reaching an already visited neighbor other than the current cell’s parent reveals a cycle.

Approach

  1. Visit each cell that has not already been explored.
  2. Start an iterative depth-first search from that cell, recording each cell’s parent.
  3. For each cell, examine its four neighbors and skip those that are out of bounds or have a different character.
  4. Add unseen matching neighbors to the search; if a matching neighbor was seen and is not the parent, return True.
  5. If every component is explored without finding a cycle, return False.
from typing import List, Tuple

class Solution:
    def containsCycle(self, grid: List[List[str]]) -> bool:
        if not grid or not grid[0]:
            return False

        rows, cols = len(grid), len(grid[0])
        visited = set()
        directions = ((1, 0), (-1, 0), (0, 1), (0, -1))

        for start_row in range(rows):
            for start_col in range(cols):
                start = (start_row, start_col)
                if start in visited:
                    continue

                visited.add(start)
                stack = [(start_row, start_col, -1, -1)]

                while stack:
                    row, col, parent_row, parent_col = stack.pop()

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

                        if not (0 <= nr < rows and 0 <= nc < cols):
                            continue
                        if grid[nr][nc] != grid[row][col]:
                            continue
                        if (nr, nc) == (parent_row, parent_col):
                            continue

                        if (nr, nc) in visited:
                            return True

                        visited.add((nr, nc))
                        stack.append((nr, nc, row, col))

        return False

Complexity:

  • Time: O(mn), since each cell and its four neighbors are examined a constant number of times.
  • Space: O(mn) for the visited set and traversal stack.

Common follow-ups

  • How would you use breadth-first search instead? Store each queued cell’s parent and apply the same visited-neighbor check.
  • Can union-find detect the cycle? Yes; union matching adjacent cells, and a failed union indicates a cycle.
  • What if diagonal moves are allowed? Include the four diagonal directions when exploring neighbors.
CodingMediumWeRideSoftware Engineer

3. Design Snake Game (LeetCode)

Model answer

The task

Implement a snake game that moves in a grid, consumes food, and grows. Return the number of foods eaten after each move, or -1 once the snake hits a wall or itself.

Key idea

Track the snake’s body in a deque and its occupied cells in a set. The set makes collision checks constant time; when the snake is not eating, its tail vacates a cell on the same move, so moving into that cell is allowed.

Approach

  1. Store the body from tail to head, plus a set of occupied cells.
  2. For each move, compute the new head and check whether it is in bounds.
  3. Determine whether the move eats the next food.
  4. Check for self-collision, allowing the current tail cell if the snake is not growing.
  5. Remove the tail when not eating, then add the new head and return the food count.
from collections import deque

class SnakeGame:
    def __init__(self, width: int, height: int, food: list[list[int]]):
        self.width = width
        self.height = height
        self.food = food
        self.food_index = 0
        self.dead = False

        # Body is ordered from tail to head.
        self.body = deque([(0, 0)])
        self.occupied = {(0, 0)}

        self.directions = {
            "U": (-1, 0),
            "D": (1, 0),
            "L": (0, -1),
            "R": (0, 1),
        }

    def move(self, direction: str) -> int:
        if self.dead:
            return -1

        row, col = self.body[-1]
        dr, dc = self.directions[direction]
        new_head = (row + dr, col + dc)
        new_row, new_col = new_head

        # A move beyond the grid ends the game.
        if not (0 <= new_row < self.height and 0 <= new_col < self.width):
            self.dead = True
            return -1

        eating = (
            self.food_index < len(self.food)
            and [new_row, new_col] == self.food[self.food_index]
        )

        tail = self.body[0]
        if new_head in self.occupied and (eating or new_head != tail):
            self.dead = True
            return -1

        # The tail vacates its cell unless the snake grows.
        if not eating:
            self.body.popleft()
            self.occupied.remove(tail)
        else:
            self.food_index += 1

        self.body.append(new_head)
        self.occupied.add(new_head)
        return self.food_index

Complexity:

  • Time: O(1) per move; each move uses constant-time deque and set operations.
  • Space: O(L) for the body and occupied-cell set, where L is the snake’s length.

Common follow-ups

  • How would you support wrapping at the grid edges? Wrap the new row and column modulo the grid dimensions.
  • What if moves arrive concurrently? Protect game state updates with a lock.
  • How could you optimize memory for a very large sparse grid? Store only occupied cells, as this implementation does.
CodingMediumWeRideSoftware Engineer

4. Maximize Greatness of an Array (LeetCode)

Model answer

The task

Reorder the array to maximize how many positions contain a value greater than the value at the same position in the original array. Return that maximum count.

Key idea

Sort the values and greedily pair each value being compared with the smallest unused value that is strictly larger. Choosing the smallest such value preserves larger values for comparisons that need them.

Approach

  1. Sort the array.
  2. Scan its values in ascending order as comparison targets.
  3. Keep a pointer to the smallest candidate not yet used.
  4. When that candidate is greater than the current target, count a successful pairing and advance the candidate pointer.
  5. Return the number of successful pairings.
from typing import List

class Solution:
    def maximizeGreatness(self, nums: List[int]) -> int:
        values = sorted(nums)
        candidate = 0
        greatness = 0

        for target in values:
            # Use the smallest available value that beats this target.
            if values[candidate] > target:
                greatness += 1
                candidate += 1

        return greatness

Complexity:

  • Time: O(n log n), due to sorting.
  • Space: O(n), for the sorted copy.

Common follow-ups

  • Why does the greedy choice work? Pairing with the smallest available value that wins avoids wasting a larger value that could win against a harder target.
  • How are duplicates handled? The comparison is strict, so equal values are never counted as a successful pairing.
  • Can extra space be reduced? Sorting nums in place avoids the separate sorted copy, though it modifies the input.
  • What if the array is empty? The loop makes no pairings, so the result is 0.
CodingHardWeRideSoftware Engineer

5. Swim in Rising Water (LeetCode)

Model answer

The task

Given a square grid of elevations, find the smallest water level at which a path from the top-left cell to the bottom-right cell is possible. Moving between cells is allowed only horizontally or vertically, and the path’s required level is its highest elevation.

Key idea

Treat each cell as a graph vertex. The cost of reaching a cell is the minimum, over all paths to it, of the maximum elevation encountered so far. This minimax version of Dijkstra’s algorithm lets a min-heap prioritize the most promising path.

Approach

  1. Initialize the start cell’s cost to its elevation and put it in a min-heap.
  2. Repeatedly remove the cell with the lowest path cost.
  3. If it is the destination, its cost is the answer.
  4. For each unvisited neighbor, compute the path cost as the larger of the current path cost and the neighbor’s elevation.
  5. Update the neighbor’s best known cost and add it to the heap when this improves its cost.
from heapq import heappop, heappush
from typing import List

class Solution:
    def swimInWater(self, grid: List[List[int]]) -> int:
        n = len(grid)
        best = [[float("inf")] * n for _ in range(n)]
        best[0][0] = grid[0][0]

        # Each entry is (minimum required level, row, column).
        heap = [(grid[0][0], 0, 0)]
        visited = [[False] * n for _ in range(n)]
        directions = ((1, 0), (-1, 0), (0, 1), (0, -1))

        while heap:
            level, row, col = heappop(heap)

            if visited[row][col]:
                continue
            visited[row][col] = True

            if row == n - 1 and col == n - 1:
                return level

            for dr, dc in directions:
                nr, nc = row + dr, col + dc
                if 0 <= nr < n and 0 <= nc < n and not visited[nr][nc]:
                    next_level = max(level, grid[nr][nc])
                    if next_level < best[nr][nc]:
                        best[nr][nc] = next_level
                        heappush(heap, (next_level, nr, nc))

        return -1  # The grid is connected, so this is unreachable.

Complexity:

  • Time: O(n² log n), since each cell can be processed and heap operations cost O(log n).
  • Space: O(n²) for the heap and auxiliary matrices.

Common follow-ups

  • Can binary search be used? Yes; test reachability at a candidate level with BFS, then binary-search the level.
  • Can union-find solve it? Yes; activate cells in increasing elevation order and union adjacent active cells until the endpoints connect.
  • What if the grid is replaced by a general graph? Use the same minimax Dijkstra approach, with edge transitions adapted to the problem’s costs.
CodingHardWeRideSoftware Engineer

6. Find Edges in Shortest Paths (LeetCode)

Model answer

The task

Given an undirected weighted graph, determine for each input edge whether it belongs to at least one shortest path from node 0 to node n - 1.

Key idea

An edge (u, v, w) is on a shortest path if a shortest route from 0 to one endpoint, followed by that edge and a shortest route from the other endpoint to n - 1, has the overall shortest-path length. Run Dijkstra from both endpoints to test this efficiently.

Approach

  1. Build an adjacency list, retaining each edge’s weight.
  2. Run Dijkstra from node 0 to find distances to all nodes.
  3. Run Dijkstra from node n - 1 to find distances back to the destination.
  4. For each edge, check both possible traversal directions against the shortest distance from 0 to n - 1.
  5. Return False for every edge if the destination is unreachable.
from heapq import heappop, heappush
from typing import List

class Solution:
    def findAnswer(self, n: int, edges: List[List[int]]) -> List[bool]:
        graph = [[] for _ in range(n)]

        for u, v, weight in edges:
            graph[u].append((v, weight))
            graph[v].append((u, weight))

        def dijkstra(start: int) -> List[int]:
            distances = [float("inf")] * n
            distances[start] = 0
            heap = [(0, start)]

            while heap:
                distance, node = heappop(heap)
                if distance != distances[node]:
                    continue

                for neighbor, weight in graph[node]:
                    candidate = distance + weight
                    if candidate < distances[neighbor]:
                        distances[neighbor] = candidate
                        heappush(heap, (candidate, neighbor))

            return distances

        from_start = dijkstra(0)
        to_end = dijkstra(n - 1)
        shortest = from_start[n - 1]

        if shortest == float("inf"):
            return [False] * len(edges)

        answer = []
        for u, v, weight in edges:
            on_shortest_path = (
                from_start[u] + weight + to_end[v] == shortest
                or from_start[v] + weight + to_end[u] == shortest
            )
            answer.append(on_shortest_path)

        return answer

Complexity:

  • Time: O((n + m) log n), for two Dijkstra runs and checking all m edges.
  • Space: O(n + m), for the adjacency list, distance arrays, and heaps.

Common follow-ups

  • What if the graph is directed? Store only outgoing edges, and check each edge in its given direction.
  • What if edge weights can be negative? Dijkstra is not suitable; use an algorithm that supports negative weights, such as Bellman–Ford.
  • How can all shortest paths be represented? Build a subgraph containing exactly the edges that pass the shortest-path test.
CodingHardWeRideSoftware Engineer

7. Text Justification (LeetCode)

Model answer

The task

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

Key idea

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

Approach

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

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

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

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

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

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

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

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

            result.append(line)
            i = j

        return result

Complexity:

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

Common follow-ups

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

8. Longest Increasing Path in a Matrix (LeetCode)

Model answer

The task

Given a matrix of integers, find the length of the longest path that moves between orthogonally adjacent cells and strictly increases at every step. The path may start and end anywhere.

Key idea

Treat each cell as a node, with directed edges to adjacent cells of greater value. This graph has no cycles because values strictly increase along every edge. Memoized DFS computes the longest path starting at each cell, reusing results for overlapping subproblems.

Approach

  1. Return 0 if the matrix is empty.
  2. Create a cache for the longest increasing path starting at each cell.
  3. For an uncached cell, recursively check its four neighbors.
  4. Extend the path only to neighbors with greater values.
  5. The answer is the largest cached path length over all cells.
from functools import lru_cache
from typing import List

class Solution:
    def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
        if not matrix or not matrix[0]:
            return 0

        rows, cols = len(matrix), len(matrix[0])
        directions = ((1, 0), (-1, 0), (0, 1), (0, -1))

        @lru_cache(maxsize=None)
        def longest_from(row: int, col: int) -> int:
            # The path can always consist of this cell alone.
            best = 1

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

                if (
                    0 <= nr < rows
                    and 0 <= nc < cols
                    and matrix[nr][nc] > matrix[row][col]
                ):
                    best = max(best, 1 + longest_from(nr, nc))

            return best

        return max(
            longest_from(row, col)
            for row in range(rows)
            for col in range(cols)
        )

Complexity:

  • Time: O(rows × cols), since each cell is computed once and checks at most four neighbors.
  • Space: O(rows × cols), for the cache and recursion stack in the worst case.

Common follow-ups

  • What if paths may decrease instead? Reverse the comparison, or negate values and reuse the same logic.
  • How would you avoid recursion-depth limits? Use topological sorting on the directed cell graph.
  • What if diagonal moves are allowed? Add the four diagonal offsets to the neighbor directions.
CodingHardWeRideSoftware Engineer

9. Maximum Profit in Job Scheduling (LeetCode)

Model answer

The task

Choose a set of jobs, each with a start time, end time, and profit, so that no chosen jobs overlap and total profit is maximized. A job may start when another chosen job ends.

Key idea

Sort jobs by start time and use dynamic programming over that order. For each job, compare skipping it with taking it and adding the best profit from the first job that can start after it finishes.

Approach

  1. Pair each job’s start, end, and profit, then sort the jobs by start time.
  2. Store the sorted start times for binary searches.
  3. Process jobs from right to left, so the best profit from any later job is already known.
  4. Use binary search to find the first compatible next job.
  5. Record the better of skipping the current job or taking it.
from bisect import bisect_left
from typing import List

class Solution:
    def jobScheduling(
        self,
        startTime: List[int],
        endTime: List[int],
        profit: List[int],
    ) -> int:
        jobs = sorted(zip(startTime, endTime, profit))
        starts = [job[0] for job in jobs]
        n = len(jobs)

        # dp[i] is the best profit using jobs from index i onward.
        dp = [0] * (n + 1)

        for i in range(n - 1, -1, -1):
            start, end, value = jobs[i]

            # Find the first later job that does not overlap this one.
            next_job = bisect_left(starts, end, lo=i + 1)

            take = value + dp[next_job]
            skip = dp[i + 1]
            dp[i] = max(take, skip)

        return dp[0]

Complexity:

  • Time: O(n log n), for sorting and one binary search per job.
  • Space: O(n), for the sorted jobs, start times, and DP table.

Common follow-ups

  • What if jobs may have a setup or cooldown time between them? Search for the first job starting at or after the current end plus that time.
  • How would you reconstruct the selected jobs? Store each DP decision and follow those choices from the first job.
  • Can jobs have negative profit? The skip option lets the algorithm avoid choosing unprofitable jobs.
  • What if jobs arrive online rather than all at once? The sorting-based method no longer directly applies; an online solution needs additional structure and assumptions.
CodingHardWeRideSoftware Engineer

10. Count Paths That Can Form a Palindrome in a Tree (LeetCode)

Model answer

The task

Given a tree rooted at node 0, count pairs of distinct nodes whose connecting path’s edge labels can be rearranged into a palindrome.

Key idea

A path can form a palindrome exactly when at most one character appears an odd number of times. Represent character parity with a bitmask: each edge toggles one bit, and the path mask between two nodes is the XOR of their root-to-node masks.

Approach

  1. Build child lists from the parent array.
  2. Traverse the tree and compute each node’s root-to-node parity mask.
  3. As each node is visited, compare its mask against masks already seen.
  4. Count equal masks and masks differing by exactly one bit; then record the current mask.
  5. This counts every pair once, in traversal order.
from typing import List

class Solution:
    def countPalindromePaths(self, parent: List[int], s: str) -> int:
        n = len(parent)
        children = [[] for _ in range(n)]

        for node in range(1, n):
            children[parent[node]].append(node)

        answer = 0
        seen = {}
        stack = [(0, 0)]  # (node, root-to-node parity mask)

        while stack:
            node, mask = stack.pop()

            # A path is valid if its parity mask has at most one set bit.
            answer += seen.get(mask, 0)
            for bit in range(26):
                answer += seen.get(mask ^ (1 << bit), 0)

            seen[mask] = seen.get(mask, 0) + 1

            for child in children[node]:
                edge_bit = 1 << (ord(s[child]) - ord('a'))
                stack.append((child, mask ^ edge_bit))

        return answer

Complexity:

  • Time: O(26n), which is O(n) for a fixed alphabet; each node checks 27 masks.
  • Space: O(n) for the child lists, traversal stack, and mask frequencies.

Common follow-ups

  • What if the alphabet is larger? Use one bit per character; the per-node check becomes proportional to the alphabet size.
  • Can the traversal be recursive? Yes, but an iterative traversal avoids recursion-depth limits on a long tree.
  • What if edge labels can change? A single update may affect many root-to-node masks, so efficient updates generally need additional tree decomposition or indexing.

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