Tower Research Capital interview questions & answers

19 real Tower Research Capital interview questions with full model answers — System design, Coding, Technical. Drawn from the same verified bank ChannelPulse drills from (19 Tower Research Capital questions in total).

CodingMediumTower Research CapitalSoftware Engineer

1. Evaluate Division (LeetCode)

Model answer

The task

Given equations that define ratios between variables, answer queries asking for a ratio between two variables. Return -1.0 when the ratio cannot be determined.

Key idea

Represent each equation as two directed graph edges: from a to b with weight a / b, and from b to a with the reciprocal weight. A path’s edge weights multiply to give the ratio between its endpoints.

Approach

  1. Build a weighted adjacency list from the equations.
  2. For each query, return -1.0 if either variable is unknown.
  3. Otherwise, use DFS to find a path between the variables, multiplying edge weights along the way.
  4. Track visited variables so cycles do not cause repeated exploration.
  5. If the variables are the same and known, the ratio is 1.0.
from collections import defaultdict
from typing import List

class Solution:
    def calcEquation(
        self,
        equations: List[List[str]],
        values: List[float],
        queries: List[List[str]]
    ) -> List[float]:
        graph = defaultdict(list)

        for (numerator, denominator), value in zip(equations, values):
            graph[numerator].append((denominator, value))
            graph[denominator].append((numerator, 1.0 / value))

        def find_ratio(start: str, target: str) -> float:
            if start not in graph or target not in graph:
                return -1.0
            if start == target:
                return 1.0

            stack = [(start, 1.0)]
            visited = {start}

            while stack:
                variable, product = stack.pop()

                for neighbor, edge_value in graph[variable]:
                    if neighbor in visited:
                        continue

                    next_product = product * edge_value
                    if neighbor == target:
                        return next_product

                    visited.add(neighbor)
                    stack.append((neighbor, next_product))

            return -1.0

        return [find_ratio(a, b) for a, b in queries]

Complexity:

  • Time: O(Q(V + E)), where each query may traverse the full graph.
  • Space: O(V + E) for the graph and the DFS state.

Common follow-ups

  • How can repeated queries be sped up? Use weighted union-find to answer each query in near-constant time after preprocessing.
  • How would you handle inconsistent equations? Detect conflicting ratios when connecting variables or revisiting an already-connected pair.
  • What if the graph is very large but queries are few? Keep DFS/BFS per query to avoid more elaborate preprocessing.
CodingMediumTower Research CapitalSoftware Engineer

2. Shortest Bridge (LeetCode)

Model answer

The task

Given a binary grid containing two islands, find the fewest water cells that must be flipped to connect them.

Key idea

Mark every cell in one island, then expand outward from all its cells at once using BFS. The first time the search reaches the other island, the BFS distance is the minimum number of water cells to flip.

Approach

  1. Find any land cell and use iterative DFS to mark its entire island.
  2. Add all cells of that island to a BFS queue.
  3. Expand the queue one layer at a time, marking water cells as visited when enqueuing them.
  4. If a neighbor belongs to the other island, return the current layer’s distance.
from collections import deque
from typing import List

class Solution:
    def shortestBridge(self, grid: List[List[int]]) -> int:
        n = len(grid)
        start = None

        # Find a cell in the first island.
        for r in range(n):
            for c in range(n):
                if grid[r][c] == 1:
                    start = (r, c)
                    break
            if start is not None:
                break

        # Mark the first island and collect all its cells.
        queue = deque()
        stack = [start]
        grid[start[0]][start[1]] = 2
        queue.append(start)

        directions = ((1, 0), (-1, 0), (0, 1), (0, -1))

        while stack:
            r, c = stack.pop()
            for dr, dc in directions:
                nr, nc = r + dr, c + dc
                if (0 <= nr < n and 0 <= nc < n
                        and grid[nr][nc] == 1):
                    grid[nr][nc] = 2
                    stack.append((nr, nc))
                    queue.append((nr, nc))

        # Expand from the first island until reaching the second.
        flips = 0
        while queue:
            for _ in range(len(queue)):
                r, c = queue.popleft()
                for dr, dc in directions:
                    nr, nc = r + dr, c + dc
                    if 0 <= nr < n and 0 <= nc < n:
                        if grid[nr][nc] == 1:
                            return flips
                        if grid[nr][nc] == 0:
                            grid[nr][nc] = 2
                            queue.append((nr, nc))
            flips += 1

        return -1

Complexity:

  • Time: O(n²), since each grid cell is visited at most once.
  • Space: O(n²), for the DFS stack and BFS queue in the worst case.

Common follow-ups

  • What if there are more than two islands? Find components first, then consider multi-source expansion or a graph-based approach.
  • Can the grid remain unchanged? Keep a separate visited matrix instead of marking cells in the grid.
  • Why mark water when enqueuing? It prevents the same cell from being added to the queue multiple times.
CodingMediumTower Research CapitalSoftware Engineer

3. Using a Robot to Print the Lexicographically Smallest String (LeetCode)

Model answer

The task

Reorder a string using a robot that can move characters from the input into a holding area and emit characters from that area. Choose when to emit so the final string is lexicographically smallest.

Key idea

Keep the holding area as a stack and track the smallest character still unread. Emit from the stack whenever its top is no greater than that smallest unread character: waiting cannot produce a better next character.

Approach

  1. Count how many times each lowercase letter appears in the input.
  2. Scan the input from left to right, pushing each character onto the stack and updating its remaining count.
  3. Advance a pointer to the smallest letter that still appears in the unread suffix.
  4. While the stack top is no greater than that letter, pop it into the result.
  5. Once the input is exhausted, emit everything left in the stack.
class Solution:
    def robotWithString(self, s: str) -> str:
        # Count characters that have not yet been read.
        remaining = [0] * 26
        for ch in s:
            remaining[ord(ch) - ord("a")] += 1

        stack = []
        result = []
        smallest = 0

        for ch in s:
            stack.append(ch)

            # This character is now in the stack, not the unread suffix.
            remaining[ord(ch) - ord("a")] -= 1

            while smallest < 26 and remaining[smallest] == 0:
                smallest += 1

            # No unread character can improve on the stack's top.
            while stack and (
                smallest == 26
                or stack[-1] <= chr(ord("a") + smallest)
            ):
                result.append(stack.pop())

        return "".join(result)

Complexity:

  • Time: O(n + Σ), where n is the string length and Σ is the alphabet size.
  • Space: O(n + Σ) for the stack, result, and character counts.

Common follow-ups

  • What if the alphabet is not fixed? Use a frequency map and an ordered structure to track the smallest remaining character.
  • Can the input be processed as a stream? Yes, if characters arrive in order; keep the stack, counts for available input, and result state.
  • Why is the comparison inclusive? If the stack top equals the smallest unread character, emitting it now is just as good as waiting, so it can be safely emitted.
CodingMediumTower Research CapitalSoftware EngineerSecond Round

4. Given a list of numbers, find the first number in the range from 1 to the maximum list value that cannot be formed by summing any subset of the list.

Model answer

Assume the list contains positive integers and each element can be used at most once. I sort the values and maintain reachable, the largest value such that every positive integer through it can be formed from the values processed so far.

function firstUnformableInRange(numbers) {
  if (numbers.length === 0) return null;

  const maxValue = Math.max(...numbers);
  const sorted = [...numbers].sort((a, b) => a - b);
  let reachable = 0;

  for (const value of sorted) {
    // A gap at reachable + 1 cannot be bridged by this or later values.
    if (value > reachable + 1) break;
    reachable += value;
  }

  const smallestMissing = reachable + 1;
  return smallestMissing <= maxValue ? smallestMissing : null;
}

console.log(firstUnformableInRange([1, 2, 5])); // 4
console.log(firstUnformableInRange([1, 2, 3])); // null
  • If the next value is at most reachable + 1, it extends the contiguous formable range to reachable + value.
  • If it is larger, reachable + 1 cannot be formed: all available values are either too small in total or individually too large to make that gap.
  • Return null when every number from 1 through the list maximum is formable.

Complexity: O(n log n) time for sorting and O(n) extra space for the sorted copy.

CodingMediumTower Research CapitalSoftware EngineerFirst Round

5. Find the Town Judge in a single pass over an adjacency matrix.

Model answer

function findJudge(trust) {
  const n = trust.length;
  const score = new Array(n).fill(0);

  // One scan of the adjacency matrix: trusting costs one point,
  // being trusted earns one point.
  for (let from = 0; from < n; from++) {
    for (let to = 0; to < n; to++) {
      if (trust[from][to]) {
        score[from]--;
        score[to]++;
      }
    }
  }

  // With n people, the judge's net score is n - 1.
  for (let person = 0; person < n; person++) {
    if (score[person] === n - 1) return person + 1; // People are labeled 1..n.
  }

  return -1;
}
  • Each trust edge decreases the truster's score and increases the trusted person's score. A judge has no outgoing edges and n - 1 incoming edges, so their score is n - 1.
  • The matrix is scanned once; the final scan checks the candidate scores. For n = 1, the sole person is correctly returned.

Complexity: Time O(n²); space O(n).

CodingHardTower Research CapitalSoftware Engineer

6. Minimum Number of Taps to Open to Water a Garden (LeetCode)

Model answer

The task

Each tap waters a contiguous interval of the garden. Find the fewest taps whose intervals cover the entire garden, or return -1 if that cannot be done.

Key idea

Treat each tap as an interval and group intervals by their left endpoint. Then use the greedy strategy for covering a line: among intervals reachable with the taps chosen so far, extend coverage as far as possible.

Approach

  1. Convert each tap into a clamped interval [left, right].
  2. For each left, store the farthest right any tap starting there can reach.
  3. Sweep from left to right, tracking the current coverage boundary and the farthest boundary reachable.
  4. Whenever the sweep reaches the current boundary, choose another tap to extend coverage.
  5. If no tap extends coverage, return -1.
class Solution:
    def minTaps(self, n: int, ranges: list[int]) -> int:
        if n == 0:
            return 0

        # farthest[left] is the furthest right endpoint of any
        # tap interval whose left endpoint is left.
        farthest = [0] * (n + 1)

        for i, radius in enumerate(ranges):
            left = max(0, i - radius)
            right = min(n, i + radius)
            farthest[left] = max(farthest[left], right)

        taps = 0
        current_end = 0
        next_end = 0

        for position in range(n):
            next_end = max(next_end, farthest[position])

            # A new tap is needed to extend coverage.
            if position == current_end:
                if next_end == current_end:
                    return -1

                taps += 1
                current_end = next_end

                if current_end >= n:
                    return taps

        return -1

Complexity:

  • Time: O(n), for building intervals and scanning positions.
  • Space: O(n), for the farthest-reach array.

Common follow-ups

  • How can the chosen taps be returned? Store the tap index that provides each farthest reach and record the choices during the sweep.
  • How would you solve it with dynamic programming? Set dp[x] to the minimum taps needed to cover through position x, relaxing each interval’s reachable range.
  • What if taps can be added or removed between queries? Use an interval data structure, such as a segment tree, to update and query reach efficiently.
System designMediumTower Research CapitalSoftware EngineerFirst Round

7. Design a list-like data structure that supports insertion, deletion, and searching at specific indices in O(√n) time.

Model answer

1. Requirements & scale

  • Support get(index), insert(index, value), and delete(index) on a sequence; optionally expose size() and append.
  • Preserve sequence order and define valid indices explicitly: get/delete require 0 <= index < n; insert allows 0 <= index <= n.
  • Target O(√n) time per positional operation, with O(n) storage. Assume an in-memory, single-process structure; concurrent access can be protected by a read/write lock.
  • The key trade-off is avoiding a single contiguous array: its shifts make insert and delete O(n).

For n = 1,000,000, choose block size B ≈ √n = 1,000. There are about 1,000 blocks. Scanning to a block and shifting within it each take about 1,000 steps, rather than one million.

2. High-level architecture

The core is an ordered sequence of bounded-size arrays, with a small directory of block lengths. For a local library, the service tiers below are simply the call path; persistence and workers are optional if this structure is embedded in a service.

flowchart TD
  subgraph Client
    C["Caller"]
  end
  subgraph Edge["Edge / VFS"]
    E["Input validation"]
  end
  subgraph LB["Load Balancer"]
    L["In-process dispatch"]
  end
  subgraph API["API / Services"]
    A["Indexed sequence API"]
    I["Block locator"]
  end
  subgraph Cache["Cache"]
    B["Hot block references"]
  end
  subgraph Datastores["Datastores"]
    D["Ordered blocks"]
    M["Block lengths"]
  end
  subgraph MQ["Message Queue"]
    Q["Optional change log"]
  end
  subgraph Workers
    W["Optional persistence worker"]
  end
  C -->|"index operation"| E
  E -->|"validated request"| L
  L -->|"method call"| A
  A -->|"locate block"| I
  I -->|"block ordinal"| M
  I -->|"read or update"| D
  A -->|"reuse reference"| B
  A -.->|"durable change"| Q
  Q -.->|"persist snapshot"| W
Diagram

3. API design

  • get(index) -> value: locate the containing block and offset; reject out-of-range indices.
  • insert(index, value) -> void: insert before the element at index, or append when index == size.
  • delete(index) -> value: remove and return the element at index.
  • size() -> integer: return the maintained total count.

4. Data model & storage

  • Store blocks: Array<Block>, where each block is a dynamic array of values, plus lengths[i] and a total n.
  • Keep ordinary blocks near B elements; split a block when it exceeds 2B, and merge or redistribute with a neighbor when one falls below roughly B/2.
  • lengths can be scanned linearly to locate a block. A Fenwick tree over block lengths is an optional optimization, but is not needed for the target bound.
  • If durability is required, persist snapshots or append mutations to a log; persistence is separate from the in-memory complexity guarantee.

5. Deep dive

To locate index k, subtract each block length in order until the remaining offset is smaller than the current block's length. Since blocks contain Θ(B) values, the scan touches O(n/B) blocks. Inside the selected array, an insertion or deletion shifts at most O(B) values. Thus each operation costs O(n/B + B); choosing B = Θ(√n) gives O(√n).

On insertion, insert into the selected block. If it exceeds 2B, split it around its midpoint and insert the new block and lengths into the directory. On deletion, remove the value; if the block is too small, redistribute with an adjacent block or merge them. These local repairs cost O(B) and keep block sizes bounded, so the number of blocks remains O(n/B).

sequenceDiagram
  participant C as Caller
  participant S as Sequence
  participant D as Block directory
  participant B as Target block
  C->>S: insert(index, value)
  S->>D: locate index using block lengths
  D-->>S: block and local offset
  S->>B: shift suffix and insert
  alt block exceeds capacity
    S->>B: split around midpoint
    S->>D: add block and update lengths
  end
  S-->>C: success
Diagram

If n changes substantially, update the target block size. A full rebuild can be amortized across a growth or shrinkage phase, but may make that particular operation O(n); a strict worst-case guarantee across resizes requires incremental rebuilding or a fixed capacity bound. For a conventional interview design, state the bound as O(√n) amortized with local splits and merges.

6. Scale, bottlenecks & trade-offs

  • Complexity: get, insert, and delete are O(√n) with B = Θ(√n); storage is O(n). size() is O(1).
  • Bottleneck: directory scanning contributes O(n/B); shifting within a block contributes O(B). A Fenwick tree reduces block lookup to O(log(n/B)), but adds update complexity and is unnecessary for the stated target.
  • Trade-off: smaller blocks reduce shifts but increase directory scanning; larger blocks do the reverse. Recompute B periodically or select it from expected capacity.
  • Concurrency: serialize mutations with a write lock; reads can share a read lock. Fine-grained locking is possible but complicates splits and index consistency.
System designMediumTower Research CapitalSoftware EngineerThird Round

8. Design a simple online book-publishing system, including its database schemas, service classes, and relevant endpoints.

Model answer

1. Requirements & scale

Functional requirements

  • Authors can create and edit book drafts, upload a manuscript and cover, submit for review, and publish or withdraw a title.
  • Readers can browse, search, and view published book metadata and sample content.
  • Editors can review submissions and record approval or rejection with a reason.

Non-functional requirements

  • Enforce author ownership and publication-state rules; retain revision history and an audit trail.
  • Serve public catalog reads quickly, while keeping draft content private. Publishing must not expose a partially uploaded or unapproved book.
  • Keep the initial design simple: relational metadata, object storage for files, and a search index for discovery.

Estimates: Assume 100,000 authors, 1 million titles, and 10 million monthly readers. At 20 catalog requests per active reader per month, that is about 77 requests/s on average; design for 2,000 requests/s at peak. If a title averages 200 KB of metadata and cover assets, that is roughly 200 GB before replicas; 1 MB manuscript files per title add about 1 TB, best stored as blobs. A peak of 100 uploads/s at 10 MB/s each would require 1 GB/s ingress, so clients upload directly to object storage rather than through application servers.

2. High-level architecture

flowchart TD
  subgraph Client
    C["Author and reader apps"]
  end
  subgraph Edge["Edge/CDN"]
    E["TLS, WAF, and public asset CDN"]
  end
  subgraph LB["Load Balancer"]
    L["Regional API load balancer"]
  end
  subgraph Services["API / Services"]
    A["API gateway"]
    B["Book service"]
    U["Upload service"]
    P["Publishing service"]
    S["Search service"]
  end
  subgraph Cache["Cache"]
    R["Published catalog cache"]
  end
  subgraph Stores["Datastores"]
    D["PostgreSQL metadata"]
    O["Object storage"]
    F["Search index"]
  end
  subgraph Queue["Message Queue"]
    Q["Publication and indexing events"]
  end
  subgraph Workers["Workers"]
    W["Validation and indexing workers"]
  end
  C -->|"HTTPS API requests"| E
  E -->|"API traffic"| L
  L -->|"authenticated request"| A
  A -->|"draft and catalog operations"| B
  A -->|"upload authorization"| U
  A -->|"submit or publish"| P
  A -->|"search query"| S
  B -->|"metadata reads and writes"| D
  B -->|"published reads"| R
  U -->|"signed upload URL"| C
  C -->|"manuscript and cover bytes"| O
  P -->|"state transition and outbox"| D
  P -->|"publication event"| Q
  Q -->|"index and validate"| W
  W -->|"fetch file metadata"| O
  W -->|"update search document"| F
  S -->|"search published titles"| F
  E -->|"cached public assets"| O
Diagram

3. API design

  • POST /v1/books — create a draft; returns book_id and revision number.
  • PATCH /v1/books/{book_id} — edit draft metadata with an If-Match revision to prevent lost updates.
  • POST /v1/books/{book_id}/uploads — request a presigned upload URL for a manuscript or cover.
  • POST /v1/books/{book_id}/submit — submit a complete draft for review.
  • POST /v1/books/{book_id}/review — editor approves or rejects with a reason.
  • POST /v1/books/{book_id}/publish — publish an approved book; idempotent with an idempotency key.
  • GET /v1/books/{book_id} — return a book only if the caller is its author/editor or the book is published.
  • GET /v1/catalog?query=&cursor= — search published titles using cursor pagination.
  • POST /v1/books/{book_id}/withdraw — remove a published title from the public catalog.

4. Data model & storage

Use PostgreSQL as the source of truth. Core tables:

  • authors(id, email, display_name, created_at).
  • books(id, author_id, title, description, language, status, current_revision, published_at, created_at, updated_at). Index (status, published_at) for public listings and (author_id, updated_at) for author dashboards.
  • book_revisions(book_id, revision, metadata_json, manuscript_key, cover_key, created_by, created_at), primary key (book_id, revision).
  • reviews(id, book_id, revision, editor_id, decision, reason, created_at).
  • outbox_events(id, aggregate_id, event_type, payload, created_at, delivered_at) for reliable async publication events.

Store manuscript and cover bytes in object storage under unguessable, versioned keys; keep buckets private and serve approved public covers through a CDN. The search index contains only published metadata and is rebuildable from PostgreSQL. Cache popular published book details, keyed by book ID and revision, and invalidate on publication or withdrawal.

5. Deep dive

Model the lifecycle explicitly: DRAFT -> IN_REVIEW -> APPROVED -> PUBLISHED, with rejection returning to DRAFT and withdrawal moving PUBLISHED -> WITHDRAWN. The publishing service validates ownership, review status, and that required file uploads completed. It performs a conditional SQL update and inserts an outbox event in the same transaction. A worker consumes that event idempotently to update the search index and invalidate cache. This avoids a distributed transaction between SQL and the search engine.

sequenceDiagram
  participant A as Author
  participant API as Book API
  participant DB as PostgreSQL
  participant O as Object storage
  participant Q as Event queue
  participant W as Index worker
  participant F as Search index
  A->>API: Request upload URL
  API-->>A: Presigned URL and object key
  A->>O: Upload manuscript and cover
  A->>API: Submit draft for review
  API->>O: Verify object keys and checksums
  API->>DB: Set IN_REVIEW and record revision
  API-->>A: Submission accepted
  Note over API,DB: Editor approval precedes publication
  API->>DB: Publish with outbox event in one transaction
  API->>Q: Deliver outbox event
  Q->>W: Publication event
  W->>F: Upsert published book document
Diagram

Use an object-store completion callback or a server-side HEAD check to ensure uploads are present and match expected size and checksum. Every worker operation is idempotent on (book_id, revision, event_type). Catalog reads filter by PUBLISHED; a search-index result is rechecked against publication status where stale visibility would be unacceptable.

6. Scale, bottlenecks & trade-offs

  • Start with one relational database and read replicas. If metadata growth or write volume requires sharding, shard by book_id; keep author dashboards queryable with an author index or a separate read model.
  • PostgreSQL is preferable for ownership, review, and state-transition invariants. Search is eventually consistent, so newly published titles may take seconds to appear; direct book pages can read from the database or cache.
  • Direct-to-object-store uploads avoid saturating API servers. Use short-lived presigned URLs, private buckets, malware scanning, file-size limits, and content-type validation. Failed uploads expire through lifecycle policies.
  • The outbox makes SQL state and event creation atomic, but delivery is at least once; workers must deduplicate. If indexing is delayed, publication remains committed and readers can still access the canonical published record.
  • Use optimistic revision checks for concurrent author edits. Return a conflict rather than silently overwriting changes. Cache only public data, and invalidate or version keys on withdrawal so a withdrawn book does not remain discoverable for long.
System designHardTower Research CapitalSoftware EngineerSecond Round

9. Using object-oriented principles, design a file system for a typical operating system so that operations such as list and delete work on both files…

The full question

Using object-oriented principles, design a file system for a typical operating system so that operations such as list and delete work on both files and folders.

Model answer

1. Requirements & scale

  • Provide a filesystem object model supporting path lookup, listing, file creation, and deletion of files or folders.
  • Use the same operations for different node types where possible, while enforcing type-specific behavior and permissions.
  • Assume a single host with a local filesystem. Correctness matters more than distributed availability: operations must preserve directory and inode consistency across failures.

For a host with 10 million filesystem objects, metadata may occupy a few gigabytes depending on names, indexes, and cached attributes. Directory listing should be proportional to the number of returned entries, O(k); path lookup is proportional to path depth with indexed directory lookup, approximately O(d) expected for hash-backed names.

2. High-level architecture

The design separates path-facing APIs from the virtual filesystem layer and concrete storage. A kernel can implement these components in-process; the diagram shows their logical boundaries. The load-balancer tier represents syscall dispatch, not a network load balancer.

flowchart TD
  subgraph Client
    P["Process"]
  end
  subgraph Edge["Edge / VFS"]
    V["Path and syscall interface"]
  end
  subgraph LB["Load Balancer"]
    L["Syscall dispatcher"]
  end
  subgraph API["API / Services"]
    R["Path resolver"]
    O["Filesystem operations"]
    D["Permission checks"]
  end
  subgraph Cache["Cache"]
    C["Dentry and page cache"]
  end
  subgraph Datastores["Datastores"]
    I["Inodes and directory entries"]
    B["File data blocks"]
  end
  subgraph MQ["Message Queue"]
    J["Write-ahead journal"]
  end
  subgraph Workers
    W["Writeback and cleanup"]
  end
  P -->|"open list unlink"| V
  V -->|"system call"| L
  L -->|"operation request"| R
  R -->|"resolved nodes"| O
  O -->|"authorize"| D
  R <-->|"lookup metadata"| C
  O -->|"metadata changes"| I
  O -->|"file contents"| B
  O -->|"transaction records"| J
  J -->|"replay or commit"| I
  J -.->|"deferred cleanup"| W
Diagram

3. API design

  • resolve(path, followSymlinks=true) -> Node: resolve a normalized absolute or relative path.
  • list(path) -> EntryInfo[]: return the immediate children of a directory; fail with NotDirectory for a file.
  • createFile(parentPath, name, mode) -> File: create a file in a directory.
  • createDirectory(parentPath, name, mode) -> Directory: create a directory.
  • delete(path, recursive=false) -> void: unlink a file or remove a directory; reject a non-empty directory unless recursive deletion is requested.

4. Data model & storage

Use a composite object model: abstract Node holds inode ID, name, owner, permissions, timestamps, and a parent reference. File adds size and block mappings; Directory owns a name-to-child-entry index; SymbolicLink stores a target path. Operations such as list and delete are exposed through a filesystem service, which dispatches by node type rather than requiring callers to inspect implementation details.

On disk, separate stable inode records from directory entries. A directory entry maps (parent_inode, name) to a child inode ID; file data is stored in blocks addressed by the file inode. Use an inode ID as identity, not a path, because renames change paths. The directory index is keyed by parent inode and name. A dentry cache accelerates repeated path lookups, and a page cache stores frequently accessed file data.

5. Deep dive

Path resolution starts at the root (or the process working directory for relative paths), splits the path into components, and looks up each name in the current directory. At each step, check execute/search permission on the directory. The result includes the resolved node and its parent directory, which is needed for deletion. Normalize . and .. carefully; follow symbolic links with a depth limit and cycle detection.

Deletion is an unlink operation, not immediate object destruction. Under a lock on the parent directory, verify permissions and the node type, then remove the directory entry transactionally. A directory may be removed only if empty, unless recursive deletion was explicitly requested. Recursive deletion walks children post-order, removing each child before its parent. The inode and blocks are reclaimed only after the link count reaches zero and no process still has the file open; this preserves Unix-style behavior where an unlinked open file remains usable.

sequenceDiagram
  participant U as User process
  participant V as VFS
  participant R as Resolver
  participant D as Parent directory
  participant J as Journal
  participant I as Inode store
  U->>V: delete(path)
  V->>R: resolve parent and final name
  R-->>V: parent directory and child inode
  V->>D: lock and check permissions/type
  D-->>V: entry found
  V->>J: begin unlink transaction
  V->>D: remove name to inode entry
  V->>I: decrement link count
  V->>J: commit transaction
  V-->>U: success
Diagram

6. Scale, bottlenecks & trade-offs

  • Consistency and recovery: protect directory mutations with locks and use a journal or copy-on-write metadata so a crash cannot leave a half-applied unlink. Replay committed journal records during mount.
  • Concurrency: lock parent directories for create, rename, and unlink; define a global lock ordering for operations involving multiple directories. Reads can use cached dentries, invalidated on mutation.
  • Deletion cost: deleting a file is near O(1) metadata work plus eventual block reclamation. Listing is O(k) for k entries. Recursive folder deletion is O(m) in the number of descendants and should be cancellable or performed incrementally for very large trees.
  • Object-oriented trade-off: polymorphic node types make behavior extensible, but persistent inode records should remain a stable storage format rather than serialized language objects. The VFS abstraction lets different backing filesystems implement the same operations.
  • Failure modes: handle permission denial, missing paths, type mismatches, non-empty directories, disk-full conditions, and interrupted recursive deletion explicitly; journal recovery and idempotent cleanup make retries safe.
System designHardTower Research CapitalSoftware EngineerThird Round

10. Design a system to handle user authentication using JWTs.

Model answer

1. Requirements & scale

Functional requirements

  • Register users, authenticate with passwords and optional MFA, issue and refresh tokens, and support logout and account disablement.
  • Let services verify identity and permissions without a database lookup on every request.
  • Support signing-key rotation and a way to revoke refresh-token sessions.

Non-functional requirements

  • Keep credential material protected; use TLS, password hashing, rate limits, and auditable security events.
  • Make token verification highly available and low-latency. For sensitive actions, support stronger revocation checks than ordinary reads.
  • Avoid embedding secrets or mutable authorization data in tokens.

Estimates: Assume 5 million monthly users, 1 million daily users, and 100,000 logins or refreshes per day. At a 20× peak, the identity APIs handle about 25 requests/s; if downstream services verify 20,000 JWTs/s, each service verifies locally. At roughly 1 KB per token, that is about 20 MB/s of token traffic. Five million refresh-session records at 300 bytes each are about 1.5 GB before indexes and replication.

2. High-level architecture

flowchart TD
  subgraph Client
    C["Web and mobile clients"]
  end
  subgraph Edge["Edge/CDN"]
    E["TLS termination and WAF"]
  end
  subgraph LB["Load Balancer"]
    L["Regional API load balancer"]
  end
  subgraph Services["API / Services"]
    A["Identity API"]
    R["Resource APIs"]
    K["JWKS endpoint"]
  end
  subgraph Cache["Cache"]
    X["Rate-limit counters"]
    J["Local JWKS cache"]
  end
  subgraph Stores["Datastores"]
    D["User and session SQL database"]
    M["KMS signing keys"]
  end
  subgraph Queue["Message Queue"]
    Q["Security event stream"]
  end
  subgraph Workers["Workers"]
    W["Audit and notification worker"]
  end
  C -->|"HTTPS credentials or bearer token"| E
  E -->|"filtered request"| L
  L -->|"login or refresh"| A
  L -->|"application request"| R
  A -->|"rate-limit check"| X
  A -->|"users and refresh sessions"| D
  A -->|"sign or rotate key"| M
  A -->|"publish public keys"| K
  K -->|"JWKS response"| J
  R -->|"verify JWT locally"| J
  A -->|"security event"| Q
  Q -->|"audit records"| W
Diagram

3. API design

  • POST /v1/auth/register — create an account; return a verification challenge, not an authenticated session by default.
  • POST /v1/auth/login — validate credentials and MFA; return a short-lived access JWT and a refresh token in a secure, HttpOnly cookie.
  • POST /v1/auth/refresh — rotate the refresh token and issue a new access JWT.
  • POST /v1/auth/logout — revoke the current refresh-token family and clear the cookie.
  • POST /v1/auth/logout-all — revoke all sessions for the authenticated user.
  • GET /.well-known/jwks.json — expose active and retiring public signing keys.
  • Resource APIs accept Authorization: Bearer <JWT> and enforce audience and scope.

4. Data model & storage

Use PostgreSQL for identity and session state, with encrypted backups and a unique index on normalized email. users(id, email, password_hash, status, auth_version, created_at) stores the account; passwords use Argon2id with per-user salts. refresh_sessions(id, user_id, token_hash, family_id, expires_at, revoked_at, replaced_by, created_at) stores only a hash of each high-entropy refresh token. Index by user_id and family_id; partition by creation month only if volume warrants it. Store signing keys in a KMS/HSM, never in the application database. Cache rate-limit counters in a shared cache; publish immutable audit events to a queue.

An access JWT contains iss, sub, aud, iat, exp, jti, and coarse scopes. Sign with an asymmetric algorithm such as EdDSA or RS256. Do not put passwords, personal data, or rapidly changing entitlements in claims. Resource services pin permitted algorithms and validate signature, issuer, audience, expiry, and required scopes.

5. Deep dive

Use short-lived access tokens (for example, five minutes) and longer-lived, rotating refresh tokens (for example, 30 days with inactivity expiry). The access token is stateless to verify; refresh is stateful so a stolen refresh token can be detected and its family revoked.

sequenceDiagram
  participant C as Client
  participant I as Identity API
  participant DB as Session database
  participant K as KMS
  participant S as Resource service
  C->>I: Login credentials and MFA
  I->>DB: Verify user and account status
  I->>K: Sign short-lived access JWT
  I->>DB: Store hash of refresh token
  I-->>C: Access JWT and secure refresh cookie
  C->>S: Request with bearer JWT
  S->>S: Verify signature and claims locally
  C->>I: Refresh cookie
  I->>DB: Atomically consume old token and create replacement
  I-->>C: New access JWT and refresh cookie
Diagram

Refresh must be an atomic compare-and-swap: mark the presented token used and insert its replacement in one transaction. If a previously consumed token is presented again, treat it as possible theft and revoke that family. Logout revokes refresh sessions immediately; already-issued access JWTs remain usable until expiry. For high-risk operations, check auth_version or session status through a strongly consistent authorization path, accepting the added latency and dependency.

6. Scale, bottlenecks & trade-offs

  • Run stateless identity API replicas across zones; use database replication and automated failover. Rate-limit login by account and source, with progressive delay and generic error messages to reduce enumeration.
  • Cache JWKS by kid with a bounded refresh interval. During key rotation, publish the new public key before signing with it, retain the old key until all old access tokens expire, then remove it. Fail closed on unknown keys for protected operations.
  • Stateless JWT verification improves availability and latency but delays ordinary-token revocation until expiry. Short expiry limits that window; targeted introspection is reserved for sensitive operations.
  • Prefer consistent SQL transactions for refresh rotation and revocation over a highly available but eventually consistent session store: accepting a replayed token is a security failure. Keep noncritical audit delivery asynchronous, using an outbox or durable queue so authentication does not depend on the audit worker.
TechnicalEasyTower Research CapitalSoftware EngineerFirst Round

11. What is the repository pattern?

Model answer

The repository pattern provides a domain-facing interface for retrieving and storing a particular kind of data, while hiding persistence details behind that interface. Application or domain logic asks for operations such as findById or save; it does not construct SQL queries or depend directly on a database client.

flowchart LR
    A[Application service] -->|domain operations| R[Repository interface]
    R --> I[Repository implementation]
    I --> D[(Database)]
Diagram

For example, an order service could use OrderRepository.findById(id) whether the implementation reads from a relational database or an in-memory test fixture.

  • Keep the interface aligned with domain use cases and return domain objects, not database-specific rows or query builders.
  • Put transaction boundaries and consistency requirements somewhere explicit; repositories should not hide important transactional behavior.
  • The pattern helps isolate persistence code and makes unit tests easier, but can become an unnecessary abstraction if it merely duplicates every ORM method.
  • For read-heavy or complex query paths, a separate query/read model can be more practical than forcing every access through a generic repository.

I would use it when persistence is a real boundary or when domain logic benefits from being tested independently—not as a mandatory wrapper around every database call.

TechnicalEasyTower Research CapitalSoftware EngineerFirst Round

12. What is dependency injection?

Model answer

Dependency injection (DI) is a design technique where an object receives the dependencies it needs from the outside, rather than constructing them itself. This separates an object's behavior from the choice of its collaborators.

For example, a pricing service can depend on a market-data interface. Production code injects a live market-data client; tests inject a deterministic fake.

flowchart LR
    C[Composition root] -->|constructs and injects| S[Pricing service]
    S -->|calls interface| M[Market data]
    P[Production client] --> M
    T[Test fake] --> M
Diagram
  • Constructor injection is generally the clearest choice: dependencies are explicit, and the object cannot be created in an invalid state.
  • A composition root—often application startup—wires concrete implementations to interfaces. A DI container can automate this, but is not required.
  • DI improves testability and makes implementations easier to replace. It does not mean “use an interface for everything”; abstractions are most useful at meaningful boundaries.
  • Avoid hidden service-locator lookups and overly broad dependency graphs: they obscure what a class needs and make failures harder to trace.

In a latency-sensitive service, I would keep wiring out of the request path and be deliberate about dependency lifetimes, especially for pooled connections or shared clients.

TechnicalEasyTower Research CapitalSoftware EngineerFirst Round

13. What is MVC architecture?

Model answer

MVC stands for Model–View–Controller. It separates an application's data and business rules, presentation, and request handling so each part can evolve independently.

  • Model: Represents domain data and business logic; it may interact with persistence or other services.
  • View: Presents information to the user, such as an HTML page or UI component.
  • Controller: Accepts user input or requests, invokes the relevant model logic, and chooses or populates a view.

A typical web request flows like this:

flowchart LR
    U[User] -->|request or action| C[Controller]
    C -->|read or update| M[Model]
    M -->|data or result| C
    C -->|select and populate| V[View]
    V -->|response| U
Diagram

For example, a controller handling an account page could ask the model for account data and pass the result to a view that renders the page. MVC improves separation of concerns and testability, but the boundaries can become blurred if controllers accumulate business logic or models become tightly coupled to presentation details.

TechnicalEasyTower Research CapitalSoftware EngineerFirst Round

14. What is Java's String Pool?

Model answer

Java's String Pool is a JVM-managed area that reuses canonical String objects, primarily for string literals and compile-time constant strings.

String a = "tower";
String b = "tower";
System.out.println(a == b); // true: both refer to the pooled object

String c = new String("tower");
System.out.println(a == c); // false: c is a distinct object
System.out.println(a.equals(c)); // true: same character content
  • Reusing immutable strings saves memory and can avoid duplicate allocations.
  • String.intern() returns the canonical pooled reference for a string's contents. Use it deliberately: interning large numbers of dynamic strings can add memory pressure.
  • Pooling affects object identity, not string equality. For comparing text, use .equals() rather than relying on the pool.
TechnicalEasyTower Research CapitalSoftware EngineerFirst Round

15. What is the difference between Java's .equals() method and the == operator?

Model answer

== and .equals() answer different questions for Java objects:

  • == checks whether two reference variables point to the exact same object.
  • .equals() checks logical equality as defined by the object's class. Object.equals() defaults to identity comparison, but classes such as String override it to compare contents.
  • For primitive values, == compares the values directly.
String a = new String("TRC");
String b = new String("TRC");

System.out.println(a == b);      // false: distinct objects
System.out.println(a.equals(b)); // true: equal text

When implementing equals() for a class, also implement hashCode() consistently: equal objects must have equal hash codes, which is essential for collections such as HashMap and HashSet.

TechnicalMediumTower Research CapitalSoftware EngineerFirst Round

16. How does database sharding work?

Model answer

Database sharding partitions a dataset across multiple database nodes so each node stores and serves only part of the data. A shard key determines where a record belongs. The goal is to increase storage and throughput beyond what one database can handle, at the cost of more complex routing and operations.

A common approach is to hash a stable key, such as account_id, and map the result to a shard:

flowchart LR
    A[Application] --> R[Shard router]
    R -->|account IDs in range or hash bucket A| S1[(Shard 1)]
    R -->|account IDs in range or hash bucket B| S2[(Shard 2)]
    R -->|account IDs in range or hash bucket C| S3[(Shard 3)]
Diagram
  • Choose the shard key based on access patterns. A good key distributes writes and keeps common queries on one shard. A poor key creates hot shards or forces cross-shard queries.
  • Route requests using a routing table or a deterministic function such as hash(account_id) % N. In practice, consistent hashing or virtual shards make adding capacity less disruptive.
  • Handle cross-shard work deliberately. Joins, global ordering, and transactions may require scatter-gather queries, denormalized data, or workflows such as sagas rather than one local transaction.
  • Plan for growth and failure. Replicate shards for availability, monitor skew, and move or split partitions when they become hot. Keep shard-map changes coordinated so reads and writes agree on ownership.

Sharding is different from replication: sharding divides data among nodes; replication keeps copies of data on multiple nodes. It is usually worth introducing only after a single database, indexing, caching, and query tuning no longer meet the workload.

TechnicalMediumTower Research CapitalSoftware EngineerThird Round

17. How does a JWT signature help verify the token's authenticity?

Model answer

For a signed JWT, the signer first Base64URL-encodes the header and payload, then signs their exact joined representation:

signingInput = base64url(header) + "." + base64url(payload)
signature = Sign(signingKey, signingInput)

With HMAC, the signer and verifier share a secret key. With an asymmetric algorithm such as RS256, the signer uses a private key and the verifier uses the corresponding public key. The verifier recomputes or checks the signature over the received header and payload. If either has been changed, verification fails, assuming the key and algorithm are handled correctly.

flowchart LR
    T["JWT header and payload"] --> S["Verify signature with trusted key"]
    S -->|"Valid"| C["Validate issuer, audience, and time claims"]
    S -->|"Invalid"| X["Reject token"]
    C -->|"Claims valid"| A["Continue authorization"]
    C -->|"Claims invalid"| X
Diagram

A valid signature supports integrity and authenticity relative to the trusted signing key: it shows that the token was signed by someone with the relevant key and has not been altered since. It does not encrypt the payload, prove that every claim is true, or by itself guarantee that the token is still authorized. The API must also validate claims and apply its authorization rules.

In practice, the verifier should allow only explicitly configured algorithms, obtain keys from a trusted source (often a JWKS endpoint for public keys), and handle key rotation safely. It must not trust an algorithm choice in the token without policy checks; mistakes such as accepting an unintended algorithm can undermine verification.

TechnicalMediumTower Research CapitalSoftware EngineerThird Round

18. What are JWTs, and how do they work?

Model answer

A JWT, or JSON Web Token, is a compact format for carrying claims—such as a user ID, issuer, or expiration time—between parties. A signed JWT is commonly used as a bearer credential for API authentication.

A JWT has three Base64URL-encoded parts separated by periods:

header.payload.signature
  • Header: Declares the token type and signing algorithm, for example alg: "RS256".
  • Payload: Contains claims such as sub (subject), iss (issuer), aud (audience), and exp (expiration). It is encoded, not encrypted, so anyone holding the token can read it.
  • Signature: Protects the header and payload from undetected modification and lets a verifier check who signed them.

A typical flow is:

sequenceDiagram
    participant C as Client
    participant A as Auth Service
    participant R as API
    C->>A: Authenticate
    A-->>C: Signed JWT
    C->>R: Request with Bearer token
    R->>R: Verify signature and claims
    R-->>C: Authorized response
Diagram

The API checks the signature and relevant claims before trusting the token. It should validate the expected issuer and audience, enforce expiration and any not-before time, and authorize the requested action. JWTs are often useful for stateless verification across services, but revoking an already-issued token can require short lifetimes, a denylist, or another stateful mechanism.

Because a bearer token grants whoever possesses it its associated authority, transmit it over TLS and avoid putting secrets or sensitive personal data in the payload. JWT is a token format; it does not inherently mean the contents are encrypted.

TechnicalMediumTower Research CapitalSoftware EngineerFirst Round

19. What is the difference between horizontal and vertical scaling?

Model answer

Vertical scaling means giving one machine more resources—for example, more CPU, RAM, or faster storage. Horizontal scaling means adding machines and distributing work among them.

flowchart LR
    subgraph V[Vertical scaling]
        A[One server] --> B[More CPU RAM or storage]
    end
    subgraph H[Horizontal scaling]
        C[Load balancer] --> D[Server 1]
        C --> E[Server 2]
        C --> F[Server 3]
    end
Diagram
  • Vertical scaling is often simpler: applications may need few architectural changes, and a larger database instance can be a straightforward first step. It has a hardware limit and can leave a larger single point of failure.
  • Horizontal scaling can provide higher aggregate capacity and resilience, but requires distributing requests and data. Stateless services scale more easily; stateful systems need choices such as replication, sharding, or externalized state.
  • Horizontal scale does not guarantee linear speedup: network overhead, coordination, hot keys, and serial bottlenecks can limit gains.

For a trading service, I might scale stateless API workers horizontally behind a load balancer, while scaling a database vertically first and then considering sharding or partitioning if measured load justifies the added consistency and operational complexity.

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