Interview Q&A / Data Structures & Algorithms
Data Structures & Algorithms interview questions
Arrays, linked lists, hashing, trees and patterns, with line-by-line code and complexity.
Prefer rapid revision? Practise Data Structures & Algorithms short interview answers →
- How do you count subarrays whose sum equals k using a prefix sum and hash map?
Keep a running prefix sum and a map of how many times each prefix sum has occurred. At each step, the number of subarrays ending here with sum k equals the count of earlier prefix sums equal to current minus k.
IntermediateQuick answerCoding1 min read - How do you find all unique triplets in an array that sum to zero?
Sort the array, fix one number, and use two pointers on the rest to find pairs that cancel it. Skip equal values to avoid duplicate triplets. It runs in O(n squared).
IntermediateQuick answerCoding1 min read - How do you find the length of the longest consecutive sequence in an unsorted array in O(n)?
Put all numbers in a set. Only start counting from a number whose predecessor is not in the set, then walk upward while the next number exists. Each number is visited at most twice.
IntermediateQuick answerCoding1 min read - How do you find the next greater element for every item in an array?
Use a monotonic stack of indices. Walk left to right; while the current value is greater than the value at the stack top, that top has found its next greater element. Then push the current index.
IntermediateQuick answerCoding1 min read - How do you rotate an array to the right by k steps in place?
Reverse the whole array, then reverse the first k elements, then reverse the rest. Take k modulo the length first. It runs in O(n) time with O(1) extra space.
IntermediateQuick answerCoding1 min read - How do you solve the Container With Most Water problem using two pointers?
Start with pointers at both ends. The area is the shorter height times the distance. Move the pointer at the shorter line inward, because moving the taller one can never increase the area.
IntermediateQuick answerCoding1 min read - How do you sort an array of 0s, 1s and 2s in a single pass?
Use the Dutch national flag method with three pointers: low for the next 0 position, high for the next 2 position, and mid scanning. Swap 0s to the front and 2s to the back; leave 1s in the middle.
IntermediateQuick answerCoding1 min read - What is Kadane's algorithm for the maximum subarray sum?
At each element decide: extend the running subarray or start fresh from this element. Track the best sum seen. It finds the largest contiguous sum in one pass.
IntermediateQuick answerCoding1 min read