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 implement binary search, and what are the common bugs?
On a sorted array, keep two pointers low and high, check the middle element, and throw away the half that cannot contain the target. Repeat until found or low passes high. It runs in O(log n). The classic bugs are computing mid as (low + high) / 2, which can overflow in Java or C++, and off-by-one errors in the loop condition and pointer updates.
BeginnerIn-depthCoding4 min read - How do you merge two sorted arrays into one sorted array?
Use two pointers, one at the start of each array. Compare the two current elements, copy the smaller one to the result and move that pointer forward. When one array runs out, copy the rest of the other. This is O(n + m) time, much better than joining and sorting again.
BeginnerIn-depthCoding3 min read - Two Sum - find two numbers that add up to a target
Walk through the array once and store each number's index in a hash map. For each number, check if target minus that number is already in the map. This takes O(n) time.
BeginnerIn-depthCoding2 min read - How do you find the longest common prefix among an array of strings?
Take the first string as the candidate prefix and shorten it until every other string starts with it. Return what is left, which may be an empty string.
BeginnerQuick answerCoding1 min read - How do you find the maximum profit from buying and selling a stock once?
Scan once while tracking the lowest price so far. At each day, the best profit if you sell today is price minus that lowest price. Keep the maximum of those.
BeginnerQuick answerCoding1 min read - How do you remove duplicates from a sorted array in place and return the new length?
Keep a write index. Because the array is sorted, a value is new only if it differs from the last value written. Copy it forward and advance the write index; the final write index is the new length.
BeginnerQuick answerCoding1 min read - What is the difference between an array and a linked list, and when would you choose each?
An array stores items contiguously, so indexing is O(1) but inserting in the middle is O(n). A linked list stores nodes connected by pointers, so insertion at a known node is O(1) but reaching the kth item is O(n).
BeginnerQuick answer1 min read - Write a function that moves all zeroes to the end of an array while keeping the order of the other elements.
Use a write pointer: copy every non-zero value forward to the write position, then fill the remaining slots with zeroes. One pass, no extra array.
BeginnerQuick answerCoding1 min read