Skip to content
Preptima

Data Structures & Algorithms interview questions and answers

DSA interview questions organised by tested pattern: arrays, hashing, rotated arrays, dynamic programming, graphs, heaps and sliding windows, so you learn transferable coding-round techniques instead of memorising puzzles.

57 published across 16 topics.

Arrays & Strings

4 questions

In-place manipulation, prefix sums, and the string-scanning problems that open most coding rounds.

mediumCoding

Find the largest sum obtainable from a contiguous run of elements in an array.

Walk the array once, keeping the best sum ending at the current element - that element alone, or that element added to the best run ending before it. The maximum of those is the answer, and the familiar version that resets the running sum to zero is wrong when every element is negative.

4 minentry, mid, senior
mediumCoding

Rotate an array k positions to the right, in place.

Rotate array by k in place by normalising k modulo n, reversing the whole array, then reversing the first k and remaining n-k elements. It is O(n) time, O(1) extra space, and avoids the cyclic-replacement pitfalls unless write count matters. Use this ARRAYS answer to show the decision, trade-off, and evidence rather than a memorised definition.

4 minentry, mid, senior
All 4 in Arrays & Strings

Hashing & Maps

4 questions

Trading memory for time with hash maps and sets, plus the collision and ordering caveats interviewers probe.

mediumCodingConcept

Count the subarrays whose elements sum to k, where the values may be negative.

Subarray Sum Equals K is solved with prefix sums and a hash map: for each running sum, count earlier prefixes equal to sum-k. This is O(n) time and works with negative numbers, unlike a sliding window. Use this hashing answer to show the decision, trade-off, and evidence rather than a memorised definition.

4 minmid, senior
mediumCodingConcept

A cache must evict the least recently used entry and every operation has to be O(1). Which two structures do you need, and why is one of them not enough?

A hash map from key to a doubly linked list node, over one recency-ordered list. The map answers find-by-key, the list answers find-the-oldest, and neither answers the other in constant time. The detail that decides the answer is that the map stores the node rather than the value, which is what makes unlinking on a hit a fixed number of pointer writes.

5 minmid, senior, staff
All 4 in Hashing & Maps

Linear-time techniques for subarray and pair-finding problems that naively look quadratic.

mediumCoding

Find the length of the longest substring without repeating characters.

Maintain a sliding window with a map from character to its last seen index; when a duplicate appears inside the current window, jump the left boundary past that previous occurrence rather than shrinking one step at a time, giving a single-pass O(n) solution. It also connects two pointers to the point an interviewer is testing.

2 minentry, mid, senior
mediumCoding

Return every distinct triplet in the array that sums to zero.

Sort the array, fix each element as an anchor, then converge two pointers inwards from both ends of the remaining range. The sort is asymptotically free against the O of n squared scan, and it is what lets you skip duplicate values positionally instead of deduplicating a set of results afterwards. It also connects sorting to the point an interviewer is testing.

4 minentry, mid, senior
All 4 in Two Pointers & Sliding Window

Linked Lists

2 questions

Pointer surgery: reversal, cycle detection, merging, and the off-by-one errors that reveal carelessness.

Stacks & Queues

4 questions

Monotonic stacks, deques, and the parsing and next-greater-element families.

mediumCodingConcept

Implement a FIFO queue using only two stacks, then tell me what a dequeue costs.

Push arrivals onto an inbound stack and serve departures from an outbound one, transferring everything across only when the outbound stack is empty. Transferring on every dequeue instead reverses the order and breaks FIFO, and the empty-only rule is also what makes the amortised cost constant.

4 minentry, mid, senior
All 4 in Stacks & Queues

Trees & BSTs

3 questions

Traversals, recursion versus iteration, balancing, and lowest-common-ancestor problems.

mediumCoding

Find the lowest common ancestor of two nodes in a binary tree.

Recurse post-order and return the node whose left and right subtrees each report back one target; if only one side reports back, propagate that result upwards. This is O(n) time and O(h) stack. A BST lets you descend by value comparison instead, and parent pointers reduce it to list intersection. It also connects recursion to the point an interviewer is testing.

5 minentry, mid, senior
mediumCoding

Given a binary tree, decide whether it is a valid binary search tree.

Every node must fall inside an open interval inherited from its ancestors, not merely compare correctly against its own two children. Recurse carrying a low and high bound, tightening one of them at each descent, or walk in-order and require the sequence to be strictly increasing.

5 minentry, mid, senior
All 3 in Trees & BSTs

Graphs

6 questions

BFS, DFS, topological sort, shortest paths, and union-find, including spotting a graph problem in disguise.

All 6 in Graphs

Top-K, streaming medians, and merges where partial ordering beats full sorting.

mediumCodingConcept

Numbers arrive one at a time and after each one you must answer what the Kth largest so far is. What do you keep, and what do you deliberately throw away?

Keep a min-heap holding exactly the K largest values seen. Its root is the answer, so the query is a read rather than a search, and every value smaller than that root is discarded the moment it arrives. What you give up is the ability to answer for any K larger than the one you chose, which is why the first thing to establish is whether K is fixed.

6 minmid, senior, staff
All 4 in Heaps & Priority Queues

Dynamic programming interview questions on state definition, recurrence transitions, memoisation, tabulation and recognising overlapping subproblems.

mediumCodingConcept

Edit distance where insert costs 1, delete costs 2 and replace costs 3. Define the DP state and the recurrence, and tell me what changes from the classic version.

The state is unchanged - the minimum cost to transform the first i characters of one string into the first j of the other - because the subproblem structure does not depend on what operations cost. Only the recurrence changes, adding a per-operation weight instead of a uniform 1, and the base cases become multiples of the insert and delete costs rather than i and j.

4 minmid, senior
mediumCodingConcept

How do you know a problem is dynamic programming?

Dynamic programming interview questions usually need overlapping subproblems, optimal substructure and a precise state definition. Define the minimum state, write the transition, then choose memoisation or tabulation based on dependency order.

5 minmid, senior
All 6 in Dynamic Programming

Greedy Algorithms

2 questions

Exchange arguments and proving a locally optimal choice is globally safe.

mediumCodingConcept

How do you know a greedy choice is safe and not merely plausible?

A greedy choice is safe when you can show at least one optimal solution contains it, usually via an exchange argument that swaps an optimum's first choice for yours without losing anything. Interval scheduling by earliest finish time admits that swap; coin change with arbitrary denominations does not.

4 minmid, senior, staff

Recursion & Backtracking

2 questions

Permutations, combinations, constraint satisfaction, and pruning to keep search tractable.

hardCoding

Count the ways to place N queens on an N by N board so that no two attack each other.

One queen per row is forced, so search row by row and keep sets of used columns, used sums and used differences to reject a conflict before recursing. The anti-diagonal is the row plus column and the main diagonal the row minus column, and that difference must be shifted into range, not reduced with an absolute value.

5 minmid, senior, staff
mediumCoding

Generate every permutation of an array that may contain duplicates, then tell me how large the search tree is

Backtracking builds each candidate incrementally and undoes the last choice on return; duplicates are suppressed by sorting and skipping a repeated value whose identical predecessor is unused. The tree holds under e times n factorial nodes, so pruning only pays when it removes subtrees near the root. It also connects recursion to the point an interviewer is testing.

4 minmid, senior

Binary search on answers, custom comparators, and sorting internals still asked about.

mediumCoding

Shipping packages within D days minimises a maximum. Now place m sensors at fixed positions so the closest pair is as far apart as possible. What changes in the binary search?

It is still binary search on the answer, over the gap rather than the positions, but the predicate flips. A gap that works means every smaller gap works, so you want the last feasible value, which needs lo = mid with a ceiling midpoint. Sort first, check each gap greedily, and the cost is O(n log n + n log R).

5 minmid, senior
mediumCoding

Given package weights in a fixed order, find the smallest ship capacity that delivers them all within D days

When you cannot construct the answer but can cheaply test a candidate, and that test is monotone, binary search the answer's numeric range instead of the input. The feasibility check here is greedy day-packing, giving O(n log S) time, and the whole implementation hinges on one loop invariant. It also connects monotonicity to the point an interviewer is testing.

5 minmid, senior, staff
All 4 in Sorting & Searching

Intervals

3 questions

Merging, overlap detection, and sweep-line scheduling problems.

easyCoding

Merge a list of overlapping intervals, and justify the key you sorted by

Sorting by start time is what reduces the merge to a single scan carrying one scalar, the end of the open block; sorting by end breaks it, and sorting by end is instead correct for maximum non-overlapping selection. Both run in O(n log n), and equal timestamps decide the answer.

4 minentry, mid, senior
All 3 in Intervals

Bit Manipulation

3 questions

Masks, XOR tricks, and the low-level questions in systems-leaning interviews.

All 3 in Bit Manipulation

Prefix trees, autocomplete, and pattern matching for search-heavy roles.

mediumCodingConcept

You need to find a substring in linear time and the interviewer will not accept a library call. What do you compute, and what goes wrong on a collision?

Rabin-Karp computes a polynomial hash of the pattern and a rolling hash of each text window, updated in constant time per step modulo a large prime. Equal hashes only nominate a candidate, so you compare characters before reporting it. Skip that check and a collision is a wrong answer; keep it and collisions cost time.

5 minmid, senior
All 3 in Tries & Advanced Strings

Deriving and defending time and space bounds, including amortised reasoning.

mediumConcept

Appending to a dynamic array is O(1) amortised. Derive that, then defend it against someone who points out that a single append copies the whole array.

Dynamic array append is amortized O(1) because capacity doubling makes the resize copy costs form a geometric series below 2n over n appends, even though one individual append can still be O(n). Use this complexity analysis answer to show the decision, trade-off, and evidence rather than a memorised definition. It also connects amortised analysis to the point an interviewer is testing.

5 minmid, senior, staff
All 3 in Complexity Analysis