Siemens interview questions & answers

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

CodingEasySiemensSoftware Engineer

1. 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.
CodingEasySiemensSoftware Engineer

2. Remove Duplicates from Sorted Array (LeetCode)

Model answer

The task

Given a sorted list of integers, modify it in place so each distinct value appears once in the front. Return the length of that unique prefix.

Key idea

Because the values are sorted, duplicates are adjacent. Keep a read pointer to scan the list and a write pointer for the next position where a new value belongs.

Approach

  1. If the list is empty, return 0.
  2. Start the write pointer at 1, since the first value is already unique.
  3. Scan from left to right.
  4. When the current value differs from the last value written, copy it to the write position and advance the pointer.
  5. Return the write pointer as the unique-prefix length.
from typing import List

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        if not nums:
            return 0

        write = 1

        # Copy each newly encountered value into the unique prefix.
        for read in range(1, len(nums)):
            if nums[read] != nums[write - 1]:
                nums[write] = nums[read]
                write += 1

        return write

Complexity:

  • Time: O(n), where n is the length of the list.
  • Space: O(1), since the list is modified in place using only a fixed number of variables.

Common follow-ups

  • What if the list is not sorted? Use a set to track seen values while compacting unique values in their original order.
  • What if each value may appear at most twice? Write a value when fewer than two values have been written, or when it differs from the value two positions back.
  • What if the list is very large and cannot fit in memory? Process sorted chunks while carrying the last value across chunk boundaries.
CodingEasySiemensSoftware Engineer

3. Merge Two Sorted Lists (LeetCode)

Model answer

The task

Given the heads of two sorted singly linked lists, combine their nodes into one sorted list. Return the head of the merged list.

Key idea

At each step, append the smaller of the two current nodes, then advance that list. A dummy node simplifies handling the merged list’s head.

Approach

  1. Create a dummy node and set a pointer to it.
  2. While both lists have nodes, compare their values.
  3. Link the smaller node after the pointer and advance its source list.
  4. Advance the pointer.
  5. Link any remaining nodes and return the node after the dummy.
# LeetCode provides the ListNode class.
class Solution:
    def mergeTwoLists(self, list1, list2):
        dummy = ListNode(0)
        tail = dummy

        # Repeatedly attach the smaller current node.
        while list1 and list2:
            if list1.val <= list2.val:
                tail.next = list1
                list1 = list1.next
            else:
                tail.next = list2
                list2 = list2.next

            tail = tail.next

        # At most one list remains; it is already sorted.
        tail.next = list1 if list1 else list2
        return dummy.next

Complexity:

  • Time: O(m + n), where m and n are the lengths of the lists.
  • Space: O(1) extra space; the existing nodes are relinked.

Common follow-ups

  • How would you implement this recursively? Choose the smaller head and recursively merge the rest; this uses O(m + n) call-stack space.
  • What if the lists are sorted in descending order? Adjust the comparison or reverse the merged result, depending on the desired output order.
  • What if one list is empty? The remaining list is returned directly.
CodingEasySiemensSoftware Engineer

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

5. Reverse String (LeetCode)

Model answer

The task

Reverse the sequence of characters in place. The method should modify the given list rather than create and return a reversed copy.

Key idea

Use two pointers, one at each end of the list. Swap their characters, then move both pointers inward until they meet or cross.

Approach

  1. Set left to the first index and right to the last.
  2. While left < right, swap the characters at those indices.
  3. Advance left and decrease right.
  4. Stop once the pointers meet or cross; the list has been reversed.
from typing import List

class Solution:
    def reverseString(self, s: List[str]) -> None:
        """Reverse s in place."""
        left = 0
        right = len(s) - 1

        while left < right:
            s[left], s[right] = s[right], s[left]
            left += 1
            right -= 1

Complexity:

  • Time: O(n), where n is the number of characters; each character is involved in at most one swap.
  • Space: O(1), since the reversal uses only two index variables and swaps in place.

Common follow-ups

  • Reverse only a subrange: Initialize the pointers to the subrange’s endpoints and use the same swap loop.
  • Reverse an immutable string: Convert it to a mutable character list, reverse that list, then join it into a new string.
  • Handle Unicode grapheme clusters: Reverse grapheme clusters rather than code points, since a visible character can consist of multiple code points.
CodingMediumSiemensSoftware 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.
CodingMediumSiemensSoftware Engineer

7. LRU Cache (LeetCode)

Model answer

The task

Design a cache with a fixed capacity that supports retrieving and inserting key-value pairs. When an insertion exceeds capacity, evict the item that has gone unused for the longest time.

Key idea

Use a hash map for direct key lookup and a doubly linked list to track recency. Keep the most recently used item at the front; the least recently used item is at the back.

Approach

  1. Create a map from keys to their linked-list nodes.
  2. Use dummy head and tail nodes so items can be added or removed without special cases at the ends.
  3. On a successful get, move the node to the front and return its value; return -1 if the key is absent.
  4. On put, update and promote an existing node, or add a new node at the front.
  5. If the cache is over capacity, remove the node just before the tail and delete its key from the map.
class _Node:
    def __init__(self, key: int = 0, value: int = 0):
        self.key = key
        self.value = value
        self.prev = None
        self.next = None

class LRUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        self.nodes = {}

        # Items are stored between these sentinels.
        self.head = _Node()
        self.tail = _Node()
        self.head.next = self.tail
        self.tail.prev = self.head

    def _remove(self, node: _Node) -> None:
        node.prev.next = node.next
        node.next.prev = node.prev

    def _add_to_front(self, node: _Node) -> None:
        node.prev = self.head
        node.next = self.head.next
        self.head.next.prev = node
        self.head.next = node

    def _make_most_recent(self, node: _Node) -> None:
        self._remove(node)
        self._add_to_front(node)

    def get(self, key: int) -> int:
        node = self.nodes.get(key)
        if node is None:
            return -1

        self._make_most_recent(node)
        return node.value

    def put(self, key: int, value: int) -> None:
        node = self.nodes.get(key)

        if node is not None:
            node.value = value
            self._make_most_recent(node)
            return

        node = _Node(key, value)
        self.nodes[key] = node
        self._add_to_front(node)

        if len(self.nodes) > self.capacity:
            least_recent = self.tail.prev
            self._remove(least_recent)
            del self.nodes[least_recent.key]

Complexity:

  • Time: O(1) for get and put; map and list operations take constant time.
  • Space: O(capacity); the map and list store at most the cache’s capacity of entries.

Common follow-ups

  • How would you make the cache thread-safe? Protect operations with a lock.
  • What if entries expire after a time-to-live? Track expiration times and remove expired entries during access or with a cleanup mechanism.
  • How would you support eviction by frequency instead of recency? Track access counts and organize entries by frequency.
CodingMediumSiemensSoftware 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.
CodingMediumSiemensSoftware Engineer

9. Minimized Maximum of Products Distributed to Any Store (LeetCode)

Model answer

The task

Distribute each product type among stores so that a store receives products of only one type. Minimize the largest number of products assigned to any store.

Key idea

For a proposed maximum of limit products per store, a type with quantity q needs ceil(q / limit) stores. This gives a monotonic feasibility check: if a limit works, any larger limit works, so binary search finds the smallest feasible one.

Approach

  1. Search between 1 and the largest product quantity.
  2. For each midpoint, count the stores needed across all product types.
  3. If the count is at most n, try a smaller limit.
  4. Otherwise, increase the limit.
  5. Return the smallest feasible limit.
from typing import List

class Solution:
    def minimizedMaximum(self, n: int, quantities: List[int]) -> int:
        low = 1
        high = max(quantities)

        while low < high:
            limit = (low + high) // 2

            # Count stores required if each gets at most `limit` products.
            stores_needed = sum(
                (quantity + limit - 1) // limit
                for quantity in quantities
            )

            if stores_needed <= n:
                high = limit
            else:
                low = limit + 1

        return low

Complexity:

  • Time: O(m log M), where m is the number of product types and M is the largest quantity.
  • Space: O(1) extra space.

Common follow-ups

  • What if each store has a different capacity? The simple monotonic check may still apply, but stores must be matched to product types; feasibility can require a more involved allocation strategy.
  • What if the number of stores is extremely large? The algorithm already depends logarithmically on the maximum quantity, not on the number of stores.
  • Can the search bounds be tightened? The lower bound can be at least ceil(sum(quantities) / n), since that is the average load per store.
CodingMediumSiemensSoftware Engineer

10. Find Peak Element (LeetCode)

Model answer

The task

Given an array whose neighboring values are distinct, return the index of any element that is greater than its neighbors. Treat positions outside the array as having value negative infinity.

Key idea

Compare the middle element with the one immediately to its right. If the middle is larger, a peak exists at or to its left; otherwise, a peak exists to its right. This lets binary search discard half the search range each iteration.

Approach

  1. Set left and right to the array’s endpoints.
  2. While the range has more than one element, inspect its midpoint and the next element.
  3. If the midpoint is larger, keep the left half, including the midpoint.
  4. Otherwise, keep the right half, starting after the midpoint.
  5. Return the remaining index.
class Solution:
    def findPeakElement(self, nums: list[int]) -> int:
        left, right = 0, len(nums) - 1

        while left < right:
            mid = (left + right) // 2

            # A descending step means a peak is at mid or somewhere to its left.
            if nums[mid] > nums[mid + 1]:
                right = mid
            else:
                # An ascending step means a peak exists to the right of mid.
                left = mid + 1

        return left

Complexity:

  • Time: O(log n), since the search range is halved each iteration.
  • Space: O(1), since only a fixed number of variables are used.

Common follow-ups

  • How would you return all peak indices? Scan the array and compare each value with its neighbors, using negative infinity at the boundaries.
  • What if adjacent values may be equal? The binary-search reasoning may no longer identify a peak in logarithmic time; handle plateaus explicitly or scan in O(n).
  • How would you find a peak in a two-dimensional grid? Use binary search across columns, finding a column maximum each step and comparing it with its horizontal neighbors.
CodingMediumSiemensSoftware Engineer

11. Zigzag Conversion (LeetCode)

Model answer

The task

Rearrange a string by writing its characters across rows in a down-and-diagonal zigzag pattern, then return the rows concatenated from top to bottom.

Key idea

Simulate the movement through the rows as characters are read. Reverse direction at the top and bottom rows; each character is appended to its current row exactly once.

Approach

  1. If there is only one row, or the string is shorter than the row count, return it unchanged.
  2. Create one character buffer per row.
  3. Track the current row and whether movement is downward or upward.
  4. Append each character to its row, changing direction at either end.
  5. Join the row buffers in order.
class Solution:
    def convert(self, s: str, numRows: int) -> str:
        # With one row, the zigzag has no turns.
        if numRows == 1 or numRows >= len(s):
            return s

        rows = [[] for _ in range(numRows)]
        current_row = 0
        direction = 1  # 1 means moving down; -1 means moving up.

        for char in s:
            rows[current_row].append(char)

            # Turn around when reaching either end of the rows.
            if current_row == 0:
                direction = 1
            elif current_row == numRows - 1:
                direction = -1

            current_row += direction

        return "".join("".join(row) for row in rows)

Complexity:

  • Time: O(n), where n is the length of the string; each character is processed once.
  • Space: O(n), for the row buffers and the returned string.

Common follow-ups

  • Can you compute the row of each character directly? Yes; use the repeating zigzag cycle of 2 * numRows - 2 positions.
  • What if the input is streamed? Keep the row buffers and movement state, and process each incoming character in order.
  • What edge cases matter? A single row, an empty string, and a row count at least as large as the string length.
CodingMediumSiemensSoftware Engineer

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

13. Minimum Add to Make Parentheses Valid (LeetCode)

Model answer

The task

Given a string containing opening and closing parentheses, find the fewest parentheses that must be inserted to make the string balanced.

Key idea

Scan from left to right, greedily matching each closing parenthesis with an unmatched opening one when possible. Count closing parentheses that have no match, then add those to the unmatched openings left at the end.

Approach

  1. Initialize counters for unmatched openings and unmatched closings.
  2. For each opening parenthesis, increment the opening counter.
  3. For each closing parenthesis, match it by decrementing the opening counter if possible.
  4. If no opening is available, increment the closing counter.
  5. Return the sum of the two counters.
class Solution:
    def minAddToMakeValid(self, s: str) -> int:
        unmatched_open = 0
        unmatched_close = 0

        for char in s:
            if char == "(":
                unmatched_open += 1
            elif unmatched_open > 0:
                # Match this close with an earlier unmatched open.
                unmatched_open -= 1
            else:
                # This close has no opening parenthesis to match it.
                unmatched_close += 1

        return unmatched_open + unmatched_close

Complexity:

  • Time: O(n), where n is the length of the string; each character is processed once.
  • Space: O(1), since only two counters are used.

Common follow-ups

  • How would you return one valid string after inserting the minimum number? Insert an opening parenthesis before each unmatched close, then append a closing parenthesis for each unmatched opening.
  • How would you handle multiple bracket types? Use a stack to match bracket types and count unmatched brackets.
  • Can this be processed as characters arrive in a stream? Yes; maintain the same two counters and update them for each character.
CodingMediumSiemensSoftware Engineer

14. Clone Graph (LeetCode)

Model answer

The task

Given a reference to a node in an undirected graph, return a deep copy of the graph. The copy must preserve each node’s value and connections while using entirely new node objects.

Key idea

Keep a map from each original node to its clone. When visiting a node, create and record its clone before exploring its neighbors; this both prevents revisiting cycles and preserves shared connections.

Approach

  1. If the input node is None, return None.
  2. Start a depth-first search from the input node.
  3. For each node, return its existing clone if it has already been copied.
  4. Otherwise, create and record a clone, then recursively copy each neighbor.
  5. Return the clone of the starting node.
# LeetCode provides the Node class.
class Solution:
    def cloneGraph(self, node):
        if node is None:
            return None

        clones = {}

        def copy(current):
            if current in clones:
                return clones[current]

            # Record the clone before traversing neighbors to handle cycles.
            cloned = Node(current.val)
            clones[current] = cloned

            for neighbor in current.neighbors:
                cloned.neighbors.append(copy(neighbor))

            return cloned

        return copy(node)

Complexity:

  • Time: O(V + E), visiting each reachable node and edge once.
  • Space: O(V), for the clone map and recursion stack.

Common follow-ups

  • What if the graph is disconnected? Run the traversal from every unvisited node.
  • Can this be done iteratively? Yes; use a queue and the same original-to-clone map.
  • What if node values are not unique? Use node objects as map keys, not their values.
  • How can you verify the result is a deep copy? Check that corresponding nodes differ by identity while their values and adjacency structure match.
CodingMediumSiemensSoftware Engineer

15. Single Number III (LeetCode)

Model answer

The task

Given an integer array where every value occurs twice except for two values that occur once, find those two values. Return them in either order.

Key idea

XORing all values cancels every pair, leaving the XOR of the two unique values. A set bit in that result marks a bit position where the unique values differ, so it can divide the array into two groups.

Approach

  1. XOR every array value to get the XOR of the two single-occurrence values.
  2. Find one set bit in that XOR using xor_all & -xor_all.
  3. XOR values with that bit set into one result, and values without it into the other.
  4. Each pair contributes to only one group and cancels; the two unique values land in separate groups.
  5. Return the two group results.
from typing import List

class Solution:
    def singleNumber(self, nums: List[int]) -> List[int]:
        # XOR cancels values that occur in pairs.
        xor_all = 0
        for value in nums:
            xor_all ^= value

        # Isolate a bit where the two unique values differ.
        distinguishing_bit = xor_all & -xor_all

        first = 0
        second = 0

        # Split values by that bit; duplicates cancel within each group.
        for value in nums:
            if value & distinguishing_bit:
                first ^= value
            else:
                second ^= value

        return [first, second]

Complexity:

  • Time: O(n), with two passes over the array.
  • Space: O(1), using only a fixed number of variables.

Common follow-ups

  • What if there is only one unique value? XORing the array gives that value directly.
  • What if values appear three times except one? Use bit counts modulo three instead of pair cancellation.
  • Can the result order be guaranteed? Yes; sort the two returned values if a specific order is needed.
CodingMediumSiemensSoftware Engineer

16. Maximum Product Subarray (LeetCode)

Model answer

The task

Given an integer array, find the largest product of any nonempty contiguous subarray.

Key idea

A negative number can turn a very small product into the largest one, so track both the maximum and minimum product ending at the current position. Update both for each number, then keep the best maximum seen overall.

Approach

  1. Initialize the ending maximum, ending minimum, and overall answer to the first number.
  2. For each remaining number, save the old ending maximum.
  3. Update the ending maximum and minimum from the number alone or from multiplying it by either saved product.
  4. Update the overall answer with the new ending maximum.
class Solution:
    def maxProduct(self, nums: list[int]) -> int:
        # The best subarray must include at least one element.
        ending_max = ending_min = answer = nums[0]

        for value in nums[1:]:
            previous_max = ending_max

            # Multiplication by a negative can swap the roles of max and min.
            ending_max = max(value, value * previous_max, value * ending_min)
            ending_min = min(value, value * previous_max, value * ending_min)

            answer = max(answer, ending_max)

        return answer

Complexity:

  • Time: O(n), processing each array element once.
  • Space: O(1), storing only a fixed number of values.

Common follow-ups

  • How would you return the subarray’s indices too? Track the start index associated with each ending maximum and save its range whenever the overall best improves.
  • What changes if the array may be empty? Define the desired empty-input result, then check for emptiness before accessing the first element.
  • How would you handle floating-point values? Use the same recurrence, while accounting for precision and the desired comparison tolerance.
CodingMediumSiemensSoftware Engineer

17. Rotate Array (LeetCode)

Model answer

The task

Rotate an integer array to the right by k positions, modifying the array in place. Rotations that exceed the array length should have the same effect as their remainder modulo the length.

Key idea

Reduce k modulo the array length, then reverse the whole array and reverse each of the two resulting sections. The reversals put the last k elements first while preserving the order within both sections.

Approach

  1. Return immediately for an empty array.
  2. Reduce k modulo the array length.
  3. Reverse the entire array.
  4. Reverse the first k elements.
  5. Reverse the remaining elements.
from typing import List

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """Rotate nums right by k positions in place."""
        n = len(nums)
        if n == 0:
            return

        k %= n

        def reverse(left: int, right: int) -> None:
            while left < right:
                nums[left], nums[right] = nums[right], nums[left]
                left += 1
                right -= 1

        reverse(0, n - 1)
        reverse(0, k - 1)
        reverse(k, n - 1)

Complexity:

  • Time: O(n), since each element is reversed at most twice.
  • Space: O(1), using only a few indices and swaps.

Common follow-ups

  • What if k is negative? Define the direction convention, then normalize it with k %= n.
  • Can this be done with extra space? Copy the array, then assign each value to its rotated destination.
  • What if the array is empty? Return before taking a modulo or accessing elements.
  • How can rotation be done by cycles? Move each value directly to its destination, tracking visited positions or using the cycle structure induced by k.
CodingMediumSiemensSoftware Engineer

18. 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.
CodingMediumSiemensSoftware Engineer

19. Angle Between Hands of a Clock (LeetCode)

Model answer

The task

Find the smaller angle, in degrees, between the hour and minute hands at a given hour and minute.

Key idea

The minute hand moves 6 degrees per minute. The hour hand moves 30 degrees per hour and also advances 0.5 degrees per minute, so account for the minutes when computing its position.

Approach

  1. Compute the minute hand’s angle from 12 o’clock.
  2. Compute the hour hand’s angle, including its movement during the current minute.
  3. Take the absolute difference between the two angles.
  4. Return the smaller of that difference and its complement to 360 degrees.
class Solution:
    def angleClock(self, hour: int, minutes: int) -> float:
        # The minute hand completes 360 degrees in 60 minutes.
        minute_angle = 6 * minutes

        # The hour hand moves 30 degrees per hour and 0.5 per minute.
        hour_angle = 30 * hour + 0.5 * minutes

        difference = abs(hour_angle - minute_angle)
        return min(difference, 360 - difference)

Complexity:

  • Time: O(1), using a fixed number of arithmetic operations.
  • Space: O(1), using a fixed number of variables.

Common follow-ups

  • How would you include seconds? Add seconds / 120 degrees to the hour hand and seconds * 0.1 degrees to the minute hand.
  • How would you return the larger angle instead? Return 360 - min(difference, 360 - difference).
  • How would you handle times beyond one day? Reduce the hour modulo 12 and the minutes modulo 60 before computing the angles.
CodingHardSiemensSoftware Engineer

20. The Skyline Problem (LeetCode)

Model answer

The task

Given rectangular buildings described by their horizontal span and height, return the corners where the outline of their union changes height. Each corner records a horizontal position and the new outline height.

Key idea

Sweep from left to right across every building start and end. Keep active buildings in a max-heap, using their right edges to lazily discard buildings that have ended; the heap’s tallest remaining building determines the outline.

Approach

  1. Group building starts by horizontal position and collect all start and end positions.
  2. Sweep the sorted positions from left to right.
  3. Remove expired buildings from the top of the heap, then add buildings that start here.
  4. The heap’s tallest active height is the current outline height.
  5. Append a corner only when that height differs from the previous one.
from collections import defaultdict
from typing import List
import heapq

class Solution:
    def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
        starts = defaultdict(list)
        positions = set()

        for left, right, height in buildings:
            starts[left].append((height, right))
            positions.add(left)
            positions.add(right)

        # Store (-height, right edge); the negative height makes this a max-heap.
        # The ground level is a permanent height-0 entry.
        heap = [(0, float("inf"))]
        skyline = []
        previous_height = 0

        for x in sorted(positions):
            # Expired buildings can be discarded when they reach the heap top.
            while heap[0][1] <= x:
                heapq.heappop(heap)

            for height, right in starts[x]:
                heapq.heappush(heap, (-height, right))

            # A building starting here has right > x, but keep cleanup explicit.
            while heap[0][1] <= x:
                heapq.heappop(heap)

            current_height = -heap[0][0]
            if current_height != previous_height:
                skyline.append([x, current_height])
                previous_height = current_height

        return skyline

Complexity:

  • Time: O(n log n), for sorting positions and heap operations across n buildings.
  • Space: O(n), for positions, grouped starts, and heap entries.

Common follow-ups

  • How would you solve it with divide and conquer? Recursively compute each half’s skyline and merge the two outlines.
  • Why is lazy deletion safe? An expired building matters only if it reaches the heap top; buried expired entries cannot affect the current maximum.
  • How do you handle multiple buildings starting at the same position? Add them all before checking the height, so only the final outline at that position is recorded.

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