Pure Storage interview questions & answers

18 real Pure Storage interview questions with full model answers — Technical, Coding. Drawn from the same verified bank ChannelPulse drills from (18 Pure Storage questions in total).

CodingEasyPure StorageSoftware Engineer

1. Maximum Repeating Substring (LeetCode)

Model answer

The task

Given a string sequence and a nonempty string word, find the largest number of consecutive copies of word that appear as a substring of sequence.

Key idea

Use dynamic programming from right to left. If word begins at position i, the count there is one plus the count beginning immediately after it. This enforces consecutive copies; separate or overlapping matches do not add to the count.

Approach

  1. Let dp[i] be the maximum number of consecutive copies starting at index i.
  2. Visit positions from right to left so the value at i + len(word) is already known.
  3. When the slice at i matches word, set dp[i] = 1 + dp[i + len(word)].
  4. Track and return the largest value.
class Solution:
    def maxRepeating(self, sequence: str, word: str) -> int:
        n = len(sequence)
        m = len(word)

        if m == 0:
            return 0

        # dp[i] counts consecutive copies of word starting at i.
        dp = [0] * (n + 1)
        best = 0

        for i in range(n - m, -1, -1):
            if sequence[i:i + m] == word:
                dp[i] = 1 + dp[i + m]
                best = max(best, dp[i])

        return best

Complexity:

  • Time: O(n · m), where each of up to n positions may compare a slice of length m.
  • Space: O(n), for the dynamic-programming array.

Common follow-ups

  • How can matching be made more efficient for long strings? Use a string-matching algorithm such as KMP to find occurrences, then combine occurrences separated by exactly len(word).
  • Do overlapping occurrences count? Only if they form consecutive, non-overlapping copies of word.
  • What if word is empty? This implementation returns 0; the usual problem definition assumes a nonempty word.
CodingEasyPure StorageSoftware Engineer

2. Binary Search (LeetCode)

Model answer

The task

Given an array sorted in ascending order and a target value, return the target’s index if it is present; otherwise return -1.

Key idea

Use binary search to repeatedly discard the half of the remaining range that cannot contain the target. Because the array is sorted, each comparison tells us which half to keep.

Approach

  1. Set left and right to the first and last valid indices.
  2. While the range is nonempty, choose its midpoint.
  3. If the midpoint value matches the target, return its index.
  4. If it is smaller, continue in the right half; otherwise, continue in the left half.
  5. If the range becomes empty, return -1.
class Solution:
    def search(self, nums: list[int], target: int) -> int:
        left = 0
        right = len(nums) - 1

        while left <= right:
            # This form avoids overflowing fixed-width integer types.
            mid = left + (right - left) // 2

            if nums[mid] == target:
                return mid
            if nums[mid] < target:
                left = mid + 1
            else:
                right = mid - 1

        return -1

Complexity:

  • Time: O(log n), since each iteration halves the search range.
  • Space: O(1), since the search uses only a fixed number of variables.

Common follow-ups

  • How would you find the first occurrence when duplicates are allowed? Record a match and keep searching the left half.
  • How would you find the insertion position for a missing target? Return left after the loop; it is the first index whose value is not less than the target.
  • What if the sorted array is rotated? Use a modified binary search that identifies which half is sorted, then checks whether the target lies in that half.
CodingEasyPure StorageSoftware EngineerOnline assessment

3. How would you remove all elements from a linked list that have the same value as a given value?

Model answer

Use a dummy node before the head so the same pointer-update logic handles deleting the first node and deleting nodes in the middle. Walk the list once, bypassing each matching node.

class ListNode {
  constructor(value, next = null) {
    this.value = value;
    this.next = next;
  }
}

function removeElements(head, target) {
  const dummy = new ListNode(null, head);
  let current = dummy;

  while (current.next !== null) {
    if (current.next.value === target) {
      // Skip the matching node; current stays in place in case the next node also matches.
      current.next = current.next.next;
    } else {
      current = current.next;
    }
  }

  return dummy.next;
}

function fromArray(values) {
  const dummy = new ListNode(null);
  let tail = dummy;
  for (const value of values) {
    tail.next = new ListNode(value);
    tail = tail.next;
  }
  return dummy.next;
}

function toArray(head) {
  const values = [];
  for (let node = head; node !== null; node = node.next) {
    values.push(node.value);
  }
  return values;
}

const list = fromArray([1, 2, 6, 3, 6, 4]);
console.log(toArray(removeElements(list, 6))); // [1, 2, 3, 4]
  • The dummy node avoids a separate head-deletion case, and keeping current in place after a deletion handles consecutive matches.
  • Complexity: O(n) time, O(1) extra space, excluding the returned list and test helpers.
CodingMediumPure StorageSoftware Engineer

4. Detect Squares (LeetCode)

Model answer

The task

Design a data structure that accepts points over time and can count how many axis-aligned squares can be formed with a given query point as one corner. Repeated points count as separate choices.

Key idea

For each other point on the query’s horizontal line, the horizontal distance fixes the square’s side length. Check both possible vertical directions, multiplying the counts of the three other corners.

Approach

  1. Store the multiplicity of each point.
  2. Also index points by their row, mapping each row’s x-coordinates to their multiplicities.
  3. When counting, scan points on the query’s row, skipping the query’s own x-coordinate.
  4. For each candidate, check the two possible rows for the remaining corners and add the product of their multiplicities.
from collections import Counter, defaultdict

class DetectSquares:
    def __init__(self):
        self.point_counts = Counter()
        # For each y-coordinate, store x-coordinates and their multiplicities.
        self.points_by_row = defaultdict(Counter)

    def add(self, point: list[int]) -> None:
        x, y = point
        self.point_counts[(x, y)] += 1
        self.points_by_row[y][x] += 1

    def count(self, point: list[int]) -> int:
        x, y = point
        total = 0

        # Choose the square's other corner on the query point's row.
        for other_x, base_count in self.points_by_row[y].items():
            if other_x == x:
                continue

            side = other_x - x

            # The square can extend either above or below the row.
            for other_y in (y + side, y - side):
                total += (
                    base_count
                    * self.point_counts[(x, other_y)]
                    * self.point_counts[(other_x, other_y)]
                )

        return total

Complexity:

  • Time: add is O(1); count is O(k), where k is the number of distinct x-coordinates on the query’s row.
  • Space: O(u), where u is the number of distinct points stored.

Common follow-ups

  • What if points must be removed? Decrement both indexes, deleting entries when their counts reach zero.
  • What if squares may be rotated? Enumerate possible diagonal pairs and verify the rotated corners.
  • How can query time be reduced for a very dense row? Choose an indexing strategy based on the expected distribution of queries and points.
CodingMediumPure StorageSoftware Engineer

5. 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.
CodingMediumPure StorageSoftware Engineer

6. 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.
CodingMediumPure StorageSoftware Engineer

7. Palindromic Substrings (LeetCode)

Model answer

The task

Given a string, count how many of its substrings are palindromes. Count each substring by its position, so equal text at different positions contributes more than once.

Key idea

Every palindrome has a center: either one character or the gap between two characters. Expand outward from each possible center while the characters match, counting each palindrome found.

Approach

  1. Initialize a counter for the palindromic substrings.
  2. Visit each character position as an odd-length center.
  3. Visit each gap between adjacent characters as an even-length center.
  4. For each center, expand left and right while the characters match, adding one to the counter for each match.
  5. Return the counter.
class Solution:
    def countSubstrings(self, s: str) -> int:
        count = 0
        n = len(s)

        def expand(left: int, right: int) -> int:
            found = 0

            # Every matching expansion forms another palindrome.
            while left >= 0 and right < n and s[left] == s[right]:
                found += 1
                left -= 1
                right += 1

            return found

        for center in range(n):
            # Odd-length palindromes centered on one character.
            count += expand(center, center)

            # Even-length palindromes centered between characters.
            count += expand(center, center + 1)

        return count

Complexity:

  • Time: O(n²), since each of the O(n) centers can expand across O(n) characters.
  • Space: O(1), using only a counter and a few indices.

Common follow-ups

  • How would you find the longest palindromic substring? Track the longest span found during each expansion.
  • How would you count distinct palindrome values instead of occurrences? Store the distinct palindrome strings in a set; this can require O(n²) space.
  • Can this be solved with dynamic programming? Yes: record whether each interval is a palindrome based on its end characters and its inner interval, using O(n²) time and space.
CodingMediumPure StorageSoftware Engineer

8. How would you draw a circle using a bitmap?

Model answer

For a bitmap, I’d use the midpoint circle algorithm. It computes one octant of the circle using integer arithmetic, then plots the eight symmetric points around the center. The pixel setter clips coordinates that fall outside the bitmap.

function createBitmap(width, height) {
  return { width, height, pixels: new Uint8Array(width * height) };
}

function setPixel(bitmap, x, y) {
  // Clip points outside the bitmap rather than indexing out of bounds.
  if (x >= 0 && x < bitmap.width && y >= 0 && y < bitmap.height) {
    bitmap.pixels[y * bitmap.width + x] = 1;
  }
}

function drawCircle(bitmap, centerX, centerY, radius) {
  if (!Number.isInteger(radius) || radius < 0) {
    throw new RangeError('Radius must be a non-negative integer');
  }

  let x = radius;
  let y = 0;
  let decision = 1 - radius;

  while (x >= y) {
    // Reflect the current point into all eight octants.
    setPixel(bitmap, centerX + x, centerY + y);
    setPixel(bitmap, centerX + y, centerY + x);
    setPixel(bitmap, centerX - y, centerY + x);
    setPixel(bitmap, centerX - x, centerY + y);
    setPixel(bitmap, centerX - x, centerY - y);
    setPixel(bitmap, centerX - y, centerY - x);
    setPixel(bitmap, centerX + y, centerY - x);
    setPixel(bitmap, centerX + x, centerY - y);

    y += 1;
    if (decision < 0) {
      decision += 2 * y + 1;
    } else {
      x -= 1;
      decision += 2 * (y - x) + 1;
    }
  }
}

function printBitmap(bitmap) {
  for (let y = 0; y < bitmap.height; y += 1) {
    let row = '';
    for (let x = 0; x < bitmap.width; x += 1) {
      row += bitmap.pixels[y * bitmap.width + x] ? '#' : '.';
    }
    console.log(row);
  }
}

const bitmap = createBitmap(11, 11);
drawCircle(bitmap, 5, 5, 4);
printBitmap(bitmap);
  • The midpoint decision value chooses the next pixel while keeping the outline close to the ideal circle; symmetry avoids computing every point independently.
  • Complexity: O(r) plotted iterations, O(width × height) bitmap storage.
CodingMediumPure StorageSoftware Engineer

9. Valid Square (LeetCode)

Model answer

The task

Determine whether four 2D points can be the vertices of a square, in any input order. The square must have nonzero side length.

Key idea

Compare the six squared distances between all pairs of points. A square has four equal, positive side lengths and two equal diagonals, each with squared length twice that of a side.

Approach

  1. Compute the squared distance for each of the six point pairs.
  2. Sort the distances.
  3. Check that the four smallest are equal and positive.
  4. Check that the two largest are equal and twice the side’s squared length.
class Solution:
    def validSquare(
        self,
        p1: list[int],
        p2: list[int],
        p3: list[int],
        p4: list[int],
    ) -> bool:
        points = [p1, p2, p3, p4]
        distances = []

        # Squared distances avoid unnecessary square roots.
        for i in range(4):
            for j in range(i + 1, 4):
                dx = points[i][0] - points[j][0]
                dy = points[i][1] - points[j][1]
                distances.append(dx * dx + dy * dy)

        distances.sort()

        side_squared = distances[0]
        return (
            side_squared > 0
            and distances[1:4] == [side_squared] * 3
            and distances[4] == distances[5] == 2 * side_squared
        )

Complexity:

  • Time: O(1), since there are always six pairwise distances.
  • Space: O(1), for the fixed-size list of distances.

Common follow-ups

  • Why use squared distances? They preserve equality and avoid floating-point operations.
  • How would this change for decimal coordinates? Use a small tolerance when comparing distances.
  • How can you avoid sorting? Count the six squared distances and verify the required multiplicities and values.
CodingMediumPure StorageSoftware EngineerOnline assessment

10. How would you implement a mutex using spinlocks and flags?

Model answer

A spinlock can use a shared integer flag: 0 means unlocked and 1 means locked. Acquire it with an atomic compare-and-swap so only one thread can change 0 to 1; release it by atomically storing 0.

class SpinMutex {
  constructor(sharedBuffer = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)) {
    // Share this buffer with every worker that must use the same mutex.
    this.flag = new Int32Array(sharedBuffer);
  }

  lock() {
    // Keep spinning until this thread changes the flag from 0 to 1.
    while (Atomics.compareExchange(this.flag, 0, 0, 1) !== 0) {
      // Busy-wait: appropriate only for very short critical sections.
    }
  }

  tryLock() {
    return Atomics.compareExchange(this.flag, 0, 0, 1) === 0;
  }

  unlock() {
    // The caller must own the lock before releasing it.
    Atomics.store(this.flag, 0, 0);
  }

  withLock(callback) {
    this.lock();
    try {
      return callback();
    } finally {
      this.unlock();
    }
  }
}

// In real concurrent use, pass the same SharedArrayBuffer to worker threads.
const mutex = new SpinMutex();
mutex.withLock(() => {
  // Access shared state here.
});
  • compareExchange makes the check-and-set atomic; ordinary reads and writes would allow two threads to acquire the lock at once.
  • JavaScript Atomics operations provide sequentially consistent ordering. A spinlock can waste CPU and does not guarantee fairness, so I would use it only for short critical sections where blocking is more expensive.
CodingMediumPure StorageSoftware EngineerOnline assessment

11. How would you find the least common ancestor in a binary tree?

Model answer

For a general binary tree, I’d use a post-order traversal. Each subtree reports whether it contains either target; the first node whose combined result contains both is the least common ancestor. I’ll assume nodes are identified by object reference and return null if either target is absent.

// Each node has the shape { value, left, right }.
function lowestCommonAncestor(root, p, q) {
  // Handle the case where both requested targets are the same node.
  const targetMask = p === q ? 3 : 0;

  function visit(node) {
    if (node === null) {
      return { mask: 0, ancestor: null };
    }

    const left = visit(node.left);
    const right = visit(node.right);

    // Propagate an ancestor already found deeper in the tree.
    if (left.ancestor !== null) return left;
    if (right.ancestor !== null) return right;

    let mask = left.mask | right.mask;
    if (node === p) mask |= 1;
    if (node === q) mask |= 2;

    // This is the lowest node whose subtree contains both targets.
    const ancestor = mask === 3 ? node : null;
    return { mask, ancestor };
  }

  const result = visit(root);
  return result.mask === 3 ? result.ancestor : null;
}
  • The bitmask records whether the subtree contains p, q, or both; checking the final mask ensures both nodes are actually in the tree.
  • Complexity: O(n) time and O(h) recursion space, where n is the number of nodes and h is tree height.
CodingHardPure StorageSoftware Engineer

12. Design Skiplist (LeetCode)

Model answer

The task

Build a skip list that supports searching for a value, inserting a value, and removing one occurrence of a value. Searches and removals report whether the value was present.

Key idea

Each node has forward links at several levels. Higher levels skip over more nodes, making searches and updates take expected logarithmic time. Choose each new node’s height randomly, with each additional level having probability one half.

Approach

  1. Keep a head sentinel with links for the maximum supported number of levels.
  2. For search, start at the highest active level and move forward while the next value is smaller than the target; then check the next node.
  3. For insertion, record the predecessor at each level, choose a random height, and splice the new node into those levels.
  4. For removal, find the predecessors the same way, unlink the first matching node, and lower the active height if top levels become empty.
  5. Allow duplicate values; each removal deletes only one occurrence.
import random

class _Node:
    def __init__(self, value, height):
        self.value = value
        self.forward = [None] * height

class Skiplist:
    MAX_LEVEL = 32

    def __init__(self):
        self.head = _Node(0, self.MAX_LEVEL)
        self.level = 1

    def _predecessors(self, value):
        """Return the nearest node before value at each active level."""
        update = [self.head] * self.MAX_LEVEL
        current = self.head

        for level in range(self.level - 1, -1, -1):
            while (
                current.forward[level] is not None
                and current.forward[level].value < value
            ):
                current = current.forward[level]
            update[level] = current

        return update

    def search(self, target: int) -> bool:
        update = self._predecessors(target)
        candidate = update[0].forward[0]
        return candidate is not None and candidate.value == target

    def add(self, num: int) -> None:
        update = self._predecessors(num)

        # Geometrically distributed height: each extra level has probability 1/2.
        height = 1
        while height < self.MAX_LEVEL and random.random() < 0.5:
            height += 1

        if height > self.level:
            for level in range(self.level, height):
                update[level] = self.head
            self.level = height

        node = _Node(num, height)
        for level in range(height):
            node.forward[level] = update[level].forward[level]
            update[level].forward[level] = node

    def erase(self, num: int) -> bool:
        update = self._predecessors(num)
        candidate = update[0].forward[0]

        if candidate is None or candidate.value != num:
            return False

        for level in range(len(candidate.forward)):
            update[level].forward[level] = candidate.forward[level]

        while self.level > 1 and self.head.forward[self.level - 1] is None:
            self.level -= 1

        return True

Complexity:

  • Time: O(log n) expected per operation; O(n) worst case with an unlucky level distribution.
  • Space: O(n) expected for nodes and their forward links.

Common follow-ups

  • How would you make height selection deterministic? Use a fixed seed for reproducible tests.
  • What if duplicates are forbidden? Check for the value before inserting.
  • How does the structure compare with a balanced search tree? Both offer expected or guaranteed logarithmic operations, but skip lists are often simpler to implement and easier to modify concurrently.
TechnicalEasyPure StorageSoftware EngineerOnline assessment

13. How do virtual functions work?

Model answer

In C++, a virtual function enables runtime polymorphism: a call through a base-class pointer or reference can invoke the derived class’s override.

  1. A class with virtual functions typically has a vtable, a table of function pointers for its virtual methods. Each object typically stores a hidden vptr pointing to its class’s vtable. These are common implementation details, not requirements of the C++ standard.
  2. When the compiler sees a call such as basePtr->draw(), it emits an indirect call through the object’s vptr rather than selecting the function solely from the pointer’s static type.
  3. The actual object’s vtable selects the override. Thus, if basePtr points to a Circle, Circle::draw() runs even though the pointer type is Shape*.
  4. override is useful because it asks the compiler to verify that a derived method really overrides a base virtual method. A pure virtual function (= 0) makes the class abstract.
struct Shape {
    virtual void draw() const = 0;
    virtual ~Shape() = default;
};

struct Circle : Shape {
    void draw() const override { /* draw a circle */ }
};

Shape* shape = new Circle();
shape->draw();  // Calls Circle::draw()
delete shape;   // Safe because the base destructor is virtual.

The virtual call has a small indirect-dispatch cost and can inhibit some optimizations, though compilers can sometimes devirtualize calls when the concrete type is known. Virtual dispatch applies to calls through pointers or references; calls made during construction and destruction have special rules and do not dispatch to a not-yet-constructed or already-destroyed derived part.

TechnicalEasyPure StorageSoftware EngineerOnline assessment

14. Which decimal numbers can be represented exactly in binary floating point?

Model answer

A rational number has a finite binary expansion exactly when, after reducing the fraction, its denominator is a power of two.

For example:

  • 1/2 = 0.1₂ and 3/8 = 0.011₂ are exact.
  • 1/10 is not exact: its reduced denominator contains a factor of 5, so its binary expansion repeats.
  • Integers are exact as real binary values, but a finite-precision format can represent only integers whose significant bits fit its precision (and whose exponent is in range).

For a decimal value written as m / 10ᵏ, reduce the fraction. Since 10ᵏ = 2ᵏ × 5ᵏ, the value is exactly representable with a finite binary expansion only if all factors of 5 cancel from the numerator, leaving a denominator that is a power of two.

There is one additional constraint in actual floating-point formats: the significand and exponent must fit the format. IEEE 754 binary64 has 53 bits of significand precision, so a value can have a terminating binary expansion but still be rounded if it needs more than 53 significant bits or is outside the representable exponent range.

TechnicalMediumPure StorageSoftware EngineerOnline assessment

15. How would you check whether locks are valid, including whether each is acquired only once and acquired in order?

Model answer

I’d first clarify the rule being validated. A common lock-ordering discipline assigns each lock a unique rank and requires a thread to acquire locks in strictly increasing rank order. I’d validate each thread’s event trace independently, while also checking that every release matches a currently held lock.

  1. Track held locks and their ranks per thread. On acquire(L), reject an unknown lock or one already held. If any locks are held, require rank(L) > max(rank of held locks). This allows acquiring a lower-ranked lock after all higher-ranked locks have been released.
  2. Track acquisition history if required. If “acquired only once” literally means a lock may be acquired at most once in the entire trace, maintain an acquiredEver set and reject a second acquisition even after release. That is stricter than typical mutex semantics; normally, reacquisition after release is valid, while recursive acquisition before release is not.
  3. Validate releases. Reject release of a lock that is not held. Remove it from the held set. If the system requires nested, stack-like locking, additionally require releases in reverse acquisition order; that is a separate policy from increasing-rank acquisition.
  4. Check completion. At the end of a trace, report any locks still held if the trace is expected to be balanced.
flowchart TD
    A[Read thread event] --> B{Acquire or release?}
    B -- Acquire --> C{Already held?}
    C -- Yes --> X[Reject duplicate held acquisition]
    C -- No --> D{Rank higher than held locks?}
    D -- No --> Y[Reject order violation]
    D -- Yes --> E[Record lock as held]
    B -- Release --> F{Lock currently held?}
    F -- No --> Z[Reject unmatched release]
    F -- Yes --> G[Remove lock from held set]
    E --> H{More events?}
    G --> H
    H -- Yes --> A
    H -- No --> I[Check required end state]
Diagram
TechnicalMediumPure StorageSoftware Engineer

16. How would you determine a counter's value in the presence of race conditions?

Model answer

First I’d clarify what “the value” means: the value at one instant, a consistent snapshot, or an approximate monitoring value. For a shared in-process counter, I’d use an atomic increment and atomic read rather than a plain integer; otherwise concurrent reads and writes are a data race.

  1. Make each update indivisible. Use an atomic fetch_add (or a lock-protected increment). Each increment then has a single linearization point, so concurrent updates are not lost.
  2. Read using the same synchronization model. An atomic load gives a race-free value that corresponds to a point in the operation order. If the counter must agree with other fields, protect and read those fields under the same lock or use a versioned snapshot; an atomic counter alone does not make a multi-field invariant consistent.
  3. Choose memory ordering deliberately. If the counter is only a count, relaxed atomic operations are often enough for correctness of the count. If observing the count must also imply visibility of other data, use a lock or appropriate acquire/release synchronization.
  4. For a distributed counter, define consistency explicitly. A single leader with replicated writes can provide a linearizable value at higher coordination cost. Sharded or eventually consistent counters scale better, but a read may be stale or combine updates from different times.
flowchart TD
    W1["Writer 1"] --> A["Atomic counter"]
    W2["Writer 2"] --> A
    A --> R["Atomic read"]
    R --> S["Value at a linearization point"]
Diagram

I’d also check overflow and whether the read path can tolerate contention. For a telemetry-only counter, approximate or periodically aggregated values may be preferable; for a correctness-critical quantity, I’d require a clearly defined consistent read.

TechnicalMediumPure StorageSoftware EngineerOnline assessment

17. How would you check whether a binary search implementation is correct?

Model answer

I’d check binary search at three levels: its invariant, its boundary behavior, and its results against a simple reference implementation.

  1. State the contract. Confirm the input is sorted, whether the search returns any matching index or the first matching index, and what it returns when the target is absent. Many apparent bugs are contract mismatches.
  2. Review the invariant. For a half-open interval [lo, hi), the candidate answer must remain inside that interval. Each iteration must shrink it, for example by setting hi = mid or lo = mid + 1. Calculate mid in a way that avoids overflow in fixed-width integer languages.
  3. Test boundaries and duplicates. Include an empty array, a one-element array, targets below and above the range, matches at either end, absent values between elements, and arrays with repeated values. Duplicates are especially important if the contract requires the first match.
  4. Use an oracle and properties. Generate sorted arrays and targets, compare the result with a straightforward linear search, and assert that any returned index is in range and contains the target. For a first-match contract, also assert that the preceding element is smaller.
  5. Check termination. Verify that every loop iteration strictly reduces hi - lo; this catches off-by-one errors that otherwise become infinite loops.
flowchart TD
    A[Define contract] --> B[Review interval invariant]
    B --> C[Test edge cases]
    C --> D[Compare with linear-search oracle]
    D --> E{All properties hold?}
    E -- No --> F[Inspect bounds and midpoint updates]
    F --> B
    E -- Yes --> G[Accept implementation]
Diagram
TechnicalHardPure StorageSoftware Engineer

18. Given two base classes and a class derived from both, how would you lay out the class instance's memory so polymorphism works correctly, assuming m…

The full question

Given two base classes and a class derived from both, how would you lay out the class instance's memory so polymorphism works correctly, assuming memory is a series of same-sized slots and methods and attributes each take one slot?

Model answer

I’d first clarify that real object layouts are ABI-specific. Also, in conventional implementations, methods are shared code rather than stored in every object; polymorphic objects typically store a dispatch pointer (or equivalent), and method slots live in a vtable. If the question’s “methods take one slot” is a strict toy-model assumption, those slots can be represented in the dispatch tables.

For a non-virtual multiple-inheritance example, lay out the object as two base subobjects followed by the derived portion:

Slot regionContents
Base 1 subobjectDispatch pointer for the Base1 view, then Base1 attributes
Base 2 subobjectDispatch pointer for the Base2 view, then Base2 attributes
Derived portionDerived attributes
flowchart LR
    S0["Base1 view: dispatch pointer"] --> S1["Base1 attributes"] --> S2["Base2 view: dispatch pointer"] --> S3["Base2 attributes"] --> S4["Derived attributes"]
    V1["Base1 method table"] -. "dispatches to overrides" .-> S0
    V2["Base2 method table"] -. "dispatches to overrides" .-> S2
Diagram
  1. Keep a dispatch view for each polymorphic base. A Base1* and a Base2* can point at different offsets within the same Derived object. Each view must find the correct method table and interpret its this pointer correctly.
  2. Preserve base-subobject layout. The Base1 and Base2 attributes remain in their respective subobjects; derived attributes follow them. A cast from Derived* to a base pointer applies the relevant offset. The compiler can use an adjustment thunk when an overridden method is called through a base pointer.
  3. Put method slots in dispatch tables. Keep a stable slot for each virtual method in each base’s table. If Derived overrides a method, its table entry points to the derived implementation (or a thunk that adjusts this). Under the literal toy assumption, these method entries occupy slots in the tables; storing function slots in every object would also work, but wastes space and is not the usual design.
  4. Handle diamonds explicitly. With non-virtual inheritance, two paths to the same ancestor produce two ancestor subobjects. With virtual inheritance, there is one shared ancestor, so the layout needs additional offset/lookup metadata to find it.

The key correctness property is that every base-class view reaches the right implementation with the right object offset—not that all methods appear only once in a simple linear list. The concrete offsets and dispatch-pointer count depend on the language ABI and inheritance features.

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