Nutanix interview questions & answers

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

CodingEasyNutanixSoftware Engineer

1. Can Place Flowers (LeetCode)

Model answer

The task

Given a row of plots where 1 marks an occupied plot and 0 an empty one, decide whether at least n flowers can be added without placing flowers in neighboring plots.

Key idea

Scan from left to right, planting in an empty plot whenever both neighboring plots are empty or outside the row. Greedily planting at the earliest available plot cannot reduce the number of later planting opportunities.

Approach

  1. Return True immediately if n is zero.
  2. Visit each plot from left to right.
  3. For an empty plot, check its left and right neighbors, treating the row boundaries as empty.
  4. If both are empty, plant there and decrement n.
  5. Return True once n reaches zero; otherwise return whether it reached zero by the end.
from typing import List

class Solution:
    def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
        if n == 0:
            return True

        for i in range(len(flowerbed)):
            if flowerbed[i] == 0:
                left_empty = i == 0 or flowerbed[i - 1] == 0
                right_empty = (
                    i == len(flowerbed) - 1 or flowerbed[i + 1] == 0
                )

                if left_empty and right_empty:
                    flowerbed[i] = 1
                    n -= 1

                    if n == 0:
                        return True

        return False

Complexity:

  • Time: O(m), where m is the number of plots; each plot is checked at most once.
  • Space: O(1), using only a fixed amount of extra space.

Common follow-ups

  • What if the input must not be modified? Track the previous plot’s occupancy instead of planting in the array.
  • How would you return the planting positions? Record each plot index when the greedy rule permits planting.
  • What if plots wrap around in a circle? Handle the first and last plots as neighbors, with special care for rows of length one or two.
CodingEasyNutanixSoftware Engineer

2. Diameter of Binary Tree (LeetCode)

Model answer

The task

Find the diameter of a binary tree: the largest number of edges on a path between any two nodes. The path does not have to pass through the root.

Key idea

At each node, the longest path that passes through it has length left_height + right_height. A postorder depth-first search computes child heights and updates the best diameter along the way.

Approach

  1. Keep a variable for the largest diameter seen so far.
  2. Recursively compute the height of each subtree, using zero for an empty subtree.
  3. At each node, combine its left and right heights to get the path length through it.
  4. Update the best diameter, then return the node’s height to its parent.
  5. Return the recorded diameter after visiting the tree.
# The TreeNode type is provided by the platform.
class Solution:
    def diameterOfBinaryTree(self, root):
        diameter = 0

        def height(node):
            nonlocal diameter

            if node is None:
                return 0

            left_height = height(node.left)
            right_height = height(node.right)

            # The path through this node uses one edge per level
            # from each child subtree.
            diameter = max(diameter, left_height + right_height)

            # Return this subtree's height in nodes.
            return 1 + max(left_height, right_height)

        height(root)
        return diameter

Complexity:

  • Time: O(n), because each node is visited once.
  • Space: O(h), for the recursion stack, where h is the tree height.

Common follow-ups

  • What if the diameter should be measured in nodes? Add one to the edge count for a non-empty tree.
  • How does a skewed tree affect recursion space? Its height is O(n), so recursion may use O(n) stack space.
  • Can this be done iteratively? Yes; use an explicit stack and process nodes in postorder while storing subtree heights.
CodingEasyNutanixSoftware Engineer

3. Convert Binary Number in a Linked List to Integer (LeetCode)

Model answer

The task

Given the head of a linked list whose nodes contain binary digits, return the integer represented by those digits in list order.

Key idea

Process the bits from left to right, updating the value as if appending each bit to a binary number. Appending a bit is equivalent to shifting the current value left once, then adding the bit.

Approach

  1. Start the accumulated value at zero.
  2. Traverse the list from its head.
  3. For each node, shift the value left one bit and add the node’s digit.
  4. Return the accumulated value after reaching the end.
class Solution:
    def getDecimalValue(self, head):
        value = 0
        node = head

        while node:
            # Shift left to make room for the next bit, then append it.
            value = (value << 1) | node.val
            node = node.next

        return value

Complexity:

  • Time: O(n), where n is the number of nodes visited once.
  • Space: O(1), using only a fixed amount of extra space.

Common follow-ups

  • What if the list is empty? The traversal does not run, so the result is zero.
  • Could the list be processed recursively? Yes, but recursion uses O(n) call-stack space.
  • What if the bits are stored least-significant first? Track the bit position and add each digit multiplied by its corresponding power of two.
CodingEasyNutanixSoftware EngineerSystem Design (Javascript)

4. Implement a number-increment counter in JavaScript.

Model answer

// Returns a function that increments and returns its own counter value.
function createCounter(initialValue = 0) {
  let count = initialValue;

  return function increment() {
    count += 1;
    return count;
  };
}

const counter = createCounter(0);
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
  • The closure keeps count private and preserves it between calls.
  • Each call increments once and returns the updated value.

Complexity: O(1) time per call and O(1) space.

CodingMediumNutanixSoftware Engineer

5. Pacific Atlantic Water Flow (LeetCode)

Model answer

The task

Given a grid of elevations, find every cell from which water can flow to both the Pacific and Atlantic oceans. Water can flow between adjacent cells only downhill or across cells of equal height; the Pacific borders the top and left edges, and the Atlantic borders the bottom and right edges.

Key idea

Instead of tracing water downhill from every cell, search backward from each ocean. From a cell already reachable by an ocean, the reverse search can move to an adjacent cell of equal or greater height.

Approach

  1. Return an empty list if the grid has no rows or columns.
  2. Initialize one search from the Pacific-border cells and another from the Atlantic-border cells.
  3. In each search, visit a neighbor only if it is in bounds, unvisited, and at least as high as the current cell.
  4. Return the coordinates visited by both searches.
from collections import deque
from typing import List

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

        rows, cols = len(heights), len(heights[0])

        def reachable(starts):
            visited = set(starts)
            queue = deque(starts)

            while queue:
                r, c = queue.popleft()

                for nr, nc in ((r - 1, c), (r + 1, c),
                               (r, c - 1), (r, c + 1)):
                    if (0 <= nr < rows and 0 <= nc < cols
                            and (nr, nc) not in visited
                            and heights[nr][nc] >= heights[r][c]):
                        visited.add((nr, nc))
                        queue.append((nr, nc))

            return visited

        pacific_starts = (
            [(0, c) for c in range(cols)]
            + [(r, 0) for r in range(rows)]
        )
        atlantic_starts = (
            [(rows - 1, c) for c in range(cols)]
            + [(r, cols - 1) for r in range(rows)]
        )

        pacific = reachable(pacific_starts)
        atlantic = reachable(atlantic_starts)

        return [[r, c] for r, c in pacific & atlantic]

Complexity:

  • Time: O(rows × cols), since each cell is visited at most once per search.
  • Space: O(rows × cols) for the visited sets and queues.

Common follow-ups

  • Can DFS replace BFS? Yes; either traversal finds the same reachable cells.
  • How would you handle diagonal flow? Include diagonal neighbors in the traversal.
  • What if the grid is updated repeatedly? Recompute reachability, or use a specialized dynamic-connectivity strategy if updates are frequent.
CodingMediumNutanixSoftware Engineer

6. 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.
CodingMediumNutanixSoftware Engineer

7. Min Cost to Connect All Points (LeetCode)

Model answer

The task

Given points in a plane, connect them so every point is reachable from every other point, minimizing the total Manhattan distance of the chosen connections.

Key idea

The points form a complete weighted graph, but explicitly building all edges is unnecessary. Prim’s algorithm can grow a minimum spanning tree by tracking each unconnected point’s cheapest connection to the current tree.

Approach

  1. Start the tree at point 0 with cost 0.
  2. Keep the cheapest known connection cost for each point and mark points as visited when added.
  3. Repeatedly add the unvisited point with the smallest connection cost.
  4. Add that cost to the answer, then update the remaining costs using Manhattan distance from the newly added point.
  5. Return the sum after all points have been added.
from typing import List

class Solution:
    def minCostConnectPoints(self, points: List[List[int]]) -> int:
        n = len(points)
        if n <= 1:
            return 0

        # best[i] is the cheapest edge currently known from the tree to i.
        best = [float("inf")] * n
        best[0] = 0
        visited = [False] * n
        total_cost = 0

        for _ in range(n):
            # Select the unvisited point with the cheapest connection.
            current = -1
            for i in range(n):
                if not visited[i] and (
                    current == -1 or best[i] < best[current]
                ):
                    current = i

            visited[current] = True
            total_cost += best[current]

            x1, y1 = points[current]
            for i in range(n):
                if not visited[i]:
                    x2, y2 = points[i]
                    distance = abs(x1 - x2) + abs(y1 - y2)
                    best[i] = min(best[i], distance)

        return total_cost

Complexity:

  • Time: O(n²), from selecting the next point and updating distances for each point.
  • Space: O(n), for the connection costs and visited flags.

Common follow-ups

  • Can Kruskal’s algorithm solve it? Yes; generate all point pairs, sort by distance, and use Union-Find, taking O(n² log n) time and O(n²) space.
  • Can Prim’s algorithm use a heap? Yes, but this dense graph still has O(n²) possible edges; the array-based version is simpler and avoids storing them.
  • What if there is only one point? No connection is needed, so the cost is 0.
  • What if distances use another metric? Replace the Manhattan distance calculation, provided the edge weights remain well-defined.
CodingMediumNutanixSoftware Engineer

8. Surrounded Regions (LeetCode)

Model answer

The task

Given a grid of X and O cells, change each O that is fully enclosed by X into X. An O connected to the grid boundary through adjacent O cells must remain unchanged.

Key idea

Any O that cannot be captured is reachable from a boundary O. Mark all such cells, then flip the remaining O cells and restore the marks.

Approach

  1. Return immediately if the grid has no rows or columns.
  2. Start a traversal from every boundary O, marking each reachable O as safe.
  3. Use an iterative stack so a large region cannot exceed Python’s recursion limit.
  4. Scan the grid: flip unmarked O cells to X and restore safe marks to O.
from typing import List

class Solution:
    def solve(self, board: List[List[str]]) -> None:
        """Modify board in place to capture surrounded regions."""
        if not board or not board[0]:
            return

        rows, cols = len(board), len(board[0])
        stack = []

        def add_if_open(r: int, c: int) -> None:
            if board[r][c] == "O":
                board[r][c] = "#"
                stack.append((r, c))

        # Seed the traversal with open cells on the boundary.
        for r in range(rows):
            add_if_open(r, 0)
            if cols > 1:
                add_if_open(r, cols - 1)

        for c in range(cols):
            add_if_open(0, c)
            if rows > 1:
                add_if_open(rows - 1, c)

        # Mark every open cell connected to the boundary.
        while stack:
            r, c = stack.pop()
            for nr, nc in ((r - 1, c), (r + 1, c),
                           (r, c - 1), (r, c + 1)):
                if 0 <= nr < rows and 0 <= nc < cols:
                    add_if_open(nr, nc)

        # Capture enclosed cells and restore the safe ones.
        for r in range(rows):
            for c in range(cols):
                if board[r][c] == "O":
                    board[r][c] = "X"
                elif board[r][c] == "#":
                    board[r][c] = "O"

Complexity:

  • Time: O(mn), where m and n are the grid dimensions; each cell is processed a constant number of times.
  • Space: O(mn) in the worst case for the traversal stack.

Common follow-ups

  • Can this be solved with BFS instead? Yes; use a queue in place of the stack.
  • How would Union-Find solve it? Connect boundary O cells to a virtual outside node, then preserve cells in that node’s component.
  • What if diagonal cells count as connected? Include the four diagonal neighbors in the traversal.
CodingMediumNutanixSoftware Engineer

9. Snapshot Array (LeetCode)

Model answer

The task

Implement an array that supports updates, saving snapshots, and reading an index’s value as it was at a particular snapshot.

Key idea

For each index, store only the values that were explicitly set, tagged with the current snapshot ID. These IDs are ordered, so a binary search finds the most recent update no later than the requested snapshot.

Approach

  1. Keep a history list for each index and a counter for the next snapshot ID.
  2. On set, overwrite that index’s last history entry if it belongs to the current snapshot; otherwise, append a new entry.
  3. On snap, return the current ID and advance the counter.
  4. On get, binary-search the index’s history for the last entry whose ID is at most the requested ID.
  5. Return 0 if that index has no earlier recorded update.
class SnapshotArray:
    def __init__(self, length: int):
        self.histories = [[] for _ in range(length)]
        self.current_snap_id = 0

    def set(self, index: int, val: int) -> None:
        history = self.histories[index]

        # Only the final value set in a snapshot needs to be recorded.
        if history and history[-1][0] == self.current_snap_id:
            history[-1] = (self.current_snap_id, val)
        else:
            history.append((self.current_snap_id, val))

    def snap(self) -> int:
        snap_id = self.current_snap_id
        self.current_snap_id += 1
        return snap_id

    def get(self, index: int, snap_id: int) -> int:
        history = self.histories[index]

        # Find the first history entry with an ID greater than snap_id.
        low, high = 0, len(history)
        while low < high:
            mid = (low + high) // 2
            if history[mid][0] <= snap_id:
                low = mid + 1
            else:
                high = mid

        # The preceding entry is the latest update visible in this snapshot.
        return history[low - 1][1] if low > 0 else 0

Complexity:

  • Time: set and snap are O(1); get is O(log H), where H is the history length for that index.
  • Space: O(W), where W is the number of recorded writes across all indices.

Common follow-ups

  • How can memory be reduced when values often repeat? Skip recording a set when it matches the most recent value.
  • How would you support undoing snapshots? Use a persistent structure or retain version roots so earlier states remain addressable.
  • What if reads are much more frequent than writes? The per-index histories already make reads efficient, with logarithmic lookup.
CodingMediumNutanixSoftware Engineer

10. Reverse Nodes in Even Length Groups (LeetCode)

Model answer

The task

Given a singly linked list, divide its nodes into consecutive groups with target sizes 1, 2, 3, and so on. Reverse each group whose actual size is even, including a final group that may be shorter than its target size.

Key idea

Process one group at a time, first counting how many nodes it actually contains. For an even-sized group, reverse its links in place and reconnect it to the surrounding list.

Approach

  1. Use a dummy node to simplify handling the list head.
  2. Track the node before the current group and the group’s target size.
  3. Count up to that many nodes, stopping at the end of the list.
  4. If the actual count is even, reverse those nodes and reconnect the group.
  5. Advance to the next group, increasing the target size.
from typing import Optional

# ListNode is provided by the platform.
class Solution:
    def reverseEvenLengthGroups(
        self, head: Optional["ListNode"]
    ) -> Optional["ListNode"]:
        dummy = ListNode(0)
        dummy.next = head

        group_prev = dummy
        group_size = 1

        while group_prev.next is not None:
            # Find the end of this group and count its actual nodes.
            group_end = group_prev
            count = 0
            while count < group_size and group_end.next is not None:
                group_end = group_end.next
                count += 1

            if count % 2 == 0:
                group_start = group_prev.next
                after_group = group_end.next

                # Reverse this group, linking its old head to the next group.
                prev = after_group
                curr = group_start
                for _ in range(count):
                    next_node = curr.next
                    curr.next = prev
                    prev = curr
                    curr = next_node

                group_prev.next = group_end
                group_prev = group_start  # The old head is now the group's tail.
            else:
                group_prev = group_end

            group_size += 1

        return dummy.next

Complexity:

  • Time: O(n), since each node is visited a constant number of times.
  • Space: O(1), since the list is modified in place.

Common follow-ups

  • How would you reverse odd-sized groups instead? Change the parity check to count % 2 == 1.
  • What if groups had a fixed size k? Use k as the target size for each group.
  • Can this be done recursively? Yes, but recursion may use O(n) stack space in the worst case.
CodingMediumNutanixSenior Software EngineerJavaScript Platform & DSA

11. Implement debounce and its variations using promises.

Model answer

function debouncePromise(fn, wait, { leading = false, trailing = true } = {}) {
  if (!leading && !trailing) {
    throw new Error("At least one of leading or trailing must be enabled");
  }

  let timer = null;
  let pending = [];
  let latestThis;
  let latestArgs;
  let lastLeadingPromise;

  function invoke(context, args, waiters = []) {
    const execution = Promise.resolve().then(() => fn.apply(context, args));
    execution.then(
      value => waiters.forEach(waiter => waiter.resolve(value)),
      error => waiters.forEach(waiter => waiter.reject(error))
    );
    return execution;
  }

  function onTimer() {
    timer = null;
    if (pending.length === 0) return Promise.resolve(undefined);

    const batch = pending;
    pending = [];
    return invoke(latestThis, latestArgs, batch);
  }

  function debounced(...args) {
    const context = this;

    if (timer === null && leading) {
      // Invoke the first call immediately, then start the debounce window.
      lastLeadingPromise = invoke(context, args);
      timer = setTimeout(onTimer, wait);
      return lastLeadingPromise;
    }

    if (trailing) {
      latestThis = context;
      latestArgs = args;
      const promise = new Promise((resolve, reject) => {
        pending.push({ resolve, reject });
      });
      clearTimeout(timer);
      timer = setTimeout(onTimer, wait);
      return promise;
    }

    // In leading-only mode, suppressed calls share the first call's result.
    return lastLeadingPromise;
  }

  debounced.cancel = () => {
    clearTimeout(timer);
    timer = null;
    const error = new Error("Debounced call cancelled");
    pending.forEach(waiter => waiter.reject(error));
    pending = [];
  };

  debounced.flush = () => {
    if (timer === null) return Promise.resolve(undefined);
    clearTimeout(timer);
    return onTimer();
  };

  return debounced;
}

// Trailing: only the final call runs after the quiet period.
const search = debouncePromise(query => fetchResults(query), 250);

// Leading + trailing: run immediately, then run once more with the final call
// if additional calls arrive during the debounce window.
const save = debouncePromise(value => persist(value), 500, {
  leading: true,
  trailing: true,
});
  • Each trailing caller gets a promise; callers in the same debounce window receive the result or rejection of the final invocation.
  • leading runs the first call immediately; trailing controls whether later calls are coalesced and run at the end. cancel() rejects queued callers; flush() runs them now.
  • Complexity: O(1) scheduling per call, plus O(k) to settle k coalesced promises; O(k) space for pending callers.
CodingMediumNutanixSoftware Engineer

12. 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.
CodingMediumNutanixSoftware Engineer

13. Boundary of Binary Tree (LeetCode)

Model answer

The task

Return the binary tree’s outer boundary in counterclockwise order, with each boundary node included once. The boundary consists of the root, the left side, the leaves from left to right, and the right side in reverse order.

Key idea

Build each part separately and exclude leaves from the side traversals, since leaves are collected in their own pass. Handle a single-node tree separately to avoid returning its root twice.

Approach

  1. Return an empty list if the tree is empty.
  2. If the root is a leaf, return just its value.
  3. Walk down the left side, preferring left children, and collect non-leaf nodes.
  4. Collect leaves in left-to-right order with DFS.
  5. Walk down the right side, preferring right children, and append its non-leaf nodes in reverse.
# Definition for a binary tree node:
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution:
    def boundaryOfBinaryTree(self, root):
        if root is None:
            return []

        def is_leaf(node):
            return node.left is None and node.right is None

        if is_leaf(root):
            return [root.val]

        boundary = [root.val]

        # Collect the left boundary, excluding leaves.
        node = root.left
        while node:
            if not is_leaf(node):
                boundary.append(node.val)
            node = node.left if node.left else node.right

        # Collect leaves from left to right.
        def add_leaves(node):
            if node is None:
                return
            if is_leaf(node):
                boundary.append(node.val)
                return
            add_leaves(node.left)
            add_leaves(node.right)

        add_leaves(root.left)
        add_leaves(root.right)

        # Collect the right boundary, excluding leaves, then reverse it.
        right_side = []
        node = root.right
        while node:
            if not is_leaf(node):
                right_side.append(node.val)
            node = node.right if node.right else node.left

        boundary.extend(reversed(right_side))
        return boundary

Complexity:

  • Time: O(n), visiting each node a constant number of times.
  • Space: O(h) auxiliary recursion and boundary storage, excluding the returned list; h is the tree height.

Common follow-ups

  • How would you avoid recursion? Use an explicit stack for the leaf traversal.
  • What if the boundary should be clockwise? Swap the side traversal order and reverse the leaf order.
  • How does a skewed tree affect complexity? The time remains O(n), while the recursion stack can grow to O(n).
CodingMediumNutanixSoftware Engineer

14. Path With Minimum Effort (LeetCode)

Model answer

The task

Given a grid of heights, find a path from the top-left cell to the bottom-right cell that minimizes the largest height difference between consecutive cells on the path. Movement is allowed between cells sharing an edge.

Key idea

Use Dijkstra’s algorithm, where a path’s cost is the maximum edge difference encountered so far, rather than the sum of edge weights. When relaxing a neighbor, its candidate cost is the larger of the current path cost and the height difference to that neighbor.

Approach

  1. Treat each cell as a graph node, with edges to its up, down, left, and right neighbors.
  2. Initialize the top-left cell’s effort to zero and push it into a min-heap.
  3. Repeatedly process the cell with the smallest known effort.
  4. For each neighbor, compute the candidate effort and update it if smaller than the recorded value.
  5. Return the effort when the bottom-right cell is reached.
import heapq
from typing import List

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

        # Best known minimum effort to reach each cell.
        effort = [[float("inf")] * cols for _ in range(rows)]
        effort[0][0] = 0

        heap = [(0, 0, 0)]  # (effort, row, column)
        directions = ((1, 0), (-1, 0), (0, 1), (0, -1))

        while heap:
            current_effort, row, col = heapq.heappop(heap)

            # Ignore outdated heap entries.
            if current_effort > effort[row][col]:
                continue

            if row == rows - 1 and col == cols - 1:
                return current_effort

            for dr, dc in directions:
                nr, nc = row + dr, col + dc
                if 0 <= nr < rows and 0 <= nc < cols:
                    step_effort = abs(heights[row][col] - heights[nr][nc])
                    candidate = max(current_effort, step_effort)

                    if candidate < effort[nr][nc]:
                        effort[nr][nc] = candidate
                        heapq.heappush(heap, (candidate, nr, nc))

        return 0

Complexity:

  • Time: O(mn log(mn)), since each cell can be pushed into the heap as its effort improves.
  • Space: O(mn) for the effort matrix and heap.

Common follow-ups

  • Can binary search be used instead? Yes: binary-search a maximum allowed step difference and use BFS/DFS to test reachability.
  • How can the problem be solved with Union-Find? Sort grid edges by height difference and union endpoints until the start and destination connect.
  • What if the path should minimize the sum of height differences? Use ordinary shortest-path Dijkstra, adding each step’s difference instead of taking a maximum.
CodingMediumNutanixSoftware Engineer

15. Spiral Matrix (LeetCode)

Model answer

The task

Return the matrix values in clockwise spiral order, starting from the top-left corner and moving inward.

Key idea

Track the unvisited rectangle with four boundaries. Visit its top, right, bottom, and left edges in turn, then shrink the rectangle and repeat.

Approach

  1. Return an empty list if the matrix has no rows or columns.
  2. Initialize boundaries for the top, bottom, left, and right edges.
  3. Traverse the top edge, then move the top boundary inward.
  4. Traverse the right edge, then move the right boundary inward.
  5. If rows remain, traverse the bottom edge in reverse; if columns remain, traverse the left edge upward.
  6. Repeat until the boundaries cross.
from typing import List

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

        result = []
        top, bottom = 0, len(matrix) - 1
        left, right = 0, len(matrix[0]) - 1

        while top <= bottom and left <= right:
            # Traverse the top edge from left to right.
            for col in range(left, right + 1):
                result.append(matrix[top][col])
            top += 1

            # Traverse the right edge from top to bottom.
            for row in range(top, bottom + 1):
                result.append(matrix[row][right])
            right -= 1

            # Traverse the bottom edge only if it has not been visited.
            if top <= bottom:
                for col in range(right, left - 1, -1):
                    result.append(matrix[bottom][col])
                bottom -= 1

            # Traverse the left edge only if it has not been visited.
            if left <= right:
                for row in range(bottom, top - 1, -1):
                    result.append(matrix[row][left])
                left += 1

        return result

Complexity: Time: O(m × n), where each cell is visited once.

Complexity: Space: O(1) auxiliary space, excluding the output list.

Common follow-ups

  • How would you return the values counterclockwise? Change the traversal order and edge directions while maintaining the same boundary updates.
  • How does this handle a single row or column? The boundary checks prevent an edge from being visited twice.
  • Can the traversal be done without boundary variables? Yes, by marking visited cells and turning when blocked, but that requires O(m × n) extra space.
CodingMediumNutanixSoftware Engineer

16. Course Schedule II (LeetCode)

Model answer

The task

Return an ordering of all courses that satisfies the prerequisite relationships. If no such ordering exists because the relationships contain a cycle, return an empty list.

Key idea

Model each course as a graph node, with an edge from a prerequisite to the course that depends on it. Kahn’s topological-sort algorithm repeatedly takes courses with no remaining prerequisites; if it cannot take every course, the graph contains a cycle.

Approach

  1. Build an adjacency list and count each course’s prerequisites as its indegree.
  2. Add all zero-indegree courses to a queue.
  3. Remove courses from the queue, adding each to the result and reducing the indegree of its dependent courses.
  4. Add a dependent course to the queue when its indegree reaches zero.
  5. Return the result if it includes every course; otherwise, return an empty list.
from collections import deque
from typing import List

class Solution:
    def findOrder(
        self, numCourses: int, prerequisites: List[List[int]]
    ) -> List[int]:
        # Edges point from prerequisite to dependent course.
        graph = [[] for _ in range(numCourses)]
        indegree = [0] * numCourses

        for course, prerequisite in prerequisites:
            graph[prerequisite].append(course)
            indegree[course] += 1

        ready = deque(
            course
            for course in range(numCourses)
            if indegree[course] == 0
        )
        order = []

        while ready:
            course = ready.popleft()
            order.append(course)

            for dependent in graph[course]:
                indegree[dependent] -= 1
                if indegree[dependent] == 0:
                    ready.append(dependent)

        # A cycle prevents all courses from being added.
        return order if len(order) == numCourses else []

**Complexity:**

- Time: O(V + E), where V is the number of courses and E is the number of prerequisite relationships.
- Space: O(V + E) for the graph, indegrees, queue, and result.

**Common follow-ups**

- How can DFS solve this? Use three node states—unvisited, visiting, and visited—to detect cycles while building a topological order.
- How can the algorithm return the number of courses that can be completed? Return the length of the processed order.
- How can you choose the smallest-numbered available course at each step? Use a min-heap instead of a queue, giving O((V + E) log V) time.
CodingMediumNutanixSoftware Engineer

17. Set Matrix Zeroes (LeetCode)

Model answer

The task

Given a matrix, modify it in place so that any row or column containing a zero is entirely zeroed. The zeroes introduced during modification should not cause additional rows or columns to be selected.

Key idea

Use the first row and first column as marker storage: mark which rows and columns must be cleared. Track separately whether either of those marker areas originally contains a zero, since they also serve as storage.

Approach

  1. Check whether the first row and first column initially contain zeroes.
  2. Scan the rest of the matrix; for every zero, mark its row in the first column and its column in the first row.
  3. Use those markers to zero the corresponding interior cells.
  4. If needed, zero the first row and first column last.
class Solution:
    def setZeroes(self, matrix: list[list[int]]) -> None:
        """
        Modify matrix in place.
        """
        rows, cols = len(matrix), len(matrix[0])

        first_row_has_zero = any(matrix[0][c] == 0 for c in range(cols))
        first_col_has_zero = any(matrix[r][0] == 0 for r in range(rows))

        # Record which interior rows and columns need to be zeroed.
        for r in range(1, rows):
            for c in range(1, cols):
                if matrix[r][c] == 0:
                    matrix[r][0] = 0
                    matrix[0][c] = 0

        # Apply the recorded markers to the interior.
        for r in range(1, rows):
            for c in range(1, cols):
                if matrix[r][0] == 0 or matrix[0][c] == 0:
                    matrix[r][c] = 0

        # Clear the marker row and column if they originally had zeroes.
        if first_row_has_zero:
            for c in range(cols):
                matrix[0][c] = 0

        if first_col_has_zero:
            for r in range(rows):
                matrix[r][0] = 0

Complexity:

  • Time: O(mn), where m and n are the matrix dimensions; the matrix is scanned a constant number of times.
  • Space: O(1) auxiliary space; markers are stored in the matrix itself.

Common follow-ups

  • What if the matrix must not be modified in place? Use separate row and column marker arrays, requiring O(m + n) extra space.
  • What if the matrix is sparse? Store the indices of affected rows and columns while scanning only the available entries.
  • Does the approach work for a one-row or one-column matrix? Yes; the separate first-row and first-column flags handle those cases.
TechnicalMediumNutanixSoftware EngineerSystem Design (Frontend + Backend)

18. How do you secure an API?

Model answer

I secure an API in layers, starting with the threat model and applying controls at the edge and in each service:

  1. Protect transport and identity. Require TLS; use a well-managed identity mechanism such as OAuth 2.0/OIDC for user-facing APIs or mTLS for service-to-service calls. Validate token signature, issuer, audience, expiry, and scopes. Keep credentials in a secrets manager, rotate them, and never place them in URLs or logs.
  2. Authorize every operation. Authentication proves who the caller is; authorization checks what they may do. Enforce least privilege and resource-level checks on every request, not just at the UI or gateway. For example, verify that a caller may access the requested cluster or tenant before returning its data.
  3. Validate inputs and constrain work. Validate types, lengths, enums, and allowed fields at the API boundary; reject malformed input rather than trying to repair it. Use parameterized data access, output encoding where relevant, request-size limits, timeouts, and pagination. These reduce injection risks and prevent a valid-looking request from consuming excessive resources.
  4. Limit abuse and make writes safe. Apply per-identity and per-tenant rate limits, concurrency limits, and quotas. Use idempotency keys for retryable write operations so a client retry does not accidentally create duplicate resources. Return generic errors to clients while retaining useful, sanitized diagnostics internally.
  5. Monitor and test the controls. Record structured audit events for sensitive actions, redact secrets and personal data, and alert on suspicious patterns. Test authorization boundaries, token validation, input handling, and rate limits; patch dependencies and rotate keys as part of normal operations.
flowchart LR
    C[Client] -->|TLS request| G[API gateway]
    G -->|Authenticate token or certificate| I[Identity checks]
    I -->|Valid identity| R[Rate limits and request validation]
    R -->|Authorized request| S[Service authorization]
    S -->|Scoped data access| D[Datastore]
    G -->|Audit and security events| M[Monitoring]
    S -->|Sanitized response| C
Diagram
TechnicalMediumNutanixSenior Software EngineerJavaScript Platform & DSA

19. Where should asynchronous code be used in Node.js, and why?

Model answer

  1. Use asynchronous I/O for operations that wait. Node.js runs JavaScript on an event-loop thread, so asynchronous file, network, database, and timer APIs let that thread serve other requests while the operation is pending. This is especially important for API servers and control-plane services handling many concurrent connections.
  2. Prefer non-blocking APIs in request paths. Use promise-based APIs or async/await for operations such as RPCs, storage access, and reading files. await makes the code easier to follow; it does not block the event loop while the promise is pending. Avoid synchronous APIs such as readFileSync in a server request handler because they prevent all other JavaScript callbacks from running until they finish.
  3. Do not assume async makes CPU work non-blocking. A long loop, compression task, or expensive JSON transformation still occupies the event-loop thread, even inside an async function. Break suitable work into bounded chunks, or move CPU-heavy work to worker_threads or a separate service. Native APIs may use the libuv thread pool, but its capacity is finite and should be considered when tuning workloads.
  4. Handle concurrency and failures deliberately. Await dependent operations in order; use Promise.all only for independent work that can safely run concurrently. Bound fan-out, apply timeouts and cancellation where supported, and handle promise rejections so failures do not become unhandled or leave requests hanging.
flowchart TD
    A[Request handler] --> B{Operation type}
    B -->|Network or storage wait| C[Start async I/O]
    C --> D[Event loop serves other work]
    C --> E[Completion callback or promise]
    E --> F[Resume handler]
    B -->|CPU intensive| G[Worker thread or separate service]
Diagram
TechnicalMediumNutanixSoftware EngineerSystem Design (Frontend + Backend)

20. For security purposes, should you use the server side or the client side?

Model answer

Use the server side for security-sensitive decisions; use the client side for presentation and responsiveness.

  • Server-side responsibilities: authenticate users, authorize every operation, validate and normalize input, enforce business rules, protect secrets, and make decisions about pricing, permissions, or payment.
  • Client-side responsibilities: provide form validation and feedback, hide or show UI elements, and display estimates. Client code and requests can be inspected or modified, so none of these checks can be trusted as the security boundary.
  • Example: The browser may show an estimated Nutanix cluster price, but the server must recalculate it from trusted product data before creating a quote or payment session. It must also verify that the user can access the relevant resources.
  • Use TLS, secure session handling, least-privilege authorization, and server-side logging. Never embed API keys or payment secrets in client code.
flowchart LR
    C[Client] -->|Request with user input| S[Server validates and authorizes]
    S -->|Trusted operation| D[Database or payment provider]
    D -->|Result| S
    S -->|Response| C
Diagram

The client can improve usability, but the server must remain authoritative.

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