Swiggy interview questions & answers

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

CodingEasySwiggySoftware Engineer

1. Merge Sorted Array (LeetCode)

Model answer

The task

Combine two already sorted arrays into one sorted array, placing the result in the first array. The first array has enough spare capacity to hold all elements from both arrays.

Key idea

Fill the first array from right to left. Comparing the largest remaining elements avoids overwriting values in the first array that have not yet been processed.

Approach

  1. Set pointers to the last valid elements of both arrays.
  2. Set a write pointer to the last slot in the first array.
  3. While the second array still has elements, compare the values at the two read pointers.
  4. Write the larger value at the write pointer, then move the corresponding read pointer and the write pointer left.
  5. Any remaining elements from the second array are copied into the first. Remaining elements from the first are already in place.
class Solution:
    def merge(self, nums1: list[int], m: int, nums2: list[int], n: int) -> None:
        """Merge nums2 into nums1 in-place, keeping nums1 sorted."""
        i = m - 1          # Last initialized element in nums1
        j = n - 1          # Last element in nums2
        write = m + n - 1  # Last available position in nums1

        # Fill from the back so unread nums1 elements are not overwritten.
        while j >= 0:
            if i >= 0 and nums1[i] > nums2[j]:
                nums1[write] = nums1[i]
                i -= 1
            else:
                nums1[write] = nums2[j]
                j -= 1
            write -= 1

Complexity:

  • Time: O(m + n), since each element is considered at most once.
  • Space: O(1), because the merge modifies the first array directly.

Common follow-ups

  • What if the arrays are sorted in descending order? Reverse the comparison or adapt the traversal direction.
  • What if the result must go into a separate array? Use two forward pointers and allocate O(m + n) extra space.
  • What if either array is empty? The loop naturally handles it; if the second is empty, the first is already complete.
  • Why merge from the end? Writing from the front could overwrite unprocessed elements in the first array.
CodingEasySwiggySoftware Engineer

2. Next Greater Element I (LeetCode)

Model answer

The task

For each value in one array, find the first larger value appearing to its right in a second array that contains it. Return -1 when no such value exists.

Key idea

Scan the second array from left to right with a decreasing stack. When a new value is larger than values on the stack, it is the next greater value for each of them; store those answers in a hash map.

Approach

  1. Initialize an empty stack and a map of answers.
  2. For each value in the second array, pop smaller values from the stack and map each popped value to the current value.
  3. Push the current value onto the stack.
  4. Values still on the stack have no greater value to their right.
  5. Build the result by looking up each value from the first array, using -1 when it has no mapped answer.
from typing import List

class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        next_greater = {}
        decreasing_stack = []

        for value in nums2:
            # The current value is the first greater value for each
            # smaller value waiting on the stack.
            while decreasing_stack and decreasing_stack[-1] < value:
                next_greater[decreasing_stack.pop()] = value
            decreasing_stack.append(value)

        # Any value without a recorded answer has no greater value to its right.
        return [next_greater.get(value, -1) for value in nums1]

Complexity:

  • Time: O(n + m), where n and m are the lengths of the two arrays; each value is pushed and popped at most once.
  • Space: O(m), for the stack and answer map.

Common follow-ups

  • What if the second array is circular? Scan it twice, using indices modulo its length, and push only during the first pass.
  • What if values can repeat? Track indices on the stack and define how to match repeated values from the first array.
  • Can the answers be found online as values arrive? Yes; resolve stack entries when a larger value arrives, while retaining unresolved entries.
CodingEasySwiggySoftware Engineer

3. Fair Candy Swap (LeetCode)

Model answer

The task

Choose one candy size from each of two collections to exchange so that the collections have equal total size afterward. Return the chosen sizes as a pair.

Key idea

If Alice gives size x and receives size y, equal totals require x - y to be half the difference between the original totals. A set of Bob’s sizes lets us check each possible Alice candy efficiently.

Approach

  1. Compute the difference between the two original totals.
  2. If the difference is odd, no integer pair can satisfy the required equation.
  3. Store Bob’s candy sizes in a set.
  4. For each Alice candy x, calculate the required Bob candy y.
  5. Return the first pair where y is in the set.
from typing import List

class Solution:
    def fairCandySwap(
        self, aliceSizes: List[int], bobSizes: List[int]
    ) -> List[int]:
        difference = sum(aliceSizes) - sum(bobSizes)

        # An odd difference cannot be split evenly between the two candies.
        if difference % 2 != 0:
            return []

        half_difference = difference // 2
        bob_candies = set(bobSizes)

        for alice_candy in aliceSizes:
            # alice_candy - bob_candy must equal half_difference.
            bob_candy = alice_candy - half_difference
            if bob_candy in bob_candies:
                return [alice_candy, bob_candy]

        return []

Complexity:

  • Time: O(n + m), for summing both lists and building/searching the set.
  • Space: O(m), for the set of Bob’s candy sizes.

Common follow-ups

  • What if there may be no valid swap? Return an empty list when no matching pair is found.
  • Can sorting be used instead? Yes; sort one list and binary-search for each required value, taking O(m log m + n log m) time.
  • What if there are many queries with different totals? Reuse the set of candy sizes and compute the required value for each query.
CodingEasySwiggySoftware Engineer

4. 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.
CodingEasySwiggySoftware Engineer

5. Best Time to Buy and Sell Stock (LeetCode)

Model answer

The task

Given daily stock prices, find the greatest profit possible from one buy followed by one later sale. If no sale would make money, return zero.

Key idea

As we scan the prices, keep the lowest price seen so far. Treat each current price as a possible sale and update the best profit using the difference from that minimum.

Approach

  1. Initialize the minimum price to a value larger than any price and the best profit to zero.
  2. Visit each price in order.
  3. Update the minimum price with the current price.
  4. Check the profit from selling today and update the best profit.
  5. Return the best profit.
class Solution:
    def maxProfit(self, prices: list[int]) -> int:
        min_price = float("inf")
        best_profit = 0

        for price in prices:
            # The current price can be a new best day to buy.
            min_price = min(min_price, price)

            # Or it can be the day to sell after the cheapest earlier buy.
            best_profit = max(best_profit, price - min_price)

        return best_profit

Complexity:

  • Time: O(n), where n is the number of prices; each is processed once.
  • Space: O(1), since only a few variables are stored.

Common follow-ups

  • What if multiple buy-and-sell transactions are allowed? Sum the gains from every adjacent price increase.
  • What if a transaction fee is charged? Track the best holding and non-holding profits, incorporating the fee when selling.
  • What if at most k transactions are allowed? Use dynamic programming over the number of completed transactions and whether a share is currently held.
CodingEasySwiggySoftware Engineer

6. Minimum Value to Get Positive Step by Step Sum (LeetCode)

Model answer

The task

Given an integer array, find the smallest positive starting value such that adding the array’s values one at a time always leaves a positive running total.

Key idea

The running total is the starting value plus a prefix sum. The smallest valid start is therefore the larger of 1 and 1 - the smallest prefix sum.

Approach

  1. Initialize the running prefix sum and its minimum to zero, accounting for the empty prefix.
  2. Scan the array, adding each value to the prefix sum.
  3. Track the smallest prefix sum seen.
  4. Return at least 1, or enough to raise that minimum prefix sum to 1.
class Solution:
    def minStartValue(self, nums: list[int]) -> int:
        prefix_sum = 0
        min_prefix_sum = 0

        for value in nums:
            prefix_sum += value
            min_prefix_sum = min(min_prefix_sum, prefix_sum)

        return max(1, 1 - min_prefix_sum)

Complexity:

  • Time: O(n), for one pass through the array.
  • Space: O(1), using only a few variables.

Common follow-ups

  • What if the running total must stay nonnegative instead? Use max(0, -min_prefix_sum) as the smallest nonnegative start.
  • What if values arrive as a stream? Track the running sum and its minimum as values arrive; the final answer uses the same formula.
  • Can the method handle an empty array? Yes; the initial minimum prefix sum is zero, so it returns 1.
CodingMediumSwiggySoftware Engineer

7. Course Schedule (LeetCode)

Model answer

The task

Given a number of courses and prerequisite pairs, decide whether it’s possible to complete every course. A prerequisite pair means one course must be taken before another.

Key idea

Represent courses as a directed graph, with an edge from each prerequisite to the course that depends on it. A cycle means the courses in that cycle depend on one another, so not all courses can be completed.

Use Kahn’s topological-sort algorithm: repeatedly take courses with no remaining prerequisites and remove their outgoing edges.

Approach

  1. Create an adjacency list and count each course’s prerequisites (its indegree).
  2. Add every course with indegree zero to a queue.
  3. Remove courses from the queue, counting each as completed.
  4. Decrease the indegree of each dependent course; enqueue it when its indegree reaches zero.
  5. Return whether the number completed equals the total number of courses.
from collections import deque
from typing import List

class Solution:
    def canFinish(
        self, numCourses: int, prerequisites: List[List[int]]
    ) -> bool:
        # Edges point from prerequisite to the course that depends on it.
        graph = [[] for _ in range(numCourses)]
        indegree = [0] * numCourses

        for course, prerequisite in prerequisites:
            graph[prerequisite].append(course)
            indegree[course] += 1

        # Begin with courses that have no prerequisites.
        ready = deque(
            course
            for course in range(numCourses)
            if indegree[course] == 0
        )

        completed = 0

        while ready:
            course = ready.popleft()
            completed += 1

            for dependent in graph[course]:
                indegree[dependent] -= 1
                if indegree[dependent] == 0:
                    ready.append(dependent)

        return completed == numCourses

Complexity:

  • Time: O(V + E), where V is the number of courses and E is the number of prerequisite pairs.
  • Space: O(V + E) for the graph, indegrees, and queue.

Common follow-ups

  • How can you return a valid course order? Record courses as they are removed from the queue; return the order if it includes every course.
  • How can DFS detect a cycle? Track nodes as unvisited, visiting, or finished; reaching a visiting node reveals a cycle.
  • What if there are no courses? The algorithm returns True, since zero courses can all be completed.
CodingMediumSwiggySoftware Engineer

8. Minimum Number of Work Sessions to Finish the Tasks (LeetCode)

Model answer

The task

Given task durations and a fixed session limit, find the fewest sessions needed to schedule every task. Tasks cannot be split, and each session’s total duration must stay within the limit.

Key idea

Process tasks one at a time using a bitmask to represent which tasks have been scheduled. For each mask, keep the best pair: number of sessions opened and time used in the current session. For the same mask, fewer sessions is better; with an equal number, less current-session time is better.

Approach

  1. Let each bit in a mask indicate whether its task has been scheduled.
  2. Start with no tasks scheduled and one empty session.
  3. For each reachable mask, try adding each task not yet in it.
  4. If the task fits in the current session, add its duration there; otherwise, open a new session.
  5. Keep the best pair for the resulting mask and return its session count.
class Solution:
    def minSessions(self, tasks: list[int], sessionTime: int) -> int:
        n = len(tasks)
        if n == 0:
            return 0

        # Each entry is (sessions opened, time used in the current session).
        # Lexicographic order prefers fewer sessions, then less current usage.
        dp = [None] * (1 << n)
        dp[0] = (1, 0)

        for mask in range(1 << n):
            state = dp[mask]
            if state is None:
                continue

            sessions, used = state

            for i, duration in enumerate(tasks):
                if mask & (1 << i):
                    continue

                next_mask = mask | (1 << i)
                if used + duration <= sessionTime:
                    candidate = (sessions, used + duration)
                else:
                    candidate = (sessions + 1, duration)

                if dp[next_mask] is None or candidate < dp[next_mask]:
                    dp[next_mask] = candidate

        return dp[-1][0]

Complexity:

  • Time: O(n · 2ⁿ), considering each task from each task subset.
  • Space: O(2ⁿ), storing one state per subset.

Common follow-ups

  • How can the actual task assignments be returned? Store each chosen predecessor and task, then backtrack from the full mask.
  • What if there are many more tasks? This subset DP becomes impractical; use branch-and-bound or approximation methods for the resulting bin-packing problem.
  • What if a task exceeds the session limit? No valid schedule exists; detect this before running the DP.
CodingMediumSwiggySoftware Engineer

9. Edit Distance (LeetCode)

Model answer

The task

Given two strings, find the fewest single-character insertions, deletions, or replacements needed to change one into the other.

Key idea

Let dp[j] represent the edit distance between the processed prefix of the first string and the first j characters of the second. For each character pair, either keep matching characters at no cost or choose the cheapest insertion, deletion, or replacement.

Approach

  1. Make the second string the shorter one to keep the DP row small.
  2. Initialize distances for converting the empty first prefix into each prefix of the second string.
  3. Process the first string one character at a time, keeping the previous row’s diagonal value.
  4. Update each cell using the matching-character case or the minimum of the three edit operations.
  5. Return the final row value.
class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        # Keep the DP row as short as possible.
        if len(word2) > len(word1):
            word1, word2 = word2, word1

        # Distances from an empty prefix of word1 to prefixes of word2.
        dp = list(range(len(word2) + 1))

        for i, char1 in enumerate(word1, start=1):
            # Distance from the current word1 prefix to an empty word2 prefix.
            diagonal = dp[0]
            dp[0] = i

            for j, char2 in enumerate(word2, start=1):
                above = dp[j]

                if char1 == char2:
                    dp[j] = diagonal
                else:
                    # Insert, delete, or replace one character.
                    dp[j] = 1 + min(
                        dp[j - 1],  # Insert
                        above,      # Delete
                        diagonal,   # Replace
                    )

                diagonal = above

        return dp[-1]

Complexity:

  • Time: O(mn), where m and n are the string lengths; each pair of characters is processed once.
  • Space: O(min(m, n)), for the DP row.

Common follow-ups

  • How would you reconstruct the actual edits? Store the full DP table, then backtrack from the final cell.
  • What if insertion, deletion, and replacement have different costs? Use those costs in the recurrence.
  • Can the time be reduced when the strings are very different in length? A length difference greater than the allowed edit limit can rule out a result within that limit.
CodingMediumSwiggySoftware Engineer

10. 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.
CodingMediumSwiggySoftware Engineer

11. Longest Palindromic Substring (LeetCode)

Model answer

The task

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

Key idea

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

Approach

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

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

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

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

        return s[best_start:best_start + best_length]

Complexity:

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

Common follow-ups

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

12. Daily Temperatures (LeetCode)

Model answer

The task

For each day in a temperature list, find how many days later a warmer temperature first occurs. If no warmer day follows, its answer is zero.

Key idea

Keep a stack of indices whose temperatures are still waiting for a warmer day. Their temperatures are in non-increasing order; when a warmer day arrives, it resolves the waiting indices at the top.

Approach

  1. Create an answer array filled with zeros and an empty stack of indices.
  2. Scan the temperatures from left to right.
  3. While the current temperature is warmer than the temperature at the stack’s top index, pop that index.
  4. Set its answer to the difference between the current index and the popped index.
  5. Push the current index; unresolved indices remain zero.
from typing import List

class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        n = len(temperatures)
        answer = [0] * n
        waiting: List[int] = []

        for day, temperature in enumerate(temperatures):
            # Resolve every earlier day for which today is the first
            # warmer day encountered.
            while waiting and temperatures[waiting[-1]] < temperature:
                earlier_day = waiting.pop()
                answer[earlier_day] = day - earlier_day

            # This day is now waiting for a warmer temperature.
            waiting.append(day)

        return answer

Complexity:

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

Common follow-ups

  • How would you handle temperatures arriving as a stream? Keep the unresolved indices and their temperatures in a stack, and emit answers when warmer values arrive; some earlier outputs may remain pending.
  • What changes if the question asks for the next colder day? Reverse the comparison so an index is resolved by a lower temperature.
  • Can the stack store temperatures instead of indices? Not for this output, because the index difference is needed to calculate the number of days.
  • What happens when temperatures are equal? Equal values do not resolve each other; only a strictly warmer temperature does.
CodingMediumSwiggySoftware Engineer

13. Maximum Score From Removing Substrings (LeetCode)

Model answer

The task

Given a string and scores for removing "ab" and "ba", choose a sequence of removals that maximizes the total score. Each removal deletes two adjacent characters.

Key idea

Remove the higher-scoring pair first. A stack lets us remove each occurrence as soon as its two characters become adjacent; after that pass, remove the other pair from the remaining string.

Approach

  1. Decide which pair has the higher score.
  2. Scan the string with a stack, removing that pair whenever it appears at the top.
  3. Scan the remaining characters the same way for the other pair.
  4. Add both passes’ scores and return the total.
class Solution:
    def maximumGain(self, s: str, x: int, y: int) -> int:
        def remove_pairs(text: str, first: str, second: str, score: int):
            stack = []
            total = 0

            for char in text:
                if stack and stack[-1] == first and char == second:
                    stack.pop()
                    total += score
                else:
                    stack.append(char)

            return "".join(stack), total

        # Remove the more valuable pair before the less valuable one.
        if x >= y:
            remaining, high_score = remove_pairs(s, "a", "b", x)
            _, low_score = remove_pairs(remaining, "b", "a", y)
        else:
            remaining, high_score = remove_pairs(s, "b", "a", y)
            _, low_score = remove_pairs(remaining, "a", "b", x)

        return high_score + low_score

Complexity:

  • Time: O(n), since each character is processed a constant number of times.
  • Space: O(n), for the stacks holding characters that remain after each pass.

Common follow-ups

  • Can you avoid building a string between passes? Yes; use a stack for each pass and iterate over the first pass’s stack directly.
  • Why remove the higher-scoring pair first? Removing it greedily preserves its value; removing the lower-value pair first can destroy an opportunity to earn the higher score.
  • What if the input contains other characters? The stack naturally keeps them, and only the specified adjacent pairs are removed.
CodingMediumSwiggySoftware Engineer

14. Sort Colors (LeetCode)

Model answer

The task

Rearrange an array containing only 0, 1, and 2 so the values appear in ascending order. Modify the array in place.

Key idea

Use three pointers to divide the array into regions: 0s at the front, 2s at the back, and 1s in between. Each step places one value into its correct region, so the array is processed in one pass without extra storage.

Approach

  1. Set low to the start and high to the end of the array.
  2. Scan with current, starting at the beginning.
  3. If the current value is 0, swap it with low, then advance both pointers.
  4. If it is 1, advance current.
  5. If it is 2, swap it with high and move high left. Do not advance current, since the swapped-in value still needs inspection.
  6. Stop when current passes high.
class Solution:
    def sortColors(self, nums: list[int]) -> None:
        """Sort nums in place; return no value."""
        low = 0
        current = 0
        high = len(nums) - 1

        while current <= high:
            if nums[current] == 0:
                nums[low], nums[current] = nums[current], nums[low]
                low += 1
                current += 1
            elif nums[current] == 1:
                current += 1
            else:  # nums[current] == 2
                nums[current], nums[high] = nums[high], nums[current]
                high -= 1

Complexity:

  • Time: O(n), where n is the number of values; each pointer moves only across the array.
  • Space: O(1), since the rearrangement is in place.

Common follow-ups

  • What if there are k distinct values? Use counting or a generalized partitioning strategy; the best approach depends on whether extra passes or storage are allowed.
  • Must the sort be stable? This in-place partitioning is not stable; preserving the order of equal values may require extra space or a different algorithm.
  • What if values outside 0, 1, and 2 appear? Validate or define their placement, then adapt the partitioning logic accordingly.
CodingMediumSwiggySoftware Engineer

15. Design Twitter (LeetCode)

Model answer

The task

Build a small social feed service that lets users publish posts, follow or unfollow others, and retrieve the ten most recent posts visible to a user.

Key idea

Store each user’s posts in chronological order and track follow relationships with sets. To build a feed, merge the newest post from each followed user (and the user themselves) using a max-heap, advancing through a user’s posts as their entries are removed.

Approach

  1. Keep a monotonically increasing timestamp and append each post to its author’s list.
  2. Store each user’s followed accounts in a set.
  3. For a feed request, gather the latest post from each relevant account and heapify those candidates.
  4. Pop up to ten posts, adding the next older post from the same author after each pop.
  5. Make follow and unfollow set operations; include the feed owner explicitly so they always see their own posts.
from collections import defaultdict
import heapq

class Twitter:
    def __init__(self):
        self.time = 0
        self.posts = defaultdict(list)      # user -> [(timestamp, tweet_id), ...]
        self.following = defaultdict(set)   # user -> accounts they follow

    def postTweet(self, userId: int, tweetId: int) -> None:
        self.posts[userId].append((self.time, tweetId))
        self.time += 1

    def getNewsFeed(self, userId: int) -> list[int]:
        accounts = self.following[userId] | {userId}
        heap = []

        # Add the newest post from each account.
        for account in accounts:
            account_posts = self.posts[account]
            if account_posts:
                index = len(account_posts) - 1
                timestamp, tweet_id = account_posts[index]
                heap.append((-timestamp, tweet_id, account, index))

        heapq.heapify(heap)
        feed = []

        # Each pop gives the newest currently available post.
        while heap and len(feed) < 10:
            _, tweet_id, account, index = heapq.heappop(heap)
            feed.append(tweet_id)

            index -= 1
            if index >= 0:
                timestamp, older_tweet_id = self.posts[account][index]
                heapq.heappush(
                    heap, (-timestamp, older_tweet_id, account, index)
                )

        return feed

    def follow(self, followerId: int, followeeId: int) -> None:
        self.following[followerId].add(followeeId)

    def unfollow(self, followerId: int, followeeId: int) -> None:
        self.following[followerId].discard(followeeId)

Complexity:

  • Time: postTweet, follow, and unfollow are O(1) average. getNewsFeed is O(F + 10 log F), where F is the number of followed accounts plus the user.
  • Space: O(T + R), where T is the number of posts and R is the number of follow relationships; a feed request uses O(F) temporary space.

Common follow-ups

  • How would you handle a very large number of followed accounts? Consider cached feeds or a distributed merge service.
  • How would you support deleting posts? Mark posts as deleted and skip them during feed generation.
  • What if posts arrive out of order? Store them by timestamp and use an ordered index rather than relying on append order.
CodingMediumSwiggySoftware Engineer

16. Integer to Roman (LeetCode)

Model answer

The task

Convert a positive integer into its standard Roman numeral representation, using subtractive forms such as IV and CM where appropriate.

Key idea

Process Roman numeral values from largest to smallest, including the six subtractive combinations as single entries. At each value, emit it as many times as possible, then continue with the remainder.

Approach

  1. List the values and their Roman numeral symbols in descending order.
  2. For each value, use integer division to determine how many times it fits in the remaining number.
  3. Append that many copies of its symbol.
  4. Subtract the represented amount and continue.
  5. Join the symbols to form the result.
class Solution:
    def intToRoman(self, num: int) -> str:
        # Include subtractive pairs alongside the ordinary symbols.
        values = [
            (1000, "M"),
            (900, "CM"),
            (500, "D"),
            (400, "CD"),
            (100, "C"),
            (90, "XC"),
            (50, "L"),
            (40, "XL"),
            (10, "X"),
            (9, "IX"),
            (5, "V"),
            (4, "IV"),
            (1, "I"),
        ]

        result = []

        for value, symbol in values:
            count, num = divmod(num, value)
            result.append(symbol * count)

        return "".join(result)

Complexity:

  • Time: O(1) for the standard bounded integer range; each of the fixed 13 values is checked.
  • Space: O(1) auxiliary space; the result uses O(1) space for the bounded output.

Common follow-ups

  • How would you convert a Roman numeral back to an integer? Scan symbols and subtract a value when it is less than the next symbol.
  • What if the input can exceed the standard Roman numeral range? Define an extension convention, such as overlines for thousands, before adapting the mapping.
  • How would you validate a Roman numeral string? Parse it, convert it to an integer, then convert that integer back and compare with the original.
CodingMediumSwiggySoftware Engineer

17. Koko Eating Bananas (LeetCode)

Model answer

The task

Given pile sizes and a fixed number of hours, find the smallest integer eating speed that lets Koko finish all the bananas in time. Each pile is handled separately, and any leftover bananas in a pile still take a full hour.

Key idea

Feasibility is monotonic: if a speed works, any faster speed works too. Binary-search the range from 1 to the largest pile, checking each candidate speed by summing the hours needed for every pile.

Approach

  1. Set the search bounds to 1 and the largest pile size.
  2. For a candidate speed, compute each pile’s hours with ceiling division: (pile + speed - 1) // speed.
  3. If the total hours fit within the limit, record the speed and search lower.
  4. Otherwise, search higher.
  5. Return the smallest feasible speed.
class Solution:
    def minEatingSpeed(self, piles: list[int], h: int) -> int:
        left, right = 1, max(piles)

        while left < right:
            speed = (left + right) // 2

            # Check whether this speed finishes all piles in time.
            hours = sum((pile + speed - 1) // speed for pile in piles)

            if hours <= h:
                right = speed
            else:
                left = speed + 1

        return left

Complexity:

  • Time: O(n log m), where n is the number of piles and m is the largest pile; each binary-search check scans the piles.
  • Space: O(1), excluding the input; the check uses only a constant amount of extra space.

Common follow-ups

  • What if the hours limit is smaller than the number of piles? No speed can finish in time, since each nonempty pile takes at least one hour.
  • Can the search bounds be tightened? A lower bound can be derived from total bananas divided by available hours, rounded up.
  • What if piles can be processed in parallel? The feasibility calculation changes to account for concurrent work; this binary search applies when piles are eaten sequentially.
CodingMediumSwiggySoftware Engineer

18. 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.
CodingMediumSwiggySoftware Engineer

19. Merge Intervals (LeetCode)

Model answer

The task

Given a collection of intervals, combine every pair that overlaps and return the resulting non-overlapping intervals. The result should be ordered by starting point.

Key idea

Sort intervals by their start. Then scan once, keeping the most recently merged interval; each next interval either extends it or starts a new one.

Approach

  1. Sort the intervals by their start value.
  2. Initialize the result with the first interval, if any.
  3. For each remaining interval, compare its start with the end of the last result interval.
  4. If they overlap, update that end to the larger of the two ends.
  5. Otherwise, append the interval as a new result.
from typing import List

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

        intervals.sort(key=lambda interval: interval[0])
        merged = [intervals[0]]

        for start, end in intervals[1:]:
            # The intervals overlap, so extend the last merged interval.
            if start <= merged[-1][1]:
                merged[-1][1] = max(merged[-1][1], end)
            else:
                # No overlap: this interval begins a new merged range.
                merged.append([start, end])

        return merged

Complexity: Time: O(n log n), dominated by sorting n intervals.

Complexity: Space: O(n) for the merged result; sorting may also use up to O(n) space.

Common follow-ups

  • What if intervals that only touch at an endpoint should remain separate? Use start < merged[-1][1] as the overlap test.
  • How would you merge intervals as they arrive in sorted order? Skip sorting and apply the same scan, processing each interval once.
  • What if intervals are inserted one at a time into an already merged collection? Use binary search to find the insertion point, then merge neighboring overlaps.
CodingMediumSwiggySoftware Engineer

20. Immediate Food Delivery II (LeetCode)

Model answer

The task

For each customer, identify their earliest delivery order and determine whether it was scheduled for the same day it was placed. Return the percentage of customers whose first order was immediate, rounded to two decimal places.

Key idea

Rank each customer’s orders by order_date and keep only the earliest one. Then divide the number of immediate first orders by the total number of customers, multiplying by 100.

Approach

  1. Use ROW_NUMBER() to rank orders separately for each customer by order date.
  2. Filter to the first order for each customer.
  3. Count first orders where order_date equals customer_pref_delivery_date.
  4. Divide by the number of first orders, multiply by 100, and round to two decimal places.
WITH ranked_orders AS (
    SELECT
        customer_id,
        order_date,
        customer_pref_delivery_date,
        ROW_NUMBER() OVER (
            PARTITION BY customer_id
            ORDER BY order_date
        ) AS order_rank
    FROM Delivery
)
SELECT
    ROUND(
        100.0 * SUM(
            CASE
                WHEN order_date = customer_pref_delivery_date THEN 1
                ELSE 0
            END
        ) / COUNT(*),
        2
    ) AS immediate_percentage
FROM ranked_orders
WHERE order_rank = 1;

Complexity:

  • Time: O(n log n), due to ranking orders by date within each customer.
  • Space: O(n) for the ranked intermediate result, depending on the database’s execution plan.

Common follow-ups

  • How would you handle customers with no orders? They do not appear in Delivery, so they are excluded from the percentage.
  • What if a customer has multiple orders on their earliest date? Define a tie-breaking rule, such as ordering by delivery_id.
  • How could this be made faster for a large table? An index on (customer_id, order_date) may help the partitioning and ordering.

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