> 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

ExerciseDescription
Best Time to Buy and Sell Stock

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 II

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 Positive

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 Subsequence

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 Element

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 Zeroes

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 Subarrays

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 Self

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 Array

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

Rotate Array

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

Strings

ExerciseDescription
Guess the Word

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 Subsequence

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

Longest Common Prefix

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

Reverse Words in a String

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

Valid Palindrome

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 Conversion

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

ExerciseDescription
Bitwise AND of Numbers Range

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

Counting Bits

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 Bits

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 Bits

Reverse bits of a given 32 bits signed integer.

Single Number

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

Single Number III

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 Integers

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

Hashtable

ExerciseDescription
Isomorphic Strings

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

Contains Duplicate II

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 HashMap

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

Encode and Decode TinyURL

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

Group Anagrams

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

Longest Consecutive Sequence

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

Maximum Number of Balloons

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 Pairs

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

Number of Good Ways to Split a String

You are given a string s.

Number of Matching Subsequences

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

Ransom Note

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

Reorganize String

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

Split Array into Consecutive Subsequences

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

Two Pointers

ExerciseDescription
3Sum

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 Water

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 Array

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 Water

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 Sorted

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

ExerciseDescription
Contiguous Array

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

Continuous Subarray Sum

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

Range Sum Query - Immutable

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

Subarray Sum Equals K

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 K

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

ExerciseDescription
Find All Anagrams In A String

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 Replacement

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 Characters

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

Max Consecutive Ones III

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 I

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

Maximum Sum of Distinct Subarrays With Length K

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 Sum

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 Substring

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 String

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

Substring with Concatenation of All Words

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

ExerciseDescription
Best Sightseeing Pair

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 Subarray

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

Maximum Sum Circular Subarray

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

Maximum Subarray

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

Matrix (2D Array)

ExerciseDescription
Game of Life

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 Image

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

Set Matrix Zeroes

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

Spiral Matrix

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

Valid Sudoku

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

ExerciseDescription
Add Two Numbers

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 Pointer

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 List

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

Flatten a Multilevel Doubly Linked List

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 Lists

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 List

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 II

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 List

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

Rotate List

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

Swap Nodes in Pairs

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

ExerciseDescription
Basic Calculator II

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

Evaluate Reverse Polish Notation

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

Longest Valid Parentheses

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

Min Stack

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

Remove All Adjacent Duplicates In String

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 Letters

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 String

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

Valid Parentheses

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

Queue

ExerciseDescription
Number of Recent Calls

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

Reveal Cards In Increasing Order

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 Tickets

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

ExerciseDescription
Maximum Gap

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 Frequency

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 Words

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

Recursion

ExerciseDescription
Decode String

Given an encoded string, return its decoded string.

Merge Two Sorted Lists

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

Pow(x, n)

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

Merge Sort

ExerciseDescription
Reverse Pairs

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

Sort List

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

Quick Sort

ExerciseDescription
Kth Largest Element in an Array

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

Sort Colors

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

ExerciseDescription
Find First and Last Position of Element in Sorted Array

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 Array

(This problem is an interactive problem.)

Find Minimum in Rotated Sorted Array

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 Element

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

Koko Eating Bananas

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 Arrays

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

Random Pick with Weight

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

Search a 2D Matrix

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

Search in Rotated Sorted Array

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

Search Insert Position

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

ExerciseDescription
Combination Sum

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 II

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 Parentheses

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

Letter Combinations of a Phone Number

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-Queens

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 Partitioning

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

Permutations

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

Subsets

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

Tree

ExerciseDescription
01 Matrix

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

Binary Search Tree Iterator

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

Binary Tree Inorder Traversal

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

Binary Tree Level Order Traversal

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 Sum

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 Paths

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

Binary Tree Postorder Traversal

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

Binary Tree Preorder Traversal

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

Binary Tree Right Side View

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 Traversal

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 Routes

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 Traversal

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 Traversal

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 Tree

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 Nodes

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

Delete Nodes And Return Forest

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

Diameter of Binary Tree

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

Distribute Coins in Binary Tree

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 Subtrees

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

Flatten Binary Tree to Linked List

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

Invert Binary Tree

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

Kth Smallest Element in a BST

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 Tree

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

Maximum Difference Between Node and Ancestor

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 Tree

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

Minimum Absolute Difference in BST

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 Nodes

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 Lock

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 III

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 II

Given a binary tree

Rotting Oranges

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

Same Tree

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 Tree

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 Elimination

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 Tree

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 Tree

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 Tree

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

Word Ladder

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

ExerciseDescription
My Calendar I

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 II

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 Fluctuation

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 Tree

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

ExerciseDescription
Design Add and Search Words Data Structure

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

Implement Trie (Prefix Tree)

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 Dictionary

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 Array

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

Search Suggestions System

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

Word Search II

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

Heaps

ExerciseDescription
Find Median from Data Stream

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 Reach

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.

IPO

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 Origin

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 Stream

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 Servers

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 CPU

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 Median

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 Elements

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

ExerciseDescription
Insert Interval

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 Attended

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

Merge Intervals

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 Balloons

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 Intervals

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

ExerciseDescription
Find K Pairs with Smallest Sums

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

Kth Smallest Element in a Sorted Matrix

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 Lists

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

Smallest Range Covering Elements from K Lists

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

ExerciseDescription
Design a Food Rating System

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

Design Browser History

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

Design Twitter

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)

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

LRU Cache

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

Maximum Frequency Stack

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

Snapshot Array

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 Store

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

Greedy Algorithms

ExerciseDescription
Candy

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 Station

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 II

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 Valid

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

Minimum Cost to Hire K Workers

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 Stops

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

Task Scheduler

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

Graph

ExerciseDescription
01 Matrix

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

All Nodes Distance K in Binary Tree

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 Target

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

Bus Routes

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

Clone Graph

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

Employee Importance

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?

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 Island

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

Number of Islands

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 Lock

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 Flow

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

Rotting Oranges

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 Elimination

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

Surrounded Regions

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 Employees

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

Word Ladder

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