Dsa

780 articles

dsa5 min read

Bit Manipulation — Complete Guide

Master bit manipulation: XOR tricks, counting bits, bitmask DP, Brian Kernighan, two's complement, and 5-language operators.

Read →
dsa1 min read

Single Number III — XOR Partition

Two numbers appear once, rest appear twice. XOR all to get a^b, then use any set bit to partition numbers into two groups.

Read →
dsa1 min read

Reverse Bits — 32-Bit Reversal

Reverse bits of a 32-bit unsigned integer. Shift result left and input right 32 times, taking last bit each time.

Read →
dsa1 min read

Sum of Two Integers — Bit Addition

Add two integers without + or - operators. Simulate: sum = a XOR b (no carry), carry = (a AND b) << 1. Repeat until carry = 0.

Read →
dsa1 min read

Subsets — Bitmask Enumeration

Generate all subsets of an array. Each subset corresponds to a bitmask of n bits where bit i = 1 means element i is included.

Read →
dsa1 min read

Climbing Stairs — Fibonacci DP

Count ways to climb n stairs taking 1 or 2 steps. Classic Fibonacci DP — dp[n] = dp[n-1] + dp[n-2] with O(1) space.

Read →
dsa1 min read

House Robber — Skip Adjacent DP

Maximize amount robbed without robbing adjacent houses. Classic skip-one DP: dp[i] = max(dp[i-1], dp[i-2] + nums[i]).

Read →
dsa1 min read

House Robber II — Circular Array DP

Houses arranged in a circle: first and last are adjacent. Run linear House Robber twice: once excluding last house, once excluding first.

Read →
dsa1 min read

Maximum Subarray — Kadane's Algorithm

Find the contiguous subarray with the largest sum. Kadane's algorithm: either extend previous subarray or start fresh at current element.

Read →
dsa2 min read

Coin Change — Unbounded Knapsack DP

Find minimum coins to make amount. Unbounded knapsack DP: dp[amount] = min(dp[amount-coin]+1) over all coins. Bottom-up from 0 to amount.

Read →
dsa1 min read

Jump Game — Greedy Reachability

Check if you can reach the last index. Greedy: track furthest reachable index. If current position > reach, stuck.

Read →
dsa1 min read

Decode Ways — Counting DP

Count ways to decode a digit string as letters (A=1,...,Z=26). DP: single digit + valid double digit transitions.

Read →
dsa1 min read

Word Break — Reachability DP

Check if string can be segmented into dictionary words. DP: dp[i]=true if some dp[j] is true and s[j:i] is in wordDict.

Read →
dsa1 min read

Russian Doll Envelopes — 2D LIS

Maximum envelopes you can nest. Sort by width ascending and height descending, then LIS on heights. Descending heights prevents using same-width twice.

Read →
dsa1 min read

Target Sum — DP Count Ways

Assign + or - to each number to reach target sum. DP counts ways to reach each sum. Reduces to 0/1 knapsack subset sum count.

Read →
dsa1 min read

Unique Paths — Grid Path Count DP

Count paths from top-left to bottom-right moving only right or down. dp[i][j] = dp[i-1][j] + dp[i][j-1]. Math formula O(1) also works.

Read →
dsa1 min read

Minimum Path Sum — Grid DP

Find minimum cost path from top-left to bottom-right moving right or down. dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1]).

Read →
dsa1 min read

Triangle — Bottom-Up 1D DP

Minimum path sum from top to bottom of triangle. Bottom-up DP: dp[j] = triangle[i][j] + min(dp[j], dp[j+1]).

Read →
dsa1 min read

Edit Distance — Wagner-Fischer DP

Minimum operations (insert, delete, replace) to transform word1 to word2. Classic Wagner-Fischer 2D DP with O(n) space optimization.

Read →
dsa1 min read

Burst Balloons — Interval DP

Maximize coins by bursting balloons. Key insight: think of last balloon burst in interval [i,j]. dp[i][j] = max coins from interval with k as last balloon.

Read →
dsa1 min read

Interleaving String — 2D DP

Check if s3 is formed by interleaving s1 and s2. dp[i][j] = can s3[:i+j] be formed from s1[:i] and s2[:j].

Read →
dsa1 min read

Regular Expression Matching — 2D DP

Match string s against pattern p with . and *. dp[i][j] = does s[:i] match p[:j]. Handle * by matching zero or more of preceding char.

Read →
dsa1 min read

Wildcard Matching — 2D DP

Match string with wildcard pattern: ? matches any char, * matches any sequence. Similar to regex but * matches any sequence (not zero/more of preceding).

Read →
dsa1 min read

Dungeon Game — Reverse Grid DP

Find minimum initial health to reach bottom-right dungeon cell. Solve backwards: dp[i][j] = min health needed at (i,j) to survive.

Read →
dsa1 min read

Ones and Zeroes — 2D 0/1 Knapsack

Find maximum strings using at most m zeros and n ones. 2D 0/1 knapsack: dp[i][j] = max strings using i zeros and j ones.

Read →
dsa1 min read

Strange Printer — Interval DP

Minimum turns to print string where each turn prints a contiguous run of same char. Interval DP: dp[i][j] = min turns for s[i..j].

Read →
dsa2 min read

Flood Fill — DFS Color Replace

Implement the flood fill algorithm (like paint bucket tool): replace all cells of the same color reachable from a starting cell.

Read →
dsa2 min read

Surrounded Regions — Boundary DFS

Capture all 'O' regions not connected to the border. Classic boundary DFS: mark safe cells from edges, then flip remaining O to X.

Read →
dsa2 min read

Rotting Oranges — Multi-Source BFS

Find minimum minutes until all oranges rot. Multi-source BFS: push all initially-rotten oranges into queue simultaneously, BFS layer by layer.

Read →
dsa2 min read

Clone Graph — BFS/DFS with HashMap

Deep copy an undirected graph. BFS/DFS with a HashMap from original node to cloned node prevents revisiting and handles cycles.

Read →
dsa1 min read

Open the Lock — BFS State Space

Minimum turns to reach target combination avoiding deadends. BFS over all 4-digit wheel states with bidirectional BFS optimization.

Read →
dsa1 min read

Course Schedule II — Topological Order

Return a valid course order given prerequisites. Kahn's BFS topological sort outputs nodes in processing order — that is the valid schedule.

Read →
dsa2 min read

Word Ladder — BFS Shortest Transformation

Find minimum transformations from beginWord to endWord changing one letter at a time (each intermediate must be in wordList). Classic BFS on word states.

Read →
dsa1 min read

Bus Routes — BFS on Route Graph

Find minimum buses to get from source to target stop. BFS where nodes are routes (buses), not stops. Jump to all stops of a route, then to all routes passing through each stop.

Read →
dsa1 min read

Gas Station — Greedy Circular

Find starting gas station index to complete circular route. If total gas >= total cost, a solution exists. Track running balance; reset start when negative.

Read →
dsa1 min read

Candy — Two-Pass Greedy

Distribute minimum candies with higher-rated children getting more than neighbors. Two-pass: left-to-right for ascending, right-to-left for descending.

Read →
dsa1 min read

Largest Rectangle in Histogram — Monotonic Stack

Find the area of the largest rectangle in a histogram. Monotonic increasing stack: when a shorter bar is found, pop and compute rectangle area using popped height and current width.

Read →
dsa1 min read

Remove K Digits — Greedy Monotonic Stack

Remove k digits to get smallest number. Monotonic increasing stack: pop larger digits when they appear before a smaller one. Remove remaining from end.

Read →
dsa1 min read

Maximal Rectangle — Histogram per Row

Find the largest rectangle in a binary matrix. Build histogram row by row (reset to 0 on '0'), apply Largest Rectangle in Histogram each row.

Read →
dsa2 min read

Last Stone Weight

Simulate stone smashing by repeatedly extracting the two heaviest stones using a max-heap.

Read →
dsa2 min read

Relative Ranks

Assign gold/silver/bronze or rank numbers to athletes based on their scores using sorted ordering.

Read →
dsa3 min read

Find K Closest Elements

Find K closest elements to x in a sorted array using binary search to find the optimal left boundary.

Read →
dsa2 min read

Top K Frequent Elements

Return the K most frequent elements using a frequency map plus min-heap, or bucket sort for O(n) solution.

Read →
dsa1 min read

Sort Characters By Frequency

Sort characters in a string by decreasing frequency using a frequency counter and max-heap or bucket sort.

Read →
dsa2 min read

K Closest Points to Origin

Find K points closest to the origin using a max-heap of size K or quickselect for O(n) average.

Read →
dsa2 min read

Task Scheduler

Find minimum CPU intervals to schedule tasks with cooldown using a greedy max-heap simulation.

Read →
dsa3 min read

Reorganize String

Rearrange a string so no two adjacent characters are the same using a greedy max-heap approach.

Read →
dsa2 min read

Find Median from Data Stream

Maintain a dynamic median using two heaps: a max-heap for the lower half and a min-heap for the upper half.

Read →
dsa3 min read

Sliding Window Median

Compute medians of all sliding windows using two heaps with lazy deletion for element removal.

Read →
dsa2 min read

Merge K Sorted Lists

Merge K sorted linked lists into one sorted list using a min-heap to always extract the globally smallest node.

Read →
dsa2 min read

Find K Pairs with Smallest Sums

Find K pairs (u, v) with smallest sums from two sorted arrays using a min-heap initialized with first row candidates.

Read →
dsa2 min read

Ugly Number II

Find the nth ugly number (only prime factors 2, 3, 5) using three pointers for the 2x, 3x, 5x merge streams.

Read →
dsa2 min read

Course Schedule III

Maximize courses taken within deadlines by greedily scheduling and swapping out the longest past course.

Read →
dsa2 min read

Meeting Rooms II

Find minimum conference rooms required by tracking room end times with a min-heap of ongoing meeting endings.

Read →
dsa2 min read

IPO

Maximize capital after k IPO investments by greedily picking the highest profit project among affordable ones.

Read →
dsa2 min read

Car Pooling

Check if a car can pick up all passengers by processing start/end events with a sorted timeline or heap.

Read →
dsa2 min read

Furthest Building You Can Reach

Greedily use ladders for the largest climbs and bricks for smaller gaps, managed with a min-heap of ladder sizes.

Read →
dsa3 min read

Process Tasks Using Servers

Assign tasks to available servers using two heaps: one for free servers and one for busy servers sorted by free time.

Read →
dsa3 min read

Trapping Rain Water II

Calculate trapped water in a 3D height map using BFS with a min-heap to process cells from shortest boundary inward.

Read →
dsa3 min read

Swim in Rising Water

Find minimum time to swim from top-left to bottom-right in a grid where time = max elevation on the path.

Read →
dsa2 min read

Super Ugly Number

Find the nth super ugly number with prime factors only from a given list using K-pointer dynamic programming.

Read →
dsa2 min read

Minimum Number of Refueling Stops

Find minimum fuel stops to reach the target by greedily selecting the largest available fuel stations when running low.

Read →
dsa3 min read

Design Twitter

Design a simplified Twitter with follow/unfollow and a news feed showing the 10 most recent tweets from followed users.

Read →
dsa2 min read

Ugly Number III

Find the nth number divisible by a, b, or c using binary search with inclusion-exclusion counting formula.

Read →
dsa2 min read

Maximum Performance of a Team

Maximize team performance (sum of speeds * min efficiency) by sorting by efficiency and using a min-heap on speeds.

Read →
dsa2 min read

Longest Happy String

Build the longest string with at most 2 consecutive identical characters by always using the most frequent available character.

Read →
dsa2 min read

Maximum Frequency Stack

Design a stack that pops the most frequent element, breaking ties by most recently pushed, using frequency-bucket stacks.

Read →
dsa2 min read

Minimize Deviation in Array

Minimize max-min of an array by doubling odd numbers and repeatedly halving the max using a max-heap.

Read →
dsa1 min read

Find Right Interval

For each interval find the interval with the smallest start point >= the end point using sorted starts and binary search.

Read →
dsa1 min read

Kth Largest Sum in a Binary Tree

Find the kth largest level sum in a binary tree using BFS to compute level sums then sorting or using a heap.

Read →
dsa2 min read

Total Cost to Hire K Workers

Minimize total hiring cost by always choosing the cheapest candidate from the first or last p candidates using two min-heaps.

Read →
dsa1 min read

Seat Reservation Manager

Design a seat manager that reserves the lowest numbered available seat and unreserves seats using a min-heap.

Read →
dsa1 min read

Stock Price Fluctuation

Track stock prices with corrections by maintaining a sorted multiset and a timestamp-to-price map.

Read →
dsa1 min read

Reduce Array Size to At Least Half

Find the minimum number of elements to remove to reduce array size by half by greedily removing most frequent elements.

Read →
dsa1 min read

Reverse Pairs — Merge Sort / BIT

Count pairs (i,j) where i<j and nums[i] > 2*nums[j]. Modified merge sort: during merge, count pairs across left/right halves.

Read →
dsa1 min read

Count of Range Sum — Merge Sort / BIT

Count subarray sums within [lower, upper]. Use prefix sums and merge sort: during merge count pairs of prefix sums with difference in range.

Read →
dsa3 min read

Delete Node in a BST

Find and delete a node from a BST while maintaining BST properties using in-order successor.

Read →
dsa2 min read

Sum Root to Leaf Numbers

Compute the total sum of all root-to-leaf numbers formed by concatenating digits along each path.

Read →
dsa3 min read

Maximum Width of Binary Tree

Find the maximum width of a binary tree where width is measured from leftmost to rightmost non-null node per level.

Read →
dsa2 min read

Convert BST to Greater Tree

Replace each node value with the sum of all values greater than or equal to it using reverse in-order traversal.

Read →
dsa2 min read

Find Duplicate Subtrees

Find all duplicate subtrees by serializing each subtree and using a hash map to detect duplicates.

Read →
dsa2 min read

Unique Binary Search Trees II

Generate all structurally unique BSTs with values 1 to n using divide and conquer with memoization.

Read →
dsa2 min read

Trim a Binary Search Tree

Trim a BST so all values lie within [low, high] by recursively pruning out-of-range subtrees.

Read →
dsa2 min read

Recover Binary Search Tree

Find and swap the two misplaced nodes in a BST using in-order traversal to detect the violations.

Read →
dsa2 min read

House Robber III

Maximize robbery from a tree-structured neighborhood where adjacent (parent-child) nodes cannot both be robbed.

Read →
dsa2 min read

Binary Tree Cameras

Find minimum cameras to monitor all nodes using greedy bottom-up: prefer placing cameras at parents of uncovered leaves.

Read →
dsa2 min read

Distribute Coins in Binary Tree

Count minimum moves to distribute coins evenly by tracking excess/deficit coins flowing through each edge.

Read →
dsa3 min read

Kth Ancestor of a Tree Node

Find the Kth ancestor of any tree node in O(log k) per query using binary lifting (sparse table DP).

Read →
dsa2 min read

Maximum Sum BST in Binary Tree

Find the maximum sum of any BST subtree within a binary tree using post-order DFS returning subtree metadata.

Read →
dsa2 min read

Find Leaves of Binary Tree

Collect leaves by height (distance from leaf) repeatedly, returning all leaves at each height level.

Read →
dsa2 min read

Count Complete Tree Nodes

Count nodes in a complete binary tree in O(log^2 n) by comparing left and right heights to identify full subtrees.

Read →
dsa3 min read

Sum of Distances in Tree

Compute sum of distances from every node to all others in O(n) using two DFS passes with rerooting technique.

Read →
dsa2 min read

Unique Binary Search Trees

Count the number of structurally unique BSTs with n nodes using Catalan numbers and DP.

Read →
dsa1 min read

Binary Tree Pruning

Remove all subtrees that do not contain a 1 by recursively returning null for subtrees with only zeros.

Read →
dsa2 min read

Binary Search Tree Iterator

Implement an in-order BST iterator with O(h) space using a stack to simulate recursive in-order traversal.

Read →
dsa2 min read

Path Sum IV

Sum all root-to-leaf path sums in a tree encoded as 3-digit integers using a hashmap to decode tree structure.

Read →
dsa2 min read

Binary Tree Upside Down

Transform a binary tree so every right child becomes a sibling and left child becomes parent using iterative rotation.

Read →
dsa2 min read

Add One Row to Tree

Insert a new row of nodes at a given depth in a binary tree using BFS to reach the target depth level.

Read →
dsa1 min read

Deepest Leaves Sum

Sum all nodes at the deepest level of a binary tree using BFS to process level by level.

Read →
dsa2 min read

Cousins in Binary Tree

Determine if two nodes are cousins (same depth, different parents) using BFS to track depth and parent.

Read →
dsa2 min read

Construct Quad Tree

Build a quad tree from a 2D grid by recursively checking if a region is uniform and splitting into four quadrants.

Read →
dsa5 min read

Tries (Prefix Trees) — Complete Guide

Master Tries: insert/search/prefix, word search II, autocomplete, XOR trie for max XOR, and bitwise trie patterns with 5-language implementations.

Read →
dsa1 min read

Graph Coloring and Bipartite Check

Check if a graph is bipartite using BFS 2-coloring. A graph is bipartite if and only if it contains no odd-length cycles — equivalent to being 2-colorable.

Read →
dsa2 min read

Reconstruct Itinerary — Hierholzer's Eulerian Path

Find the itinerary using all flight tickets exactly once (Eulerian path). Uses Hierholzer's algorithm: DFS with post-order insertion into result — the only graph algorithm that uses post-order for path construction.

Read →
dsa2 min read

String Problems — Meta and Google Favourites

High-frequency string problems from Meta and Google interviews: valid parentheses, longest substring without repeating characters, zigzag conversion, and string to integer.

Read →
dsa2 min read

Aho-Corasick — Multi-Pattern String Matching

Aho-Corasick automaton matches all patterns simultaneously in O(n+m+z) where z is the number of matches. Builds failure links on a trie for efficient multi-pattern search.

Read →
dsa3 min read

Mock Week 3 — Hard Problems Under Time Pressure

Week 3 mock focuses on hard problems. Strategy: get a working solution in 35 minutes, optimize in remaining 15. Includes triage framework for when you're stuck on a hard problem.

Read →
dsa3 min read

Google Behavioral + Coding Interview Prep

Google's interview process: Googleyness criteria, coding expectations, and how to prepare for the unique 'How would you improve Google Maps?' style questions.

Read →
dsa3 min read

Meta Behavioral + Coding Interview Prep

Meta's interview process: core values evaluation, coding speed expectations, and preparation strategies for Meta's unique product-focused behavioral questions.

Read →
dsa2 min read

Amazon — Merge K Sorted Lists (Min-Heap)

Merge k sorted linked lists into one sorted list using a min-heap. O(n log k) time by always extracting the current minimum across all list heads.

Read →
dsa2 min read

Google — Count Inversions (Modified Merge Sort)

Count the number of inversions in an array (pairs where i < j but arr[i] > arr[j]) using modified merge sort in O(n log n). Google uses this to test deep algorithm understanding.

Read →
dsa3 min read

Design Snake Game — Deque-Based State Machine

Simulate a snake game on a grid where the snake eats food to grow and dies if it hits walls or itself. Uses a deque for O(1) head/tail and a set for O(1) body collision checks.

Read →