Epic Systems interview questions & answers

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

CodingEasyEpic SystemsSoftware Engineer

1. Two Sum (LeetCode)

Model answer

The task

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

Key idea

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

Approach

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

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

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

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

            seen[value] = index

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

Complexity:

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

Common follow-ups

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

2. Valid Palindrome (LeetCode)

Model answer

The task

Determine whether a string reads the same forward and backward after disregarding characters that are not letters or digits and treating uppercase and lowercase as equivalent.

Key idea

Compare characters from both ends, skipping anything that should be ignored. If every remaining pair matches, the string is a palindrome.

Approach

  1. Initialize pointers at the start and end of the string.
  2. Move the left pointer past non-alphanumeric characters.
  3. Move the right pointer past non-alphanumeric characters.
  4. Compare the lowercase forms of the characters at the pointers; return False if they differ.
  5. Move both pointers inward and continue. If they meet or cross, return True.
class Solution:
    def isPalindrome(self, s: str) -> bool:
        left, right = 0, len(s) - 1

        while left < right:
            # Ignore characters that are not letters or digits.
            while left < right and not s[left].isalnum():
                left += 1
            while left < right and not s[right].isalnum():
                right -= 1

            # Compare without regard to letter case.
            if s[left].lower() != s[right].lower():
                return False

            left += 1
            right -= 1

        return True

Complexity:

  • Time: O(n), where n is the string length; each pointer moves only inward.
  • Space: O(1), since the comparisons use no additional data structure.

Common follow-ups

  • What if the input contains no letters or digits? It is considered a palindrome, since there are no mismatching characters.
  • Can you avoid creating a normalized copy of the string? Yes; the two-pointer scan uses constant extra space.
  • How would you handle Unicode normalization? Normalize the string first if canonically equivalent characters should compare as equal; that may require additional space.
CodingEasyEpic SystemsSoftware Engineer

3. 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.
CodingEasyEpic SystemsSoftware Engineer

4. Self Dividing Numbers (LeetCode)

Model answer

The task

Given an inclusive range of positive integers, return those numbers that are divisible by every digit they contain. A number with a zero digit does not qualify.

Key idea

Check each number one digit at a time. Reject it if any digit is zero or does not divide the original number evenly.

Approach

  1. Visit each integer in the given range.
  2. Keep a copy of it for extracting digits.
  3. For each digit, reject the integer if the digit is zero or the integer is not divisible by it.
  4. Add the integer to the result if all its digits pass the check.
  5. Return the collected integers in ascending order.
class Solution:
    def selfDividingNumbers(self, left: int, right: int) -> list[int]:
        result = []

        for number in range(left, right + 1):
            remaining = number
            qualifies = True

            while remaining > 0:
                digit = remaining % 10

                if digit == 0 or number % digit != 0:
                    qualifies = False
                    break

                remaining //= 10

            if qualifies:
                result.append(number)

        return result

Complexity:

  • Time: O(R · D), where R is the number of integers in the range and D is the number of digits per integer.
  • Space: O(1) auxiliary space, excluding the result list.

Common follow-ups

  • How would you handle negative numbers? Define whether the sign is ignored; typically, only positive integers qualify.
  • Can the digit checks be moved into a helper function? Yes; a helper can return whether a single number qualifies.
  • What if the range is very large? The direct scan is still linear in the range size; skipping candidates requires additional structure or constraints.
CodingMediumEpic SystemsSoftware Engineer

5. Additive Number (LeetCode)

Model answer

The task

Determine whether a digit string can be split into at least three numbers where each number after the first two is the sum of the previous two. Numbers cannot have leading zeros unless they are zero.

Key idea

Try every valid pair of starting numbers. For each pair, repeatedly compute the next sum and check whether its decimal representation matches the next part of the string.

Approach

  1. Choose end positions for the first and second numbers.
  2. Skip either number if it has a leading zero and contains more than one digit.
  3. Convert the starting numbers to integers.
  4. Generate sums in sequence; stop if the next sum does not match the remaining string.
  5. Return True if a sequence reaches the end with at least three numbers.
class Solution:
    def isAdditiveNumber(self, num: str) -> bool:
        n = len(num)

        # Choose the end of the first number and the second number.
        for first_end in range(1, n):
            first_text = num[:first_end]
            if len(first_text) > 1 and first_text[0] == "0":
                continue

            for second_end in range(first_end + 1, n):
                second_text = num[first_end:second_end]
                if len(second_text) > 1 and second_text[0] == "0":
                    continue

                first = int(first_text)
                second = int(second_text)
                position = second_end
                count = 2

                # Match each expected sum against the next substring.
                while position < n:
                    total_text = str(first + second)
                    if not num.startswith(total_text, position):
                        break

                    position += len(total_text)
                    first, second = second, int(total_text)
                    count += 1

                if position == n and count >= 3:
                    return True

        return False

Complexity:

  • Time: O(n³), considering O(n²) starting splits and up to O(n) work to validate each sequence.
  • Space: O(n), for temporary number representations and conversions.

Common follow-ups

  • How would you avoid large integer conversions? Implement decimal-string addition and compare sums as strings.
  • What if the input has leading zeros throughout? Only the single-digit number 0 is valid with a leading zero.
  • Can the first two numbers be pruned by length? Yes; their lengths cannot exceed the remaining string, and their sum must fit within the remaining digits.
CodingMediumEpic SystemsSoftware Engineer

6. Word Search (LeetCode)

Model answer

The task

Determine whether a word can be traced through adjacent cells in a character grid. Each cell may be used at most once in the same trace.

Key idea

Try each cell as a starting point and use depth-first search to match the word one character at a time. Track cells used in the current path, then undo that tracking when backtracking.

Approach

  1. Return False if the grid is empty or the word is longer than the number of cells.
  2. Start a DFS from every cell matching the word’s first character.
  3. In the DFS, reject out-of-bounds cells, used cells, or character mismatches.
  4. Return True once all characters are matched.
  5. Add each matched cell to the path before exploring neighbors, and remove it afterward.
from typing import List, Set, Tuple

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        if not word:
            return True
        if not board or not board[0]:
            return False

        rows, cols = len(board), len(board[0])
        if len(word) > rows * cols:
            return False

        used: Set[Tuple[int, int]] = set()

        def search(row: int, col: int, index: int) -> bool:
            if (
                row < 0 or row >= rows
                or col < 0 or col >= cols
                or (row, col) in used
                or board[row][col] != word[index]
            ):
                return False

            if index == len(word) - 1:
                return True

            used.add((row, col))
            found = (
                search(row + 1, col, index + 1)
                or search(row - 1, col, index + 1)
                or search(row, col + 1, index + 1)
                or search(row, col - 1, index + 1)
            )
            used.remove((row, col))
            return found

        for row in range(rows):
            for col in range(cols):
                if search(row, col, 0):
                    return True

        return False

Complexity:

  • Time: O(RC · 4^L), where R and C are grid dimensions and L is the word length; each cell may start a search.
  • Space: O(L), for the visited path and recursive call stack.

Common follow-ups

  • What if diagonal moves are allowed? Add the four diagonal directions to the DFS.
  • How can the search be pruned? Check character frequencies before searching, or start from the rarer end of the word.
  • How would you search for many words at once? Build a trie and search the grid while matching trie prefixes.
CodingMediumEpic SystemsSoftware Engineer

7. Spiral Matrix (LeetCode)

Model answer

The task

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

Key idea

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

Approach

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

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

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

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

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

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

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

        return result

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

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

Common follow-ups

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

8. Letter Combinations of a Phone Number (LeetCode)

Model answer

The task

Given a string of digits from 2 through 9, return every string formed by choosing the corresponding phone-keypad letter for each digit. If the input is empty, return an empty list.

Key idea

Build each string one character at a time using backtracking. For each digit, try every letter mapped to it, then undo that choice before trying the next one.

Approach

  1. Define the digit-to-letters mapping.
  2. Return an empty list if there are no digits.
  3. Use a recursive helper to track the current digit position and partial string.
  4. When the partial string has one letter per digit, add it to the results.
  5. Otherwise, recurse once for each letter mapped to the current digit.
class Solution:
    def letterCombinations(self, digits: str) -> list[str]:
        if not digits:
            return []

        letters = {
            "2": "abc",
            "3": "def",
            "4": "ghi",
            "5": "jkl",
            "6": "mno",
            "7": "pqrs",
            "8": "tuv",
            "9": "wxyz",
        }

        result = []
        current = []

        def backtrack(index: int) -> None:
            # A complete choice has one letter for every digit.
            if index == len(digits):
                result.append("".join(current))
                return

            # Try each possible letter for this digit.
            for letter in letters[digits[index]]:
                current.append(letter)
                backtrack(index + 1)
                current.pop()  # Undo the choice before trying another.

        backtrack(0)
        return result

Complexity:

  • Time: O(n · 4ⁿ), since there can be up to 4ⁿ combinations and building each takes O(n).
  • Space: O(n) auxiliary space for the recursion and current combination, excluding the output.

Common follow-ups

  • What if the input contains 0 or 1? Define their behavior explicitly, since they do not map to letters in the standard keypad mapping.
  • How would you avoid recursion? Build combinations iteratively, adding each digit’s letters to the partial results.
  • Can the results be generated lazily? Yield each completed combination from the recursive search instead of storing them all.
CodingMediumEpic SystemsSoftware Engineer

9. Permutations (LeetCode)

Model answer

The task

Given a list of distinct integers, return every possible ordering of those integers. The order of the returned permutations does not matter.

Key idea

Build each permutation one position at a time. Track which values are already chosen so each value appears exactly once in a permutation.

Approach

  1. Keep a mutable list for the permutation currently being built.
  2. Keep a used array indicating which input positions are already in that list.
  3. At each recursive call, try every unused value, mark it used, and recurse.
  4. Once the current permutation has the same length as the input, save a copy of it.
  5. Undo the choice after returning from recursion so other possibilities can be explored.
from typing import List

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        result: List[List[int]] = []
        current: List[int] = []
        used = [False] * len(nums)

        def backtrack() -> None:
            # A complete ordering has been constructed.
            if len(current) == len(nums):
                result.append(current.copy())
                return

            for i, value in enumerate(nums):
                if used[i]:
                    continue

                # Choose this value for the next position.
                used[i] = True
                current.append(value)

                backtrack()

                # Undo the choice before trying another value.
                current.pop()
                used[i] = False

        backtrack()
        return result

Complexity:

  • Time: O(n · n!), since there are n! permutations and copying each takes O(n).
  • Space: O(n) auxiliary space for recursion and the current permutation, excluding the returned permutations.

Common follow-ups

  • How would you handle repeated values? Sort the input and skip a value when it duplicates the previous value at the same recursion depth.
  • Can the permutations be generated without storing them all? Yield each completed permutation from a generator instead of appending it to a result list.
  • What if only permutations of length k are needed? Stop the recursion when the current list reaches length k.
CodingMediumEpic SystemsSoftware Engineer

10. Longest Palindromic Substring (LeetCode)

Model answer

The task

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

Key idea

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

Approach

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

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

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

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

        return s[best_start:best_start + best_length]

Complexity:

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

Common follow-ups

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

11. Stepping Numbers (LeetCode)

Model answer

The task

Return every non-negative integer in the inclusive range [low, high] whose neighboring decimal digits differ by exactly one.

Key idea

Build numbers one digit at a time with breadth-first search. From a number ending in digit d, the only possible next digits are d - 1 and d + 1; discard extensions that exceed high.

Approach

  1. Include 0 if it lies in the requested range.
  2. Start the queue with the one-digit numbers from 1 through min(9, high).
  3. For each queued number, add it to the answer if it is at least low.
  4. Extend it with each valid neighboring digit, enqueueing only values no greater than high.
  5. Return the answer. BFS visits numbers by digit length and then in ascending order, so the result is sorted.
from collections import deque
from typing import List

class Solution:
    def countSteppingNumbers(self, low: int, high: int) -> List[int]:
        result = [0] if low == 0 else []
        queue = deque(range(1, min(9, high) + 1))

        while queue:
            number = queue.popleft()

            if number >= low:
                result.append(number)

            last_digit = number % 10

            # Appending a digit creates a larger number, so values above
            # high never need to be explored further.
            for next_digit in (last_digit - 1, last_digit + 1):
                if 0 <= next_digit <= 9:
                    next_number = number * 10 + next_digit
                    if next_number <= high:
                        queue.append(next_number)

        return result

Complexity:

  • Time: O(K), where K is the number of stepping numbers generated up to high.
  • Space: O(K) for the queue and returned list.

Common follow-ups

  • What if the range includes negative numbers? Stepping numbers are usually defined as non-negative; clarify whether a sign affects the digit rule.
  • What if high is extremely large? Use digit-based generation or digit DP if enumerating every result is impractical.
  • What if only the count is needed? Count qualifying generated values instead of storing them in the result list.
CodingMediumEpic SystemsSoftware Engineer

12. Palindromic Substrings (LeetCode)

Model answer

The task

Given a string, count how many of its substrings are palindromes. Count each substring by its position, so equal text at different positions contributes more than once.

Key idea

Every palindrome has a center: either one character or the gap between two characters. Expand outward from each possible center while the characters match, counting each palindrome found.

Approach

  1. Initialize a counter for the palindromic substrings.
  2. Visit each character position as an odd-length center.
  3. Visit each gap between adjacent characters as an even-length center.
  4. For each center, expand left and right while the characters match, adding one to the counter for each match.
  5. Return the counter.
class Solution:
    def countSubstrings(self, s: str) -> int:
        count = 0
        n = len(s)

        def expand(left: int, right: int) -> int:
            found = 0

            # Every matching expansion forms another palindrome.
            while left >= 0 and right < n and s[left] == s[right]:
                found += 1
                left -= 1
                right += 1

            return found

        for center in range(n):
            # Odd-length palindromes centered on one character.
            count += expand(center, center)

            # Even-length palindromes centered between characters.
            count += expand(center, center + 1)

        return count

Complexity:

  • Time: O(n²), since each of the O(n) centers can expand across O(n) characters.
  • Space: O(1), using only a counter and a few indices.

Common follow-ups

  • How would you find the longest palindromic substring? Track the longest span found during each expansion.
  • How would you count distinct palindrome values instead of occurrences? Store the distinct palindrome strings in a set; this can require O(n²) space.
  • Can this be solved with dynamic programming? Yes: record whether each interval is a palindrome based on its end characters and its inner interval, using O(n²) time and space.
CodingMediumEpic SystemsSoftware Engineer

13. Bulls and Cows (LeetCode)

Model answer

The task

Given two equal-length digit strings, count exact matches and misplaced matches. Format the result as the bull count followed by A and the cow count followed by B.

Key idea

Count exact matches directly. For all other positions, count each digit’s occurrences separately in the unmatched parts of both strings; the overlap of those counts gives the number of cows.

Approach

  1. Create one frequency array for each string, with ten slots for the digits 0 through 9.
  2. Scan the strings together, incrementing the bull count when digits match at the same position.
  3. For nonmatching positions, record each string’s digit in its respective frequency array.
  4. Sum the smaller frequency for each digit to count cows without counting any occurrence more than once.
  5. Format and return both counts.
class Solution:
    def getHint(self, secret: str, guess: str) -> str:
        bulls = 0
        secret_counts = [0] * 10
        guess_counts = [0] * 10

        for secret_digit, guess_digit in zip(secret, guess):
            if secret_digit == guess_digit:
                bulls += 1
            else:
                secret_counts[int(secret_digit)] += 1
                guess_counts[int(guess_digit)] += 1

        cows = sum(
            min(secret_counts[digit], guess_counts[digit])
            for digit in range(10)
        )

        return f"{bulls}A{cows}B"

Complexity:

  • Time: O(n), where n is the length of the strings.
  • Space: O(1), since the frequency arrays always have ten entries.

Common follow-ups

  • What if the strings use a larger character set? Use a hash map for frequencies instead of fixed-size arrays.
  • Can the solution use a single frequency array? Yes; track signed differences while scanning unmatched positions and count cows when a digit’s balance crosses zero.
  • What if the strings can have different lengths? Clarify the desired behavior first; this implementation assumes equal lengths.
CodingMediumEpic SystemsSoftware Engineer

14. Count Primes (LeetCode)

Model answer

The task

Count how many prime numbers are strictly less than n.

Key idea

Use the Sieve of Eratosthenes: initially treat every number as prime, then mark multiples of each prime as composite. It is enough to start marking at p * p, since smaller multiples of p have already been handled.

Approach

  1. Return 0 if n is less than 3.
  2. Create a boolean array marking numbers below n as prime.
  3. Mark 0 and 1 as non-prime.
  4. For each prime p with p p < n, mark its multiples from p p as non-prime.
  5. Sum the remaining prime flags.
class Solution:
    def countPrimes(self, n: int) -> int:
        if n < 3:
            return 0

        # A nonzero byte represents a number still considered prime.
        is_prime = bytearray(b"\x01") * n
        is_prime[0] = is_prime[1] = 0

        p = 2
        while p * p < n:
            if is_prime[p]:
                # Smaller multiples were marked by earlier primes.
                for multiple in range(p * p, n, p):
                    is_prime[multiple] = 0
            p += 1

        return sum(is_prime)

Complexity:

  • Time: O(n log log n), for marking composite numbers.
  • Space: O(n), for the primality flags.

Common follow-ups

  • How would you reduce memory when sieving a very large range? Use a segmented sieve, processing one block at a time.
  • Can you reduce the sieve's memory use? Store flags only for odd numbers and handle 2 separately.
  • What if the task asks for primes up to and including n? Allocate flags through n and adjust the marking and counting bounds.
CodingMediumEpic SystemsSoftware Engineer

15. 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.
CodingHardEpic SystemsSoftware Engineer

16. Longest Increasing Path in a Matrix (LeetCode)

Model answer

The task

Given a matrix of integers, find the length of the longest path that moves between orthogonally adjacent cells and strictly increases at every step. The path may start and end anywhere.

Key idea

Treat each cell as a node, with directed edges to adjacent cells of greater value. This graph has no cycles because values strictly increase along every edge. Memoized DFS computes the longest path starting at each cell, reusing results for overlapping subproblems.

Approach

  1. Return 0 if the matrix is empty.
  2. Create a cache for the longest increasing path starting at each cell.
  3. For an uncached cell, recursively check its four neighbors.
  4. Extend the path only to neighbors with greater values.
  5. The answer is the largest cached path length over all cells.
from functools import lru_cache
from typing import List

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

        rows, cols = len(matrix), len(matrix[0])
        directions = ((1, 0), (-1, 0), (0, 1), (0, -1))

        @lru_cache(maxsize=None)
        def longest_from(row: int, col: int) -> int:
            # The path can always consist of this cell alone.
            best = 1

            for dr, dc in directions:
                nr, nc = row + dr, col + dc

                if (
                    0 <= nr < rows
                    and 0 <= nc < cols
                    and matrix[nr][nc] > matrix[row][col]
                ):
                    best = max(best, 1 + longest_from(nr, nc))

            return best

        return max(
            longest_from(row, col)
            for row in range(rows)
            for col in range(cols)
        )

Complexity:

  • Time: O(rows × cols), since each cell is computed once and checks at most four neighbors.
  • Space: O(rows × cols), for the cache and recursion stack in the worst case.

Common follow-ups

  • What if paths may decrease instead? Reverse the comparison, or negate values and reuse the same logic.
  • How would you avoid recursion-depth limits? Use topological sorting on the directed cell graph.
  • What if diagonal moves are allowed? Add the four diagonal offsets to the neighbor directions.

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