sorting
sorting is one of the most repeated interview dimensions. Start with edge-safe fundamentals, then move into pattern-level trade-offs.
Interview Signal
Frequently tests problem modeling, edge handling, and verbal clarity.
Common Pitfall
Template-only answers break under follow-up questioning.
Practice Strategy
Practice in 3-5 problem rounds and always review complexity alternatives.
Recommended Progression
Pattern Bridge
High-Pressure Round
3Sum
Given an integer array, return all unique triplets where the sum is zero using two-pointer scanning with careful duplica…
3Sum Closest
Find the sum of three integers in an array that is closest to a given target using two-pointer scanning.
4Sum
The 4Sum problem requires finding all unique quadruplets in an array that sum to a specific target value.
Permutations II
Generate all unique permutations of an array containing duplicates using backtracking and pruning to avoid repeated sequ…
Group Anagrams
Group the anagrams in a list of strings using efficient hash table-based methods, focusing on array scanning.
Merge Intervals
Merge Intervals requires sorting an array of interval pairs and combining overlaps efficiently using sequential comparis…
Sort Colors
Sort Colors requires in-place reordering of an array using a two-pointer scanning strategy to group 0s, 1s, and 2s effic…
Merge Sorted Array
Merge two sorted arrays into the first array in non-decreasing order, using a two-pointer approach.
Insertion Sort List
Sort a singly linked list using insertion sort by carefully manipulating pointers to maintain a sorted order efficiently…
Sort List
Sort List requires sorting a singly linked list efficiently using pointer manipulation and merge sort for optimal perfor…
Maximum Gap
Find the largest difference between successive elements in a sorted array efficiently using linear time techniques and b…
Majority Element
Find the majority element in an array, where the element appears more than n/2 times, using efficient algorithms.
Largest Number
The problem asks to arrange integers to form the largest possible number, focusing on greedy algorithms and string handl…
Kth Largest Element in an Array
Find the kth largest element in an unsorted array using optimal approaches like Quickselect or heaps.
Contains Duplicate
Determine if an integer array contains any duplicate values by efficiently scanning with a hash lookup to ensure fast de…
Contains Duplicate III
The problem involves finding a pair of indices in an array where the index and value differences are within given limits…
Majority Element II
Identify all elements in an integer array appearing more than ⌊ n/3 ⌋ times using efficient array scanning and hash coun…
Valid Anagram
Check if two strings are anagrams using hashing or sorting techniques.
Missing Number
Find the missing number in an array containing distinct numbers in the range [0, n].
H-Index
Determine a researcher's h-index by analyzing citations using array sorting and counting techniques efficiently and accu…
Find Median from Data Stream
Implement a MedianFinder class that supports adding numbers and finding the median from a data stream.
Wiggle Sort II
Rearrange an array in a way that every odd-indexed element is greater than its adjacent even-indexed elements.
Top K Frequent Elements
Find the k most frequent elements from an array using efficient algorithms like hashing and sorting.
Intersection of Two Arrays
Find the intersection of two arrays while ensuring unique elements using efficient array scanning and hash lookups.
Intersection of Two Arrays II
Find the intersection of two arrays, accounting for multiple occurrences of the same number.
Russian Doll Envelopes
Russian Doll Envelopes is a dynamic programming problem that involves finding the longest chain of envelopes that can be…
Largest Divisible Subset
Find the largest subset of distinct positive integers where every pair satisfies divisibility using state transition dyn…
Kth Smallest Element in a Sorted Matrix
Find the kth smallest element in a sorted n x n matrix using efficient binary search or heap strategies for optimized me…
Find the Difference
Find the Difference involves identifying the additional letter in one string compared to another, emphasizing hash table…
Queue Reconstruction by Height
Reconstruct a queue based on the given heights and the number of taller people in front, using sorting and binary indexe…
Third Maximum Number
Find the third distinct maximum number in an array using array traversal and sorting techniques, handling duplicates car…
Non-overlapping Intervals
Determine the minimum number of intervals to remove from a list to ensure no intervals overlap using dynamic programming…
Sort Characters By Frequency
Sort Characters By Frequency requires counting characters efficiently and rearranging a string in descending frequency o…
Minimum Number of Arrows to Burst Balloons
Find the minimum number of arrows needed to burst all balloons by considering greedy choice and invariant validation.
Assign Cookies
Maximize content children by assigning at most one cookie per child using two-pointer scanning and greedy sorting techni…
Minimum Moves to Equal Array Elements II
Find the minimum moves to equalize all array elements using increments or decrements with array and math techniques.
Concatenated Words
Find concatenated words by using dynamic programming and depth-first search to identify valid words made of other words …
Heaters
Determine the minimum heater radius to cover all houses using a binary search over potential radius values efficiently.
IPO
Maximize total capital by selecting up to k projects, based on initial capital and project profits using a greedy strate…
Relative Ranks
Solve Relative Ranks by sorting scores with original indices, then writing medal labels or numeric places back in answer…
Longest Uncommon Subsequence II
Find the longest string in an array that is not a subsequence of any other string, using array scanning and hash checks …
Longest Word in Dictionary through Deleting
Find the longest word in the dictionary that can be formed by deleting characters from a string, using two-pointer scann…
K-diff Pairs in an Array
Solve K-diff Pairs in an Array by counting unique differences with a hash map or sorted two-pointer sweep.
Minimum Time Difference
Calculate the smallest time difference between clock points using array manipulation and mathematical conversions effici…
Array Partition
Maximize the sum of minimums of n pairs in a 2n integer array using a greedy pairing strategy efficiently.
Shortest Unsorted Continuous Subarray
Find the shortest unsorted continuous subarray that, if sorted, would sort the entire array.
Longest Harmonious Subsequence
Find the length of the longest harmonious subsequence in an integer array using array scanning and hash-based frequency …
Valid Triangle Number
Count all triplets in an integer array that satisfy the triangle inequality to form valid triangles efficiently using so…
Task Scheduler
Task Scheduler is solved by counting task frequencies and computing how cooldown gaps force idle slots around the most f…
Maximum Product of Three Numbers
Find three numbers in an array whose product is the largest using sorting and careful handling of negative values.
Course Schedule III
Solve the 'Course Schedule III' problem with a greedy approach involving course selection and validation of constraints.
Smallest Range Covering Elements from K Lists
Find the minimal range covering at least one number from each of k sorted lists using array scanning and hash lookup eff…
Set Mismatch
Identify the duplicated and missing numbers in an integer array using array scanning combined with hash table lookup eff…
Maximum Length of Pair Chain
Determine the maximum length of a chain formed by pairs using dynamic programming and greedy sorting techniques efficien…
Find K Closest Elements
Identify the k integers closest to a target x in a sorted array using binary search and two-pointer strategies efficient…
Top K Frequent Words
Solve Top K Frequent Words by counting each word, then ordering ties alphabetically so frequency wins before lexicograph…
Random Pick with Blacklist
Random Pick with Blacklist requires designing a method to uniformly pick integers while excluding blacklisted values eff…
Find K-th Smallest Pair Distance
Solve Find K-th Smallest Pair Distance by sorting nums, then binary searching the distance and counting valid pairs with…
Longest Word in Dictionary
Find the longest word in a dictionary that can be built one character at a time from other words in the dictionary.
Accounts Merge
Merge accounts by connecting emails and returning each user's sorted email list using array scanning and hash lookup eff…
Number of Atoms
Compute the exact count of each atom in a chemical formula using stack-based state management and hashing techniques eff…
Largest Number At Least Twice of Others
Determine if the largest number in the array is at least twice as large as every other element, and return its index or …
Set Intersection Size At Least Two
Solve the Set Intersection Size At Least Two problem using a greedy approach and invariant validation.
Reorganize String
Reorganize a string so that no two adjacent characters are the same, if possible, using a greedy approach.
Max Chunks To Make Sorted II
Determine the maximum number of chunks you can split an array into so that sorting each chunk results in a fully sorted …
Max Chunks To Make Sorted
The Max Chunks To Make Sorted problem requires you to split an array into the maximum number of chunks that can be sorte…
K-th Smallest Prime Fraction
Find the k-th smallest fraction from a sorted array of unique primes using a binary search over the answer space.
Custom Sort String
Sort the string `s` according to a custom order defined by string `order`.
Number of Matching Subsequences
Given a string s and a list of words, count how many words are subsequences of s using efficient array scanning and hash…
Binary Trees With Factors
Given an array of integers, find how many binary trees can be formed such that non-leaf nodes' values are the product of…
Friends Of Appropriate Ages
The Friends Of Appropriate Ages problem involves counting valid friend requests between people based on their ages with …
Most Profit Assigning Work
Assign workers to jobs maximizing total profit using difficulty, profit, and worker arrays efficiently with binary searc…
Find And Replace in String
This problem challenges you to perform multiple string replacements at specific indices using a pattern involving array …
Hand of Straights
Check if a hand of cards can be rearranged into groups of consecutive values.
Car Fleet
The Car Fleet problem asks how many car fleets will reach a target given their starting positions and speeds, considerin…
Minimum Cost to Hire K Workers
Find the minimum cost to hire exactly k workers based on quality and wage expectations in this challenging greedy proble…
Reordered Power of 2
Determine if a number's digits can be rearranged to form a power of two using counting and hash-based checks.
Advantage Shuffle
Maximize the advantage of nums1 over nums2 using a two-pointer greedy strategy, carefully tracking which elements beat o…
Boats to Save People
Find the minimum number of boats required to save all people, using a two-pointer approach for efficient pairing.
Fair Candy Swap
Determine which single candy box Alice and Bob should swap to equalize their total candies using array scanning and hash…
Sum of Subsequence Widths
Calculate the sum of widths for all subsequences in an integer array using sorting and combinatorial math efficiently.
Groups of Special-Equivalent Strings
Determine the number of special-equivalent string groups using character swaps at even or odd indices efficiently.
Orderly Queue
Given a string and integer k, rearrange characters to achieve the lexicographically smallest string using limited rotati…
Sort Array By Parity
Reorder an integer array so all even numbers come before odd numbers using a precise two-pointer scanning method.
Smallest Range II
Determine the minimum possible difference between the largest and smallest numbers after adjusting each by plus or minus…
Sort an Array
Sort an array using an optimal algorithm, focusing on time and space complexity considerations.
Sort Array By Parity II
Sort an array where even numbers appear at even indices and odd numbers appear at odd indices using two-pointer scanning…
3Sum With Multiplicity
Count all unique triplets in an integer array whose sum equals the target, handling multiplicity efficiently using hashi…
Reorder Data in Log Files
Reorder Data in Log Files requires sorting letter-logs lexicographically while keeping digit-logs in original order for …
Minimum Area Rectangle
Find the minimum area of a rectangle formed by given points on a 2D plane with sides parallel to axes.
Minimum Increment to Make Array Unique
This problem challenges you to find the minimum moves to make all elements in an array unique by incrementing elements.
Bag of Tokens
Maximize your score in the Bag of Tokens problem by strategically playing tokens with two-pointer scanning and greedy te…
Reveal Cards In Increasing Order
Determine the initial deck order to reveal cards in strictly increasing order using queue-driven simulation logic.
Array of Doubled Pairs
Given an array of even length, check if it can be reordered to satisfy a specific doubling condition.
Pancake Sorting
Sort an array using pancake flips, leveraging two-pointer scanning and invariant tracking to iteratively position the la…
K Closest Points to Origin
Find the k closest points to the origin in a 2D plane using array operations and Euclidean distance calculations efficie…
Odd Even Jump
Determine the number of valid starting indices in an array where you can reach the end with alternating odd and even jum…
Largest Perimeter Triangle
Given an integer array, find the largest perimeter of a triangle formed from three of these lengths.
Squares of a Sorted Array
The problem involves squaring elements of a sorted array and returning the squares in non-decreasing order.
Vertical Order Traversal of a Binary Tree
Perform a vertical order traversal of a binary tree, sorting nodes by their values within columns.
Maximize Sum Of Array After K Negations
Maximize the sum of an integer array after exactly k negations using a greedy approach and invariant tracking for optima…
Two City Scheduling
Two City Scheduling requires selecting optimal city assignments for 2n people to minimize total travel costs efficiently…
Matrix Cells in Distance Order
Compute all matrix cell coordinates sorted by Manhattan distance from a given center using array and math techniques eff…
Moving Stones Until Consecutive II
Determine the minimum and maximum moves to make stones consecutive using sliding window and endpoint adjustments efficie…
Longest String Chain
Find the longest word chain by scanning arrays and using hash lookups to efficiently track predecessor-successor sequenc…
Height Checker
Determine how many students are out of place in a line by comparing their heights to the sorted expected order efficient…
Distant Barcodes
Rearrange barcodes in an array so that no two adjacent elements are equal, using a greedy approach and hash table for ef…
Largest Values From Labels
Maximize the sum of selected item values while respecting label use limits using array scanning and hash tracking.
Car Pooling
Determine if a car can handle multiple trips without exceeding its capacity using array sorting and event simulation tec…
Relative Sort Array
Sort arr1 by the relative order of arr2, with remaining elements placed in ascending order.
Invalid Transactions
Detect invalid transactions by scanning arrays and cross-checking with hash tables for time, amount, and city conflicts …
Compare Strings by Frequency of the Smallest Character
Compare Strings by Frequency of the Smallest Character requires counting minimal character frequencies in words and quer…
Make Array Strictly Increasing
Determine the minimum operations to transform arr1 into a strictly increasing sequence using values from arr2 efficientl…
Minimum Absolute Difference
Find all pairs with the minimum absolute difference between two elements in an array, and return them in ascending order…
Smallest String With Swaps
Find the lexicographically smallest string by swapping characters in given pairs of indices.
Maximum Profit in Job Scheduling
Compute the maximum profit from non-overlapping jobs using state transition dynamic programming with sorted arrays and b…
Greatest Sum Divisible by Three
Find the maximum sum divisible by three from a given array using dynamic programming and state transition.
Search Suggestions System
Design a search suggestion system that provides the top three lexicographically smallest products matching a search word…
Remove Covered Intervals
Remove all intervals fully covered by another using sorting and linear traversal, counting only distinct remaining inter…
Divide Array in Sets of K Consecutive Numbers
Determine if an integer array can be partitioned into sets of k consecutive numbers using array scanning and hash mappin…
Sum of Mutated Array Closest to Target
Find the integer that mutates all larger elements in an array to minimize the sum difference to a target efficiently.
All Elements in Two Binary Search Trees
Merge elements from two binary search trees and return them sorted in ascending order.
Get Watched Videos by Your Friends
Find videos watched by friends up to a given level and return them sorted by frequency and alphabetically.
Sort the Matrix Diagonally
Sort each diagonal of a matrix in ascending order, applying sorting and matrix traversal techniques.
Rank Transform of an Array
Transform the elements of an array into their ranks, where the rank represents the size order of the elements.
Filter Restaurants by Vegan-Friendly, Price and Distance
Filter restaurants by vegan-friendly status, price, and distance, and sort them by rating and ID.
The K Weakest Rows in a Matrix
Find the k weakest rows in a binary matrix where rows contain soldiers and civilians, using sorting and binary search te…
Reduce Array Size to The Half
This problem asks to minimize the set of integers removed to reduce an array's size to at least half by removing occurre…
Jump Game V
Jump Game V is a hard dynamic programming problem that focuses on maximizing jumps between indices in an array.
Check If N and Its Double Exist
Solve Check If N and Its Double Exist by scanning once and checking doubles or halves in a hash set.
Tweet Counts Per Frequency
Design an efficient solution to track and retrieve tweet counts over different frequencies using binary search and hash …
Maximum Number of Events That Can Be Attended
Maximize the number of events you can attend given their start and end days using a greedy strategy.
Sort Integers by The Number of 1 Bits
Sort an array of integers by the number of 1's in their binary representation and then by their value in case of ties.
Largest Multiple of Three
Find the largest number divisible by three by selecting and ordering digits optimally using state transition dynamic pro…
How Many Numbers Are Smaller Than the Current Number
In this problem, you need to determine how many numbers are smaller than each element in an array, focusing on array sca…
Rank Teams by Votes
Rank Teams by Votes requires counting position-based votes and resolving ties with array scanning and hash lookup techni…
Maximum Performance of a Team
Maximize the performance of a team by selecting up to k engineers with the highest performance based on speed and effici…
Find the Distance Value Between Two Arrays
Calculate the distance value between two integer arrays by determining how many elements in arr1 don't have a close coun…
Sort Integers by The Power Value
Sort integers in a range based on their power value using dynamic programming and memoization, handling ties with ascend…
Reducing Dishes
Maximize the sum of like-time coefficients by optimally choosing dishes to prepare in this dynamic programming problem.
Minimum Subsequence in Non-Increasing Order
Find the minimum subsequence in non-increasing order such that its sum exceeds the sum of non-included elements.
Display Table of Food Orders in a Restaurant
Generate a restaurant display table from orders by counting each food item per table using array scanning and hash looku…
Diagonal Traverse II
Traverse a jagged 2D array diagonally by grouping elements with equal row and column sums efficiently using sorting and …
Check If a String Can Break Another String
This problem checks whether one string can break another using permutations and a greedy approach for comparison.
Rearrange Words in a Sentence
Rearrange words in a sentence by their length, maintaining original order for words of equal size for consistent output.
Make Two Arrays Equal by Reversing Subarrays
Solve Make Two Arrays Equal by Reversing Subarrays by checking whether target and arr contain the same values with match…
Maximum Product of Two Elements in an Array
Find the maximum product of two elements in an array by carefully selecting indices and leveraging sorting for efficienc…
Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
Maximize the area of a piece of cake after specified horizontal and vertical cuts using greedy algorithms and sorting.
The k Strongest Values in an Array
Identify the k strongest values in an array using two-pointer scanning and careful tracking of the array's centre value.
Allocate Mailboxes
Allocate k mailboxes to houses along a street minimizing total distance using dynamic programming with state transitions…
Least Number of Unique Integers after K Removals
Find the least number of unique integers after removing exactly k elements from an array using efficient frequency count…
Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree
Identify critical and pseudo-critical edges in a weighted graph's minimum spanning tree using Union Find efficiently.
Average Salary Excluding the Minimum and Maximum Salary
Calculate the average salary of employees, excluding the highest and lowest salaries, from an array of unique salaries.
Number of Subsequences That Satisfy the Given Sum Condition
Count all non-empty subsequences in an integer array where the sum of the minimum and maximum elements is at most a targ…
Can Make Arithmetic Progression From Sequence
Determine if a given array can be rearranged into a valid arithmetic progression using sorting and consecutive differenc…
Range Sum of Sorted Subarray Sums
Compute the sum of sorted subarray sums efficiently using binary search over valid sum ranges and prefix sum accumulatio…
Minimum Difference Between Largest and Smallest Value in Three Moves
Find the minimum difference between the largest and smallest values in an array after performing at most three moves.
Minimum Cost to Cut a Stick
Find the minimum cost to cut a stick into segments at specified positions using dynamic programming and sorting.
Magnetic Force Between Two Balls
Maximize the minimum magnetic force between balls by strategically placing them in baskets using binary search on positi…
Maximum Number of Coins You Can Get
Solve the Maximum Number of Coins You Can Get using greedy pile selection and invariant validation to maximize your coin…
Check If String Is Transformable With Substring Sort Operations
This problem requires checking if string 's' can be transformed into string 't' using substring sort operations.
Maximum Sum Obtained of Any Permutation
Maximize the total sum of requests on nums by greedily assigning larger numbers to most frequently requested indices.
Alert Using Same Key-Card Three or More Times in a One Hour Period
Solve LeetCode 1604 by grouping swipe times per employee, sorting each list, and scanning for any three within 60 minute…
Special Array With X Elements Greater Than or Equal X
Determine if an array has exactly x elements greater than or equal to x using binary search over the answer space.
Maximum Number of Visible Points
Determine the maximum number of points visible from a fixed location within a given angle using a sliding window approac…
Mean of Array After Removing Some Elements
Calculate the trimmed mean by removing the lowest and highest 5% of elements in an array using sorting for accuracy and …
Best Team With No Conflicts
Find the highest score basketball team by choosing players without conflicts in age and score using dynamic programming.
Arithmetic Subarrays
Determine whether subarrays of a given array can be rearranged to form arithmetic sequences using array scanning and has…
Rank Transform of a Matrix
Compute a unique rank matrix using graph indegree with topological ordering, ensuring each element reflects its relative…
Sort Array by Increasing Frequency
Sort Array by Increasing Frequency requires counting each element and ordering them by frequency, breaking ties with des…
Widest Vertical Area Between Two Points Containing No Points
Find the maximum width of a vertical area between points with no points inside using array sorting efficiently.
Minimum Deletions to Make Character Frequencies Unique
Determine the minimum deletions needed to ensure all character frequencies in a string are unique using a greedy approac…
Sell Diminishing-Valued Colored Balls
Maximize total value by greedily selling diminishing-valued colored balls based on inventory and customer orders.
Determine if Two Strings Are Close
Check if two strings can transform into each other using letter swaps and frequency reorganizations, leveraging hash tab…
Minimum Initial Energy to Finish Tasks
Determine the minimum initial energy needed to finish all tasks using a greedy ordering based on required versus actual …
Max Number of K-Sum Pairs
Max Number of K-Sum Pairs is a problem involving counting disjoint pairs with a given sum k in an array.
Stone Game VI
Determine the winner in Stone Game VI using a greedy strategy that accounts for each stone's dual value impact on Alice …
Maximum Height by Stacking Cuboids
Maximize the height of stacked cuboids by strategically rotating and stacking them using dynamic programming.
Checking Existence of Edge Length Limited Paths
Solve the problem of checking if there exists a path between two nodes under edge length constraints using efficient tec…
Maximum Units on a Truck
Maximize total units loaded on a truck by choosing boxes greedily based on highest units per box within truck capacity l…
Largest Submatrix With Rearrangements
Rearrange columns of a binary matrix to find the largest submatrix of 1s.
Find Kth Largest XOR Coordinate Value
Compute the kth largest XOR coordinate in a 2D matrix using prefix sums, bit manipulation, and optimized selection techn…
Maximum Number of Events That Can Be Attended II
Determine the maximum sum of event values you can collect by attending at most k non-overlapping events using DP.
Closest Subsequence Sum
Find the minimum absolute difference between a target goal and any subsequence sum using optimized dynamic programming a…
Count Pairs Of Nodes
Given a graph with nodes and edges, count pairs of nodes where the degree sum exceeds a given threshold for each query.
Maximum Number of Consecutive Values You Can Make
Find the maximum number of consecutive integer values starting from zero that can be formed using your coins array.
Minimum Absolute Sum Difference
Minimize the absolute sum difference between two integer arrays by replacing at most one element from the first array.
Maximum Ice Cream Bars
Maximize the number of ice cream bars a boy can buy by applying a greedy choice strategy based on cost sorting.
Single-Threaded CPU
Simulate task processing with a single-threaded CPU by sorting and prioritizing tasks based on arrival and processing ti…
Frequency of the Most Frequent Element
Maximize the frequency of an element in an array by incrementing at most `k` elements. Use binary search and greedy tech…
Maximum Building Height
Find the maximum building height in a city given height restrictions for specific buildings.
Maximum Element After Decreasing and Rearranging
Determine the maximum value in an array after decreasing elements and rearranging using a greedy invariant approach.
Closest Room
Find the closest hotel room meeting minimum size requirements using binary search over the valid answer space efficientl…
Minimum Interval to Include Each Query
Find the smallest interval containing each query efficiently using binary search.
Sorting the Sentence
Reconstruct a shuffled sentence by sorting words using their embedded indices to restore the original sentence order eff…
Minimize Maximum Pair Sum in Array
Minimize the maximum pair sum in an array by optimally pairing its elements.
Get Biggest Three Rhombus Sums in a Grid
Find the three largest distinct rhombus sums from a given grid using array and math techniques.
Reduction Operations to Make the Array Elements Equal
Find the minimum number of operations to make all array elements equal by reducing the largest elements to the next smal…
Minimum Space Wasted From Packaging
Minimize the wasted space when packaging items into boxes, considering package and box size constraints.
Maximum Product Difference Between Two Pairs
Find the maximum product difference between two pairs in an integer array using sorting for optimal selection.
Eliminate Maximum Number of Monsters
Eliminate monsters by strategically using a weapon in a video game to stop them before they reach your city.
Describe the Painting
Solve the problem of describing a painted segment with mixed colors using array scanning and hash table lookups.
Array With Elements Not Equal to Average of Neighbors
Rearrange an array such that no element equals the average of its neighbors using a greedy approach.
Minimum Difference Between Highest and Lowest of K Scores
Minimize the difference between the highest and lowest of k student scores using a sliding window approach.
Find the Kth Largest Integer in the Array
This problem asks to find the kth largest integer in an array of string numbers, highlighting sorting and string-based c…
The Number of Weak Characters in the Game
Identify all weak characters in a game by analyzing attack and defense values using a stack-based greedy sorting approac…
GCD Sort of an Array
The GCD Sort problem challenges you to sort an array using a specific gcd-based swap method.
Find Original Array From Doubled Array
Given a shuffled array, determine if it is a doubled array and find the original array.
Maximum Earnings From Taxi
Maximize earnings by optimizing taxi ride selection and tips using array scanning, hash lookups, and sorting.
Minimum Operations to Make a Uni-Value Grid
Determine the fewest additions or subtractions of x to make all grid elements identical using array and math logic.
Minimum Number of Moves to Seat Everyone
Calculate the minimum total moves to seat each student using greedy assignment and invariant validation efficiently.
Two Best Non-Overlapping Events
Maximize the total value of at most two non-overlapping events using state transition dynamic programming efficiently.
Most Beautiful Item for Each Query
Determine the maximum beauty of items affordable for each query using efficient binary search and sorting techniques.
Maximum Number of Tasks You Can Assign
Maximize the number of tasks that can be completed by efficiently using workers and magical pills.
Find Target Indices After Sorting Array
Find the target indices of a sorted array and return them in increasing order using binary search and sorting techniques…
Find All People With Secret
Find all people who receive a secret through meetings using graph traversal with depth-first search efficiently and corr…
Finding 3-Digit Even Numbers
Generate unique 3-digit even numbers from a given array of digits with duplicates.
Find Subsequence of Length K With the Largest Sum
Pick the k largest values, then restore their original order to build the maximum-sum subsequence correctly.
Recover the Original Array
Recover the Original Array helps you understand how to reverse-engineer an array from two subsets using array scanning a…
Destroying Asteroids
This problem requires destroying asteroids by choosing the right order of collisions based on mass, using a greedy appro…
Count Words Obtained After Adding a Letter
Given startWords and targetWords, check how many targetWords can be formed by adding one letter and rearranging letters …
Earliest Possible Day of Full Bloom
Find the earliest day where all flower seeds are blooming based on their planting and growth times, using a greedy strat…
Maximum Running Time of N Computers
Solve the problem of determining the maximum running time of n computers using a set of batteries.
Minimum Cost of Buying Candies With Discount
Minimize the total cost of buying candies using a greedy approach with a discount system based on candy prices.
K Highest Ranked Items Within a Price Range
Use BFS to rank reachable shop items by distance, price, row, and column, then return the best k coordinates.
Count Elements With Strictly Smaller and Greater Elements
Count elements in an array that have both strictly smaller and strictly greater numbers using array sorting efficiently.
Keep Multiplying Found Values by Two
The "Keep Multiplying Found Values by Two" problem involves repeatedly multiplying a number by two if it is found in an …
Minimum Sum of Four Digit Number After Splitting Digits
Find the minimum sum of two 2-digit numbers by splitting a four-digit number into two integers.
Sort Even and Odd Indices Independently
Rearrange a 0-indexed array by sorting even and odd indices independently for predictable order and correctness.
Smallest Value of the Rearranged Number
Rearrange the digits of an integer to minimize its value while avoiding leading zeros, keeping the sign unchanged.
Removing Minimum Number of Magic Beans
Determine the minimum beans to remove so all remaining non-empty bags have equal beans using a greedy approach.
Sort the Jumbled Numbers
Sort numbers based on a custom mapping of their digits, leveraging array manipulation and sorting techniques.
Append K Integers With Minimal Sum
In this problem, you need to append k unique positive integers to a given array nums such that the sum is minimized.
Find Players With Zero or One Losses
Identify players with zero or one losses by efficiently scanning arrays and counting losses using hash lookups for accur…
Largest Number After Digit Swaps by Parity
Maximize a number by swapping digits of the same parity using sorting and priority queue techniques efficiently.
Maximum Total Beauty of the Gardens
Determine the maximum total beauty of gardens by strategically planting flowers using binary search over achievable flow…
Maximum Score of a Node Sequence
Find the maximum score of a valid node sequence in an undirected graph with given node scores and edges.
Intersection of Multiple Arrays
Find integers that are common across all arrays in a given list of arrays.
Count Number of Rectangles Containing Each Point
Given a set of rectangles and points, determine how many rectangles contain each point.
Number of Flowers in Full Bloom
Find the number of flowers in full bloom at the given times for a list of people.
Maximum White Tiles Covered by a Carpet
Solve Maximum White Tiles Covered by a Carpet by sorting intervals, checking optimal carpet starts, and counting full pl…
Find Resultant Array After Removing Anagrams
This problem requires removing adjacent anagrams from a list of words using an array scanning and hash lookup approach.
Maximum Consecutive Floors Without Special Floors
Find the maximum sequence of consecutive floors without any special floors using array sorting techniques efficiently.
Maximum Bags With Full Capacity of Rocks
Maximize the number of bags filled to capacity by distributing additional rocks using a greedy approach.
Minimum Lines to Represent a Line Chart
Determine the fewest lines needed to accurately connect stock price points in a line chart using array and math reasonin…
Maximum Total Importance of Roads
Assign unique values to cities to maximize the total importance of all roads using greedy selection based on city connec…
Partition Array Such That Maximum Difference Is K
Find the minimum number of subsequences required such that the difference between the maximum and minimum value in each …
Successful Pairs of Spells and Potions
Count how many potions pair successfully with each spell using binary search over sorted potion strengths efficiently.
The Latest Time to Catch a Bus
Find the latest time to catch a bus based on departure times, passenger arrivals, and capacity using binary search over …
Minimum Sum of Squared Difference
Calculate the minimum sum of squared differences between two arrays using limited modifications and binary search techni…
Minimum Amount of Time to Fill Cups
Determine the minimum seconds to fill cups of cold, warm, and hot water using a greedy selection strategy and invariant …
Max Sum of a Pair With Equal Sum of Digits
Find the maximum sum of two numbers with equal digit sums in a given array of positive integers.
Query Kth Smallest Trimmed Number
Solve the Query Kth Smallest Trimmed Number problem by efficiently trimming and sorting strings in an array to answer qu…
Minimum Deletions to Make Array Divisible
Find the minimum number of deletions to make the smallest element in nums divide all elements of numsDivide.
Make Array Zero by Subtracting Equal Amounts
Minimize operations to make all array elements zero by subtracting equal amounts in each operation.
Merge Similar Items
Merge Similar Items combines values and weights from two lists, returning the result sorted by value.
Find the K-Sum of an Array
Find the K-Sum of an Array requires computing the kth largest subsequence sum in an array using sorting and heap techniq…
Longest Subsequence With Limited Sum
Find the maximum size of a subsequence from nums with a sum less than or equal to each query value.
Meeting Rooms III
Determine which meeting room holds the most meetings by simulating room assignments with precise time tracking.
Divide Intervals Into Minimum Number of Groups
Determine the minimum number of non-overlapping groups for a set of intervals using precise two-pointer scanning logic.
Maximum Matching of Players With Trainers
Maximize the number of valid player-trainer matchings using two-pointer scanning and careful sorting strategy.
Minimum Money Required Before Transactions
Find the minimum money required to complete all transactions in any order while considering cost and cashback.
Sort the People
Sort the People requires pairing names with heights and sorting them in descending height order efficiently using arrays…
Number of Good Paths
Count all good paths in a tree by scanning node values and using hash maps to track valid connections efficiently.
Largest Positive Integer That Exists With Its Negative
Find the largest positive integer in an array such that its negative counterpart also exists.
Minimum Cost to Make Array Equal
Find the minimum cost to make all elements of an array equal by using binary search over valid answers.
Minimum Number of Operations to Make Arrays Similar
Determine the minimum operations to make two arrays similar by adjusting pairs while respecting element frequencies and …
Next Greater Element IV
Find the second greater integer for each element in an array using binary search and monotonic stack techniques.
Most Popular Video Creator
Identify the most popular video creator by summing views and selecting their top-viewed video with array and hash patter…
Minimum Total Distance Traveled
Optimize the total distance traveled by robots to factories using dynamic programming, sorting, and state transitions.
Number of Distinct Averages
Calculate the number of unique averages formed by repeatedly pairing smallest and largest elements efficiently using has…
Number of Unequal Triplets in Array
Count all triplets in a positive integer array where each element is distinct using scanning and hash lookup efficiently…
Divide Players Into Teams of Equal Skill
Divide players into equal skill teams and return the sum of their chemistry, or -1 if impossible.
Maximum Star Sum of a Graph
Find the maximum star sum in a graph with specific node values and edges, using greedy algorithms to select the optimal …
Delete Greatest Value in Each Row
Calculate the total of removed maximum values from each row of a matrix, iterating until all columns are deleted efficie…
Longest Square Streak in an Array
Find the length of the longest subsequence where each element is a perfect square of its previous one.
Maximum Number of Points From Grid Queries
Solve the Maximum Number of Points From Grid Queries problem using two-pointer scanning and invariant tracking.
Reward Top K Students
Calculate top K student scores by scanning reports and using hash tables for positive and negative word lookups efficien…
Maximum Tastiness of Candy Basket
Maximize the tastiness of a candy basket by choosing k candies from a list of candy prices.
Maximum Subsequence Score
Maximize the score of a subsequence by selecting indices based on nums1 and nums2, using a greedy approach and sorting.
Sort the Students by Their Kth Score
Sort a matrix of student scores by the kth exam efficiently using array manipulation and custom sorting techniques.
Put Marbles in Bags
The "Put Marbles in Bags" problem challenges you to distribute marbles into bags for maximum score difference using gree…
Maximum Number of Integers to Choose From a Range I
Determine the maximum count of integers from 1 to n avoiding banned numbers while keeping the sum under maxSum.
Count the Number of Fair Pairs
Efficiently count all fair pairs in an array using sorting and binary search, focusing on the sum range between lower an…
Minimum Score by Changing Two Elements
The problem asks for the minimum score after changing two elements of an array using a greedy approach.
Find the Maximum Number of Marked Indices
Maximize marked indices in an array by performing allowed operations, applying binary search to find the optimal count e…
Split With Minimum Sum
Split a positive integer into two parts to minimize their sum using a greedy approach and sorting.
Count Ways to Group Overlapping Ranges
Count Ways to Group Overlapping Ranges is a medium difficulty problem focused on array manipulation and sorting to count…
Kth Largest Sum in a Binary Tree
Find the kth largest level sum in a binary tree using level-order traversal and sorting.
Rearrange Array to Maximize Prefix Score
Maximize the number of positive prefix sums by rearranging an integer array using a greedy, order-focused strategy.
Minimum Time to Complete All Tasks
Determine the minimum active time for a computer to complete all scheduled tasks within their specific time windows effi…
Maximize Greatness of an Array
Maximize Greatness of an Array requires permuting numbers to exceed original values at most indices efficiently.
Find Score of an Array After Marking All Elements
The problem involves marking elements in an array and calculating the score based on adjacent elements.
The Number of Beautiful Subsets
Count all non-empty subsets of an array where no two numbers have an absolute difference equal to k, using array scannin…
Minimum Operations to Make All Array Elements Equal
Find the minimum number of operations to make all elements in an array equal for each query.
Make K-Subarray Sums Equal
Solve Make K-Subarray Sums Equal by grouping circular indices with gcd cycles and minimizing each group to its median.
Mice and Cheese
In 'Mice and Cheese', you must maximize the total reward of two mice eating cheese while respecting their preferences an…
Minimize the Maximum Difference of Pairs
Minimize the Maximum Difference of Pairs seeks to optimize the maximum pairwise difference in a set of index pairs from …
Make Array Empty
Solve the "Make Array Empty" problem using binary search to determine the minimum number of operations required.
Sum in a Matrix
Calculate the maximum score by repeatedly removing the largest elements from each row of a 2D matrix efficiently using s…
Power of Heroes
Calculate the total power of all non-empty hero groups using state transition dynamic programming efficiently with sorti…
Buy Two Chocolates
Determine the leftover money after buying exactly two chocolates using a greedy selection and sum validation approach.
Maximum Strength of a Group
Maximize the strength of a student group by carefully selecting students based on their scores, using dynamic programmin…
Maximum Strictly Increasing Cells in a Matrix
Find the maximum number of cells that can be visited in a matrix by following strictly increasing values from a starting…
Movement of Robots
Calculate total distances between robots moving on a number line while accounting for collisions using array plus braint…
Neither Minimum nor Maximum
Find a number in an array that is neither the minimum nor maximum value, or return -1 if no such number exists.
Maximum Sum Queries
Find the maximum sum of paired elements from two arrays under query constraints using efficient binary search techniques…
Find the Value of the Partition
Find the minimum partition value by dividing a positive integer array into two subarrays using sorting for efficiency.
Count Zero Request Servers
Count Zero Request Servers finds the number of servers with zero requests during specific time intervals for a given set…
Robot Collisions
Robot Collisions involves simulating robot movements and handling collisions with stack-based state management.
Relocate Marbles
Relocate marbles to new positions in an array by simulating moves, and return sorted occupied positions.
Maximum Beauty of an Array After Applying Operation
Find the maximum beauty of an array by adjusting elements within a range using binary search and sliding window techniqu…
Minimum Index of a Valid Split
Find the minimum index to split an array such that both subarrays have the same dominant element.
Check if Array is Good
Determine if a given integer array is a permutation of base[n], containing 1 to n-1 once and n twice, using scanning and…
Sort Vowels in a String
Sort Vowels in a String requires identifying vowels in a string and rearranging them in ascending order while keeping co…
Maximum Number of Groups With Increasing Length
Maximize the number of groups that can be formed with given usage limits, leveraging binary search for optimal solutions…
Minimum Time to Make Array Sum At Most x
Calculate the minimum seconds to reduce the array sum to at most x using optimal single-time reductions per index effici…
Maximum Elegance of a K-Length Subsequence
Maximize elegance of a k-length subsequence from a list of items with profits and categories.
Apply Operations to Maximize Score
Maximize the score by applying operations on a subarray at most k times, utilizing stack-based state management.
Count Pairs Whose Sum is Less than Target
This problem asks you to count all index pairs in an array whose sum is strictly less than a given target value efficien…
Maximize the Profit as the Salesman
Determine the maximum profit a salesman can earn by strategically selecting non-overlapping offers on consecutive houses…
Check if Strings Can be Made Equal With Operations II
Check if two strings can be made equal using operations that swap characters with the same parity.
Happy Students
The Happy Students problem asks how many ways a teacher can select a group of students so everyone is happy, based on ce…
Minimum Processing Time
Determine the minimum total processing time by optimally assigning tasks to multiple processors using a greedy approach.
Maximum Spending After Buying Items
Maximize spending by carefully choosing the right items across multiple shops over m * n days.
High-Access Employees
Identify employees with high system access within one-hour periods based on access logs.
Maximize Area of Square Hole in Grid
Learn how to maximize the area of a square-shaped hole by selectively removing horizontal and vertical bars efficiently …
Make Lexicographically Smallest Array by Swapping Elements
Solve the problem of making an array lexicographically smallest through element swaps under a limit constraint.
Minimum Number of Coins to be Added
Determine the minimum number of coins to add so all values up to target are obtainable using a greedy sum approach.
Divide Array Into Arrays With Max Difference
Divide an array into subarrays with a maximum element difference under a given threshold using a greedy approach.
Minimum Cost to Make Array Equalindromic
Determine the minimum cost to convert an integer array into a palindromic array using allowed element modifications effi…
Apply Operations to Maximize Frequency Score
Maximize the frequency score by applying up to k operations on a sorted array using binary search over valid answer spac…
Find Polygon With the Largest Perimeter
Determine the largest perimeter polygon from a set of side lengths using a greedy approach with invariant validation che…
Find Number of Coins to Place in Tree Nodes
Determine the exact number of coins to place on each tree node using subtree cost products and DFS tracking.
Minimum Number Game
The Minimum Number Game involves simulating moves by Alice and Bob on an array, sorting elements and appending them to a…
Smallest Missing Integer Greater Than Sequential Prefix Sum
Find the smallest missing integer greater than the sum of the longest sequential prefix in an array.
Divide an Array Into Subarrays With Minimum Cost I
Divide an array into three contiguous subarrays with minimum cost by leveraging array and sorting principles.
Find if Array Can Be Sorted
Determine if a given array can be sorted using adjacent swaps restricted by equal set bits in binary representation.
Minimum Number of Pushes to Type Word II
Given a word, find the minimum number of pushes to type it on a remapped keypad using a greedy approach.
Type of Triangle
Determine the type of triangle from a three-element array using side sums and equality checks efficiently in constant ti…
Find the Number of Ways to Place People I
Calculate how many valid pairs of points can be formed on a 2D plane using array and math enumeration techniques efficie…
Find the Number of Ways to Place People II
Calculate all valid placements of people on a 2D grid ensuring Alice can fence herself with Bob without enclosing others…
Maximum Palindromes After Operations
The problem focuses on maximizing the number of palindromes that can be formed from a given list of words through specif…
Apply Operations to Make String Empty
Learn how to systematically apply operations on a string using array scanning and hash lookups to reduce it efficiently.
Maximize Consecutive Elements in an Array After Modification
Solve Maximize Consecutive Elements in an Array After Modification by sorting and using state transition DP on value and…
Find the Maximum Sum of Node Values
Solve Find the Maximum Sum of Node Values by tracking XOR gain parity, not by simulating edge operations across the tree…
Apple Redistribution into Boxes
Distribute packs of apples into boxes using a greedy strategy, minimizing the number of boxes selected efficiently and c…
Maximize Happiness of Selected Children
Maximize the happiness of selected children by choosing the k happiest ones and applying greedy strategies to minimize l…
Mark Elements on Array by Performing Queries
Efficiently mark elements in an array based on queries using scanning plus hash lookup to track marked indices and compu…
Replace Question Marks in String to Minimize Its Value
Minimize the cost of a string with '?' characters by replacing them with letters in lexicographical order while minimizi…
Minimum Deletions to Make String K-Special
Minimize deletions to make a string k-special by adjusting character frequencies.
Find the Sum of Subsequence Powers
Compute the sum of powers for all subsequences of length k using state transition dynamic programming efficiently.
Minimize Manhattan Distances
Compute the minimum maximum Manhattan distance by removing one point using array math and geometry insights efficiently.
Minimum Operations to Make Median of Array Equal to K
The problem involves minimizing operations to make the median of an array equal to a given value k using a greedy approa…
Minimum Rectangles to Cover Points
Find the minimum number of rectangles needed to cover all points, given constraints on width and position.
Find the Integer Added to Array II
Given two arrays nums1 and nums2, determine the integer added to nums1 to make it equal to nums2 after removing two elem…
Maximum Points Inside the Square
Find the maximum number of points inside a valid square centered at the origin using a scanning and hashing approach.
Count Days Without Meetings
Count Days Without Meetings is a problem where you need to count days without scheduled meetings in a given work period.
Maximum Total Damage With Spell Casting
Calculate the maximum total damage by selectively casting spells while avoiding adjacent power conflicts using array sca…
Minimum Average of Smallest and Largest Elements
Solve the Minimum Average of Smallest and Largest Elements problem using two-pointer scanning to track averages effectiv…
Minimum Cost for Cutting Cake I
In this problem, you need to minimize the cost of cutting a cake into 1x1 pieces using vertical and horizontal cuts.
Minimum Cost for Cutting Cake II
Solve Minimum Cost for Cutting Cake II by choosing optimal cuts using a greedy strategy while tracking cost increments p…
Count Almost Equal Pairs I
Count Almost Equal Pairs I involves finding pairs of elements that can be made equal by swapping at most one digit.
Count Almost Equal Pairs II
Count the number of almost equal integer pairs in an array using array scanning and hash lookup efficiently.
Minimum Amount of Damage Dealt to Bob
Minimize the total damage dealt to Bob using power to eliminate enemies efficiently with greedy approach.
Maximize Score of Numbers in Ranges
Maximize Score of Numbers in Ranges asks to find the maximum score by selecting integers within given intervals with a f…
Length of the Longest Increasing Path
Determine the maximum length of an increasing path in a 2D array using binary search over potential path lengths efficie…
Maximize the Total Height of Unique Towers
Assign heights to towers ensuring each height is unique and the total sum is maximized using greedy sorting techniques.
K-th Largest Perfect Subtree Size in Binary Tree
Find the size of the kth largest perfect subtree in a binary tree using tree traversal and state tracking.
Maximum Frequency of an Element After Performing Operations I
Maximize the frequency of an element in an array after performing a series of operations to find the best possible resul…
Maximum Frequency of an Element After Performing Operations II
Determine the maximum frequency of any element after performing limited operations using binary search and sliding windo…
Zero Array Transformation III
Zero Array Transformation III requires removing the minimum number of queries to make all elements zero using greedy val…
Rearrange K Substrings to Form Target String
Determine if s can be split into k equal substrings and rearranged to match t using a hash table for frequency tracking.
Maximum Area Rectangle With Point Constraints I
Find the maximum area of a rectangle formed by given points on a plane with unique coordinates.
Maximum Area Rectangle With Point Constraints II
Find the largest rectangle on a plane using given points while avoiding any interior points and optimizing with math and…
Check if Grid can be Cut into Sections
Determine if an n x n grid can be divided with two horizontal or vertical cuts using rectangle ranges efficiently.
Maximum Number of Distinct Elements After Operations
Maximize distinct elements in an array by performing at most one operation on each element.
Maximum Coins From K Consecutive Bags
Solve the problem of maximizing coins from selecting k consecutive bags, using binary search and sliding window techniqu…
Maximum Score of Non-overlapping Intervals
Maximize the score of up to 4 non-overlapping intervals, considering their weight and ensuring no overlap between chosen…
Minimum Cost to Make Arrays Identical
Minimize cost to make arrays identical by performing operations with given constraints and a greedy strategy.
Maximum and Minimum Sums of at Most Size K Subsequences
Find the sum of the maximum and minimum elements of subsequences with at most k elements, using dynamic programming.
Count Mentions Per User
Calculate how many times each user is mentioned across MESSAGE events, accounting for offline and online statuses effici…
Sort Matrix by Diagonals
Sort Matrix by Diagonals groups cells by diagonal, then sorts bottom-left diagonals descending and top-right diagonals a…
Eat Pizzas!
Maximize the total weight gained by optimally eating pizzas in groups of four using greedy selection and invariant valid…
Select K Disjoint Special Substrings
Determine if k non-overlapping special substrings exist in a string using dynamic programming and careful substring trac…
Maximum Sum With at Most K Elements
Find the maximum sum by selecting at most k elements from a 2D matrix respecting per-row limits using a greedy strategy.
Transform Array by Parity
Transform an array by sorting even numbers first, followed by odd numbers.
Choose K Elements With Maximum Sum
Choose K Elements With Maximum Sum involves sorting and selecting elements based on a specific rule, applying array plus…
Smallest Palindromic Rearrangement I
Build the smallest palindrome by sorting the left half counts and mirroring them around the optional middle character.
Count Covered Buildings
Determine how many buildings in an n x n city are completely surrounded using array scanning and hash lookup efficiently…
Path Existence Queries in a Graph II
Solve path existence queries in a graph using binary search on the answer space, focusing on sorted nodes and maximum di…
Maximum Product of Two Digits
Find the highest product obtainable from any two digits of a given positive integer using math and sorting techniques ef…
Minimum Deletions for At Most K Distinct Characters
You need to delete characters in a string to reduce its distinct characters to at most k.
Maximum Sum of Edge Values in a Graph
Maximize the sum of edge values in a connected graph by assigning unique node values and optimizing edge products.
Minimum Swaps to Sort by Digit Sum
Calculate the minimum swaps to sort an array by digit sum, ensuring correct order with tiebreaker values for efficiency.
Sum of Largest Prime Substrings
Compute the sum of the three largest unique primes from all substrings using hash table plus math efficiently.
Minimum Absolute Difference in Sliding Submatrix
Find the minimum absolute difference in each k x k submatrix within a given 2D grid using array and sorting techniques.
Maximize Y‑Sum by Picking a Triplet of Distinct X‑Values
Select three distinct x-values from arrays to maximize the sum of their corresponding y-values efficiently using hashing…
Coupon Code Validator
The Coupon Code Validator problem requires filtering and sorting coupons based on specific criteria for validity.
Minimum Time for K Connected Components
Find the minimum time to remove edges such that a graph with n nodes has at least k connected components.
Related Patterns
Array scanning plus hash lookup
98 linked problems
Greedy choice plus invariant validation
76 linked problems
Binary search over the valid answer space
54 linked problems
Array plus Sorting
42 linked problems
State transition dynamic programming
31 linked problems
Two-pointer scanning with invariant tracking
25 linked problems