Whatnot interview questions & answers

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

CodingEasyWhatnotSoftware Engineer

1. Valid Palindrome II (LeetCode)

Model answer

The task

Determine whether a string can become a palindrome after removing at most one character.

Key idea

Compare characters from both ends, moving inward while they match. At the first mismatch, the one allowed removal must skip either the left character or the right character; check whether either remaining range is a palindrome.

Approach

  1. Initialize pointers at the start and end of the string.
  2. While the pointed-to characters match, move both pointers inward.
  3. If the pointers meet, the string is already a palindrome.
  4. Otherwise, check the two ranges formed by skipping either mismatched character.
  5. Return true if at least one range is a palindrome.
class Solution:
    def validPalindrome(self, s: str) -> bool:
        def is_palindrome(left: int, right: int) -> bool:
            # Check whether this inclusive range reads the same both ways.
            while left < right:
                if s[left] != s[right]:
                    return False
                left += 1
                right -= 1
            return True

        left, right = 0, len(s) - 1

        while left < right:
            if s[left] != s[right]:
                # Use the one allowed deletion on either mismatched end.
                return (
                    is_palindrome(left + 1, right)
                    or is_palindrome(left, right - 1)
                )
            left += 1
            right -= 1

        return True

Complexity:

  • Time: O(n), since at most two linear range checks are performed.
  • Space: O(1), excluding the input string; the checks use only pointers.

Common follow-ups

  • What if up to k characters may be removed? Use recursion or dynamic programming to track the remaining deletion budget; the simple one-mismatch check no longer suffices.
  • What if the input is a linked list? Use a stack or find the midpoint and reverse part of the list, depending on whether extra space is allowed.
  • Should comparison ignore capitalization or punctuation? Normalize or skip irrelevant characters while moving the two pointers inward.
CodingEasyWhatnotSoftware Engineer

2. Remove All Adjacent Duplicates In String (LeetCode)

Model answer

The task

Given a string, repeatedly remove any pair of equal characters that are next to each other. Return the string left after no such pair remains.

Key idea

Process the characters from left to right using a stack. The stack represents the reduced string so far: if the next character matches its top, remove the top; otherwise, add the character.

Approach

  1. Start with an empty stack.
  2. Visit each character in the input string.
  3. If it matches the stack’s top, pop the top.
  4. Otherwise, push the character.
  5. Join the stack to produce the result.

Each decision leaves the processed prefix fully reduced. Removing a pair can expose a new adjacent pair, but the stack handles that naturally when later characters are processed.

class Solution:
    def removeDuplicates(self, s: str) -> str:
        stack = []

        for char in s:
            if stack and stack[-1] == char:
                stack.pop()
            else:
                stack.append(char)

        return "".join(stack)

Complexity:

  • Time: O(n), since each character is pushed at most once and popped at most once.
  • Space: O(n), for the stack in the worst case.

Common follow-ups

  • What if each character must be removed when it appears in a run of at least k equal characters? Store character counts on the stack and pop a group when its count reaches k.
  • Can this be done in place on a mutable character array? Use a write index as a stack pointer, overwriting the processed prefix.
  • What if removals follow a specified priority or multiple different patterns? Clarify the rules first; a stack may still work, but the match and removal logic may need to change.
CodingEasyWhatnotSoftware Engineer

3. Squares of a Sorted Array (LeetCode)

Model answer

The task

Given an array sorted in nondecreasing order, return a new array containing the square of each value, also sorted in nondecreasing order.

Key idea

Squaring can make negative values large, so the largest square must come from one of the two ends of the input. Compare the absolute values at both ends and fill the result from right to left.

Approach

  1. Set pointers at the first and last elements.
  2. Allocate a result array of the same length.
  3. Compare the absolute values at the pointers.
  4. Place the larger square at the current result position, then move the corresponding pointer inward.
  5. Continue until every position has been filled.
class Solution:
    def sortedSquares(self, nums: list[int]) -> list[int]:
        left, right = 0, len(nums) - 1
        result = [0] * len(nums)
        write = len(nums) - 1

        while left <= right:
            if abs(nums[left]) > abs(nums[right]):
                value = nums[left]
                left += 1
            else:
                value = nums[right]
                right -= 1

            result[write] = value * value
            write -= 1

        return result

Complexity:

  • Time: O(n), since each input element is processed once.
  • Space: O(n), for the returned array.

Common follow-ups

  • Can this be done without allocating a result array? Not while returning a separate sorted array in the general case; the output itself requires O(n) space.
  • What if the input is not sorted? Sort it first, which takes O(n log n), then use the two-pointer method.
  • How do duplicates affect the algorithm? They need no special handling; equal absolute values produce equal squares.
CodingEasyWhatnotSoftware Engineer

4. First Bad Version (LeetCode)

Model answer

The task

Given versions numbered from 1 through n, find the earliest version that is bad. The bad-version check is provided as an API, and once a version is bad, all later versions are bad.

Key idea

Use binary search on the boundary between good and bad versions. If the midpoint is bad, the first bad version is at or before it; otherwise, it must be after it.

Approach

  1. Set the search range to [1, n].
  2. While the range contains more than one version, choose its midpoint.
  3. If the midpoint is bad, move the right endpoint to it.
  4. Otherwise, move the left endpoint to the version after it.
  5. When the endpoints meet, return that version.
# isBadVersion(version) is supplied by the interactive API.

class Solution:
    def firstBadVersion(self, n: int) -> int:
        left, right = 1, n

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

            if isBadVersion(mid):
                right = mid
            else:
                left = mid + 1

        return left

Complexity:

  • Time: O(log n), because each API call halves the search range.
  • Space: O(1), using only a fixed number of variables.

Common follow-ups

  • What if API calls are expensive? Minimize calls with binary search; it uses at most O(log n) checks.
  • How would you avoid integer overflow in languages with fixed-width integers? Compute the midpoint as left + (right - left) // 2.
  • What if there might be no bad version? The API contract or return convention must specify how to represent that case.
CodingMediumWhatnotSoftware Engineer

5. Number of Islands (LeetCode)

Model answer

The task

Given a grid of land and water, count the groups of connected land cells. Cells connect horizontally or vertically, not diagonally.

Key idea

Each group is one island. Scan the grid, and whenever an unvisited land cell is found, count a new island and explore its entire connected region. Mark cells as visited when adding them to the search queue so no cell is processed more than once.

Approach

  1. Return 0 if the grid is empty.
  2. Scan every cell in the grid.
  3. When a land cell is found, increment the island count and start a breadth-first search from it.
  4. During the search, mark each discovered land cell as water and add its in-bounds land neighbors to the queue.
  5. Return the island count after the scan is complete.
from collections import deque
from typing import List

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        if not grid or not grid[0]:
            return 0

        rows, cols = len(grid), len(grid[0])
        islands = 0

        for row in range(rows):
            for col in range(cols):
                if grid[row][col] != "1":
                    continue

                islands += 1
                grid[row][col] = "0"
                queue = deque([(row, col)])

                while queue:
                    current_row, current_col = queue.popleft()

                    for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                        next_row = current_row + dr
                        next_col = current_col + dc

                        if (
                            0 <= next_row < rows
                            and 0 <= next_col < cols
                            and grid[next_row][next_col] == "1"
                        ):
                            # Mark when enqueuing to avoid duplicate work.
                            grid[next_row][next_col] = "0"
                            queue.append((next_row, next_col))

        return islands

Complexity: Time: O(rows * cols), since each cell is examined at most a constant number of times.

Complexity: Space: O(rows * cols) in the worst case for the BFS queue.

Common follow-ups

  • Preserve the input grid? Track visited cells in a separate set instead of changing land cells to water.
  • Use depth-first search instead? Recursively or iteratively explore the four neighbors; iterative DFS avoids recursion-depth concerns.
  • Count diagonally connected land as part of the same island? Include the four diagonal directions in the neighbor list.
CodingMediumWhatnotSoftware Engineer

6. Analyze User Website Visit Pattern (LeetCode)

Model answer

The task

Given users’ website visits and their timestamps, find the three-website sequence visited by the greatest number of distinct users. Visits in a sequence must be chronological; ties are resolved lexicographically.

Key idea

Sort each user’s visits by time, then enumerate that user’s three-visit combinations. Deduplicate combinations per user before counting, so a user contributes at most once to any sequence.

Approach

  1. Group each visit’s timestamp and website by username.
  2. Sort each user’s visits chronologically.
  3. Generate all three-website combinations from each sorted list.
  4. Count each combination once per user.
  5. Return the most frequent combination, choosing the lexicographically smallest in a tie.
from collections import Counter, defaultdict
from itertools import combinations
from typing import List

class Solution:
    def mostVisitedPattern(
        self,
        username: List[str],
        timestamp: List[int],
        website: List[str],
    ) -> List[str]:
        visits_by_user = defaultdict(list)

        for user, time, site in zip(username, timestamp, website):
            visits_by_user[user].append((time, site))

        pattern_counts = Counter()

        for visits in visits_by_user.values():
            visits.sort(key=lambda visit: visit[0])
            sites = [site for _, site in visits]

            # Count a pattern at most once for each user.
            user_patterns = set(combinations(sites, 3))
            pattern_counts.update(user_patterns)

        if not pattern_counts:
            return []

        highest_count = max(pattern_counts.values())
        best_pattern = min(
            pattern
            for pattern, count in pattern_counts.items()
            if count == highest_count
        )
        return list(best_pattern)

Complexity:

  • Time: O(n log n + Σ mᵤ³), where n is the number of visits and mᵤ is the number of visits for each user.
  • Space: O(n + p), where p is the number of distinct patterns stored.

Common follow-ups

  • What if the pattern length is configurable? Generate combinations of the requested length instead of three.
  • How do repeated visits affect counting? They can form repeated sites in a sequence, but each full sequence still counts only once per user.
  • How would this scale across machines? Partition visits by user so each user’s sequences can be counted independently, then aggregate counts.
CodingMediumWhatnotSoftware Engineer

7. Knight Dialer (LeetCode)

Model answer

The task

Count the digit sequences of length n that can be dialed by moving a chess knight between digits on a phone keypad. The first digit can be any digit, and the count is returned modulo \(10^9+7\).

Key idea

Treat each digit as a state in a graph, with edges for legal knight moves. Let dp[d] count sequences of the current length ending at digit d; each move transfers those counts to neighboring digits.

Approach

  1. List the legal destinations for each digit.
  2. Initialize every digit’s count to one for sequences of length one.
  3. For each additional position, add each digit’s count to the counts of its legal destinations.
  4. Reduce counts modulo \(10^9+7\) during updates.
  5. Sum the counts after n positions.
class Solution:
    def knightDialer(self, n: int) -> int:
        mod = 10**9 + 7

        # Legal knight moves from each keypad digit.
        moves = [
            [4, 6],     # 0
            [6, 8],     # 1
            [7, 9],     # 2
            [4, 8],     # 3
            [0, 3, 9],  # 4
            [],         # 5
            [0, 1, 7],  # 6
            [2, 6],     # 7
            [1, 3],     # 8
            [2, 4],     # 9
        ]

        # Every digit is a valid one-digit sequence.
        dp = [1] * 10

        for _ in range(n - 1):
            next_dp = [0] * 10

            for digit, destinations in enumerate(moves):
                for destination in destinations:
                    next_dp[destination] = (
                        next_dp[destination] + dp[digit]
                    ) % mod

            dp = next_dp

        return sum(dp) % mod

Complexity:

  • Time: O(n), since each step processes a fixed number of keypad moves.
  • Space: O(1), using two arrays of ten counts.

Common follow-ups

  • What if n is extremely large? Represent moves as a matrix and use exponentiation by squaring to compute the transition power in O(log n) matrix multiplications.
  • What if sequences must start at a specific digit? Initialize dp to zero except for a count of one at that digit.
  • Can the keypad or move rules change? Replace the adjacency list with the graph for the new rules; the same DP applies.
CodingMediumWhatnotSoftware Engineer

8. Maximal Square (LeetCode)

Model answer

The task

Given a rectangular matrix of "0" and "1" characters, find the area of the largest square containing only "1" cells. Return 0 if no such square exists.

Key idea

For each cell containing "1", let its DP value be the side length of the largest all-"1" square ending at that cell. It is limited by the squares ending above, to the left, and diagonally above-left.

Approach

  1. Return 0 for an empty matrix.
  2. Keep one DP row, where dp[j] holds the largest square ending at the current row and column j.
  3. Save the previous row’s diagonal value before updating each cell.
  4. For a "1" cell, set its value to one plus the minimum of its top, left, and diagonal values; for a "0", set it to zero.
  5. Track the largest side length and return its square.
from typing import List

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

        rows, cols = len(matrix), len(matrix[0])
        dp = [0] * (cols + 1)
        largest_side = 0

        for i in range(rows):
            diagonal = 0  # DP value from the previous row, previous column

            for j in range(1, cols + 1):
                above = dp[j]

                if matrix[i][j - 1] == "1":
                    dp[j] = 1 + min(dp[j], dp[j - 1], diagonal)
                    largest_side = max(largest_side, dp[j])
                else:
                    dp[j] = 0

                diagonal = above

        return largest_side * largest_side

Complexity:

  • Time: O(mn), where m and n are the matrix dimensions.
  • Space: O(n), for the rolling DP row.

Common follow-ups

  • How would you reconstruct the square’s coordinates? Track the location where the largest side is found, then derive its top-left corner.
  • Can the solution use more memory to simplify the recurrence? Yes; store DP values for all cells in an m × n table.
  • What if the matrix is streamed one row at a time? The rolling-row approach already supports this, retaining only the previous row’s state.
CodingMediumWhatnotSoftware Engineer

9. K Closest Points to Origin (LeetCode)

Model answer

The task

Given points in a 2D plane and an integer k, return any k points nearest to the origin. Points tied in distance may be returned in any order.

Key idea

Compare squared distances, x² + y²; taking square roots is unnecessary. Keep a max-heap of the k closest points seen so far, so its root is the farthest point currently selected.

Approach

  1. Return an empty list if k is zero.
  2. Add points to a heap, storing negative squared distance so the farthest selected point is at the root.
  3. Once the heap has k points, replace its root whenever a closer point is found.
  4. Return the points referenced by the heap.
import heapq
from typing import List

class Solution:
    def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
        if k == 0:
            return []

        # Store (-squared_distance, point_index). The most negative key
        # corresponds to the farthest point, making this a max-heap.
        heap = []

        for i, (x, y) in enumerate(points):
            distance_squared = x * x + y * y

            if len(heap) < k:
                heapq.heappush(heap, (-distance_squared, i))
            elif distance_squared < -heap[0][0]:
                heapq.heapreplace(heap, (-distance_squared, i))

        return [points[i] for _, i in heap]

Complexity:

  • Time: O(n log k), where n is the number of points and each heap update costs O(log k).
  • Space: O(k) for the heap.

Common follow-ups

  • Can sorting solve it? Yes; sort by squared distance in O(n log n) time.
  • Can it be faster on average? Quickselect finds the first k points in expected O(n) time, though its worst case is O(n²).
  • What if points have more dimensions? Sum the squared coordinate differences across all dimensions.
  • How should ties be handled? Any tied points are acceptable unless the question specifies a tie-breaking rule.
CodingMediumWhatnotSoftware Engineer

10. Meeting Rooms II (LeetCode)

Model answer

The task

Given meeting time intervals, find the minimum number of rooms needed so that no overlapping meetings share a room.

Key idea

Process meetings in start-time order. Track each occupied room by the time its meeting ends; a room is available when its meeting ends no later than the next meeting starts.

Approach

  1. Sort intervals by start time.
  2. Keep a min-heap of end times for meetings using rooms.
  3. For each meeting, remove the earliest end time if that room is available.
  4. Add the current meeting’s end time to the heap.
  5. The largest heap size reached is the minimum room count.
import heapq
from typing import List

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

        intervals.sort(key=lambda meeting: meeting[0])
        room_end_times = []

        for start, end in intervals:
            # Reuse the room whose meeting finishes first, if available.
            if room_end_times and room_end_times[0] <= start:
                heapq.heappop(room_end_times)

            heapq.heappush(room_end_times, end)

        return len(room_end_times)

Complexity:

  • Time: O(n log n), for sorting and heap operations across n meetings.
  • Space: O(n), for the heap in the worst case.

Common follow-ups

  • What if a meeting ending at time t overlaps one starting at t? Change the availability check from <= to <.
  • How can you return a room assignment for every meeting? Store (end_time, room_id) in the heap and reuse the freed room ID.
  • How would you handle meetings arriving online? Maintain the end-time heap as meetings arrive; each new meeting can reuse a room or add one.
CodingMediumWhatnotSoftware Engineer

11. Group Anagrams (LeetCode)

Model answer

The task

Partition the input strings into groups so that strings in the same group contain the same characters with the same frequencies. The order of the groups does not matter.

Key idea

Sort the characters of each string to create a canonical key. Anagrams produce the same key, so a hash table can collect them together.

Approach

  1. Create a mapping from canonical keys to lists of original strings.
  2. For each string, sort its characters and use the result as its key.
  3. Append the string to the list for that key.
  4. Return all grouped lists.
from collections import defaultdict
from typing import List

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        groups = defaultdict(list)

        for word in strs:
            # Anagrams have identical sorted-character representations.
            key = "".join(sorted(word))
            groups[key].append(word)

        return list(groups.values())

Complexity:

  • Time: O(n · k log k), where n is the number of strings and k is the maximum string length.
  • Space: O(n · k) to store the grouped strings and their keys.

Common follow-ups

  • Can this be faster for a fixed alphabet? Use a character-frequency tuple as the key, computing it in O(k) per string.
  • Does this work with uppercase letters or Unicode? Yes; sorting characters works for any Python strings.
  • Can groups be returned in a deterministic order? Sort the groups, or their keys, before returning them.
  • What if memory is limited? Consider processing input in batches or grouping externally by canonical key.

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