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 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 group anagrams together from a list of words?
Anagrams share the same sorted letters, so use the sorted word as a hash map key and collect each word under its key. The map values are the groups.
IntermediateQuick answerCoding1 min read