Essential algorithms and data structures
Comprehensive collection of must-know algorithms and data structures with clear explanations, complexity analysis, and production-ready code examples.
Essential array algorithms and techniques
Efficiently search for an element in a sorted array using divide and conquer.
Binary search works by repeatedly dividing the search interval in half. If the target value is less than the middle element, search the left half; otherwise, search the right half.
Find two numbers in an array that add up to a target sum.
Use a hash map to store each number and its index. For each number, check if its complement (target - current number) exists in the map.
Find the contiguous subarray with the largest sum.
At each position, decide whether to extend the current subarray or start a new one. Keep track of the maximum sum seen so far.
Use two pointers to solve array problems efficiently.
Move two pointers inward (or forward together) to find pairs efficiently. Useful for sorted arrays.
Precompute prefix sums to answer range sum queries quickly.
Store cumulative sums. Range sum [l, r] = prefix[r+1] - prefix[l].
Sort an array of 0s, 1s, and 2s in linear time.
Partition array into three regions (0s, 1s, 2s) using three pointers.
Perform range updates efficiently in O(1).
Use a difference array to mark range updates, then prefix sum to finalize values.
Randomly select one element from a stream of unknown length.
Keeps each element with equal probability 1/n without knowing n in advance.
Answer offline range queries efficiently using sqrt decomposition.
Sort queries into blocks and adjust range incrementally to compute results efficiently.
Efficient static range queries (min/max/gcd).
Precompute answers for power-of-two ranges. Query with overlap of two ranges.
Divide problem into halves and combine results, useful for large input sizes.
Split array into halves, compute all subset sums, and binary search for complement sums.
Find the majority element (> n/2 occurrences).
Keep a candidate and adjust counter. The majority element will remain at the end.
Find the maximum element in every sliding window of size k.
Use a deque to maintain indices of elements in decreasing order of their values. The front always contains the index of the maximum element in the current window.