Ola interview questions & answers

20 real Ola interview questions with full model answers — System design, Technical, Coding. Drawn from the same verified bank ChannelPulse drills from (31 Ola questions in total).

CodingEasyOlaSoftware Engineer

1. Two Sum (LeetCode)

Model answer

The task

Given a list of integers and a target, return the indices of two distinct elements whose values add up to the target. The usual version guarantees a valid pair.

Key idea

As we scan the list, store each value’s index in a hash table. For the current value, check whether its needed complement has already appeared; this finds a pair in one pass.

Approach

  1. Create a dictionary mapping previously seen values to their indices.
  2. For each element, compute the complement needed to reach the target.
  3. If that complement is in the dictionary, return its stored index and the current index.
  4. Otherwise, store the current value and index, then continue.
from typing import List

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        # Map each value already visited to its index.
        seen = {}

        for index, value in enumerate(nums):
            complement = target - value

            # A match must come from an earlier, distinct element.
            if complement in seen:
                return [seen[complement], index]

            seen[value] = index

        # The standard problem guarantees a solution.
        raise ValueError("No two elements sum to the target")

Complexity:

  • Time: O(n), where n is the number of elements; each lookup and insertion is O(1) on average.
  • Space: O(n), for the dictionary of values seen so far.

Common follow-ups

  • What if there may be multiple valid pairs? Return the first pair found, or keep searching and collect pairs according to the required output rules.
  • What if the input is sorted? Use two pointers from opposite ends for O(1) extra space; preserve original indices if those are required.
  • What if values repeat? The dictionary stores indices, and checking before insertion ensures the current element is not paired with itself.
CodingEasyOlaSoftware Engineer

2. Find Pivot Index (LeetCode)

Model answer

The task

Given an integer array, return the leftmost index where the sum of the elements before it equals the sum of the elements after it. Return -1 if no such index exists.

Key idea

Compute the total sum once, then scan from left to right while maintaining the sum to the left. At each index, the right sum is the total minus the left sum and the current element.

Approach

  1. Sum all elements to get the total.
  2. Initialize the running left sum to zero.
  3. For each index, compare the left sum with total - left_sum - nums[index].
  4. Return the index when the sums match; otherwise, add the current value to the left sum.
  5. Return -1 if the scan finishes without a match.
from typing import List

class Solution:
    def pivotIndex(self, nums: List[int]) -> int:
        total = sum(nums)
        left_sum = 0

        for i, value in enumerate(nums):
            right_sum = total - left_sum - value

            if left_sum == right_sum:
                return i

            left_sum += value

        return -1

Complexity:

  • Time: O(n), for one pass through the array after summing it.
  • Space: O(1), using only a fixed number of extra variables.

Common follow-ups

  • What if there are multiple pivot indices? The left-to-right scan returns the first; collect each matching index instead if all are required.
  • Can this handle negative values? Yes. The equality check relies on sums, not on values being positive.
  • What if the array is updated repeatedly? A single update changes the sums for many indices; a Fenwick tree or segment tree can support range-sum queries and updates more efficiently.
CodingEasyOlaSoftware Engineer

3. Excel Sheet Column Title (LeetCode)

Model answer

The task

Convert a positive column number into its Excel-style column label, where labels use uppercase letters and continue past Z with combinations such as AA.

Key idea

This is a base-26 representation with digits 1 through 26, rather than the usual 0 through 25. Subtract one before each division so the remainder maps directly to A through Z.

Approach

  1. Start with the given column number.
  2. Subtract one to shift its range to 0 through 25.
  3. Use division and remainder by 26 to find the next letter.
  4. Append that letter and continue with the quotient.
  5. Reverse the collected letters to form the label.
class Solution:
    def convertToTitle(self, columnNumber: int) -> str:
        letters = []

        while columnNumber > 0:
            # Shift to a zero-based range so the remainder maps to A-Z.
            columnNumber -= 1
            remainder = columnNumber % 26
            letters.append(chr(ord("A") + remainder))
            columnNumber //= 26

        return "".join(reversed(letters))

Complexity:

  • Time: O(log n), where n is the column number; each iteration processes one base-26 digit.
  • Space: O(log n) for the output letters.

Common follow-ups

  • How would you convert a column label back to a number? Accumulate digits in base 26, mapping A to 1 through Z to 26.
  • What changes if labels use a different alphabet size? Replace 26 with the alphabet size and map remainders to its characters.
  • What if the input is zero or negative? The stated conversion is for positive column numbers; define input validation behavior if those values must be handled.
CodingEasyOlaSoftware Engineer

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

5. Climbing Stairs (LeetCode)

Model answer

The task

Count how many distinct ways there are to reach the top of a staircase with n steps when each move advances either one or two steps.

Key idea

To reach step i, the last move must come from step i - 1 or i - 2. Thus the number of ways to reach i is the sum of the ways to reach those two earlier steps. Only the previous two counts are needed, so there is no need to store a full table.

Approach

  1. Set the number of ways to reach step 0 to 1, representing the single empty sequence of moves.
  2. Set the number of ways to reach step 1 to 1.
  3. For each step from 2 through n, add the counts for the preceding two steps.
  4. Return the count for step n.
class Solution:
    def climbStairs(self, n: int) -> int:
        # Ways to reach steps 0 and 1.
        two_back = 1
        one_back = 1

        # Build the count using the two preceding results.
        for _ in range(2, n + 1):
            current = two_back + one_back
            two_back = one_back
            one_back = current

        return one_back

Complexity:

  • Time: O(n), since each step is processed once.
  • Space: O(1), since only two prior counts are retained.

Common follow-ups

  • What if each move can advance 1, 2, or 3 steps? Sum the counts for the previous three steps.
  • What if the result must be returned modulo a number? Apply the modulus after each addition.
  • What if some steps are forbidden? Set their ways count to zero and use dynamic programming for the allowed steps.
CodingMediumOlaSoftware Engineer

6. 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.
CodingMediumOlaFrontend EngineerRound 3: Platform round

7. Create a generic, configurable slider or carousel using any framework, displaying only 3 slides at a time.

Model answer

Here’s a reusable React carousel that shows at most three slides, advances one slide at a time, and optionally wraps at either end. The caller controls slide rendering and can configure the gap and looping behavior.

import React, { useEffect, useState } from 'react';

export function Carousel({
  slides,
  renderSlide = (slide) => slide,
  keyExtractor = (slide, index) => slide?.id ?? index,
  gap = 16,
  loop = false
}) {
  const [index, setIndex] = useState(0);
  const maxStart = Math.max(0, slides.length - 3);
  const canMove = slides.length > 3;

  // Keep the selected window valid if the slide list changes.
  useEffect(() => {
    setIndex((current) => Math.min(current, maxStart));
  }, [maxStart]);

  function previous() {
    setIndex((current) => {
      if (current > 0) return current - 1;
      return loop && canMove ? maxStart : current;
    });
  }

  function next() {
    setIndex((current) => {
      if (current < maxStart) return current + 1;
      return loop && canMove ? 0 : current;
    });
  }

  const visibleSlides = slides.slice(index, index + 3);

  return (
    <section aria-label='Carousel'>
      <div
        style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
          gap: `${gap}px`
        }}
        aria-live='polite'
      >
        {visibleSlides.map((slide, offset) => {
          const slideIndex = index + offset;
          return (
            <div key={keyExtractor(slide, slideIndex)}>
              {renderSlide(slide, slideIndex)}
            </div>
          );
        })}
      </div>

      <div style={{ display: 'flex', gap: '8px', marginTop: '12px' }}>
        <button
          type='button'
          onClick={previous}
          disabled={!canMove || (!loop && index === 0)}
          aria-label='Previous slides'
        >
          Previous
        </button>
        <button
          type='button'
          onClick={next}
          disabled={!canMove || (!loop && index === maxStart)}
          aria-label='Next slides'
        >
          Next
        </button>
      </div>
    </section>
  );
}
  • slides is the data source; renderSlide lets the caller supply any card or component.
  • The visible window is slides.slice(index, index + 3); controls disable at the ends unless loop is enabled.

Complexity: Rendering the visible window takes O(3) time and space; each navigation update takes O(1) time and state space.

CodingMediumOlaSoftware Engineer

8. 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.
CodingMediumOlaSoftware Engineer

9. Decode String (LeetCode)

Model answer

The task

Decode a string where a number before brackets indicates how many times to repeat the bracketed section. Sections may be nested.

Key idea

Parse the input into a compact tree of literal fragments and repeat nodes instead of expanding nested sections immediately. Then traverse that tree to produce the decoded string, avoiding repeated copying of large intermediate strings.

Approach

  1. Scan the input, accumulating each repetition count.
  2. On an opening bracket, save the current fragment list and count, then start a new list.
  3. On a closing bracket, wrap the current list in a repeat node and add it to its parent.
  4. Traverse the resulting structure with an explicit stack, yielding literal fragments as they are needed.
  5. Join the yielded fragments into the result.
class Solution:
    def decodeString(self, s: str) -> str:
        # Each repeat node is a (count, fragments) tuple.
        current = []
        stack = []
        count = 0

        for char in s:
            if "0" <= char <= "9":
                count = count * 10 + int(char)
            elif char == "[":
                stack.append((current, count))
                current = []
                count = 0
            elif char == "]":
                parent, repeat = stack.pop()
                # Omit zero repetitions so traversal skips empty sections.
                if repeat:
                    parent.append((repeat, current))
                current = parent
            else:
                current.append(char)

        def fragments():
            # Frames contain a fragment list, its next index, and
            # how many times to traverse that list.
            frames = [[current, 0, 1]]

            while frames:
                parts, index, remaining = frames[-1]

                if index == len(parts):
                    remaining -= 1
                    if remaining == 0:
                        frames.pop()
                    else:
                        frames[-1][1] = 0
                        frames[-1][2] = remaining
                    continue

                node = parts[index]
                frames[-1][1] += 1

                if isinstance(node, str):
                    yield node
                else:
                    repeat, nested = node
                    frames.append([nested, 0, repeat])

        return "".join(fragments())

Complexity:

  • Time: O(n + m), where n is the encoded length and m is the decoded length.
  • Space: O(n + m) for the parsed structure and returned string.

Common follow-ups

  • How would you handle malformed input? Validate bracket balance and ensure each opening bracket has a preceding count.
  • How could this support streaming output? Yield decoded fragments to a consumer instead of joining them into one string.
  • What if the grammar adds escaping or other operators? Extend the parser with explicit rules and represent each operation as a distinct node.
CodingMediumOlaSoftware Engineer

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

11. All Nodes Distance K in Binary Tree (LeetCode)

Model answer

The task

Return the values of all nodes exactly k edges from a given target node in a binary tree. The nodes may be reached through child links or by moving to a parent.

Key idea

Add parent links to the tree, turning it into a graph where each node has at most three neighbors. Then use breadth-first search from the target, stopping after k layers.

Approach

  1. Traverse the tree and record each node’s parent.
  2. Start BFS at the target, marking it visited.
  3. For each node, consider its left child, right child, and parent.
  4. After k layers, return the values in the queue.
from collections import deque
from typing import List

class Solution:
    def distanceK(self, root, target, k: int) -> List[int]:
        if root is None or k < 0:
            return []

        # Record each node's parent so the tree can be traversed in both directions.
        parent = {root: None}
        stack = [root]

        while stack:
            node = stack.pop()

            if node.left:
                parent[node.left] = node
                stack.append(node.left)

            if node.right:
                parent[node.right] = node
                stack.append(node.right)

        if target not in parent:
            return []

        queue = deque([target])
        visited = {target}
        distance = 0

        while queue and distance < k:
            for _ in range(len(queue)):
                node = queue.popleft()

                for neighbor in (node.left, node.right, parent[node]):
                    if neighbor is not None and neighbor not in visited:
                        visited.add(neighbor)
                        queue.append(neighbor)

            distance += 1

        return [node.val for node in queue] if distance == k else []

Complexity:

  • Time: O(n), to build parent links and perform BFS.
  • Space: O(n), for the parent map, queue, and visited set.

Common follow-ups

  • What if node values are duplicated? Identify nodes by object identity, not by value.
  • Can the tree remain unchanged? Yes; the parent map is stored separately.
  • What if many targets are queried? Build the parent map once and reuse it.
CodingMediumOlaSoftware Engineer

12. Add Two Numbers (LeetCode)

Model answer

The task

Each linked list stores a non-negative integer one digit per node, with the least significant digit first. Return a new linked list containing their sum in the same order.

Key idea

Add corresponding digits from left to right, carrying any value of 10 or more into the next position. Continue until both lists and the carry are exhausted, so a final carry gets its own node.

Approach

  1. Create a dummy node to simplify building the result.
  2. Track the current nodes and a carry initialized to zero.
  3. While either list has digits or a carry remains, add the available digits and carry.
  4. Use division and remainder by 10 to get the next carry and result digit.
  5. Append the digit, advance whichever input nodes exist, and return the node after the dummy.
from typing import Optional

class ListNode:
    def __init__(self, val: int = 0, next: Optional["ListNode"] = None):
        self.val = val
        self.next = next

class Solution:
    def addTwoNumbers(
        self, l1: Optional[ListNode], l2: Optional[ListNode]
    ) -> Optional[ListNode]:
        dummy = ListNode()
        tail = dummy
        carry = 0

        while l1 is not None or l2 is not None or carry:
            total = carry

            if l1 is not None:
                total += l1.val
                l1 = l1.next

            if l2 is not None:
                total += l2.val
                l2 = l2.next

            carry, digit = divmod(total, 10)
            tail.next = ListNode(digit)
            tail = tail.next

        return dummy.next

Complexity:

  • Time: O(max(m, n)), where m and n are the list lengths.
  • Space: O(max(m, n)) for the newly created result; O(1) auxiliary space.

Common follow-ups

  • What if digits are stored most significant first? Reverse the lists, or use stacks to add from the ends without modifying them.
  • Can the input lists be modified to save space? Reuse nodes from one list to store result digits, while handling any remaining carry.
  • How would you implement this recursively? Recurse node by node, passing the carry and treating a missing node as digit zero.
CodingMediumOlaSoftware Engineer

13. Validate Binary Search Tree (LeetCode)

Model answer

The task

Determine whether a binary tree satisfies binary search tree ordering: every node must be strictly greater than all values in its left subtree and strictly less than all values in its right subtree.

Key idea

Checking only a node against its immediate children is not enough; values must also obey the limits imposed by every ancestor. Carry an exclusive lower and upper bound down the tree, tightening them as each node is visited.

Approach

  1. Start at the root with no lower or upper bound.
  2. For each node, reject it if it is not strictly inside the current bounds.
  3. Recursively check the left child with the node’s value as its new upper bound.
  4. Recursively check the right child with the node’s value as its new lower bound.
  5. An empty subtree is valid; return whether both child checks pass.
from typing import Optional

class Solution:
    def isValidBST(self, root: Optional[TreeNode]) -> bool:
        def check(
            node: Optional[TreeNode],
            lower: Optional[int],
            upper: Optional[int],
        ) -> bool:
            if node is None:
                return True

            # Bounds are exclusive, so duplicate values are rejected.
            if lower is not None and node.val <= lower:
                return False
            if upper is not None and node.val >= upper:
                return False

            return (
                check(node.left, lower, node.val)
                and check(node.right, node.val, upper)
            )

        return check(root, None, None)

Complexity:

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

Common follow-ups

  • How would you handle duplicate values? Define a consistent rule for which side may contain equals, then adjust the bound checks accordingly.
  • Can this be done iteratively? Use a stack of nodes with their lower and upper bounds.
  • What happens on a skewed tree? The time remains O(n), while recursion stack space grows to O(n); an iterative version avoids recursion depth limits.
CodingMediumOlaSoftware Engineer

14. Container With Most Water (LeetCode)

Model answer

The task

Given nonnegative heights arranged along a line, choose two positions to form a container with the greatest possible area. Its area is the distance between the positions multiplied by the shorter of their two heights.

Key idea

Start with the widest possible pair, at the two ends. The shorter side limits the area, so moving the taller side inward cannot improve that limiting height and only reduces the width. Move the shorter side instead, hoping to find a taller boundary.

Approach

  1. Set pointers to the first and last positions.
  2. Compute the area using their distance and the shorter height; update the best area.
  3. Move the pointer at the shorter height inward by one position.
  4. Repeat until the pointers meet.
  5. Return the greatest area seen.
from typing import List

class Solution:
    def maxArea(self, height: List[int]) -> int:
        left = 0
        right = len(height) - 1
        best_area = 0

        while left < right:
            width = right - left
            limiting_height = min(height[left], height[right])
            best_area = max(best_area, width * limiting_height)

            # The shorter side limits this container's area.
            # Moving the taller side inward cannot improve that limit.
            if height[left] <= height[right]:
                left += 1
            else:
                right -= 1

        return best_area

Complexity:

  • Time: O(n), because each pointer moves inward at most n times.
  • Space: O(1), since only a few variables are used.

Common follow-ups

  • What if heights can be negative? A negative height does not describe a valid container; clarify the input rules, or treat invalid heights as unusable.
  • Why is it safe to discard the shorter side? With the same shorter boundary, every inward pair has less width, so it cannot produce a larger area.
  • Can this be done with extra memory? Not usefully for this objective; the two-pointer scan already processes the candidates in linear time with constant space.
CodingMediumOlaSoftware Engineer

15. House Robber (LeetCode)

Model answer

The task

Given a row of houses with a nonnegative amount of money in each, choose houses to rob so that no two neighboring houses are chosen. Return the largest total amount.

Key idea

For each house, the best total either skips it or robs it and adds its value to the best total two houses earlier. Keep only the previous two best totals, since earlier results are no longer needed.

Approach

  1. Set the best totals for the first two positions to zero.
  2. Scan the house values from left to right.
  3. For each value, compare the best total from skipping this house with the total from robbing it.
  4. Advance the two rolling totals and return the best total after the final house.
from typing import List

class Solution:
    def rob(self, nums: List[int]) -> int:
        # best_two_back and best_one_back hold the optimal totals
        # for the prefixes ending two and one positions earlier.
        best_two_back = 0
        best_one_back = 0

        for amount in nums:
            # Either skip this house, or rob it and add the best
            # total that cannot include its immediate neighbor.
            current = max(best_one_back, best_two_back + amount)

            best_two_back = best_one_back
            best_one_back = current

        return best_one_back

Complexity:

  • Time: O(n), where n is the number of houses scanned once.
  • Space: O(1), using two rolling totals rather than a table.

Common follow-ups

  • What if the houses are arranged in a circle? Solve two linear ranges: exclude the first house or exclude the last, then take the larger result.
  • How would you return which houses were robbed? Store the best total for each prefix, then backtrack the choices.
  • What if some house values are negative? The recurrence still works when robbing no houses is allowed; it will never choose a negative-value house.
CodingMediumOlaSoftware Engineer

16. Unique Paths (LeetCode)

Model answer

The task

Count the routes from the upper-left to the lower-right of an m-by-n grid when each move goes either right or down.

Key idea

The number of ways to reach a cell is the sum of the ways to reach the cell above and the cell to its left. Keep only one row of counts, since each update needs just those two values.

Approach

  1. Make the smaller grid dimension the stored row to reduce space.
  2. Initialize every cell in the first row to one: there is only one way to move right along it.
  3. For each later row, update each cell by adding the count from its left to the count already stored from above.
  4. Return the count at the final cell.
class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        # Keep the DP array as short as possible.
        if m < n:
            m, n = n, m

        # The first row has one way to reach each cell.
        paths = [1] * n

        # Update each row using the value above and the value to the left.
        for _ in range(1, m):
            for col in range(1, n):
                paths[col] += paths[col - 1]

        return paths[-1]

Complexity:

  • Time: O(mn), updating each cell once.
  • Space: O(min(m, n)), storing one row of counts.

Common follow-ups

  • How would you handle blocked cells? Set a blocked cell’s count to zero as each row is updated.
  • Can you compute the count without dynamic programming? Use the binomial coefficient C(m + n - 2, m - 1), since every route consists of a fixed number of down and right moves.
  • What if only the number of routes using exactly k turns is needed? Extend the state to track the last move direction and the number of turns.
System designMediumOlaFrontend EngineerRound 2: System Design

17. How would you store users’ locations and use them to search for products within the specified radius?

Model answer

1. Requirements & scale

Functional requirements

  • Store a location for each active listing and search for listings within a buyer-selected radius, such as 5 km.
  • Support a buyer-selected center: current location, map pin, or saved address. A seller’s listing location need not be their precise home address.
  • Combine distance filtering with text, category, price, and listing-status filters; paginate results consistently.

Non-functional requirements

  • Return correct radius membership, with low latency at city scale and predictable behavior near cell or shard boundaries.
  • Protect location privacy, tolerate stale search indexes, and avoid making location permission mandatory.

Back-of-the-envelope scale

  • Assume 20 million active listings and 1,200 peak search QPS. At roughly 1 KB per indexed listing, primary search documents are about 20 GB before replicas and index overhead; plan for several times that amount.
  • If each search returns 20 cards and each card is about 1 KB excluding images, 1,200 QPS produces roughly 24 MB/s of result payload at peak. CDN-backed thumbnails should be fetched separately and resized.

2. High-level architecture

flowchart TD
  subgraph C["Client"]
    App["Web and mobile app"]
    Geo["Location permission or map pin"]
  end
  subgraph E["Edge/CDN"]
    CDN["CDN and WAF"]
  end
  subgraph L["Load Balancer"]
    LB["API gateway"]
  end
  subgraph A["API / Services"]
    Search["Geo search API"]
    Listings["Listing API"]
    Privacy["Location privacy service"]
  end
  subgraph K["Cache"]
    Cache["Redis query cache"]
  end
  subgraph D["Datastores"]
    SQL["PostgreSQL with PostGIS"]
    GeoIndex["Search index with geo points"]
    Blob["Object storage"]
  end
  subgraph Q["Message Queue"]
    Events["Listing change events"]
  end
  subgraph X["Workers"]
    Worker["Geo index workers"]
  end
  App -->|"search request"| CDN
  Geo -->|"chosen search center"| App
  CDN -->|"API request"| LB
  LB --> Search
  LB --> Listings
  Listings -->|"precise or approved listing point"| Privacy
  Privacy -->|"validated location"| SQL
  Listings -->|"listing change"| Events
  Events --> Worker
  Worker -->|"geo document upsert"| GeoIndex
  Search -->|"coarse query cache"| Cache
  Search -->|"radius query and filters"| GeoIndex
  Search -->|"authoritative detail check"| SQL
  App -->|"thumbnail request"| CDN
  CDN -->|"image"| Blob
Diagram

3. API design

  • POST /v1/listings — create a listing with a validated location or location token; require seller authentication.
  • PATCH /v1/listings/{id}/location — update a listing’s search location, with ownership checks and audit history.
  • GET /v1/search?lat=...&lon=...&radius_m=5000&q=...&category=...&cursor=... — return matching listings and approximate distance.
  • POST /v1/location/geocode — optionally convert a user-selected place into a location token; do not geocode an address without user consent.

Validate latitude and longitude ranges, supported radius limits, and maximum result size. Avoid logging raw coordinates or putting them in analytics events.

4. Data model & storage

Authoritative store: PostgreSQL with PostGIS. A listing row can include id, seller_id, status, category_id, title, price, location geography(Point, 4326), location_precision, and timestamps. Store the point in longitude/latitude order and create a GiST index on the geography column. PostGIS provides accurate distance calculations and useful transactional constraints.

Search read model: A geo-capable search index, such as OpenSearch, stores a geo_point plus searchable text and filter fields. It is optimized for text relevance and geo-distance queries. Treat it as rebuildable, not as the source of truth.

If using a grid such as H3 or geohash, store a cell ID as an additional candidate-routing/indexing field, not as the sole location representation. Cell membership alone is not an exact radius test. Keep the actual point for final distance filtering.

For a large deployment, partition the index by broad region or a suitable spatial scheme, with overlap or neighboring-cell fanout at boundaries. Do not shard only on a fine grid without measuring skew: city centers can be much hotter than rural cells.

5. Deep dive

For a 5 km query, first retrieve candidates efficiently, then ensure exact membership. With PostGIS the canonical predicate is ST_DWithin(location, query_point, radius_meters) on the geography type; it uses the spatial index to narrow candidates and evaluates distance in meters. If the search index serves the query, use its geo-distance filter, then optionally verify critical results against the authoritative store. Be explicit about whether the product uses straight-line distance or road travel time; a radius normally means straight-line distance.

A grid index can help route queries to relevant partitions: determine cells intersecting the search circle, query those cells, and apply exact distance to candidates. The cell covering must include every cell intersecting the circle; querying only the center cell will miss valid listings near cell boundaries. For a small number of global regions, a single managed geo index is usually simpler and less error-prone.

sequenceDiagram
  participant App as Client
  participant API as Search API
  participant Cache as Redis
  participant Index as Geo Search Index
  participant SQL as PostgreSQL
  App->>API: center, radius, filters, cursor
  API->>API: validate and normalize query
  API->>Cache: lookup coarse-cell cache key
  alt cache hit
    Cache-->>API: candidate result page
  else cache miss
    API->>Index: geo-distance filter and text filters
    Index-->>API: ranked candidate IDs and distances
    API->>SQL: verify status for selected IDs if needed
    SQL-->>API: current listing status
    API->>Cache: cache eligible result briefly
  end
  API-->>App: results, approximate distance, next cursor
Diagram

For the frontend, ask for device location only after an explicit “near me” action. Offer map selection or manual city/postcode entry if permission is denied. Send the chosen center and radius, debounce query changes, cancel obsolete requests, and represent the active center visibly. Return approximate distances and never return a seller’s raw home coordinate to another user. Listing pins can be jittered or snapped to a coarser cell where appropriate.

6. Scale, bottlenecks & trade-offs

  • A spatial index avoids scanning every listing. Monitor query latency, candidate-to-result ratio, index size, hot regions, and index freshness. A poor candidate ratio may indicate overly broad cells or weak filter selectivity.
  • Replicate the search index across zones and use replicas for read throughput. Shard by region only when a single index no longer meets measured latency or capacity goals; route cross-boundary searches to all relevant shards and merge results by ranking.
  • Cache only carefully normalized, coarse-location queries for a short TTL. Exact coordinates create high cache cardinality; coarse cells improve reuse but can return the wrong set unless the exact radius is re-applied before responding.
  • Keep SQL writes strongly consistent and update the search index asynchronously through a transactional outbox. That favors availability and scale for search at the cost of a short period where a new or changed listing may not appear. Show current listing details from SQL if stale status would materially mislead a buyer.
  • Precise location is sensitive data. Minimize stored precision where product needs allow, restrict access by service role, encrypt it, set retention rules, and scrub it from logs. Keep user search location separate from seller listing location and do not infer consent from app installation.
  • Start with PostGIS or a managed search engine’s geo-distance feature. Introduce H3/geohash routing only after measurements show a need; it adds boundary handling and operational complexity without replacing exact distance checks.
System designHardOlaFrontend EngineerRound 2: System Design

18. Design a hyperlocal marketplace similar to Facebook Marketplace, where users can post products and search for products available within a specified…

The full question

Design a hyperlocal marketplace similar to Facebook Marketplace, where users can post products and search for products available within a specified radius, such as 5 km of the seller’s location.

Model answer

1. Requirements & scale

Functional requirements

  • Sellers can create, edit, pause, and remove listings with photos, price, category, description, and a location.
  • Buyers can search by text/category and a radius around their chosen location, then sort and filter results.
  • Buyers can view listing details and contact sellers; users can report listings and sellers.
  • Users can save searches or listings and receive relevant notifications.

Non-functional requirements

  • Search should feel responsive: p95 under 300 ms for a cached query and under 700 ms end to end.
  • Listing writes must be durable; search indexing can be eventually consistent.
  • Protect precise user locations and prevent abuse, spam, and unauthorized edits.
  • Support mobile networks, degraded connectivity, and accessible interfaces.

Back-of-the-envelope scale

  • Assume 10 million registered users, 1 million DAU, and 10 searches per DAU: 10 million searches/day, or about 116 average QPS. At a 10× peak, plan for roughly 1,200 QPS.
  • At 200,000 new listings/day and 2 KB of listing metadata each, metadata grows by about 400 MB/day before indexes and replicas. If each listing has five 500 KB photos, image ingestion is about 500 GB/day; use object storage and CDN delivery rather than serving images from application servers.

2. High-level architecture

flowchart TD
  subgraph C["Client"]
    W["Web app"]
    M["Mobile app"]
  end
  subgraph E["Edge/CDN"]
    CDN["CDN and WAF"]
  end
  subgraph L["Load Balancer"]
    LB["API gateway"]
  end
  subgraph A["API / Services"]
    Search["Search API"]
    Listing["Listing API"]
    User["User and auth API"]
    Media["Media service"]
  end
  subgraph K["Cache"]
    RC["Redis query cache"]
  end
  subgraph D["Datastores"]
    DB["Listings SQL with geo data"]
    Index["Search index"]
    Obj["Object storage"]
  end
  subgraph Q["Message Queue"]
    MQ["Listing events"]
  end
  subgraph X["Workers"]
    Indexer["Indexing workers"]
    Notify["Notification workers"]
  end
  W -->|"search and listing requests"| CDN
  M -->|"search and listing requests"| CDN
  CDN -->|"API calls"| LB
  LB --> Search
  LB --> Listing
  LB --> User
  LB --> Media
  Search -->|"query results"| RC
  Search -->|"geo and text query"| Index
  Listing -->|"authoritative listing writes"| DB
  Listing -->|"publish listing event"| MQ
  Media -->|"signed upload and image metadata"| Obj
  Obj -->|"image delivery"| CDN
  MQ --> Indexer
  MQ --> Notify
  Indexer -->|"upsert listing document"| Index
Diagram

The browser or app sends search requests to a stateless API. The search service uses a geo-capable index for candidate retrieval; listing data remains authoritative in SQL. Listing changes flow asynchronously through a queue to update the index and trigger notifications. Images upload directly to object storage using signed URLs and are served through the CDN.

3. API design

  • POST /v1/listings — create a listing; authenticated, idempotent with a client request ID.
  • PATCH /v1/listings/{listingId} — update fields owned by the seller.
  • GET /v1/search?lat=...&lon=...&radius_m=5000&q=...&category=...&cursor=... — search within a radius with filters and cursor pagination.
  • GET /v1/listings/{listingId} — fetch listing details, excluding private seller data.
  • POST /v1/listings/{listingId}/reports — report unsafe or prohibited content.
  • POST /v1/media/upload-url — issue a short-lived signed upload URL.

Validate coordinates, radius limits, page size, and listing ownership server-side. Return a stable cursor rather than relying on large offsets.

4. Data model & storage

  • SQL (for example, PostgreSQL): users, listings, listing_images, and reports. A listing contains id, seller_id, title, description, price, category_id, status, created_at, and a geographic point. SQL provides transactions, constraints, and a clear source of truth.
  • Geo/search index: documents contain searchable text, category, status, price, seller ID, and a geo_point. Use a geo-distance filter and relevance/distance sort. Keep index documents rebuildable from SQL and events.
  • Object storage: original and resized listing images; store only object keys and image metadata in SQL.
  • Redis: short-lived cache for popular, non-personalized searches and rate-limit counters. Cache keys include normalized filters and a coarse location cell; do not cache private seller data.
  • Partition listings by a stable listing ID or region only when measured load justifies it. Keep user data and exact coordinates access-controlled.

5. Deep dive

For a search, validate the requested center and radius, clamp the radius to a product-defined maximum, and normalize filters. Query the geo index for active listings whose coordinates fall within the radius, then apply text/category/price filters. Sort by a combination of relevance, distance, freshness, and quality rather than distance alone. Use a deterministic tie-breaker such as listing ID for cursor pagination.

The geo index is an eventually consistent read model. On listing creation or location change, commit SQL first and publish an outbox event in the same transaction. Workers consume events idempotently and upsert the search document. This avoids losing index updates if the process crashes after a database commit. Search results can briefly lag; listing detail reads can verify current status against SQL when necessary.

On the frontend, request location only when the user chooses “near me,” explain why it is needed, and offer a manual location or map-center fallback. Debounce text input, cancel stale requests, preserve filters in the URL, and show loading, empty, permission-denied, and network-error states. Never expose a seller’s exact home location: index a suitably coarsened or seller-approved point and show approximate distance.

6. Scale, bottlenecks & trade-offs

  • Run stateless API replicas across availability zones; autoscale search separately from listing writes. Use read replicas for suitable SQL reads, while preserving a single authoritative write path per listing.
  • Replicate and shard the search index by region or document ID as volume grows. Geographic partitioning can improve locality, but listings near boundaries must be searchable from adjacent partitions.
  • CDN caching is valuable for images and static assets. Search caching is less effective for arbitrary coordinates; cache only popular queries using a coarse cell and short TTL, and invalidate or tolerate bounded staleness.
  • SQL gives strong listing-write consistency; the index favors fast, scalable reads with eventual consistency. The outbox, retries, dead-letter queue, and reconciliation job address missed or poison events.
  • Location is sensitive: minimize precision, restrict access, encrypt data in transit and at rest, define retention, and avoid putting raw coordinates in logs or analytics.
  • For a first release, a managed search engine with geo queries is simpler than a custom spatial index. Measure query latency, index lag, empty-result rate, and search-to-contact conversion before adding more complex ranking or partitioning.
System designHardOlaFrontend EngineerRound 2: System Design

19. How would you build the frontend app for creating and searching posts, including its components, state management, debouncing, network calls, and u…

The full question

How would you build the frontend app for creating and searching posts, including its components, state management, debouncing, network calls, and use of the location API?

Model answer

1. Requirements & scale

Functional requirements

  • Browse and search posts by text and optional location; paginate results and open a post.
  • Create, edit, and delete a post. A post can include text and an optional location.
  • Handle loading, empty, error, offline, and permission-denied states clearly.

Non-functional requirements

  • Keep search responsive, avoid stale results, and work well on mobile networks.
  • Protect user location: request it only when needed, explain why, and allow manual location selection.
  • Make post creation resilient to retries without creating duplicates.

Assumptions and estimates

  • Assume 1 million daily active users, averaging 10 searches per day: 10 million searches/day, or about 116 requests/second on average. At a 10× peak, plan for roughly 1,200 search requests/second.
  • Assume 100,000 new posts/day at 2 KB of text and metadata each: about 200 MB/day before indexes and replication. Images, if supported, are stored separately in object storage.
  • Serve the static frontend from a CDN; keep search requests small and paginated, for example 20 posts per page.

2. High-level architecture

The frontend is a React/TypeScript single-page app. Components own transient UI state; a query cache owns server state. The diagram shows the frontend and the backend contract it relies on.

flowchart TD
  subgraph Client["Client"]
    UI["React app"]
    Search["Search and results"]
    Composer["Post composer"]
    Geo["Location API"]
    UI --> Search
    UI --> Composer
    Search --> Geo
  end
  subgraph Edge["Edge/CDN"]
    CDN["Static assets and API edge"]
  end
  subgraph LB["Load Balancer"]
    LB1["HTTPS routing"]
  end
  subgraph Services["API / Services"]
    API["Posts API"]
    SearchSvc["Search service"]
  end
  subgraph Cache["Cache"]
    Redis["Query and feed cache"]
  end
  subgraph Stores["Datastores"]
    DB["Posts database"]
    Index["Search and geo index"]
    Blob["Object storage"]
  end
  subgraph Queue["Message Queue"]
    Events["Post events"]
  end
  subgraph Workers["Workers"]
    Indexer["Index and moderation workers"]
  end
  UI -->|"HTTPS requests"| CDN
  CDN -->|"API traffic"| LB1
  LB1 --> API
  API --> SearchSvc
  SearchSvc -->|"read-through"| Redis
  SearchSvc -->|"text and geo query"| Index
  API -->|"write transaction"| DB
  API -->|"upload metadata"| Blob
  API -->|"post-created event"| Events
  Events --> Indexer
  Indexer -->|"update document"| Index
Diagram

3. API design

  • GET /v1/posts?q=&lat=&lng=&radius_m=&cursor=&limit= — search posts; return items, next_cursor, and applied filters.
  • POST /v1/posts — create a post; accept text, optional location, and an idempotency key.
  • GET /v1/posts/{id} — retrieve a post.
  • PATCH /v1/posts/{id} and DELETE /v1/posts/{id} — update or delete an owned post.
  • POST /v1/uploads/presign — optional, obtain a signed upload URL for an attachment.

Use authenticated requests, input validation, rate limits, and structured error codes. The client sends coordinates only after the user chooses a location-based action and grants permission.

4. Data model & storage

  • Store posts in a relational database: posts(id, author_id, body, lat, lng, visibility, created_at, updated_at, status). Index by created_at and author; use a geospatial index for location queries.
  • Use a search index for full-text ranking and combined text-and-distance queries. Treat it as a derived index: the database is the source of truth.
  • Store media in object storage and keep only its URL and metadata on the post. Cache popular or recent search results in Redis with short TTLs and invalidate or refresh them after writes.
  • Partition large search indexes by geography and time where useful; use opaque cursor pagination rather than offsets for stable, scalable results.

5. Deep dive

Frontend components and state

  • SearchPage composes SearchBar, LocationFilter, PostList, PostCard, and LoadMore. CreatePostPage composes PostComposer, validation, and an optional location picker.
  • Keep input text, open dialogs, and permission prompts in component state. Put remote results, loading status, and pagination in a server-state cache such as TanStack Query. Key queries by normalized text, selected location, radius, and cursor so changing a filter cannot reuse the wrong result.
  • On each keystroke, wait 300 ms before searching. Cancel the previous timer and abort its in-flight request with AbortController. Also associate responses with the active query key so a slower old response cannot overwrite newer results. Retain previous results while fetching, but label them as stale if the query changed.
  • Debounce text input, not explicit actions: Enter, selecting a suggestion, or changing location should trigger an immediate query. Reset the cursor when search filters change, and fetch the next page only on demand or near the end of the list.
  • Use the browser Geolocation API only after a clear user action, such as tapping “Use my location.” Show a permission rationale first, handle timeout and denial, and fall back to a place search or manual area selection. Avoid storing precise coordinates in persistent browser storage; send only the precision needed for the requested radius.
  • Validate the composer before submission. Disable duplicate submits, show a pending state, and use an idempotency key. Optimistically show the new post only if the API contract supports rollback; otherwise show a clear success state after the server confirms it.
sequenceDiagram
  participant U as User
  participant C as React client
  participant G as Geolocation API
  participant A as Posts API
  participant S as Search service
  U->>C: Type query
  C->>C: Debounce 300 ms
  U->>C: Choose use my location
  C->>G: Request location permission
  G-->>C: Coordinates or denial
  C->>A: GET posts with query and optional location
  A->>S: Search text and geo filters
  S-->>A: Ranked page and cursor
  A-->>C: Results
  C-->>U: Render results and next-page action
Diagram

6. Scale, bottlenecks & trade-offs

  • Cache static assets at the CDN and use query caching on the client to reduce repeat requests. Keep result-cache TTLs short because new posts can change rankings.
  • Search is the read bottleneck: scale search replicas horizontally, cap radius and page size, and apply rate limits. Cursor pagination avoids expensive deep offsets.
  • Creation should commit to the primary database before returning success; index updates can be asynchronous through the queue. This gives fast writes but means a new post may not appear in search immediately, so the client can display the confirmed post locally.
  • A database failure should fail creation clearly rather than claim success. Search may serve cached results during a search-index outage, marked as potentially stale. Queue retries must be idempotent, and a dead-letter queue plus monitoring should catch indexing failures.
  • Choose consistency by operation: strongly consistent ownership and writes, eventually consistent search indexing, and best-effort location enrichment. This keeps posting reliable without making every search wait for indexing.
TechnicalEasyOlaFrontend EngineerRound 3: Platform round

20. What are JavaScript best practices?

Model answer

  1. Write clear, maintainable code. Use descriptive names, small functions with focused responsibilities, and consistent formatting. Prefer straightforward code over clever shortcuts.
  2. Use modern JavaScript deliberately. Use const by default and let when reassignment is needed; avoid var. Prefer modules, async/await, and well-understood built-in APIs. Choose immutable transformations when they make state changes easier to reason about.
  3. Handle failures and edge cases. Validate inputs at system boundaries, handle rejected promises, and provide useful errors. Avoid swallowing exceptions or returning misleading fallback values.
  4. Avoid shared-state surprises. Keep state local where possible, avoid unintended mutation, and be cautious with closures, this, and asynchronous work that can finish out of order.
  5. Treat security as part of correctness. Do not inject untrusted content with innerHTML; escape or sanitize data for its output context. Avoid exposing secrets, and use safe APIs for browser storage and network requests.
  6. Test behavior, not implementation details. Cover normal cases, boundaries, and failures. For frontend code, test accessibility and user interactions as well as rendering.
  7. Keep performance measurable. Choose suitable data structures, avoid unnecessary work in render paths, and profile before optimizing. For example, debounce expensive search requests and cancel or ignore stale responses.
  8. Use tooling and team conventions. Apply linting, formatting, type checking where appropriate, code review, and dependency updates. Keep APIs and browser compatibility explicit rather than relying on accidental behavior.

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