Meesho interview questions & answers

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

CodingEasyMeeshoSoftware Engineer

1. Rising Temperature (LeetCode)

Model answer

The task

Find each weather record whose temperature is higher than the temperature recorded on the immediately preceding calendar day. Return the IDs of those records.

Key idea

Join the table to itself, matching each record with the record dated exactly one day earlier. Comparing only adjacent rows would be incorrect because dates may have gaps.

Approach

  1. Treat one copy of the table as the current day and another as the previous day.
  2. Join them where the current date is one day after the previous date.
  3. Keep pairs where the current temperature is higher.
  4. Return the current record’s ID.
SELECT current_day.id AS Id
FROM Weather AS current_day
JOIN Weather AS previous_day
  ON current_day.recordDate = DATE_ADD(previous_day.recordDate, INTERVAL 1 DAY)
WHERE current_day.temperature > previous_day.temperature;

Complexity:

  • Time: O(n log n) with an index on recordDate; the exact cost depends on the database’s query plan.
  • Space: O(1) auxiliary space, excluding space used for the result and any database join workspace.

Common follow-ups

  • What if there are missing dates? The exact one-day join naturally skips dates without a prior-day record.
  • How could this perform better on a large table? Add an index on recordDate and inspect the database’s execution plan.
  • How would you adapt this for another SQL dialect? Replace DATE_ADD with that dialect’s date arithmetic, such as a one-day interval expression.
CodingMediumMeeshoSoftware Engineer

2. 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.
CodingMediumMeeshoSoftware Engineer

3. Number of Strings Which Can Be Rearranged to Contain Substring (LeetCode)

Model answer

The task

Count lowercase strings of length n whose characters can be rearranged so the result contains "leet". Return the count modulo 10^9 + 7.

Key idea

A string qualifies exactly when it has at least one l, at least one t, and at least two es. Track these counts, capping them at their required amounts; all other letters can be grouped together.

Approach

  1. Use DP states (l, t, e), where l and t are each 0 or 1, and e is 0, 1, or 2.
  2. Start with one empty string in state (0, 0, 0).
  3. For each position, transition using an l, t, or e, updating and capping its count.
  4. Add the 23 other lowercase letters as a transition that leaves the state unchanged.
  5. Return the state where all requirements are met.
class Solution:
    def stringCount(self, n: int) -> int:
        mod = 10**9 + 7

        # dp[l_seen][t_seen][e_count_capped_at_2]
        dp = [[[0] * 3 for _ in range(2)] for _ in range(2)]
        dp[0][0][0] = 1

        for _ in range(n):
            nxt = [[[0] * 3 for _ in range(2)] for _ in range(2)]

            for l_seen in range(2):
                for t_seen in range(2):
                    for e_count in range(3):
                        ways = dp[l_seen][t_seen][e_count]
                        if ways == 0:
                            continue

                        # Choose one of the 23 letters other than l, t, e.
                        nxt[l_seen][t_seen][e_count] += 23 * ways

                        # Choose l, t, or e.
                        nxt[1][t_seen][e_count] += ways
                        nxt[l_seen][1][e_count] += ways
                        nxt[l_seen][t_seen][min(2, e_count + 1)] += ways

            for l_seen in range(2):
                for t_seen in range(2):
                    for e_count in range(3):
                        nxt[l_seen][t_seen][e_count] %= mod

            dp = nxt

        return dp[1][1][2]

Complexity:

  • Time: O(n) — each position updates a fixed number of states.
  • Space: O(1) — the DP has only 12 states.

Common follow-ups

  • What if the required string has different repeated letters? Track each required letter count, capped at its needed frequency.
  • What if the alphabet is larger? Group irrelevant letters together; their transition is weighted by how many there are.
  • What if n is extremely large? Represent the fixed-state transitions as a matrix and use fast exponentiation.
CodingMediumMeeshoSoftware Engineer

4. 3Sum (LeetCode)

Model answer

The task

Given an integer array, return every distinct triplet of values whose sum is zero. Triplets are considered the same if they contain the same values, regardless of order.

Key idea

Sort the array, then fix each value in turn and use two pointers to find pairs that complete its sum to zero. Skipping repeated values prevents duplicate triplets.

Approach

  1. Sort the input array.
  2. For each index, treat its value as the first element of a triplet.
  3. Skip the index if its value is the same as the previous value.
  4. Set two pointers immediately after the fixed index and at the end of the array.
  5. Move a pointer according to whether the current sum is too small or too large.
  6. When a triplet is found, record it and advance past duplicate pointer values.
from typing import List

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        triplets = []
        n = len(nums)

        for i in range(n - 2):
            # Only use the first occurrence of each fixed value.
            if i > 0 and nums[i] == nums[i - 1]:
                continue

            left, right = i + 1, n - 1

            while left < right:
                total = nums[i] + nums[left] + nums[right]

                if total < 0:
                    left += 1
                elif total > 0:
                    right -= 1
                else:
                    triplets.append([nums[i], nums[left], nums[right]])
                    left += 1
                    right -= 1

                    # Avoid repeating the same pair for this fixed value.
                    while left < right and nums[left] == nums[left - 1]:
                        left += 1
                    while left < right and nums[right] == nums[right + 1]:
                        right -= 1

        return triplets

Complexity:

  • Time: O(n²), from fixing each value and scanning with two pointers.
  • Space: O(n) for Python's in-place sort; excludes the returned triplets.

Common follow-ups

  • How would you return unique index triplets instead of value triplets? Track original indices while sorting, then return the corresponding index triples.
  • What if the target sum is a variable? Replace the zero-sum check with a comparison against the target.
  • Can the approach be extended to four values? Fix two values and use two pointers for the remaining pair, giving O(n³) time.
CodingMediumMeeshoSoftware Engineer

5. Next Permutation (LeetCode)

Model answer

The task

Rearrange the array in place to produce the next lexicographically greater ordering of its values. If no greater ordering exists, wrap around to the smallest ordering.

Key idea

The suffix after the rightmost position where the sequence increases is in descending order, so it is already the largest arrangement of those values. Swap that position with the smallest value in the suffix that is still larger, then reverse the suffix to make it as small as possible.

Approach

  1. Scan from right to left to find the rightmost index whose value is smaller than the value after it.
  2. If such an index exists, scan from the end to find the rightmost value larger than the pivot, then swap them.
  3. Reverse the portion after the pivot. This also handles the case where no pivot exists: the whole array becomes ascending.
  4. Mutate the input list directly.
from typing import List

class Solution:
    def nextPermutation(self, nums: List[int]) -> None:
        n = len(nums)

        # Find the rightmost position that can be increased.
        pivot = n - 2
        while pivot >= 0 and nums[pivot] >= nums[pivot + 1]:
            pivot -= 1

        if pivot >= 0:
            # The suffix is descending; its rightmost value greater
            # than the pivot is the smallest value that can replace it.
            successor = n - 1
            while nums[successor] <= nums[pivot]:
                successor -= 1

            nums[pivot], nums[successor] = nums[successor], nums[pivot]

        # Reverse the suffix to make it the smallest possible ordering.
        left, right = pivot + 1, n - 1
        while left < right:
            nums[left], nums[right] = nums[right], nums[left]
            left += 1
            right -= 1

Complexity:

  • Time: O(n), with a constant number of linear scans.
  • Space: O(1), since the rearrangement is done in place.

Common follow-ups

  • Why choose the rightmost pivot? It preserves the longest possible prefix, making the next ordering as close as possible.
  • How are duplicate values handled? The strict comparisons skip equal values and still select the correct next ordering.
  • What if the input is already in descending order? No pivot exists, so reversing the full array produces the smallest ordering.
  • How would you return a new list instead? Copy the input first, then apply the same in-place algorithm to the copy.
CodingMediumMeeshoSoftware Engineer

6. Possible Bipartition (LeetCode)

Model answer

The task

Given a set of people and pairs who cannot be in the same group, determine whether everyone can be split into two groups without violating any pair.

Key idea

Treat people as vertices and each disliked pair as an edge. A valid split exists exactly when the graph is bipartite, so we can try to color each connected component with two alternating colors.

Approach

  1. Build an adjacency list from the disliked pairs.
  2. Keep a color for each person: uncolored, group one, or group two.
  3. Start a BFS from each uncolored person to cover every component.
  4. For each edge, assign an uncolored neighbor the opposite color.
  5. If adjacent people already have the same color, return False; otherwise return True after checking all components.
from collections import deque
from typing import List

class Solution:
    def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:
        graph = [[] for _ in range(n + 1)]

        for a, b in dislikes:
            graph[a].append(b)
            graph[b].append(a)

        # 0 means uncolored; 1 and -1 represent the two groups.
        color = [0] * (n + 1)

        for person in range(1, n + 1):
            if color[person] != 0:
                continue

            color[person] = 1
            queue = deque([person])

            while queue:
                current = queue.popleft()

                for neighbor in graph[current]:
                    if color[neighbor] == 0:
                        color[neighbor] = -color[current]
                        queue.append(neighbor)
                    elif color[neighbor] == color[current]:
                        return False

        return True

Complexity:

  • Time: O(n + m), where m is the number of disliked pairs; each person and edge is processed a constant number of times.
  • Space: O(n + m) for the adjacency list, colors, and BFS queue.

Common follow-ups

  • Can this be solved with DFS? Yes; recursively or iteratively color each component and reject same-colored neighbors.
  • How would you return the two groups? Collect people by their final color after all components are colored.
  • What if dislikes arrive dynamically? A standard disjoint-set structure can track opposite-group relationships, though handling arbitrary online additions requires careful parity tracking.
CodingMediumMeeshoSoftware Engineer

7. Asteroid Collision (LeetCode)

Model answer

The task

Given a sequence of signed asteroid sizes, simulate their movement and collisions. Return the asteroids that remain, in their original order.

Key idea

A collision can happen only when a right-moving asteroid is followed by a left-moving one. Keep surviving asteroids in a stack; resolve each possible collision with the stack’s most recent survivor.

Approach

  1. Start with an empty stack.
  2. Process asteroids from left to right.
  3. While the stack’s top moves right and the current asteroid moves left, compare their sizes.
  4. Remove the smaller asteroid; if they are equal, remove both. Stop resolving if the current asteroid is destroyed.
  5. Add the current asteroid if it survives, then return the stack.
from typing import List

class Solution:
    def asteroidCollision(self, asteroids: List[int]) -> List[int]:
        survivors: List[int] = []

        for asteroid in asteroids:
            alive = True

            # Only a right-moving survivor can collide with a left-moving one.
            while (
                alive
                and asteroid < 0
                and survivors
                and survivors[-1] > 0
            ):
                top = survivors[-1]

                if top < -asteroid:
                    # The top asteroid is smaller and is destroyed.
                    survivors.pop()
                elif top == -asteroid:
                    # Both asteroids are destroyed.
                    survivors.pop()
                    alive = False
                else:
                    # The current asteroid is smaller and is destroyed.
                    alive = False

            if alive:
                survivors.append(asteroid)

        return survivors

Complexity:

  • Time: O(n), since each asteroid is pushed and popped at most once.
  • Space: O(n) for the stack of surviving asteroids.

Common follow-ups

  • How would you handle zero-sized asteroids? Define their movement and collision behavior, then adjust the collision rules accordingly.
  • Can the result be computed in place? Yes, use the input list’s prefix as the stack, if modifying the input is allowed.
  • What if collisions occur in multiple dimensions? A single stack is no longer sufficient; the model needs spatial positions and directions.
CodingMediumMeeshoSoftware Engineer

8. Reach a Number (LeetCode)

Model answer

The task

Starting at zero on an infinite number line, each move must travel a distance equal to its move number, in either direction. Find the fewest moves needed to land exactly on the target.

Key idea

By symmetry, only the target’s absolute value matters. After n moves, traveling right every time reaches n(n + 1) / 2; reversing directions changes that position by an even amount, so a target is reachable when the difference has even parity.

Approach

  1. Take the absolute value of the target.
  2. Double an upper bound until its triangular sum reaches or exceeds the target.
  3. Binary-search for the smallest move count with a large enough triangular sum.
  4. Increase the count until the sum and target have matching parity.
class Solution:
    def reachNumber(self, target: int) -> int:
        target = abs(target)

        def triangular(n: int) -> int:
            return n * (n + 1) // 2

        # Find an upper bound whose triangular sum reaches the target.
        high = 1
        while triangular(high) < target:
            high *= 2

        # Find the smallest n with triangular(n) >= target.
        low = 0
        while low < high:
            mid = (low + high) // 2
            if triangular(mid) >= target:
                high = mid
            else:
                low = mid + 1

        moves = low

        # Each move reversal changes the final position by an even amount.
        while (triangular(moves) - target) % 2 != 0:
            moves += 1

        return moves

Complexity:

  • Time: O(log target) — doubling and binary search take logarithmic iterations; parity adjustment takes at most two more moves.
  • Space: O(1) — only a fixed number of values are stored.

Common follow-ups

  • How would you produce an actual sequence of directions? Start with all moves right, then reverse moves whose lengths sum to half the excess.
  • What happens for a negative target? The answer is unchanged; reflect every direction.
  • Can you avoid binary search? Yes; increment the move count until the triangular sum reaches the target, then adjust parity.
CodingMediumMeeshoSoftware Engineer

9. Minimum Time to Complete Trips (LeetCode)

Model answer

The task

Given machines that each complete trips at a fixed rate, find the smallest integer time by which they can collectively complete at least the requested number of trips.

Key idea

The number of completed trips is monotonic in time: if the machines can finish by time t, they can also finish by any later time. Binary search for the first feasible time, checking how many trips each machine can complete.

Approach

  1. Set the search range from 1 to min(time) * totalTrips. The fastest machine alone can finish by the upper bound.
  2. For a candidate time, sum candidate // duration across machines.
  3. Stop counting early if the sum reaches the target.
  4. If the candidate is feasible, search earlier times; otherwise, search later times.
  5. Return the first feasible time.
from typing import List

class Solution:
    def minimumTime(self, time: List[int], totalTrips: int) -> int:
        left = 1
        right = min(time) * totalTrips

        def can_finish(limit: int) -> bool:
            trips_done = 0

            for duration in time:
                trips_done += limit // duration
                if trips_done >= totalTrips:
                    return True

            return False

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

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

        return left

Complexity:

  • Time: O(n log U), where n is the number of machines and U = min(time) * totalTrips.
  • Space: O(1), excluding the input.

Common follow-ups

  • What if the number of trips must be exactly the target? The same feasibility check works when the requirement is “at least”; completing extra trips does not prevent reaching the target.
  • Can the upper bound be tightened? Yes. Any known feasible time can serve as an upper bound; the fastest machine’s bound is simple and safe.
  • How would you handle very large inputs? Use integer arithmetic and stop the trip-count loop as soon as it reaches the target, as above.
CodingMediumMeeshoSoftware Engineer

10. Jump Game II (LeetCode)

Model answer

The task

Given an array where each value is the maximum distance you can jump forward from that position, find the fewest jumps needed to reach the final index.

Key idea

Treat all indices reachable with the same number of jumps as a layer. While scanning a layer, track the farthest index the next jump can reach; when the current layer ends, commit one jump and move to the next layer.

Approach

  1. If the array has at most one element, return 0.
  2. Track the current layer’s end and the farthest index reachable while scanning it.
  3. When the scan reaches the layer’s end, increment the jump count and set the next layer’s end to the farthest reach.
  4. Stop once the final index is reachable. Return -1 if progress stalls and the end cannot be reached.
from typing import List

class Solution:
    def jump(self, nums: List[int]) -> int:
        n = len(nums)
        if n <= 1:
            return 0

        jumps = 0
        layer_end = 0
        farthest = 0

        # The final index needs no further scan: reaching it is sufficient.
        for i in range(n - 1):
            farthest = max(farthest, i + nums[i])

            if i == layer_end:
                # Finish this layer and take one jump into the next.
                if farthest == layer_end:
                    return -1  # Unreachable input.
                jumps += 1
                layer_end = farthest

                if layer_end >= n - 1:
                    return jumps

        return -1

Complexity:

  • Time: O(n), because each index is scanned once.
  • Space: O(1), because only a few counters are stored.

Common follow-ups

  • Return the actual jump path? Store a predecessor when extending the farthest reach, then backtrack from the final index.
  • What if some indices are unreachable? The implementation returns -1 if the scan cannot extend its reachable range.
  • Can the same method count jumps to any target index? Yes; treat that target as the end and stop when its layer becomes reachable.
CodingMediumMeeshoSoftware Engineer

11. Odd Even Linked List (LeetCode)

Model answer

The task

Rearrange a singly linked list so nodes at odd positions come first, followed by nodes at even positions. Keep the original relative order within both groups.

Key idea

Build the odd-position and even-position chains in place as we traverse the list. Keep the even-chain head so it can be attached after the odd chain when traversal ends.

Approach

  1. Return the list unchanged if it has fewer than two nodes.
  2. Set pointers for the current odd node, current even node, and the head of the even chain.
  3. Repeatedly link the next odd node into the odd chain, then the next even node into the even chain.
  4. Attach the even-chain head after the last odd node.
  5. Return the original head.
# Definition for singly-linked list:
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution:
    def oddEvenList(self, head: ListNode | None) -> ListNode | None:
        if head is None or head.next is None:
            return head

        odd = head
        even = head.next
        even_head = even

        while even is not None and even.next is not None:
            # Append the next node in the original sequence to the odd chain.
            odd.next = even.next
            odd = odd.next

            # Append the following node to the even chain.
            even.next = odd.next
            even = even.next

        # Join the two stable chains.
        odd.next = even_head
        return head

Complexity:

  • Time: O(n), where n is the number of nodes visited once.
  • Space: O(1), using only a fixed number of pointers.

Common follow-ups

  • What if the list has zero or one node? Return it unchanged.
  • Are nodes grouped by their values? No; grouping is by one-based position, regardless of values.
  • Can the relative order within each group change? No; this algorithm preserves it.
  • Can this be done without modifying links? Yes, but it would require extra storage to collect and rebuild the node order.
CodingMediumMeeshoSoftware Engineer

12. 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.
CodingMediumMeeshoSoftware Engineer

13. Design Exam Scores Tracker (LeetCode)

Model answer

The task

Design a tracker that records exam scores over time and answers queries for the total score recorded within an inclusive time range.

Key idea

Store exam times in order alongside prefix sums of scores. Binary search finds the first exam at or after the range’s start and the first exam after its end; subtracting the corresponding prefix sums gives the range total.

Approach

  1. Keep a sorted list of recorded times and a prefix-sum list starting with zero.
  2. When recording an exam, append its time and the new cumulative score.
  3. For a query, use bisect_left to find the first included exam.
  4. Use bisect_right to find the position just past the last included exam.
  5. Return the difference between the prefix sums at those positions.
from bisect import bisect_left, bisect_right

class ExamTracker:
    def __init__(self):
        self.times = []
        # prefix[i] is the sum of scores for the first i exams.
        self.prefix = [0]

    def record(self, time: int, score: int) -> None:
        self.times.append(time)
        self.prefix.append(self.prefix[-1] + score)

    def totalScore(self, startTime: int, endTime: int) -> int:
        left = bisect_left(self.times, startTime)
        right = bisect_right(self.times, endTime)
        return self.prefix[right] - self.prefix[left]

Complexity:

  • Time: record is O(1); totalScore is O(log n) due to binary search.
  • Space: O(n) for the recorded times and prefix sums.

Common follow-ups

  • What if exam times arrive out of order? Keep records sorted and update prefix sums, or use an ordered structure with subtree sums.
  • What if queries ask for an average? Divide the range sum by the number of exams in the range, found using the same two indices.
  • What if scores can be updated? Rebuild affected prefix sums, or use a Fenwick tree for efficient updates and range sums.
CodingMediumMeeshoSoftware Engineer

14. Subarray Product Less Than K (LeetCode)

Model answer

The task

Count the contiguous subarrays whose product is strictly less than k.

Key idea

With positive numbers, extending a window never decreases its product. Maintain the longest window whose product is below k; every suffix of that window ending at the current position also qualifies.

Approach

  1. If k <= 1, return 0, since positive-number products are at least 1.
  2. Expand the right edge, multiplying its value into the window product.
  3. While the product is at least k, move the left edge forward and divide out the values it passes.
  4. Add the window length to the count: each possible starting point in the current window gives one qualifying subarray ending at the right edge.
from typing import List

class Solution:
    def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
        if k <= 1:
            return 0

        left = 0
        product = 1
        count = 0

        for right, value in enumerate(nums):
            product *= value

            # Restore the condition that the window product is less than k.
            while product >= k:
                product //= nums[left]
                left += 1

            # Every nonempty suffix of this window is valid.
            count += right - left + 1

        return count

Complexity:

  • Time: O(n), since each element enters and leaves the window at most once.
  • Space: O(1), using only a few variables.

Common follow-ups

  • What if the array can contain zeros? Split at zeros, count positive-only ranges, and account for subarrays containing zero separately.
  • What if values can be negative? This sliding-window method no longer applies; products are not monotonic as the window grows.
  • Can the answer exceed a 32-bit integer? Yes; use an integer type large enough for the maximum subarray count.
CodingMediumMeeshoSoftware Engineer

15. Maximum Subarray (LeetCode)

Model answer

The task

Given an integer array, find the largest sum obtainable from a nonempty contiguous subarray. The array may contain only negative numbers.

Key idea

At each position, the best subarray ending there either starts at the current value or extends the best subarray ending just before it. Track that running best and the largest sum seen so far; this naturally handles all-negative arrays.

Approach

  1. Initialize both the running sum and overall maximum to the first value.
  2. Scan the remaining values from left to right.
  3. For each value, either start a new subarray there or extend the previous one.
  4. Update the overall maximum whenever the running sum improves.
  5. Return the overall maximum.
from typing import List

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        # The subarray must be nonempty, so start with the first element.
        current_sum = best_sum = nums[0]

        for value in nums[1:]:
            # Either begin at this value or extend the prior subarray.
            current_sum = max(value, current_sum + value)
            best_sum = max(best_sum, current_sum)

        return best_sum

Complexity:

  • Time: O(n), where n is the number of array elements; each is processed once.
  • Space: O(1), since only two running sums are stored.

Common follow-ups

  • How would you return the subarray’s start and end indices? Track the current start index and record both indices whenever the overall maximum improves.
  • What if the input can be empty? Define the desired empty-input result, then handle it before accessing the first element.
  • How does divide and conquer solve this? Recursively compute the best sum on each half, plus the best suffix on the left and prefix on the right; combine the three results.
CodingMediumMeeshoSoftware Engineer

16. Number of Unique XOR Triplets II (LeetCode)

Model answer

The task

Given a permutation of the integers from 1 through n, count the distinct XOR values obtainable by choosing three elements. The same element may be chosen more than once.

Key idea

Every result fits in the bit-width needed to represent n, so there are at most 2^n.bit_length() possible results. For n >= 3, the values from 1 through n can produce every XOR value in that range; for smaller arrays, count the results directly.

Approach

  1. Let n be the array length.
  2. If n < 3, return n: the possible XOR values are exactly the array’s elements.
  3. Otherwise, return 2^n.bit_length(). The input’s order does not affect the result.
class Solution:
    def uniqueXorTriplets(self, nums: list[int]) -> int:
        n = len(nums)

        # With fewer than three available values, the distinct results
        # are exactly those values.
        if n < 3:
            return n

        # For a permutation of 1..n, all values in this bit-width range
        # are attainable using three selections, with repetition allowed.
        return 1 << n.bit_length()

Complexity:

  • Time: O(1) — uses only the array length.
  • Space: O(1) — no extra storage.

Common follow-ups

  • What if the same index cannot be selected more than once? The coverage argument changes; the answer depends on the available distinct triples.
  • Does the permutation’s order matter? No. Only the set of values, 1 through n, determines the count.
  • How does the result change at powers of two? When n reaches a power of two, n.bit_length() increases, doubling the count.
CodingMediumMeeshoSoftware Engineer

17. Best Time to Buy and Sell Stock II (LeetCode)

Model answer

The task

Given a sequence of daily stock prices, compute the greatest profit possible when you may make multiple buy-and-sell transactions. You must sell before buying again and cannot hold more than one share at a time.

Key idea

Every upward move between consecutive days can contribute to the total profit. Summing all positive day-to-day increases captures the profit from each rising stretch without needing to choose its endpoints explicitly.

Approach

  1. Start with zero profit.
  2. Walk through each pair of consecutive prices.
  3. If the price rises, add that increase to the profit.
  4. Return the accumulated amount.
from typing import List

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        profit = 0

        # Collect each positive one-day price increase.
        for previous, current in zip(prices, prices[1:]):
            if current > previous:
                profit += current - previous

        return profit

Complexity:

  • Time: O(n), where n is the number of prices; each price is examined once.
  • Space: O(1), excluding the temporary iterator used to traverse the prices.

Common follow-ups

  • What if each sale has a transaction fee? Track holding and not-holding states, subtracting the fee when selling.
  • What if there is a cooldown after selling? Use dynamic programming states that track whether buying is currently allowed.
  • What if only k transactions are allowed? Use dynamic programming over the number of completed transactions and holding status.
CodingMediumMeeshoSoftware Engineer

18. Consecutive Numbers (LeetCode)

Model answer

The task

Return each number that appears in at least three rows whose IDs are consecutive. Report a number only once, even if it occurs in multiple qualifying runs.

Key idea

Join the table to itself three times, matching adjacent IDs and equal numbers. DISTINCT removes duplicates from overlapping runs.

Approach

  1. Use one copy of Logs as the first row in a potential run.
  2. Join a second copy where the ID is one greater and the number matches.
  3. Join a third copy where the ID is one greater again and the number still matches.
  4. Select the matching number once.
SELECT DISTINCT first_row.num AS ConsecutiveNums
FROM Logs AS first_row
JOIN Logs AS second_row
  ON second_row.id = first_row.id + 1
 AND second_row.num = first_row.num
JOIN Logs AS third_row
  ON third_row.id = second_row.id + 1
 AND third_row.num = first_row.num;

Complexity:

  • Time: O(n) with indexed IDs, scanning rows and performing indexed lookups.
  • Space: O(k) for the distinct result set, where k is the number of qualifying numbers.

Common follow-ups

  • What if the required run length is configurable? Generate or construct joins for that length, or use window functions to group consecutive equal values.
  • How do you avoid missing a number that appears in overlapping runs? Keep DISTINCT, which collapses repeated matches.
  • What if IDs are not consecutive integers? Define consecutiveness using the relevant ordering and compare each row with its actual successor.
CodingMediumMeeshoSoftware Engineer

19. Number of Unique XOR Triplets I (LeetCode)

Model answer

The task

Given a permutation of the integers from 1 to n, count the distinct values obtainable by XORing three array elements. An element may be used more than once.

Key idea

For n >= 3, the possible XOR values cover every number from 0 up to one less than the smallest power of two strictly greater than n. The small cases n = 1 and n = 2 need separate handling.

Approach

  1. Let n be the array length.
  2. If n == 1, only one XOR value is possible.
  3. If n == 2, the three possible values are the two elements and their XOR.
  4. Otherwise, n.bit_length() gives the exponent of the smallest power of two greater than n; return that power.
class Solution:
    def uniqueXorTriplets(self, nums: list[int]) -> int:
        n = len(nums)

        if n == 1:
            return 1
        if n == 2:
            return 3

        # For n >= 3, all values in this XOR range are attainable.
        return 1 << n.bit_length()

Complexity:

  • Time: O(1), using only the array length.
  • Space: O(1), using a fixed number of variables.

Common follow-ups

  • What if the array is not a permutation of 1..n? The result can depend on the actual values; use a set-based or bitset approach to track attainable XORs.
  • What if only distinct indices are allowed? The attainable values change, and small inputs may have no valid triplets.
  • Why are the small cases separate? With one or two values, the general full-range result does not hold.
CodingMediumMeeshoSoftware Engineer

20. Exchange Seats (LeetCode)

Model answer

The task

Return every student’s seat after swapping each pair of neighboring seats. If the final seat has no partner, its student stays there.

Key idea

The seat IDs are consecutive and start at 1, so each odd ID swaps with the next ID, and each even ID swaps with the previous one. Keep the last ID unchanged when the total number of seats is odd.

Approach

  1. Count the rows to identify whether the final seat is unpaired.
  2. For an odd ID that is the final seat, keep its ID.
  3. For other odd IDs, assign the next ID; for even IDs, assign the previous ID.
  4. Return the assigned IDs with the students, ordered by the new IDs.
SELECT
    CASE
        WHEN id % 2 = 1 AND id = (SELECT COUNT(*) FROM Seat) THEN id
        WHEN id % 2 = 1 THEN id + 1
        ELSE id - 1
    END AS id,
    student
FROM Seat
ORDER BY id;

Complexity:

  • Time: O(n log n), primarily to order the result; counting scans the rows.
  • Space: O(n) in the worst case if sorting requires a temporary structure.

Common follow-ups

  • What if IDs are not consecutive? Pair rows by their order, for example with ROW_NUMBER(), then swap adjacent row numbers.
  • Can the result be updated in place? Use a temporary mapping or a safe two-phase update to avoid ID collisions.
  • What if there are no seats? The query naturally returns no rows.

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