leetcode
Data Structures & Algorithms · 143 notes
- 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.
- Longest Common Subsequencehistorical
Given two strings text1 and text2, return the length of their longest common subsequence.
- Longest Substring Without Repeating Charactershistorical
Given an array, return the length of its longest contiguous subarray without repeated elements.
- Edit Distancehistorical
Given two words word1 and word2, calculate the minimum number of operations required to convert word1 into word2.
- 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.
- Subsetshistorical
Given an integer array nums whose elements are all distinct, return all possible subsets (the power set).
- 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.
- Number of Islandshistorical
Given a 2D grid consisting of '1' (land) and '0' (water), calculate the number of islands in the grid.
- Maximal Squarehistorical
In a 2D matrix consisting of '0' and '1', find the largest square containing only '1' and return its area.
- Course Schedulehistorical
Given numCourses courses and their prerequisite relationships, determine whether all courses can be completed.
- 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.
- 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.
- 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.
- Word Searchhistorical
Given a two-dimensional grid and a word, determine whether the word exists in the grid.
- 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.
- 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.
- 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.
- 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.
- 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.
- Longest Common Subsequencehistorical
Given two strings text1 and text2, return the length of their longest common subsequence.
- 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.
- 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.
- 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.
- Edit Distancehistorical
Given two words word1 and word2, calculate the minimum number of operations required to convert word1 into word2.
- 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.
- Group Anagramshistorical
Given an array of strings, group the anagrams together. Anagrams contain the same letters but in a different order.
- 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.
- 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.
- Longest Increasing Subsequencehistorical
Given an integer array nums, find the length of the longest strictly increasing subsequence.
- Longest Common Prefixhistorical
Write a function to find the longest common prefix among an array of strings.
- Jump Gamehistorical
Each element of a nonnegative integer array gives the maximum jump length from that position. Determine whether the last position is reachable.
- 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.
- Check Palindromehistorical
Given a string, write a function to determine whether it is a palindrome. Return true if it is, otherwise return false.
- 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.
- Reverse Stringhistorical
Write a program that accepts a string and outputs the reversed string. (The string length does not exceed 1000.).
- First Missing Positivehistorical
Given an unsorted integer array nums, find the smallest positive integer that does not appear in the array.
- Palindromic Substringshistorical
Given a string, calculate how many palindromic substrings it contains.
- 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.
- Find the Duplicate Numberhistorical
Given n + 1 integers whose values range from 1 to n, find the repeated number.
- Longest Palindromic Substringhistorical
Given a string s, find the longest palindromic substring in s.
- 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.
- 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.
- 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'.).
- Subarray Sum Equals Khistorical
Given an integer array and an integer k, find the number of contiguous subarrays whose sum equals k.
- 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.
- Longest Valid Parentheseshistorical
Given a string containing only '(' and ')', find the length of the longest valid (well-formed and consecutive) parentheses substring.
- Remove Invalid Parentheseshistorical
Given a string s containing parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.
- Generate Parentheseshistorical
The number n represents the number of pairs of parentheses. Design a function that can generate all possible valid combinations of parentheses.
- 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.
- Regular Expression Matchinghistorical
Given a string s and a pattern p, implement regular expression matching with support for '.' and '*'.
- 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.
- Longest Substring Without Repeating Charactershistorical
Given an array, return the length of its longest contiguous subarray without repeated elements.
- 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.
- 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].
- 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.
- Hamming Distancehistorical
The Hamming distance between two integers is the number of positions at which their corresponding binary bits are different.
- 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.
- Reverse Integerhistorical
Given a 32-bit signed integer x, return the result of reversing the digits of x.
- 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.
- Climbing Stairshistorical
A staircase has n steps, and each move climbs one or two steps. Count the distinct ways to reach the top.
- 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.
- 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.
- 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.
- Find Peak Elementhistorical
A peak element is strictly greater than its neighbors. Find a peak in the given array and return its index.
- Find the K-th Largesthistorical
Given an integer array, use the idea of quicksort to find the K-th largest number in the array.
- 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.
- Find Minimum in Rotated Sorted Arrayhistorical
Given a rotated ascending array, find its minimum element.
- Square Roothistorical
Implement the function int sqrt(int x). Compute and return the square root of x, rounded down.
- Spiral Matrixhistorical
Given an m-row, n-column matrix, return all elements of the matrix in clockwise spiral order.
- 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.
- 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.
- 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.
- 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.
- 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.
- Top K Frequent Elementshistorical
Given a non-empty integer array, return the k most frequent elements.
- 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.
- Single Numberhistorical
Given a non-empty integer array, every element appears twice except for one. Find the element that appears only once.
- 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.
- 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].
- 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.
- 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.
- 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.
- Subarray Sum Equals Khistorical
Given an integer array and an integer k, find the number of contiguous subarrays whose sum equals k.
- Maximal Squarehistorical
In a 2D matrix consisting of '0' and '1', find the largest square containing only '1' and return its area.
- 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.
- 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.
- Sliding Window Maximumhistorical
Slide a window of length k across an array from left to right and return the maximum value in each window.
- Merge Intervalshistorical
Given a collection of intervals, merge all overlapping intervals and return the resulting coverage.
- Min Stackhistorical
Design a stack that supports push, pop, and top, and can retrieve the minimum element in constant time.
- Median of Two Sorted Arrayshistorical
Given two sorted arrays of lengths m and n, find the median of their combined values.
- Jump Gamehistorical
Each element of a nonnegative integer array gives the maximum jump length from that position. Determine whether the last position is reachable.
- 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.
- Best Time to Buy and Sell Stockhistorical
Given daily stock prices, find the maximum profit from a single purchase followed by a single sale.
- Rotate Imagehistorical
Given an n x n two-dimensional matrix matrix representing an image, rotate the image 90 degrees clockwise.
- Implement Trie (Prefix Tree)historical
Implement a Trie (prefix tree) with the three operations insert, search, and startsWith.
- Unique Binary Search Treeshistorical
Given an integer n, determine how many binary search trees can be formed using nodes 1 ... n.
- Binary Tree Inorder Traversalhistorical
Given the root root of a binary tree, return its inorder traversal.
- Construct Binary Tree from Preorder and Inorder Traversalhistorical
Construct a binary tree from its preorder traversal and inorder traversal.
- Binary Tree Preorder, Inorder, and Postorder Traversalhistorical
Print all nodes of a binary tree in preorder, inorder, and postorder respectively.
- 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.
- Validate Binary Search Treehistorical
Given a binary tree, determine whether it is a valid binary search tree.
- 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.
- Lowest Common Ancestor of a Binary Treehistorical
Given a binary tree, find the lowest common ancestor of two specified nodes in the tree.
- 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.
- Lowest Common Ancestor Nodehistorical
Given a binary tree and two nodes o1 and o2 in the tree, find their lowest common ancestor.
- Merge Two Binary Treeshistorical
Merge two binary trees by adding the values of overlapping nodes and retaining nodes that do not overlap.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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).
- 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.
- 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).
- 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).
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- Linked List Cycle IIhistorical
Given a linked list, return the first node where the cycle begins. If the list has no cycle, return null.
- Rotate Listhistorical
Given the head head of a linked list, rotate the list to the right by k positions.
- Linked List Cycle IIhistorical
Given a linked list, return the first node where the cycle begins. If the list has no cycle, return null.
- Intersection of Two Linked Listshistorical
Write a program that finds the first node at which two singly linked lists intersect.
- Reorder Listhistorical
Reorder a singly linked list by alternating nodes from the beginning and end, changing links without modifying node values.
- 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.
- Merge k Sorted Listshistorical
Merge k sorted linked lists into one sorted linked list. Analyze and describe the complexity.
- 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.
- 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.
- Sort Listhistorical
Given the head head of a linked list, sort the list in ascending order and return the sorted list.
- Intersection of Two Linked Listshistorical
Write a program that finds the first node at which two singly linked lists intersect.