Logic & Coding Puzzles
63+ hand-picked puzzles across arrays, recursion, graphs, DP, bit tricks and classic logic riddles. Every puzzle is tagged with a topic and comes with a full answer — try it yourself before revealing.
The Missing Number
An array holds n distinct numbers taken from 0 to n. One number is missing. How do you find it in O(n) time and O(1) space?
Two Sum
Given an array and a target, find two numbers that add up to the target. What's the fastest approach beyond brute force?
Kadane's Puzzle
How do you find the maximum sum of a contiguous subarray in O(n) time?
The Dutch National Flag
Sort an array containing only 0s, 1s, and 2s in a single pass without extra space.
Rotate in Place
Rotate an array right by k positions using O(1) extra space.
Duplicate Detective
How can you detect a duplicate in an array of n+1 integers where each value is between 1 and n, without modifying the array or using extra space?
Anagram Check
How do you check if two strings are anagrams of each other efficiently?
Longest Palindromic Substring
What's an efficient way to find the longest palindromic substring?
Reverse Words, Not Letters
Reverse the word order in a sentence without reversing individual letters.
First Non-Repeating Character
Find the first character in a string that never repeats.
Minimum Window Substring
Given a string s and a string t, find the smallest window in s containing all characters of t.
Valid Parentheses
Given a string of brackets ( ) { } [ ], how do you check if they're balanced and correctly nested?
Factorial Trace
What does fact(4) return if fact(n) = n <= 1 ? 1 : n * fact(n-1)?
Tower of Hanoi Moves
How many moves are required to solve Tower of Hanoi with n disks?
Subsets Generator
How do you generate all subsets of a set using recursion?
Memoized Fibonacci
Why is naive recursive Fibonacci O(2^n), and how do you fix it?
Reverse a String Recursively
Write the recursive idea to reverse a string without loops.
Detect a Cycle
How do you detect whether a linked list has a cycle, in O(1) space?
Reverse a Linked List
Reverse a singly linked list iteratively.
Find the Middle Node
Find the middle node of a linked list in a single pass.
Merge k Sorted Lists
What's an efficient strategy to merge k sorted linked lists?
Queue Using Two Stacks
How do you implement a queue using only two stacks?
Next Greater Element
For each element in an array, find the next element to its right that's greater. Do it in O(n).
Min Stack
Design a stack that supports push, pop, and getMin all in O(1).
Sliding Window Maximum
Find the maximum in every window of size k in an array, in O(n) total.
Height of a Binary Tree
How do you compute the height of a binary tree recursively?
Validate a BST
How do you check if a binary tree is a valid binary search tree?
Lowest Common Ancestor
Find the lowest common ancestor of two nodes in a binary tree.
Level Order Traversal
How do you print a binary tree level by level?
Serialize and Deserialize
How would you serialize a binary tree to a string and rebuild it later?
BFS vs DFS
When would you prefer BFS over DFS on a graph?
Detect a Cycle in a Directed Graph
How do you detect a cycle in a directed graph?
Topological Sort
Give an approach to topologically sort a directed acyclic graph.
Shortest Path with Weights
Which algorithm finds shortest paths in a graph with non-negative weighted edges?
Climbing Stairs
You can climb 1 or 2 steps at a time. How many ways to reach step n?
0/1 Knapsack
Given item weights, values, and a capacity, maximize value without exceeding capacity.
Longest Common Subsequence
How do you find the length of the longest common subsequence of two strings?
Coin Change (Fewest Coins)
Find the minimum number of coins needed to make an amount, given a set of denominations.
Edit Distance
How many single-character insert/delete/replace operations turn one string into another, at minimum?
Binary Search Bug
In binary search, why do we write mid = low + (high - low) / 2 instead of (low + high) / 2?
Quicksort's Worst Case
When does quicksort degrade to O(n²), and how do you avoid it?
Merge Sort Stability
Why is merge sort considered a stable sorting algorithm?
Find in a Rotated Sorted Array
Search a target in a rotated sorted array in O(log n).
Check Power of Two
How do you check if a number is a power of two, using bit tricks?
Single Number
Every element in an array appears twice except one. Find that one element in O(n) time, O(1) space.
Count Set Bits
What's Brian Kernighan's trick for counting set bits in an integer?
Swap Without a Temp Variable
Swap two integers without using a third variable.
GCD the Fast Way
What's the fastest classical way to compute the GCD of two numbers?
Sieve of Eratosthenes
How do you find all primes up to n efficiently?
Fast Exponentiation
How do you compute a^b in O(log b) instead of O(b)?
Detect a Perfect Square Without sqrt()
Check if a number is a perfect square without using a built-in sqrt function.
Overloading vs Overriding
What's the core difference between method overloading and overriding?
Why Favor Composition Over Inheritance?
Why do many designs prefer composition over deep inheritance chains?
Abstract Class vs Interface
When would you choose an abstract class over an interface?
The Diamond Problem
What is the diamond problem in multiple inheritance, and how do languages avoid it?
The Closure Loop
for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); } — what does this print?
Type Coercion Trap
What does '5' + 3 - 2 evaluate to in JavaScript?
Mutable Default Argument
def add(item, lst=[]): lst.append(item); return lst — what's the risk of calling add(1) twice?
Hoisting Confusion
console.log(x); var x = 5; — what gets printed and why?
The Two Egg Problem
You have 2 identical eggs and a 100-floor building. Find the highest floor an egg survives a drop from, minimizing worst-case attempts.
Fox, Chicken, and Grain
A farmer must cross a river with a fox, a chicken, and a bag of grain, taking one at a time. Fox eats chicken, chicken eats grain if left alone. How does he get everyone across?
100 Prisoners and a Lightbulb
100 prisoners are called one at a time, at random, into a room with a lightbulb. They must collectively determine when everyone has visited at least once. What strategy works?
Weighing the Odd Ball
You have 9 identical-looking balls, one heavier than the rest. Using a balance scale, find it in 2 weighings.