Quora interview questions & answers

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

CodingEasyQuoraSoftware Engineer

1. Find the K-Beauty of a Number (LeetCode)

Model answer

The task

Count the length-k digit sequences in num whose numeric value is a nonzero divisor of num. Sequences with leading zeroes are still considered windows.

Key idea

Scan the digits with a sliding numeric window, updating its value in constant time per digit. Check divisibility only when the window is nonzero.

Approach

  1. Convert num to a string so windows retain their original digits.
  2. Return 0 if k is longer than the digit string.
  3. Build the first window’s numeric value.
  4. For each window, count it if it is nonzero and divides num.
  5. Slide forward by removing the leading digit and appending the next digit.
class Solution:
    def divisorSubstrings(self, num: int, k: int) -> int:
        digits = str(num)
        if k > len(digits):
            return 0

        # Keep the last k - 1 digits when shifting the window.
        base = 10 ** (k - 1)
        window = int(digits[:k])
        count = 0

        for start in range(len(digits) - k + 1):
            if window != 0 and num % window == 0:
                count += 1

            # Advance to the next length-k window.
            if start + k < len(digits):
                window = (window % base) * 10 + int(digits[start + k])

        return count

Complexity:

  • Time: O(d), where d is the number of digits, assuming arithmetic on these values takes constant time.
  • Space: O(d) for the digit string.

Common follow-ups

  • What if k exceeds the number of digits? Return 0; no window of that length exists.
  • Why skip zero-valued windows? Division by zero is undefined, so they cannot be divisors.
  • How would you handle a number too large for built-in integer types? Keep the original number as a digit string and use an appropriate big-integer or modular arithmetic strategy for divisibility checks.
CodingEasyQuoraSoftware Engineer

2. Longest Common Prefix (LeetCode)

Model answer

The task

Given a list of strings, return the longest string that is a prefix of every entry. If there is no shared prefix, return an empty string.

Key idea

Compare characters at the same position across all strings, starting from the first string. Stop at the first mismatch or when any string runs out.

Approach

  1. If the list is empty, return an empty string.
  2. Scan each character of the first string from left to right.
  3. For each position, compare that character with the character at the same position in every other string.
  4. If a string is too short or a character differs, return the matching prefix before that position.
  5. If all positions match, return the first string.
from typing import List

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs:
            return ""

        first = strs[0]

        for i, char in enumerate(first):
            for word in strs[1:]:
                if i == len(word) or word[i] != char:
                    return first[:i]

        return first

Complexity:

  • Time: O(S), where S is the total number of characters inspected.
  • Space: O(1) auxiliary space, excluding the returned prefix.

Common follow-ups

  • How would you handle many prefix queries over the same set of strings? Build a trie once, then traverse it to find shared prefixes.
  • Could sorting help? Yes. Sort the strings and compare only the first and last; their common prefix is shared by all strings.
  • What if strings arrive as a stream? Keep a running prefix and shorten it as each new string arrives.
CodingEasyQuoraSoftware Engineer

3. Find Numbers with Even Number of Digits (LeetCode)

Model answer

The task

Given an array of integers, count how many have an even number of decimal digits.

Key idea

Count each number’s digits by repeatedly dividing its absolute value by 10. Add one to the answer when that count is even.

Approach

  1. Start a counter for qualifying numbers.
  2. For each value, use its absolute value so the digit count works for negative numbers too.
  3. Count digits by repeatedly dividing by 10; treat zero as having one digit.
  4. Increment the answer when the digit count is even.
  5. Return the counter.
from typing import List

class Solution:
    def findNumbers(self, nums: List[int]) -> int:
        count = 0

        for value in nums:
            number = abs(value)

            # Zero has one digit; other numbers are counted by division.
            digits = 1
            while number >= 10:
                number //= 10
                digits += 1

            if digits % 2 == 0:
                count += 1

        return count

Complexity:

  • Time: O(n · d), where n is the number of values and d is the maximum digit count.
  • Space: O(1), using only a fixed amount of extra space.

Common follow-ups

  • How would you count digits without a loop? Use len(str(abs(value))), at the cost of creating a temporary string.
  • How would you handle values in another base? Divide repeatedly by that base instead of 10.
  • How would you process a stream of values? Keep a running count and update it as each value arrives.
CodingEasyQuoraSoftware Engineer

4. 1-bit and 2-bit Characters (LeetCode)

Model answer

The task

Given a sequence of bits encoded using 0 for a one-bit character and 10 or 11 for a two-bit character, determine whether the final character is one-bit.

Key idea

Decode from left to right, advancing one position for a 0 and two positions for a 1. If decoding reaches the final bit, that bit starts a one-bit character; if it jumps past it, the final bit belongs to a two-bit character.

Approach

  1. Set an index to the start of the sequence.
  2. While the index is before the final bit, advance by one or two according to the current bit.
  3. Return whether the index lands exactly on the final bit.
from typing import List

class Solution:
    def isOneBitCharacter(self, bits: List[int]) -> bool:
        index = 0
        last = len(bits) - 1

        # Decode characters until reaching or passing the final bit.
        while index < last:
            index += 1 if bits[index] == 0 else 2

        return index == last

Complexity:

  • Time: O(n), where n is the number of bits scanned.
  • Space: O(1), using only an index.

Common follow-ups

  • What if the sequence is empty? The stated encoding assumes a nonempty sequence; otherwise, define the desired result explicitly.
  • Can the scan stop early? Yes. The loop already stops as soon as it reaches or passes the final bit.
  • Does the algorithm require the input to be validly encoded? Yes; it relies on each 1 beginning a two-bit character.
CodingEasyQuoraSoftware Engineer

5. Subtract the Product and Sum of Digits of an Integer (LeetCode)

Model answer

The task

For a positive integer, compute the product of its decimal digits minus the sum of its decimal digits.

Key idea

Extract one digit at a time with divmod. Accumulate its contribution to both the product and the sum in a single pass.

Approach

  1. Use the absolute value so the digit calculation also works for negative inputs.
  2. Initialize the product to 1 and the sum to 0.
  3. Repeatedly extract the last digit and update both accumulators.
  4. Process at least one digit so that 0 is handled as a single zero digit.
  5. Return the product minus the sum.
class Solution:
    def subtractProductAndSum(self, n: int) -> int:
        n = abs(n)
        product = 1
        digit_sum = 0

        # Process at least once so n = 0 contributes a digit of zero.
        while True:
            n, digit = divmod(n, 10)
            product *= digit
            digit_sum += digit

            if n == 0:
                break

        return product - digit_sum

Complexity:

  • Time: O(d), where d is the number of digits.
  • Space: O(1), since only a fixed number of variables are used.

Common follow-ups

  • How would you compute only the digit sum? Accumulate each extracted digit and omit the product.
  • What if the number is very large? Process its digits as a string in one pass.
  • How do zero digits affect the result? They make the product zero while adding zero to the sum.
CodingEasyQuoraSoftware Engineer

6. Maximum Number of Words You Can Type (LeetCode)

Model answer

The task

Given a string of space-separated words and a collection of broken lowercase letters, count how many words contain none of those letters.

Key idea

Put the broken letters in a set for constant-time membership checks. A word is typable if scanning its letters never finds one in that set.

Approach

  1. Convert brokenLetters to a set.
  2. Split the text into words.
  3. For each word, check whether any character is broken.
  4. Count the words that pass the check.
class Solution:
    def canBeTypedWords(self, text: str, brokenLetters: str) -> int:
        broken = set(brokenLetters)
        typable_count = 0

        for word in text.split():
            if all(char not in broken for char in word):
                typable_count += 1

        return typable_count

Complexity:

  • Time: O(n + b), where n is the length of text and b is the number of broken letters. Each text character is checked at most once.
  • Space: O(n + b) for the split words and the set of broken letters.

Common follow-ups

  • What if the text has repeated spaces? split() without an argument treats runs of whitespace as separators.
  • Can you avoid storing all split words? Scan characters directly and track whether the current word contains a broken letter.
  • What if letters are case-insensitive? Normalize both the text and broken-letter string to the same case before checking.
CodingEasyQuoraSoftware Engineer

7. Substrings of Size Three with Distinct Characters (LeetCode)

Model answer

The task

Count the contiguous substrings of length three in a string whose three characters are all different.

Key idea

Check each length-three window once. A window is valid exactly when its set contains three characters.

Approach

  1. Start a count at zero.
  2. Slide across every possible starting position for a length-three window.
  3. Compare the window’s three characters; increment the count if they are distinct.
  4. Return the count.
class Solution:
    def countGoodSubstrings(self, s: str) -> int:
        count = 0

        # Each window starts at an index with two following characters.
        for i in range(len(s) - 2):
            if len(set(s[i:i + 3])) == 3:
                count += 1

        return count

Complexity:

  • Time: O(n), where n is the string length; each window takes constant work.
  • Space: O(1), since the set contains at most three characters.

Common follow-ups

  • How would you count valid windows of length k? Track character frequencies in a sliding window and check whether all k characters are distinct.
  • What if the string is very large and arrives as a stream? Keep only the most recent three characters and update the count as each new character arrives.
  • What if characters are case-insensitive? Normalize each character (for example, with lower()) before checking distinctness.
CodingMediumQuoraSoftware Engineer

8. Insert Delete GetRandom O(1) (LeetCode)

Model answer

The task

Design a collection that supports adding and removing values, plus returning a uniformly random stored value. Each operation should take average O(1) time.

Key idea

Store values in a list for constant-time random indexing, and map each value to its index for fast lookup. To remove an item without shifting the list, swap it with the last item and then pop.

Approach

  1. Keep a list of stored values and a dictionary from value to its list index.
  2. For insertion, return False if the value is already present; otherwise append it and record its index.
  3. For removal, return False if absent. Otherwise, move the last value into the removed value’s slot, update its index, then pop and delete the removed value from the dictionary.
  4. For random selection, choose a uniformly random index in the list.
  5. Assume random selection is called only when the collection is nonempty.
import random

class RandomizedSet:
    def __init__(self):
        self.values = []
        self.index_by_value = {}

    def insert(self, val: int) -> bool:
        if val in self.index_by_value:
            return False

        self.index_by_value[val] = len(self.values)
        self.values.append(val)
        return True

    def remove(self, val: int) -> bool:
        if val not in self.index_by_value:
            return False

        index = self.index_by_value[val]
        last_value = self.values[-1]

        # Fill the removed value's slot with the last value.
        self.values[index] = last_value
        self.index_by_value[last_value] = index

        self.values.pop()
        del self.index_by_value[val]
        return True

    def getRandom(self) -> int:
        return random.choice(self.values)

Complexity:

  • Time: O(1) average per operation; dictionary operations are expected O(1).
  • Space: O(n), for the list and index map storing n values.

Common follow-ups

  • How would you support duplicates? Store each value’s set of indices and update that set during swaps.
  • What if random selection must be weighted? Maintain cumulative weights and use binary search, or use a dynamic weighted-sampling structure.
  • What happens if getRandom is called when empty? Define a clear error or sentinel behavior; the implementation assumes at least one value exists.
CodingMediumQuoraSoftware Engineer

9. 3Sum With Multiplicity (LeetCode)

Model answer

The task

Count how many ways to choose three different array indices whose values sum to target. Return the count modulo \(10^9+7\).

Key idea

Count each value’s frequency, then consider value triples in nondecreasing order. The number of index choices for a triple depends on whether its values are all distinct, two are equal, or all three are equal.

Approach

  1. Build a frequency map and sort its distinct values.
  2. Choose the first two values, x and y, with x <= y.
  3. Compute z = target - x - y; continue only if z is present and y <= z.
  4. Add the appropriate frequency combinations for the equality pattern.
  5. Return the accumulated count modulo \(10^9+7\).
from collections import Counter
from typing import List

class Solution:
    def threeSumMulti(self, arr: List[int], target: int) -> int:
        mod = 10**9 + 7
        counts = Counter(arr)
        values = sorted(counts)
        total = 0

        for i, x in enumerate(values):
            for y in values[i:]:
                z = target - x - y

                # Enforce x <= y <= z so each value triple is counted once.
                if z < y or z not in counts:
                    continue

                cx, cy, cz = counts[x], counts[y], counts[z]

                if x == y == z:
                    ways = cx * (cx - 1) * (cx - 2) // 6
                elif x == y:
                    ways = cx * (cx - 1) // 2 * cz
                elif y == z:
                    ways = cx * cy * (cy - 1) // 2
                else:
                    ways = cx * cy * cz

                total = (total + ways) % mod

        return total

Complexity:

  • Time: O(n + U²), for counting values and checking pairs of distinct values.
  • Space: O(U), for the frequency map and sorted values; U is the number of distinct values.

Common follow-ups

  • How would you handle a streaming array? Maintain frequencies and update counts as each value arrives.
  • What if the answer must be exact rather than modulo a number? Remove the modulo operation; Python integers support arbitrary precision.
  • How can you reduce the pair-enumeration cost when the value range is small? Use a frequency array and enumerate only values in that range.
CodingMediumQuoraSoftware Engineer

10. Sort the Matrix Diagonally (LeetCode)

Model answer

The task

Rearrange each diagonal running from the matrix’s upper-left toward its lower-right so its values are in ascending order. Return the modified matrix.

Key idea

Process one diagonal at a time, collecting and sorting its values before writing them back. Each diagonal can be identified by its starting cell, so no extra grouping structure is needed.

Approach

  1. Visit each diagonal starting on the top row.
  2. Then visit each diagonal starting on the left edge, skipping the already-visited top-left cell.
  3. For each starting cell, collect values by moving down and right.
  4. Sort the collected values and write them back along that diagonal.
class Solution:
    def diagonalSort(self, mat: list[list[int]]) -> list[list[int]]:
        rows, cols = len(mat), len(mat[0])

        def sort_diagonal(start_row: int, start_col: int) -> None:
            values = []
            r, c = start_row, start_col

            # Collect values along this diagonal.
            while r < rows and c < cols:
                values.append(mat[r][c])
                r += 1
                c += 1

            values.sort()

            # Write the sorted values back in diagonal order.
            r, c = start_row, start_col
            for value in values:
                mat[r][c] = value
                r += 1
                c += 1

        # Diagonals beginning on the top edge.
        for col in range(cols):
            sort_diagonal(0, col)

        # Diagonals beginning on the left edge, excluding the top-left.
        for row in range(1, rows):
            sort_diagonal(row, 0)

        return mat

Complexity:

  • Time: O(mn log(min(m, n))), sorting the values on each diagonal.
  • Space: O(min(m, n)), storing the values of one diagonal at a time.

Common follow-ups

  • How would you sort each diagonal in descending order? Sort in reverse order before writing values back.
  • How would you sort diagonals in place with less auxiliary memory? Consider an in-place sorting method, though it may be slower.
  • How would you group diagonals without traversing from their starting cells? Use the invariant row - col to identify each diagonal.
CodingMediumQuoraSoftware Engineer

11. Subarray Sum Equals K (LeetCode)

Model answer

The task

Count the contiguous subarrays whose elements sum to a given target k. The array may contain negative numbers, so subarray sums do not necessarily grow as the subarray gets longer.

Key idea

For each position, let prefix be the sum of all elements seen so far. A subarray ending here sums to k exactly when an earlier prefix sum equals prefix - k. Keep counts of earlier prefix sums in a hash table.

Approach

  1. Start with prefix sum 0 occurring once, representing the empty prefix.
  2. Scan the array and add each value to the running prefix sum.
  3. Add the number of times prefix - k has appeared to the answer.
  4. Record the current prefix sum for future positions.
from collections import defaultdict
from typing import List

class Solution:
    def subarraySum(self, nums: List[int], k: int) -> int:
        # Counts of prefix sums seen so far.
        prefix_counts = defaultdict(int)
        prefix_counts[0] = 1

        prefix_sum = 0
        subarray_count = 0

        for value in nums:
            prefix_sum += value

            # Each matching earlier prefix identifies one subarray
            # ending at the current position.
            subarray_count += prefix_counts[prefix_sum - k]

            # Record this prefix only after counting, so the match
            # refers to an earlier position.
            prefix_counts[prefix_sum] += 1

        return subarray_count

Complexity: Time: O(n), where n is the number of elements; each element is processed once.

Complexity: Space: O(n) in the worst case, for the distinct prefix sums stored.

Common follow-ups

  • Why not use a sliding window? Negative values break the monotonic behavior of window sums that sliding-window techniques rely on.
  • What if all values are nonnegative? A sliding window can be used, though prefix sums still provide a straightforward solution.
  • Can this count subarrays for many target values? The prefix-frequency scan is target-specific; repeated queries may need a different strategy depending on the input size and query count.
CodingMediumQuoraSoftware Engineer

12. You are given a list of (website, user) pairs that represent users visiting websites.

The full question

You are given a list of (website, user) pairs that represent users visiting websites. Come up with a program that identifies the top k pairs of websites with the greatest similarity.

For example, suppose k = 1, and the list of tuples is:

[('a', 1), ('a', 3), ('a', 5), ('b', 2), ('b', 6), ('c', 1), ('c', 2), ('c', 3), ('c', 4), ('c', 5) ('d', 4), ('d', 5), ('d', 6), ('d', 7), ('e', 1), ('e', 3), ('e': 5), ('e', 6)]

Then a reasonable similarity metric would most likely conclude that a and e are the most similar, so your program should return [('a', 'e')].

Model answer

function topSimilarWebsitePairs(visits, k) {
  // Build one set per website so repeated visits by a user count once.
  const usersBySite = new Map();
  for (const [site, user] of visits) {
    if (!usersBySite.has(site)) usersBySite.set(site, new Set());
    usersBySite.get(site).add(user);
  }

  const sites = [...usersBySite.keys()].sort();
  const scoredPairs = [];

  for (let i = 0; i < sites.length; i++) {
    for (let j = i + 1; j < sites.length; j++) {
      const a = sites[i];
      const b = sites[j];
      const usersA = usersBySite.get(a);
      const usersB = usersBySite.get(b);

      let intersectionSize = 0;
      for (const user of usersA) {
        if (usersB.has(user)) intersectionSize++;
      }

      // Jaccard similarity: shared users / users who visited either site.
      const unionSize = usersA.size + usersB.size - intersectionSize;
      const similarity = unionSize === 0 ? 0 : intersectionSize / unionSize;
      scoredPairs.push({ pair: [a, b], similarity });
    }
  }

  scoredPairs.sort((x, y) =>
    y.similarity - x.similarity ||
    x.pair[0].localeCompare(y.pair[0]) ||
    x.pair[1].localeCompare(y.pair[1])
  );

  return scoredPairs.slice(0, Math.max(0, k)).map(item => item.pair);
}

const visits = [
  ['a', 1], ['a', 3], ['a', 5],
  ['b', 2], ['b', 6],
  ['c', 1], ['c', 2], ['c', 3], ['c', 4], ['c', 5],
  ['d', 4], ['d', 5], ['d', 6], ['d', 7],
  ['e', 1], ['e', 3], ['e', 5], ['e', 6]
];

console.log(topSimilarWebsitePairs(visits, 1));
// [ [ 'a', 'e' ] ]
  • Treat each website’s visitors as a set, then score every pair with Jaccard similarity. It is 1 for identical audiences and 0 for disjoint audiences.
  • Sorting all pairs also gives deterministic results for ties. For very large numbers of sites, an inverted index from user to sites can avoid scoring pairs with no shared visitors.
  • Complexity: O(S² × U + S² log S) time in the straightforward implementation, where S is the number of sites and U is the largest audience; O(S × U + S²) space.
CodingMediumQuoraSoftware Engineer

13. Finding Pairs With a Certain Sum (LeetCode)

Model answer

The task

Design a data structure for two integer arrays. It should support adding a value to an indexed element of the second array and counting pairs—one element from each array—that sum to a requested total.

Key idea

Keep a frequency map of the second array, updating it whenever an element changes. To count pairs for a total, scan the first array and look up how often its required complement appears in that map.

Approach

  1. Store the first array and a mutable copy of the second.
  2. Build a frequency map for the second array.
  3. For an update, decrement the old value’s frequency, change the element, then increment the new value’s frequency.
  4. For a count query, sum the frequencies of the complements needed by each element in the first array.
from collections import Counter
from typing import List

class FindSumPairs:
    def __init__(self, nums1: List[int], nums2: List[int]):
        self.nums1 = nums1
        self.nums2 = nums2
        self.counts2 = Counter(nums2)

    def add(self, index: int, val: int) -> None:
        old_value = self.nums2[index]
        self.counts2[old_value] -= 1

        self.nums2[index] += val
        self.counts2[self.nums2[index]] += 1

    def count(self, tot: int) -> int:
        pairs = 0
        for value in self.nums1:
            pairs += self.counts2[tot - value]
        return pairs

Complexity:

  • Time: add is O(1) average; count is O(n1), where n1 is the first array’s length.
  • Space: O(u2) for the frequency map, where u2 is the number of distinct values in the second array.

Common follow-ups

  • Can counting be faster for repeated totals? Cache query results, invalidating or updating the cache after each modification.
  • Can counting scan the smaller array? Maintain frequency maps for both arrays and sum frequency products over the smaller one’s distinct values.
  • What if updates can remove values? Apply the same frequency adjustment, adding the negative change to the indexed element.
CodingMediumQuoraSoftware Engineer

14. Range Frequency Queries (LeetCode)

Model answer

The task

Design a data structure over a fixed array that answers how many times a given value appears in an inclusive index range.

Key idea

Store, for each value, the sorted indices where it occurs. Two binary searches find the first and last matching positions within the requested range, so each query avoids scanning the array.

Approach

  1. Iterate through the array and append each index to the list for its value. The lists are sorted because indices are visited in order.
  2. For a query, get the list of indices for the requested value.
  3. Use bisect_left to find the first index at least left.
  4. Use bisect_right to find the first index greater than right.
  5. The difference between those positions is the number of occurrences in the inclusive range.
from collections import defaultdict
from bisect import bisect_left, bisect_right

class RangeFreqQuery:
    def __init__(self, arr: list[int]):
        self.positions = defaultdict(list)

        for index, value in enumerate(arr):
            self.positions[value].append(index)

    def query(self, left: int, right: int, value: int) -> int:
        indices = self.positions.get(value, [])

        first = bisect_left(indices, left)
        after_last = bisect_right(indices, right)

        return after_last - first

Complexity:

  • Time: O(n) to build; O(log f) per query, where f is the number of occurrences of the queried value.
  • Space: O(n), for the stored indices.

Common follow-ups

  • How would point updates be supported? Keep an ordered set of indices per value; updates remove the index from one set and insert it into another.
  • What if the array is very large and rarely queried? Consider storing only values or ranges relevant to the expected queries, if that workload is known.
  • Could a segment tree answer these queries? Yes, but a tree storing value-frequency maps is more complex; for a static array, per-value index lists are simpler and efficient.
CodingMediumQuoraSoftware Engineer

15. Word sense disambiguation is the problem of determining which sense a word takes on in a particular setting, if that word has multiple meanings.

The full question

Word sense disambiguation is the problem of determining which sense a word takes on in a particular setting, if that word has multiple meanings. For example, in the sentence "I went to get money from the bank", bank probably means the place where people deposit money, not the land beside a river or lake.

Suppose you are given a list of meanings for several words, formatted like so:

{ "word_1": ["meaning one", "meaning two", ...], ... "word_n": ["meaning one", "meaning two", ...] } Given a sentence, most of whose words are contained in the meaning list above, create an algorithm that determines the likely sense of each possibly ambiguous word.

Model answer

A practical approach is a gloss-overlap method, often called a Lesk-style algorithm. Each listed meaning acts as a short definition (gloss); choose the sense whose gloss best matches the sentence context.

function disambiguate(sentence, meaningsByWord) {
  const stopWords = new Set([
    'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from',
    'in', 'is', 'it', 'of', 'on', 'or', 'the', 'to', 'was', 'were', 'with'
  ]);

  const tokenize = text =>
    text.toLowerCase().match(/[a-z0-9]+/g) || [];
  const usefulTokens = text =>
    tokenize(text).filter(token => !stopWords.has(token));

  const sentenceTokens = tokenize(sentence);
  const glosses = [];

  // Build gloss token sets and document frequencies for IDF weighting.
  for (const [word, meanings] of Object.entries(meaningsByWord)) {
    meanings.forEach((meaning, senseIndex) => {
      const tokens = usefulTokens(meaning);
      glosses.push({ word: word.toLowerCase(), senseIndex, tokens });
    });
  }

  const documentFrequency = new Map();
  for (const gloss of glosses) {
    for (const token of new Set(gloss.tokens)) {
      documentFrequency.set(token, (documentFrequency.get(token) || 0) + 1);
    }
  }

  const totalGlosses = glosses.length;
  const results = [];

  sentenceTokens.forEach((token, position) => {
    const meanings = meaningsByWord[token];
    if (!meanings || meanings.length === 0) return;

    // Other sentence words provide evidence for the sense at this occurrence.
    const context = sentenceTokens.filter((_, i) => i !== position);
    const contextCounts = new Map();
    for (const contextToken of context) {
      if (!stopWords.has(contextToken)) {
        contextCounts.set(contextToken, (contextCounts.get(contextToken) || 0) + 1);
      }
    }

    let bestIndex = 0;
    let bestScore = -1;

    meanings.forEach((meaning, senseIndex) => {
      const glossTokens = new Set(usefulTokens(meaning));
      let score = 0;

      for (const [contextToken, count] of contextCounts) {
        if (glossTokens.has(contextToken)) {
          const df = documentFrequency.get(contextToken) || 0;
          const idf = Math.log((totalGlosses + 1) / (df + 1)) + 1;
          score += count * idf;
        }
      }

      // Keep the first listed sense when evidence ties or all scores are zero.
      if (score > bestScore) {
        bestScore = score;
        bestIndex = senseIndex;
      }
    });

    results.push({
      word: token,
      tokenIndex: position,
      senseIndex: bestIndex,
      meaning: meanings[bestIndex],
      score: bestScore
    });
  });

  return results;
}

const meanings = {
  bank: ['a financial institution that accepts deposits', 'the land beside a river'],
  money: ['currency used to buy goods and services'],
  river: ['a large natural stream of water']
};

console.log(disambiguate('I went to get money from the bank', meanings));
  • For each occurrence of a listed word, compare the other sentence words with each candidate definition. IDF weighting makes distinctive context words count more than words common across definitions.
  • Return the highest-scoring sense; ties fall back to the first listed meaning. A production system could improve this with stemming, phrase overlap, a wider document context, or a trained contextual model.
  • Complexity: If there are T sentence tokens and G total tokens across definitions, this simple implementation is approximately O(T × G) time; space is O(G).
CodingMediumQuoraSoftware Engineer

16. Given a string, find the palindrome that can be made by inserting the fewest number of characters as possible anywhere in the word.

The full question

Given a string, find the palindrome that can be made by inserting the fewest number of characters as possible anywhere in the word. If there is more than one palindrome of minimum length that can be made, return the lexicographically earliest one (the first one alphabetically). For example, given the string "race", you should return "ecarace", since we can add three letters to it (which is the smallest amount to make a palindrome). There are seven other palindromes that can be made from "race" by adding three letters, but "ecarace" comes first alphabetically. As another example, given the string "google", you should return "elgoogle".

Model answer

function shortestLexPalindrome(s) {
  const n = s.length;
  if (n === 0) return "";

  // Memoize the best palindrome for each substring [i, j].
  const memo = Array.from({ length: n }, () => Array(n));

  function solve(i, j) {
    if (i > j) return "";
    if (i === j) return s[i];
    if (memo[i][j] !== undefined) return memo[i][j];

    const candidates = [];

    // Match the existing ends when they are equal.
    if (s[i] === s[j]) {
      candidates.push(s[i] + solve(i + 1, j - 1) + s[j]);
    }

    // Insert a copy of the left character at the right, or vice versa.
    candidates.push(s[i] + solve(i + 1, j) + s[i]);
    candidates.push(s[j] + solve(i, j - 1) + s[j]);

    // Minimize length first; break ties by JavaScript's lexical order.
    let best = candidates[0];
    for (const candidate of candidates.slice(1)) {
      if (candidate.length < best.length ||
          (candidate.length === best.length && candidate < best)) {
        best = candidate;
      }
    }

    memo[i][j] = best;
    return best;
  }

  return solve(0, n - 1);
}

// Examples:
console.log(shortestLexPalindrome("race"));   // "ecarace"
console.log(shortestLexPalindrome("google")); // "elgoogle"
  • For each substring, consider matching equal ends or inserting a copy of either end character.
  • Choose the shortest candidate, then the lexicographically earliest among equal-length candidates. This tie-break ensures the minimum-insertion palindrome is returned.

Complexity: There are (O(n^2)) substring states. String construction and comparison cost up to (O(n)) per state, so time is (O(n^3)); memoized strings use up to (O(n^3)) space.

CodingMediumQuoraSoftware Engineer

17. Get Biggest Three Rhombus Sums in a Grid (LeetCode)

Model answer

The task

For every rhombus whose sides follow the grid’s diagonal directions, calculate the sum of its border cells. Return the three largest distinct sums, or fewer if there are fewer than three.

Key idea

Build prefix sums along both diagonal directions so each rhombus edge can be summed in constant time. A rhombus with side length zero is a single cell; for larger rhombi, add the four edge sums and subtract the four vertices, which were counted twice.

Approach

  1. Build cumulative sums for northwest-to-southeast and northeast-to-southwest diagonals.
  2. Add every grid cell value as a size-zero rhombus sum.
  3. Treat each cell as a rhombus’s top vertex and try every side length that fits.
  4. Get each border sum from the diagonal prefixes, correcting for duplicated vertices.
  5. Sort the distinct sums in descending order and return up to three.
class Solution:
    def getBiggestThree(self, grid: list[list[int]]) -> list[int]:
        rows, cols = len(grid), len(grid[0])

        # dr[r][c]: cumulative sum along the diagonal from northwest to (r, c).
        # dl[r][c]: cumulative sum along the diagonal from northeast to (r, c).
        dr = [[0] * cols for _ in range(rows)]
        dl = [[0] * cols for _ in range(rows)]

        for r in range(rows):
            for c in range(cols):
                dr[r][c] = grid[r][c]
                dl[r][c] = grid[r][c]

                if r > 0 and c > 0:
                    dr[r][c] += dr[r - 1][c - 1]
                if r > 0 and c + 1 < cols:
                    dl[r][c] += dl[r - 1][c + 1]

        sums = {value for row in grid for value in row}

        for r in range(rows):
            for c in range(cols):
                side = 1
                while r + 2 * side < rows and c - side >= 0 and c + side < cols:
                    right_r, right_c = r + side, c + side
                    bottom_r, bottom_c = r + 2 * side, c
                    left_r, left_c = r + side, c - side

                    # Sum each of the four edges, including both endpoints.
                    edge1 = dr[right_r][right_c]
                    if r > 0 and c > 0:
                        edge1 -= dr[r - 1][c - 1]

                    edge2 = dl[bottom_r][bottom_c]
                    if right_r > 0 and right_c + 1 < cols:
                        edge2 -= dl[right_r - 1][right_c + 1]

                    edge3 = dr[bottom_r][bottom_c]
                    if left_r > 0 and left_c > 0:
                        edge3 -= dr[left_r - 1][left_c - 1]

                    edge4 = dl[left_r][left_c]
                    if r > 0 and c + 1 < cols:
                        edge4 -= dl[r - 1][c + 1]

                    border_sum = (
                        edge1 + edge2 + edge3 + edge4
                        - grid[r][c]
                        - grid[right_r][right_c]
                        - grid[bottom_r][bottom_c]
                        - grid[left_r][left_c]
                    )
                    sums.add(border_sum)
                    side += 1

        return sorted(sums, reverse=True)[:3]

Complexity:

  • Time: O(mn · min(m, n) + K log K), where K is the number of candidate rhombi.
  • Space: O(mn + K) for the diagonal prefixes and distinct sums.

Common follow-ups

  • How can the extra sort be avoided? Keep a min-heap of the three largest distinct sums.
  • What if only the largest sum is needed? Track the maximum as candidates are generated.
  • What if the rhombus border must be returned too? Store its vertices and enumerate the four diagonal edges.
Product & growthMediumQuoraData Scientist

18. Assume you want to test whether a new feature increases signups to the site.

The full question

Assume you want to test whether a new feature increases signups to the site. How would you run this experiment? What statistical test(s) would you use?

Model answer

Clarify & scope

I’d define the feature and the signup outcome before launching. For example, the primary question is whether showing the feature causes more eligible visitors to complete signup within a fixed window. I’d confirm that the feature is the only intended difference between groups and that the experiment can be run safely.

User segments & pain points

I’d focus on eligible, logged-out visitors who can actually encounter the feature. Randomize consistently at the user level (or a stable anonymous-ID level before signup) so one person does not see both variants. I’d exclude bots and internal traffic using rules set before looking at results.

Goals & success metrics

The primary metric would be signup conversion: unique users completing signup divided by eligible users assigned to each arm. I’d also monitor guardrails such as page latency, errors, signup quality or downstream retention, and any abuse or privacy impact. I’d choose a practically meaningful minimum detectable effect, significance level (often 5%), and power (often 80–90%) in advance, then calculate the required sample size from the baseline conversion rate. I’d run through the planned sample size and at least a representative weekly cycle rather than stopping when a result first looks significant.

Solutions

I’d compare control with the feature using a randomized A/B test. The assignment should be persistent, and analysis should follow intent-to-treat: analyze users according to the group they were assigned, even if they did not engage with the feature.

Recommendation: Use a two-sided two-proportion z-test for the difference in signup rates, with a confidence interval for the absolute and relative lift. A chi-square test gives the equivalent large-sample test for a 2×2 table; use Fisher’s exact test if counts are too small for the approximation. If I test multiple variants or multiple primary outcomes, I’d adjust for multiple comparisons or designate one primary hypothesis. I would not use a t-test on individual binary outcomes as my default.

Prioritization & trade-offs

I’d prioritize a clean, adequately powered test over adding many variants. Segmented results can reveal heterogeneity, but I’d treat unplanned subgroup findings as exploratory to avoid false positives.

MVP, measurement & rollout

I’d validate exposure and conversion logging, run an A/A or instrumentation check if needed, then launch gradually with monitoring. At the end, I’d report the estimated lift, confidence interval, p-value, guardrails, and limitations. I’d ship only if the evidence supports a meaningful benefit without unacceptable harm—not merely because the p-value is below 0.05.

TechnicalMediumQuoraProduct Manager

19. Explain statistical significance and why it's important.

The full question

Explain statistical significance and why it's important.

Make it harder? Say your answer out loud - do so in under 1 minute.

Model answer

Statistical significance is evidence, under a specified statistical model, that an observed result would be unusual if the null hypothesis were true. A p-value is the probability of seeing a result at least this extreme assuming that null hypothesis—not the probability that the null is true.

It matters because random variation can make a feature appear to improve signups even when it has no real effect. Significance gives us a disciplined way to assess that risk when deciding whether to act on an experiment. But it does not tell us whether the effect is large enough to matter, or whether the experiment was well designed. I’d consider the effect size, confidence interval, sample size, and practical impact alongside the p-value.

TechnicalMediumQuoraData Scientist

20. You are drawing from a normally distributed random variable X ~ N(0, 1) once a day.

The full question

You are drawing from a normally distributed random variable X ~ N(0, 1) once a day. What is the approximate expected number of days until you get a value of more than 2?

Model answer

For a standard normal variable, the chance of exceeding 2 is

[ p=P(X>2)=1-\Phi(2)\approx 0.0228. ]

Each day's draw is an independent Bernoulli trial with success probability (p), so the waiting time is geometric. Its expected value, counting the successful day, is

[ E[T]=\frac{1}{p}\approx \frac{1}{0.0228}\approx 44\text{ days}. ]

This is an average, not a guarantee: the first such value could arrive tomorrow or much later.

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