Huawei interview questions & answers

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

CodingEasyHuaweiSoftware Engineer

1. Two Sum (LeetCode)

Model answer

The task

Given a list of integers and a target, return the indices of two distinct elements whose values add up to the target. The usual version guarantees a valid pair.

Key idea

As we scan the list, store each value’s index in a hash table. For the current value, check whether its needed complement has already appeared; this finds a pair in one pass.

Approach

  1. Create a dictionary mapping previously seen values to their indices.
  2. For each element, compute the complement needed to reach the target.
  3. If that complement is in the dictionary, return its stored index and the current index.
  4. Otherwise, store the current value and index, then continue.
from typing import List

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        # Map each value already visited to its index.
        seen = {}

        for index, value in enumerate(nums):
            complement = target - value

            # A match must come from an earlier, distinct element.
            if complement in seen:
                return [seen[complement], index]

            seen[value] = index

        # The standard problem guarantees a solution.
        raise ValueError("No two elements sum to the target")

Complexity:

  • Time: O(n), where n is the number of elements; each lookup and insertion is O(1) on average.
  • Space: O(n), for the dictionary of values seen so far.

Common follow-ups

  • What if there may be multiple valid pairs? Return the first pair found, or keep searching and collect pairs according to the required output rules.
  • What if the input is sorted? Use two pointers from opposite ends for O(1) extra space; preserve original indices if those are required.
  • What if values repeat? The dictionary stores indices, and checking before insertion ensures the current element is not paired with itself.
CodingEasyHuaweiSoftware Engineer

2. Valid Parentheses (LeetCode)

Model answer

The task

Determine whether a string of opening and closing round, square, and curly brackets is correctly nested and matched. Return a boolean.

Key idea

A closing bracket must match the most recent unmatched opening bracket. A stack captures that order: push openings, and check each closing bracket against the stack’s top.

Approach

  1. Return False if the string has odd length.
  2. Map each closing bracket to its matching opening bracket.
  3. Scan the string from left to right.
  4. Push opening brackets onto the stack.
  5. For a closing bracket, return False if the stack is empty or its top does not match; otherwise pop.
  6. Return True only if the stack is empty after the scan.
class Solution:
    def isValid(self, s: str) -> bool:
        pairs = {")": "(", "]": "[", "}": "{"}
        openings = set(pairs.values())
        stack = []

        for char in s:
            if char in openings:
                stack.append(char)
            else:
                # A closing bracket must match the latest unmatched opening.
                if not stack or stack[-1] != pairs.get(char):
                    return False
                stack.pop()

        # Unmatched opening brackets make the sequence invalid.
        return not stack

Complexity:

  • Time: O(n), where n is the string length; each character is processed once.
  • Space: O(n) in the worst case, when all characters are opening brackets.

Common follow-ups

  • How would you support additional bracket types? Add their matching pairs to the map.
  • Can you stop early? Yes; return False as soon as a closing bracket mismatches or has no opening bracket.
  • What if the input includes non-bracket characters? Define how to handle them, then either ignore them or reject them during the scan.
CodingEasyHuaweiSoftware Engineer

3. Linked List Cycle (LeetCode)

Model answer

The task

Determine whether a singly linked list eventually revisits a node, forming a cycle.

Key idea

Move two pointers through the list at different speeds. If a cycle exists, the faster pointer eventually catches the slower one; if the fast pointer reaches the end, the list is acyclic.

Approach

  1. Initialize both pointers at the list head.
  2. Advance the slow pointer by one node and the fast pointer by two.
  3. If the fast pointer or its next node is None, return False.
  4. If the pointers meet, return True.
from typing import Optional

class Solution:
    def hasCycle(self, head: Optional["ListNode"]) -> bool:
        # The slow pointer moves one step at a time.
        slow = head
        # The fast pointer moves two steps at a time.
        fast = head

        while fast is not None and fast.next is not None:
            slow = slow.next
            fast = fast.next.next

            if slow is fast:
                return True

        return False

Complexity:

  • Time: O(n), where n is the number of nodes visited before the pointers meet or the list ends.
  • Space: O(1), because only two pointers are used.

Common follow-ups

  • How could you solve it using a hash set? Record visited node identities; a repeated identity means there is a cycle, using O(n) extra space.
  • How can you find the cycle’s starting node? After the pointers meet, reset one to the head and move both one step at a time; their next meeting is the start.
  • How can you find the cycle’s length? Keep one pointer at the meeting node and advance another until it returns, counting steps.
CodingEasyHuaweiSoftware Engineer

4. Single Number (LeetCode)

Model answer

The task

Given an integer array in which every value appears twice except for one value that appears once, return the value that appears only once.

Key idea

XOR cancels pairs: x ^ x is zero, and XOR with zero leaves a value unchanged. Since XOR is also associative and commutative, the order of the array does not matter.

Approach

  1. Initialize an accumulator to zero.
  2. XOR each array value into the accumulator.
  3. After all pairs cancel, the accumulator contains the unpaired value.
  4. Return it.
class Solution:
    def singleNumber(self, nums: list[int]) -> int:
        # Paired values cancel under XOR.
        result = 0

        for value in nums:
            result ^= value

        return result

Complexity:

  • Time: O(n), where n is the number of array elements; each value is processed once.
  • Space: O(1), since the algorithm uses only one accumulator, regardless of the array size.

Common follow-ups

  • What if every value appears three times except one? Use bit counts across all values, keeping each count modulo three; the remaining bits form the unique value.
  • What if two values appear once and all others appear twice? XOR all values to get the XOR of the two unique values, then use a set bit to divide values into two groups.
  • Does the order of the array matter? No. XOR is associative and commutative, so the same result is produced for any order.
  • Can this be solved without modifying the input? Yes. The algorithm only reads the array and stores its running XOR.
CodingMediumHuaweiSoftware Engineer

5. Number of Islands (LeetCode)

Model answer

The task

Given a grid of land and water, count the groups of connected land cells. Cells connect horizontally or vertically, not diagonally.

Key idea

Each group is one island. Scan the grid, and whenever an unvisited land cell is found, count a new island and explore its entire connected region. Mark cells as visited when adding them to the search queue so no cell is processed more than once.

Approach

  1. Return 0 if the grid is empty.
  2. Scan every cell in the grid.
  3. When a land cell is found, increment the island count and start a breadth-first search from it.
  4. During the search, mark each discovered land cell as water and add its in-bounds land neighbors to the queue.
  5. Return the island count after the scan is complete.
from collections import deque
from typing import List

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

        rows, cols = len(grid), len(grid[0])
        islands = 0

        for row in range(rows):
            for col in range(cols):
                if grid[row][col] != "1":
                    continue

                islands += 1
                grid[row][col] = "0"
                queue = deque([(row, col)])

                while queue:
                    current_row, current_col = queue.popleft()

                    for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                        next_row = current_row + dr
                        next_col = current_col + dc

                        if (
                            0 <= next_row < rows
                            and 0 <= next_col < cols
                            and grid[next_row][next_col] == "1"
                        ):
                            # Mark when enqueuing to avoid duplicate work.
                            grid[next_row][next_col] = "0"
                            queue.append((next_row, next_col))

        return islands

Complexity: Time: O(rows * cols), since each cell is examined at most a constant number of times.

Complexity: Space: O(rows * cols) in the worst case for the BFS queue.

Common follow-ups

  • Preserve the input grid? Track visited cells in a separate set instead of changing land cells to water.
  • Use depth-first search instead? Recursively or iteratively explore the four neighbors; iterative DFS avoids recursion-depth concerns.
  • Count diagonally connected land as part of the same island? Include the four diagonal directions in the neighbor list.
CodingMediumHuaweiSoftware Engineer

6. Longest Palindromic Substring (LeetCode)

Model answer

The task

Given a string, return its longest contiguous substring that reads the same forward and backward. If several substrings have the same maximum length, returning any of them is acceptable.

Key idea

Every palindrome has a center: either a character (odd length) or the gap between two characters (even length). Expand outward from each possible center while the characters match, keeping track of the longest range found.

Approach

  1. Initialize the best range to an empty substring.
  2. For each character position, expand from that position to check odd-length palindromes.
  3. Also expand from the gap after that position to check even-length palindromes.
  4. When an expansion finds a longer palindrome, save its start and end indices.
  5. Return the substring covered by the saved range.
class Solution:
    def longestPalindrome(self, s: str) -> str:
        best_start = 0
        best_length = 0

        def expand(left: int, right: int) -> None:
            nonlocal best_start, best_length

            # Keep expanding while the current range is a palindrome.
            while left >= 0 and right < len(s) and s[left] == s[right]:
                length = right - left + 1
                if length > best_length:
                    best_start = left
                    best_length = length
                left -= 1
                right += 1

        for center in range(len(s)):
            expand(center, center)      # Odd-length palindromes
            expand(center, center + 1)  # Even-length palindromes

        return s[best_start:best_start + best_length]

Complexity:

  • Time: O(n²), since each of the O(n) centers can expand across O(n) characters.
  • Space: O(1), excluding the returned substring.

Common follow-ups

  • How can this be made linear time? Use Manacher’s algorithm to reuse information from previously explored centers.
  • How would you return all longest palindromic substrings? Track every range tied for the maximum length.
  • What if the input is empty? The method returns an empty string.
  • How would you count all palindromic substrings? Count each successful expansion instead of only saving the longest range.
CodingMediumHuaweiSoftware Engineer

7. Generate Parentheses (LeetCode)

Model answer

The task

Given a nonnegative number of pairs, return every string of that many opening and closing parentheses that is correctly balanced.

Key idea

Build each string one character at a time. Add an opening parenthesis only while fewer than n have been used, and add a closing parenthesis only when it will not outnumber the openings already used.

Approach

  1. Track how many opening and closing parentheses have been added, plus the current string.
  2. If the string has length 2 * n, save it.
  3. Recurse with an opening parenthesis when fewer than n openings have been used.
  4. Recurse with a closing parenthesis when fewer closings have been used than openings.
  5. Start with an empty string and zero counts.
from typing import List

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        results: List[str] = []
        current: list[str] = []

        def backtrack(open_count: int, close_count: int) -> None:
            if len(current) == 2 * n:
                results.append("".join(current))
                return

            if open_count < n:
                current.append("(")
                backtrack(open_count + 1, close_count)
                current.pop()

            if close_count < open_count:
                current.append(")")
                backtrack(open_count, close_count + 1)
                current.pop()

        backtrack(0, 0)
        return results

Complexity:

  • Time: O(Cₙ · n), where Cₙ is the number of valid strings; each is assembled in O(n) time.
  • Space: O(n) auxiliary space for the recursion and current string, excluding the returned results.

Common follow-ups

  • How can you count the results without generating them? Use the Catalan number formula, Cₙ = binomial(2n, n) / (n + 1).
  • What happens when n is zero? The algorithm returns a list containing the empty string.
  • How would you generate strings with multiple bracket types? Track each type’s balance and ensure closing brackets match the most recent unmatched opening bracket.
CodingMediumHuaweiSoftware Engineer

8. Top K Frequent Elements (LeetCode)

Model answer

The task

Given an integer array and a value k, return the k values that occur most often. Their order does not matter.

Key idea

Count each value’s occurrences, then group values by frequency. Since no frequency can exceed the array length, scan these groups from highest frequency down until k values are collected.

Approach

  1. Build a frequency map from each value to its count.
  2. Create buckets indexed by frequency.
  3. Put each distinct value into the bucket for its count.
  4. Scan buckets from highest to lowest, collecting values until there are k.
from collections import defaultdict
from typing import List

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        # Count occurrences of each value.
        frequency = defaultdict(int)
        for value in nums:
            frequency[value] += 1

        # Bucket each value by its frequency.
        buckets = [[] for _ in range(len(nums) + 1)]
        for value, count in frequency.items():
            buckets[count].append(value)

        # Collect values from most frequent to least frequent.
        result = []
        for count in range(len(nums), 0, -1):
            for value in buckets[count]:
                result.append(value)
                if len(result) == k:
                    return result

        return result

Complexity:

  • Time: O(n), where n is the array length; counting and scanning the buckets take linear time.
  • Space: O(n), for the frequency map and buckets.

Common follow-ups

  • How would you solve it with a heap? Keep a size-k heap of distinct values, giving O(n + m log k) time, where m is the number of distinct values.
  • What if results must be ordered by frequency? Sort the selected values by their counts, or collect them in descending bucket order.
  • What if the data arrives as a stream? Maintain approximate counts with a streaming frequency sketch, or use a bounded candidate structure when exact counts are not feasible.
CodingMediumHuaweiSoftware Engineer

9. Longest Increasing Subsequence (LeetCode)

Model answer

The task

Given an integer array, return the length of its longest strictly increasing subsequence. The chosen elements must stay in their original order, but they do not need to be adjacent.

Key idea

Maintain tails, where tails[k] is the smallest possible ending value for an increasing subsequence of length k + 1 seen so far. Smaller endings leave more room to extend a subsequence, so these values let us process each element efficiently.

Approach

  1. Start with an empty tails list.
  2. For each number, binary-search for the first value in tails that is greater than or equal to it.
  3. Replace that value with the number, or append the number if none exists.
  4. Return the length of tails. Its values need not themselves form the final subsequence; its length is the answer.
from bisect import bisect_left
from typing import List

class Solution:
    def lengthOfLIS(self, nums: List[int]) -> int:
        # tails[i] is the smallest ending value found for a
        # strictly increasing subsequence of length i + 1.
        tails: List[int] = []

        for value in nums:
            # Find the first ending value >= value.
            # Replacing it preserves the best possible tail.
            index = bisect_left(tails, value)

            if index == len(tails):
                tails.append(value)
            else:
                tails[index] = value

        return len(tails)

Complexity:

  • Time: O(n log n), with one binary search per element.
  • Space: O(n), for the tails list in the worst case.

Common follow-ups

  • How would you return an actual longest subsequence? Track predecessor indices and the source index for each tail, then backtrack from the final tail.
  • How would you handle a non-decreasing subsequence? Use bisect_right so equal values can extend a subsequence.
  • Can this be solved with dynamic programming? Yes; compare each element with all earlier elements for O(n²) time and O(n) space.
CodingMediumHuaweiSoftware Engineer

10. Maximum Binary String After Change (LeetCode)

Model answer

The task

Given a binary string, repeatedly apply the allowed changes to adjacent bits to make the resulting string as large as possible in binary order. Return that maximum string.

Key idea

If the string contains a zero, the best result has exactly one zero. Its final position is determined by the first zero and the total number of zeros: it ends up at index first_zero + zero_count - 1. All other positions can be ones.

Approach

  1. Find the first zero.
  2. If there is none, return the string unchanged.
  3. Count the zeros in the string.
  4. Build a string of ones, then place a zero at the calculated final position.
class Solution:
    def maximumBinaryString(self, binary: str) -> str:
        first_zero = binary.find("0")

        # The string is already maximal if it contains no zero.
        if first_zero == -1:
            return binary

        zero_count = binary.count("0")
        final_zero_index = first_zero + zero_count - 1

        # All bits can become one except the zero at its final position.
        result = ["1"] * len(binary)
        result[final_zero_index] = "0"
        return "".join(result)

Complexity:

  • Time: O(n), to scan the string and construct the result.
  • Space: O(n), for the returned string.

Common follow-ups

  • Why can there be at most one zero in the maximum? The operations can turn pairs of zeros into ones while preserving one zero to move right.
  • Why does the zero end at this index? Each zero after the first zero contributes one position to its rightward movement.
  • What if the input has no zeros? It is already the maximum string, so return it unchanged.
CodingHardHuaweiSoftware Engineer

11. N-Queens (LeetCode)

Model answer

The task

Return every distinct arrangement of n queens on an n × n board such that no two queens share a row, column, or diagonal. Represent each arrangement as a list of strings.

Key idea

Place one queen per row and backtrack whenever a column or diagonal is already occupied. Bitmasks track occupied columns and the diagonals attacked in the next row, making each safety check constant time.

Approach

  1. Track occupied columns and the two diagonal attack patterns as bitmasks.
  2. For the current row, compute which columns are available.
  3. Try each available column, update the masks, and recurse.
  4. When all rows are filled, convert the recorded column positions into board strings.
  5. Backtrack to explore every valid arrangement.
from typing import List

class Solution:
    def solveNQueens(self, n: int) -> List[List[str]]:
        full = (1 << n) - 1
        positions = []
        boards = []

        def search(row: int, columns: int, diag_left: int, diag_right: int) -> None:
            if row == n:
                board = []
                for col in positions:
                    board.append("." * col + "Q" + "." * (n - col - 1))
                boards.append(board)
                return

            available = full & ~(columns | diag_left | diag_right)

            while available:
                # Extract the rightmost available column.
                bit = available & -available
                available -= bit

                positions.append(bit.bit_length() - 1)
                search(
                    row + 1,
                    columns | bit,
                    ((diag_left | bit) << 1) & full,
                    (diag_right | bit) >> 1,
                )
                positions.pop()

        search(0, 0, 0, 0)
        return boards

Complexity:

  • Time: O(n! + S · n²), where S is the number of returned boards; the first term bounds the search tree.
  • Space: O(n) auxiliary space for recursion and placement tracking, excluding the returned boards.

Common follow-ups

  • How would you count solutions without storing boards? Increment a counter at each completed placement.
  • How could you find just one solution? Stop the search as soon as a complete placement is found.
  • What if some cells are blocked? Exclude blocked columns from the available choices for each row.
CodingHardHuaweiSoftware Engineer

12. Trapping Rain Water (LeetCode)

Model answer

The task

Given an array of nonnegative bar heights, compute how much water remains trapped between the bars after rainfall. Each bar has unit width.

Key idea

Water above a position is limited by the shorter of the tallest bars to its left and right. With two pointers, process the side whose current height is lower: its boundary already determines the maximum water that position can hold, so no arrays of prefix and suffix maxima are needed.

Approach

  1. Start pointers at both ends and track the greatest height seen from each side.
  2. While the pointers have not crossed, compare their current heights.
  3. If the left height is lower, update the left maximum and add any water above the left bar, then advance the left pointer.
  4. Otherwise, do the symmetric operation on the right.
  5. Return the accumulated water.
from typing import List

class Solution:
    def trap(self, height: List[int]) -> int:
        left, right = 0, len(height) - 1
        left_max = right_max = 0
        water = 0

        while left < right:
            if height[left] < height[right]:
                # The right side is tall enough that the left maximum
                # determines the water level at this position.
                left_max = max(left_max, height[left])
                water += left_max - height[left]
                left += 1
            else:
                # Symmetrically, the right maximum determines this level.
                right_max = max(right_max, height[right])
                water += right_max - height[right]
                right -= 1

        return water

Complexity:

  • Time: O(n), because each pointer moves across the array at most once.
  • Space: O(1), because the algorithm uses only a fixed number of variables.

Common follow-ups

  • How can this be solved with dynamic programming? Precompute the maximum height to each position from the left and right, then sum the trapped water at each position.
  • How can a monotonic stack solve it? Keep indices of decreasing bar heights; when a taller bar arrives, pop a basin bottom and calculate the bounded layer.
  • What if bars have different widths? Track each bar’s width and use area rather than unit-width contributions; the boundary logic must account for the resulting horizontal spans.
CodingHardHuaweiSoftware Engineer

13. Minimum Number of Visited Cells in a Grid (LeetCode)

Model answer

The task

Given a grid where each cell limits how far you can move right or down, find the fewest cells visited on a path from the top-left to the bottom-right. Return -1 if no path exists.

Key idea

Process cells in row-major order, so every possible predecessor has already been considered. For each row and column, keep a min-heap of reachable cells, ordered by the number of cells visited; lazily discard heap entries that can no longer reach the current position.

Approach

  1. Create one heap per row and one per column.
  2. At each cell, remove heap-top entries whose reach ends before this cell.
  3. Set the start cell’s distance to 1; otherwise, take one plus the smallest available predecessor distance.
  4. If the cell is reachable, add it to its row and column heaps with its rightward and downward reach.
  5. Return the destination’s distance, or -1 if it was unreachable.
from heapq import heappush, heappop
from typing import List

class Solution:
    def minimumVisitedCells(self, grid: List[List[int]]) -> int:
        rows, cols = len(grid), len(grid[0])

        # Entries are (visited_cells, farthest_reachable_column/row).
        row_heaps = [[] for _ in range(rows)]
        col_heaps = [[] for _ in range(cols)]
        answer = -1

        for r in range(rows):
            for c in range(cols):
                row_heap = row_heaps[r]
                col_heap = col_heaps[c]

                # Discard heap-top entries that cannot reach this cell.
                while row_heap and row_heap[0][1] < c:
                    heappop(row_heap)
                while col_heap and col_heap[0][1] < r:
                    heappop(col_heap)

                if r == 0 and c == 0:
                    steps = 1
                else:
                    best = float("inf")
                    if row_heap:
                        best = min(best, row_heap[0][0])
                    if col_heap:
                        best = min(best, col_heap[0][0])

                    steps = best + 1 if best != float("inf") else float("inf")

                if steps != float("inf"):
                    if r == rows - 1 and c == cols - 1:
                        answer = steps

                    reach_right = min(cols - 1, c + grid[r][c])
                    reach_down = min(rows - 1, r + grid[r][c])
                    heappush(row_heap, (steps, reach_right))
                    heappush(col_heap, (steps, reach_down))

        return answer

Complexity:

  • Time: O(mn log(max(m, n))); each cell is added to two heaps and removed at most once.
  • Space: O(mn); the heaps can hold entries for all reachable cells.

Common follow-ups

  • Can BFS solve it? Yes, but naive BFS may revisit many cells; heaps or disjoint-set skipping avoid that work.
  • What if moves can go in any direction? The row-major ordering no longer applies; use a graph-search approach.
  • Can unreachable cells be stored in the heaps? No; only cells with a finite distance can extend a path.

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