01 Longest Substring Without Repeating Characters
Sliding Window Hash Map String

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

Examples
Example 1
Input: s = "abcabcbb"
Output: 3
The longest substring without repeating characters is "abc", which has length 3. Note that "bca" and "cab" are also valid answers of the same length.
Example 2
Input: s = "bbbbb"
Output: 1
Every character is the same, so the longest substring without repeating characters is just "b" with length 1.
Example 3
Input: s = "pwwkew"
Output: 3
The answer is "wke" with length 3. Note that "pwke" is a subsequence, not a substring - the characters are not contiguous.
Edge Cases to Consider
Empty string: s = "" → Output: 0
Single character: s = "a" → Output: 1
All unique: s = "abcdef" → Output: 6 (entire string)
Special characters: String may contain spaces, digits, and symbols
Constraints
  • 0 ≤ s.length ≤ 5 × 104
  • s consists of English letters, digits, symbols, and spaces
  • Character set is ASCII (at most 128 unique characters)
Complexity Target
Time O(n) Single pass through the string
Space O(min(m, n)) Where m = character set size, n = string length
02 LRU Cache
Design Doubly Linked List Hash Map

Design a data structure that follows the constraints of a Least Recently Used (LRU) cache. Implement the LRUCache class that supports get and put operations in O(1) average time complexity.

Examples
Example 1
Input:
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1,1], [2,2], [1], [3,3], [2], [4,4], [1], [3], [4]]
Output: [null, null, null, 1, null, -1, null, -1, 3, 4]
Explanation:
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // cache: {1=1}
lRUCache.put(2, 2); // cache: {1=1, 2=2}
lRUCache.get(1); // return 1
lRUCache.put(3, 3); // LRU key 2 evicted. cache: {1=1, 3=3}
lRUCache.get(2); // return -1 (not found)
lRUCache.put(4, 4); // LRU key 1 evicted. cache: {4=4, 3=3}
lRUCache.get(1); // return -1 (not found)
lRUCache.get(3); // return 3
lRUCache.get(4); // return 4
Edge Cases to Consider
Capacity = 1: Every new key evicts the previous one immediately
Update existing key: put(k, v) on existing key updates value and marks as MRU
Get moves to front: Accessing a key via get() makes it most recently used
Key not found: get() returns -1, cache unchanged
Constraints
  • 1 ≤ capacity ≤ 3000
  • 0 ≤ key ≤ 104
  • 0 ≤ value ≤ 105
  • At most 2 × 105 calls to get and put
Complexity Target
get() O(1) Hash lookup + list pointer move
put() O(1) Hash insert + list operations
Space O(capacity) Map + List nodes storage
03 Merge K Sorted Lists
Min Heap Linked List Divide & Conquer

You are given an array of k linked-lists, where each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.

Examples
Example 1
Input:
lists = [[1,4,5], [1,3,4], [2,6]]
Output: [1, 1, 2, 3, 4, 4, 5, 6]
The linked-lists are:
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6
Example 2
Input: lists = []
Output: []
Example 3
Input: lists = [[]]
Output: []
Edge Cases to Consider
Empty Input: lists = [] → Return null
Empty Lists: lists = [[], []] → Return null
Single List: lists = [[1,2,3]] → Return the list itself
Constraints
  • k = lists.length, 0 ≤ k ≤ 104
  • 0 ≤ lists[i].length ≤ 500
  • -104 ≤ lists[i][j] ≤ 104
  • Total nodes N ≤ 104
Complexity Target
Time O(N log k) N = total nodes, k = number of lists
Space O(k) Min-Heap stores at most k nodes
04 Trapping Rain Water
Two PointersStackDP

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

Examples
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: Blue areas in diagram above represent trapped water.
Constraints & Complexity
  • n == height.length, 1 ≤ n ≤ 2 × 10⁴
  • 0 ≤ height[i] ≤ 10⁵
Target: Time O(n) | Space O(1) (Two Pointers approach)
05 Course Schedule
GraphTopological SortCycle Detection

You are required to take a total of numCourses courses, labeled from 0 to numCourses - 1.

Some courses have prerequisites, defined by the array prerequisites. Each element prerequisites[i] = [a, b] means that to take course a, you must first finish course b.

This dependency can be modeled as a directed edge from course b to course a (i.e., b -> a).

Return true if it is possible to finish all courses (i.e., there are no circular dependencies). Otherwise, return false.

Examples
Example 1
Input:
numCourses = 2, prerequisites = [[1,0]]
Output: true
Dependency: To take course 1, you must finish course 0 (0 -> 1).
Sequence: You can take course 0 first, then course 1.
All courses can be finished.
Example 2
Input:
numCourses = 2, prerequisites = [[1,0], [0,1]]
Output: false
Dependencies:
1. 0 -> 1 (Finish 0 before 1)
2. 1 -> 0 (Finish 1 before 0)
Analysis: This creates a cycle (0 -> 1 -> 0). It is impossible to complete either course.
Example 3
Input:
numCourses = 4, prerequisites = [[1,0], [2,1], [3,2]]
Output: true
Dependencies: 0 -> 1 -> 2 -> 3.
Sequence: Take courses in order: 0, 1, 2, then 3. No cycles exist.
Edge Cases to Consider
No Prerequisites: prerequisites = []. Always possible (true).
Self Loop: [0, 0]. Impossible to finish (false).
Disconnected Graph: Courses may form independent groups. All groups must be cycle-free.
Constraints & Complexity
  • 1 <= numCourses <= 2000
  • 0 <= prerequisites.length <= 5000
  • prerequisites[i].length == 2
  • All pairs [ai, bi] are distinct.
Target: Time O(V + E) | Space O(V + E) using DFS or Kahn's Algorithm (BFS).
06 Word Ladder
BFSGraphShortest Path

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

  • Every adjacent pair of words differs by a single letter.
  • Every si for 1 <= i <= k must be in wordList. Note that beginWord does not need to be in wordList.
  • sk == endWord.

Given two words, beginWord and endWord, and the dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord. If no such sequence exists, return 0.

Examples
Example 1
Input:
beginWord = "hit", endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
Output: 5
One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> "cog".
This sequence contains 5 words.
Example 2
Input:
beginWord = "hit", endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
Output: 0
The endWord "cog" is not in wordList, so there is no valid transformation sequence.
Example 3
Input:
beginWord = "a", endWord = "c"
wordList = ["a", "b", "c"]
Output: 2
"a" -> "c" is a valid sequence.
Note: Since "a" transforms directly to "c" (if allowed by rules of adjacency, here assumed typical substitution), length is 2. (Actually typically word ladder implies same length words, usually standard constraints apply).
Correction for clarity based on standard problem: "a" -> "c" changes 1 letter. "a" is start, "c" is end. Sequence: "a", "c". Count: 2.
Edge Cases to Consider
End Word Missing: If endWord is not in wordList, immediately return 0.
No Path: Words might exist but no chain of single-letter changes connects them.
Same Word: If beginWord equals endWord (typically not the case in constraints, but if so), length is 1.
Constraints & Complexity
  • 1 <= wordList.length <= 5000
  • wordList[i].length == beginWord.length == endWord.length
  • 1 <= beginWord.length <= 10
  • All words consist of lowercase English letters.
Target: Time O(M² * N) where M is word length, N is list size (Breadth-First Search).
07 Minimum Window Substring
Sliding WindowTwo Pointers

Given two strings s and t, return the minimum window substring of s such that every character in t (including duplicates) is included in the window.

If there is no such substring, return the empty string "".

Examples
Example 1
Input:
s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.
Example 2
Input:
s = "a", t = "a"
Output: "a"
The entire string s is the minimum window.
Example 3
Input:
s = "a", t = "aa"
Output: ""
Both 'a's from t must be included in the window. Since s only has one 'a', return empty string.
Edge Cases to Consider
Length check: If s.length < t.length, strictly impossible.
Constraints & Complexity
  • 1 <= s.length, t.length <= 10^5
  • s and t consist of uppercase and lowercase English letters.
Target: Time O(m + n) | Space O(1) (fixed char set)
08 Median of Two Sorted Arrays
Binary SearchDivide & Conquer

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

The overall run time complexity should be O(log (m+n)).

Examples
Example 1
Input:
nums1 = [1,3], nums2 = [2]
Output: 2.00000
Merged array = [1, 2, 3]. Median is 2.
Example 2
Input:
nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Merged array = [1, 2, 3, 4]. Median is (2 + 3) / 2 = 2.5.
Example 3
Input:
nums1 = [0,0], nums2 = [0,0]
Output: 0.00000
Constraints & Complexity
  • nums1.length == m, nums2.length == n
  • 0 <= m, n <= 1000
  • 1 <= m + n <= 2000
Target: The overall run time complexity should be O(log (m+n)).
09 Number of Islands
DFSBFSMatrix

Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

1
1
0
0
0
1
1
0
0
0
0
0
1
0
0
0
0
0
1
1
Examples
Example 1
Input:
grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
Output: 1
All '1's are connected.
Example 2
Input:
grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3
Constraints & Complexity
  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 300
Target: Time O(M × N) | Space O(M × N) (worst case recursion/queue)
10 Merge Intervals
SortingArrays

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

Examples
Example 1
Input:
intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Intervals [1,3] and [2,6] overlap. Merging them gives [1,6] (min start, max end).
Example 2
Input:
intervals = [[1,4],[4,5]]
Output: [[1,5]]
Intervals generally are treated as closed [a, b]. 4 touches 4, so they merge.
Edge Cases to Consider
Fully Contained: [[1,10], [2,5]] merges to [[1,10]].
Single Interval: Input [[1,2]] returns [[1,2]].
Constraints & Complexity
  • 1 <= intervals.length <= 10^4
  • intervals[i].length == 2
Target: Time O(N log N) (due to sorting)
11 Find Median from Data Stream
HeapDesign

The median is the middle value in an ordered integer list. If the size of the list is even, the median is the average of the two middle values.

Design a data structure that supports the following:

  • void addNum(int num) - Adds the integer num from the data stream to the data structure.
  • double findMedian() - Returns the median of all elements so far.
Examples
Example 1
Sequence:
addNum(1) → list: [1]
addNum(2) → list: [1, 2]
findMedian() → 1.5 ((1+2)/2)
addNum(3) → list: [1, 2, 3]
findMedian() → 2.0
Edge Cases to Consider
Negatives: Stream may contain negative integers.
Duplicates: Multiple instances of the same number are allowed and affect the median.
Constraints & Complexity
  • At most 5 * 10^4 calls in total.
  • -10^5 <= num <= 10^5
Target: addNum: O(log N), findMedian: O(1) (Two Heaps Strategy)
12 Binary Tree Maximum Path Sum
DFSRecursionTree

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

The path sum is the sum of the node's values in the path. Return the maximum path sum of any non-empty path.

Note: The path does not need to pass through the root.

Examples
Example 1
Input:
root = [1,2,3]
Output: 6
Path: 2 -> 1 -> 3. Sum: 2 + 1 + 3 = 6.
Example 2
Input:
root = [-10, 9, 20, null, null, 15, 7]
Output: 42
Optimal Path: 15 -> 20 -> 7. Sum: 15 + 20 + 7 = 42. Note node -10 is ignored.
Edge Cases to Consider
All Negative: If tree is [-3], output is -3 (must pick at least one node).
Constraints & Complexity
  • Number of nodes: [1, 3 * 10^4]
  • -1000 <= Node.val <= 1000
Target: Time O(N) | Space O(H) (Recursion Stack)
13 Serialize and Deserialize Binary Tree
BFS/DFSDesignTree

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

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

Examples
Example 1
Input Tree:
root = [1,2,3,null,null,4,5]
Action: deserialize(serialize(root))
Output Tree: [1,2,3,null,null,4,5]
Example 2
Input: [] (Empty Tree)
Output: []
Edge Cases to Consider
Format: You can use standard LeetCode level-order like "1,2,3,null,null" or preorder/postorder strings.
Constraints & Complexity
Target: Time O(N) | Space O(N)
14 Longest Palindromic Substring
DPString

Given a string s, return the longest palindromic substring in s.

A palindrome is a string that reads the same forward and backward.

Examples
Example 1
Input:
s = "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2
Input:
s = "cbbd"
Output: "bb"
Edge Cases to Consider
Single Char: "a" -> "a". Length 1.
Entire String: "racecar" -> "racecar".
Constraints & Complexity
  • 1 <= s.length <= 1000
  • s consist of only digits and English letters.
Target: Time O(N^2) (Expand Around Center)
15 Coin Change
DPKnapsack

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return the fewest number of coins needed to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

You may assume that you have an infinite number of each kind of coin.

Examples
Example 1
Input:
coins = [1,2,5], amount = 11
Output: 3
11 = 5 + 5 + 1. (3 coins)
Example 2
Input:
coins = [2], amount = 3
Output: -1
Cannot make 3 using only 2s.
Example 3
Input:
coins = [1], amount = 0
Output: 0
Edge Cases to Consider
Amount 0: Zero coins needed.
Impossible: Return -1.
Constraints & Complexity
  • 1 <= coins.length <= 12
  • 0 <= amount <= 10^4
Target: Time O(S * N) where S is amount, N is coins count.
16 Group Anagrams
Hash MapString

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

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Examples
Example 1
Input:
strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Example 2
Input:
strs = [""]
Output: [[""]]
Example 3
Input:
strs = ["a"]
Output: [["a"]]
Edge Cases to Consider
Empty String: Should be grouped as [""].
No Anagrams: If no two words match, each word is its own group.
Constraints & Complexity
  • 1 <= strs.length <= 10^4
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lowercase English letters.
Target: Time O(N * K log K) (Sort) or O(N * K) (Count) | Space O(N * K)
17 Kth Largest Element in an Array
QuickSelectHeap

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

Note that it is the kth largest element in the sorted order, not the kth distinct element.

Can you solve it without sorting?

Examples
Example 1
Input:
nums = [3,2,1,5,6,4], k = 2
Output: 5
Example 2
Input:
nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4
Edge Cases to Consider
Duplicates: Array may contain duplicates; they count towards the ranking.
Boundaries: k=1 (max) or k=n (min).
Constraints & Complexity
  • 1 <= k <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
Target: Time O(N) average (QuickSelect) or O(N log k) (Min Heap)
18 Product of Array Except Self
ArrayPrefix Sum

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

You must write an algorithm that runs in O(n) time and without using the division operation.

Examples
Example 1
Input:
nums = [1,2,3,4]
Output: [24,12,8,6]
Example 2
Input:
nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]
Edge Cases to Consider
Zeros: If there's one zero, all products are 0 except at that index. If two+ zeros, all 0.
Memory: Follow up: Can you solve it with O(1) extra space (output array doesn't count)?
Constraints & Complexity
  • 2 <= nums.length <= 10^5
  • -30 <= nums[i] <= 30
Target: Time O(N) | Space O(1) (excluding output array)
19 3Sum
Two PointersSorting

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

The solution set must not contain duplicate triplets.

Examples
Example 1
Input:
nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Example 2
Input:
nums = [0,1,1]
Output: []
Example 3
Input:
nums = [0,0,0]
Output: [[0,0,0]]
Edge Cases to Consider
Duplicates: Input [-2,0,1,1,2] should not yield duplicate triplets like [-2,1,1] twice.
Empty/Small: Fewer than 3 elements return [].
Constraints & Complexity
  • 0 <= nums.length <= 3000
  • -10^5 <= nums[i] <= 10^5
Target: Time O(N²) (Sort + Two Pointers)
20 Implement Trie (Prefix Tree)
TrieDesign

A Trie (pronounced as "try") or Prefix Tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.

Implement the Trie class:

  • void insert(String word) Inserts the string word into the trie.
  • boolean search(String word) Returns true if the string word is in the trie (i.e., was previously inserted), and false otherwise.
  • boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.
Examples
Example 1
Actions:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // return True
trie.search("app"); // return False
trie.startsWith("app"); // return True
trie.insert("app");
trie.search("app"); // return True
Edge Cases to Consider
Prefix vs Word: Searching "app" should return false if only "apple" was inserted, but startsWith("app") is true.
Empty String: Handle empty string insertions/searches if constraints allow.
Constraints & Complexity
  • 1 <= word.length, prefix.length <= 2000
  • word and prefix consist only of lowercase English letters.
  • At most 3 * 10^4 calls in total.
Target: Time O(L) per operation where L is word length | Space O(N*L)
21 Meeting Rooms II
HeapGreedyIntervals

Given an array of meeting time intervals intervals where intervals[i] = [start, end], return the minimum number of conference rooms required.

Examples
Example 1
Input:
intervals = [[0,30],[5,10],[15,20]]
Output: 2
Room 1: Use for [0, 30].
Room 2: Use for [5, 10], then reused for [15, 20].
Example 2
Input:
intervals = [[7,10],[2,4]]
Output: 1
Edge Cases to Consider
Touching Intervals: [1,5] and [5,10] do not overlap. Same room can be used.
Constraints & Complexity
  • 1 <= intervals.length <= 10^4
  • 0 <= start < end <= 10^6
Target: Time O(N log N) | Space O(N) (Min-Heap or Chronological Ordering)
22 Copy List with Random Pointer
Linked ListDeep Copy

Construct a deep copy of a linked list where each node contains an additional random pointer, which could point to any node in the list, or null.

The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list.

7
13
11
(Random pointers omitted for simplicity)
Examples
Example 1
Input:
head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]
Format: [val, random_index].
Edge Cases to Consider
Null Random: Some random pointers may be null.
Self Loop: A random pointer may point to the node itself.
Constraints & Complexity
  • 0 <= n <= 1000
  • -10^4 <= Node.val <= 10^4
Target: Time O(N) | Space O(1) (Interleaving nodes) or O(N) (HashMap)
23 Alien Dictionary
Topological SortGraph

There is a new alien language that uses the English alphabet. However, the order among the letters is unknown to you.

You are given a list of strings words from the alien language's dictionary, where the strings are sorted lexicographically by the rules of this new language.

Return a string of the unique letters in the new alien language sorted in lexicographically increasing order by the new rules. If there is no solution, return "". If there are multiple solutions, return any of them.

Examples
Example 1
Input:
words = ["wrt","wrf","er","ett","rftt"]
Output: "wertf"
Example 2
Input:
words = ["z","x"]
Output: "zx"
Example 3
Input:
words = ["z","x","z"]
Output: ""
The order is invalid (z < x and x < z implies cycle).
Edge Cases to Consider
Prefix Error: If input is ["abc", "ab"], this is invalid because "ab" is a prefix of "abc" but appears after it.
Cycles: a < b and b < a makes it impossible.
Constraints & Complexity
  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 100
Target: Time O(C) where C is total characters in all words (Graph Build + Topo Sort)
24 Task Scheduler
GreedyHeap

Given a characters array tasks, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle.

However, there is a non-negative integer n that represents the cooling period between two same tasks (the same letter in the array), that is that there must be at least n units of time between any two same tasks.

Return the least number of units of time that the CPU will take to finish all the given tasks.

Examples
Example 1
Input:
tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
A -> B -> idle -> A -> B -> idle -> A -> B.
There is at least 2 units between each 'A' and each 'B'.
Example 2
Input:
tasks = ["A","A","A","B","B","B"], n = 0
Output: 6
No cooling needed: A -> A -> A -> B -> B -> B.
Edge Cases to Consider
Idle Time: If n is large, we might need many idle slots.
Bottleneck: The most frequent task determines the bulk of the schedule.
Constraints & Complexity
  • 1 <= tasks.length <= 10^4
  • 0 <= n <= 100
Target: Time O(N) (Count freqs) | Space O(1) (26 chars)
25 Lowest Common Ancestor
DFSTree

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

The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).

Examples
Example 1
Input:
root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
The LCA of 5 and 1 is 3.
Example 2
Input:
root = [3,5,1...], p = 5, q = 4
Output: 5
The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself.
Edge Cases to Consider
Direct Ancestry: If p is a child of q, then q is the LCA.
Constraints & Complexity
  • The number of nodes value is in the range [2, 10^5].
  • p != q
  • p and q will exist in the tree.
Target: Time O(N) | Space O(H) (Recursion Stack)
26 Word Break
DPTrie

Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.

Note that the same word in the dictionary may be reused multiple times in the segmentation.

Examples
Example 1
Input:
s = "leetcode", wordDict = ["leet","code"]
Output: true
Return true because "leetcode" can be segmented as "leet code".
Example 2
Input:
s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output: false
Edge Cases to Consider
Reuse: "applepenapple" with ["apple", "pen"] is valid (apple reused).
Constraints & Complexity
  • 1 <= s.length <= 300
  • 1 <= wordDict.length <= 1000
  • All strings consist of lowercase English letters.
Target: Time O(N³) or O(N² * K) (DP)
27 Container With Most Water
Two PointersGreedy

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

Find two lines that together with the x-axis form a container, such that the container contains the most water.

Return the maximum amount of water a container can store.

Examples
Example 1
Input:
height = [1,8,6,2,5,4,8,3,7]
Output: 49
The lines at index 1 (height 8) and index 8 (height 7) form the container.
Area = min(8, 7) * (8 - 1) = 7 * 7 = 49.
Example 2
Input:
height = [1,1]
Output: 1
Edge Cases to Consider
Width vs Height: Sometimes shorter lines farther apart yield more area than tall lines close together.
Constraints & Complexity
  • n == height.length
  • 2 <= n <= 10^5
  • 0 <= height[i] <= 10^4
Target: Time O(N) | Space O(1)
28 Design Add and Search Words
TrieBacktracking

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

Implement the WordDictionary class:

  • void addWord(word) Adds word to the data structure.
  • bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter.
Examples
Example 1
Actions:
WordDictionary wd = new WordDictionary();
wd.addWord("bad");
wd.addWord("dad");
wd.addWord("mad");
wd.search("pad"); // return False
wd.search("bad"); // return True
wd.search(".ad"); // return True
wd.search("b.."); // return True
Edge Cases to Consider
All Dots: "..." matches any 3-letter word.
Length Mismatch: "pad" (length 3) should not match "padd" (length 4).
Constraints & Complexity
  • 1 <= word.length <= 25
  • At most 10^4 calls.
Target: Search: O(M) for no dots, O(M * 26) with dots
29 Regular Expression Matching
DPRecursion

Implement regular expression matching with support for '.' and '*'.

  • '.' Matches any single character.
  • '*' Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

Examples
Example 1
Input:
s = "aa", p = "a"
Output: false
"a" does not match the entire string "aa".
Example 2
Input:
s = "aa", p = "a*"
Output: true
'*' means zero or more of the preceding 'a'. We match two 'a's.
Example 3
Input:
s = "ab", p = ".*"
Output: true
".*" means "zero or more (*) of any character (.)".
Edge Cases to Consider
Empty Match: p = "c*a*b*" can match empty string "".
Constraints & Complexity
  • 1 <= s.length <= 20
  • 1 <= p.length <= 20
  • s contains only lowercase English letters.
  • p contains only lowercase English letters, '.', and '*'.
Target: Time O(M*N) | Space O(M*N) (DP Matrix)
30 Longest Increasing Path in Matrix
DFSMemoization

Given an m x n integers matrix, return the length of the longest increasing path.

From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed).

Examples
Example 1
Input:
matrix = [[9,9,4],[6,6,8],[2,1,1]]
Output: 4
The longest increasing path is [1, 2, 6, 9].
Example 2
Input:
matrix = [[3,4,5],[3,2,6],[2,2,1]]
Output: 4
The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.
Edge Cases to Consider
No Increase: If all items are equal, path length is 1.
Constraints & Complexity
  • m == matrix.length, n == matrix[i].length
  • 1 <= m, n <= 200
  • 0 <= matrix[i][j] <= 2^31 - 1
Target: Time O(M*N) | Space O(M*N)
08 Rotate Image
MatrixMath

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

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Examples
Example 1
Input:
matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]
Rows become columns in reverse order.
Example 2
Input:
matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
Edge Cases to Consider
1x1 Matrix: A single element remains unchanged.
Constraints & Complexity
  • n == matrix.length == matrix[i].length
  • 1 <= n <= 20
  • -1000 <= matrix[i][j] <= 1000
Target: Time O(N²) | Space O(1) (In-place)
09 Subarray Sum Equals K
Hash MapPrefix Sum

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

Examples
Example 1
Input:
nums = [1,1,1], k = 2
Output: 2
The subarrays [1,1] (indices 0,1) and [1,1] (indices 1,2) sum to 2.
Example 2
Input:
nums = [1,2,3], k = 3
Output: 2
Subarrays [1,2] and [3] sum to 3.
Edge Cases to Consider
Negative Numbers: Input can contain negative numbers (prefix sum + hashmap needed, sliding window won't work).
Constraints & Complexity
  • 1 <= nums.length <= 2 * 10^4
  • -1000 <= nums[i] <= 1000
  • -10^7 <= k <= 10^7
Target: Time O(N) | Space O(N) (Using HashMap)
10 Longest Repeating Character Replacement
Sliding WindowString

You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character.

You can perform this operation at most k times.

Return the length of the longest substring containing the same letter you can get after performing the above operations.

Examples
Example 1
Input:
s = "ABAB", k = 2
Output: 4
Replace the two 'A's with two 'B's or vice versa.
Example 2
Input:
s = "AABABBA", k = 1
Output: 4
Replace the one 'A' in the middle with 'B' and form "AABBBBA". The longest same-letter substring is "BBBB", which is length 4.
Edge Cases to Consider
Full Replacement: If k is large enough, we can change the whole string (length N).
No Changes Needed: If the string is already uniform "AAAA", result is N.
Constraints & Complexity
  • 1 <= s.length <= 10^5
  • 0 <= k <= s.length
Target: Time O(N) | Space O(1) (26 uppercase chars)
11 Permutation in String
Sliding WindowHash Map

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

In other words, return true if one of s1's permutations is the substring of s2.

Examples
Example 1
Input:
s1 = "ab", s2 = "eidbaooo"
Output: true
s2 contains one permutation of s1 ("ba").
Example 2
Input:
s1 = "ab", s2 = "eidboaoo"
Output: false
Edge Cases to Consider
Length Check: If s1.length > s2.length, immediately return false.
Constraints & Complexity
  • 1 <= s1.length, s2.length <= 10^4
  • Strings constist of lowercase English letters.
Target: Time O(N) | Space O(1) (26 lowercase chars)
12 Valid Parentheses
StackString

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

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
  3. Every close bracket has a corresponding open bracket of the same type.

Examples
Example 1
Input:
s = "()[]{}"
Output: true
Example 2
Input:
s = "(]"
Output: false
Edge Cases to Consider
Starts Closed: A string like "]" or "){" is invalid immediately.
Leftover Open and Empty: "(((" is invalid (stack not empty). Empty string is valid.
Constraints & Complexity
  • 1 <= s.length <= 10^4
  • s consists of parentheses only.
Target: Time O(N) | Space O(N) (Stack)
13 Generate Parentheses
BacktrackingRecursion

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

Examples
Example 1
Input:
n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2
Input:
n = 1
Output: ["()"]
Edge Cases to Consider
Constraints: Must maintain open < n to add '(' and close < open to add ')'.
Constraints & Complexity
  • 1 <= n <= 8
Target: Time O(4^N / sqrt(N)) (Catalan Number)
14 Daily Temperatures
Monotonic StackArray

Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature.

If there is no future day for which this is possible, keep answer[i] == 0.

Examples
Example 1
Input:
temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]
Example 2
Input:
temperatures = [30,40,50,60]
Output: [1,1,1,0]
Edge Cases to Consider
Decreasing Order: If temps are [50, 40, 30], result is all 0s.
Constraints & Complexity
  • 1 <= temperatures.length <= 10^5
  • 30 <= temperatures[i] <= 100
Target: Time O(N) | Space O(N) (Monotonic Stack)
15 Invert Binary Tree
TreeRecursion

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

(Swap left and right children for every node).

Examples
Example 1
Input:
root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]
Example 2
Input:
root = [2,1,3]
Output: [2,3,1]
Edge Cases to Consider
Empty Tree: Return null.
Leaf Node: A node with no children remains unchanged (just returns itself).
Constraints & Complexity
  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100
Target: Time O(N) | Space O(N) (Recursion Depth)
16 Validate Binary Search Tree
DFSTree

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

A valid BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

Examples
Example 1
Input:
root = [2,1,3]
Output: true
Example 2
Input:
root = [5,1,4,null,null,3,6]
Output: false
The root node's value is 5 but its right child's value is 4 (4 < 5, invalid).
Edge Cases to Consider
Range Check: Simply checking left < node < right for each node is NOT enough. Need to pass down (min, max) ranges.
Constraints & Complexity
  • The number of nodes in the tree is in the range [1, 10^4].
  • -2^31 <= Node.val <= 2^31 - 1
Target: Time O(N) | Space O(N) (Recursion)
17 Binary Tree Level Order Traversal
BFSQueue

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

(i.e., from left to right, level by level).

Examples
Example 1
Input:
root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
Example 2
Input:
root = [1]
Output: [[1]]
Edge Cases to Consider
Empty Tree: Input [] should return [].
Constraints & Complexity
  • The number of nodes in the tree is in the range [0, 2000].
  • -1000 <= Node.val <= 1000
Target: Time O(N) | Space O(N) (Queue)
18 Kth Smallest Element in a BST
DFSTree

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

Examples
Example 1
Input:
root = [3,1,4,null,2], k = 1
Output: 1
Example 2
Input:
root = [5,3,6,2,4,null,null,1], k = 3
Output: 3
Edge Cases to Consider
In-Order Property: In-order traversal of a BST gives sorted values. Stop at k-th visited node.
Constraints & Complexity
  • The number of nodes in the tree is n.
  • 1 <= k <= n <= 10^4
  • 0 <= Node.val <= 10^4
Target: Time O(H + k) | Space O(H) (Stack)
19 Construct Binary Tree from Preorder and Inorder
RecursionTree

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

Examples
Example 1
Input:
preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
Example 2
Input:
preorder = [-1], inorder = [-1]
Output: [-1]
Edge Cases to Consider
Uniqueness: Problem guarantees unique values, so we can use a HashMap to find index in inorder array quickly.
Constraints & Complexity
  • 1 <= preorder.length <= 3000
  • inorder.length == preorder.length
Target: Time O(N) | Space O(N) (HashMap)
20 Clone Graph
GraphDFS/BFS

Given a reference of a node in a connected undirected graph.

Return a deep copy (clone) of the graph.

Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors.

Examples
Example 1
Input:
adjList = [[2,4],[1,3],[2,4],[1,3]]
Output: [[2,4],[1,3],[2,4],[1,3]]
There are 4 nodes in the graph. 1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). 3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
Edge Cases to Consider
Empty Graph: Function should simply return null.
Cycles: Graph may contain cycles, must use visited map to avoid infinite loops.
Constraints & Complexity
  • The number of nodes in the graph is in the range [0, 100].
  • 1 <= Node.val <= 100
  • Node.val is unique for each node.
Target: Time O(V + E) | Space O(V) (HashMap)
21 Rotting Oranges
Multi-Source BFSMatrix

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

  • 0 representing an empty cell,
  • 1 representing a fresh orange, or
  • 2 representing a rotten orange.

Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.

Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.

Minute 0
Minute 1
Minute 2
Minute 3
Minute 4
Examples
Example 1
Input:
grid = [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Example 2
Input:
grid = [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
Edge Cases to Consider
No Fresh Oranges: If start with 0 fresh oranges, return 0.
No Rotten Oranges: If fresh oranges exist but no rotten ones, they can never rot. Return -1.
Constraints & Complexity
  • m == grid.length, n == grid[i].length
  • 1 <= m, n <= 10
  • grid[i][j] is 0, 1, or 2.
Target: Time O(M * N) | Space O(M * N) (Queue)
22 House Robber
DPArray

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

Examples
Example 1
Input:
nums = [1,2,3,1]
Output: 4
Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount = 1 + 3 = 4.
Example 2
Input:
nums = [2,7,9,3,1]
Output: 12
Rob house 1 (money = 2), house 3 (money = 9) and house 5 (money = 1). Total amount = 2 + 9 + 1 = 12.
Edge Cases to Consider
Single House: If len is 1, return the value of that house.
Two Houses: Return max(nums[0], nums[1]).
Constraints & Complexity
  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 400
Target: Time O(N) | Space O(1) (DP Optimization)
23 Unique Paths
DPCombinatorics

There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]).

The robot can only move either down or right at any point in time.

Return the number of possible unique paths that the robot can take to reach the bottom-right corner.

Examples
Example 1
Input:
m = 3, n = 7
Output: 28
Example 2
Input:
m = 3, n = 2
Output: 3
From top-left (0,0) to bottom-right (2,1), there are 3 paths: 1. Right -> Down -> Down 2. Down -> Down -> Right 3. Down -> Right -> Down
Edge Cases to Consider
1D Grid: If m=1 or n=1, there is only 1 path (straight line).
Constraints & Complexity
  • 1 <= m, n <= 100
Target: Time O(M * N) | Space O(N) (Row Optimization)
24 Longest Common Subsequence
DPString

Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.

A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

Examples
Example 1
Input:
text1 = "abcde", text2 = "ace"
Output: 3
The longest common subsequence is "ace" and its length is 3.
Example 2
Input:
text1 = "abc", text2 = "abc"
Output: 3
Example 3
Input:
text1 = "abc", text2 = "def"
Output: 0
Edge Cases to Consider
No Overlap: If no characters match, result is 0.
Constraints & Complexity
  • 1 <= text1.length, text2.length <= 1000
  • Inputs consist of lowercase English characters.
Target: Time O(M * N) | Space O(M * N)
25 Decode Ways
DPString

A message containing letters from A-Z can be encoded into numbers using the following mapping:

  • 'A' -> "1"
  • 'B' -> "2"
  • ...
  • 'Z' -> "26"

To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways).

Given a string s containing only digits, return the number of ways to decode it.

Examples
Example 1
Input:
s = "12"
Output: 2
It could be decoded as "AB" (1 2) or "L" (12).
Example 2
Input:
s = "226"
Output: 3
"BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
Example 3
Input:
s = "06"
Output: 0
"06" cannot be mapped because "0" has no mapping.
Edge Cases to Consider
Leading Zeros: "0..." is invalid immediately.
Invalid Pairs: "30", "40", etc., are impossible as 2-digit pairs.
Constraints & Complexity
  • 1 <= s.length <= 100
Target: Time O(N) | Space O(1)
26 Subsets
BacktrackingBit Manipulation

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

The solution set must not contain duplicate subsets. Return the solution in any order.

Examples
Example 1
Input:
nums = [1,2,3]
Output: [[1,2,3],[1,2],[1,3],[1],[2,3],[2],[3],[]]
Example 2
Input:
nums = [0]
Output: [[0],[]]
Edge Cases to Consider
Empty Input: If nums is [], return [[]].
Constraints & Complexity
  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10
  • All the numbers of nums are unique.
Target: Time O(N * 2^N)
27 Permutations
BacktrackingRecursion

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

Examples
Example 1
Input:
nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Example 2
Input:
nums = [0,1]
Output: [[0,1],[1,0]]
Example 3
Input:
nums = [1]
Output: [[1]]
Edge Cases to Consider
Factorial Growth: N! grows very fast. N=10 is 3.6 million.
Constraints & Complexity
  • 1 <= nums.length <= 6
  • -10 <= nums[i] <= 10
  • All the integers of nums are unique.
Target: Time O(N * N!)
28 Combination Sum
BacktrackingRecursion

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

The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.

Examples
Example 1
Input:
candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
Example 2
Input:
candidates = [2], target = 1
Output: []
Edge Cases to Consider
Unreachable Target: Return empty list if no combination sums to target.
Constraints & Complexity
  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • 1 <= target <= 40
Target: Time O(N^(T/M)) (Exponential)
29 Top K Frequent Elements
HeapBucket Sort

Given an integer array nums and an integer k, return the k most frequent elements.

You may return the answer in any order.

Examples
Example 1
Input:
nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2
Input:
nums = [1], k = 1
Output: [1]
Edge Cases to Consider
All Distinct: If all elements occur once, return any k elements.
Constraints & Complexity
  • 1 <= nums.length <= 10^5
  • k is in the range [1, the number of unique elements in the array].
  • It is guaranteed that the answer is unique.
Target: Time O(N) (Bucket Sort) or O(N log k) (Heap)
30 Reorder List
Linked ListTwo Pointers

You are given the head of a singly linked-list. The list can be represented as: L0 → L1 → … → Ln-1 → Ln.

Reorder the list to be on the following form: L0 → Ln → L1 → Ln-1 → L2 → Ln-2 …

You may not modify the values in the list's nodes. Only nodes themselves may be changed.

Examples
Example 1
Input:
head = [1,2,3,4]
Output: [1,4,2,3]
Example 2
Input:
head = [1,2,3,4,5]
Output: [1,5,2,4,3]
Edge Cases to Consider
Single Node: No change needed.
Constraints & Complexity
  • The number of nodes in the list is in the range [1, 5 * 10^4].
  • 1 <= Node.val <= 1000
Target: Time O(N) | Space O(1)