X (Twitter) interview questions & answers

20 real X (Twitter) interview questions with full model answers — Coding, Product & growth. Drawn from the same verified bank ChannelPulse drills from (67 X (Twitter) questions in total).

CodingEasyX (Twitter)Software Engineer

1. Happy Number (LeetCode)

Model answer

The task

Determine whether repeatedly replacing a positive integer with the sum of the squares of its digits eventually reaches 1. If the sequence loops without reaching 1, the number is not happy.

Key idea

The digit transformation is deterministic, so the sequence either reaches 1 or eventually repeats a value. Floyd’s cycle-finding algorithm detects a repeat using two pointers and constant extra space.

Approach

  1. Define a helper that computes the sum of the squared digits of a number.
  2. Start a slow pointer at the input and a fast pointer one transformation ahead.
  3. Advance the slow pointer once and the fast pointer twice per iteration.
  4. Stop if the fast pointer reaches 1 or the pointers meet.
  5. Return whether the fast pointer reached 1.
class Solution:
    def isHappy(self, n: int) -> bool:
        def next_value(value: int) -> int:
            total = 0
            while value > 0:
                digit = value % 10
                total += digit * digit
                value //= 10
            return total

        slow = n
        fast = next_value(n)

        while fast != 1 and slow != fast:
            slow = next_value(slow)
            fast = next_value(next_value(fast))

        return fast == 1

Complexity:

  • Time: O(log n), since digit transformations rapidly reduce the value and each transformation processes its digits.
  • Space: O(1), because only two pointers and a few temporary values are used.

Common follow-ups

  • How can a set solve this? Store values as they appear; a repeated value proves a cycle, using O(k) extra space for k visited values.
  • What if the transformation changes? The cycle-detection method still works for any deterministic transformation.
  • How would you test edge cases? Check 1, a known happy value, and values whose sequences enter a non-1 cycle.
CodingEasyX (Twitter)Software 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.
CodingEasyX (Twitter)Software Engineer

3. Pascal's Triangle (LeetCode)

Model answer

The task

Given a number of rows, build Pascal’s Triangle up to that many rows. Each row starts and ends with 1, and each interior value is the sum of the two values above it.

Key idea

Construct rows from top to bottom. For each new row, use the previous row to compute its interior values.

Approach

  1. Start with an empty list of rows.
  2. For each row index, create a row of the required length filled with 1s.
  3. For interior positions, add the two relevant values from the preceding row.
  4. Append the completed row and return all rows.
from typing import List

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        triangle: List[List[int]] = []

        for row_index in range(numRows):
            # The first and last entries are always 1.
            row = [1] * (row_index + 1)

            # Compute interior entries from the previous row.
            if row_index > 1:
                previous = triangle[-1]
                for column in range(1, row_index):
                    row[column] = previous[column - 1] + previous[column]

            triangle.append(row)

        return triangle

Complexity:

  • Time: O(n²), since the total number of entries generated is proportional to the square of the number of rows.
  • Space: O(n²), to store the returned triangle.

Common follow-ups

  • Return only the row at a given index: build rows iteratively while retaining only the current row.
  • Generate a row using binomial coefficients: compute each value from the preceding value in constant time.
  • Reduce auxiliary space: update one row in place, working from right to left so earlier values remain available.
CodingEasyX (Twitter)Software Engineer

4. Time Needed to Buy Tickets (LeetCode)

Model answer

The task

Given how many tickets each person wants and a target person’s position in the queue, find how many seconds pass before that person gets all their tickets. Each turn, the person at the front buys one ticket if they still need one, then leaves or goes to the back of the queue.

Key idea

Count purchases only up to the target person’s final turn. People before the target can buy at most as many tickets as the target; people after the target get one fewer opportunity.

Approach

  1. Let limit be the number of tickets the target person needs.
  2. For each person at or before the target, count min(tickets[i], limit) purchases.
  3. For each person after the target, count min(tickets[i], limit - 1) purchases.
  4. Sum these counts to get the elapsed time.
from typing import List

class Solution:
    def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
        limit = tickets[k]
        seconds = 0

        for i, needed in enumerate(tickets):
            if i <= k:
                seconds += min(needed, limit)
            else:
                seconds += min(needed, limit - 1)

        return seconds

Complexity:

  • Time: O(n), where n is the number of people in the queue.
  • Space: O(1), using only a few variables.

Common follow-ups

  • What if the target is at the front or back? The same formula handles both positions.
  • What if everyone needs the same number of tickets? The formula counts the target’s final round and excludes later people from that round.
  • Could this be simulated directly? Yes, but simulation may take time proportional to the total number of tickets; the counting formula takes O(n).
CodingEasyX (Twitter)Software Engineer

5. Binary Gap (LeetCode)

Model answer

The task

Given a positive integer, find the largest distance between two consecutive 1 bits in its binary representation. Return 0 if there are fewer than two 1 bits.

Key idea

Scan the bits from least significant to most significant. Track the position of the previous 1 bit, and update the largest distance whenever another 1 is found.

Approach

  1. Initialize the bit position, previous 1 position, and maximum gap.
  2. While any bits remain, check whether the current least significant bit is 1.
  3. If so, measure its distance from the previous 1 and update the maximum.
  4. Shift right to examine the next bit.
  5. Return the maximum gap.
class Solution:
    def binaryGap(self, n: int) -> int:
        position = 0
        previous_one = -1
        largest_gap = 0

        while n:
            if n & 1:
                if previous_one != -1:
                    largest_gap = max(largest_gap, position - previous_one)
                previous_one = position

            n >>= 1
            position += 1

        return largest_gap

Complexity:

  • Time: O(log n), since each bit is examined once.
  • Space: O(1), using a fixed number of variables.

Common follow-ups

  • What if the number has fewer than two 1 bits? The maximum remains 0.
  • Can this be done by scanning a binary string? Yes; track the indices of consecutive 1 characters.
  • How would you find the minimum gap instead? Replace the maximum update with a minimum, handling the first gap separately.
CodingEasyX (Twitter)Software Engineer

6. Reverse Linked List (LeetCode)

Model answer

The task

Given the head of a singly linked list, reverse its links in place and return the new head.

Key idea

Recursively reverse the list starting at the second node. As the recursion unwinds, point each node’s successor back to it, then clear its old forward link.

Approach

  1. If the list has zero or one node, it is already reversed.
  2. Recursively reverse the list after the head and save its new head.
  3. Point the next node back to the current node.
  4. Set the current node’s next pointer to None to finish the reversed list.
  5. Return the saved new head.
class Solution:
    def reverseList(self, head):
        # An empty or single-node list is already reversed.
        if head is None or head.next is None:
            return head

        # Reverse the remainder of the list.
        new_head = self.reverseList(head.next)

        # Put the current node after its former successor.
        head.next.next = head
        head.next = None

        return new_head

Complexity:

  • Time: O(n), where n is the number of nodes.
  • Space: O(n), for the recursive call stack.

Common follow-ups

  • Can you do it iteratively with O(1) extra space? Use previous, current, and next_node pointers to reverse links while traversing.
  • What if the list is empty or has one node? The base case returns it unchanged.
  • Can you reverse only a portion of the list? Track the sublist boundaries and reconnect them after reversing that segment.
CodingEasyX (Twitter)Software Engineer

7. Customer Placing the Largest Number of Orders (LeetCode)

Model answer

The task

Find the customer who appears in the greatest number of rows in the orders table. Return that customer’s identifier.

Key idea

Group orders by customer and count each group. Sort the counts from largest to smallest, then select the top customer.

Approach

  1. Group the rows by customer_number.
  2. Count the rows in each group.
  3. Order groups by that count in descending order.
  4. Return the first group.
SELECT customer_number
FROM Orders
GROUP BY customer_number
ORDER BY COUNT(*) DESC
LIMIT 1;

Complexity:

  • Time: O(n log n), where n is the number of orders; grouping and sorting the customer counts take time.
  • Space: O(k), where k is the number of distinct customers represented in the orders.

Common follow-ups

  • What if every customer tied for the largest count should be returned? Use a subquery to compare each customer’s count with the maximum count.
  • What if customers with no orders must also be considered? Start from the Customers table and use a LEFT JOIN.
  • Can the result be made deterministic when counts tie? Add a secondary sort key, such as customer_number, to the ORDER BY clause.
CodingEasyX (Twitter)Software Engineer

8. Invalid Tweets (LeetCode)

Model answer

The task

Find the IDs of tweets whose content contains more than 15 characters.

Key idea

Filter the Tweets table by the character count of each content value.

Approach

  1. Read rows from Tweets.
  2. Use CHAR_LENGTH to count characters in each tweet.
  3. Keep rows with a count greater than 15.
  4. Return their tweet_id values.
SELECT tweet_id
FROM Tweets
WHERE CHAR_LENGTH(content) > 15;

Complexity:

  • Time: O(n), where n is the number of tweets checked.
  • Space: O(1) auxiliary space, excluding database execution overhead.

Common follow-ups

  • What if the limit changes? Replace 15 with the new threshold.
  • Why use CHAR_LENGTH instead of LENGTH? CHAR_LENGTH counts characters; LENGTH may count bytes.
  • How would you return the tweet content too? Add content to the selected columns.
CodingMediumX (Twitter)Software Engineer

9. A network consists of nodes labeled 0 to N.

The full question

A network consists of nodes labeled 0 to N. You are given a list of edges (a, b, t), describing the time t it takes for a message to be sent from node a to node b. Whenever a node receives a message, it immediately passes the message on to a neighboring node, if possible.

Assuming all nodes are connected, determine how long it will take for every node to receive a message that begins at node 0.

For example, given N = 5, and the following edges:

edges = [ (0, 1, 5), (0, 2, 3), (0, 5, 4), (1, 3, 8), (2, 3, 1), (3, 5, 10), (3, 4, 5) ] You should return 9, because propagating the message from 0 -> 2 -> 3 -> 4 will take that much time.

Model answer

class MinHeap {
  constructor() {
    this.items = [];
  }

  push(item) {
    this.items.push(item);
    let i = this.items.length - 1;
    while (i > 0) {
      const parent = Math.floor((i - 1) / 2);
      if (this.items[parent][0] <= this.items[i][0]) break;
      [this.items[parent], this.items[i]] = [this.items[i], this.items[parent]];
      i = parent;
    }
  }

  pop() {
    if (this.items.length === 0) return null;
    const minimum = this.items[0];
    const last = this.items.pop();
    if (this.items.length > 0) {
      this.items[0] = last;
      let i = 0;
      while (true) {
        const left = 2 * i + 1;
        const right = left + 1;
        let smallest = i;
        if (left < this.items.length && this.items[left][0] < this.items[smallest][0]) {
          smallest = left;
        }
        if (right < this.items.length && this.items[right][0] < this.items[smallest][0]) {
          smallest = right;
        }
        if (smallest === i) break;
        [this.items[i], this.items[smallest]] = [this.items[smallest], this.items[i]];
        i = smallest;
      }
    }
    return minimum;
  }

  get size() {
    return this.items.length;
  }
}

// Nodes are labeled 0 through maxNode. Edges are directed: a -> b.
function timeForAllNodes(maxNode, edges) {
  const nodeCount = maxNode + 1;
  const graph = Array.from({ length: nodeCount }, () => []);

  for (const [from, to, time] of edges) {
    graph[from].push([to, time]);
  }

  const distances = Array(nodeCount).fill(Infinity);
  distances[0] = 0;
  const heap = new MinHeap();
  heap.push([0, 0]); // [elapsed time, node]

  while (heap.size > 0) {
    const [time, node] = heap.pop();
    if (time !== distances[node]) continue; // Ignore stale heap entries.

    for (const [neighbor, travelTime] of graph[node]) {
      const candidate = time + travelTime;
      if (candidate < distances[neighbor]) {
        distances[neighbor] = candidate;
        heap.push([candidate, neighbor]);
      }
    }
  }

  const longest = Math.max(...distances);
  return longest === Infinity ? -1 : longest;
}

const edges = [
  [0, 1, 5], [0, 2, 3], [0, 5, 4], [1, 3, 8],
  [2, 3, 1], [3, 5, 10], [3, 4, 5]
];
console.log(timeForAllNodes(5, edges)); // 9
  • A node’s receipt time is its shortest-path distance from node 0; the answer is the maximum such distance.
  • This treats each edge as directed. If edges are undirected, add each edge in both directions when building the graph.

Complexity: O((N + E) log N) time and O(N + E) space.

CodingMediumX (Twitter)Software Engineer

10. Validate IP Address (LeetCode)

Model answer

The task

Classify a string as an IPv4 address, an IPv6 address, or neither. Each format has its own rules for the number and shape of its components.

Key idea

Check the two formats independently. Splitting on the appropriate separator makes it straightforward to validate both the component count and each component’s characters and numeric or length limits.

Approach

  1. Split on . and check for four IPv4 components.
  2. Require each component to contain only ASCII digits, have no unnecessary leading zero, and represent a value from 0 to 255.
  3. Otherwise, split on : and check for eight IPv6 components.
  4. Require each IPv6 component to contain one to four ASCII hexadecimal characters.
  5. Return the matching classification, or "Neither" if neither check succeeds.
class Solution:
    def validIPAddress(self, queryIP: str) -> str:
        parts = queryIP.split(".")

        if len(parts) == 4:
            valid_ipv4 = True

            for part in parts:
                # IPv4 components must be nonempty ASCII decimal strings.
                if not part or any(ch not in "0123456789" for ch in part):
                    valid_ipv4 = False
                    break

                # Multi-digit components cannot begin with zero.
                if len(part) > 1 and part[0] == "0":
                    valid_ipv4 = False
                    break

                if int(part) > 255:
                    valid_ipv4 = False
                    break

            if valid_ipv4:
                return "IPv4"

        parts = queryIP.split(":")

        if len(parts) == 8:
            hex_digits = "0123456789abcdefABCDEF"

            for part in parts:
                if not 1 <= len(part) <= 4:
                    break
                if any(ch not in hex_digits for ch in part):
                    break
            else:
                return "IPv6"

        return "Neither"

Complexity:

  • Time: O(n), where n is the string length; each character is checked a constant number of times.
  • Space: O(n) for the component lists created by splitting the string.

Common follow-ups

  • How would you support IPv6 :: compression? Allow one compression marker and verify it replaces at least one omitted group.
  • How would you handle IPv4-embedded IPv6 addresses? Parse the final dotted component as IPv4 and count it as two IPv6 groups.
  • What happens with leading zeros in IPv4 components? Reject them unless the component is exactly "0".
CodingMediumX (Twitter)Software Engineer

11. One Edit Distance (LeetCode)

Model answer

The task

Determine whether two strings differ by exactly one edit: inserting one character, deleting one character, or replacing one character.

Key idea

Scan both strings from left to right. Before the first mismatch, the characters match; at that mismatch, the only valid edit determines whether to advance one pointer or both. If the strings match through the end, they count only when one has a single trailing character.

Approach

  1. If the length difference exceeds one, return False.
  2. Use two pointers to scan both strings.
  3. On a mismatch, reject a second mismatch.
  4. For equal lengths, advance both pointers (replacement); otherwise, advance only the pointer for the longer string (insertion or deletion).
  5. If no mismatch occurred, check whether exactly one character remains.
class Solution:
    def isOneEditDistance(self, s: str, t: str) -> bool:
        # The strings cannot be one edit apart if their lengths differ
        # by more than one.
        if abs(len(s) - len(t)) > 1:
            return False

        i = j = 0
        edits = 0

        while i < len(s) and j < len(t):
            if s[i] == t[j]:
                i += 1
                j += 1
                continue

            edits += 1
            if edits > 1:
                return False

            if len(s) == len(t):
                # One replacement.
                i += 1
                j += 1
            elif len(s) > len(t):
                # One deletion from s.
                i += 1
            else:
                # One insertion into s (equivalently, deletion from t).
                j += 1

        # Any unmatched suffix must be exactly one character long.
        if i < len(s) or j < len(t):
            edits += 1

        return edits == 1

Complexity:

  • Time: O(min(n, m)) — the scan stops at the end of the shorter string or the second mismatch.
  • Space: O(1) — only pointers and a counter are used.

Common follow-ups

  • What if zero edits are allowed? Return true for identical strings by changing the final condition to edits <= 1.
  • How would you return the edit itself? Record the mismatch position and whether it is a replacement, insertion, or deletion.
  • What if multiple edits are allowed? Use edit-distance dynamic programming, or a more specialized algorithm if only a small number of edits is permitted.
CodingMediumX (Twitter)Software Engineer

12. Largest Plus Sign (LeetCode)

Model answer

The task

Given an n × n grid with mines marking unusable cells, find the largest plus sign whose center and four arms contain only usable cells. Its order is the number of usable cells from the center to the end of any arm, including the center.

Key idea

For each cell, track the length of its consecutive usable run in each of the four directions. The largest plus centered there is limited by the shortest run, so take the minimum of the four lengths.

Approach

  1. Initialize a DP grid with n; mark each mine as zero.
  2. Scan each row left to right and right to left, recording the shortest run seen so far at each cell.
  3. Scan each column top to bottom and bottom to top, updating those minima.
  4. Return the largest value in the DP grid.
class Solution:
    def orderOfLargestPlusSign(self, n: int, mines: list[list[int]]) -> int:
        mine_cells = {tuple(cell) for cell in mines}
        dp = [[n] * n for _ in range(n)]

        for r, c in mine_cells:
            dp[r][c] = 0

        # Intersect each cell's best arm lengths across all four directions.
        for r in range(n):
            run = 0
            for c in range(n):
                run = 0 if (r, c) in mine_cells else run + 1
                dp[r][c] = min(dp[r][c], run)

            run = 0
            for c in range(n - 1, -1, -1):
                run = 0 if (r, c) in mine_cells else run + 1
                dp[r][c] = min(dp[r][c], run)

        for c in range(n):
            run = 0
            for r in range(n):
                run = 0 if (r, c) in mine_cells else run + 1
                dp[r][c] = min(dp[r][c], run)

            run = 0
            for r in range(n - 1, -1, -1):
                run = 0 if (r, c) in mine_cells else run + 1
                dp[r][c] = min(dp[r][c], run)

        return max(max(row) for row in dp)

Complexity:

  • Time: O(n²), from scanning every cell a constant number of times.
  • Space: O(n²), for the DP grid and mine lookup set.

Common follow-ups

  • What if the grid is rectangular? Use its row and column counts in the corresponding scans.
  • How would you handle mine updates? Recomputing is straightforward; maintaining exact arm lengths efficiently under updates is more involved.
  • Can the DP grid be avoided? Yes, but storing minima per cell makes combining all four directions simple and efficient.
CodingMediumX (Twitter)Software Engineer

13. Process Tasks Using Servers (LeetCode)

Model answer

The task

Assign each task, in order, to a server that is available when the task can start. Prefer the server with the lowest weight, breaking ties by its index; return the chosen server for each task.

Key idea

Use one min-heap for available servers, ordered by (weight, index), and another for busy servers, ordered by (finish_time, weight, index). Simulate time, releasing completed servers and jumping forward when none are available.

Approach

  1. Put every server in the available heap.
  2. For each task, advance time to at least its arrival time.
  3. Move all servers that have finished by then into the available heap.
  4. If no server is available, jump to the next finish time and release all servers finishing then.
  5. Assign the task to the best available server and record its new finish time.
import heapq
from typing import List

class Solution:
    def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]:
        # Available servers are ordered by weight, then index.
        available = [(weight, index) for index, weight in enumerate(servers)]
        heapq.heapify(available)

        # Busy servers are ordered by finish time, then weight, then index.
        busy = []

        assignments = []
        current_time = 0

        for arrival_time, duration in enumerate(tasks):
            current_time = max(current_time, arrival_time)

            # Release every server that has finished by the current time.
            while busy and busy[0][0] <= current_time:
                _, weight, index = heapq.heappop(busy)
                heapq.heappush(available, (weight, index))

            # If all servers are busy, advance to the earliest finish time.
            if not available:
                current_time = busy[0][0]
                while busy and busy[0][0] <= current_time:
                    _, weight, index = heapq.heappop(busy)
                    heapq.heappush(available, (weight, index))

            weight, index = heapq.heappop(available)
            assignments.append(index)
            heapq.heappush(
                busy,
                (current_time + duration, weight, index),
            )

        return assignments

Complexity:

  • Time: O((n + m) log n), where n is the number of servers and m is the number of tasks; each server assignment or release uses a heap operation.
  • Space: O(n) auxiliary space for the heaps, excluding the returned assignments.

Common follow-ups

  • What if servers have additional priorities? Add the priority fields to the heap ordering.
  • What if tasks can be processed out of order? Define the scheduling policy first, then adapt how tasks enter the simulation.
  • How would you support a very large stream of tasks? Process tasks incrementally, keeping only the heaps and required output.
CodingMediumX (Twitter)Software Engineer

14. Insert Delete GetRandom O(1) (LeetCode)

Model answer

The task

Design a collection that supports adding and removing values, plus returning a uniformly random stored value. Each operation should take average O(1) time.

Key idea

Store values in a list for constant-time random indexing, and map each value to its index for fast lookup. To remove an item without shifting the list, swap it with the last item and then pop.

Approach

  1. Keep a list of stored values and a dictionary from value to its list index.
  2. For insertion, return False if the value is already present; otherwise append it and record its index.
  3. For removal, return False if absent. Otherwise, move the last value into the removed value’s slot, update its index, then pop and delete the removed value from the dictionary.
  4. For random selection, choose a uniformly random index in the list.
  5. Assume random selection is called only when the collection is nonempty.
import random

class RandomizedSet:
    def __init__(self):
        self.values = []
        self.index_by_value = {}

    def insert(self, val: int) -> bool:
        if val in self.index_by_value:
            return False

        self.index_by_value[val] = len(self.values)
        self.values.append(val)
        return True

    def remove(self, val: int) -> bool:
        if val not in self.index_by_value:
            return False

        index = self.index_by_value[val]
        last_value = self.values[-1]

        # Fill the removed value's slot with the last value.
        self.values[index] = last_value
        self.index_by_value[last_value] = index

        self.values.pop()
        del self.index_by_value[val]
        return True

    def getRandom(self) -> int:
        return random.choice(self.values)

Complexity:

  • Time: O(1) average per operation; dictionary operations are expected O(1).
  • Space: O(n), for the list and index map storing n values.

Common follow-ups

  • How would you support duplicates? Store each value’s set of indices and update that set during swaps.
  • What if random selection must be weighted? Maintain cumulative weights and use binary search, or use a dynamic weighted-sampling structure.
  • What happens if getRandom is called when empty? Define a clear error or sentinel behavior; the implementation assumes at least one value exists.
CodingMediumX (Twitter)Software Engineer

15. Implement Trie (Prefix Tree) (LeetCode)

Model answer

The task

Design a prefix tree that supports inserting strings, checking whether a complete string has been inserted, and checking whether any inserted string begins with a given prefix.

Key idea

Represent each character as an edge to a child node. Mark the node at the end of each inserted string, so a path can indicate a prefix without necessarily representing a complete word.

Approach

  1. Give each node a map from characters to child nodes and a flag indicating whether a word ends there.
  2. For insertion, create any missing nodes along the string’s path.
  3. Mark the final node as the end of a word.
  4. For both searches, follow the path character by character; if a child is missing, return False.
  5. A full-word search also checks the final node’s end-of-word flag; a prefix search only checks that the path exists.
class TrieNode:
    def __init__(self):
        self.children = {}
        self.is_word = False

class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word: str) -> None:
        node = self.root

        for char in word:
            if char not in node.children:
                node.children[char] = TrieNode()
            node = node.children[char]

        node.is_word = True

    def search(self, word: str) -> bool:
        node = self._find_node(word)
        return node is not None and node.is_word

    def startsWith(self, prefix: str) -> bool:
        return self._find_node(prefix) is not None

    def _find_node(self, text: str):
        node = self.root

        for char in text:
            if char not in node.children:
                return None
            node = node.children[char]

        return node

Complexity:

  • Time: O(L) per operation, where L is the length of the word or prefix being processed.
  • Space: O(S) for the trie, where S is the total number of characters stored across distinct paths.

Common follow-ups

  • How would you delete a word? Clear its end-of-word flag, then remove nodes that are no longer needed.
  • How would you support case-insensitive matching? Normalize strings consistently, such as by converting them to lowercase.
  • How can you reduce memory use for sparse or large alphabets? Use compact child storage, such as a radix trie or a sorted edge list.
CodingMediumX (Twitter)Software Engineer

16. Count Sub Islands (LeetCode)

Model answer

The task

Count the connected land regions in the second grid where every cell also belongs to land in the first grid. A region in the second grid counts only if it is wholly contained within a land region of the first.

Key idea

Explore each land component in the second grid with flood fill. Track whether every visited cell overlaps land in the first grid; count the component only if it does.

Approach

  1. Scan every cell of the second grid.
  2. When an unvisited land cell is found, start an iterative depth-first search.
  3. Mark cells as visited by changing them to water in the second grid.
  4. During the search, record whether any cell does not overlap land in the first grid.
  5. Add one to the result if the entire component overlaps.
class Solution:
    def numSubIslands(self, grid1: list[list[int]],
                      grid2: list[list[int]]) -> int:
        rows, cols = len(grid2), len(grid2[0])
        count = 0

        for r in range(rows):
            for c in range(cols):
                if grid2[r][c] == 0:
                    continue

                stack = [(r, c)]
                grid2[r][c] = 0  # Mark visited.
                is_sub_island = True

                while stack:
                    cr, cc = stack.pop()

                    if grid1[cr][cc] == 0:
                        is_sub_island = False

                    for nr, nc in (
                        (cr - 1, cc),
                        (cr + 1, cc),
                        (cr, cc - 1),
                        (cr, cc + 1),
                    ):
                        if (0 <= nr < rows and 0 <= nc < cols
                                and grid2[nr][nc] == 1):
                            grid2[nr][nc] = 0
                            stack.append((nr, nc))

                if is_sub_island:
                    count += 1

        return count

Complexity:

  • Time: O(mn), since each cell is visited at most once.
  • Space: O(mn) in the worst case for the DFS stack.

Common follow-ups

  • What if the grids must remain unchanged? Use a separate visited matrix instead of marking grid2.
  • How would you use breadth-first search? Replace the stack with a queue.
  • What if connectivity includes diagonals? Check all eight neighboring cells during the flood fill.
CodingMediumX (Twitter)Software Engineer

17. Tweet Counts Per Frequency (LeetCode)

Model answer

The task

Design a data structure that records timestamped tweets by name and returns counts for consecutive time buckets within a requested inclusive time range. The bucket size is specified as minute, hour, or day.

Key idea

Keep each tweet name’s timestamps sorted. For each bucket, use binary search to find how many timestamps fall between its inclusive bounds.

Approach

  1. Map each frequency label to its bucket duration in seconds.
  2. When recording a tweet, insert its timestamp into that tweet’s sorted list.
  3. For a query, divide the requested range into buckets, with the last bucket ending at endTime.
  4. Use binary searches to count timestamps in each bucket.
from bisect import bisect_left, bisect_right, insort
from collections import defaultdict

class TweetCounts:
    def __init__(self):
        self.times = defaultdict(list)
        self.bucket_size = {
            "minute": 60,
            "hour": 3600,
            "day": 86400,
        }

    def recordTweet(self, tweetName: str, time: int) -> None:
        insort(self.times[tweetName], time)

    def getTweetCountsPerFrequency(
        self, freq: str, tweetName: str, startTime: int, endTime: int
    ) -> list[int]:
        size = self.bucket_size[freq]
        timestamps = self.times[tweetName]
        counts = []

        bucket_start = startTime
        while bucket_start <= endTime:
            bucket_end = min(bucket_start + size - 1, endTime)

            left = bisect_left(timestamps, bucket_start)
            right = bisect_right(timestamps, bucket_end)
            counts.append(right - left)

            bucket_start += size

        return counts

Complexity:

  • Time: recordTweet is O(n) due to list insertion; a query is O(k log n), where k is the number of buckets and n is the number of timestamps for that tweet.
  • Space: O(N), where N is the total number of recorded tweets.

Common follow-ups

  • How can recording scale better? Use a balanced search tree or an ordered multiset for O(log n) insertion.
  • What if queries are frequent over a fixed time range? Maintain per-interval aggregates to avoid repeatedly searching all timestamps.
  • How should duplicate timestamps be handled? Store each occurrence; the binary-search range counts all duplicates.
CodingMediumX (Twitter)Software Engineer

18. LRU Cache (LeetCode)

Model answer

The task

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

Key idea

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

Approach

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

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

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

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

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

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

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

        self._make_most_recent(node)
        return node.value

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

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

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

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

Complexity:

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

Common follow-ups

  • How would you make the cache thread-safe? Protect operations with a lock.
  • What if entries expire after a time-to-live? Track expiration times and remove expired entries during access or with a cleanup mechanism.
  • How would you support eviction by frequency instead of recency? Track access counts and organize entries by frequency.
CodingMediumX (Twitter)Software Engineer

19. Minimum Genetic Mutation (LeetCode)

Model answer

The task

Find the fewest single-character changes needed to turn the starting gene into the target gene, using only valid genes from the bank. Return -1 if the target cannot be reached.

Key idea

Model each gene as a node, with an edge between genes that differ at one position. Breadth-first search finds the shortest path in this unweighted graph.

Approach

  1. Return 0 if the start already equals the target.
  2. Convert the bank to a set; if the target is absent, return -1.
  3. Run BFS from the start, tracking each gene’s mutation count.
  4. Generate possible neighbors by changing each position to one of the other DNA bases.
  5. Enqueue valid, unseen bank genes; return the count when the target is reached.
from collections import deque
from typing import List

class Solution:
    def minMutation(self, startGene: str, endGene: str, bank: List[str]) -> int:
        if startGene == endGene:
            return 0

        valid_genes = set(bank)
        if endGene not in valid_genes:
            return -1

        bases = "ACGT"
        queue = deque([(startGene, 0)])
        visited = {startGene}

        while queue:
            gene, mutations = queue.popleft()

            for i, original_base in enumerate(gene):
                for base in bases:
                    if base == original_base:
                        continue

                    neighbor = gene[:i] + base + gene[i + 1:]
                    if neighbor not in valid_genes or neighbor in visited:
                        continue

                    if neighbor == endGene:
                        return mutations + 1

                    visited.add(neighbor)
                    queue.append((neighbor, mutations + 1))

        return -1

Complexity:

  • Time: O(B · L · |Σ| · L) in Python, accounting for creating and hashing candidate strings; B is bank size, L is gene length, and |Σ| = 4.
  • Space: O(B · L) for the visited set and BFS queue.

Common follow-ups

  • How would you reduce search when the bank is large? Use bidirectional BFS, expanding from the start and target fronts and always expanding the smaller frontier.
  • What if mutations have different costs? Use Dijkstra’s algorithm instead of BFS.
Product & growthMediumX (Twitter)Data Scientist

20. How would you improve product engagement on Twitter?

Model answer

Clarify & scope

I’d define engagement as users finding value and choosing to return—not simply spending more time scrolling. I’d focus on improving meaningful interactions in the home timeline for existing users, while protecting conversation quality and user well-being.

User segments & pain points

I’d start with users who open X but rarely interact, especially newer users and people whose interests are not yet well represented in their feed. Their likely pain point is that the timeline does not quickly show relevant, trustworthy posts or give them a comfortable way to participate.

Goals & success metrics

My North Star would be weekly active users who have at least one meaningful interaction, such as a reply, repost, bookmark, or follow, with quality signals considered. I’d track this alongside time to first relevant post, repeat visits, follows of relevant accounts, and retained engagement at 7 and 28 days. Guardrails would include mutes, blocks, reports, hides, session abandonment, and survey measures of feed quality.

Solutions

  1. Improve onboarding by asking users to select topics and follow a few accounts, then make it easy to refine those interests.
  2. Make recommendations more explainable and controllable: indicate why a post appears and offer simple actions to see more or less like it.
  3. Create lower-pressure participation paths, such as saving a post or reacting privately, so users can build habits before replying publicly.

Recommendation: I’d test better onboarding and recommendation controls together for new and low-engagement users. They address relevance directly and give users agency, rather than optimizing for more impressions alone.

Prioritization & trade-offs

I’d prioritize by expected retained meaningful engagement, confidence, and engineering cost. Onboarding is likely a high-impact, relatively contained experiment; feed-ranking changes have broader reach but greater risk of amplifying low-quality content. I’d avoid rewarding raw reply volume without quality constraints.

MVP, measurement & rollout

I’d run a randomized experiment with a holdout, stratified by new versus existing users and major locales. I’d review relevance and safety guardrails daily, and evaluate retention over at least four weeks to capture durable effects. If meaningful engagement and retention improve without worsening quality or safety, I’d expand gradually; otherwise, I’d use behavior and feedback to identify which part of the experience failed.

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