Skip to content
Branch: master
Find file History
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
Failed to load latest commit information.

CheatSheet: Leetcode For Code Interview

Handy CheatSheet for your code interview. Common code templates, typical problems by categories, etc.


PRs Welcome

Top 20 Code Templates

1#bfsLeetcode: Binary Tree Level Order Traversal
2#dfsLeetcode: Island Perimeter
3#binarysearchLeetcode: Search Insert Position
4#interval, #mergetwolistLeetcode: Interval List Intersections
5#twopointer, #arrayLeetcode: Reverse Words in a String II
6#twopointerLeetcode: Two Sum
7#backtracking, #subsetLeetcode: Subsets II
8#linkedlist, #presumLeetcode: Remove Zero Sum Consecutive Nodes from Linked List
9#unionfindLeetcode: Accounts Merge
10#trieLeetcode: Longest Word in Dictionary
11#heapLeetcode: Top K Frequent Elements
12#editdistance, #dynamicprogrammingLeetcode: Longest Common Subsequence
13#intervalLeetcode: Meeting Rooms II, Leetcode: Course Schedule
14#monotoneLeetcode: Daily Temperatures
15#knapsackLeetcode: Coin Change
16#sortbyfunctionLeetcode: Relative Sort Array
17#slidingwindowLeetcode: Longest Substring Without Repeating Characters
18#divideconquer, #recursive
19#baseconversionLeetcode: Base 7

Top 20 Graph Problems

1Graph Connectivity: Count islands in a 2D matrix#dfs, #unionfindLeetcode: Number of Islands, Leetcode: Island Perimeter
2Get the size of the largest island#dfsLeetcode: Max Area of Island
3Whether a graph is a tree#unionfind, #bfsLeetcode: Graph Valid Tree
4Whether an undirected graph has a loop
5Whether a directed graph has a loopLeetcode: Redundant Connection II
6Shortest path for two nodes in a weighted graph - Dijkstra’s Algorithm
7Minimum spanning tree of a weighted graph - Kruskal’s algorithm#unionfindLeetcode: Connecting Cities With Minimum Cost
8Update a specific regionLeetcode: Flood Fill
9Update regions for a given ruleLeetcode: Surrounded Regions
10Mark levelsLeetcode: 01 Matrix
11Duplicate edgesLeetcode: Reconstruct Itinerary
12Find a certain node in a graph#unionfindLeetcode: Find the Celebrity
13Find a certain path from source to destination in a graphLeetcode: Path With Maximum Minimum Value
14Find the minimum steps from point1 to point2Leetcode: Word Ladder, Leetcode: Sliding Puzzle
15Find all minimum paths from point1 to point2Leetcode: Word Ladder II
16All Paths from Source Lead to DestinationLeetcode: All Paths from Source Lead to Destination
18dijkstra Dijkstra’s Shortest Path First algorithm

Top 5 Binarysearch Problems

1Find a first failing versionLeetcode: First Bad Version
2Search Insert PositionLeetcode: Search Insert Position, Leetcode: Time Based Key-Value Store

Top 10 Dynamic Programming Problems

1LIS - Longest increasing subsequence#string, #lisLeetcode: Longest Increasing Subsequence
4LCS - Longest Common Subsequence#editdistance, #lcsLeetcode: Longest Common Subsequence
2Edit distance of two strings#editdistanceLeetcode: Edit Distance
3Maximum subarray problem#maxsubarraysumLeetcode: Maximum Subarray

Top 10 BinaryTree Problems

1Binary Tree Level Order Traversal#bfsLeetcode: Binary Tree Right Side View
2Height of binary tree#dfsLeetcode: Balanced Binary Tree
3LCA - Lowest Common Ancestor of a binary Tree#dfsLeetcode: Lowest Common Ancestor of a Binary Tree
4Construct binary treeLeetcode: Construct Binary Tree from Preorder and Postorder Traversal
5Check whether a binary tree is a full binary tree#dfs, #bfs
6Right view of a tree

Top 5 String Problems

1Edit distance of two strings#editdistanceLeetcode: Edit Distance
2Remove duplicate letters#greedy, #stackRemove Duplicate Letters

Top 5 Math Problems

1Check prime - Sieve of Eratosthenes#primeLeetcode: Count Primes
2Check leap year#leapyearLeetcode: Day of the Week

Top 40 General Problems

1Split string#stringLeetcode: License Key Formatting
2Two pointers#twosum, #twopointerLeetcode: Two Sum
3Sort one array based on another array#sortbyfunctionLeetcode: Relative Sort Array
4Buy stock for maximum profit list#array, #greedy, #buystockLeetcode: Best Time to Buy and Sell Stock
5Prefix search from a list of strings#trieLeetcode: Longest Word in Dictionary
6Longest substring with at most K distinct characters#slidingwindow, #atmostkdistinctLeetcode: Longest Substring with At Most K Distinct Characters
7Longest subarray with maximum K 0s#slidingwindowLeetcode: Max Consecutive Ones III
8Get all possibilities of subsets#subset, #backtrackingLeetcode: Subsets II, Leetcode: Subsets
9Choose k numbers from a list#combination, #backtrackingLeetcode: Combination Sum II
10Combination from multiple segments#combination, #backtrackingLeetcode: Letter Combinations of a Phone Number
11Factor Combinations#combination, #backtrackingLeetcode: Factor Combinations
12Permutation without duplicates#permutation, #backtrackingLeetcode: Palindrome Permutation II
13Int to string or string to int#bitmanipulation
14Convert a number into negative base representation#bitmanipulation, #baseconversionLeetcode: Convert to Base -2
15Remove nodes from linked list#linkedlist, #presumLeetcode: Remove Zero Sum Consecutive Nodes from Linked List
16Check whether a linked list has a loop
17Network connectivity#unionfindLeetcode: Friend Circles
18Build relationship among different sets#unionfindLeetcode: Accounts Merge
19Knapsack problem to maximize benefits#knapsackLeetcode: Coin Change
20Find the next greater value#monotoneLeetcode: Daily Temperatures
21Meeting conflict#intervalLeetcode: Meeting Rooms, Leetcode: Course Schedule
22Minimum conference rooms#interval, #overlappingintervalLeetcode: Meeting Rooms II
23TopK problem#heapLeetcode: Top K Frequent Elements, Leetcode: Find K Pairs with Smallest Sums
24Quick slow pointers#twopointerLintCode: Middle of Linked List
25Longest Repeating Character with at most K changes#slidingwindowLeetcode: Longest Repeating Character Replacement
26Count out of boundary paths in a 2D matrix#bfs, #outofboundarypathLeetcode: Out of Boundary Paths
27Prefix and Suffix Search#trieLeetcode: Prefix and Suffix Search
28Remove duplicate letters#greedy, #string, #stackRemove Duplicate Letters
29Next Permutation#greedy, #nextpermutationLeetcode: Next Permutation
30Beautiful array#divideconquerLeetcode: Beautiful Array
31Whether 132 pattern exists in array#stackLeetcode: 132 Pattern
32Travelling salesman problem
33Leetcode: Remove Duplicates from Sorted Array II
34Leetcode: Min Stack
35#minmax, #dynamicprogrammingLeetcode: Predict the Winner, Leetcode: Stone Game
36Topological Sort

Common Tips For Clean Code

1Caculate sum of a range quickly#presum,Leetcode: Maximum Subarray
2Move in four directions for a matrixLeetcode: Sliding Puzzle
3Split string by multiple seperatorLeetcode: Brace Expansion
4Add a dummy tailing element to simplify codeLeetcode: Brace Expansion
5Fast slow pointersLintCode: Middle of Linked List
6Deep copy an arrayLeetcode: Combination Sum
7Use arrays instead of hashmaps, if possibleLeetcode: Number of Days in a Month
8Control the order of dfsLeetcode: Subsets II
9Avoid inserting into the head of an arrayLeetcode: Path In Zigzag Labelled Binary Tree
10From right to left, instead of left to rightLeetcode: Merge Sorted Array
11Think the other way aroundAdd Items vs Remove Items, Increase Counter vs Decrease Counter
12Avoid uncessary if…else…res[i] = (diff/2 <= k), Leetcode: Can Make Palindrome from Substring
13To get the case of K, solve: at most K - at most (K-1)Leetcode: Subarrays with K Different Integers
14Instead of deleting entry from hashmap, decrease counterLeetcode: Longest Substring with At Most K Distinct Characters
15Find the max/min; If not found, return 0Leetcode: Minimum Area Rectangle
16With helper function vs without helper functionLeetcode: Longest Repeating Character Replacement
17Instead of adding a character, try to delete oneLeetcode: Longest String Chain
18#roudtrippass: from left to right, then right to leftLeetcode: Shortest Distance to a Character
19One pass instead of two pass
20Avoid unnecessary precheck
21Swiping line algorithm
22Add a dummy head node for linked list
23Hide details which are irrelevant
24Avoid delete element from hashmaps

Review Problems By Category

1#binarytreeReview: Binary Tree Problems
2#linkedlistReview: Linked List Problems
3#binarysearchReview: Binary Search Problems
4#dynamicprogrammingReview: Dynamic Programming Problems
5#twopointerReview: TwoPointers Problems
6#trieReview: Trie Tree Problems
7#stringReview: String Problems
8#stackReview: Stack Problems
9#bfsReview: BFS Problems
10#dfsReview: DFS Problems
11#arrayReview: Array/SubArray Problems
12#hashmapReview: Hashmap Problems
13#monotoneReview: Monotone Stack Or Monotone Queue Problems
14#knapsackReview: Knapsack Problems
15#heapReview: Heap Problems
16#divideconquerReview: Divide And Conquer Problems
17#backtrackingReview: Backtracking Problems
18#unionfindReview: Union Find Problems
19#greedyReview: Greedy Problems
20#gcdReview: GCD Problems
21#intervalReview: Interval Problems
22#combinationReview: Combinations and Permutations Problems
23#sqlReview: SQL Problems
24#sqrtReview: sqrt Problems

Golang Tips

Golang return a tuplefunc dfs(root *TreeNode, max *float64) (sum int, cnt int), Leetcode: Maximum Average Subtree
Use strings.Builder, instead of stringLeetcode: Unique Email Addresses
Variable Conversionfloat64(x_int/y_int) != float64(x_int)/float64(y_int), Leetcode: Maximum Average Subtree
For a list of objects, pass by value or referencef(l []*TreeNode) vs f(l *[]*TreeNode), Leetcode: Lowest Common Ancestor of a Binary Tree

Resource For Code Problems

Leetcode summaryLink: Top Google Questions, Link: Top 100 Liked Questions, Link: Top Interview Questions
Leetcode summaryGitHub: kdn251/interviews
Leetcoder on YouTubelee 215, Aoxiang Cui
Online test, hackerrank - hard
Online test
Online test,
Online test,,,
ReferenceYoutube: Abdul Bari - Algorithm

Resource For Code Problems - In Chinese


More Resources

License: Code is licensed under MIT License.

You can’t perform that action at this time.