MathWorks interview questions & answers

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

CodingEasyMathWorksSoftware Engineer

1. Reshape the Matrix (LeetCode)

Model answer

The task

Rearrange a matrix’s elements in row-major order into a matrix with the requested dimensions. If the new dimensions cannot hold exactly the same number of elements, return the original matrix unchanged.

Key idea

Reshaping changes where elements are placed, not their order. The element at flat index k belongs at row k // c and column k % c in the reshaped matrix.

Approach

  1. Read the original row and column counts.
  2. If the requested shape has a different total number of cells, return the original matrix.
  3. Create an empty result with the requested number of rows.
  4. Visit source elements in row-major order, tracking their flat index.
  5. Place each element at the corresponding destination row and column.
from typing import List

class Solution:
    def matrixReshape(
        self, mat: List[List[int]], r: int, c: int
    ) -> List[List[int]]:
        # Handle an empty matrix safely.
        if not mat or not mat[0]:
            return mat if r * c == 0 else mat

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

        # A reshape is possible only if the element counts match.
        if rows * cols != r * c:
            return mat

        result = [[0] * c for _ in range(r)]

        # Map each source element's row-major index to its new position.
        for i in range(rows):
            for j in range(cols):
                index = i * cols + j
                result[index // c][index % c] = mat[i][j]

        return result

Complexity:

  • Time: O(mn), where m × n is the original matrix size; each element is visited once.
  • Space: O(mn) for the reshaped result.

Common follow-ups

  • What if the requested dimensions do not match the element count? Return the original matrix without changing it.
  • Can the reshape be done without allocating another matrix? Only if modifying storage in place is allowed; the mapping is more involved.
  • How would you support a stream of elements? Buffer elements until a full destination row is available, then emit that row.
CodingEasyMathWorksSoftware Engineer

2. Valid Parentheses (LeetCode)

Model answer

The task

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

Key idea

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

Approach

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

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

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

Complexity:

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

Common follow-ups

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

3. Keyboard Row (LeetCode)

Model answer

The task

Given a list of words, return the words whose letters can all be typed using keys from a single row of a standard QWERTY keyboard. Matching should ignore letter case, while returned words keep their original spelling.

Key idea

Represent each keyboard row as a set of lowercase letters. A word qualifies when its letters are a subset of at least one row.

Approach

  1. Create a set for each keyboard row.
  2. For each word, convert its letters to lowercase.
  3. Check whether all its letters belong to any one row.
  4. Add qualifying words to the result, preserving their order.
from typing import List

class Solution:
    def findWords(self, words: List[str]) -> List[str]:
        rows = [
            set("qwertyuiop"),
            set("asdfghjkl"),
            set("zxcvbnm"),
        ]

        result = []

        for word in words:
            letters = set(word.lower())

            if any(letters <= row for row in rows):
                result.append(word)

        return result

Complexity:

  • Time: O(C), where C is the total number of characters across all words; each word is checked against a fixed number of rows.
  • Space: O(1) auxiliary space, since the row sets have fixed size; the result is not counted.

Common follow-ups

  • How would you support a different keyboard layout? Pass the row definitions as input and build sets from them.
  • What if the input includes non-letter characters? Decide whether to ignore them or reject the word, then apply that rule during validation.
  • How could you avoid checking every row for each word? Map each letter to its row index and verify all letters in a word share the same index.
CodingEasyMathWorksSoftware Engineer

4. Lexicographically Smallest Palindrome (LeetCode)

Model answer

The task

Given a string, change characters as needed so the result is a palindrome. Among all possible results, return the lexicographically smallest one.

Key idea

Each pair of mirrored positions must match. If the characters differ, using the smaller character at both positions gives the smallest result; the center character of an odd-length string stays unchanged.

Approach

  1. Convert the string to a mutable character list.
  2. Set pointers at the first and last positions.
  3. While they have not crossed, compare the pointed-to characters.
  4. If they differ, write the smaller character to both positions.
  5. Move both pointers inward and join the list.
class Solution:
    def makeSmallestPalindrome(self, s: str) -> str:
        chars = list(s)
        left, right = 0, len(chars) - 1

        while left < right:
            smaller = min(chars[left], chars[right])
            chars[left] = smaller
            chars[right] = smaller
            left += 1
            right -= 1

        return "".join(chars)

Complexity:

  • Time: O(n), where n is the length of the string.
  • Space: O(n) for the mutable character list.

Common follow-ups

  • How would you handle uppercase letters or other characters? Use the required character ordering when comparing each pair.
  • Can you return the number of changed positions as well? Count the mismatched mirrored pairs and multiply by two.
  • What if some positions cannot be changed? Check each mismatched pair for an allowed common character; report impossibility if none exists.
CodingEasyMathWorksSoftware Engineer

5. Pass the Pillow (LeetCode)

Model answer

The task

People stand in a line, and a pillow moves one person per second, reversing direction at each end. Return the position holding the pillow after the given time.

Key idea

The pillow’s position repeats every 2 * (n - 1) seconds. Reduce the time modulo that period, then reflect the result if it falls on the return trip.

Approach

  1. If there is only one person, return position 1.
  2. Compute the time’s offset within one full back-and-forth cycle.
  3. Use the offset directly on the outward trip; reflect it on the return trip.
  4. Convert the zero-based position to a one-based position.
class Solution:
    def passThePillow(self, n: int, time: int) -> int:
        # With one person, the pillow never changes hands.
        if n == 1:
            return 1

        # A full cycle goes from one end to the other and back.
        cycle_length = 2 * (n - 1)
        offset = time % cycle_length

        # Reflect the offset during the return trip.
        if offset > n - 1:
            offset = cycle_length - offset

        return offset + 1

Complexity:

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

Common follow-ups

  • What if the time is extremely large? Reduce it modulo the cycle length, as above.
  • What if the line has one person? The pillow remains with that person.
  • How would you solve it by simulation? Move one position per second and reverse direction at either end.
CodingMediumMathWorksSoftware Engineer

6. Total Cost to Hire K Workers (LeetCode)

Model answer

The task

Hire k workers one at a time from the ends of a cost array. At each step, choose the lowest-cost worker among the first or last candidates available workers; ties go to the worker with the smaller original index. Return the total hiring cost.

Key idea

Keep the eligible workers in two min-heaps: one for the left end and one for the right. After hiring from a side, add the next not-yet-considered worker from that same side.

Approach

  1. Use pointers to track the next unadded worker at each end.
  2. Fill the two heaps with up to candidates workers apiece, without adding anyone twice.
  3. For each hire, compare the heaps’ smallest (cost, index) pairs.
  4. Add the chosen cost and refill its heap from the corresponding end if workers remain.
  5. Return the accumulated cost.
import heapq
from typing import List

class Solution:
    def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
        n = len(costs)
        left = []
        right = []
        l, r = 0, n - 1

        # Add eligible workers from the left.
        while l <= r and len(left) < candidates:
            heapq.heappush(left, (costs[l], l))
            l += 1

        # Add eligible workers from the right, avoiding overlap.
        while l <= r and len(right) < candidates:
            heapq.heappush(right, (costs[r], r))
            r -= 1

        total = 0

        for _ in range(k):
            # Tuples compare by cost, then index, so ties use the
            # smaller original index.
            if not right or (left and left[0] <= right[0]):
                cost, _ = heapq.heappop(left)
                total += cost
                if l <= r:
                    heapq.heappush(left, (costs[l], l))
                    l += 1
            else:
                cost, _ = heapq.heappop(right)
                total += cost
                if l <= r:
                    heapq.heappush(right, (costs[r], r))
                    r -= 1

        return total

Complexity:

  • Time: O((candidates + k) log candidates), for heap setup and k heap operations.
  • Space: O(min(n, 2 × candidates)), for the eligible-worker heaps.

Common follow-ups

  • What if candidates exceeds the number of remaining workers? The heaps naturally contain all remaining workers, without duplicates.
  • How are equal costs resolved? Store (cost, original_index) so heap ordering selects the smaller index.
  • Can the heaps be initialized faster? Build their lists first and use heapq.heapify for linear-time heap construction.
CodingMediumMathWorksSoftware Engineer

7. Maximum Number of Alloys (LeetCode)

Model answer

The task

Given several alloy recipes, available metal stocks, per-metal purchase costs, and a budget, find the greatest number of identical alloys that can be made using any one recipe.

Key idea

For a fixed recipe, the cost to make a target quantity is easy to calculate: buy only the ingredients that exceed available stock. Feasibility is monotonic—a quantity that fits the budget implies every smaller quantity does too—so binary search the maximum for each recipe.

Approach

  1. Set an upper bound of budget + sum(stock): each alloy uses at least one unit of metal, and each purchased unit costs at least one.
  2. For each recipe, binary search between zero and that bound.
  3. For a candidate quantity, sum the purchase cost of each metal’s shortage.
  4. Stop checking a candidate as soon as its cost exceeds the budget.
  5. Return the largest feasible quantity found across recipes.
from typing import List

class Solution:
    def maxNumberOfAlloys(
        self,
        n: int,
        k: int,
        budget: int,
        composition: List[List[int]],
        stock: List[int],
        cost: List[int],
    ) -> int:
        # With positive ingredient costs and recipe quantities, this is
        # a safe exclusive upper bound on the number of alloys.
        upper = budget + sum(stock) + 1

        def feasible(recipe: List[int], count: int) -> bool:
            total_cost = 0

            for metal in range(n):
                shortage = max(0, recipe[metal] * count - stock[metal])
                total_cost += shortage * cost[metal]

                if total_cost > budget:
                    return False

            return True

        best = 0

        for recipe in composition:
            low, high = 0, upper  # low is feasible; high is exclusive

            while low + 1 < high:
                mid = (low + high) // 2

                if feasible(recipe, mid):
                    low = mid
                else:
                    high = mid

            best = max(best, low)

        return best

Complexity:

  • Time: O(k · n · log(budget + sum(stock))) — binary search each recipe, checking up to n metals per step.
  • Space: O(1) — uses only a few counters beyond the input.

Common follow-ups

  • What if the budget differs by recipe? Run the same search with that recipe’s budget.
  • What if some metals have zero cost? The upper bound may no longer be finite; handle unbounded production or derive a bound from the problem’s constraints.
  • Can recipes be processed in parallel? Yes; each recipe’s search is independent, and the answer is the maximum across them.
CodingMediumMathWorksSoftware Engineer

8. Sell Diminishing-Valued Colored Balls (LeetCode)

Model answer

The task

Given inventories of differently colored balls, sell a specified number of balls, always choosing a ball with the highest current value. Each sale reduces that color’s value by one. Return the maximum total revenue modulo \(10^9+7\).

Key idea

Find the value threshold \(t\) such that selling every ball valued above \(t\) uses at most the requested number of sales, but lowering the threshold would use too many. Sum those higher values with arithmetic-series formulas, then sell any remaining balls at value \(t\).

Approach

  1. Binary-search for the largest threshold \(t\) where the number of balls valued above \(t\) is at least the number of requested sales.
  2. For each inventory value \(v > t\), add the sum of values from \(t+1\) through \(v\).
  3. Count those sales.
  4. Add the remaining sales at value \(t\), and return the total modulo \(10^9+7\).
from typing import List

class Solution:
    def maxProfit(self, inventory: List[int], orders: int) -> int:
        mod = 10**9 + 7

        # Number of balls whose current values are strictly above threshold.
        def balls_above(threshold: int) -> int:
            return sum(max(value - threshold, 0) for value in inventory)

        # Find the largest threshold with enough balls above it.
        low, high = 0, max(inventory)
        while low < high:
            mid = (low + high + 1) // 2
            if balls_above(mid) >= orders:
                low = mid
            else:
                high = mid - 1

        threshold = low
        revenue = 0
        sold = 0

        # Sell every value above the threshold.
        for value in inventory:
            if value > threshold:
                count = value - threshold
                revenue += (value + threshold + 1) * count // 2
                sold += count

        # Any remaining sales are made at the threshold value.
        revenue += (orders - sold) * threshold
        return revenue % mod

Complexity:

  • Time: O(n log M), where \(n\) is the number of colors and \(M\) is the largest inventory value.
  • Space: O(1) auxiliary space.

Common follow-ups

  • How would a max-heap solve it? Repeatedly sell the current highest-valued ball; this is straightforward but costs O(orders log n).
  • Why use an arithmetic-series sum? A color with value \(v > t\) contributes \(v + (v-1) + \dots + (t+1)\).
  • What if orders equals the total inventory? The threshold becomes zero, so all balls are sold.
CodingMediumMathWorksSoftware Engineer

9. Shopping Offers (LeetCode)

Model answer

The task

Given item prices, bundle offers that specify item quantities and a total cost, and a list of quantities to buy, find the minimum total cost. Each offer may be used repeatedly, and any remaining items can be bought individually.

Key idea

Memoize the cheapest cost for each remaining-needs vector. From a state, either buy everything left at regular prices or apply any offer that fits and solve the smaller state.

Approach

  1. Store each needs vector as a tuple so it can be used as a memoization key.
  2. Set the baseline cost to buying all remaining items individually.
  3. For each offer that fits, subtract its quantities and consider its cost plus the cached cost of the remainder.
  4. Ignore offers that contain no items, so every recursive offer application makes progress.
  5. Return the minimum cost.
from functools import cache
from typing import List

class Solution:
    def shoppingOffers(
        self,
        price: List[int],
        special: List[List[int]],
        needs: List[int],
    ) -> int:
        item_count = len(price)

        # Keep only offers that actually provide at least one item.
        offers = [
            (tuple(offer[:item_count]), offer[item_count])
            for offer in special
            if any(offer[:item_count])
        ]

        @cache
        def min_cost(remaining: tuple[int, ...]) -> int:
            # Buy every remaining item at its regular unit price.
            best = sum(
                quantity * unit_price
                for quantity, unit_price in zip(remaining, price)
            )

            for quantities, offer_cost in offers:
                if all(
                    quantities[i] <= remaining[i]
                    for i in range(item_count)
                ):
                    next_needs = tuple(
                        remaining[i] - quantities[i]
                        for i in range(item_count)
                    )
                    best = min(best, offer_cost + min_cost(next_needs))

            return best

        return min_cost(tuple(needs))

Complexity:

  • Time: O(P · S · n), where P is the number of reachable needs vectors, S is the number of offers, and n is the number of item types.
  • Space: O(P · n) for memoized needs vectors, plus recursion depth.

Common follow-ups

  • How can dominated offers be pruned? Remove an offer if its cost is no lower than buying the same quantities individually.
  • What if there are many item types but few reachable states? Keep the memoized search; it explores only states reached by fitting offers.
  • Could this be iterative? Yes. Enumerate needs vectors in increasing order and compute each state from smaller vectors.
CodingMediumMathWorksSoftware Engineer

10. Longest Palindromic Subsequence (LeetCode)

Model answer

The task

Given a string, find the length of its longest subsequence that reads the same forward and backward. Characters may be skipped, but their order must stay unchanged.

Key idea

For each substring, its best palindromic subsequence either uses matching endpoint characters together or skips one endpoint. Compute these answers for progressively shorter starting indices, keeping only one row of dynamic programming values.

Approach

  1. Return 0 if the string is empty.
  2. Process starting indices from right to left; a single character has answer 1.
  3. For each ending index to the right, save the previous row’s value before updating it.
  4. If the endpoints match, extend the inner substring’s answer by 2; otherwise, take the better answer from skipping either endpoint.
  5. The final value stores the answer for the entire string.
class Solution:
    def longestPalindromeSubseq(self, s: str) -> int:
        n = len(s)
        if n == 0:
            return 0

        # dp[j] stores the answer for the current start index through j.
        dp = [0] * n

        for i in range(n - 1, -1, -1):
            dp[i] = 1
            diagonal = 0  # Previous row's answer for the inner substring.

            for j in range(i + 1, n):
                old_dp_j = dp[j]  # Preserve the previous row's value.

                if s[i] == s[j]:
                    dp[j] = diagonal + 2
                else:
                    # Skip the left or right endpoint.
                    dp[j] = max(dp[j], dp[j - 1])

                # For the next j, this is the previous row's inner value.
                diagonal = old_dp_j

        return dp[n - 1]

Complexity:

  • Time: O(n²), since each pair of indices is processed once.
  • Space: O(n), for the one-dimensional DP array.

Common follow-ups

  • How would you return an actual longest palindromic subsequence? Store the full DP table, then walk inward, recording matched endpoints and choosing the better skip when characters differ.
  • How does this differ from the longest palindromic substring? A subsequence can skip characters; a substring must be contiguous.
  • Can the time complexity be improved? For a general string, the standard DP takes O(n²); specialized constraints or a small alphabet may allow other techniques.
  • What if the input is empty or has one character? The result is 0 or 1, respectively.
CodingMediumMathWorksSoftware Engineer

11. Earliest Second to Mark Indices I (LeetCode)

Model answer

The task

Given required decrement counts and a sequence of indices available to mark at each second, find the earliest prefix of seconds in which every index can be reduced to zero and marked. Return -1 if no prefix works.

Key idea

Binary search the prefix length: if a prefix works, every longer prefix also works. For a candidate prefix, mark each index at its last available second; scanning seconds in order, check that enough earlier seconds are available for its decrements.

Approach

  1. Binary search prefix lengths from 1 to the number of seconds.
  2. For each candidate prefix, record the last second on which each index can be marked.
  3. If any index has no available marking second, the prefix is infeasible.
  4. Scan the prefix: non-marking seconds add one available decrement operation.
  5. At each chosen marking second, spend the required decrement operations; fail if there are not enough.
from typing import List

class Solution:
    def earliestSecondToMarkIndices(
        self, nums: List[int], changeIndices: List[int]
    ) -> int:
        n = len(nums)
        m = len(changeIndices)

        def feasible(seconds: int) -> bool:
            # Store the last available marking second for each index.
            last = [-1] * n
            for t in range(seconds):
                last[changeIndices[t] - 1] = t

            if any(t == -1 for t in last):
                return False

            available = 0
            for t in range(seconds):
                idx = changeIndices[t] - 1

                if last[idx] == t:
                    # This second is used to mark idx, so its decrements
                    # must have been completed using earlier seconds.
                    if available < nums[idx]:
                        return False
                    available -= nums[idx]
                else:
                    # Use this second for one decrement operation.
                    available += 1

            return True

        left, right = 1, m
        answer = -1

        while left <= right:
            mid = (left + right) // 2
            if feasible(mid):
                answer = mid
                right = mid - 1
            else:
                left = mid + 1

        return answer

Complexity:

  • Time: O((n + m) log m) — each binary-search check scans up to m seconds and n indices.
  • Space: O(n) — stores the last marking second for each index.

Common follow-ups

  • What if the sequence can change dynamically? The binary-search checks would need a data structure that supports updating and querying marking availability.
  • Can you reject impossible inputs early? Yes; at least sum(nums) + n seconds are needed for decrements and marking.
  • What if marking can happen on any second? Then the marking deadlines disappear; only the total number of available seconds matters.
CodingMediumMathWorksSoftware Engineer

12. Maximum Palindromes After Operations (LeetCode)

Model answer

The task

Redistribute characters among the given words using swaps, then rearrange words as needed. Return the largest number of words that can each be made palindromes.

Key idea

A palindrome of length L needs L // 2 matching character pairs; an odd-length word also needs a center character. The character pool provides sum(count // 2) pairs. Since the selected words use no more characters than the full pool, there will be enough characters left for their centers.

Approach

  1. Count each character across all words and sum the available pairs.
  2. Compute length // 2 for each word.
  3. Sort these pair requirements; shorter words are cheapest to make palindromes.
  4. Greedily take each word while its pair requirement fits the remaining pair supply.
  5. Return the number taken.
from collections import Counter
from typing import List

class Solution:
    def maxPalindromesAfterOperations(self, words: List[str]) -> int:
        # Each matching pair can fill one mirrored pair of positions.
        frequencies = Counter("".join(words))
        available_pairs = sum(count // 2 for count in frequencies.values())

        # Build the words with the smallest pair requirements first.
        pair_needs = sorted(len(word) // 2 for word in words)

        result = 0
        for needed in pair_needs:
            if needed > available_pairs:
                break
            available_pairs -= needed
            result += 1

        return result

Complexity:

  • Time: O(N + W log W), where N is the total number of characters and W is the number of words.
  • Space: O(Σ), where Σ is the number of distinct characters.

Common follow-ups

  • Why sort by length? Pair requirements are length // 2, so shorter words never require more pairs.
  • Do odd-length words need separate handling? No; their center characters come from the remaining pool, which has enough characters because selected words fit within the total character count.
  • What if characters cannot be redistributed between words? Then each word must be checked using only its own character counts; the global greedy allocation no longer applies.
CodingMediumMathWorksSoftware Engineer

13. Minimum Cost Tree From Leaf Values (LeetCode)

Model answer

The task

Given leaf values in their fixed left-to-right order, form a full binary tree whose leaves are those values. Each internal node’s value is the product of the largest leaf values in its two child subtrees; minimize the sum of all internal-node values.

Key idea

A smaller leaf is cheapest to combine with the smaller of its nearest larger neighbors. A monotonic decreasing stack finds those neighbors and accounts for each leaf’s combination once, avoiding interval dynamic programming.

Approach

  1. Keep a decreasing stack of leaf values, with an infinite sentinel at its bottom.
  2. For each value, pop stack values no greater than it.
  3. For each popped value, add its product with the smaller of the popped value’s nearest remaining left neighbor and the current value.
  4. Push the current value.
  5. After processing all leaves, combine the remaining stack values from right to left.
from math import inf
from typing import List

class Solution:
    def mctFromLeafValues(self, arr: List[int]) -> int:
        # The stack is decreasing; the sentinel avoids an empty-stack check.
        stack = [inf]
        cost = 0

        for value in arr:
            # The popped leaf is paired with its cheaper adjacent larger leaf.
            while stack[-1] <= value:
                leaf = stack.pop()
                cost += leaf * min(stack[-1], value)

            stack.append(value)

        # Combine leaves still on the stack, from right to left.
        while len(stack) > 2:
            cost += stack.pop() * stack[-1]

        return cost

Complexity:

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

Common follow-ups

  • How can the actual tree be reconstructed? Store leaf-node references on the stack and create an internal node whenever two subtrees are combined.
  • Can dynamic programming solve it? Yes: try every split for each interval, but this takes O(n³) time and O(n²) space.
  • What if leaf values can be negative? The greedy argument relies on the usual positive leaf values; with negatives, use a method tailored to the changed cost rules.
CodingMediumMathWorksSoftware Engineer

14. Total Characters in String After Transformations I (LeetCode)

Model answer

The task

Given a lowercase string and a number of transformations, find the string’s length after repeatedly replacing each character with its successor in the alphabet; z becomes ab. Return the length modulo \(10^9+7\).

Key idea

Track how many copies of each of the 26 letters exist, rather than constructing the transformed string. Each round, move every letter’s count to the letter or letters it produces.

Approach

  1. Count the original string’s letters.
  2. For each transformation, create a fresh array of 26 counts.
  3. Move each letter’s count to its successor; move z’s count to both a and b.
  4. Apply the modulus while updating counts.
  5. Sum the final counts modulo \(10^9+7\).
class Solution:
    def lengthAfterTransformations(self, s: str, t: int) -> int:
        mod = 1_000_000_007
        counts = [0] * 26

        for char in s:
            counts[ord(char) - ord('a')] += 1

        for _ in range(t):
            next_counts = [0] * 26

            for i, count in enumerate(counts):
                if i == 25:  # 'z' becomes 'a' and 'b'
                    next_counts[0] = (next_counts[0] + count) % mod
                    next_counts[1] = (next_counts[1] + count) % mod
                else:
                    next_counts[i + 1] = (
                        next_counts[i + 1] + count
                    ) % mod

            counts = next_counts

        return sum(counts) % mod

Complexity:

  • Time: \(O(|s| + 26t)\), for counting and updating 26 letter frequencies per round.
  • Space: \(O(26)\), for the frequency arrays.

Common follow-ups

  • What if t is extremely large? Represent one transformation as a 26-by-26 matrix and use fast exponentiation.
  • What if the alphabet or replacement rules change? Build a transition table and distribute each letter’s count according to its outputs.
  • Can the actual transformed string be returned? Its length can grow exponentially, so producing it may be infeasible even when its length can be computed efficiently.
CodingMediumMathWorksSoftware Engineer

15. Task Scheduler (LeetCode)

Model answer

The task

Find the fewest time slots needed to run all tasks when identical task types must be separated by at least n slots. A slot may be left idle.

Key idea

The most frequent task types determine the minimum schedule length. Put copies of a most frequent type into frames of length n + 1; other tasks can fill the gaps. If there are enough other tasks to fill every gap, no idle slots are needed.

Approach

  1. Count how many times each task type appears.
  2. Find the largest frequency, max_freq.
  3. Count how many types occur exactly max_freq times.
  4. Compute the frame-based length: (max_freq - 1) * (n + 1) + max_count.
  5. Return the larger of that length and the total number of tasks.
from collections import Counter
from typing import List

class Solution:
    def leastInterval(self, tasks: List[str], n: int) -> int:
        frequencies = Counter(tasks)
        max_freq = max(frequencies.values())
        max_count = sum(
            frequency == max_freq
            for frequency in frequencies.values()
        )

        # The most frequent tasks establish the frame-based schedule.
        frame_length = (max_freq - 1) * (n + 1) + max_count

        # Other tasks may fill idle slots, but cannot reduce below task count.
        return max(len(tasks), frame_length)

Complexity:

  • Time: O(m + k), to count m tasks and scan k task types.
  • Space: O(k), for the task-frequency counts.

Common follow-ups

  • What if n is zero? The formula returns the task count, since no cooldown is required.
  • What if several task types share the highest frequency? Include all of them in the last frame, as max_count does.
  • How could you construct an actual schedule? Greedily run the most frequent available task, tracking cooldowns with a max-heap and a queue.
  • What if tasks have different cooldowns? The simple formula no longer applies; model each task’s next available time and schedule with a priority queue.
CodingMediumMathWorksSoftware Engineer

16. Number of Divisible Triplet Sums (LeetCode)

Model answer

The task

Count index triples i < j < k whose three array values sum to a multiple of d. Each distinct choice of indices counts once.

Key idea

For each pair of indices i and j, look up how many later values have the residue needed to make the sum divisible by d. Keep frequencies of those later values’ remainders in a hash table.

Approach

  1. Iterate over each index i as the first index.
  2. Build remainder frequencies for values after i.
  3. As j moves through those values, remove nums[j] from the frequencies so only indices k > j remain.
  4. Look up the remainder that completes nums[i] + nums[j] to a multiple of d, and add its frequency to the answer.
from collections import defaultdict
from typing import List

class Solution:
    def divisibleTripletCount(self, nums: List[int], d: int) -> int:
        n = len(nums)
        answer = 0

        for i in range(n - 2):
            # Store remainders for indices strictly after i.
            later = defaultdict(int)
            for k in range(i + 1, n):
                later[nums[k] % d] += 1

            # Before counting, remove j so the table contains only k > j.
            for j in range(i + 1, n - 1):
                later[nums[j] % d] -= 1

                needed = (-(nums[i] + nums[j])) % d
                answer += later[needed]

        return answer

Complexity:

  • Time: O(n²), for each pair of first and second indices.
  • Space: O(min(n, d)), for the distinct remainders stored in the hash table.

Common follow-ups

  • How are negative values handled? Python’s % d gives a normalized remainder when d is positive.
  • Can this be faster for small d? Use an array of d remainder counts instead of a hash table; the asymptotic time remains O(n²).
  • What if triples may use repeated indices? The counting rules must change; this approach specifically enforces i < j < k.
CodingMediumMathWorksSoftware Engineer

17. Remove Colored Pieces if Both Neighbors are the Same Color (LeetCode)

Model answer

The task

Given a string of A and B pieces, determine whether Alice wins when players alternate removing a piece whose two immediate neighbors match that player’s color. Alice moves first.

Key idea

A run of k identical pieces allows exactly max(0, k - 2) removals for that color. Moves only shrink a player’s own runs, so the players’ available move counts do not interfere.

Approach

  1. Scan the string and identify each maximal run of identical characters.
  2. For each run, add its length minus two, if positive, to that color’s move count.
  3. Alice wins exactly when the number of A moves is greater than the number of B moves.
class Solution:
    def winnerOfGame(self, colors: str) -> bool:
        alice_moves = 0
        bob_moves = 0

        i = 0
        while i < len(colors):
            j = i + 1

            # Find the end of this maximal run.
            while j < len(colors) and colors[j] == colors[i]:
                j += 1

            available_moves = max(0, j - i - 2)
            if colors[i] == "A":
                alice_moves += available_moves
            else:
                bob_moves += available_moves

            i = j

        return alice_moves > bob_moves

Complexity:

  • Time: O(n), where n is the string length.
  • Space: O(1), using only counters and indices.

Common follow-ups

  • What if Bob moves first? Alice wins only if her move count is greater than Bob’s.
  • Can the counts be computed without explicitly finding runs? Yes; count each character whose immediate neighbors are the same character.
  • Why does the exact move order not matter? A move shortens only the mover’s color run and does not change the other player’s available moves.
CodingMediumMathWorksSoftware Engineer

18. Minimum Equal Sum of Two Arrays After Replacing Zeros (LeetCode)

Model answer

The task

Choose a positive integer for every zero in each of two arrays so that their sums are equal. Return the smallest equal sum possible, or -1 if no choice can make the sums match.

Key idea

Replacing every zero with 1 gives each array its smallest possible sum. From there, an array can reach any larger sum if it contains at least one zero; without zeros, its sum is fixed.

Approach

  1. For each array, compute its sum after replacing zeros with 1.
  2. Count the zeros in each array.
  3. If the lower sums are equal, return that sum.
  4. Otherwise, the array with the smaller lower sum must be able to increase.
  5. If it has no zeros, return -1; otherwise, return the larger lower sum.
from typing import List

class Solution:
    def minSum(self, nums1: List[int], nums2: List[int]) -> int:
        # Replacing each zero with 1 produces the smallest possible sum.
        sum1 = sum(nums1) + nums1.count(0)
        sum2 = sum(nums2) + nums2.count(0)

        if sum1 == sum2:
            return sum1

        if sum1 < sum2:
            # Array 1 must increase to reach sum2.
            return sum2 if 0 in nums1 else -1

        # Array 2 must increase to reach sum1.
        return sum1 if 0 in nums2 else -1

Complexity:

  • Time: O(n + m), to scan both arrays.
  • Space: O(1), using only a few extra variables.

Common follow-ups

  • How would you avoid scanning each array multiple times? Compute its sum and zero count in one pass.
  • What if zeros could be replaced only by values from a limited range? Check whether the attainable sums overlap.
  • What if the arrays are very large and stored on disk? Stream through each array once to collect its sum and zero count.
CodingMediumMathWorksSoftware Engineer

19. Count Vowel Strings in Ranges (LeetCode)

Model answer

The task

Given a list of words and several inclusive index ranges, return how many words in each range both begin and end with a vowel.

Key idea

Build a prefix sum where each position contributes 1 if its word starts and ends with a vowel, and 0 otherwise. Each range count is then the difference of two prefix sums.

Approach

  1. Create a set containing the vowels.
  2. Scan the words and record a running total of qualifying words.
  3. For each range [left, right], subtract the total before left from the total through right.
  4. Return the range counts in query order.
from typing import List

class Solution:
    def vowelStrings(
        self, words: List[str], queries: List[List[int]]
    ) -> List[int]:
        vowels = set("aeiou")
        prefix = [0]

        for word in words:
            qualifies = word[0] in vowels and word[-1] in vowels
            prefix.append(prefix[-1] + int(qualifies))

        answers = []
        for left, right in queries:
            answers.append(prefix[right + 1] - prefix[left])

        return answers

Complexity:

  • Time: O(n + q), where n is the number of words and q is the number of queries.
  • Space: O(n) for the prefix sums and O(q) for the returned answers.

Common follow-ups

  • What if queries arrive one at a time? Keep the prefix sums built once and answer each query in O(1).
  • What if the word list changes? A standard prefix array needs rebuilding; for frequent updates and queries, use a Fenwick tree or segment tree.
  • What if vowel rules are case-insensitive? Normalize each word’s first and last characters before checking membership.
CodingHardMathWorksSoftware Engineer

20. Minimum Edge Reversals So Every Node Is Reachable (LeetCode)

Model answer

The task

Given a tree whose edges have directions, compute for each node the fewest edge reversals needed so that every node can be reached from that node.

Key idea

Root the tree temporarily at node 0. During a traversal, count edges that point toward the root; those must be reversed for 0 to reach every node. Then reroot across each edge: the required count changes by +1 or -1 depending on that edge’s direction.

Approach

  1. Build an undirected adjacency list, recording whether each traversal follows the original edge direction.
  2. Traverse from 0 to count the reversals needed for node 0.
  3. Traverse the tree again, propagating the answer to each child.
  4. Add one when the edge points from parent to child; subtract one when it points from child to parent.
from typing import List

class Solution:
    def minEdgeReversals(self, n: int, edges: List[List[int]]) -> List[int]:
        # For an adjacency entry (neighbor, cost), cost is 0 if the
        # original edge points toward neighbor, and 1 otherwise.
        graph = [[] for _ in range(n)]
        for u, v in edges:
            graph[u].append((v, 0))
            graph[v].append((u, 1))

        # Find the number of reversals needed when node 0 is the root.
        parent = [-1] * n
        parent[0] = 0
        order = [0]
        initial_reversals = 0

        for node in order:
            for neighbor, cost in graph[node]:
                if neighbor == parent[node]:
                    continue
                parent[neighbor] = node
                initial_reversals += cost
                order.append(neighbor)

        # Reroot the answer from each parent to its child.
        answer = [0] * n
        answer[0] = initial_reversals

        for node in order[1:]:
            p = parent[node]
            # If the original edge points p -> node, rerooting adds one.
            # If it points node -> p, rerooting removes one.
            edge_cost = next(cost for neighbor, cost in graph[p] if neighbor == node)
            answer[node] = answer[p] + (1 if edge_cost == 0 else -1)

        return answer

Complexity:

  • Time: O(n), since the tree is traversed a constant number of times.
  • Space: O(n) for the adjacency list and traversal data.

Common follow-ups

  • Can the traversal avoid recursion? Yes; the iterative traversal above also avoids recursion-depth limits.
  • What if the input is not a tree? Rerooting this way no longer applies directly; cycles can create multiple paths and require a different optimization model.
  • How would you handle weighted reversal costs? Track the edge’s reversal cost and update the answer by adding or subtracting that cost when rerooting.

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