Groww interview questions & answers

20 real Groww interview questions with full model answers — Coding, Technical, Behavioral, Product & growth. Drawn from the same verified bank ChannelPulse drills from (23 Groww questions in total).

BehavioralMediumGrowwFrontend EngineerHiring Manager

1. Walk me through a frontend problem you owned end to end in production.

Model answer

  1. Situation — I owned the frontend for an investment order flow used by both first-time and returning investors. The existing flow had grown across several releases: validation rules were duplicated, loading states differed by screen, and users could be unsure whether a tap had submitted an order. Because this is a money movement journey, correctness and clear feedback mattered more than simply reducing clicks.
  2. Task — I was responsible for taking the problem from identifying the user-facing failure through implementation, rollout, and production monitoring. I needed to improve confidence and reduce avoidable failures without changing the backend order semantics or delaying a scheduled release.
  3. Action
  • I first combined support tickets, session replays, and frontend/API telemetry. That showed a meaningful cluster of failures around validation and retries, so I defined success as fewer client-side order errors and fewer duplicate submissions, with completion time and crash-free sessions as guardrails.
  • I mapped the flow with design and backend engineers, then agreed on a single source of truth for order status and field validation. I documented the API states and edge cases—slow responses, rejected orders, and app backgrounding—before changing the UI.
  • I extracted shared validation and status components rather than rewriting the whole flow. I added an explicit submitting state, disabled duplicate submission while a request was in flight, and made error messages actionable without clearing valid user input.
  • I added tests for the important transitions and reviewed accessibility: focus behavior, readable errors, and status announcements. I also added telemetry for validation failures and submission outcomes so we could distinguish UI problems from backend rejection.
  • I coordinated a gradual rollout with QA and the product team. I watched the new metrics and support reports, and kept a rollback path available rather than treating release as the finish line.
  1. Result — In the first few weeks, client-side order errors fell by about 25%, duplicate-submit reports dropped, and order completion improved without a regression in crash-free sessions. The work also gave the team reusable components and clearer ownership of order states. I learned to treat production UI work as an end-to-end reliability problem: the best fix is one users can understand, the team can verify, and telemetry can confirm.
BehavioralMediumGrowwFrontend EngineerHiring Manager

2. Describe a time you pushed back on a product decision.

Model answer

  1. Situation — At a previous company, I worked on a customer-facing web app where the product team wanted to add a confirmation modal before users could save a partially completed form. The motivation was understandable: support had seen cases where users believed their work was saved when it was not. But the proposed modal appeared on every save, including routine saves, and our users often repeated that action while entering long applications.
  2. Task — I owned the frontend implementation and needed to help reduce mistaken assumptions about saving without adding friction to a high-frequency task. I wanted to challenge the proposed interaction with evidence, not simply argue from personal preference or block the release.
  3. Action
  • I first clarified the underlying problem with the PM and support lead. We found that the issue was not users failing to confirm a save; it was that the existing success state was easy to miss when the network was slow.
  • I brought examples from session recordings and proposed an alternative: an inline save status that moved through “Saving,” “Saved,” and a recoverable error state, with a timestamp. A modal would remain for genuinely destructive actions.
  • I worked with design to prototype both approaches and ran short usability sessions with representative users. Users noticed the persistent status more reliably and could explain whether their work had been saved.
  • I suggested shipping the status behind an experiment, while tracking save-related support contacts, repeat save attempts, completion time, and save failures. That gave the team a reversible way to decide.
  • When the PM worried that the inline state might be overlooked, I adjusted the placement and added an accessible live announcement for screen readers rather than treating visual prominence as the only solution.
  1. Result — We shipped the inline status for routine saves and kept confirmation dialogs for destructive actions. In the following release period, save-related support contacts fell by 22%, while median form completion time improved by 9%; save failure rates did not increase. I learned that effective pushback starts by aligning on the user problem, then offering a testable alternative that respects the product team’s original concern.
CodingEasyGrowwSoftware Engineer

3. 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.
CodingMediumGrowwSoftware Engineer

4. Minimum Number of Operations to Make X and Y Equal (LeetCode)

Model answer

The task

Given positive integers x and y, find the fewest operations needed to turn x into y. An operation can increase or decrease the current value by one, or divide it by 5 or 11 when the division is exact.

Key idea

Use memoized recursion, considering each division as a shortcut. Before dividing, either decrease to the nearest multiple or increase to the next multiple; after division, solve the smaller subproblem. If the current value is already at or below y, incrementing directly is optimal.

Approach

  1. Define solve(n) as the minimum operations to reach y from n.
  2. If n <= y, return y - n.
  3. Initialize the best cost to decrementing all the way to y.
  4. For each divisor, try adjusting n to the multiple just below it and the multiple just above it, then divide.
  5. Cache results so repeated subproblems are computed once.
from functools import lru_cache

class Solution:
    def minimumOperations(self, x: int, y: int) -> int:
        @lru_cache(maxsize=None)
        def solve(n: int) -> int:
            # If n is at or below the target, incrementing is optimal.
            if n <= y:
                return y - n

            # A direct sequence of decrements is always an option.
            best = n - y

            for divisor in (5, 11):
                remainder = n % divisor

                # Decrement to the previous multiple, then divide.
                lower = n - remainder
                best = min(best, remainder + 1 + solve(lower // divisor))

                # Increment to the next multiple, then divide.
                increase = (divisor - remainder) % divisor
                upper = n + increase
                best = min(best, increase + 1 + solve(upper // divisor))

            return best

        return solve(x)

Complexity:

  • Time: O(S), where S is the number of distinct states evaluated by the memoized recursion.
  • Space: O(S) for the cache and recursion stack.

Common follow-ups

  • What if additional divisors are allowed? Add each divisor to the set of choices in the recurrence.
  • Why consider only the nearest multiples? Any farther adjustment before dividing costs more and reaches the same quotient or a less useful one.
  • What if operations have different costs? Include those costs in each candidate and use a shortest-path algorithm if the choices no longer reduce to smaller states.
CodingMediumGrowwSoftware Engineer

5. Maximum Length of a Concatenated String with Unique Characters (LeetCode)

Model answer

The task

Choose a subset of the given strings whose concatenation contains no repeated character. Return the maximum possible length of that concatenation.

Key idea

Represent each string with a bitmask of its characters. Discard strings that already contain a repeated character; then backtrack over the remaining strings, adding one only when its mask does not overlap the characters already chosen.

Approach

  1. For each string, build a bitmask using one bit per lowercase English letter.
  2. Skip a string if building its mask reveals a repeated character.
  3. Recursively consider skipping or including each remaining string.
  4. Include a string only if its mask has no bits in common with the current mask.
  5. Track the best length reached.
from typing import List

class Solution:
    def maxLength(self, arr: List[str]) -> int:
        candidates = []

        # Keep only strings with unique characters internally.
        for word in arr:
            mask = 0
            valid = True

            for char in word:
                bit = 1 << (ord(char) - ord("a"))
                if mask & bit:
                    valid = False
                    break
                mask |= bit

            if valid:
                candidates.append((mask, len(word)))

        def search(index: int, used: int, length: int) -> int:
            if index == len(candidates):
                return length

            # Skip this string.
            best = search(index + 1, used, length)

            # Include it if it adds no repeated characters.
            mask, word_length = candidates[index]
            if used & mask == 0:
                best = max(
                    best,
                    search(index + 1, used | mask, length + word_length),
                )

            return best

        return search(0, 0, 0)

Complexity:

  • Time: O(L + 2^m), where L is the total input length and m is the number of valid strings.
  • Space: O(m) for the candidate list and recursion stack.

Common follow-ups

  • Can this be made iterative? Store reachable character masks and update them for each valid string.
  • What if characters come from a larger alphabet? Use a set or a wider/dynamic bit representation.
  • How would you reduce work on large inputs? Sort candidates by length and use an upper bound to prune branches that cannot beat the best result.
CodingMediumGrowwFrontend EngineerFrontend Deep Dive + Machine Coding

6. Implement polyfills for map(), filter(), and reduce().

Model answer

"use strict";

// Convert a value to an integer length in the range [0, Number.MAX_SAFE_INTEGER].
function toLength(value) {
  const number = Number(value);
  if (Number.isNaN(number) || number <= 0) return 0;
  if (number === Infinity) return Number.MAX_SAFE_INTEGER;
  return Math.min(Math.floor(number), Number.MAX_SAFE_INTEGER);
}

function requireObject(value) {
  if (value === null || value === undefined) {
    throw new TypeError("Array method called on null or undefined");
  }
  return Object(value);
}

Array.prototype.myMap = function (callback, thisArg) {
  const object = requireObject(this);
  if (typeof callback !== "function") throw new TypeError("Callback must be a function");

  const length = toLength(object.length);
  const result = new Array(length);

  for (let index = 0; index < length; index++) {
    // Preserve sparse-array holes; inherited indexed properties are visited too.
    if (index in object) {
      result[index] = callback.call(thisArg, object[index], index, object);
    }
  }
  return result;
};

Array.prototype.myFilter = function (callback, thisArg) {
  const object = requireObject(this);
  if (typeof callback !== "function") throw new TypeError("Callback must be a function");

  const length = toLength(object.length);
  const result = [];

  for (let index = 0; index < length; index++) {
    if (index in object) {
      const value = object[index];
      if (callback.call(thisArg, value, index, object)) result.push(value);
    }
  }
  return result;
};

Array.prototype.myReduce = function (callback /*, initialValue */) {
  const object = requireObject(this);
  if (typeof callback !== "function") throw new TypeError("Callback must be a function");

  const length = toLength(object.length);
  const hasInitialValue = arguments.length > 1;
  let index = 0;
  let accumulator;

  if (hasInitialValue) {
    accumulator = arguments[1];
  } else {
    // Find the first present element; holes are skipped.
    while (index < length && !(index in object)) index++;
    if (index >= length) throw new TypeError("Reduce of empty array with no initial value");
    accumulator = object[index++];
  }

  for (; index < length; index++) {
    if (index in object) {
      accumulator = callback(accumulator, object[index], index, object);
    }
  }
  return accumulator;
};

// Examples:
console.log([1, 2, 3].myMap((value) => value * 2)); // [2, 4, 6]
console.log([1, 2, 3].myFilter((value) => value > 1)); // [2, 3]
console.log([1, 2, 3].myReduce((sum, value) => sum + value, 0)); // 6
  • Each method snapshots the receiver’s length and skips indices that are holes.
  • map preserves holes, filter returns a dense array, and reduce throws for an empty array without an initial value.
  • Complexity: map and filter are O(n) time and O(n) output space; reduce is O(n) time and O(1) auxiliary space.
CodingMediumGrowwSoftware Engineer

7. Maximum Good Subarray Sum (LeetCode)

Model answer

The task

Find the largest sum among contiguous subarrays whose first and last values differ by exactly k. Return 0 if no such subarray exists.

Key idea

For each value, keep the smallest prefix sum seen just before an occurrence of that value. When the current value is x, a valid subarray can start at a prior x - k or x + k; subtracting the smallest stored prefix gives the best sum ending here.

Approach

  1. Track the prefix sum before the current position.
  2. Look up prior occurrences of x - k and x + k.
  3. Use their minimum prefix sums to update the best valid subarray sum.
  4. Record the current prefix sum as a possible starting point for future subarrays.
  5. Return 0 if no valid subarray was found.
from typing import List

class Solution:
    def maximumSubarraySum(self, nums: List[int], k: int) -> int:
        # Smallest prefix sum before an occurrence of each value.
        min_prefix = {}

        prefix = 0
        best = None

        for x in nums:
            # Query before recording this position, so the subarray is nonempty.
            for start_value in (x - k, x + k):
                if start_value in min_prefix:
                    subarray_sum = prefix + x - min_prefix[start_value]
                    if best is None or subarray_sum > best:
                        best = subarray_sum

            # This position may be the start of a future valid subarray.
            if x not in min_prefix or prefix < min_prefix[x]:
                min_prefix[x] = prefix

            prefix += x

        return 0 if best is None else best

Complexity:

  • Time: O(n), with expected O(1) hash-map operations per element.
  • Space: O(n), for the prefix minimum stored for each distinct value.

Common follow-ups

  • What if k is zero? The same lookup works; querying before updating ensures the endpoints are at different positions.
  • Can this be solved without storing all distinct values? Not generally in one pass, since a future endpoint may match any earlier value.
  • What if the answer must include the subarray indices? Store the index alongside each minimum prefix and retain the best pair of endpoints.
CodingMediumGrowwFrontend EngineerRound 3

8. Implement polyfills for Array.map, Array.filter, and Array.reduce, including thisArg support, sparse-array handling, and reduce behavior with and w…

The full question

Implement polyfills for Array.map, Array.filter, and Array.reduce, including thisArg support, sparse-array handling, and reduce behavior with and without an initial value.

Model answer

'use strict';

const MAX_SAFE_LENGTH = Number.MAX_SAFE_INTEGER;

function toLength(value) {
  const number = Number(value);
  if (Number.isNaN(number) || number <= 0) return 0;
  if (!Number.isFinite(number)) return MAX_SAFE_LENGTH;
  return Math.min(Math.floor(number), MAX_SAFE_LENGTH);
}

function toObject(value) {
  if (value == null) throw new TypeError('Array method called on null or undefined');
  return Object(value);
}

Object.defineProperties(Array.prototype, {
  myMap: {
    configurable: true,
    writable: true,
    value: function (callback, thisArg) {
      const object = toObject(this);
      const length = toLength(object.length);
      if (typeof callback !== 'function') throw new TypeError('callback must be a function');

      const result = new Array(length);
      for (let index = 0; index < length; index++) {
        if (index in object) {
          result[index] = callback.call(thisArg, object[index], index, object);
        }
      }
      return result;
    }
  },

  myFilter: {
    configurable: true,
    writable: true,
    value: function (callback, thisArg) {
      const object = toObject(this);
      const length = toLength(object.length);
      if (typeof callback !== 'function') throw new TypeError('callback must be a function');

      const result = [];
      for (let index = 0; index < length; index++) {
        if (index in object) {
          const value = object[index];
          if (callback.call(thisArg, value, index, object)) result.push(value);
        }
      }
      return result;
    }
  },

  myReduce: {
    configurable: true,
    writable: true,
    value: function (callback /*, initialValue */) {
      const object = toObject(this);
      const length = toLength(object.length);
      if (typeof callback !== 'function') throw new TypeError('callback must be a function');

      let index = 0;
      let accumulator;
      if (arguments.length > 1) {
        accumulator = arguments[1];
      } else {
        // Find the first present element; holes are skipped.
        while (index < length && !(index in object)) index++;
        if (index >= length) throw new TypeError('Reduce of empty array with no initial value');
        accumulator = object[index++];
      }

      for (; index < length; index++) {
        if (index in object) {
          accumulator = callback(accumulator, object[index], index, object);
        }
      }
      return accumulator;
    }
  }
});

// Examples:
// [1, , 3].myMap(x => x * 2);            // [2, <hole>, 6]
// [1, , 3].myFilter(x => x > 1);         // [3]
// [1, 2, 3].myReduce((sum, x) => sum + x); // 6
  • map preserves holes, while filter produces a dense result; all three skip absent indexes.
  • map and filter call the callback with thisArg; reduce does not accept one.
  • reduce uses the first present element when no initial value is supplied, and throws if none exists.

Complexity: Each method takes O(n) time. map uses O(n) output space; filter uses O(k), where k is the number of accepted elements; reduce uses O(1) auxiliary space.

CodingMediumGrowwSoftware Engineer

9. 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.
CodingMediumGrowwFrontend EngineerProblem Solving in TypeScript

10. Given a linked list, detect whether it has a cycle and, if it does, return the node where the cycle begins.

Model answer

// A list node has the usual shape: { value, next }.
function findCycleStart(head) {
  let slow = head;
  let fast = head;

  // Phase 1: find a meeting point inside the cycle, if one exists.
  while (fast !== null && fast.next !== null) {
    slow = slow.next;
    fast = fast.next.next;
    if (slow === fast) break;
  }

  // Reaching the end means the list is acyclic.
  if (fast === null || fast.next === null) return null;

  // Phase 2: one pointer starts at the head; both move one step.
  // Their next meeting point is the first node in the cycle.
  let fromHead = head;
  let fromMeetingPoint = slow;
  while (fromHead !== fromMeetingPoint) {
    fromHead = fromHead.next;
    fromMeetingPoint = fromMeetingPoint.next;
  }

  return fromHead;
}
  • Floyd’s tortoise-and-hare algorithm compares node identity, so it does not need a set or modify the list.
  • After a meeting, resetting one pointer to the head makes the two pointers meet at the cycle entry.
  • Complexity: O(n) time and O(1) extra space.
CodingHardGrowwSoftware Engineer

11. Maximum Number of Events That Can Be Attended II (LeetCode)

Model answer

The task

Given events with a start day, end day, and value, choose at most k events to maximize the total value. Attended events must not overlap, so the next event must start strictly after the current event ends.

Key idea

Sort events by start day. For each event, binary-search the first event that can follow it; dynamic programming then compares skipping the event with attending it and using one fewer attendance slot.

Approach

  1. Sort events by start day and store their start days for binary search.
  2. For each event, find the first later event whose start day is greater than its end day.
  3. Let dp[i][j] be the best value using events from index i onward with at most j attendances.
  4. Fill the table from right to left, choosing between skipping event i and attending it.
  5. Return the best value starting at the first event with at most k attendances.
from bisect import bisect_right
from typing import List

class Solution:
    def maxValue(self, events: List[List[int]], k: int) -> int:
        events.sort(key=lambda event: event[0])
        n = len(events)

        if n == 0 or k == 0:
            return 0

        starts = [event[0] for event in events]

        # next_index[i] is the first event that starts after event i ends.
        next_index = [
            bisect_right(starts, events[i][1])
            for i in range(n)
        ]

        # dp[i][j]: best value from events[i:] with at most j attendances.
        k = min(k, n)
        dp = [[0] * (k + 1) for _ in range(n + 1)]

        for i in range(n - 1, -1, -1):
            value = events[i][2]
            following = next_index[i]

            for remaining in range(1, k + 1):
                skip = dp[i + 1][remaining]
                attend = value + dp[following][remaining - 1]
                dp[i][remaining] = max(skip, attend)

        return dp[0][k]

Complexity:

  • Time: O(n log n + nk) for sorting, binary searches, and the DP table.
  • Space: O(nk) for the DP table and O(n) for event start days and next indices.

Common follow-ups

  • How can memory use be reduced? The recurrence jumps to arbitrary later indices, so simple rolling rows do not suffice; more advanced optimization depends on additional structure.
  • What if events ending on day d can be followed by events starting on day d? Search for the first start day greater than or equal to the end day instead.
  • What if k is larger than the number of events? Cap it at n, since attending more than n events is impossible.
CodingHardGrowwFrontend EngineerProblem Solving in TypeScript

12. Implement an LRU cache with O(1) get and put operations using TypeScript generics.

Model answer

/** @template K, V */
class Node {
  /** @param {K} key @param {V} value */
  constructor(key, value) {
    this.key = key;
    this.value = value;
    this.prev = null;
    this.next = null;
  }
}

/**
 * Least-recently-used cache.
 * @template K, V
 */
class LRUCache {
  /** @param {number} capacity */
  constructor(capacity) {
    if (!Number.isInteger(capacity) || capacity < 0) {
      throw new RangeError("capacity must be a non-negative integer");
    }
    this.capacity = capacity;
    /** @type {Map<K, Node<K, V>>} */
    this.nodes = new Map();
    this.head = new Node(null, null); // Most-recent sentinel
    this.tail = new Node(null, null); // Least-recent sentinel
    this.head.next = this.tail;
    this.tail.prev = this.head;
  }

  /** @param {K} key @returns {V | undefined} */
  get(key) {
    const node = this.nodes.get(key);
    if (!node) return undefined;
    this.#moveToFront(node);
    return node.value;
  }

  /** @param {K} key @param {V} value */
  put(key, value) {
    if (this.capacity === 0) return;

    let node = this.nodes.get(key);
    if (node) {
      node.value = value;
      this.#moveToFront(node);
      return;
    }

    node = new Node(key, value);
    this.nodes.set(key, node);
    this.#addAfterHead(node);

    if (this.nodes.size > this.capacity) {
      const leastRecent = this.tail.prev;
      this.#remove(leastRecent);
      this.nodes.delete(leastRecent.key);
    }
  }

  /** @param {Node<K, V>} node */
  #moveToFront(node) {
    this.#remove(node);
    this.#addAfterHead(node);
  }

  /** @param {Node<K, V>} node */
  #addAfterHead(node) {
    node.prev = this.head;
    node.next = this.head.next;
    this.head.next.prev = node;
    this.head.next = node;
  }

  /** @param {Node<K, V>} node */
  #remove(node) {
    node.prev.next = node.next;
    node.next.prev = node.prev;
  }
}

// Example:
const cache = new LRUCache(2);
cache.put("A", 10);
cache.put("B", 20);
cache.get("A"); // A becomes most recently used
cache.put("C", 30); // evicts B
  • The Map provides O(1) key lookup; the doubly linked list tracks recency and supports O(1) removal and promotion.
  • get returns undefined for a miss; put updates existing entries and evicts the least-recently-used entry when full. JSDoc templates provide generic type checking in JavaScript tooling.
  • Complexity: O(1) average time for get and put; O(capacity) space.
CodingHardGrowwSoftware Engineer

13. Maximize Score After N Operations (LeetCode)

Model answer

The task

Given an even-length array of positive integers, pair up all its elements over successive operations. Each operation contributes its index multiplied by the pair’s GCD; maximize the total score.

Key idea

Use a bitmask to represent which elements have already been paired. The best score from a mask depends only on that mask, so memoization avoids recomputing the same remaining choices.

Approach

  1. Precompute the GCD of every pair of elements.
  2. Define a recursive function for the best additional score from a used-elements mask.
  3. Derive the next operation number from how many elements are already used.
  4. Try every pair of unused elements, add that pair’s contribution, and keep the maximum.
  5. Memoize each mask’s result.
from functools import lru_cache
from math import gcd
from typing import List

class Solution:
    def maxScore(self, nums: List[int]) -> int:
        size = len(nums)
        full_mask = (1 << size) - 1

        # GCD lookup avoids repeating these calculations during the search.
        pair_gcd = [
            [gcd(nums[i], nums[j]) for j in range(size)]
            for i in range(size)
        ]

        @lru_cache(maxsize=None)
        def best(mask: int) -> int:
            if mask == full_mask:
                return 0

            # Each completed operation uses exactly two elements.
            operation = mask.bit_count() // 2 + 1
            answer = 0

            for i in range(size):
                if mask & (1 << i):
                    continue

                for j in range(i + 1, size):
                    if mask & (1 << j):
                        continue

                    next_mask = mask | (1 << i) | (1 << j)
                    score = operation * pair_gcd[i][j] + best(next_mask)
                    answer = max(answer, score)

            return answer

        return best(0)

Complexity:

  • Time: O(2^m · m²), where m is the number of elements; each mask considers pairs.
  • Space: O(2^m), for memoized masks.

Common follow-ups

  • How would you reduce repeated GCD work? Precompute all pairwise GCDs, as in the solution.
  • Can you use bottom-up dynamic programming? Yes; compute values for masks in descending order of their number of set bits.
  • What if only k operations are performed? Make the terminal condition stop after k pairs rather than after all elements are used.
CodingHardGrowwFrontend EngineerRound 3

14. Implement a deep clone without JSON.stringify that handles circular references, Dates, RegExp, Maps, Sets, and symbol keys.

Model answer

function deepClone(value, seen = new WeakMap()) {
  // Primitives and functions are returned as-is; cloning function behavior
  // and closures is not generally possible.
  if (value === null || typeof value !== 'object') return value;
  if (seen.has(value)) return seen.get(value);

  let clone;

  if (value instanceof Date) {
    clone = new Date(value.getTime());
  } else if (value instanceof RegExp) {
    clone = new RegExp(value.source, value.flags);
    clone.lastIndex = value.lastIndex;
  } else if (value instanceof Map) {
    clone = new Map();
    seen.set(value, clone);
    for (const [key, item] of value) {
      clone.set(deepClone(key, seen), deepClone(item, seen));
    }
  } else if (value instanceof Set) {
    clone = new Set();
    seen.set(value, clone);
    for (const item of value) clone.add(deepClone(item, seen));
  } else if (Array.isArray(value)) {
    clone = new Array(value.length);
  } else {
    // Preserve the prototype for ordinary objects and class instances.
    clone = Object.create(Object.getPrototypeOf(value));
  }

  // Register before descending so self-references and cycles resolve correctly.
  if (!seen.has(value)) seen.set(value, clone);

  // Reflect.ownKeys includes non-enumerable and symbol-keyed properties.
  for (const key of Reflect.ownKeys(value)) {
    // Built-in slots were copied above; RegExp's lastIndex was copied too.
    if ((value instanceof Date) ||
        (value instanceof RegExp && key === 'lastIndex') ||
        (value instanceof Map && (key === 'size')) ||
        (value instanceof Set && (key === 'size'))) {
      continue;
    }

    const descriptor = Object.getOwnPropertyDescriptor(value, key);
    if ('value' in descriptor) {
      descriptor.value = deepClone(descriptor.value, seen);
    }
    // Accessor functions are retained; invoking getters during cloning is avoided.
    Object.defineProperty(clone, key, descriptor);
  }

  return clone;
}

// Circular reference, symbol key, Map, Set, Date, and RegExp example:
const symbolKey = Symbol('metadata');
const original = { date: new Date(), pattern: /groww/gi };
original.self = original;
original.map = new Map([[original, new Set([1, 2])]]);
original[symbolKey] = 'private metadata';

const copy = deepClone(original);
// copy !== original; copy.self === copy; copy.map !== original.map
// copy[symbolKey] === 'private metadata'
  • A WeakMap tracks original-to-clone identities, preserving cycles and shared references.
  • Own symbol and non-enumerable properties are copied via Reflect.ownKeys; descriptors are retained without invoking getters.
  • Functions are intentionally shared, and weak collections or host objects with internal slots need specialized handling if they are part of the input domain.

Complexity: O(V + E) time and O(V) space, where V is the number of reachable objects and E is the number of properties or collection entries.

Product & growthMediumGrowwFrontend EngineerHiring Manager

15. How do you decide when to refactor versus ship?

Model answer

Clarify & scope

I treat refactor versus ship as a risk-and-value decision, not a preference for clean code or speed. First I clarify what the deadline protects, what user outcome the change delivers, and whether the existing code creates a correctness, reliability, or delivery risk. In a financial app, a defect in order placement or displayed balances has a much higher cost than a minor visual inconsistency.

User segments & pain points

I identify who bears the cost of the current code. Users may experience crashes, incorrect states, slow screens, or confusing errors; engineers may be slowed by fragile code, making every future feature riskier. I also ask whether this is a high-change area, such as an order flow, or stable code that is unlikely to be touched again.

Goals & success metrics

The goal is to deliver the user value safely while preserving the ability to make future changes. I look at release impact, defect and rollback risk, cycle time, test coverage of critical behavior, and the expected cost of carrying the debt. I set guardrails around correctness, crash-free sessions, and the committed delivery date.

Solutions

I usually consider three choices: ship the smallest safe change; do a targeted refactor around the risky boundary; or defer the feature for a broader refactor. Recommendation: Prefer the smallest safe change plus a focused refactor when the current structure makes the feature unsafe or repeatedly expensive. I avoid broad rewrites unless evidence shows that incremental changes cannot address the risk.

Prioritization & trade-offs

I compare the cost of refactoring now with the likely cost of bugs and slower follow-on work. I refactor before shipping when the code prevents us from proving critical behavior, creates material production risk, or makes the requested change disproportionately expensive. I ship first when the change is low-risk, reversible, and time-sensitive, while documenting debt and creating a specific follow-up owner and milestone. I make that trade-off visible to product, design, and backend partners rather than silently borrowing quality.

MVP, measurement & rollout

I keep the scope bounded: tests around the risky behavior, a small seam or component extraction, and no unrelated cleanup. I use code review, automated tests, and a staged or feature-flagged rollout where available. After release, I check the agreed guardrails and the follow-up work’s actual cost. If the debt is not creating measurable risk or friction, I do not refactor merely for aesthetics; if it is, I prioritize it with evidence.

Product & growthMediumGrowwFrontend EngineerHiring Manager

16. What would you change in the Groww app?

Model answer

Clarify & scope

I would improve the moment when a user tries to understand whether their investments are doing well. I’d focus on the portfolio overview, not add another trading feature: it is a frequent destination, and a clearer explanation can help users make informed decisions without encouraging unnecessary trades.

User segments & pain points

My primary segment is a newer investor who owns a few mutual funds or stocks but does not yet understand the difference between invested amount, current value, and returns. A single green or red number can be misleading: it may represent today’s movement, total profit and loss, or an annualized return, and users may not know which.

Goals & success metrics

The North Star would be the percentage of portfolio visitors who can correctly understand their portfolio’s value and return. In practice, I’d use a short research task to measure comprehension, alongside repeat portfolio visits and usage of return breakdowns. Guardrails would include support contacts about portfolio values, time to find a holding, page performance, and no increase in impulsive order activity.

Solutions

I’d explore three options: clearer labels and tooltips; a compact breakdown of invested amount, current value, and absolute return; and a time-range chart with a clear explanation of the selected period. I would test the terminology with both new and experienced investors before choosing a visual design.

Recommendation: Start with the labeled value-and-return breakdown, then add the time-range chart only if research shows it resolves a remaining user question. It addresses the core ambiguity with less visual complexity and lower implementation risk.

Prioritization & trade-offs

I’d prioritize by user impact, reach, confidence, and effort. Labels and a breakdown are likely to have broad reach and modest effort; a sophisticated chart has higher engineering and data-validation cost. I would not trade accurate, consistent numbers across screens for a more polished visualization. All calculations and definitions should match the underlying portfolio data and be reviewed with the relevant domain owners.

MVP, measurement & rollout

I’d prototype the language, validate comprehension in usability sessions, then release the change to a small cohort behind a feature flag. I’d compare the primary metric and guardrails against a control, check for differences between new and experienced users, and expand only if users understand the numbers better without performance or trust regressions. I’d use support feedback and event data to decide whether the chart belongs in a later iteration.

Product & growthMediumGrowwFrontend EngineerHiring Manager

17. What would you change about Groww's web experience right now?

Model answer

Clarify & scope

I wouldn’t start by assuming the web experience is broken. I’d first look at funnel data, support contacts, and usability sessions to identify the biggest user problem. My initial hypothesis would be that newer investors can find a product, but may have difficulty understanding what they own, what changed, and what action—if any—they should take. I’d focus on the signed-in investing experience, not redesign the whole site.

User segments & pain points

I’d prioritize first-time and occasional investors. They need confidence and clear explanations, while experienced users often value speed, compact information, and control. A dense dashboard can serve the latter but overwhelm the former; a simplified dashboard can do the reverse.

Goals & success metrics

The North Star would be the share of users who successfully complete an intended investing task—such as reviewing a holding or placing an order—without needing support. I’d pair that with task-completion time and user-reported confidence. Guardrails: order errors, accidental or rapidly reversed orders, support contacts, page performance, and accessibility. I would not optimize for more trades alone; that can reward unnecessary activity.

Solutions

  1. Make the portfolio’s total value, day change, and longer-term performance easy to distinguish, with clear time ranges and plain-language definitions.
  2. Give each holding a consistent detail view: position, relevant performance period, key risks or disclosures, and available actions—without implying a recommendation.
  3. Improve responsive behavior, keyboard navigation, loading feedback, and error recovery across the research-to-order journey.

Recommendation: Start with a usability-led portfolio clarity improvement. It addresses a high-frequency task, is measurable, and can be delivered without changing the underlying investment decision or order flow.

flowchart LR
  A[Open portfolio] --> B[Understand value and change]
  B --> C[Review a holding]
  C --> D{Choose an action}
  D --> E[View details]
  D --> F[Continue to order]
Diagram

Prioritization & trade-offs

I’d rank work by user impact, confidence from research, and implementation effort. Clear labels and time-range explanations are likely lower effort than a broad dashboard redesign, so I’d test those first. I’d preserve a fast path for experienced users and avoid adding educational content that pushes important actions below the fold.

MVP, measurement & rollout

I’d prototype the changes, test key tasks with new and experienced investors, then run an instrumented experiment on a limited cohort. I’d compare task completion, comprehension, and guardrails against the existing experience, segmenting by device and user tenure. If clarity improves without harming speed or safety, I’d expand gradually; otherwise, I’d use session findings to revise the design before rollout.

TechnicalMediumGrowwFrontend EngineerRound 3

18. How does React batch state updates, and when does batching not happen?

Model answer

React batching groups multiple state updates so React can process them together and usually render and commit once. It does not merge state values blindly: updates are queued and applied in order. When the next value depends on the previous one, use functional updates:

setCount(current => current + 1);
setCount(current => current + 1); // increments twice

With a direct value such as setCount(count + 1) twice in one handler, both calls may use the same render's count, producing only one increment.

Where batching happens

  • React 18 with createRoot: automatic batching applies to updates in React event handlers and, in general, callbacks such as promises, timers, and native event handlers. Updates made together in one callback are typically batched.
  • Before React 18, or with a legacy root: batching was primarily limited to React-managed event handlers; updates in a timer or promise callback commonly caused separate renders unless explicitly batched.
  • Separate tasks or intentional user events: React may commit between distinct events so the UI can reflect one interaction before processing the next. An await can split code into separate continuations; do not assume updates on both sides form one batch.
sequenceDiagram
    participant UI as React event
    participant Q as Update queue
    participant R as React render
    UI->>Q: enqueue update A
    UI->>Q: enqueue update B
    Q->>R: process queued updates together
    R-->>UI: commit one resulting UI
Diagram

When batching does not apply, or is deliberately bypassed

  • flushSync from react-dom forces React to flush updates synchronously. Use it sparingly, mainly when an imperative integration must read the updated DOM immediately.
  • Legacy roots do not get React 18's full automatic batching behavior.
  • Updates separated into different execution contexts may produce separate commits; batching is not a promise that unrelated asynchronous work becomes one transaction.
  • Different priorities, such as transition updates, can be rendered or committed separately. startTransition marks work as non-urgent; it does not make the update synchronous.

For debugging, distinguish number of setter calls from number of renders: a setter enqueues work, and batching affects when React processes that work. Avoid relying on an exact render count for correctness; use functional updates and effects with accurate dependencies.

TechnicalMediumGrowwFrontend EngineerRound 3

19. When can removing useMemo or useCallback break a React app?

Model answer

Removing useMemo or useCallback can change behavior anywhere the cached identity is observed. It is usually safe when they only avoid expensive work or unnecessary renders, but identity-sensitive code can react to a newly created value or function.

  1. Effect dependencies: A fresh object or callback is different on every render. An effect depending on it will rerun. If that effect updates state, it can create a render loop or repeatedly reconnect, fetch, or subscribe.
   const options = useMemo(() => ({ roomId }), [roomId]);
   useEffect(() => connect(options), [options]);

Removing the memo makes options new on each render. Often the better fix is to create the object inside the effect and depend on roomId directly.

  1. Identity-sensitive consumers: A memoized child (React.memo), a Map keyed by an object, or an imperative API that registers and later removes the same callback may observe the changed identity. This can cause extra work or, if the API relies on identity for correctness, a real bug.
  2. Callback stability across subscriptions: If an event system or hook expects a stable callback, replacing it on every render may repeatedly unsubscribe/resubscribe or leave a stale registration if cleanup is incorrect.

A useful distinction: extra renders are usually a performance issue, not a correctness issue. useMemo and useCallback are performance optimizations; application correctness should not depend on React preserving their cached value indefinitely. If stable identity is a true semantic requirement, use an appropriate design—often a ref or an API that reads the latest value—rather than treating memoization as a permanent guarantee.

Before removing one, inspect its consumers and dependency arrays. If it only avoids recomputation or lets a memoized child skip renders, removal should preserve behavior, though it may hurt performance. If identity is part of an effect, subscription, or external API contract, refactor that boundary deliberately and test it.

TechnicalMediumGrowwFrontend EngineerProblem Solving in TypeScript

20. Why does O(1) space matter when detecting a cycle in a linked list?

Model answer

O(1) space means cycle detection uses a fixed amount of extra memory, regardless of how many nodes the list contains. The list itself is not counted as auxiliary space.

A common alternative stores every visited node in a Set. That takes O(n) extra space in the worst case. Floyd’s tortoise-and-hare algorithm instead keeps two references: slow moves one node at a time, and fast moves two. If there is a cycle, they eventually meet; if fast reaches the end, there is no cycle.

flowchart TD
    A["Initialize slow and fast at head"] --> B{"fast and fast.next exist?"}
    B -->|No| C["No cycle"]
    B -->|Yes| D["Move slow one step and fast two steps"]
    D --> E{"slow equals fast?"}
    E -->|Yes| F["Cycle found"]
    E -->|No| B
Diagram

This matters for very large lists or memory-constrained environments: O(1) auxiliary space avoids per-node allocations, garbage-collection pressure, and memory growth proportional to the input. It does not make the algorithm constant-time: Floyd’s algorithm is O(n) time and O(1) auxiliary space.

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