1. 1.1 Data Structures and Algorithmshistorical

    Learning data structures and algorithms starts with a programming language and practice with concrete problems. This page collects links to the related notes.

  2. 2.1 arrayhistorical

    A dynamic array tracks its length and capacity on top of a fixed-size array, expanding when space runs out. The notes include its structure, API, and implementation.

  3. 2.2 hashmaphistorical

    A map associates keys with values. These notes compare search-tree and hash-table implementations, including hashing, collision handling, and resizing.

  4. 2.3 linkedlisthistorical

    Arrays support indexed access, while linked lists insert and remove elements by changing links. These notes implement singly and doubly linked lists with APIs and test examples.

  5. 2.4 queuehistorical

    A queue stores and retrieves elements in first-in, first-out order. These notes cover ordinary and circular queues with their structures, APIs, and implementations.

  6. 2.5 sethistorical

    A set stores distinct elements. These notes implement a set using a hash map, with its data structure, API, and test examples.

  7. 2.6 stackhistorical

    A stack retrieves elements in last-in, first-out order and can be implemented with a dynamic array or linked list. The notes include its API, implementation, and test examples.

  8. 2.7 treehistorical

    Each binary-tree node has at most two children. These notes introduce common operations through preorder, inorder, postorder, and level-order traversal.

  9. 2.8 Red-Black Treehistorical

    A red-black tree is a balanced binary search tree that maintains balance through node colors and structural rules. These notes introduce its five properties.

  10. 2.9 Skip Listhistorical

    A skip list adds multiple levels of index links to a linked list, trading extra space for faster search. The bottom level holds all elements, while higher levels narrow the search.

  11. 2.10 heaphistorical

    A heap is logically a tree that can be stored in an array. Max-heaps and min-heaps maintain order through parent-child value relationships.

  12. 2.11 BitMaphistorical

    A bitmap records whether values exist using individual bits: 1 indicates presence and 0 indicates absence.

  13. 2.12 BloomFilterhistorical

    BloomFilter: A website has 2 billion URLs in a blacklist. How should this blacklist be stored? If a URL is entered, how can we quickly determine whether it is in this blacklist, while keeping within a given memory limit such as 500 MB?

  14. 2.13 graphhistorical

    A graph consists of vertices and edges. It may be directed or undirected, weighted or unweighted, and represented with an adjacency matrix or adjacency list.

  15. 2.14 UnionFindhistorical

    Union-find represents connectivity with parent-linked trees. These notes work through Quick Find, Quick Union, and their optimizations.

  16. 2.15 LSMhistorical

    An LSM tree, or log-structured merge-tree, serves write-heavy workloads by organizing and merging data around sequential disk writes.

  17. Longest Common Substringhistorical

    Given two strings str1 and str2, return their longest common substring. The problem guarantees that the longest common substring of str1 and str2 exists and is unique.

  18. 2.16 ziplisthistorical

    Ziplist is a compact data structure used inside Redis. These notes record its relationship to data types such as lists and sorted sets.

  19. Longest Common Subsequencehistorical

    Given two strings text1 and text2, return the length of their longest common subsequence.

  20. 2.17 B Treehistorical

    A B-tree is a balanced multiway search tree. These notes explain its structure and use cases through exact-match and range-query requirements.

  21. Longest Substring Without Repeating Charactershistorical

    Given an array, return the length of its longest contiguous subarray without repeated elements.

  22. 2.18 Sparse Indexhistorical

    A sparse index stores entries for only some keys, using less space than a dense index. These notes compare their structures, lookup methods, and usage conditions.

  23. 2.19 Indexhistorical

    An index associates search keys with data records to speed up lookups. These notes compare sparse and dense indexes, as well as forward and inverted indexes.

  24. 2.20 Inverted Indexhistorical

    A forward index maps document IDs to documents, while an inverted index maps terms to document IDs to find documents containing a given term.

  25. 3.1 Cache Replacement Policieshistorical

    Caches have limited space and must evict data when full. These notes compare how strategies such as FIFO and LRU choose what to retain or remove.

  26. 3.2 Dynamic Programminghistorical

    Dynamic programming can be derived from recursion and memoization. These notes use path-counting examples to explain states, transitions, and optimal substructure.

  27. 3.3 Greedyhistorical

    A greedy algorithm makes the best available choice at each step. These notes explore this approach through loading and coin-change problems.

  28. 3.4 Divide and Conquerhistorical

    Divide and conquer splits a problem into smaller problems of the same structure, solves them recursively, and combines their results.

  29. 3.5 Recursionhistorical

    Recursion lets a function call itself, breaking a problem into smaller cases until they can be solved directly and their results returned through the call chain.

  30. Edit Distancehistorical

    Given two words word1 and word2, calculate the minimum number of operations required to convert word1 into word2.

  31. 3.6 Backtrackinghistorical

    Backtracking explores a choice, continues while it remains viable, and returns to try alternatives when it fails. These notes illustrate it with problems such as eight queens.

  32. 3.7 DFShistorical

    Depth-first search is commonly used for string, array, and tree problems, often together with backtracking. These notes explore it through permutation and combination examples.

  33. 3.8 Binary Searchhistorical

    Binary search compares a target with the middle element of a sorted array, then continues in the left or right half to narrow the search.

  34. 3.9 Bubble Sorthistorical

    Bubble sort repeatedly scans an array, comparing adjacent elements and swapping out-of-order pairs until the array is sorted.

  35. 3.10 Linear Searchhistorical

    Linear search compares array elements one by one, returning the target's index or -1 if it is absent. The notes include a Go implementation and test examples.

  36. 3.11 Heap Sorthistorical

    Heap sort builds a heap and repeatedly removes the root while restoring the heap structure. The notes include implementation, tests, and complexity analysis.

  37. Next Permutationhistorical

    Implement a function that obtains the next permutation. The algorithm must rearrange the given sequence of numbers into the next lexicographically greater permutation.

  38. 3.12 Merge Sorthistorical

    Merge sort repeatedly divides an array until each part is sorted, then merges the sorted parts to produce the final array.

  39. Permutationshistorical

    Given a sequence of distinct numbers, return all possible permutations.

  40. 3.13 Insertion Sorthistorical

    Insertion sort divides an array into sorted and unsorted parts, taking one element at a time and inserting it into the appropriate position in the sorted part.

  41. Subsetshistorical

    Given an integer array nums whose elements are all distinct, return all possible subsets (the power set).

  42. 3.14 Quick Sorthistorical

    Quicksort selects a pivot, moves smaller values to one side and larger values to the other, then repeats the process on each partition.

  43. Unique Pathshistorical

    A robot starts at the top-left corner of an m × n grid and can move only down or right. Count the paths to the bottom-right corner.

  44. 3.15 Selection Sorthistorical

    Selection sort finds the largest or smallest element on each pass and places it in position, reducing the number of swaps compared with bubble sort.

  45. Number of Islandshistorical

    Given a 2D grid consisting of '1' (land) and '0' (water), calculate the number of islands in the grid.

  46. 3.16 Sortinghistorical

    This page collects notes on bubble, selection, insertion, merge, quick, and heap sort, comparing their time complexity, space complexity, and stability.

  47. 4.1 Compare-and-Swap (CAS)historical

    Compare-and-Swap (CAS): CAS (Compare-and-Swap) is an atomic operation: compare the current value in memory with an expected value, and replace it with a new value only when they match.

  48. Maximal Squarehistorical

    In a 2D matrix consisting of '0' and '1', find the largest square containing only '1' and return its area.

  49. 4.2 Lock-Free Queuehistorical

    A Lock-Free Queue is a thread-safe queue implemented with lock-free techniques, usually relying on CAS and other atomic operations to coordinate concurrent updates.

  50. Course Schedulehistorical

    Given numCourses courses and their prerequisite relationships, determine whether all courses can be completed.

  51. Partition Equal Subset Sumhistorical

    Given a non-empty array containing only positive integers, determine whether the array can be partitioned into two subsets whose sums are equal.

  52. Word Breakhistorical

    Given a non-empty string s and a list wordDict containing non-empty words, determine whether s can be segmented by spaces into one or more words that appear in the dictionary.

  53. Perfect Squareshistorical

    Given a positive integer n, find several perfect-square numbers (such as 1, 4, 9, 16, ...) whose sum equals n. You need to minimize the number of perfect squares used.

  54. Word Searchhistorical

    Given a two-dimensional grid and a word, determine whether the word exists in the grid.

  55. Target Sumhistorical

    Assign a plus or minus sign to each number in a nonnegative integer array and count the assignments whose sum equals the target S.

  56. Longest Common Substringhistorical

    Given two strings str1 and str2, output their longest common substring. The problem guarantees that the longest common substring of str1 and str2 exists and is unique.

  57. Combination Sumhistorical

    Given an array candidates containing no duplicate elements and a target number target, find all combinations of numbers in candidates whose sum equals target.

  58. Design an LRU Cachehistorical

    Design an LRU cache with a fixed capacity K that supports key lookups and writes, evicting the least recently used entry when capacity is reached.

  59. Coin Changehistorical

    Given coins of different denominations and a total amount, write a function to compute the minimum number of coins needed to make up that amount. If no combination of coins can make up the amount, return -1.

  60. Longest Common Subsequencehistorical

    Given two strings text1 and text2, return the length of their longest common subsequence.

  61. Burst Balloonshistorical

    Each balloon carries a number, and bursting it earns points based on its neighbors. Choose a bursting order that maximizes the total score.

  62. Letter Combinations of a Phone Numberhistorical

    Given a string containing only digits 2-9, return all letter combinations it can represent. The answer may be returned in any order.

  63. House Robberhistorical

    You are a professional robber planning to rob houses along a street. Each house contains some cash. The only constraint is that adjacent houses have connected security systems, and the alarm will automatically trigger if two adjacent houses are broken into on the same night.

  64. Edit Distancehistorical

    Given two words word1 and word2, calculate the minimum number of operations required to convert word1 into word2.

  65. Best Time to Buy and Sell Stock with Cooldownhistorical

    Given daily stock prices, find the maximum trading profit when selling a stock requires a one-day cooldown before buying again.

  66. Group Anagramshistorical

    Given an array of strings, group the anagrams together. Anagrams contain the same letters but in a different order.

  67. Minimum Path Sumhistorical

    Given an m x n grid of non-negative integers, find a path from the top-left corner to the bottom-right corner such that the sum of the numbers along the path is minimized.

  68. Find All Anagrams in a Stringhistorical

    Given a string s and a non-empty string p, find all substrings in s that are anagrams of p and return their starting indexes.

  69. Longest Increasing Subsequencehistorical

    Given an integer array nums, find the length of the longest strictly increasing subsequence.

  70. Longest Common Prefixhistorical

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

  71. Jump Gamehistorical

    Each element of a nonnegative integer array gives the maximum jump length from that position. Determine whether the last position is reachable.

  72. Maximum Product Subarrayhistorical

    Given an integer array nums, find the contiguous subarray with the largest product (the subarray contains at least one number) and return that product.

  73. Check Palindromehistorical

    Given a string, write a function to determine whether it is a palindrome. Return true if it is, otherwise return false.

  74. Maximum Subarrayhistorical

    Given an integer array nums, find the contiguous subarray with the largest sum (the subarray contains at least one element) and return its sum.

  75. Reverse Stringhistorical

    Write a program that accepts a string and outputs the reversed string. (The string length does not exceed 1000.).

  76. First Missing Positivehistorical

    Given an unsorted integer array nums, find the smallest positive integer that does not appear in the array.

  77. Palindromic Substringshistorical

    Given a string, calculate how many palindromic substrings it contains.

  78. 3Sumhistorical

    Given an array nums containing n integers, determine whether there are three elements a, b, and c such that a + b + c = 0. Find all unique triplets whose sum is 0.

  79. Find the Duplicate Numberhistorical

    Given n + 1 integers whose values range from 1 to n, find the repeated number.

  80. Longest Palindromic Substringhistorical

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

  81. Two Sumhistorical

    Given an integer array, find two numbers in the array whose sum equals the target value. The twoSum function should return the indices of these two numbers (index1, index2), with index1 < index2.

  82. Find All Numbers Disappeared in an Arrayhistorical

    An array of length n contains values from 1 to n, some once and some twice. Find the values in this range that do not appear in the array.

  83. Big Number Additionhistorical

    Read two numbers as strings, write a function to calculate their sum, and return the result as a string. (The string length does not exceed 100000, and each string contains only the ten characters '0'~'9'.).

  84. Subarray Sum Equals Khistorical

    Given an integer array and an integer k, find the number of contiguous subarrays whose sum equals k.

  85. Longest Consecutive Sequencehistorical

    Given an unsorted integer array nums, find the length of the longest sequence of consecutive numbers. The elements do not need to be contiguous in the original array.

  86. Decode Stringhistorical

    Given an encoded string, return its decoded string.

  87. Longest Valid Parentheseshistorical

    Given a string containing only '(' and ')', find the length of the longest valid (well-formed and consecutive) parentheses substring.

  88. Remove Invalid Parentheseshistorical

    Given a string s containing parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.

  89. Generate Parentheseshistorical

    The number n represents the number of pairs of parentheses. Design a function that can generate all possible valid combinations of parentheses.

  90. Valid Parentheseshistorical

    Given a string containing only the characters '(', ')', '{', '}', '[' and ']', determine whether the string is a valid parentheses sequence. Parentheses must close in the correct order.

  91. Regular Expression Matchinghistorical

    Given a string s and a pattern p, implement regular expression matching with support for '.' and '*'.

  92. Binary Search Upper Boundhistorical

    Implement binary search on an ascending array that may contain duplicate values. Return the position of the first value greater than or equal to the target.

  93. Longest Substring Without Repeating Charactershistorical

    Given an array, return the length of its longest contiguous subarray without repeated elements.

  94. Find First and Last Position of Element in Sorted Arrayhistorical

    Given an integer array nums sorted in ascending order and a target value target, find the starting and ending positions of the target value in the array.

  95. Evaluate Divisionhistorical

    Given an array of variable pairs equations and an array of real values values as known conditions, where equations[i] = [Ai, Bi] and values[i] together represent the equation Ai / Bi = values[i].

  96. Counting Bitshistorical

    Given a non-negative integer num. For every number i in the range 0 ≤ i ≤ num, calculate the number of 1s in its binary representation and return them as an array.

  97. Hamming Distancehistorical

    The Hamming distance between two integers is the number of positions at which their corresponding binary bits are different.

  98. Binary Search Upper Boundhistorical

    Implement binary search on an ascending array that may contain duplicate values. Return the position of the first value greater than or equal to the target.

  99. Reverse Integerhistorical

    Given a 32-bit signed integer x, return the result of reversing the digits of x.

  100. Find First and Last Position of Element in Sorted Arrayhistorical

    Given an integer array nums sorted in ascending order and a target value target, find the starting and ending positions of the target value in the array.

  101. Climbing Stairshistorical

    A staircase has n steps, and each move climbs one or two steps. Count the distinct ways to reach the top.

  102. Search in Rotated Sorted Arrayhistorical

    Given a rotated sorted array whose rotation count is unknown in advance (for example, 0 1 2 4 5 6 7 may become 4 5 6 7 0 1 2). Search for the given target value in the array.

  103. Search in Rotated Sorted Arrayhistorical

    Given a rotated sorted array whose rotation count is unknown in advance (for example, 0 1 2 4 5 6 7 may become 4 5 6 7 0 1 2). Search for the given target value in the array.

  104. Merge Two Sorted Arrayshistorical

    Merge two sorted integer arrays A and B into A while preserving order. Assume A has enough space for all elements.

  105. Find Peak Elementhistorical

    A peak element is strictly greater than its neighbors. Find a peak in the given array and return its index.

  106. Find the K-th Largesthistorical

    Given an integer array, use the idea of quicksort to find the K-th largest number in the array.

  107. Binary Searchhistorical

    Given an n-element sorted (ascending) integer array nums and a target value target, write a function to search for target in nums. If the target exists, return its index; otherwise return -1.

  108. Find Minimum in Rotated Sorted Arrayhistorical

    Given a rotated ascending array, find its minimum element.

  109. Square Roothistorical

    Implement the function int sqrt(int x). Compute and return the square root of x, rounded down.

  110. Spiral Matrixhistorical

    Given an m-row, n-column matrix, return all elements of the matrix in clockwise spiral order.

  111. Find Smallest Letter Greater Than Targethistorical

    Given a sorted list of characters letters containing only lowercase English letters, and a target letter target, find the smallest letter in this ordered list that is greater than the target letter.

  112. Trapping Rain Waterhistorical

    Given n non-negative integers representing an elevation map where each bar has width 1, calculate how much rain water can be trapped after raining.

  113. Container With Most Waterhistorical

    Given the heights of vertical lines, choose two lines that form a container with the horizontal axis and maximize its water-holding area.

  114. Queue Reconstruction by Heighthistorical

    Each person is described by their height and the number of people at least as tall ahead of them. Reconstruct the queue from these shuffled descriptions.

  115. Largest Numberhistorical

    Given a group of non-negative integers nums, rearrange the order of each number (each number cannot be split) so that they form the largest integer.

  116. String Permutationshistorical

    Given a string, print all permutations of its characters in lexicographic order. For example, given the string abc, print all strings formed by a, b, and c in lexicographic order: abc, acb, bac, bca, cab, and cba.

  117. Top K Frequent Elementshistorical

    Given a non-empty integer array, return the k most frequent elements.

  118. Majority Elementhistorical

    Given an array of size n, find its majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times in the array.

  119. Single Numberhistorical

    Given a non-empty integer array, every element appears twice except for one. Find the element that appears only once.

  120. Move Zeroeshistorical

    Given an array nums, write a function to move all 0s to the end of the array while preserving the relative order of the non-zero elements.

  121. Product of Array Except Selfhistorical

    Given an integer array nums of length n, where n > 1, return an output array output where output[i] equals the product of all elements in nums except nums[i].

  122. Sort Colorshistorical

    Given an array with n elements colored red, white, and blue, sort them in place so that elements of the same color are adjacent, in the order red, white, and blue.

  123. Search a 2D Matrixhistorical

    Given a row- and column-sorted matrix and a target value, design an efficient algorithm to determine whether the value is present.

  124. Jump Floorhistorical

    A frog can jump either 1 step or 2 steps at a time. Find the total number of ways the frog can jump up a staircase with n steps (different orders count as different results).

  125. Jump Floor IIhistorical

    A frog can jump 1 step at a time, 2 steps at a time... or even n steps at a time. Find the total number of ways the frog can jump up a staircase with n steps.

  126. Fibonacci Sequencehistorical

    Given an integer n, output the nth item of the Fibonacci sequence (starting from 0, where the 0th item is 0 and the 1st item is 1).

  127. Number of 1 Bitshistorical

    Given an integer, output the number of 1s in its 32-bit binary representation. Negative numbers are represented using two's complement.

  128. Integer Power of a Numberhistorical

    Given a floating-point number base of type double and an integer exponent of type int, calculate base raised to the power of exponent.

  129. Number of Digit 1 Occurrenceshistorical

    Given an integer n, count how many times the digit 1 appears in all integers from 1 through n.

  130. Maximum Product Subarrayhistorical

    Given an integer array nums, find the contiguous subarray with the largest product (the subarray contains at least one number) and return that product.

  131. First Non-Repeating Character in a Character Streamhistorical

    Implement a function that finds the first character that appears only once in a character stream. For example, after reading only the first two characters "go", the first character that appears once is "g".

  132. Subarray Sum Equals Khistorical

    Given an integer array and an integer k, find the number of contiguous subarrays whose sum equals k.

  133. Left Rotate Stringhistorical

    Assembly language has a shift instruction called rotate left (ROL). This task uses a string to simulate its result. Given a character sequence S, output the sequence after cyclically rotating it K positions to the left.

  134. Maximal Squarehistorical

    In a 2D matrix consisting of '0' and '1', find the largest square containing only '1' and return its area.

  135. Poker Straighthistorical

    Determine whether five playing cards can form a straight, allowing jokers to represent any number.

  136. Daily Temperatureshistorical

    Given a list of daily temperatures, generate a new list where each position contains the minimum number of days you must wait to observe a warmer temperature.

  137. Replace Spaceshistorical

    Implement a function that replaces every space in a string with "%20". For example, when the string is We Are Happy., the result after replacement is We%20Are%20Happy.

  138. Daily Temperatureshistorical

    Given a list of daily temperatures, generate a new list where each position contains the minimum number of days you must wait to observe a warmer temperature.

  139. Print Linked List from Tail to Headhistorical

    Given a linked list, return an ArrayList containing its values from tail to head.

  140. Sliding Window Maximumhistorical

    Slide a window of length k across an array from left to right and return the maximum value in each window.

  141. Reverse Linked Listhistorical

    Given a linked list, reverse it and return the head of the reversed list.

  142. Merge Intervalshistorical

    Given a collection of intervals, merge all overlapping intervals and return the resulting coverage.

  143. Min Stackhistorical

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

  144. Merge Two Sorted Linked Listshistorical

    Given two monotonically increasing linked lists, merge them into one linked list that remains monotonically non-decreasing.

  145. Sort an Arrayhistorical

    Given an array, write a function that returns the array in sorted order.

  146. K-th Node from the End of a Linked Listhistorical

    Given a linked list, return its k-th node from the end.

  147. Median of Two Sorted Arrayshistorical

    Given two sorted arrays of lengths m and n, find the median of their combined values.

  148. Jump Gamehistorical

    Each element of a nonnegative integer array gives the maximum jump length from that position. Determine whether the last position is reachable.

  149. Copy Complex Linked Listhistorical

    Given a complex linked list (each node contains a node value and two pointers, one pointing to the next node and another special pointer pointing to any node), return the head of the copied complex linked list.

  150. Shortest Unsorted Continuous Subarrayhistorical

    Given an integer array nums, find a continuous subarray such that sorting only this subarray in ascending order makes the whole array sorted in ascending order.

  151. Entry Node of a Loop in a Linked Listhistorical

    Given a linked list, if it contains a cycle, find the entry node of the cycle; otherwise, return null.

  152. Best Time to Buy and Sell Stockhistorical

    Given daily stock prices, find the maximum profit from a single purchase followed by a single sale.

  153. First Common Node of Two Linked Listshistorical

    Given two linked lists, find their first common node. (Note: because the input data is provided as linked lists, invalid test data may be displayed in other ways; the input data is guaranteed to be valid.).

  154. Rotate Imagehistorical

    Given an n x n two-dimensional matrix matrix representing an image, rotate the image 90 degrees clockwise.

  155. Delete Duplicate Nodes in a Linked Listhistorical

    In a sorted linked list, duplicate nodes may exist. Delete all duplicate nodes from the list without retaining any duplicate occurrence, and return the head pointer.

  156. Implement Trie (Prefix Tree)historical

    Implement a Trie (prefix tree) with the three operations insert, search, and startsWith.

  157. Postorder Traversal Sequence of a Binary Search Treehistorical

    Given an integer array, determine whether it is the postorder traversal result of a binary search tree. Return true if it is, otherwise return false. Assume that any two numbers in the input array are distinct.

  158. Unique Binary Search Treeshistorical

    Given an integer n, determine how many binary search trees can be formed using nodes 1 ... n.

  159. Next Node in a Binary Treehistorical

    Given a binary tree and one of its nodes, find and return the next node in inorder traversal order. Note that each tree node contains not only left and right child pointers, but also a pointer to its parent.

  160. Binary Tree Inorder Traversalhistorical

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

  161. Binary Search Tree and Doubly Linked Listhistorical

    Given a binary search tree, convert it into a sorted doubly linked list. No new nodes may be created; only the pointers between existing tree nodes may be adjusted.

  162. Construct Binary Tree from Preorder and Inorder Traversalhistorical

    Construct a binary tree from its preorder traversal and inorder traversal.

  163. Kth Node in a Binary Search Treehistorical

    Given a binary search tree, find its kth smallest node. For example, in (5, 3, 7, 2, 4, 6, 8), the value of the third smallest node is 4.

  164. Binary Tree Preorder, Inorder, and Postorder Traversalhistorical

    Print all nodes of a binary tree in preorder, inorder, and postorder respectively.

  165. Depth of a Binary Treehistorical

    Given a binary tree, find its depth. A path is formed by the nodes traversed from the root to a leaf, including both the root and the leaf. The length of the longest path is the depth of the tree.

  166. Convert BST to Greater Treehistorical

    Given the root of a binary search tree whose node values are distinct, convert it to a Greater Sum Tree so that the new value of each node equals the sum of all values in the original tree that are greater than or equal to node.val.

  167. Print a Binary Tree from Top to Bottomhistorical

    Print every node of a binary tree from top to bottom, with nodes on the same level printed from left to right.

  168. Validate Binary Search Treehistorical

    Given a binary tree, determine whether it is a valid binary search tree.

  169. Symmetric Binary Treehistorical

    Implement a function to determine whether a binary tree is symmetric. A binary tree is defined as symmetric if it is identical to its mirror image.

  170. Flatten Binary Tree to Linked Listhistorical

    Flatten a binary tree in place into a linked list whose node order follows the tree's preorder traversal.

  171. Balanced Binary Treehistorical

    Given a binary tree, determine whether it is a balanced binary tree.

  172. Lowest Common Ancestor of a Binary Treehistorical

    Given a binary tree, find the lowest common ancestor of two specified nodes in the tree.

  173. Mirror of a Binary Treehistorical

    Transform a binary tree into its mirror by swapping the left and right subtrees at every node.

  174. Diameter of Binary Treehistorical

    Given a binary tree, calculate its diameter. The diameter of a binary tree is the maximum path length between any two nodes. This path may or may not pass through the root.

  175. Print a Binary Tree in Multiple Lineshistorical

    Print a binary tree level by level from top to bottom, with nodes on the same level output from left to right. Output each level on a separate line.

  176. Lowest Common Ancestor Nodehistorical

    Given a binary tree and two nodes o1 and o2 in the tree, find their lowest common ancestor.

  177. Print a Binary Tree in Zigzag Orderhistorical

    Implement a function that prints a binary tree in zigzag order: the first row from left to right, the second level from right to left, the third row from left to right, and so on.

  178. Merge Two Binary Treeshistorical

    Merge two binary trees by adding the values of overlapping nodes and retaining nodes that do not overlap.

  179. Substructure of a Treehistorical

    Given two binary trees A and B, determine whether B is a substructure of A. (ps: an empty tree is not considered a substructure of any tree.).

  180. Symmetric Treehistorical

    Given a binary tree, check whether it is mirror-symmetric.

  181. Reconstruct Binary Treehistorical

    Given the preorder traversal and inorder traversal results of a binary tree, reconstruct the binary tree. Assume that the input preorder traversal and inorder traversal results contain no duplicate numbers.

  182. House Robber IIIhistorical

    Houses form a binary tree, and a parent and its child cannot both be robbed. Choose houses that maximize the total amount stolen.

  183. Paths in a Binary Tree With a Given Sumhistorical

    Given the root node of a binary tree and an integer, print all paths in the binary tree whose node values sum to the given integer. A path is defined as the nodes traversed from the root node of the tree downward to a leaf node.

  184. Sum Root to Leaf Numbershistorical

    Each binary-tree node contains a digit from 0 to 9. Root-to-leaf paths form integers; return their total sum.

  185. Serialize a Binary Treehistorical

    Implement two functions to serialize and deserialize a binary tree respectively.

  186. Invert Binary Treehistorical

    Invert a binary tree.

  187. Convert a String to an Integerhistorical

    Convert a string to an integer without using a library function that converts strings to integers. Return 0 if the value is 0 or if the string is not a valid numeric value.

  188. Path Sum IIIhistorical

    Count downward paths in an integer-valued binary tree whose sum equals a target. Paths need not start at the root or end at a leaf.

  189. Reverse Word Orderhistorical

    Reverse the order of words in an English sentence while preserving the character order within each word.

  190. Maximum Depth of Binary Treehistorical

    Given a binary tree, find its maximum depth.

  191. Stack with a min Functionhistorical

    Define a stack data structure and implement a min function in this type that can obtain the minimum element contained in the stack, with O(1) time complexity.

  192. Binary Tree Maximum Path Sumhistorical

    A path in a binary tree may connect any nodes through parent-child edges. Find the nonempty path with the largest sum of node values.

  193. Stack Push and Pop Sequenceshistorical

    Given two integer sequences, the first sequence represents the push order of a stack. Determine whether the second sequence could be a pop order of that stack.

  194. Binary Tree Right Side Viewhistorical

    Given a binary tree, imagine standing on its right side. Return the values of the nodes visible from the right, ordered from top to bottom.

  195. Implement a Queue with Two Stackshistorical

    Use two stacks to implement a queue and complete the queue's Push and Pop operations. The elements in the queue are of type int.

  196. Binary Tree Level Order Traversalhistorical

    Given a binary tree, return the node values obtained by level-order traversal (that is, visit all nodes level by level from left to right).

  197. Search in a 2D Arrayhistorical

    Each row and column of a two-dimensional array is sorted in ascending order. Determine whether a given integer appears in the array.

  198. Serialize and Deserialize Binary Treehistorical

    Serialization converts a data structure or object into a continuous representation so the result can be stored in a file or memory, transmitted over a network, and later reconstructed by the reverse operation.

  199. Two Numbers with Sum Shistorical

    Given an array sorted in increasing order and a number S, find two numbers in the array whose sum is exactly S. If there are multiple pairs whose sum equals S, output the pair with the smallest product.

  200. Binary Tree Zigzag Level Order Traversalhistorical

    Given the root root of a binary tree, return the zigzag level-order traversal of its node values (left to right on one level, then right to left on the next, alternating between levels).

  201. Continuous Positive Sequences with Sum Shistorical

    Given a positive integer S, find all sequences of at least two consecutive positive integers whose sum is S.

  202. Swap Nodes in Pairshistorical

    Given a linked list, swap every two adjacent nodes and return the head of the modified list. You must solve the problem without modifying node values (only node links may be changed).

  203. Last Remaining Number in a Circlehistorical

    Arrange n numbers in a circle and repeatedly remove every m-th number. Find the last remaining number.

  204. Reverse Linked List IIhistorical

    Given a singly linked list and positions left and right, reverse the nodes in that range and return the updated list.

  205. Arrange an Array into the Smallest Numberhistorical

    Given an array of positive integers, concatenate all numbers to form one number and print the smallest possible result. For example, for {3,32,321}, the smallest number that can be formed is 321323.

  206. Reverse Linked Listhistorical

    Reverse a singly linked list.

  207. Count Occurrences in a Sorted Arrayhistorical

    Count how many times a number appears in a sorted array.

  208. Reverse Nodes in k-Grouphistorical

    Reverse the nodes of the given linked list in groups of k and return the resulting list. If the number of nodes is not a multiple of k, leave the remaining nodes at the end unchanged.

  209. Number Appearing More Than Half the Timehistorical

    An array contains a number that appears more than half the length of the array. Find this number. For example, in the length-9 array {1,2,3,2,2,2,5,4,2}, the number 2 appears five times, which is more than half the array length, so output 2.

  210. Add Two Numbershistorical

    You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each node stores a single digit.

  211. Numbers Appearing Only Oncehistorical

    In an integer array, every number appears twice except for two numbers. Write a program to find the two numbers that appear only once.

  212. Remove Duplicates from Sorted List IIhistorical

    Given the head head of a sorted linked list, delete all nodes whose values are duplicated, leaving only values that appear once. Return the sorted linked list.

  213. Inverse Pairs in an Arrayhistorical

    An inversion occurs when an earlier array element is greater than a later one. Count all inversions in the given array.

  214. Remove Duplicates from Sorted Listhistorical

    Given the head head of a sorted linked list, delete duplicate elements so that each value appears only once. Return the sorted linked list.

  215. Duplicate Number in an Arrayhistorical

    An array of length n contains values from 0 to n - 1, with some values repeated. Find a duplicate value.

  216. Remove Nth Node From End of Listhistorical

    Given a linked list, remove the nth node from the end and return the head of the list. For example, given the linked list: 1->2->3->4->5, n = 2. after removing the nth node from the end, the list becomes 1->2->3->5.

  217. Minimum Number in a Rotated Arrayhistorical

    Moving some elements from the beginning of an array to the end is called a rotation of the array. Given a rotation of a non-decreasingly sorted array, output the minimum element of the rotated array.

  218. Palindrome Linked Listhistorical

    Determine whether a linked list is a palindrome.

  219. Smallest K Numbershistorical

    Given n integers, find the smallest K numbers. For example, among 4,5,1,6,2,7,3,8, the smallest four numbers are 1,2,3,4.

  220. Palindrome Linked Listhistorical

    Determine whether a linked list is a palindrome.

  221. Robot Movement Rangehistorical

    There is a grid with m rows and n columns. A robot starts at coordinate (0,0) and can move one cell at a time left, right, up, or down, but it cannot enter a cell when the sum of the digits of its row and column coordinates is greater than k.

  222. Linked List Cyclehistorical

    Given a linked list, determine whether it contains a cycle.

  223. Maximum in Sliding Windowshistorical

    Given an array and a sliding-window size, find the maximum value in every sliding window. For example, for the array {2,3,4,2,6,2,5,1} with window size 3, there are six windows and their maximum values are {4,4,6,6,6,5}.

  224. Linked List Cycle IIhistorical

    Given a linked list, return the first node where the cycle begins. If the list has no cycle, return null.

  225. Reorder Array with Odd Numbers Before Even Numbershistorical

    Given an integer array, implement a function that reorders its numbers so that all odd numbers are in the first half and all even numbers are in the second half, while preserving the relative order among odd numbers and among even numbers.

  226. Rotate Listhistorical

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

  227. Maximum Sum of a Contiguous Subarrayhistorical

    Given an integer array that may contain negative values, find the maximum sum of a contiguous subarray.

  228. Linked List Cyclehistorical

    Given a linked list, determine whether it contains a cycle.

  229. Linked List Cycle IIhistorical

    Given a linked list, return the first node where the cycle begins. If the list has no cycle, return null.

  230. Intersection of Two Linked Listshistorical

    Write a program that finds the first node at which two singly linked lists intersect.

  231. Reorder Listhistorical

    Reorder a singly linked list by alternating nodes from the beginning and end, changing links without modifying node values.

  232. Partition Listhistorical

    Given the head head of a linked list and a value x, partition the list so that all nodes with values less than x come before nodes with values greater than or equal to x.

  233. Merge k Sorted Listshistorical

    Merge k sorted linked lists into one sorted linked list. Analyze and describe the complexity.

  234. Merge Two Sorted Listshistorical

    Merge two sorted linked lists into one new sorted linked list and return it. The new list is formed by splicing together all nodes from the two given lists.

  235. Odd Even Linked Listhistorical

    Given the head head of a singly linked list, group all nodes at odd positions together followed by all nodes at even positions, and return the reordered list.

  236. Sort Listhistorical

    Given the head head of a linked list, sort the list in ascending order and return the sorted list.

  237. Intersection of Two Linked Listshistorical

    Write a program that finds the first node at which two singly linked lists intersect.