Coding interview questions & answers

20 coding interview questions with complete model answers. The bank holds 19934 coding questions across every role and company we cover.

CodingEasyData ScientistCoding screen

1. Given a pandas DataFrame df with columns ‘Date’, ‘Sales’, and ‘Customer_Rating’, write a Python code snippet to clean this DataFrame.

The full question

Given a pandas DataFrame df with columns ‘Date’, ‘Sales’, and ‘Customer_Rating’, write a Python code snippet to clean this DataFrame. Assume there are missing values in ‘Customer_Rating’ and duplicate rows across all columns. Remove duplicates and replace missing values in ‘Customer_Rating’ with the average rating.

Model answer

The flow

  1. Clarify inputs & output shape: Understand the DataFrame structure and the requirements for cleaning.
  2. Brute force first: Implement straightforward solutions for removing duplicates and handling missing values.
  3. Optimize: Utilize pandas built-in functions to efficiently perform the operations.
  4. State complexity: Consider the time complexity of operations, especially with large datasets.
  5. Test the edges: Ensure the solution handles edge cases like all values missing or no duplicates.

The answer

1. Clarify inputs & output shape

  • We have a DataFrame df with columns Date, Sales, and Customer_Rating.
  • The task is to remove duplicate rows and fill missing values in Customer_Rating with the average rating.

2. Brute force first

  • Start by identifying duplicate rows and removing them.
  • Calculate the average of Customer_Rating and use it to fill missing values.

3. Optimize

  • Use pandas functions like drop_duplicates() and fillna() to efficiently clean the DataFrame.
import pandas as pd

# Sample DataFrame
# df = pd.DataFrame({
#     'Date': [...],
#     'Sales': [...],
#     'Customer_Rating': [...]
# })

# Remove duplicate rows
cleaned_df = df.drop_duplicates()

# Calculate the mean of Customer_Rating, ignoring NaN values
average_rating = cleaned_df['Customer_Rating'].mean()

# Fill missing values in Customer_Rating with the average rating
cleaned_df['Customer_Rating'].fillna(average_rating, inplace=True)
  • Approach:
  • drop_duplicates() removes all duplicate rows based on all columns.
  • mean() calculates the average of Customer_Rating, ignoring NaN values.
  • fillna() replaces NaN values with the calculated average.
  • Complexity: The time complexity is approximately $O(n)$ for both removing duplicates and filling NaN values, where $n$ is the number of rows in the DataFrame.

4. Test the edges

  • Ensure the solution works when all Customer_Rating values are missing, or when there are no duplicates.

Why this works

  • Testing understanding: The interviewer is assessing your ability to use pandas for data cleaning tasks.
  • Efficiency: Using pandas built-in functions ensures operations are performed efficiently on potentially large datasets.
  • Edge cases: A strong answer considers edge cases, such as all values missing or no duplicates, ensuring robustness.
  • Weak answers: Failing to handle missing values correctly or not removing duplicates would indicate a lack of attention to detail or understanding of pandas capabilities.
CodingEasyStaff EngineerLive coding interview

2. Solve a simple game problem while adapting to changing requirements.

Model answer

Assumption: the game is a generalized tic-tac-toe board. The function supports changing board dimensions and win length, rather than hard-coding a 3×3 board.

function gameState(board, target = 3, empty = '.') {
  if (!Array.isArray(board) || board.length === 0 || !Array.isArray(board[0])) {
    throw new Error('Board must be a non-empty 2D array');
  }
  if (!Number.isInteger(target) || target < 1) {
    throw new Error('target must be a positive integer');
  }

  const rows = board.length;
  const cols = board[0].length;
  if (cols === 0 || board.some(row => !Array.isArray(row) || row.length !== cols)) {
    throw new Error('Board must be rectangular and non-empty');
  }

  const directions = [
    [0, 1],   // horizontal
    [1, 0],   // vertical
    [1, 1],   // diagonal down-right
    [1, -1]   // diagonal down-left
  ];
  const winners = new Set();
  let hasEmptyCell = false;

  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      const player = board[r][c];
      if (player === empty) {
        hasEmptyCell = true;
        continue;
      }
      if (typeof player !== 'string') {
        throw new Error('Board cells must be strings');
      }

      // A winning run can start at any occupied cell and extend in four directions.
      for (const [dr, dc] of directions) {
        let length = 1;
        let nr = r + dr;
        let nc = c + dc;
        while (
          length < target &&
          nr >= 0 && nr < rows &&
          nc >= 0 && nc < cols &&
          board[nr][nc] === player
        ) {
          length++;
          nr += dr;
          nc += dc;
        }
        if (length === target) winners.add(player);
      }
    }
  }

  // Multiple winners usually means an invalid game state, not a normal result.
  if (winners.size > 1) return { status: 'invalid', winners: [...winners] };
  if (winners.size === 1) return { status: 'win', winner: [...winners][0] };
  return { status: hasEmptyCell ? 'in_progress' : 'draw' };
}

const board = [
  ['X', 'O', 'X', '.'],
  ['O', 'X', 'O', '.'],
  ['X', 'O', 'X', '.']
];
console.log(gameState(board, 3)); // { status: 'win', winner: 'X' }
  • I made board size, win length, and empty-cell marker configurable so a changed requirement does not require rewriting the algorithm.
  • I scan four directions from each occupied cell and explicitly flag impossible states with multiple winners.
  • Complexity: O(R × C × K) time, where K is the target run length; O(P) extra space for the set of winners, where P is the number of player symbols.
CodingEasySoftware EngineerTechnical Screen

3. You are asked to solve two separate coding questions.

The full question

You are asked to solve two separate coding questions. You do not need to run code; be prepared to explain your approach and walk through examples.

Question 1: Near-palindrome with one deletion

Given a string s, determine whether it can become a palindrome after deleting at most one character.

  • Input: a string s (consisting of lowercase English letters)
  • Output: true if s can be made a palindrome by removing 0 or 1 character; otherwise false
  • Constraints (typical): 1 <= len(s) <= 1e5

Example:

  • s = "abca" → true (delete 'b' or 'c')
  • s = "abc" → false

Question 2: Binary tree vertical order traversal

Given the root of a binary tree, return its vertical order traversal.

Define a node’s column as follows:

  • Root is at column 0
  • Left child is column col - 1
  • Right child is column col + 1

Return a list of columns from leftmost to rightmost. Within each column, list nodes in top-to-bottom order. If multiple nodes share the same row and column, order them in the same order they would appear in a level-order (BFS) traversal from left to right.

  • Input: root of a binary tree
  • Output: List[List[int]] (values grouped by column)
  • Constraints (typical): up to 1e4–1e5 nodes

Example: For the tree:

  • 3 as root
  • left child 9, right child 8
  • 9 has children 4 and 0
  • 8 has children 1 and 7

Vertical order output:

  • [[4], [9], [3, 0, 1], [8], [7]]

Explain your algorithm and its time/space complexity.

Model answer

// Question 1: Near-palindrome with one deletion
function validPalindrome(s) {
    function isPalindrome(l, r) {
        while (l < r) {
            if (s[l] !== s[r]) return false;
            l++;
            r--;
        }
        return true;
    }

    let left = 0;
    let right = s.length - 1;

    while (left < right) {
        if (s[left] !== s[right]) {
            // Try removing one character from either end
            return isPalindrome(left + 1, right) || isPalindrome(left, right - 1);
        }
        left++;
        right--;
    }
    return true;
}

// Approach for Question 1:
// - Use two pointers to check if the string is a palindrome.
// - If a mismatch is found, check if removing one of the mismatched characters results in a palindrome.
// - This is done by checking two substrings: one excluding the left character and one excluding the right character.

// Complexity for Question 1:
// Time: O(n), where n is the length of the string, as we may need to check the entire string.
// Space: O(1), as we use a constant amount of extra space.


// Question 2: Binary tree vertical order traversal
function verticalOrder(root) {
    if (!root) return [];

    const columnTable = new Map();
    const queue = [{ node: root, col: 0 }];
    let minCol = 0, maxCol = 0;

    while (queue.length > 0) {
        const { node, col } = queue.shift();

        if (!columnTable.has(col)) {
            columnTable.set(col, []);
        }
        columnTable.get(col).push(node.val);

        if (node.left) {
            queue.push({ node: node.left, col: col - 1 });
            minCol = Math.min(minCol, col - 1);
        }
        if (node.right) {
            queue.push({ node: node.right, col: col + 1 });
            maxCol = Math.max(maxCol, col + 1);
        }
    }

    const result = [];
    for (let i = minCol; i <= maxCol; i++) {
        result.push(columnTable.get(i));
    }
    return result;
}

// Approach for Question 2:
// - Use a BFS approach to traverse the tree while keeping track of the column index for each node.
// - Store nodes in a map where keys are column indices and values are lists of node values.
// - Track the minimum and maximum column indices to determine the range of columns to output.
// - Collect results from the map in order from the smallest to the largest column index.

// Complexity for Question 2:
// Time: O(n), where n is the number of nodes in the tree, as each node is processed once.
// Space: O(n), for the map and queue used to store nodes and their column indices.
CodingEasyData ScientistTechnical Screen

4. You are given a binary classifier’s outputs on a dataset: y_true: array of true labels in ({0,1}) y_score: array of predicted scores/probabilities…

The full question

You are given a binary classifier’s outputs on a dataset:

  • y_true: array of true labels in ({0,1})
  • y_score: array of predicted scores/probabilities (higher means more likely positive)

Tasks

  1. Define precision and recall.
  2. Describe how to compute the precision–recall curve by sweeping a decision threshold over y_score.
  3. Implement (in pseudocode or Python) a function that returns PR curve points:
  • Output arrays: thresholds, precision, recall
  1. Mention at least two edge cases/pitfalls (e.g., ties in scores, no predicted positives at a threshold, extreme class imbalance).

Optional: Explain how to compute Average Precision / AUPRC and what the baseline means.

Model answer

import numpy as np

def precision_recall_curve(y_true, y_score):
    # Sort scores and corresponding true labels in descending order
    desc_score_indices = np.argsort(y_score)[::-1]
    y_true = np.array(y_true)[desc_score_indices]
    y_score = np.array(y_score)[desc_score_indices]

    # Initialize variables
    thresholds = []
    precision = []
    recall = []
    tp = 0  # True positives
    fp = 0  # False positives
    fn = np.sum(y_true)  # False negatives initially all positives

    # Iterate through scores to calculate precision and recall
    for i in range(len(y_score)):
        if i == 0 or y_score[i] != y_score[i - 1]:
            thresholds.append(y_score[i])
            precision.append(tp / (tp + fp) if (tp + fp) > 0 else 1.0)
            recall.append(tp / (tp + fn) if (tp + fn) > 0 else 0.0)

        if y_true[i] == 1:
            tp += 1
            fn -= 1
        else:
            fp += 1

    # Add the last point at threshold 0
    thresholds.append(0)
    precision.append(tp / (tp + fp) if (tp + fp) > 0 else 1.0)
    recall.append(tp / (tp + fn) if (tp + fn) > 0 else 0.0)

    return thresholds, precision, recall

# Example usage
y_true = [0, 1, 1, 0, 1]
y_score = [0.1, 0.4, 0.35, 0.8, 0.7]
thresholds, precision, recall = precision_recall_curve(y_true, y_score)
print("Thresholds:", thresholds)
print("Precision:", precision)
print("Recall:", recall)
  • Precision is the ratio of true positives to the sum of true positives and false positives. It measures the accuracy of positive predictions.
  • Recall is the ratio of true positives to the sum of true positives and false negatives. It measures the ability to find all positive samples.
  • To compute the precision-recall curve, sort y_score in descending order and iterate over it. For each unique score, calculate precision and recall, updating true positives, false positives, and false negatives accordingly.

Complexity:

  • Time: O(n log n) due to sorting, where n is the number of samples.
  • Space: O(n) for storing sorted indices and result arrays.

Edge Cases/Pitfalls:

  1. Ties in scores: Ensure that precision and recall are calculated correctly when multiple instances have the same score.
  2. No predicted positives: Handle cases where no samples are predicted as positive at a certain threshold, which can lead to division by zero in precision calculation.

Average Precision / AUPRC:

  • Average Precision (AP) is the area under the precision-recall curve. It summarizes the precision-recall trade-off across thresholds. The baseline for AP is the proportion of positive samples in the dataset.
CodingEasyStaff EngineerCoding interview

5. Build a simple app in Xcode.

Model answer

import React, { useState } from "react";
import { SafeAreaView, StyleSheet, Text, Pressable, View } from "react-native";

export default function App() {
  const [count, setCount] = useState(0);

  return (
    <SafeAreaView style={styles.screen}>
      <View style={styles.card}>
        <Text style={styles.title}>Counter</Text>
        <Text style={styles.count} accessibilityLiveRegion="polite">
          {count}
        </Text>
        <View style={styles.buttons}>
          <Pressable
            accessibilityRole="button"
            accessibilityLabel="Decrease count"
            style={styles.button}
            onPress={() => setCount((value) => value - 1)}
          >
            <Text style={styles.buttonText}>−</Text>
          </Pressable>
          <Pressable
            accessibilityRole="button"
            accessibilityLabel="Reset count"
            style={[styles.button, styles.reset]}
            onPress={() => setCount(0)}
          >
            <Text style={styles.buttonText}>Reset</Text>
          </Pressable>
          <Pressable
            accessibilityRole="button"
            accessibilityLabel="Increase count"
            style={styles.button}
            onPress={() => setCount((value) => value + 1)}
          >
            <Text style={styles.buttonText}>+</Text>
          </Pressable>
        </View>
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  screen: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#f2f4f7",
    padding: 24,
  },
  card: {
    width: "100%",
    maxWidth: 420,
    alignItems: "center",
    padding: 32,
    borderRadius: 16,
    backgroundColor: "white",
  },
  title: { fontSize: 28, fontWeight: "700", marginBottom: 16 },
  count: { fontSize: 64, fontWeight: "600", marginBottom: 24 },
  buttons: { flexDirection: "row", alignItems: "center", gap: 12 },
  button: {
    minWidth: 56,
    minHeight: 48,
    justifyContent: "center",
    alignItems: "center",
    paddingHorizontal: 16,
    borderRadius: 10,
    backgroundColor: "#0a66c2",
  },
  reset: { backgroundColor: "#52606d" },
  buttonText: { color: "white", fontSize: 20, fontWeight: "600" },
});
  • This is a small React Native iOS app: create a React Native project, use this component as App.js, then open the generated iOS workspace in Xcode to build and run it in a simulator or on a device.
  • The counter uses component state and functional updates, so rapid presses do not rely on stale state. The controls include accessibility roles and labels.
  • Complexity: O(1) time and O(1) space per interaction.
CodingEasySoftware Engineer

6. Count Numbers With Unique Digits II (LeetCode)

Model answer

The task

The title suggests counting numbers whose decimal digits are all distinct. The exact input format is unclear, so this answer gives a general method for counting such numbers in a nonnegative integer range.

Key idea

Use digit DP to count valid numbers from zero through a bound, then subtract two such counts for a range. Track which digits have appeared in a bitmask; leading zeroes do not count as digits.

Approach

  1. Convert the upper bound to a string and process its digits from left to right.
  2. Track the position, used-digit mask, whether the number has started, and whether the prefix still matches the bound.
  3. For each candidate digit, skip it if it repeats a digit in an already-started number.
  4. At the end, count the formed number, including zero.
  5. For a range [lo, hi], subtract the count through lo - 1 from the count through hi.
from functools import lru_cache

def count_unique_up_to(bound: int) -> int:
    """Count nonnegative integers <= bound with no repeated decimal digits."""
    if bound < 0:
        return 0

    digits = str(bound)

    @lru_cache(maxsize=None)
    def dp(pos: int, mask: int, started: bool, tight: bool) -> int:
        if pos == len(digits):
            # The all-leading-zero path represents the number zero.
            return 1

        limit = int(digits[pos]) if tight else 9
        total = 0

        for digit in range(limit + 1):
            next_tight = tight and digit == limit

            if not started and digit == 0:
                total += dp(pos + 1, mask, False, next_tight)
                continue

            bit = 1 << digit
            if mask & bit:
                continue

            total += dp(pos + 1, mask | bit, True, next_tight)

        return total

    return dp(0, 0, False, True)

def count_unique_in_range(lo: int, hi: int) -> int:
    """Count nonnegative integers in [lo, hi] with no repeated digits."""
    if lo < 0 or hi < lo:
        raise ValueError("Expected 0 <= lo <= hi")
    return count_unique_up_to(hi) - count_unique_up_to(lo - 1)

Complexity:

  • Time: O(L × 2^10 × 10), where L is the number of digits in the bound.
  • Space: O(L × 2^10), for the memoized DP states.

Common follow-ups

  • How would you count only positive numbers? Subtract one to exclude zero.
  • How would you use another base? Replace the digit range and mask size with the base.
  • Can this be optimized for bounds with many digits? The state space is already bounded by the ten possible decimal digits.
CodingEasyData ScientistTechnical Screen

7. Two players play independent games of table tennis.

The full question

Two players play independent games of table tennis.

  • Player A wins each game with probability (p) (constant across games).
  • They play a best-of-5 match (first to 3 wins).
  • Let (X) be the number of games played until the match ends (so (X\in{3,4,5})).

Tasks

1) Compute (\theta = \Pr(X=5)). 2) Write a simulation (Monte Carlo) approach to estimate (\theta). 3) Follow-up: given (M) simulated matches, how would you build a confidence interval for (\theta)?

Model answer

// Function to compute the probability that a match goes to 5 games
function probabilityOfFiveGames(p) {
  // Probability that the match goes to 5 games
  // This happens if both players win 2 games each in the first 4 games
  const prob = 6 * Math.pow(p, 2) * Math.pow(1 - p, 2);
  return prob;
}

// Monte Carlo simulation to estimate the probability of a match going to 5 games
function simulateMatches(numMatches, p) {
  let fiveGameMatches = 0;

  for (let i = 0; i < numMatches; i++) {
    let winsA = 0;
    let winsB = 0;
    let gamesPlayed = 0;

    while (winsA < 3 && winsB < 3) {
      gamesPlayed++;
      if (Math.random() < p) {
        winsA++;
      } else {
        winsB++;
      }
    }

    if (gamesPlayed === 5) {
      fiveGameMatches++;
    }
  }

  return fiveGameMatches / numMatches;
}

// Function to build a confidence interval for the estimated probability
function confidenceInterval(numMatches, p, confidenceLevel = 0.95) {
  const thetaEstimate = simulateMatches(numMatches, p);
  const z = 1.96; // z-score for 95% confidence
  const marginOfError = z * Math.sqrt((thetaEstimate * (1 - thetaEstimate)) / numMatches);

  return [thetaEstimate - marginOfError, thetaEstimate + marginOfError];
}

// Example usage
const p = 0.5; // Probability that player A wins a game
const numMatches = 10000; // Number of simulated matches
console.log("Probability of 5 games (analytical):", probabilityOfFiveGames(p));
console.log("Probability of 5 games (simulation):", simulateMatches(numMatches, p));
console.log("95% Confidence Interval:", confidenceInterval(numMatches, p));
  • Analytical Calculation: The probability that a match goes to 5 games is calculated by considering the scenarios where both players win exactly 2 games each in the first 4 games. This is given by \(6 \times p^2 \times (1-p)^2\), where 6 is the number of ways to arrange 2 wins for each player in 4 games.
  • Monte Carlo Simulation: Simulate a large number of matches, counting how many go to 5 games. For each match, simulate games until one player wins 3 games. Count matches where exactly 5 games are played.
  • Confidence Interval: Use the normal approximation for the binomial distribution to calculate the confidence interval for the estimated probability. The margin of error is calculated using the standard error and the z-score for the desired confidence level.

Complexity:

  • Time: \(O(M)\) for the simulation, where \(M\) is the number of matches.
  • Space: \(O(1)\), constant space usage.
CodingEasySoftware Engineer

8. Fruits Into Baskets II (LeetCode)

Model answer

The task

Process fruit quantities in order, assigning each to the leftmost unused basket whose capacity is large enough. Count how many fruit types cannot be assigned.

Key idea

Store the maximum capacity in each segment of a segment tree. This lets us find the leftmost basket that fits a fruit and mark that basket as used in logarithmic time.

Approach

  1. Build a segment tree whose leaves hold basket capacities and whose internal nodes hold the maximum capacity in their range.
  2. For each fruit, check whether the tree’s maximum capacity is sufficient.
  3. If it is, descend the tree, preferring the left child whenever it can fit the fruit.
  4. Mark the chosen basket as used and update the maxima on the path back up.
  5. Count fruits for which no basket is available.
from typing import List

class Solution:
    def numOfUnplacedFruits(
        self, fruits: List[int], baskets: List[int]
    ) -> int:
        n = len(baskets)
        if n == 0:
            return len(fruits)

        tree = [0] * (4 * n)

        def build(node: int, left: int, right: int) -> None:
            if left == right:
                tree[node] = baskets[left]
                return

            mid = (left + right) // 2
            build(node * 2, left, mid)
            build(node * 2 + 1, mid + 1, right)
            tree[node] = max(tree[node * 2], tree[node * 2 + 1])

        def take_leftmost(node: int, left: int, right: int, need: int) -> int:
            if left == right:
                tree[node] = 0  # This basket is now used.
                return left

            mid = (left + right) // 2
            if tree[node * 2] >= need:
                index = take_leftmost(node * 2, left, mid, need)
            else:
                index = take_leftmost(node * 2 + 1, mid + 1, right, need)

            tree[node] = max(tree[node * 2], tree[node * 2 + 1])
            return index

        build(1, 0, n - 1)

        unplaced = 0
        for amount in fruits:
            if tree[1] < amount:
                unplaced += 1
            else:
                take_leftmost(1, 0, n - 1, amount)

        return unplaced

Complexity:

  • Time: O(n + m log n), where n is the number of baskets and m is the number of fruits.
  • Space: O(n) for the segment tree.

Common follow-ups

  • What if baskets can be reused? Do not remove a basket after assignment; each fruit can independently check for a fitting capacity.
  • What if we need to report the chosen basket for each fruit? Record the returned index from the tree descent.
  • Could a simple scan work? Yes, it takes O(nm) in the worst case and may be adequate for small inputs.
CodingEasySoftware Engineer

9. Fruits Into Baskets II (LeetCode)

Model answer

The task

Process fruit quantities in order, assigning each to the leftmost unused basket whose capacity is large enough. Count how many fruit types cannot be assigned.

Key idea

Store the maximum capacity in each segment of a segment tree. This lets us find the leftmost basket that fits a fruit and mark that basket as used in logarithmic time.

Approach

  1. Build a segment tree whose leaves hold basket capacities and whose internal nodes hold the maximum capacity in their range.
  2. For each fruit, check whether the tree’s maximum capacity is sufficient.
  3. If it is, descend the tree, preferring the left child whenever it can fit the fruit.
  4. Mark the chosen basket as used and update the maxima on the path back up.
  5. Count fruits for which no basket is available.
from typing import List

class Solution:
    def numOfUnplacedFruits(
        self, fruits: List[int], baskets: List[int]
    ) -> int:
        n = len(baskets)
        if n == 0:
            return len(fruits)

        tree = [0] * (4 * n)

        def build(node: int, left: int, right: int) -> None:
            if left == right:
                tree[node] = baskets[left]
                return

            mid = (left + right) // 2
            build(node * 2, left, mid)
            build(node * 2 + 1, mid + 1, right)
            tree[node] = max(tree[node * 2], tree[node * 2 + 1])

        def take_leftmost(node: int, left: int, right: int, need: int) -> int:
            if left == right:
                tree[node] = 0  # This basket is now used.
                return left

            mid = (left + right) // 2
            if tree[node * 2] >= need:
                index = take_leftmost(node * 2, left, mid, need)
            else:
                index = take_leftmost(node * 2 + 1, mid + 1, right, need)

            tree[node] = max(tree[node * 2], tree[node * 2 + 1])
            return index

        build(1, 0, n - 1)

        unplaced = 0
        for amount in fruits:
            if tree[1] < amount:
                unplaced += 1
            else:
                take_leftmost(1, 0, n - 1, amount)

        return unplaced

Complexity:

  • Time: O(n + m log n), where n is the number of baskets and m is the number of fruits.
  • Space: O(n) for the segment tree.

Common follow-ups

  • What if baskets can be reused? Do not remove a basket after assignment; each fruit can independently check for a fitting capacity.
  • What if we need to report the chosen basket for each fruit? Record the returned index from the tree descent.
  • Could a simple scan work? Yes, it takes O(nm) in the worst case and may be adequate for small inputs.
CodingEasySoftware Engineer

10. Fruits Into Baskets II (LeetCode)

Model answer

The task

Process fruit quantities in order, assigning each to the leftmost unused basket whose capacity is large enough. Count how many fruit types cannot be assigned.

Key idea

Store the maximum capacity in each segment of a segment tree. This lets us find the leftmost basket that fits a fruit and mark that basket as used in logarithmic time.

Approach

  1. Build a segment tree whose leaves hold basket capacities and whose internal nodes hold the maximum capacity in their range.
  2. For each fruit, check whether the tree’s maximum capacity is sufficient.
  3. If it is, descend the tree, preferring the left child whenever it can fit the fruit.
  4. Mark the chosen basket as used and update the maxima on the path back up.
  5. Count fruits for which no basket is available.
from typing import List

class Solution:
    def numOfUnplacedFruits(
        self, fruits: List[int], baskets: List[int]
    ) -> int:
        n = len(baskets)
        if n == 0:
            return len(fruits)

        tree = [0] * (4 * n)

        def build(node: int, left: int, right: int) -> None:
            if left == right:
                tree[node] = baskets[left]
                return

            mid = (left + right) // 2
            build(node * 2, left, mid)
            build(node * 2 + 1, mid + 1, right)
            tree[node] = max(tree[node * 2], tree[node * 2 + 1])

        def take_leftmost(node: int, left: int, right: int, need: int) -> int:
            if left == right:
                tree[node] = 0  # This basket is now used.
                return left

            mid = (left + right) // 2
            if tree[node * 2] >= need:
                index = take_leftmost(node * 2, left, mid, need)
            else:
                index = take_leftmost(node * 2 + 1, mid + 1, right, need)

            tree[node] = max(tree[node * 2], tree[node * 2 + 1])
            return index

        build(1, 0, n - 1)

        unplaced = 0
        for amount in fruits:
            if tree[1] < amount:
                unplaced += 1
            else:
                take_leftmost(1, 0, n - 1, amount)

        return unplaced

Complexity:

  • Time: O(n + m log n), where n is the number of baskets and m is the number of fruits.
  • Space: O(n) for the segment tree.

Common follow-ups

  • What if baskets can be reused? Do not remove a basket after assignment; each fruit can independently check for a fitting capacity.
  • What if we need to report the chosen basket for each fruit? Record the returned index from the tree descent.
  • Could a simple scan work? Yes, it takes O(nm) in the worst case and may be adequate for small inputs.
CodingEasySoftware Engineer

11. Fruits Into Baskets II (LeetCode)

Model answer

The task

Process fruit quantities in order, assigning each to the leftmost unused basket whose capacity is large enough. Count how many fruit types cannot be assigned.

Key idea

Store the maximum capacity in each segment of a segment tree. This lets us find the leftmost basket that fits a fruit and mark that basket as used in logarithmic time.

Approach

  1. Build a segment tree whose leaves hold basket capacities and whose internal nodes hold the maximum capacity in their range.
  2. For each fruit, check whether the tree’s maximum capacity is sufficient.
  3. If it is, descend the tree, preferring the left child whenever it can fit the fruit.
  4. Mark the chosen basket as used and update the maxima on the path back up.
  5. Count fruits for which no basket is available.
from typing import List

class Solution:
    def numOfUnplacedFruits(
        self, fruits: List[int], baskets: List[int]
    ) -> int:
        n = len(baskets)
        if n == 0:
            return len(fruits)

        tree = [0] * (4 * n)

        def build(node: int, left: int, right: int) -> None:
            if left == right:
                tree[node] = baskets[left]
                return

            mid = (left + right) // 2
            build(node * 2, left, mid)
            build(node * 2 + 1, mid + 1, right)
            tree[node] = max(tree[node * 2], tree[node * 2 + 1])

        def take_leftmost(node: int, left: int, right: int, need: int) -> int:
            if left == right:
                tree[node] = 0  # This basket is now used.
                return left

            mid = (left + right) // 2
            if tree[node * 2] >= need:
                index = take_leftmost(node * 2, left, mid, need)
            else:
                index = take_leftmost(node * 2 + 1, mid + 1, right, need)

            tree[node] = max(tree[node * 2], tree[node * 2 + 1])
            return index

        build(1, 0, n - 1)

        unplaced = 0
        for amount in fruits:
            if tree[1] < amount:
                unplaced += 1
            else:
                take_leftmost(1, 0, n - 1, amount)

        return unplaced

Complexity:

  • Time: O(n + m log n), where n is the number of baskets and m is the number of fruits.
  • Space: O(n) for the segment tree.

Common follow-ups

  • What if baskets can be reused? Do not remove a basket after assignment; each fruit can independently check for a fitting capacity.
  • What if we need to report the chosen basket for each fruit? Record the returned index from the tree descent.
  • Could a simple scan work? Yes, it takes O(nm) in the worst case and may be adequate for small inputs.
CodingEasySoftware Engineer

12. Fruits Into Baskets II (LeetCode)

Model answer

The task

Process fruit quantities in order, assigning each to the leftmost unused basket whose capacity is large enough. Count how many fruit types cannot be assigned.

Key idea

Store the maximum capacity in each segment of a segment tree. This lets us find the leftmost basket that fits a fruit and mark that basket as used in logarithmic time.

Approach

  1. Build a segment tree whose leaves hold basket capacities and whose internal nodes hold the maximum capacity in their range.
  2. For each fruit, check whether the tree’s maximum capacity is sufficient.
  3. If it is, descend the tree, preferring the left child whenever it can fit the fruit.
  4. Mark the chosen basket as used and update the maxima on the path back up.
  5. Count fruits for which no basket is available.
from typing import List

class Solution:
    def numOfUnplacedFruits(
        self, fruits: List[int], baskets: List[int]
    ) -> int:
        n = len(baskets)
        if n == 0:
            return len(fruits)

        tree = [0] * (4 * n)

        def build(node: int, left: int, right: int) -> None:
            if left == right:
                tree[node] = baskets[left]
                return

            mid = (left + right) // 2
            build(node * 2, left, mid)
            build(node * 2 + 1, mid + 1, right)
            tree[node] = max(tree[node * 2], tree[node * 2 + 1])

        def take_leftmost(node: int, left: int, right: int, need: int) -> int:
            if left == right:
                tree[node] = 0  # This basket is now used.
                return left

            mid = (left + right) // 2
            if tree[node * 2] >= need:
                index = take_leftmost(node * 2, left, mid, need)
            else:
                index = take_leftmost(node * 2 + 1, mid + 1, right, need)

            tree[node] = max(tree[node * 2], tree[node * 2 + 1])
            return index

        build(1, 0, n - 1)

        unplaced = 0
        for amount in fruits:
            if tree[1] < amount:
                unplaced += 1
            else:
                take_leftmost(1, 0, n - 1, amount)

        return unplaced

Complexity:

  • Time: O(n + m log n), where n is the number of baskets and m is the number of fruits.
  • Space: O(n) for the segment tree.

Common follow-ups

  • What if baskets can be reused? Do not remove a basket after assignment; each fruit can independently check for a fitting capacity.
  • What if we need to report the chosen basket for each fruit? Record the returned index from the tree descent.
  • Could a simple scan work? Yes, it takes O(nm) in the worst case and may be adequate for small inputs.
CodingEasySoftware Engineer

13. Subtree of Another Tree (LeetCode)

Model answer

The task

Determine whether one binary tree occurs in another as a subtree: both the node values and the tree structure must match.

Key idea

Serialize each tree in preorder, recording a marker for every missing child. These markers preserve structure, so the smaller tree is a subtree exactly when its serialization appears contiguously in the larger tree’s serialization. Use KMP to search in linear time.

Approach

  1. Treat an empty candidate tree as a subtree.
  2. Serialize each tree in preorder, using None to represent missing nodes.
  3. Build the KMP prefix table for the candidate serialization.
  4. Scan the larger serialization with KMP and return whether the candidate is found.
class Solution:
    def isSubtree(self, root, subRoot):
        if subRoot is None:
            return True

        def serialize(node):
            tokens = []

            def visit(current):
                if current is None:
                    tokens.append(None)
                    return

                tokens.append(current.val)
                visit(current.left)
                visit(current.right)

            visit(node)
            return tokens

        text = serialize(root)
        pattern = serialize(subRoot)

        # Build the KMP prefix table.
        prefix = [0] * len(pattern)
        matched = 0

        for i in range(1, len(pattern)):
            while matched and pattern[i] != pattern[matched]:
                matched = prefix[matched - 1]

            if pattern[i] == pattern[matched]:
                matched += 1
                prefix[i] = matched

        # Search for the candidate serialization.
        matched = 0
        for token in text:
            while matched and token != pattern[matched]:
                matched = prefix[matched - 1]

            if token == pattern[matched]:
                matched += 1
                if matched == len(pattern):
                    return True

        return False

Complexity:

  • Time: O(n + m), where n and m are the numbers of nodes in the two trees.
  • Space: O(n + m) for the serialized tokens and KMP prefix table.

Common follow-ups

  • Can this be done without serialization? Try matching the candidate at every node; the worst case is O(nm).
  • What if many subtree queries use the same main tree? Cache a structural hash for each node, then verify matches to guard against collisions.
  • How do you avoid recursion-depth issues on skewed trees? Serialize iteratively with an explicit stack.
CodingEasySoftware Engineer

14. Subtree of Another Tree (LeetCode)

Model answer

The task

Determine whether one binary tree occurs in another as a subtree: both the node values and the tree structure must match.

Key idea

Serialize each tree in preorder, recording a marker for every missing child. These markers preserve structure, so the smaller tree is a subtree exactly when its serialization appears contiguously in the larger tree’s serialization. Use KMP to search in linear time.

Approach

  1. Treat an empty candidate tree as a subtree.
  2. Serialize each tree in preorder, using None to represent missing nodes.
  3. Build the KMP prefix table for the candidate serialization.
  4. Scan the larger serialization with KMP and return whether the candidate is found.
class Solution:
    def isSubtree(self, root, subRoot):
        if subRoot is None:
            return True

        def serialize(node):
            tokens = []

            def visit(current):
                if current is None:
                    tokens.append(None)
                    return

                tokens.append(current.val)
                visit(current.left)
                visit(current.right)

            visit(node)
            return tokens

        text = serialize(root)
        pattern = serialize(subRoot)

        # Build the KMP prefix table.
        prefix = [0] * len(pattern)
        matched = 0

        for i in range(1, len(pattern)):
            while matched and pattern[i] != pattern[matched]:
                matched = prefix[matched - 1]

            if pattern[i] == pattern[matched]:
                matched += 1
                prefix[i] = matched

        # Search for the candidate serialization.
        matched = 0
        for token in text:
            while matched and token != pattern[matched]:
                matched = prefix[matched - 1]

            if token == pattern[matched]:
                matched += 1
                if matched == len(pattern):
                    return True

        return False

Complexity:

  • Time: O(n + m), where n and m are the numbers of nodes in the two trees.
  • Space: O(n + m) for the serialized tokens and KMP prefix table.

Common follow-ups

  • Can this be done without serialization? Try matching the candidate at every node; the worst case is O(nm).
  • What if many subtree queries use the same main tree? Cache a structural hash for each node, then verify matches to guard against collisions.
  • How do you avoid recursion-depth issues on skewed trees? Serialize iteratively with an explicit stack.
CodingEasySoftware Engineer

15. Subtree of Another Tree (LeetCode)

Model answer

The task

Determine whether one binary tree occurs in another as a subtree: both the node values and the tree structure must match.

Key idea

Serialize each tree in preorder, recording a marker for every missing child. These markers preserve structure, so the smaller tree is a subtree exactly when its serialization appears contiguously in the larger tree’s serialization. Use KMP to search in linear time.

Approach

  1. Treat an empty candidate tree as a subtree.
  2. Serialize each tree in preorder, using None to represent missing nodes.
  3. Build the KMP prefix table for the candidate serialization.
  4. Scan the larger serialization with KMP and return whether the candidate is found.
class Solution:
    def isSubtree(self, root, subRoot):
        if subRoot is None:
            return True

        def serialize(node):
            tokens = []

            def visit(current):
                if current is None:
                    tokens.append(None)
                    return

                tokens.append(current.val)
                visit(current.left)
                visit(current.right)

            visit(node)
            return tokens

        text = serialize(root)
        pattern = serialize(subRoot)

        # Build the KMP prefix table.
        prefix = [0] * len(pattern)
        matched = 0

        for i in range(1, len(pattern)):
            while matched and pattern[i] != pattern[matched]:
                matched = prefix[matched - 1]

            if pattern[i] == pattern[matched]:
                matched += 1
                prefix[i] = matched

        # Search for the candidate serialization.
        matched = 0
        for token in text:
            while matched and token != pattern[matched]:
                matched = prefix[matched - 1]

            if token == pattern[matched]:
                matched += 1
                if matched == len(pattern):
                    return True

        return False

Complexity:

  • Time: O(n + m), where n and m are the numbers of nodes in the two trees.
  • Space: O(n + m) for the serialized tokens and KMP prefix table.

Common follow-ups

  • Can this be done without serialization? Try matching the candidate at every node; the worst case is O(nm).
  • What if many subtree queries use the same main tree? Cache a structural hash for each node, then verify matches to guard against collisions.
  • How do you avoid recursion-depth issues on skewed trees? Serialize iteratively with an explicit stack.
CodingEasySoftware Engineer

16. Subtree of Another Tree (LeetCode)

Model answer

The task

Determine whether one binary tree occurs in another as a subtree: both the node values and the tree structure must match.

Key idea

Serialize each tree in preorder, recording a marker for every missing child. These markers preserve structure, so the smaller tree is a subtree exactly when its serialization appears contiguously in the larger tree’s serialization. Use KMP to search in linear time.

Approach

  1. Treat an empty candidate tree as a subtree.
  2. Serialize each tree in preorder, using None to represent missing nodes.
  3. Build the KMP prefix table for the candidate serialization.
  4. Scan the larger serialization with KMP and return whether the candidate is found.
class Solution:
    def isSubtree(self, root, subRoot):
        if subRoot is None:
            return True

        def serialize(node):
            tokens = []

            def visit(current):
                if current is None:
                    tokens.append(None)
                    return

                tokens.append(current.val)
                visit(current.left)
                visit(current.right)

            visit(node)
            return tokens

        text = serialize(root)
        pattern = serialize(subRoot)

        # Build the KMP prefix table.
        prefix = [0] * len(pattern)
        matched = 0

        for i in range(1, len(pattern)):
            while matched and pattern[i] != pattern[matched]:
                matched = prefix[matched - 1]

            if pattern[i] == pattern[matched]:
                matched += 1
                prefix[i] = matched

        # Search for the candidate serialization.
        matched = 0
        for token in text:
            while matched and token != pattern[matched]:
                matched = prefix[matched - 1]

            if token == pattern[matched]:
                matched += 1
                if matched == len(pattern):
                    return True

        return False

Complexity:

  • Time: O(n + m), where n and m are the numbers of nodes in the two trees.
  • Space: O(n + m) for the serialized tokens and KMP prefix table.

Common follow-ups

  • Can this be done without serialization? Try matching the candidate at every node; the worst case is O(nm).
  • What if many subtree queries use the same main tree? Cache a structural hash for each node, then verify matches to guard against collisions.
  • How do you avoid recursion-depth issues on skewed trees? Serialize iteratively with an explicit stack.
CodingEasySoftware Engineer

17. Subtree of Another Tree (LeetCode)

Model answer

The task

Determine whether one binary tree occurs in another as a subtree: both the node values and the tree structure must match.

Key idea

Serialize each tree in preorder, recording a marker for every missing child. These markers preserve structure, so the smaller tree is a subtree exactly when its serialization appears contiguously in the larger tree’s serialization. Use KMP to search in linear time.

Approach

  1. Treat an empty candidate tree as a subtree.
  2. Serialize each tree in preorder, using None to represent missing nodes.
  3. Build the KMP prefix table for the candidate serialization.
  4. Scan the larger serialization with KMP and return whether the candidate is found.
class Solution:
    def isSubtree(self, root, subRoot):
        if subRoot is None:
            return True

        def serialize(node):
            tokens = []

            def visit(current):
                if current is None:
                    tokens.append(None)
                    return

                tokens.append(current.val)
                visit(current.left)
                visit(current.right)

            visit(node)
            return tokens

        text = serialize(root)
        pattern = serialize(subRoot)

        # Build the KMP prefix table.
        prefix = [0] * len(pattern)
        matched = 0

        for i in range(1, len(pattern)):
            while matched and pattern[i] != pattern[matched]:
                matched = prefix[matched - 1]

            if pattern[i] == pattern[matched]:
                matched += 1
                prefix[i] = matched

        # Search for the candidate serialization.
        matched = 0
        for token in text:
            while matched and token != pattern[matched]:
                matched = prefix[matched - 1]

            if token == pattern[matched]:
                matched += 1
                if matched == len(pattern):
                    return True

        return False

Complexity:

  • Time: O(n + m), where n and m are the numbers of nodes in the two trees.
  • Space: O(n + m) for the serialized tokens and KMP prefix table.

Common follow-ups

  • Can this be done without serialization? Try matching the candidate at every node; the worst case is O(nm).
  • What if many subtree queries use the same main tree? Cache a structural hash for each node, then verify matches to guard against collisions.
  • How do you avoid recursion-depth issues on skewed trees? Serialize iteratively with an explicit stack.
CodingEasySoftware Engineer

18. Subtree of Another Tree (LeetCode)

Model answer

The task

Determine whether one binary tree occurs in another as a subtree: both the node values and the tree structure must match.

Key idea

Serialize each tree in preorder, recording a marker for every missing child. These markers preserve structure, so the smaller tree is a subtree exactly when its serialization appears contiguously in the larger tree’s serialization. Use KMP to search in linear time.

Approach

  1. Treat an empty candidate tree as a subtree.
  2. Serialize each tree in preorder, using None to represent missing nodes.
  3. Build the KMP prefix table for the candidate serialization.
  4. Scan the larger serialization with KMP and return whether the candidate is found.
class Solution:
    def isSubtree(self, root, subRoot):
        if subRoot is None:
            return True

        def serialize(node):
            tokens = []

            def visit(current):
                if current is None:
                    tokens.append(None)
                    return

                tokens.append(current.val)
                visit(current.left)
                visit(current.right)

            visit(node)
            return tokens

        text = serialize(root)
        pattern = serialize(subRoot)

        # Build the KMP prefix table.
        prefix = [0] * len(pattern)
        matched = 0

        for i in range(1, len(pattern)):
            while matched and pattern[i] != pattern[matched]:
                matched = prefix[matched - 1]

            if pattern[i] == pattern[matched]:
                matched += 1
                prefix[i] = matched

        # Search for the candidate serialization.
        matched = 0
        for token in text:
            while matched and token != pattern[matched]:
                matched = prefix[matched - 1]

            if token == pattern[matched]:
                matched += 1
                if matched == len(pattern):
                    return True

        return False

Complexity:

  • Time: O(n + m), where n and m are the numbers of nodes in the two trees.
  • Space: O(n + m) for the serialized tokens and KMP prefix table.

Common follow-ups

  • Can this be done without serialization? Try matching the candidate at every node; the worst case is O(nm).
  • What if many subtree queries use the same main tree? Cache a structural hash for each node, then verify matches to guard against collisions.
  • How do you avoid recursion-depth issues on skewed trees? Serialize iteratively with an explicit stack.
CodingEasySoftware Engineer

19. Subtree of Another Tree (LeetCode)

Model answer

The task

Determine whether one binary tree occurs in another as a subtree: both the node values and the tree structure must match.

Key idea

Serialize each tree in preorder, recording a marker for every missing child. These markers preserve structure, so the smaller tree is a subtree exactly when its serialization appears contiguously in the larger tree’s serialization. Use KMP to search in linear time.

Approach

  1. Treat an empty candidate tree as a subtree.
  2. Serialize each tree in preorder, using None to represent missing nodes.
  3. Build the KMP prefix table for the candidate serialization.
  4. Scan the larger serialization with KMP and return whether the candidate is found.
class Solution:
    def isSubtree(self, root, subRoot):
        if subRoot is None:
            return True

        def serialize(node):
            tokens = []

            def visit(current):
                if current is None:
                    tokens.append(None)
                    return

                tokens.append(current.val)
                visit(current.left)
                visit(current.right)

            visit(node)
            return tokens

        text = serialize(root)
        pattern = serialize(subRoot)

        # Build the KMP prefix table.
        prefix = [0] * len(pattern)
        matched = 0

        for i in range(1, len(pattern)):
            while matched and pattern[i] != pattern[matched]:
                matched = prefix[matched - 1]

            if pattern[i] == pattern[matched]:
                matched += 1
                prefix[i] = matched

        # Search for the candidate serialization.
        matched = 0
        for token in text:
            while matched and token != pattern[matched]:
                matched = prefix[matched - 1]

            if token == pattern[matched]:
                matched += 1
                if matched == len(pattern):
                    return True

        return False

Complexity:

  • Time: O(n + m), where n and m are the numbers of nodes in the two trees.
  • Space: O(n + m) for the serialized tokens and KMP prefix table.

Common follow-ups

  • Can this be done without serialization? Try matching the candidate at every node; the worst case is O(nm).
  • What if many subtree queries use the same main tree? Cache a structural hash for each node, then verify matches to guard against collisions.
  • How do you avoid recursion-depth issues on skewed trees? Serialize iteratively with an explicit stack.
CodingEasySoftware Engineer

20. Shortest Subarray With OR at Least K I (LeetCode)

Model answer

The task

Find the length of the shortest non-empty contiguous subarray whose bitwise OR is at least k. Return -1 if no such subarray exists.

Key idea

A sliding window works because adding elements can only add set bits to its OR, but removing an element may clear a bit only if no other window element has it. Track how many times each bit appears so the window OR can be updated correctly as its left edge moves.

Approach

  1. Keep a count for each bit position and the OR of the current window.
  2. Expand the window one element at a time, adding its set bits to the counts.
  3. While the window OR is at least k, record its length and remove its leftmost element.
  4. When a bit’s count drops to zero, clear that bit from the window OR.
  5. Return the shortest length found, or -1 if none was found.
from typing import List

class Solution:
    def minimumSubarrayLength(self, nums: List[int], k: int) -> int:
        if not nums:
            return -1

        bit_count = [0] * max(1, max(nums).bit_length())
        window_or = 0
        left = 0
        shortest = len(nums) + 1

        for right, value in enumerate(nums):
            # Add this value's set bits to the window.
            for bit in range(len(bit_count)):
                mask = 1 << bit
                if value & mask:
                    bit_count[bit] += 1
                    window_or |= mask

            # Shrink while the current window satisfies the target.
            while left <= right and window_or >= k:
                shortest = min(shortest, right - left + 1)

                outgoing = nums[left]
                for bit in range(len(bit_count)):
                    mask = 1 << bit
                    if outgoing & mask:
                        bit_count[bit] -= 1
                        if bit_count[bit] == 0:
                            window_or &= ~mask

                left += 1

        return shortest if shortest <= len(nums) else -1

Complexity:

  • Time: O(nB), where B is the number of bit positions needed for the input values.
  • Space: O(B) for the per-bit counts.

Common follow-ups

  • What if the condition were OR equal to k? Track qualifying windows carefully; “at least” no longer gives the same shrink condition.
  • Can bit updates be made faster? Iterate only over set bits of each value rather than over all B positions.
  • What if the operation were bitwise AND? Maintain per-bit counts and consider how bits change as the window expands and shrinks.

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