> Uploading knowledge... _
[░░░░░░░░░░░░░░░░░░░░░░░░] 0%
blog logo
> CHICIO CODING_Pixels. Code. Unplugged.

DSA Exercises

Below you can find a curated list of exercises for each topic covered in the DSA course. Each exercise links to a dedicated page with a problem summary, the key techniques involved, and a TypeScript solution walkthrough.

Arrays

ExerciseDifficultyDescription
Best Time to Buy and Sell StockEasy

Given an array of stock prices where prices[i] is the price on the i-th day, find the maximum profit by choosing a single day to buy and a different future day to sell.

Best Time to Buy and Sell Stock IIMedium

Given an array of stock prices, you can buy and sell the stock multiple times — find the maximum total profit you can achieve.

First Missing PositiveHard

Given an unsorted integer array nums, return the smallest missing positive integer. The algorithm must run in O(n) time and use constant extra space.

Increasing Triplet SubsequenceMedium

Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k].

Majority ElementEasy

Given an array nums of size n, return the majority element — the element that appears more than ⌊n / 2⌋ times. The majority element always exists in the array.

Move ZeroesEasy

Given an integer array nums, move all 0s to the end of it while maintaining the relative order of the non-zero elements, in-place.

Number of Zero-Filled SubarraysMedium

Given an integer array nums, return the number of subarrays entirely filled with 0s. A subarray is a contiguous non-empty sequence of elements within an array.

Product of Array Except SelfMedium

Given an integer array nums, return an array where each element is the product of all other elements, without using division, in O(n) time.

Remove Duplicates from Sorted ArrayEasy

Given a sorted array nums, remove duplicates in-place so each unique element appears only once and return the count of unique elements.

Rotate ArrayMedium

Given an array, rotate it to the right by k steps, where k is non-negative, using an in-place reversal technique.

Strings

ExerciseDifficultyDescription
Guess the WordHard

You are given an array of unique strings words where words[i] is six letters long. One word of words was chosen as a secret word.

Is SubsequenceEasy

Given two strings s and t, return true if s is a subsequence of t, or false otherwise.

Longest Common PrefixEasy

Write a function to find the longest common prefix string amongst an array of strings.

Reverse Words in a StringMedium

Given an input string s, reverse the order of the words.

Valid PalindromeEasy

A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward.

Zigzag ConversionMedium

The string PAYPALISHIRING is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

Bit Manipulation

ExerciseDifficultyDescription
Bitwise AND of Numbers RangeMedium

Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.

Counting BitsEasy

Given an integer n, return *an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of *i.

Number of 1 BitsEasy

Given a positive integer n, write a function that returns the number of set bits in its binary representation (also known as the Hamming weight).

Reverse BitsEasy

Reverse bits of a given 32 bits signed integer.

Single NumberEasy

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

Single Number IIIMedium

Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer...

Sum of Two IntegersMedium

Given two integers a and b, return the sum of the two integers without using the operators + and -.

Hashtable

ExerciseDifficultyDescription
Isomorphic StringsEasy

Given two strings s and t, determine if they are isomorphic.

Contains Duplicate IIEasy

Given an integer array nums and an integer k, return true *if there are two distinct indices i and j in the array such that nums[i] == nums[j] and *abs(i - j) <= k.

Design HashMapEasy

Design a HashMap without using any built-in hash table libraries.

Encode and Decode TinyURLMedium

Note: This is a companion problem to the System Design problem: Design TinyURL.

Group AnagramsMedium

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

Longest Consecutive SequenceMedium

Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.

Maximum Number of BalloonsEasy

Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible.

Number of Good PairsEasy

Given an array of integers nums, return the number of good pairs.

Number of Good Ways to Split a StringMedium

You are given a string s.

Number of Matching SubsequencesMedium

Given a string s and an array of strings words, return the number of words[i] that is a subsequence of s.

Ransom NoteEasy

Given two strings ransomNote and magazine, return true* if ransomNote can be constructed by using the letters from magazine and false otherwise*.

Reorganize StringMedium

Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.

Split Array into Consecutive SubsequencesMedium

You are given an integer array nums that is sorted in non-decreasing order.

Two Pointers

ExerciseDifficultyDescription
3SumMedium

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Container With Most WaterMedium

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).

Merge Sorted ArrayEasy

You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.

Trapping Rain WaterHard

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Two Sum II - Input Array Is SortedMedium

Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers b...

Prefix Sum

ExerciseDifficultyDescription
Contiguous ArrayMedium

Given a binary array nums, return *the maximum length of a contiguous subarray with an equal number of 0 and *1.

Continuous Subarray SumMedium

Given an integer array nums and an integer k, return true if nums has a good subarray or false otherwise.

Range Sum Query - ImmutableEasy

Given an integer array nums, handle multiple queries of the following type:

Subarray Sum Equals KMedium

Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.

Subarray Sums Divisible by KMedium

Given an integer array nums and an integer k, return *the number of non-empty subarrays that have a sum divisible by *k.

Sliding Window

ExerciseDifficultyDescription
Find All Anagrams In A StringMedium

Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.

Longest Repeating Character ReplacementMedium

You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.

Longest Substring Without Repeating CharactersMedium

Given a string s, find the length of the longest substring without duplicate characters.

Max Consecutive Ones IIIMedium

Given a binary array nums and an integer k, return the maximum number of consecutive 1s in the array after flipping at most k zeros to ones.

Maximum Average Subarray IEasy

You are given an integer array nums consisting of n elements, and an integer k.

Maximum Sum of Distinct Subarrays With Length KMedium

You are given an integer array nums and an integer k. Find the maximum subarray sum of all the subarrays of nums that meet the following conditions:

Minimum Size Subarray SumMedium

Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such sub...

Minimum Window SubstringHard

Given two strings s and t of lengths m and n respectively, return the minimum window substring* of s such that every character in t (including duplicates) is include...

Permutation in StringMedium

Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.

Substring with Concatenation of All WordsHard

You are given a string s and an array of strings words. All the strings of words are of the same length.

Kadane's Algorithm

ExerciseDifficultyDescription
Best Sightseeing PairMedium

You are given an integer array values where values[i] represents the value of the ith sightseeing spot. Two sightseeing spots i and j have a distance j - i between them.

Maximum Product SubarrayMedium

Given an integer array nums, find a subarray that has the largest product, and return the product.

Maximum Sum Circular SubarrayMedium

Given a circular integer array nums of length n, return *the maximum possible sum of a non-empty subarray of *nums.

Maximum SubarrayMedium

Given an integer array nums, find the subarray with the largest sum, and return its sum.

Matrix (2D Array)

ExerciseDifficultyDescription
Game of LifeMedium

According to Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."

Rotate ImageMedium

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

Set Matrix ZeroesMedium

Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's.

Spiral MatrixMedium

Given an m x n matrix, return all elements of the matrix in spiral order.

Valid SudokuMedium

Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

Linked List

ExerciseDifficultyDescription
Add Two NumbersMedium

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers...

Copy List With Random PointerMedium

A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null.

Design Linked ListMedium

Design your implementation of the linked list. You can choose to use a singly or doubly linked list.

Flatten a Multilevel Doubly Linked ListMedium

You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. This child pointer may or may not point to a separate dou...

Intersection of Two Linked ListsEasy

Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.

Partition ListMedium

Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

Remove Duplicates from Sorted List IIMedium

Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.

Remove Nth Node From End of ListMedium

Given the head of a linked list, remove the nth node from the end of the list and return its head.

Rotate ListMedium

Given the head of a linked list, rotate the list to the right by k places.

Swap Nodes in PairsMedium

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)

Stack

ExerciseDifficultyDescription
Basic Calculator IIMedium

Given a string s which represents an expression, evaluate this expression and return its value.

Evaluate Reverse Polish NotationMedium

You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation.

Longest Valid ParenthesesHard

Given a string containing just the characters '(' and ')', return *the length of the longest valid (well-formed) parentheses *substring.

Min StackMedium

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

Remove All Adjacent Duplicates In StringEasy

You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.

Remove Duplicate LettersMedium

Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.

Removing Stars From a StringMedium

You are given a string s, which contains stars *.

Valid ParenthesesEasy

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

Queue

ExerciseDifficultyDescription
Number of Recent CallsEasy

You have a RecentCounter class which counts the number of recent requests within a certain time frame.

Reveal Cards In Increasing OrderMedium

You are given an integer array deck. There is a deck of cards where every card has a unique integer. The integer on the ith card is deck[i].

Time Needed To Buy TicketsEasy

There are n people in a line queuing to buy tickets, where the 0th person is at the front of the line and the (n - 1)th person is at the back of the line.

Bucket sort

ExerciseDifficultyDescription
Maximum GapMedium

Given an integer array nums, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0.

Sort Characters By FrequencyMedium

Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.

Top K Frequent WordsMedium

Given an array of strings words and an integer k, return the k most frequent strings.

Recursion

ExerciseDifficultyDescription
Decode StringMedium

Given an encoded string, return its decoded string.

Merge Two Sorted ListsEasy

You are given the heads of two sorted linked lists list1 and list2.

Pow(x, n)Medium

Implement pow(x, n), which calculates x raised to the power n (i.e., xn).

Merge Sort

ExerciseDifficultyDescription
Reverse PairsHard

Given an integer array nums, return the number of reverse pairs in the array.

Sort ListMedium

Given the head of a linked list, return the list after sorting it in ascending order.

Quick Sort

ExerciseDifficultyDescription
Kth Largest Element in an ArrayMedium

Given an integer array nums and an integer k, return the kth largest element in the array.

Sort ColorsMedium

Given an array nums with n objects colored red, white, or blue, sort them **in-place **so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

Binary Search

ExerciseDifficultyDescription
Find First and Last Position of Element in Sorted ArrayMedium

Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.

Find in Mountain ArrayHard

(This problem is an interactive problem.)

Find Minimum in Rotated Sorted ArrayMedium

Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:

Find Peak ElementMedium

A peak element is an element that is strictly greater than its neighbors.

Koko Eating BananasMedium

Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours.

Median of Two Sorted ArraysHard

Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

Random Pick with WeightMedium

You are given a 0-indexed array of positive integers w where w[i] describes the weight of the ith index.

Search a 2D MatrixMedium

You are given an m x n integer matrix matrix with the following two properties:

Search in Rotated Sorted ArrayMedium

There is an integer array nums sorted in ascending order (with distinct values).

Search Insert PositionEasy

Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

Backtracking

ExerciseDifficultyDescription
Combination SumMedium

Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You ...

Combination Sum IIMedium

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.

Generate ParenthesesMedium

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Letter Combinations of a Phone NumberMedium

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

N-QueensHard

The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.

Palindrome PartitioningMedium

Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.

PermutationsMedium

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

SubsetsMedium

Given an integer array nums of unique elements, return all possible subsets (the power set).

Tree

ExerciseDifficultyDescription
01 MatrixMedium

Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.

Binary Search Tree IteratorMedium

Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):

Binary Tree Inorder TraversalEasy

Given the root of a binary tree, return the inorder traversal of its nodes' values.

Binary Tree Level Order TraversalMedium

Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).

Binary Tree Maximum Path SumHard

A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that ...

Binary Tree PathsEasy

Given the root of a binary tree, return all root-to-leaf paths in any order.

Binary Tree Postorder TraversalEasy

Given the root of a binary tree, return the postorder traversal of its nodes' values.

Binary Tree Preorder TraversalEasy

Given the root of a binary tree, return the preorder traversal of its nodes' values.

Binary Tree Right Side ViewMedium

Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

Binary Tree Zigzag Level Order TraversalMedium

Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).

Bus RoutesHard

You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever.

Construct Binary Tree from Inorder and Postorder TraversalMedium

Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return *the b...

Construct Binary Tree from Preorder and Inorder TraversalMedium

Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return *the bina...

Convert Sorted Array to Binary Search TreeEasy

Given an integer array nums where the elements are sorted in ascending order, convert *it to a *height-balanced binary search tree.

Count Complete Tree NodesEasy

Given the root of a complete binary tree, return the number of the nodes in the tree.

Delete Nodes And Return ForestMedium

Given the root of a binary tree, each node in the tree has a distinct value.

Diameter of Binary TreeEasy

Given the root of a binary tree, return the length of the diameter of the tree.

Distribute Coins in Binary TreeMedium

You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree.

Find Duplicate SubtreesMedium

Given the root of a binary tree, return all duplicate subtrees.

Flatten Binary Tree to Linked ListMedium

Given the root of a binary tree, flatten the tree into a "linked list":

Invert Binary TreeEasy

Given the root of a binary tree, invert the tree, and return its root.

Kth Smallest Element in a BSTMedium

Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.

Lowest Common Ancestor of a Binary TreeMedium

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

Maximum Difference Between Node and AncestorMedium

Given the root of a binary tree, find the maximum value v for which there exist different nodes a and b where v = |a.val - b.val| and a is an ancestor of b.

Maximum Width of Binary TreeMedium

Given the root of a binary tree, return the maximum width of the given tree.

Minimum Absolute Difference in BSTEasy

Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.

Minimum Distance Between BST NodesEasy

Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.

Open the LockMedium

You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can...

Path Sum IIIMedium

Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum.

Populating Next Right Pointers in Each Node IIMedium

Given a binary tree

Rotting OrangesMedium

You are given an m x n grid where each cell can have one of three values:

Same TreeEasy

Given the roots of two binary trees p and q, write a function to check if they are the same or not.

Serialize and Deserialize Binary TreeHard

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to...

Shortest Path in a Grid with Obstacles EliminationHard

You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step.

Symmetric TreeEasy

Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

Trim a Binary Search TreeMedium

Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not ch...

Validate Binary Search TreeMedium

Given the root of a binary tree, determine if it is a valid binary search tree (BST).

Word LadderHard

A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:

Binary Search Tree and Ordered Set

ExerciseDifficultyDescription
My Calendar IMedium

You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a double booking.

My Calendar IIMedium

You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a triple booking.

Stock Price FluctuationMedium

You are given a stream of records about a particular stock. Each record contains a timestamp and the corresponding price of the stock at that timestamp.

Trim a Binary Search TreeMedium

Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not ch...

Tries

ExerciseDifficultyDescription
Design Add and Search Words Data StructureMedium

Design a data structure that supports adding new words and finding if a string matches any previously added string.

Implement Trie (Prefix Tree)Medium

A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structu...

Longest Word in DictionaryMedium

Given an array of strings words representing an English Dictionary, return the longest word in words that can be built one character at a time by other words in words.

Maximum XOR of Two Numbers in an ArrayMedium

Given an integer array nums, return *the maximum result of *nums[i] XOR nums[j], where 0 <= i <= j < n.

Search Suggestions SystemMedium

You are given an array of strings products and a string searchWord.

Word Search IIHard

Given an m x n board of characters and a list of strings words, return all words on the board.

Heaps

ExerciseDifficultyDescription
Find Median from Data StreamHard

Design a data structure that supports inserting integers from a data stream one at a time and efficiently computing the median of all values added so far.

Furthest Building You Can ReachMedium

Given building heights, a supply of bricks and ladders, travel from building 0 as far as possible by optimally choosing when to spend bricks versus ladders for upward climbs.

IPOHard

Given n projects each with a required capital and profit, starting with w capital and allowed to complete at most k projects, return the maximum capital achievable by greedily picking the highest-profit affordable project at each step.

K Closest Points to OriginMedium

Given an array of 2D points and an integer k, return the k points closest to the origin (0,0) by Euclidean distance.

Kth Largest Element in a StreamEasy

Design a class that maintains a running stream of integers and returns the k-th largest value after each new integer is added.

Process Tasks Using ServersMedium

You have n servers (each with a weight) and m tasks (each with a processing duration). Assign each task to the free server with the smallest weight, breaking ties by index. Return the server index assigned to each task.

Single-Threaded CPUMedium

Given n tasks each with an enqueue time and processing duration, simulate a single-threaded CPU that always picks the shortest available task. Return the order in which tasks are processed.

Sliding Window MedianHard

Given an integer array and a window size k, return the median for each sliding window position as the window moves from left to right across the array.

Top K Frequent ElementsMedium

Given an integer array nums and an integer k, return the k elements that appear most frequently. The answer is guaranteed to be unique.

Intervals

ExerciseDifficultyDescription
Insert IntervalMedium

You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending or...

Maximum Number Of Events That Can Be AttendedMedium

You are given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi.

Merge IntervalsMedium

Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

Minimum Number of Arrows to Burst BalloonsMedium

There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a ballo...

Non Overlapping IntervalsMedium

Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.

K-Way Merge

ExerciseDifficultyDescription
Find K Pairs with Smallest SumsMedium

You are given two integer arrays nums1 and nums2 sorted in non-decreasing order and an integer k.

Kth Smallest Element in a Sorted MatrixMedium

Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix.

Merge k Sorted ListsHard

You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.

Smallest Range Covering Elements from K ListsHard

You have k lists of sorted integers in non-decreasing order. Find the smallest range that includes at least one number from each of the k lists.

Data Structure Design

ExerciseDifficultyDescription
Design a Food Rating SystemMedium

Design a food rating system that supports modifying food ratings and returning the highest-rated food for a given cuisine.

Design Browser HistoryMedium

Design a browser history system that supports visiting URLs, navigating back, and navigating forward through history.

Design TwitterMedium

Design a simplified Twitter where users can post tweets, follow and unfollow others, and retrieve the 10 most recent tweets in their news feed.

Insert Delete GetRandom O(1)Medium

Implement a data structure that supports insert, delete, and getRandom in average O(1) time.

LRU CacheMedium

Design a data structure that follows the constraints of a Least Recently Used (LRU) cache with O(1) get and put operations.

Maximum Frequency StackHard

Design a stack-like data structure that pushes elements and pops the most frequent element, breaking ties by recency.

Snapshot ArrayMedium

Implement a SnapshotArray that supports setting values, taking snapshots, and retrieving the value at a given index for a past snapshot.

Time Based Key-Value StoreMedium

Design a time-based key-value data structure that can store multiple values for the same key at different timestamps.

Greedy Algorithms

ExerciseDifficultyDescription
CandyHard

Given an array of children's ratings, distribute the minimum number of candies so that each child gets at least one and children with higher ratings get more than their neighbors.

Gas StationMedium

Given gas available and cost to travel between stations on a circular route, find the starting station index that allows a complete circuit, or return -1.

Jump Game IIMedium

Given an array where each element represents the maximum forward jump length, find the minimum number of jumps to reach the last index.

Minimum Add to Make Parentheses ValidMedium

Given a parentheses string, determine the minimum number of insertions needed to make it valid.

Minimum Cost to Hire K WorkersHard

Given workers with quality and wage expectations, find the minimum cost to hire exactly k workers while paying proportionally to quality.

Minimum Number of Refueling StopsHard

Given a target distance, starting fuel, and gas stations along the way, find the minimum number of refueling stops to reach the destination.

Task SchedulerMedium

Given CPU tasks with cooldown constraints, find the minimum number of intervals needed to complete all tasks.

Graph

ExerciseDifficultyDescription
01 MatrixMedium

Given a binary matrix, find the distance of each cell to the nearest zero using BFS.

All Nodes Distance K in Binary TreeMedium

Given a binary tree, a target node, and an integer K, return the values of all nodes that are exactly distance K from the target.

All Paths From Source to TargetMedium

Given a directed acyclic graph with n nodes, find all possible paths from node 0 to node n-1.

Bus RoutesHard

Given bus routes and a source and target stop, find the minimum number of buses needed to travel from source to target.

Clone GraphMedium

Given a reference to a node in a connected undirected graph, return a deep copy of the entire graph.

Employee ImportanceMedium

Given a list of employees with importance values and subordinate lists, return the total importance of a given employee and all their subordinates.

Is Graph Bipartite?Medium

Given an undirected graph, determine whether it can be partitioned into two sets such that every edge connects nodes in different sets.

Making A Large IslandHard

Given an n x n binary grid, change at most one 0 to 1 and return the size of the largest island.

Number of IslandsMedium

Given a 2D binary grid representing a map of land and water, return the number of islands formed by horizontally or vertically adjacent land cells.

Open the LockMedium

Given a lock with 4 circular wheels and a list of deadends, find the minimum number of turns to reach the target combination from 0000.

Pacific Atlantic Water FlowMedium

Given a rectangular island height map, find all cells from which water can flow to both the Pacific and Atlantic oceans.

Rotting OrangesMedium

Given a grid of fresh and rotten oranges, determine the minimum time for all fresh oranges to become rotten, or return -1 if impossible.

Shortest Path in a Grid with Obstacles EliminationHard

Find the shortest path in a grid from top-left to bottom-right, with the ability to eliminate up to k obstacles.

Surrounded RegionsMedium

Given a matrix of 'X' and 'O', capture all regions of 'O' that are completely surrounded by 'X' by flipping them to 'X'.

Time Needed to Inform All EmployeesMedium

Given a company hierarchy and inform times, find the total time needed for the head to inform all employees.

Word LadderHard

Given two words and a dictionary, find the length of the shortest transformation sequence where each step changes one letter.

Topological Sort

ExerciseDifficultyDescription
Course Schedule IIMedium

Given a number of courses and their prerequisites, return a valid ordering to complete all courses, or an empty array if impossible.

Find Eventual Safe StatesMedium

Given a directed graph, return all nodes where every possible path leads to a terminal node.

Minimum Height TreesMedium

Given an undirected tree of n nodes, find all root labels that produce trees with the minimum possible height.

Sort Items by Groups Respecting DependenciesHard

Sort n items so that items in the same group are adjacent and all dependency constraints are satisfied.

Union Find

ExerciseDifficultyDescription
Accounts MergeMedium

Given a list of accounts where each account has a name and a list of emails, merge accounts that share a common email and return the merged result.

Minimize Malware SpreadHard

Given a network of nodes and a list of initially infected nodes, find the node whose removal from the infected list minimizes the total spread of malware.

Number of ProvincesMedium

Given an n x n adjacency matrix representing direct connections between cities, return the total number of provinces (groups of directly or indirectly connected cities).

Redundant ConnectionMedium

Given a graph that started as a tree with one extra edge added, find an edge that can be removed so the resulting graph is a tree.

Minimum Spanning Tree

ExerciseDifficultyDescription
Min Cost to Connect All PointsMedium

Find the minimum cost to connect all points on a 2D plane using Manhattan distance.

Shortest Path

ExerciseDifficultyDescription
Cheapest Flights Within K StopsMedium

Find the cheapest price from a source city to a destination with at most k stops.

Network Delay TimeMedium

Find the minimum time for a signal to reach all nodes in a network of directed weighted edges.

Path with Maximum ProbabilityMedium

Find the path with the maximum probability of success between two nodes in an undirected weighted graph.

Path With Minimum EffortMedium

Find the route from top-left to bottom-right of a grid that minimizes the maximum absolute height difference between consecutive cells.

Swim in Rising WaterHard

Find the minimum time to swim from the top-left to the bottom-right of a grid where the water level rises over time.

Eulerian Circuit

ExerciseDifficultyDescription
Cracking the SafeHard

Find a minimum-length string that contains every possible n-digit password over a k-symbol alphabet as a substring.

Reconstruct ItineraryHard

Given a list of airline tickets represented as pairs of departure and arrival airports, reconstruct the itinerary in order starting from JFK.