Two Sum — The Hash Map Pattern Every FAANG Engineer Knows
LeetCode 1 — Two Sum is the most-asked Amazon, Google, and Meta phone screen warmup. Single-pass hash map gives O(n) time and unlocks the complement-lookup pattern.
119 articles
LeetCode 1 — Two Sum is the most-asked Amazon, Google, and Meta phone screen warmup. Single-pass hash map gives O(n) time and unlocks the complement-lookup pattern.
LeetCode 121 — track the running minimum and the running best profit in a single linear pass. The cleanest greedy pattern asked at Amazon, Google, and Microsoft.
LeetCode 217 asks whether any value repeats in an array. The hash set answer runs in O(n) time and O(n) space. This guide compares it against sorting and brute force, shows why hash sets degrade to O(n) in the worst case, and works through the Contains Duplicate II and III follow-ups interviewers actually ask next.
LeetCode 283 — move all zeroes to the end while keeping nonzero order, in place and in O(n). The write pointer technique tested at Meta, Amazon, and Microsoft.
LeetCode 66 — increment a large integer represented as a digit array, propagating the carry. The deceptively simple FAANG warmup that catches careless coders.
LeetCode 88 — merge nums2 into nums1 in place by walking from the back. The classic two-pointer interview question at Meta and Microsoft.
Master the write pointer pattern — the canonical technique for in-place array modification. Full walkthrough of LeetCode 26 with visual dry run, common mistakes, and the LC 80 generalization. Python and JavaScript solutions included.
Find the one element that appears once while every other appears twice. The XOR bit trick delivers O(n) time and O(1) space — no extra memory, no sorting. Master the three XOR properties that make it work, then see how interviewers escalate to Single Number II and III.
Two problems, one pair of concepts: LC 349 asks for the unique intersection (HashSet), LC 350 asks for the frequency-aware intersection (HashMap). Master all three approaches for LC 349 — HashSet, sort+two pointers, binary search — then learn why the follow-up questions on LC 350 are what Google and Amazon actually care about: sorted input, skewed sizes, and data that does not fit in memory.
Master Pascal's Triangle (LeetCode 118 & 119) by understanding the binomial coefficient connection, the row-by-row DP pattern, space-optimized O(k) single-row generation, and five hidden mathematical properties that show up in Unique Paths, Coin Change, and beyond.
Master LeetCode 242 Valid Anagram with three approaches — sort O(n log n), 26-element frequency array O(n)/O(1), and HashMap O(n)/O(k). Includes a visual dry run, the critical Unicode follow-up, and the direct connection to Group Anagrams (LC 49).
LeetCode 344 is the canonical two-pointer problem — and it shows up at Meta, Microsoft, and Amazon as both a standalone question and as the foundation for palindrome checks, anagram detection, and rotate-array problems. Learn the in-place swap pattern deeply, trace through every edge case, and master the follow-ups that separate passing candidates from standout ones.
LeetCode 387 is deceptively simple — but the way you solve it, explain it, and handle its follow-ups separates candidates who get the offer from those who do not. Master the two-pass frequency map, understand why O(1) space is possible, and be ready for every streaming and ordering twist Amazon throws at you.
Master LeetCode 125 — Valid Palindrome with the O(1)-space two-pointer technique. Learn why every FAANG loop starts here, visualize the pointer walk on a classic example, avoid the four most common pitfalls, and unlock the palindrome follow-up chain: LC 680, LC 5, and LC 647.
LeetCode 14 appears deceptively simple — until the interviewer asks you to do it without sorting, then with binary search, then on a stream of words. Master all three approaches (vertical scan, horizontal fold, binary search on length), understand exactly why each one works, and walk into your Google screen ready for every escalation.
Count primes below n sounds trivial — until your naive solution times out on n=5,000,000. Master the Sieve of Eratosthenes, one of the most elegant algorithms in all of computer science, and learn the exact intuition that separates candidates who pass Amazon and Google screens from those who do not.
LeetCode 268 hides four distinct valid solutions behind a deceptively simple problem. Learn Sort, HashSet, Gauss Formula, and XOR — understand exactly why each exists, when interviewers ask for each one, and why XOR is the most elegant answer in the room.
The Boyer-Moore Voting Algorithm solves LeetCode 169 in O(n) time and O(1) space using a brilliantly counterintuitive cancellation trick. Learn the proof, the dry run, all four approaches, and why interviewers love this problem — plus the Majority Element II follow-up that extends the same idea to two candidates.
LeetCode 448 is the definitive interview test for index-as-a-hash-key thinking. Learn the O(n) time, O(1) space negation trick that eliminates the need for any extra data structure — and every follow-up question a FAANG interviewer will throw at you after you solve it.
Master LeetCode 414 — Third Maximum Number. Learn the subtle INT_MIN sentinel trap, two clean approaches (sorted set + three-variable O(1)), and real FAANG follow-up questions interviewers ask after you solve it.
Design a class to track the kth largest element in a live data stream. Learn why a min-heap of exactly k elements is the perfect data structure, trace through a full dry run, avoid the classic pitfalls, and walk away with clean Python and JavaScript solutions ready for FAANG interviews.
Most shuffle implementations are silently biased. Learn why naive random fails, how Fisher-Yates guarantees every permutation is equally probable, and what FAANG interviewers really want to hear when they ask this question.
LeetCode 1480 is the gateway to one of the most powerful patterns in competitive programming and FAANG interviews: prefix sums. Master the in-place O(1) space solution, understand why the prefix sum array unlocks O(1) range queries, and learn the real follow-up questions — range sum queries, subarray sum equals K, and 2D matrix prefix sums — that interviewers ask once you solve this problem in thirty seconds.
LeetCode 268 — asked at Amazon, Microsoft, and Google. Find the missing number from 0 to n using the Gauss sum formula in O(n) time and O(1) space. Alternatively use XOR for a bit-manipulation approach. Both are classic array interview questions at FAANG companies.
LeetCode 228 — asked at Amazon, Google, and Microsoft. Collapse a sorted unique integer array into the smallest list of ranges. Use a two-pointer linear scan to detect where consecutive runs break. O(n) time, O(1) space — clean and fast.
LeetCode 796 — asked at Amazon and Google. Check if string s can become string goal by rotating. The elegant O(n) trick: concatenate s with itself and check if goal is a substring. One line of code once you see the insight.
LeetCode 704 — the foundational FAANG binary search problem solved in O(log n) using the classic three-way exact-match template with overflow-safe midpoint.
LeetCode 278 — find the first bad version among n versions in O(log n) API calls using left-boundary binary search, the canonical FAANG predicate-search problem.
LeetCode 35 — find the index where a target exists or should be inserted in a sorted array. The canonical FAANG left-boundary binary search and the from-scratch implementation of bisect_left.
Compute the integer square root (floor) of x using right-boundary binary search. Find the largest k where k*k <= x, understand the upper-mid trick, and learn why this is the mirror image of the left-boundary template.
Find the secret number between 1 and n using the guess() API in O(log n) calls. Master the exact binary search template used in all interactive/guessing problems and understand why the API return values map directly to the lo/hi update rules.
LC 1351 asks you to count negatives in a matrix sorted both row-wise and column-wise. The O(m+n) staircase approach is optimal; an O(m log n) binary-search-per-row alternative is also acceptable. Both demonstrate how sorted structure eliminates naive O(mn) scanning.
LC 367 asks if a positive integer is a perfect square without using built-in sqrt. Binary search on [1, num] for a value k where k*k == num. Also learn the elegant O(sqrt(n)) odd-number identity. A classic easy binary search problem at Google and Apple.
LC 744 finds the smallest letter in a circular sorted array that is strictly greater than the target. Left-boundary binary search with modular wrap-around handles the circular case elegantly. A clean variant that extends the standard left-boundary template.
LC 1346 asks if any element and its double both appear in an array. The optimal O(n) hash set approach processes elements one by one. An O(n log n) sort-and-binary-search alternative demonstrates the binary search pattern. A good warm-up for two-sum variants.
LC 136 Single Number is the canonical XOR interview problem. Every duplicate cancels itself via a^a=0, leaving only the unique element. Master this identity and every follow-up variant before your next coding screen.
LeetCode 191 Number of 1 Bits: count set bits using Brian Kernighan trick n & (n-1). Foundational popcount technique that every FAANG interviewer expects you to know cold.
LeetCode 338 Counting Bits: compute popcount for every integer 0..n in O(n). Master the elegant DP recurrence dp[i] = dp[i >> 1] + (i & 1) that FAANG interviewers love.
LeetCode 190 Reverse Bits: reverse the binary representation of a 32-bit unsigned integer. Master the shift loop and the elegant divide-and-conquer mask reversal used in real-world DSP and crypto code.
LeetCode 268 Missing Number: find the one missing integer in [0..n] using XOR cancellation or the Gauss arithmetic-series formula. Two O(n) techniques every FAANG interviewer expects you to compare.
Design a class to find the kth largest element in a stream using a min-heap of size k. Amazon tests this to evaluate heap design, streaming data patterns, and online algorithm thinking.
Master Two Sum and its variants — 3Sum, 4Sum, Two Sum II — using hashmap for O(N) and two pointers for sorted arrays. Amazon relies on this problem family to assess foundational array skills and generalization ability.
LC 70 Climbing Stairs is the canonical introduction to 1D dynamic programming. The recurrence dp[n] = dp[n-1] + dp[n-2] is pure Fibonacci, and mastering why it works — recursion to memoization to tabulation — unlocks the entire family of staircase DP problems asked at Google, Amazon, and Meta.
LC 746 Min Cost Climbing Stairs extends the Climbing Stairs Fibonacci DP with per-step costs. The recurrence dp[i] = cost[i] + min(dp[i-1], dp[i-2]) computes the minimum total cost to leave each step. Asked at Amazon and Google as a direct test of whether you can adapt a known recurrence pattern under new constraints.
LC 53 Maximum Subarray is the foundational problem behind Kadane's Algorithm — a deceptively simple O(n) DP that asks: at each position, should I extend the current subarray or start fresh? Asked at Amazon, Google, and Microsoft and the basis for Maximum Product Subarray and other contiguous-subarray problems.
LC 121 Best Time to Buy and Sell Stock is the foundational stock DP problem at every FAANG company. While solvable with a one-pass greedy approach, understanding its state machine formulation (hold/not-hold states) unlocks the full stock problem series from LC 122 through LC 714.
Solve LeetCode 733 Flood Fill with simple DFS in O(m*n) time. The paint bucket tool from MS Paint reduced to a five-line recursion — the cleanest introduction to grid traversal you can give an interviewer.
Solve LeetCode 463 Island Perimeter in O(m*n) without DFS or BFS. The trick: every land cell contributes 4 edges, minus 2 for each shared edge with another land cell. Pure counting beats traversal.
A reachability check between two vertices in an undirected graph. Three optimal approaches: BFS, DFS, and Union Find — each with different trade-offs for follow-up questions about dynamic edges.
LeetCode 455 Assign Cookies is a Google and Amazon warm-up that teaches the greedy exchange argument. Sort both arrays and use two pointers to satisfy the maximum number of children in O(n log n).
LC 496 Next Greater Element I is the canonical entry point for monotonic stack thinking. Master the decreasing stack pattern and hash map lookup here, and you will recognize the same structure in Daily Temperatures, Largest Rectangle in Histogram, and Trapping Rain Water.
LeetCode 1 Two Sum is the most asked FAANG hashmap interview question. Master the one-pass complement HashMap that turns the brute-force O(n^2) into O(n).
LeetCode 242 Valid Anagram is a top FAANG warm-up that trains the frequency-array hashmap pattern reused in Group Anagrams, Find All Anagrams, and Minimum Window Substring.
LeetCode 383 Ransom Note is a FAANG warm-up that trains the supply-versus-demand frequency hashmap pattern reused in inventory, scheduling, and rate-limit interview questions.
LeetCode 205 Isomorphic Strings is a classic FAANG hashmap interview question that trains the bidirectional bijection check used in cipher validation, schema mapping, and Word Pattern.
LeetCode 290 Word Pattern is the FAANG hashmap interview question that lifts the Isomorphic Strings bijection from characters to whole words.
LeetCode 202 Happy Number is a FAANG hashmap interview classic that trains HashSet cycle detection and the Floyd two-pointer alternative for O(1) space.
LeetCode 219 Contains Duplicate II is a FAANG hashmap interview question that trains the last-seen-index pattern and the bounded sliding-window HashSet alternative.
Find Common Characters teaches frequency intersection — the element-wise minimum of character counts across multiple strings. This pattern appears in multi-set intersection problems, resource allocation, and constraint satisfaction at tech company interviews.
Jewels and Stones is the cleanest demonstration of the "build a lookup set, then query it" pattern. While the problem itself is easy, the skill it teaches — converting a repeated linear search into O(1) lookups — is fundamental to optimizing real-world code.
Unique Number of Occurrences teaches the double-hash technique: build a frequency map, then check if all frequency values are distinct. This two-layer hashing pattern appears in data validation, duplicate detection, and constraint checking problems at every major company.
LeetCode 653 (Easy) asks if any two nodes in a BST sum to k. Google, Facebook, and Amazon frequently use it as a warm-up to test whether you can combine DFS traversal with the Two Sum hash-set pattern.
Implement a HashMap from scratch using an array of buckets with chaining for collision resolution — the foundational data structure interview that every engineer should be able to implement cold.
Implement a HashSet from scratch using either a bit array for dense integer keys or chaining for general keys — the implementation-level interview that tests your understanding of set data structures.
LC 819 Most Common Word finds the most frequent non-banned word in a paragraph using normalization, regex tokenization, and a frequency hash map — a practical string-processing problem tested at Amazon and Microsoft.
Solve LeetCode 703 Kth Largest Element in a Stream — a classic Amazon and Meta phone-screen heap problem using a fixed-size min-heap of size K.
Solve LeetCode 1046 Last Stone Weight, a classic Amazon and Google warmup that teaches max-heap simulation by repeatedly smashing the two heaviest stones.
Solve LeetCode 506 Relative Ranks by assigning Olympic-style medals using a max-heap or index-sort, a common Amazon and Google warmup question.
Sort an array by element frequency ascending (ties broken by value descending) using a frequency map and custom comparator — a clean problem that tests mastery of custom sort keys.
LeetCode 2099 solved with a heap-based top-K selection followed by an index-preserving reconstruction. Tests whether you can decouple selection from ordering — a classic FAANG screening pattern.
LeetCode 206 Reverse Linked List is the foundational pointer-manipulation problem at FAANG interviews. Master the iterative three-pointer rewiring and the recursive call-stack reversal — both are used as subroutines in dozens of harder problems.
LeetCode 876 Middle of the Linked List teaches the fast/slow pointer technique that appears in half of all linked-list interview problems. Find the middle node in one pass with zero extra space, and understand exactly which middle you get for even-length lists.
LC 141 Linked List Cycle is a classic interview question asked by Amazon, Microsoft, and Google that tests your mastery of the two-pointer fast/slow technique. Learn Floyd's tortoise and hare algorithm with a visual dry run, Python and JavaScript solutions, and key interview tips.
LC 21 Merge Two Sorted Lists is one of the most frequently asked linked list interview problems at Amazon, Google, and Microsoft. Learn the dummy head merge pattern with step-by-step Python and JavaScript solutions, visual dry run, and interview tips.
LC 234 Palindrome Linked List is a popular interview problem at Facebook, Amazon, and Apple that combines three core techniques: fast/slow pointer midpoint finding, in-place list reversal, and two-pointer comparison. Master the O(1) space solution with Python and JavaScript code and a step-by-step dry run.
LC 83 Remove Duplicates from Sorted List is a foundational linked list interview problem asked at Bloomberg and Microsoft. Learn the single-pass pointer walk solution with Python and JavaScript, a visual dry run, common traps, and how to extend it to the harder variant (LC 82).
LC 237 Delete Node in a Linked List is a clever trick problem asked at Adobe and Microsoft that tests whether you understand linked list node deletion when you only have access to the node itself and not the head. Learn the copy-and-skip approach with Python and JavaScript solutions.
LC 160 Intersection of Two Linked Lists is a popular O(1) space interview question at Amazon, Facebook, and Microsoft. Learn the elegant two-pointer length-equalizer trick, the mathematical proof behind why it works, visual dry run, and Python/JavaScript solutions.
LC 1290 Convert Binary Number in a Linked List to Integer is an easy interview problem that combines linked list traversal with binary number conversion. Learn the elegant bit-shift accumulation pattern with Python and JavaScript solutions, dry run, and interview tips.
LC 203 Remove Linked List Elements is a fundamental interview problem asked at Google and Amazon that teaches the dummy head sentinel pattern for handling head deletion cleanly. Learn O(n) solutions in Python and JavaScript with visual dry run, common mistakes, and recursive variant.
Number theory basics — divisibility, congruences, digit DP, perfect numbers — power half of the math problems at Amazon and Microsoft. Master the divisibility rules, modular congruence properties, and digit-extraction tricks before tackling advanced number theory.
Master the Valid Parentheses problem using a stack to match nested brackets in O(n) time. The canonical LIFO warm-up problem asked at Google, Meta, Amazon, and Microsoft — learn the hash-map trick and every edge case.
Implement a LIFO stack using only queue operations. Learn both the single-queue rotation trick and the two-queue approach — a classic data-structure design problem that tests your understanding of LIFO vs FIFO at FAANG interviews.
Implement a FIFO queue using two stacks with amortized O(1) push and pop. The two-stack lazy-transfer trick is a FAANG interview staple that demonstrates deep understanding of amortized complexity and LIFO vs FIFO semantics.
Design a stack that supports push, pop, top, and getMin in O(1) time using a parallel min-tracking stack. A classic FAANG design interview problem testing stack invariants and auxiliary state maintenance.
Simulate a baseball scoring game using a stack to handle score records, doubles, sum operations, and cancellations in O(n) time. A clean stack-simulation problem that tests your ability to model stateful operations with LIFO access.
Compare two typed strings after applying backspace characters using a stack simulation or O(1) space two-pointer from the right. Covers both approaches with full complexity analysis and FAANG interview tips.
Find the minimum operations to return to the root folder by simulating file system navigation with a stack depth counter in O(n) time and O(1) space. A clean warm-up problem testing stack simulation and boundary conditions.
Count ping requests within the last 3000ms using a FIFO queue that evicts expired timestamps from the front in O(1) amortized time. A clean introduction to the sliding window queue pattern used in rate limiters and real-time counters.
Remove adjacent pairs of same letters with different cases using a stack that processes each character and cancels bad pairs immediately. A clean application of the stack-based adjacent-pair-removal pattern common in FAANG string interviews.
Find the next greater element for each query using a monotonic stack on nums2 and a hash map lookup in O(n+m) time. A classic application of the monotonic stack pattern combined with hash map lookups for efficient query answering.
Design a parking system with big, medium, and small spaces. O(1) addCar checks slot availability and decrements the counter—a warm-up problem testing array indexing and capacity management in FAANG phone screens.
LeetCode 104 — Maximum Depth of Binary Tree, asked by Amazon, Google, Meta and Apple as a phone-screen warmup. Solve it in one line of recursive DFS or with iterative BFS level counting in O(n) time.
LeetCode 226 — Invert Binary Tree, the famous Max Howell / Google whiteboard rejection question. Solve recursively in 4 lines or iteratively with BFS in O(n) time.
LeetCode 101 — Symmetric Tree, asked at Amazon, Microsoft and Bloomberg. Compare opposite subtrees with a two-pointer recursive helper to check mirror symmetry in O(n) time.
LeetCode 112 — Path Sum, asked at Amazon, Microsoft, Apple and Meta. Use DFS with a running remainder to detect any root-to-leaf path that sums to a target value in O(n) time.
LeetCode 100 — Same Tree, asked at Amazon, Meta, Google and Apple. Walk both trees simultaneously and return false on the first structural or value mismatch in O(n) time.
LeetCode 110 — Balanced Binary Tree, asked at Amazon, Meta, Google and Microsoft. Use a postorder DFS that returns -1 on imbalance to solve it in O(n) time instead of the naive O(n log n).
LeetCode 617 — Merge Two Binary Trees, asked at Amazon, Apple, Meta and Microsoft. Walk both trees in parallel, sum overlapping nodes, and reuse existing pointers in O(n) time.
LeetCode 938 — Range Sum of BST, asked at Amazon, Facebook (Meta), Google and Apple. Use the BST property to prune entire out-of-range subtrees and run in O(h + k) time.
LeetCode 700 — Search in a BST, asked at Amazon, Microsoft, Apple and Meta. Eliminate half the tree at each step using the BST property and finish in O(h) time, O(1) iterative space.
LeetCode 543 Diameter of Binary Tree — top Tree DP problem at Amazon, Meta, Google, Bloomberg. Single DFS that returns height while tracking the longest path through any node.
LeetCode 671 (Easy) asked at Amazon and Lyft. Find the second minimum value in a special binary tree where every node equals the min of its children, using DFS with pruning in O(n) time.
LeetCode 606 (Easy) asked at Amazon and Apple. Serialize a binary tree in preorder with parentheses, omitting empty parens only when they do not affect the one-to-one mapping, in O(n) time.
LC 993 Cousins in Binary Tree checks if two nodes are at the same depth with different parents. The clean O(n) BFS solution processes one level at a time — a foundational tree problem tested at Amazon and Microsoft.
LC 589 N-ary Tree Preorder and LC 590 Postorder Traversal generalize binary tree DFS to trees with any number of children. These easy problems build the foundation for harder n-ary tree problems asked at Amazon and Google.
LeetCode 897 (Easy). Rebuild a BST into a strictly right-skewed list using a single inorder traversal that rewires left and right pointers in place.
LeetCode 2185 — count how many strings in words have pref as a prefix. The simple linear scan is optimal for a single query; the trie shines once you anticipate many queries against the same word list.
LeetCode 125 Valid Palindrome is the most common two pointer warm-up at Meta, Microsoft, and Amazon. Learn the inward-converging pointer technique that runs in O(n) time and O(1) space without building a cleaned copy of the string.
LeetCode 344 Reverse String is the simplest two pointer swap problem and a daily warm-up at Amazon, Apple, and Meta. Solve it in O(n) time and O(1) space using opposite-end pointers without allocating a new array.
LeetCode 977 Squares of a Sorted Array is a classic Google and Bloomberg two pointer question. Squaring negatives flips the sort order, so we merge from the outside in to produce a sorted output in O(n) time without re-sorting.
LeetCode 27 Remove Element introduces the fast and slow pointer pattern used in dozens of in-place array problems. Master the read and write index template here and LC 26, LC 283, and LC 80 become trivial.
LeetCode 26 Remove Duplicates from Sorted Array is the canonical fast and slow pointer deduplication problem. Microsoft, Meta, and Amazon use it to verify that candidates can compare against the previous kept element in O(n) time and O(1) space.
LeetCode 88 Merge Sorted Array is the classic three pointer in-place merge problem at Microsoft, Bloomberg, and Amazon. Walk both arrays from the end into the trailing empty slots to achieve O(m plus n) time with O(1) extra space.
LeetCode 392 Is Subsequence is a Google and Amazon greedy two pointer problem. Walk both strings forward, advance the source pointer only on matches, and answer in O(m plus n) time with O(1) space.
LeetCode 1176 Diet Plan Performance is a Google fixed sliding window problem. Maintain a running sum of exactly k consecutive calories to score points or penalties in O(n) time and O(1) space.
LeetCode 1480 Running Sum of 1D Array introduces the prefix sum technique used in dozens of FAANG range query problems. Build the running sum in O(n) time and O(1) extra space and unlock LC 303, LC 560, and LC 974.
LC 1984 asks for the minimum max-minus-min over any k chosen scores. The optimal k scores are always contiguous in sorted order — sort once then scan windows of size k in O(n log n) time, O(1) space.
Check whether an integer array can be split into three contiguous parts with equal sum. LeetCode 1013 in O(n) using a greedy single-pass counter, with full Python and JavaScript code.