Pattern 01 of 22

Hash Map Pattern: Template + 709 LeetCode Problems

Trade memory for time: remember what you have seen so the second pass never happens.

Easy
227
Medium
372
Hard
110

What the hash map pattern is

A hash map converts a search into a lookup, which is why it is the most common single answer in this entire corpus — 588 of the 3000 problems are built on one. Three uses cover nearly all of them. The complement lookup asks, at each element, whether the thing that would complete the answer has already been seen: storing values as you go turns two nested loops into one pass, and the reason it works is that a pair is found from its second member, so only the past needs to be remembered. Frequency counting answers anagram, majority and top-k questions by comparing counts instead of arrangements. Grouping needs a canonical key — a sorted string, a character-count tuple, a normalised pattern — chosen so that two inputs collide exactly when they belong together, and that choice is the whole problem. Python's dict preserves insertion order, so an ordered result often needs no extra bookkeeping.

When to use it

  • The brute force is a nested loop asking "is there another element such that…".
  • You are counting occurrences, or comparing two multisets.
  • Items must be grouped by a property you can compute into a stable key.
  • Membership must be tested repeatedly and the input is not sorted.
  • Seen-before state has to survive across a single pass — de-duplication, cycle detection on values.

The hash map template in Python

The shape, not a solution to any one problem. Adapt the condition and the summary being maintained; the skeleton stays the same across the 709 problems listed below.

PythonHash Map template
def two_sum(nums, target):
    seen = {}                            # value -> the index it was found at

    for i, value in enumerate(nums):
        if target - value in seen:       # the partner was already scanned
            return [seen[target - value], i]
        seen[value] = i

    return []

Complexity characteristics

Time
O(1) average per operation, O(n) worst case
Auxiliary space
O(n)

Average-case constant lookups are what turn a nested-loop search into a single pass, so the complement and frequency-counting solutions are O(n) time and O(n) space. The worst case is linear per operation when every key collides, which is irrelevant on real data and is the reason a language's string hash is randomised per process. Ordering is not free: getting a sorted result out of a map costs the sort on top.

Eyes only

Meet the hash map problem you did not practise.

In the live round, Stealth Interview reads the problem off your screen, returns a working solution with a step-by-step explanation and its time and space complexity, and transcribes what the interviewer says. It's a desktop app for macOS and Windows, invisible to screen sharing.

All 709 hash map LeetCode problems

Every problem in the library the hash map pattern applies to, grouped by LeetCode's own difficulty rating. 601 of the 709 carry a complete Python solution with a worked example and complexity analysis; the rest are listed for completeness, with the LeetCode Premium ones marked.

Related LeetCode topics

Easy (227)

Easy problems
No.Problem
0001Two Sum
0013Roman to Integer
0058Length of Last Word
0141Linked List Cycle
0160Intersection of Two Linked Lists
0169Majority Element
0202Happy Number
0205Isomorphic Strings
0217Contains Duplicate
0219Contains Duplicate II
0242Valid Anagram
0268Missing Number
0290Word Pattern
0349Intersection of Two Arrays
0350Intersection of Two Arrays II
0383Ransom Note
0387First Unique Character in a String
0389Find the Difference
0409Longest Palindrome
0434Number of Segments in a String
0448Find All Numbers Disappeared in an Array
0459Repeated Substring Pattern
0482License Key Formatting
0496Next Greater Element I
0500Keyboard Row
0520Detect Capital
0521Longest Uncommon Subsequence I
0551Student Attendance Record I
0575Distribute Candies
0594Longest Harmonious Subsequence
0599Minimum Index Sum of Two Lists
0645Set Mismatch
0653Two Sum IV - Input is a BST
0657Robot Return to Origin
0697Degree of an Array
0705Design HashSet
0706Design HashMap
0709To Lower Case
0748Shortest Completing Word
1207Unique Number of Occurrences
2215Find the Difference of Two Arrays
0170Two Sum III - Data structure designPremium
0243Shortest Word DistancePremium
0246Strobogrammatic NumberPremium
0266Palindrome PermutationPremium
0293Flip GamePremium
0359Logger Rate LimiterPremium
0604Design Compressed String IteratorPremium
0734Sentence SimilarityPremium
0760Find Anagram MappingsPremium
0771Jewels and Stones
0796Rotate String
0804Unique Morse Code Words
0806Number of Lines To Write String
0819Most Common Word
0824Goat Latin
0830Positions of Large Groups
0859Buddy Strings
0884Uncommon Words from Two Sentences
0888Fair Candy Swap
0914X of a Kind in a Deck of Cards
0929Unique Email Addresses
0944Delete Columns to Make Sorted
0953Verifying an Alien Dictionary
0961N-Repeated Element in Size 2N Array
0997Find the Town Judge
1002Find Common Characters
1078Occurrences After Bigram
1086High FivePremium
1108Defanging an IP Address
1119Remove Vowels from a StringPremium
1122Relative Sort Array
1128Number of Equivalent Domino Pairs
1133Largest Unique NumberPremium
1160Find Words That Can Be Formed by Characters
1165Single-Row KeyboardPremium
1189Maximum Number of Balloons
1213Intersection of Three Sorted ArraysPremium
1221Split a String in Balanced Strings
1275Find Winner on a Tic Tac Toe Game
1309Decrypt String from Alphabet to Integer Mapping
1331Rank Transform of an Array
1346Check If N and Its Double Exist
1356Sort Integers by The Number of 1 Bits
1365How Many Numbers Are Smaller Than the Current Number
1370Increasing Decreasing String
1374Generate a String With Characters That Have Odd Counts
1394Find Lucky Integer in an Array
1399Count Largest Group
1408String Matching in an Array
1417Reformat The String
1426Counting ElementsPremium
1436Destination City
1446Consecutive Characters
1460Make Two Arrays Equal by Reversing Subarrays
1496Path Crossing
1507Reformat Date
1512Number of Good Pairs
1528Shuffle String
1556Thousand Separator
1576Replace All ?'s to Avoid Consecutive Repeating Characters
1592Rearrange Spaces Between Words
1603Design Parking System
1624Largest Substring Between Two Equal Characters
1629Slowest Key
1636Sort Array by Increasing Frequency
1640Check Array Formation Through Concatenation
1656Design an Ordered Stream
1662Check If Two String Arrays are Equivalent
1678Goal Parser Interpretation
1684Count the Number of Consistent Strings
1694Reformat Phone Number
1704Determine if String Halves Are Alike
1742Maximum Number of Balls in a Box
1748Sum of Unique Elements
1758Minimum Changes To Make Alternating Binary String
1763Longest Nice Substring
1773Count Items Matching a Rule
1784Check if Binary String Has at Most One Segment of Ones
1790Check if One String Swap Can Make Strings Equal
1796Second Largest Digit in a String
1805Number of Different Integers in a String
1816Truncate Sentence
1832Check if the Sentence Is Pangram
1844Replace All Digits with Characters
1854Maximum Population Year
1869Longer Contiguous Segments of Ones than Zeros
1876Substrings of Size Three with Distinct Characters
1880Check if Word Equals Summation of Two Words
1893Check if All the Integers in a Range Are Covered
1897Redistribute Characters to Make All Strings Equal
1933Check if String Is Decomposable Into Value-Equal SubstringsPremium
1935Maximum Number of Words You Can Type
1941Check if All Characters Have Equal Number of Occurrences
1945Sum of Digits of String After Convert
1957Delete Characters to Make Fancy String
1967Number of Strings That Appear as Substrings in Word
1995Count Special Quadruplets
2006Count Number of Pairs With Absolute Difference K
2011Final Value of Variable After Performing Operations
2032Two Out of Three
2042Check if Numbers Are Ascending in a Sentence
2047Number of Valid Words in a Sentence
2053Kth Distinct String in an Array
2062Count Vowel Substrings of a String
2068Check Whether Two Strings are Almost Equivalent
2085Count Common Words With One Occurrence
2094Finding 3-Digit Even Numbers
2099Find Subsequence of Length K With the Largest Sum
2103Rings and Rods
2114Maximum Number of Words Found in Sentences
2124Check if All A's Appears Before All B's
2129Capitalize the Title
2133Check if Every Row and Column Contains All Numbers
2138Divide a String Into Groups of Size k
2148Count Elements With Strictly Smaller and Greater Elements
2154Keep Multiplying Found Values by Two
2185Counting Words With a Given Prefix
2190Most Frequent Number Following Key In an Array
2194Cells in a Range on an Excel Sheet
2206Divide Array Into Equal Pairs
2229Check if an Array Is ConsecutivePremium
2243Calculate Digit Sum of a String
2248Intersection of Multiple Arrays
2255Count Prefixes of a Given String
2264Largest 3-Same-Digit Number in String
2273Find Resultant Array After Removing Anagrams
2278Percentage of Letter in String
2283Check if Number Has Equal Digit Count and Digit Value
2287Rearrange Characters to Make Target String
2299Strong Password Checker II
2309Greatest English Letter in Upper and Lower Case
2315Count Asterisks
2325Decode the Message
2341Maximum Number of Pairs in Array
2347Best Poker Hand
2351First Letter to Appear Twice
2357Make Array Zero by Subtracting Equal Amounts
2363Merge Similar Items
2367Number of Arithmetic Triplets
2395Find Subarrays With Equal Sum
2399Check Distances Between Same Letters
2404Most Frequent Even Element
2418Sort the People
2423Remove Letter To Equalize Frequency
2437Number of Valid Clock Times
2441Largest Positive Integer That Exists With Its Negative
2446Determine if Two Events Have Conflict
2451Odd String Difference
2465Number of Distinct Averages
2475Number of Unequal Triplets in Array
2490Circular Sentence
2496Maximum Value of a String in an Array
2506Count Pairs Of Similar Strings
2515Shortest Distance to Target String in a Circular Array
2529Maximum Count of Positive Integer and Negative Integer
2540Minimum Common Value
2549Count Distinct Numbers on Board
2570Merge Two 2D Arrays by Summing Values
2586Count the Number of Vowel Strings in Range
2605Form Smallest Number From Two Digit Arrays
2609Find the Longest Balanced Substring of a Binary String
2670Find the Distinct Difference Array
2678Number of Senior Citizens
2682Find the Losers of the Circular Game
2710Remove Trailing Zeros From a String
2716Minimize String Length
2729Check if The Number is Fascinating
2744Find Maximum Number of String Pairs
2748Number of Beautiful Pairs
2784Check if Array is Good
2788Split Strings by Separator
2810Faulty Keyboard
2815Max Pair Sum in an Array
2828Check if a String Is an Acronym of Words
2833Furthest Point From Origin
2839Check if Strings Can be Made Equal With Operations I
2848Points That Intersect With Cars
2869Minimum Operations to Collect Elements
2913Subarrays Distinct Element Sum of Squares I
2932Maximum Strong Pair XOR I
2937Make Three Strings Equal
2942Find Words Containing Character
2956Find Common Elements Between Two Arrays
2960Count Tested Devices After Test Operations
2965Find Missing and Repeated Values
2996Smallest Missing Integer Greater Than Sequential Prefix Sum

Medium (372)

Medium problems
No.Problem
0003Longest Substring Without Repeating Characters
0006Zigzag Conversion
0008String to Integer (atoi)
0012Integer to Roman
0017Letter Combinations of a Phone Number
0036Valid Sudoku
0038Count and Say
0049Group Anagrams
0073Set Matrix Zeroes
0105Construct Binary Tree from Preorder and Inorder Traversal
0106Construct Binary Tree from Inorder and Postorder Traversal
0128Longest Consecutive Sequence
0133Clone Graph
0138Copy List with Random Pointer
0139Word Break
0142Linked List Cycle II
0146LRU Cache
0166Fraction to Recurring Decimal
0187Repeated DNA Sequences
0208Implement Trie (Prefix Tree)
0229Majority Element II
0264Ugly Number II
0299Bulls and Cows
0347Top K Frequent Elements
0355Design Twitter
0380Insert Delete GetRandom O(1)
0395Longest Substring with At Least K Repeating Characters
0398Random Pick Index
0421Maximum XOR of Two Numbers in an Array
0423Reconstruct Original Digits from English
0424Longest Repeating Character Replacement
0433Minimum Genetic Mutation
0438Find All Anagrams in a String
0442Find All Duplicates in an Array
0447Number of Boomerangs
0451Sort Characters By Frequency
04544Sum II
0457Circular Array Loop
0468Validate IP Address
0491Non-decreasing Subsequences
0508Most Frequent Subtree Sum
0519Random Flip Matrix
0522Longest Uncommon Subsequence II
0523Continuous Subarray Sum
0525Contiguous Array
0532K-diff Pairs in an Array
0535Encode and Decode TinyURL
0554Brick Wall
0560Subarray Sum Equals K
0567Permutation in String
0609Find Duplicate File in System
0621Task Scheduler
0648Replace Words
0652Find Duplicate Subtrees
0659Split Array into Consecutive Subsequences
0676Implement Magic Dictionary
0677Map Sum Pairs
0686Repeated String Match
0690Employee Importance
0692Top K Frequent Words
0720Longest Word in Dictionary
0721Accounts Merge
0722Remove Comments
0740Delete and Earn
0763Partition Labels
0846Hand of Straights
0981Time Based Key-Value Store
1657Determine if Two Strings Are Close
1679Max Number of K-Sum Pairs
2013Detect Squares
2336Smallest Number in Infinite Set
2352Equal Row and Column Pairs
0159Longest Substring with At Most Two Distinct CharactersPremium
0244Shortest Word Distance IIPremium
0245Shortest Word Distance IIIPremium
0247Strobogrammatic Number IIPremium
0249Group Shifted StringsPremium
0267Palindrome Permutation IIPremium
0271Encode and Decode StringsPremium
0288Unique Word AbbreviationPremium
0291Word Pattern IIPremium
0311Sparse Matrix MultiplicationPremium
0314Binary Tree Vertical Order TraversalPremium
0325Maximum Size Subarray Sum Equals kPremium
0340Longest Substring with At Most K Distinct CharactersPremium
0348Design Tic-Tac-ToePremium
0353Design Snake GamePremium
0356Line ReflectionPremium
0379Design Phone DirectoryPremium
0531Lonely Pixel IPremium
0533Lonely Pixel IIPremium
0544Output Contest MatchesPremium
0582Kill ProcessPremium
0616Add Bold Tag in StringPremium
0635Design Log Storage SystemPremium
0666Path Sum IVPremium
0681Next Closest TimePremium
0694Number of Distinct IslandsPremium
0737Sentence Similarity IIPremium
0752Open the Lock
0756Pyramid Transition Matrix
0758Bold Words in StringPremium
0767Reorganize String
0781Rabbits in Forest
0791Custom Sort String
0792Number of Matching Subsequences
0811Subdomain Visit Count
0817Linked List Components
0820Short Encoding of Words
0822Card Flipping Game
0823Binary Trees With Factors
0831Masking Personal Information
0833Find And Replace in String
0840Magic Squares In Grid
0863All Nodes Distance K in Binary Tree
0865Smallest Subtree with all the Deepest Nodes
0869Reordered Power of 2
0873Length of Longest Fibonacci Subsequence
0874Walking Robot Simulation
0889Construct Binary Tree from Preorder and Postorder Traversal
0890Find and Replace Pattern
0893Groups of Special-Equivalent Strings
0900RLE Iterator
0904Fruit Into Baskets
0911Online Election
0916Word Subsets
09233Sum With Multiplicity
0930Binary Subarrays With Sum
0939Minimum Area Rectangle
0945Minimum Increment to Make Array Unique
0947Most Stones Removed with Same Row or Column
0954Array of Doubled Pairs
0957Prison Cells After N Days
0959Regions Cut By Slashes
0963Minimum Area Rectangle II
0966Vowel Spellchecker
0970Powerful Integers
0974Subarray Sums Divisible by K
1010Pairs of Songs With Total Durations Divisible by 60
1015Smallest Integer Divisible by K
1016Binary String With Substrings Representing 1 To N
1027Longest Arithmetic Subsequence
1048Longest String Chain
1054Distant Barcodes
1072Flip Columns For Maximum Number of Equal Rows
1079Letter Tile Possibilities
1090Largest Values From Labels
1100Find K-Length Substrings With No Repeated CharactersPremium
1110Delete Nodes And Return Forest
1123Lowest Common Ancestor of Deepest Leaves
1124Longest Well-Performing Interval
1138Alphabet Board Path
1146Snapshot Array
1152Analyze User Website Visit PatternPremium
1156Swap For Longest Repeated Character Substring
1166Design File SystemPremium
1169Invalid Transactions
1170Compare Strings by Frequency of the Smallest Character
1171Remove Zero Sum Consecutive Nodes from Linked List
1177Can Make Palindrome from Substring
1181Before and After PuzzlePremium
1198Find Smallest Common Element in All RowsPremium
1202Smallest String With Swaps
1218Longest Arithmetic Subsequence of Given Difference
1244Design A LeaderboardPremium
1248Count Number of Nice Subarrays
1257Smallest Common RegionPremium
1258Synonymous SentencesPremium
1261Find Elements in a Contaminated Binary Tree
1267Count Servers that Communicate
1282Group the People Given the Group Size They Belong To
1296Divide Array in Sets of K Consecutive Numbers
1297Maximum Number of Occurrences of a Substring
1311Get Watched Videos by Your Friends
1324Print Words Vertically
1338Reduce Array Size to The Half
1347Minimum Number of Steps to Make Two Strings Anagram
1348Tweet Counts Per Frequency
1357Apply Discount Every n Orders
1358Number of Substrings Containing All Three Characters
1366Rank Teams by Votes
1371Find the Longest Substring Containing Vowels in Even Counts
1386Cinema Seat Allocation
1396Design Underground System
1400Construct K Palindrome Strings
1410HTML Entity Parser
1418Display Table of Food Orders in a Restaurant
1419Minimum Number of Frogs Croaking
1429First Unique NumberPremium
1442Count Triplets That Can Form Two Arrays of Equal XOR
1443Minimum Time to Collect All Apples in a Tree
1452People Whose List of Favorite Companies Is Not a Subset of Another List
1461Check If a String Contains All Binary Codes of Size K
1477Find Two Non-overlapping Sub-arrays Each With Target Sum
1481Least Number of Unique Integers after K Removals
1485Clone Binary Tree With Random PointerPremium
1487Making File Names Unique
1488Avoid Flood in The City
1490Clone N-ary TreePremium
1497Check If Array Pairs Are Divisible by k
1500Design a File Sharing SystemPremium
1506Find Root of N-Ary TreePremium
1519Number of Nodes in the Sub-Tree With the Same Label
1525Number of Good Ways to Split a String
1540Can Convert String in K Moves
1545Find Kth Bit in Nth Binary String
1546Maximum Number of Non-Overlapping Subarrays With Sum Equals Target
1554Strings Differ by One CharacterPremium
1562Find Latest Group of Size M
1570Dot Product of Two Sparse VectorsPremium
1577Number of Ways Where Square of Number Is Equal to Product of Two Numbers
1590Make Sum Divisible by P
1593Split a String Into the Max Number of Unique Substrings
1600Throne Inheritance
1604Alert Using Same Key-Card Three or More Times in a One Hour Period
1612Check If Two Expression Trees are EquivalentPremium
1630Arithmetic Subarrays
1638Count Substrings That Differ by One Character
1647Minimum Deletions to Make Character Frequencies Unique
1650Lowest Common Ancestor of a Binary Tree IIIPremium
1658Minimum Operations to Reduce X to Zero
1660Correct a Binary TreePremium
1674Minimum Moves to Make Array Complementary
1676Lowest Common Ancestor of a Binary Tree IVPremium
1695Maximum Erasure Value
1711Count Good Meals
1726Tuple with Same Product
1733Minimum Number of People to Teach
1737Change Minimum Characters to Satisfy One of Three Conditions
1740Find Distance in a Binary TreePremium
1743Restore the Array From Adjacent Pairs
1772Sort Features by PopularityPremium
1775Equal Sum Arrays With Minimum Number of Operations
1781Sum of Beauty of All Substrings
1794Count Pairs of Equal Substrings With Minimum DifferencePremium
1797Design Authentication Manager
1804Implement Trie II (Prefix Tree)Premium
1807Evaluate the Bracket Pairs of a String
1814Count Nice Pairs in an Array
1817Finding the Users Active Minutes
1836Remove Duplicates From an Unsorted Linked ListPremium
1852Distinct Numbers in Each SubarrayPremium
1865Finding Pairs With a Certain Sum
1906Minimum Absolute Difference Queries
1915Number of Wonderful Substrings
1930Unique Length-3 Palindromic Subsequences
1940Longest Common Subsequence Between Sorted ArraysPremium
1942The Number of the Smallest Unoccupied Chair
1943Describe the Painting
1980Find Unique Binary String
1983Widest Pair of Indices With Equal Range SumPremium
1993Operations on Tree
2001Number of Pairs of Interchangeable Rectangles
2007Find Original Array From Doubled Array
2008Maximum Earnings From Taxi
2023Number of Pairs of Strings With Concatenation Equal to Target
2029Stone Game IX
2031Count Subarrays With More Ones Than ZerosPremium
2034Stock Price Fluctuation
2043Simple Bank System
2048Next Greater Numerically Balanced Number
2067Number of Equal Count SubstringsPremium
2075Decode the Slanted Ciphertext
2080Range Frequency Queries
2083Substrings That Begin and End With the Same LetterPremium
2107Number of Unique Flavors After Sharing K CandiesPremium
2115Find All Possible Recipes from Given Supplies
2120Execution of All Suffix Instructions Staying in a Grid
2121Intervals Between Identical Elements
2131Longest Palindrome by Concatenating Two Letter Words
2135Count Words Obtained After Adding a Letter
2150Find All Lonely Numbers in the Array
2152Minimum Number of Lines to Cover PointsPremium
2166Design Bitset
2168Unique Substrings With Equal Digit FrequencyPremium
2170Minimum Operations to Make the Array Alternating
2182Construct String With Repeat Limit
2186Minimum Number of Steps to Make Two Strings Anagram II
2196Create Binary Tree From Descriptions
2201Count Artifacts That Can Be Extracted
2225Find Players With Zero or One Losses
2232Minimize Result by Adding Parentheses to Expression
2244Minimum Rounds to Complete All Tasks
2249Count Lattice Points Inside a Circle
2250Count Number of Rectangles Containing Each Point
2260Minimum Consecutive Cards to Pick Up
2261K Divisible Elements Subarrays
2266Count Number of Texts
2268Minimum Number of KeypressesPremium
2275Largest Combination With Bitwise AND Greater Than Zero
2284Sender With Largest Word Count
2288Apply Discount to Prices
2295Replace Elements in an Array
2342Max Sum of a Pair With Equal Sum of Digits
2349Design a Number Container System
2353Design a Food Rating System
2364Count Number of Bad Pairs
2365Task Scheduler II
2368Reachable Nodes With Restrictions
2370Longest Ideal Subsequence
2374Node With Highest Edge Score
2384Largest Palindromic Number
2385Amount of Time for Binary Tree to Be Infected
2405Optimal Partition of String
2408Design SQLPremium
2414Length of the Longest Alphabetical Continuous Substring
2424Longest Uploaded Prefix
2434Using a Robot to Print the Lexicographically Smallest String
2442Count Number of Distinct Integers After Reverse Operations
2453Destroy Sequential Targets
2456Most Popular Video Creator
2461Maximum Sum of Distinct Subarrays With Length K
2489Number of Substrings With Fixed RatioPremium
2491Divide Players Into Teams of Equal Skill
2501Longest Square Streak in an Array
2502Design Memory Allocator
2512Reward Top K Students
2516Take K of Each Character From Left and Right
2521Distinct Prime Factors of Product of Array
2526Find Consecutive Integers from a Data Stream
2531Make Number of Distinct Characters Equal
2537Count the Number of Good Subarrays
2539Count the Number of Good SubsequencesPremium
2554Maximum Number of Integers to Choose From a Range I
2564Substring XOR Queries
2588Count the Number of Beautiful Subarrays
2590Design a Todo ListPremium
2593Find Score of an Array After Marking All Elements
2597The Number of Beautiful Subsets
2598Smallest Missing Non-negative Integer After Operations
2606Find the Substring With Maximum Cost
2610Convert an Array Into a 2D Array With Conditions
2615Sum of Distances
2641Cousins in Binary Tree II
2653Sliding Subarray Beauty
2657Find the Prefix Common Array of Two Arrays
2661First Completely Painted Row or Column
2671Frequency Tracker
2707Extra Characters in a String
2711Difference of Number of Distinct Values on Diagonals
2718Sum of Matrix After Queries
2743Count Substrings Without Repeating CharacterPremium
2747Count Zero Request Servers
2766Relocate Marbles
2767Partition String Into Minimum Beautiful Substrings
2768Number of Black Blocks
2780Minimum Index of a Valid Split
2782Number of Unique CategoriesPremium
2799Count Complete Subarrays in an Array
2808Minimum Seconds to Equalize a Circular Array
2830Maximize the Profit as the Salesman
2831Find the Longest Equal Subarray
2840Check if Strings Can be Made Equal With Operations II
2841Maximum Sum of Almost Unique Subarray
2845Count of Interesting Subarrays
2852Sum of Remoteness of All CellsPremium
2856Minimum Array Length After Pair Removals
2857Count Pairs of Points With Distance k
2870Minimum Number of Operations to Make Array Empty
2875Minimum Size Subarray in Infinite Array
2898Maximum Linear Stock ScorePremium
2910Minimum Number of Groups to Create a Valid Assignment
2914Minimum Number of Changes to Make Binary String Beautiful
2933High-Access Employees
2947Count Beautiful Substrings I
2950Number of Divisible SubstringsPremium
2955Number of Same-End SubstringsPremium
2958Length of Longest Subarray With at Most K Frequency
2964Number of Divisible Triplet SumsPremium
2975Maximum Square Area by Removing Fences From a Field
2981Find Longest Special Substring That Occurs Thrice I
2982Find Longest Special Substring That Occurs Thrice II

Hard (110)

Hard problems
No.Problem
0030Substring with Concatenation of All Words
0037Sudoku Solver
0041First Missing Positive
0065Valid Number
0068Text Justification
0076Minimum Window Substring
0126Word Ladder II
0127Word Ladder
0140Word Break II
0149Max Points on a Line
0214Shortest Palindrome
0336Palindrome Pairs
0352Data Stream as Disjoint Intervals
0381Insert Delete GetRandom O(1) - Duplicates allowed
0391Perfect Rectangle
0432All O`one Data Structure
0460LFU Cache
0480Sliding Window Median
0632Smallest Range Covering Elements from K Lists
0691Stickers to Spell Word
0710Random Pick with Blacklist
0736Parse Lisp Expression
0745Prefix and Suffix Search
0248Strobogrammatic Number IIIPremium
0305Number of Islands IIPremium
0358Rearrange String k Distance ApartPremium
0548Split Array with Equal SumPremium
0588Design In-Memory File SystemPremium
0631Design Excel Sum FormulaPremium
0711Number of Distinct Islands IIPremium
0726Number of Atoms
0761Special Binary String
0770Basic Calculator IV
0815Bus Routes
0828Count Unique Characters of All Substrings of a Given String
0839Similar String Groups
0854K-Similar Strings
0895Maximum Frequency Stack
0924Minimize Malware Spread
0928Minimize Malware Spread II
0952Largest Component Size by Common Factor
0982Triples with Bitwise AND Equal To Zero
0987Vertical Order Traversal of a Binary Tree
0992Subarrays with K Different Integers
0996Number of Squareful Arrays
1001Grid Illumination
1036Escape a Large Maze
1074Number of Submatrices That Sum to Target
1096Brace Expansion II
1121Divide Array Into Increasing SequencesPremium
1153String Transforms Into Another StringPremium
1172Dinner Plate Stacks
1178Number of Valid Words for Each Puzzle
1224Maximum Equal Frequency
1255Maximum Score Words Formed by Letters
1284Minimum Number of Flips to Convert Binary Matrix to Zero Matrix
1345Jump Game IV
1392Longest Happy Prefix
1542Find Longest Awesome Substring
1713Minimum Operations to Make a Subsequence
1782Count Pairs Of Nodes
1788Maximize the Beauty of the GardenPremium
1819Number of Different Subsequences GCDs
1857Largest Color Value in a Directed Graph
1912Design Movie Rental System
1932Merge BSTs to Create Single BST
1938Maximum Genetic Difference Query
1948Delete Duplicate Folders in System
1960Maximum Product of the Length of Two Palindromic Substrings
1994The Number of Good Subsets
2009Minimum Number of Operations to Make Array Continuous
2014Longest Subsequence Repeated k Times
2019The Score of Students Solving Math Expression
2025Maximum Number of Ways to Partition an Array
2122Recover the Original Array
2213Longest Substring of One Repeating Character
2227Encrypt and Decrypt Strings
2251Number of Flowers in Full Bloom
2254Design Video Sharing PlatformPremium
2262Total Appeal of A String
2301Match Substring After Replacement
2306Naming a Company
2350Shortest Impossible Sequence of Rolls
2354Number of Excellent Pairs
2402Meeting Rooms III
2416Sum of Prefix Scores of Strings
2421Number of Good Paths
2488Count Subarrays With Median K
2499Minimum Total Cost to Make Arrays Unequal
2508Add Edges to Make Degrees of All Nodes Even
2514Count Anagrams
2524Maximum Frequency Score of a SubarrayPremium
2547Minimum Cost to Split an Array
2561Rearranging Fruits
2581Count Number of Possible Root Nodes
2584Split the Array to Make Coprime Products
2612Minimum Reverse Operations
2713Maximum Strictly Increasing Cells in a Matrix
2732Find a Good Subset of the Matrix
2763Sum of Imbalance Numbers of All Subarrays
2781Length of the Longest Valid Substring
2813Maximum Elegance of a K-Length Subsequence
2842Count K-Subsequences of a String With Maximum Beauty
2897Apply Operations on Array to Maximize Sum of Squares
2902Count of Sub-Multisets With Bounded Sum
2935Maximum Strong Pair XOR II
2949Count Beautiful Substrings II
2953Count Complete Substrings
2963Count the Number of Good Partitions
2983Palindrome Rearrangement Queries

Hash Map pattern FAQ

What is the hash map pattern?

A hash map converts a search into a lookup, which is why it is the most common single answer in this entire corpus — 588 of the 3000 problems are built on one.

How many LeetCode problems use the hash map pattern?

This page lists 709 LeetCode problems that the hash map pattern applies to: 227 Easy, 372 Medium and 110 Hard. 601 of them carry a complete Python solution with complexity analysis.

What is the time complexity of the hash map pattern?

O(1) average per operation, O(n) worst case time and O(n) space. Average-case constant lookups are what turn a nested-loop search into a single pass, so the complement and frequency-counting solutions are O(n) time and O(n) space. The worst case is linear per operation when every key collides, which is irrelevant on real data and is the reason a language's string hash is randomised per process. Ordering is not free: getting a sorted result out of a map costs the sort on top.

When should I use the hash map pattern in an interview?

The brute force is a nested loop asking "is there another element such that…". You are counting occurrences, or comparing two multisets.

Which hash map problem should I start with?

LeetCode 1. Two Sum is the lowest-numbered Easy problem on this page, which makes it the usual starting point: the technique is visible without the problem's own complications getting in the way.

What patterns are related to hash map?

Prefix Sum, Sliding Window, Sorting, Trie. Problems frequently sit in more than one of these, and the overlap is where the interesting follow-up questions come from.

More ways in: all 22 patterns, the curated study lists, or the full problem list.