Sigmoid interview questions & answers

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

CodingEasySigmoidSoftware Engineer

1. Longest Common Prefix (LeetCode)

Model answer

The task

Given a list of strings, return the longest string that is a prefix of every entry. If there is no shared prefix, return an empty string.

Key idea

Compare characters at the same position across all strings, starting from the first string. Stop at the first mismatch or when any string runs out.

Approach

  1. If the list is empty, return an empty string.
  2. Scan each character of the first string from left to right.
  3. For each position, compare that character with the character at the same position in every other string.
  4. If a string is too short or a character differs, return the matching prefix before that position.
  5. If all positions match, return the first string.
from typing import List

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs:
            return ""

        first = strs[0]

        for i, char in enumerate(first):
            for word in strs[1:]:
                if i == len(word) or word[i] != char:
                    return first[:i]

        return first

Complexity:

  • Time: O(S), where S is the total number of characters inspected.
  • Space: O(1) auxiliary space, excluding the returned prefix.

Common follow-ups

  • How would you handle many prefix queries over the same set of strings? Build a trie once, then traverse it to find shared prefixes.
  • Could sorting help? Yes. Sort the strings and compare only the first and last; their common prefix is shared by all strings.
  • What if strings arrive as a stream? Keep a running prefix and shorten it as each new string arrives.
CodingEasySigmoidSoftware Engineer

2. Best Time to Buy and Sell Stock (LeetCode)

Model answer

The task

Given daily stock prices, find the greatest profit possible from one buy followed by one later sale. If no sale would make money, return zero.

Key idea

As we scan the prices, keep the lowest price seen so far. Treat each current price as a possible sale and update the best profit using the difference from that minimum.

Approach

  1. Initialize the minimum price to a value larger than any price and the best profit to zero.
  2. Visit each price in order.
  3. Update the minimum price with the current price.
  4. Check the profit from selling today and update the best profit.
  5. Return the best profit.
class Solution:
    def maxProfit(self, prices: list[int]) -> int:
        min_price = float("inf")
        best_profit = 0

        for price in prices:
            # The current price can be a new best day to buy.
            min_price = min(min_price, price)

            # Or it can be the day to sell after the cheapest earlier buy.
            best_profit = max(best_profit, price - min_price)

        return best_profit

Complexity:

  • Time: O(n), where n is the number of prices; each is processed once.
  • Space: O(1), since only a few variables are stored.

Common follow-ups

  • What if multiple buy-and-sell transactions are allowed? Sum the gains from every adjacent price increase.
  • What if a transaction fee is charged? Track the best holding and non-holding profits, incorporating the fee when selling.
  • What if at most k transactions are allowed? Use dynamic programming over the number of completed transactions and whether a share is currently held.
CodingEasySigmoidSoftware Engineer

3. Move Zeroes (LeetCode)

Model answer

The task

Rearrange an integer array in place so all zeroes come after the nonzero values. Keep the nonzero values in their original relative order.

Key idea

Use a write pointer to mark where the next nonzero value belongs. Scan the array once, swapping each nonzero value into that position; this keeps the nonzero values stable and uses constant extra space.

Approach

  1. Set write to the first available position for a nonzero value.
  2. Scan each index from left to right.
  3. When a nonzero value is found, swap it with the value at write.
  4. Advance write after each nonzero value.
  5. Once the scan ends, all remaining positions contain zeroes.
from typing import List

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        # The next nonzero value belongs at index write.
        write = 0

        for read in range(len(nums)):
            if nums[read] != 0:
                nums[write], nums[read] = nums[read], nums[write]
                write += 1

Complexity:

  • Time: O(n), where n is the array length; each value is examined once.
  • Space: O(1), since rearrangement is done in place.

Common follow-ups

  • What if relative order does not matter? Partitioning zeroes and nonzeroes can be done with two pointers, potentially with fewer assignments.
  • Can you reduce unnecessary writes? Swap only when read != write; this avoids self-swaps.
  • What if the input is a linked list? Relink nonzero nodes in their original order, then append the zero-valued nodes.
CodingMediumSigmoidSoftware Engineer

4. 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.
CodingMediumSigmoidSoftware Engineer

5. Rotting Oranges (LeetCode)

Model answer

The task

Given a grid of empty cells, fresh oranges, and rotten oranges, find the minimum number of minutes until no fresh oranges remain. Each minute, a rotten orange makes any fresh orange directly above, below, left, or right of it rotten; return -1 if some fresh oranges can never be reached.

Key idea

Use multi-source breadth-first search: all initially rotten oranges spread at the same time, so put them all in the queue at the start. Process the queue one minute at a time, counting newly rotten oranges to detect whether any fresh ones remain unreachable.

Approach

  1. Count the fresh oranges and enqueue every initially rotten orange.
  2. If there are no fresh oranges, return 0.
  3. For each BFS layer, rot adjacent fresh oranges, decrement the fresh count, and enqueue them.
  4. Count each processed layer as one minute.
  5. Return the minutes if all fresh oranges rotted; otherwise return -1.
from collections import deque
from typing import List

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

        # Gather all initial sources and count oranges that still need to rot.
        for r in range(rows):
            for c in range(cols):
                if grid[r][c] == 2:
                    queue.append((r, c))
                elif grid[r][c] == 1:
                    fresh += 1

        if fresh == 0:
            return 0

        minutes = 0
        directions = ((1, 0), (-1, 0), (0, 1), (0, -1))

        while queue and fresh > 0:
            # Process exactly the oranges rotten before this minute began.
            for _ in range(len(queue)):
                r, c = queue.popleft()

                for dr, dc in directions:
                    nr, nc = r + dr, c + dc
                    if (
                        0 <= nr < rows
                        and 0 <= nc < cols
                        and grid[nr][nc] == 1
                    ):
                        grid[nr][nc] = 2
                        fresh -= 1
                        queue.append((nr, nc))

            minutes += 1

        return minutes if fresh == 0 else -1

Complexity:

  • Time: O(rows × cols), since each cell is visited at most once.
  • Space: O(rows × cols) for the BFS queue in the worst case.

Common follow-ups

  • What if diagonal neighbors also spread rot? Add the four diagonal directions to the neighbor list.
  • Can the original grid be preserved? Copy it first, or track visited cells separately.
  • How would you return which oranges rot each minute? Store each BFS layer’s cells or record a rot-time value per cell.
CodingMediumSigmoidSoftware Engineer

6. Binary Tree Zigzag Level Order Traversal (LeetCode)

Model answer

The task

Return the values of a binary tree grouped by depth, alternating the direction in which each level is read: left-to-right, then right-to-left.

Key idea

Use breadth-first search so nodes are processed one level at a time. Keep the queue order unchanged, but collect each level in the appropriate direction.

Approach

  1. Return an empty list if the tree is empty.
  2. Initialize a queue with the root and mark the first level as left-to-right.
  3. For each level, process exactly the number of nodes currently in the queue.
  4. Add each node’s children to the queue in normal left-to-right order.
  5. Collect level values from the left or right end as appropriate, then switch direction.
from collections import deque

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

        result = []
        queue = deque([root])
        left_to_right = True

        while queue:
            level_values = deque()

            # The queue length at the start gives this level's node count.
            for _ in range(len(queue)):
                node = queue.popleft()

                if left_to_right:
                    level_values.append(node.val)
                else:
                    level_values.appendleft(node.val)

                # Keep the queue in standard breadth-first order.
                if node.left is not None:
                    queue.append(node.left)
                if node.right is not None:
                    queue.append(node.right)

            result.append(list(level_values))
            left_to_right = not left_to_right

        return result

Complexity:

  • Time: O(n), where n is the number of nodes; each node is processed once.
  • Space: O(n), including the returned levels; the queue holds at most one level’s nodes.

Common follow-ups

  • Can you implement this recursively? Yes; group nodes by depth and place each value at the appropriate end for that depth.
  • What if the traversal should start right-to-left? Initialize the direction flag to False.
  • How can you reduce per-level collection overhead? Use a list and place values at calculated indices instead of using a deque.
  • What happens for an empty tree or a single-node tree? The empty tree returns an empty list; a single node returns one level.
CodingMediumSigmoidSoftware Engineer

7. Merge Intervals (LeetCode)

Model answer

The task

Given a collection of intervals, combine every pair that overlaps and return the resulting non-overlapping intervals. The result should be ordered by starting point.

Key idea

Sort intervals by their start. Then scan once, keeping the most recently merged interval; each next interval either extends it or starts a new one.

Approach

  1. Sort the intervals by their start value.
  2. Initialize the result with the first interval, if any.
  3. For each remaining interval, compare its start with the end of the last result interval.
  4. If they overlap, update that end to the larger of the two ends.
  5. Otherwise, append the interval as a new result.
from typing import List

class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        if not intervals:
            return []

        intervals.sort(key=lambda interval: interval[0])
        merged = [intervals[0]]

        for start, end in intervals[1:]:
            # The intervals overlap, so extend the last merged interval.
            if start <= merged[-1][1]:
                merged[-1][1] = max(merged[-1][1], end)
            else:
                # No overlap: this interval begins a new merged range.
                merged.append([start, end])

        return merged

Complexity: Time: O(n log n), dominated by sorting n intervals.

Complexity: Space: O(n) for the merged result; sorting may also use up to O(n) space.

Common follow-ups

  • What if intervals that only touch at an endpoint should remain separate? Use start < merged[-1][1] as the overlap test.
  • How would you merge intervals as they arrive in sorted order? Skip sorting and apply the same scan, processing each interval once.
  • What if intervals are inserted one at a time into an already merged collection? Use binary search to find the insertion point, then merge neighboring overlaps.
CodingMediumSigmoidSoftware Engineer

8. Next Greater Element II (LeetCode)

Model answer

The task

For each position in a circular array, find the first value encountered moving forward that is strictly greater than the value at that position. Return -1 if no such value exists.

Key idea

Use a decreasing monotonic stack of unresolved indices. Scan the array twice to account for wrapping, but add indices to the stack only during the first scan so each position is processed once as a candidate.

Approach

  1. Initialize every answer to -1 and create an empty stack of indices.
  2. Scan positions from 0 to 2 * n - 1, using modulo n to read the circular array.
  3. While the current value is greater than the value at the stack’s top index, record it as that index’s answer and pop the index.
  4. Push the current index only during the first scan.
class Solution:
    def nextGreaterElements(self, nums: list[int]) -> list[int]:
        n = len(nums)
        answer = [-1] * n
        stack = []  # Indices whose next greater value is not yet found.

        for i in range(2 * n):
            index = i % n

            # Resolve earlier indices for which this value is the next greater.
            while stack and nums[stack[-1]] < nums[index]:
                answer[stack.pop()] = nums[index]

            # Add each index only once, during the first pass.
            if i < n:
                stack.append(index)

        return answer

Complexity:

  • Time: O(n), since each index is pushed and popped at most once.
  • Space: O(n), for the answer and stack.

Common follow-ups

  • What changes for a non-circular array? Scan only once, without modulo or the second pass.
  • How would you handle “next greater or equal”? Change the comparison to <=.
  • Can the result be computed in place? It can be done with extra bookkeeping, but a separate answer array is clearer and avoids overwriting values needed for comparisons.
CodingMediumSigmoidSoftware Engineer

9. Boats to Save People (LeetCode)

Model answer

The task

Given each person’s weight and a boat weight limit, find the fewest boats needed. Each boat can carry at most two people.

Key idea

Sort the weights. Pair the heaviest person with the lightest person if they fit together; otherwise, send the heaviest alone. This greedy choice is optimal because no one can pair with the heaviest if even the lightest person cannot.

Approach

  1. Sort the weights in ascending order.
  2. Track the lightest and heaviest people with two pointers.
  3. Use one boat for the heaviest person.
  4. If the lightest person fits with them, move the light pointer too.
  5. Move the heavy pointer and repeat until everyone is assigned.
class Solution:
    def numRescueBoats(self, people: list[int], limit: int) -> int:
        people.sort()

        light = 0
        heavy = len(people) - 1
        boats = 0

        while light <= heavy:
            # The heaviest person always takes a boat.
            # Pair them with the lightest only if they fit.
            if people[light] + people[heavy] <= limit:
                light += 1

            heavy -= 1
            boats += 1

        return boats

Complexity:

  • Time: O(n log n), due to sorting; the two-pointer scan is O(n).
  • Space: O(n) for sorting’s auxiliary storage.

Common follow-ups

  • What if the weights are already sorted? Skip sorting; the scan takes O(n) time.
  • How would you return the people assigned to each boat? Record each heaviest person and any lightest person paired with them.
  • What if a boat can carry more than two people? The two-pointer greedy rule no longer directly applies; the problem depends on the capacity and may become substantially harder.
  • What if someone weighs more than the limit? They cannot be transported, so first define how the result should represent an impossible assignment.
CodingMediumSigmoidSoftware Engineer

10. Min Stack (LeetCode)

Model answer

The task

Design a stack that supports pushing and removing values, inspecting the top value, and retrieving the minimum value currently stored. Each operation should take constant time.

Key idea

Alongside each value, store the minimum seen at that point in the stack. The top entry then contains enough information to answer a minimum query without scanning the stack.

Approach

  1. Keep a list of (value, minimum_so_far) pairs.
  2. On push, compare the new value with the current minimum and store the smaller one.
  3. On pop, remove the top pair.
  4. Return the value or minimum from the top pair for top and getMin.
class MinStack:
    def __init__(self):
        # Each entry is (value, minimum among entries up to this one).
        self.stack = []

    def push(self, val: int) -> None:
        current_min = val
        if self.stack:
            current_min = min(val, self.stack[-1][1])
        self.stack.append((val, current_min))

    def pop(self) -> None:
        self.stack.pop()

    def top(self) -> int:
        return self.stack[-1][0]

    def getMin(self) -> int:
        return self.stack[-1][1]

Complexity:

  • Time: O(1) per operation; each method accesses or updates only the top entry.
  • Space: O(n); each stack entry stores its value and the minimum so far.

Common follow-ups

  • Can you reduce the extra space? Store only values and keep a second stack of minimums, pushing a minimum when it is no greater than the current one.
  • How should duplicate minimums be handled? Track duplicates in the minimum stack too, so popping one leaves the other available.
  • What if the stack can be empty when queried? Define the API’s empty-stack behavior, such as raising an exception or returning a sentinel.
CodingMediumSigmoidSoftware Engineer

11. Group Anagrams (LeetCode)

Model answer

The task

Partition the input strings into groups so that strings in the same group contain the same characters with the same frequencies. The order of the groups does not matter.

Key idea

Sort the characters of each string to create a canonical key. Anagrams produce the same key, so a hash table can collect them together.

Approach

  1. Create a mapping from canonical keys to lists of original strings.
  2. For each string, sort its characters and use the result as its key.
  3. Append the string to the list for that key.
  4. Return all grouped lists.
from collections import defaultdict
from typing import List

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        groups = defaultdict(list)

        for word in strs:
            # Anagrams have identical sorted-character representations.
            key = "".join(sorted(word))
            groups[key].append(word)

        return list(groups.values())

Complexity:

  • Time: O(n · k log k), where n is the number of strings and k is the maximum string length.
  • Space: O(n · k) to store the grouped strings and their keys.

Common follow-ups

  • Can this be faster for a fixed alphabet? Use a character-frequency tuple as the key, computing it in O(k) per string.
  • Does this work with uppercase letters or Unicode? Yes; sorting characters works for any Python strings.
  • Can groups be returned in a deterministic order? Sort the groups, or their keys, before returning them.
  • What if memory is limited? Consider processing input in batches or grouping externally by canonical key.
CodingMediumSigmoidSoftware Engineer

12. Longest Substring Without Repeating Characters (LeetCode)

Model answer

The task

Find the length of the longest contiguous section of a string in which every character appears at most once.

Key idea

Maintain a sliding window with no repeated characters. When a character repeats within the window, move the left edge just past its previous occurrence.

Approach

  1. Track each character’s most recent index in a dictionary.
  2. Keep left as the window’s starting index and best as its longest length so far.
  3. For each character, move left forward if its previous occurrence is inside the current window.
  4. Record the character’s current index and update best using the window length.
class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        last_seen = {}
        left = 0
        best = 0

        for right, char in enumerate(s):
            # Skip past a repeated character if it is in the current window.
            if char in last_seen and last_seen[char] >= left:
                left = last_seen[char] + 1

            last_seen[char] = right
            best = max(best, right - left + 1)

        return best

Complexity:

  • Time: O(n), because each character is processed once.
  • Space: O(k), where k is the number of distinct characters encountered.

Common follow-ups

  • Return the substring itself: store the best window’s start and end indices when updating best.
  • Handle a stream of characters: keep the same window state and process each arriving character incrementally.
  • Use a fixed-size character set: replace the dictionary with an array of last-seen indices.
CodingMediumSigmoidSoftware Engineer

13. Best Time to Buy and Sell Stock II (LeetCode)

Model answer

The task

Given a sequence of daily stock prices, compute the greatest profit possible when you may make multiple buy-and-sell transactions. You must sell before buying again and cannot hold more than one share at a time.

Key idea

Every upward move between consecutive days can contribute to the total profit. Summing all positive day-to-day increases captures the profit from each rising stretch without needing to choose its endpoints explicitly.

Approach

  1. Start with zero profit.
  2. Walk through each pair of consecutive prices.
  3. If the price rises, add that increase to the profit.
  4. Return the accumulated amount.
from typing import List

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        profit = 0

        # Collect each positive one-day price increase.
        for previous, current in zip(prices, prices[1:]):
            if current > previous:
                profit += current - previous

        return profit

Complexity:

  • Time: O(n), where n is the number of prices; each price is examined once.
  • Space: O(1), excluding the temporary iterator used to traverse the prices.

Common follow-ups

  • What if each sale has a transaction fee? Track holding and not-holding states, subtracting the fee when selling.
  • What if there is a cooldown after selling? Use dynamic programming states that track whether buying is currently allowed.
  • What if only k transactions are allowed? Use dynamic programming over the number of completed transactions and holding status.
CodingHardSigmoidSoftware Engineer

14. 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.
CodingHardSigmoidSoftware Engineer

15. Reverse Nodes in k-Group (LeetCode)

Model answer

The task

Rearrange a singly linked list by reversing each consecutive block of k nodes. If the final block has fewer than k nodes, leave it as it is.

Key idea

Before reversing a block, check that it contains all k nodes. Use the node after the block as the stopping point for pointer reversal, then connect the reversed block back to the list.

Approach

  1. Add a dummy node before the head to simplify reconnecting the first block.
  2. From the node before each block, locate its kth node. If none exists, stop.
  3. Save the node after the block, then reverse pointers up to that node.
  4. Connect the previous block to the reversed block and advance to its new tail.
  5. Return the node after the dummy.
class Solution:
    def reverseKGroup(self, head, k):
        # The dummy makes it easy to update the list's first node.
        dummy = ListNode(0, head)
        group_prev = dummy

        while True:
            # Find the last node in the next complete group.
            kth = group_prev
            for _ in range(k):
                kth = kth.next
                if kth is None:
                    return dummy.next

            group_next = kth.next

            # Reverse this group, stopping just before group_next.
            prev = group_next
            curr = group_prev.next
            while curr is not group_next:
                next_node = curr.next
                curr.next = prev
                prev = curr
                curr = next_node

            # The old first node is now the group's tail.
            old_first = group_prev.next
            group_prev.next = kth
            group_prev = old_first

Complexity:

  • Time: O(n), as each node is visited a constant number of times.
  • Space: O(1), using only a fixed number of pointers.

Common follow-ups

  • How would you implement this recursively? Reverse one group, then recursively process the remainder, taking care not to reverse an incomplete final group.
  • What happens when k is 1? Each group contains one node, so the list stays unchanged.
  • Can you reverse only complete groups? Yes; the initial k-node check ensures incomplete groups are untouched.

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