LeetCode Site Generator

LeetCode Site Generator

  • Problems
  • GitHub

›Problems

Problems

  • Two Sum
  • Add Two Numbers
  • Longest Substring Without Repeating Characters
  • Median of Two Sorted Arrays
  • Longest Palindromic Substring
  • ZigZag Conversion
  • Reverse Integer
  • Palindrome Number
  • Container With Most Water
  • Longest Common Prefix
  • 3Sum
  • 3Sum Closest
  • Letter Combinations of a Phone Number
  • 4Sum
  • Remove Nth Node From End of List
  • Valid Parentheses
  • Merge Two Sorted Lists
  • Generate Parentheses
  • Merge k Sorted Lists
  • Swap Nodes in Pairs
  • Reverse Nodes in k-Group
  • Remove Duplicates from Sorted Array
  • Remove Element
  • Implement strStr()
  • Next Permutation
  • Longest Valid Parentheses
  • Search in Rotated Sorted Array
  • Find First and Last Position of Element in Sorted Array
  • Search Insert Position
  • Valid Sudoku
  • Combination Sum
  • Combination Sum II
  • First Missing Positive
  • Multiply Strings
  • Jump Game II
  • Permutations
  • Permutations II
  • Rotate Image
  • Group Anagrams
  • Pow(x, n)
  • Maximum Subarray
  • Spiral Matrix
  • Jump Game
  • Merge Intervals
  • Insert Interval
  • Permutation Sequence
  • Rotate List
  • Unique Paths
  • Unique Paths II
  • Minimum Path Sum
  • Plus One
  • Add Binary
  • Sqrt(x)
  • Climbing Stairs
  • Simplify Path
  • Edit Distance
  • Set Matrix Zeroes
  • Search a 2D Matrix
  • Sort Colors
  • Minimum Window Substring
  • Combinations
  • Subsets
  • Word Search
  • Remove Duplicates from Sorted Array II
  • Search in Rotated Sorted Array II
  • Remove Duplicates from Sorted List II
  • Remove Duplicates from Sorted List
  • Partition List
  • Merge Sorted Array
  • Subsets II
  • Reverse Linked List II
  • Binary Tree Inorder Traversal
  • Unique Binary Search Trees II
  • Unique Binary Search Trees
  • Validate Binary Search Tree
  • Recover Binary Search Tree
  • Same Tree
  • Symmetric Tree
  • Binary Tree Level Order Traversal
  • Binary Tree Zigzag Level Order Traversal
  • Maximum Depth of Binary Tree
  • Construct Binary Tree from Preorder and Inorder Traversal
  • Construct Binary Tree from Inorder and Postorder Traversal
  • Binary Tree Level Order Traversal II
  • Convert Sorted Array to Binary Search Tree
  • Convert Sorted List to Binary Search Tree
  • Balanced Binary Tree
  • Minimum Depth of Binary Tree
  • Path Sum
  • Path Sum II
  • Flatten Binary Tree to Linked List
  • Populating Next Right Pointers in Each Node
  • Populating Next Right Pointers in Each Node II
  • Pascal's Triangle
  • Pascal's Triangle II
  • Triangle
  • Best Time to Buy and Sell Stock
  • Best Time to Buy and Sell Stock II
  • Best Time to Buy and Sell Stock III
  • Binary Tree Maximum Path Sum
  • Valid Palindrome
  • Word Ladder
  • Longest Consecutive Sequence
  • Sum Root to Leaf Numbers
  • Surrounded Regions
  • Palindrome Partitioning
  • Clone Graph
  • Single Number
  • Copy List with Random Pointer
  • Word Break
  • Linked List Cycle
  • Linked List Cycle II
  • Binary Tree Preorder Traversal
  • Binary Tree Postorder Traversal
  • LRU Cache
  • Insertion Sort List
  • Evaluate Reverse Polish Notation
  • Reverse Words in a String
  • Maximum Product Subarray
  • Find Minimum in Rotated Sorted Array
  • Find Minimum in Rotated Sorted Array II
  • Min Stack
  • Longest Substring with At Most Two Distinct Characters
  • Intersection of Two Linked Lists
  • One Edit Distance
  • Find Peak Element
  • Missing Ranges
  • Maximum Gap
  • Compare Version Numbers
  • Two Sum II - Input array is sorted
  • Excel Sheet Column Title
  • Majority Element
  • Two Sum III - Data structure design
  • Excel Sheet Column Number
  • Factorial Trailing Zeroes
  • Binary Search Tree Iterator
  • Largest Number
  • Reverse Words in a String II
  • Best Time to Buy and Sell Stock IV
  • Rotate Array
  • Number of 1 Bits
  • House Robber
  • Binary Tree Right Side View
  • Number of Islands
  • Happy Number
  • Remove Linked List Elements
  • Count Primes
  • Isomorphic Strings
  • Reverse Linked List
  • Course Schedule
  • Implement Trie (Prefix Tree)
  • Minimum Size Subarray Sum
  • Course Schedule II
  • Design Add and Search Words Data Structure
  • House Robber II
  • Kth Largest Element in an Array
  • Combination Sum III
  • Contains Duplicate
  • Contains Duplicate II
  • Contains Duplicate III
  • Maximal Square
  • Count Complete Tree Nodes
  • Rectangle Area
  • Basic Calculator
  • Implement Stack using Queues
  • Invert Binary Tree
  • Basic Calculator II
  • Summary Ranges
  • Majority Element II
  • Kth Smallest Element in a BST
  • Power of Two
  • Implement Queue using Stacks
  • Number of Digit One
  • Palindrome Linked List
  • Lowest Common Ancestor of a Binary Search Tree
  • Lowest Common Ancestor of a Binary Tree
  • Delete Node in a Linked List
  • Product of Array Except Self
  • Sliding Window Maximum
  • Search a 2D Matrix II
  • Different Ways to Add Parentheses
  • Valid Anagram
  • Shortest Word Distance
  • Shortest Word Distance II
  • Shortest Word Distance III
  • Strobogrammatic Number
  • Strobogrammatic Number II
  • Strobogrammatic Number III
  • Group Shifted Strings
  • Count Univalue Subtrees
  • Flatten 2D Vector
  • Meeting Rooms
  • Meeting Rooms II
  • Factor Combinations
  • Verify Preorder Sequence in Binary Search Tree
  • Paint House
  • Binary Tree Paths
  • Add Digits
  • Graph Valid Tree
  • Ugly Number
  • Ugly Number II
  • Paint House II
  • Palindrome Permutation
  • Palindrome Permutation II
  • Missing Number
  • Closest Binary Search Tree Value
  • Closest Binary Search Tree Value II
  • Find the Celebrity
  • First Bad Version
  • Perfect Squares
  • Wiggle Sort
  • Zigzag Iterator
  • Move Zeroes
  • Peeking Iterator
  • Inorder Successor in BST
  • Walls and Gates
  • Find the Duplicate Number
  • Word Pattern
  • Flip Game
  • Flip Game II
  • Find Median from Data Stream
  • Serialize and Deserialize Binary Tree
  • Binary Tree Longest Consecutive Sequence
  • Bulls and Cows
  • Longest Increasing Subsequence
  • Range Sum Query - Immutable
  • Range Sum Query 2D - Immutable
  • Additive Number
  • Range Sum Query - Mutable
  • Best Time to Buy and Sell Stock with Cooldown
  • Minimum Height Trees
  • Super Ugly Number
  • Binary Tree Vertical Order Traversal
  • Count of Smaller Numbers After Self
  • Remove Duplicate Letters
  • Generalized Abbreviation
  • Coin Change
  • Number of Connected Components in an Undirected Graph
  • Maximum Size Subarray Sum Equals k
  • Power of Three
  • Odd Even Linked List
  • Longest Increasing Path in a Matrix
  • Verify Preorder Serialization of a Binary Tree
  • Reconstruct Itinerary
  • Largest BST Subtree
  • Increasing Triplet Subsequence
  • House Robber III
  • Counting Bits
  • Nested List Weight Sum
  • Longest Substring with At Most K Distinct Characters
  • Flatten Nested List Iterator
  • Power of Four
  • Integer Break
  • Reverse String
  • Moving Average from Data Stream
  • Top K Frequent Elements
  • Design Tic-Tac-Toe
  • Intersection of Two Arrays
  • Intersection of Two Arrays II
  • Design Snake Game
  • Logger Rate Limiter
  • Sort Transformed Array
  • Bomb Enemy
  • Design Hit Counter
  • Nested List Weight Sum II
  • Water and Jug Problem
  • Find Leaves of Binary Tree
  • Valid Perfect Square
  • Sum of Two Integers
  • Find K Pairs with Smallest Sums
  • Kth Smallest Element in a Sorted Matrix
  • Insert Delete GetRandom O(1)
  • Linked List Random Node
  • Ransom Note
  • First Unique Character in a String
  • Find the Difference
  • Is Subsequence
  • Decode String
  • Longest Substring with At Least K Repeating Characters
  • Integer Replacement
  • Evaluate Division
  • Remove K Digits
  • Frog Jump
  • Sum of Left Leaves
  • Queue Reconstruction by Height
  • Longest Palindrome
  • Split Array Largest Sum
  • Add Strings
  • Partition Equal Subset Sum
  • Longest Repeating Character Replacement
  • Non-overlapping Intervals
  • Find Right Interval
  • Path Sum III
  • Find All Anagrams in a String
  • Arranging Coins
  • Find All Duplicates in an Array
  • String Compression
  • Add Two Numbers II
  • Find All Numbers Disappeared in an Array
  • Serialize and Deserialize BST
  • Delete Node in a BST
  • Sort Characters By Frequency
  • Minimum Number of Arrows to Burst Balloons
  • Minimum Moves to Equal Array Elements
  • 4Sum II
  • 132 Pattern
  • Repeated Substring Pattern
  • Hamming Distance
  • Minimum Moves to Equal Array Elements II
  • Island Perimeter
  • Can I Win
  • Count The Repetitions
  • Matchsticks to Square
  • Sliding Window Median
  • Max Consecutive Ones
  • Predict the Winner
  • Increasing Subsequences
  • Target Sum
  • Next Greater Element I
  • Diagonal Traverse
  • Keyboard Row
  • Find Mode in Binary Search Tree
  • Next Greater Element II
  • Most Frequent Subtree Sum
  • Inorder Successor in BST II
  • Find Bottom Left Tree Value
  • Find Largest Value in Each Tree Row
  • Longest Palindromic Subsequence
  • Coin Change 2
  • Longest Word in Dictionary through Deleting
  • Contiguous Array
  • Beautiful Arrangement
  • Minimum Absolute Difference in BST
  • Convert BST to Greater Tree
  • Minimum Time Difference
  • Single Element in a Sorted Array
  • 01 Matrix
  • Diameter of Binary Tree
  • Friend Circles
  • Binary Tree Longest Consecutive Sequence II
  • Reverse Words in a String III
  • Subarray Sum Equals K
  • Array Partition I
  • Longest Line of Consecutive One in Matrix
  • Array Nesting
  • Reshape the Matrix
  • Permutation in String
  • Subtree of Another Tree
  • Shortest Unsorted Continuous Subarray
  • Delete Operation for Two Strings
  • Longest Harmonious Subsequence
  • Minimum Index Sum of Two Lists
  • Design Compressed String Iterator
  • Valid Triangle Number
  • Merge Two Binary Trees
  • Add One Row to Tree
  • Maximum Product of Three Numbers
  • Sum of Square Numbers
  • Average of Levels in Binary Tree
  • Design Search Autocomplete System
  • Maximum Average Subarray I
  • Maximum Length of Pair Chain
  • Palindromic Substrings
  • Replace Words
  • 2 Keys Keyboard
  • Find Duplicate Subtrees
  • Two Sum IV - Input is a BST
  • Maximum Binary Tree
  • Print Binary Tree
  • Find K Closest Elements
  • Split Array into Consecutive Subsequences
  • Maximum Width of Binary Tree
  • Non-decreasing Array
  • Trim a Binary Search Tree
  • Maximum Swap
  • Second Minimum Node In a Binary Tree
  • Number of Longest Increasing Subsequence
  • Longest Continuous Increasing Subsequence
  • Map Sum Pairs
  • Valid Parenthesis String
  • 24 Game
  • Valid Palindrome II
  • Next Closest Time
  • Redundant Connection
  • Repeated String Match
  • Longest Univalue Path
  • Top K Frequent Words
  • Binary Number with Alternating Bits
  • Number of Distinct Islands
  • Max Area of Island
  • Count Binary Substrings
  • Degree of an Array
  • Minimum ASCII Delete Sum for Two Strings
  • Subarray Product Less Than K
  • Best Time to Buy and Sell Stock with Transaction Fee
  • Maximum Length of Repeated Subarray
  • Accounts Merge
  • Find Pivot Index
  • My Calendar I
  • Flood Fill
  • Sentence Similarity
  • Asteroid Collision
  • Sentence Similarity II
  • Monotone Increasing Digits
  • Daily Temperatures
  • To Lower Case
  • Closest Leaf in a Binary Tree
  • Network Delay Time
  • Find Smallest Letter Greater Than Target
  • Min Cost Climbing Stairs
  • Open the Lock
  • N-ary Tree Level Order Traversal
  • Flatten a Multilevel Doubly Linked List
  • Partition Labels
  • Couples Holding Hands
  • Maximum Depth of N-ary Tree
  • N-ary Tree Preorder Traversal
  • N-ary Tree Postorder Traversal
  • Toeplitz Matrix
  • Reorganize String
  • Jewels and Stones
  • Search in a Binary Search Tree
  • Insert into a Binary Search Tree
  • Kth Largest Element in a Stream
  • Binary Search
  • Minimum Distance Between BST Nodes
  • Letter Case Permutation
  • Number of Matching Subsequences
  • Rotate String
  • Minimum Swaps To Make Sequences Increasing
  • Max Increase to Keep City Skyline
  • Largest Sum of Averages
  • Binary Tree Pruning
  • Shortest Distance to a Character
  • Design Circular Deque
  • Design Circular Queue
  • Flipping an Image
  • Rectangle Overlap
  • Keys and Rooms
  • Split Array into Fibonacci Sequence
  • Backspace String Compare
  • Longest Mountain in Array
  • Hand of Straights
  • Peak Index in a Mountain Array
  • Exam Room
  • Score of Parentheses
  • Minimum Cost to Hire K Workers
  • Lemonade Change
  • All Nodes Distance K in Binary Tree
  • Smallest Subtree with all the Deepest Nodes
  • Binary Gap
  • Advantage Shuffle
  • Leaf-Similar Trees
  • Length of Longest Fibonacci Subsequence
  • Middle of the Linked List
  • Stone Game
  • Fair Candy Swap
  • Construct Binary Tree from Preorder and Postorder Traversal
  • All Possible Full Binary Trees
  • Monotonic Array
  • Increasing Order Search Tree
  • Online Stock Span
  • Sort Array By Parity
  • Sum of Subarray Minimums
  • Sort an Array
  • Reverse Only Letters
  • Maximum Sum Circular Subarray
  • Complete Binary Tree Inserter
  • Minimum Add to Make Parentheses Valid
  • Sort Array By Parity II
  • Flip String to Monotone Increasing
  • Unique Email Addresses
  • Binary Subarrays With Sum
  • Minimum Falling Path Sum
  • Shortest Bridge
  • Range Sum of BST
  • Minimum Area Rectangle
  • Valid Mountain Array
  • Minimum Increment to Make Array Unique
  • Validate Stack Sequences
  • Most Stones Removed with Same Row or Column
  • Flip Equivalent Binary Trees
  • Largest Component Size by Common Factor
  • Verifying an Alien Dictionary
  • Array of Doubled Pairs
  • Check Completeness of a Binary Tree
  • Maximum Width Ramp
  • Univalued Binary Tree
  • Flip Binary Tree To Match Preorder Traversal
  • Fibonacci Number
  • K Closest Points to Origin
  • Subarray Sums Divisible by K
  • Largest Perimeter Triangle
  • Squares of a Sorted Array
  • Distribute Coins in Binary Tree
  • Time Based Key-Value Store
  • Interval List Intersections
  • Vertical Order Traversal of a Binary Tree
  • Smallest String Starting From Leaf
  • Satisfiability of Equality Equations
  • Broken Calculator
  • Subarrays with K Different Integers
  • Cousins in Binary Tree
  • Rotting Oranges
  • Find the Town Judge
  • Find Common Characters
  • Max Consecutive Ones III
  • Minimum Domino Rotations For Equal Row
  • Construct Binary Search Tree from Preorder Traversal
  • Capacity To Ship Packages Within D Days
  • Missing Element in Sorted Array
  • Partition Array Into Three Parts With Equal Sum
  • Best Sightseeing Pair
  • Next Greater Node In Linked List
  • Brace Expansion
  • Sum of Root To Leaf Binary Numbers
  • Two Sum Less Than K
  • Maximum Difference Between Node and Ancestor
  • Two City Scheduling
  • Path With Maximum Minimum Value
  • Uncrossed Lines
  • Binary Search Tree to Greater Sum Tree
  • As Far from Land as Possible
  • Minimum Cost to Connect Sticks
  • Last Stone Weight
  • Remove All Adjacent Duplicates In String
  • Longest String Chain
  • Grumpy Bookstore Owner
  • Distant Barcodes
  • Minimum Knight Moves
  • Two Sum BSTs
  • Path In Zigzag Labelled Binary Tree
  • Distribute Candies to People
  • Delete Tree Nodes
  • Delete Nodes And Return Forest
  • Maximum Nesting Depth of Two Valid Parentheses Strings
  • Sequential Digits
  • Relative Sort Array
  • Element Appearing More Than 25% In Sorted Array
  • Remove Covered Intervals
  • Minimum Falling Path Sum II
  • Minimum Cost Tree From Leaf Values
  • Stone Game II
  • Decompress Run-Length Encoded List
  • Sum of Nodes with Even-Valued Grandparent
  • Snapshot Array
  • Longest Common Subsequence
  • Break a Palindrome
  • Sort the Matrix Diagonally
  • Rank Transform of an Array
  • Number of Days Between Two Dates
  • Validate Binary Tree Nodes
  • Closest Divisors
  • Reformat Date
  • Four Divisors
  • Balance a Binary Search Tree
  • Constrained Subsequence Sum
  • Maximum Subarray Sum with One Deletion
  • Reverse Substrings Between Each Pair of Parentheses
  • Longest Happy String
  • Minimum Absolute Difference
  • Smallest String With Swaps
  • Unique Number of Occurrences
  • Remove All Adjacent Duplicates in String II
  • Path with Maximum Probability
  • Split a String in Balanced Strings
  • Perform String Shifts
  • Check If It Is a Straight Line
  • Remove Sub-Folders from the Filesystem
  • Maximum Profit in Job Scheduling
  • Maximum Length of a Concatenated String with Unique Characters
  • First Unique Number
  • Count Number of Nice Subarrays
  • Minimum Remove to Make Valid Parentheses
  • Leftmost Column with at Least a One
  • Find Elements in a Contaminated Binary Tree
  • Greatest Sum Divisible by Three
  • Counting Elements
  • Search Suggestions System
  • Count Square Submatrices with All Ones
  • Subtract the Product and Sum of Digits of an Integer
  • Group the People Given the Group Size They Belong To
  • Find the Smallest Divisor Given a Threshold
  • Convert Binary Number in a Linked List to Integer
  • Maximum Side Length of a Square with Sum Less than or Equal to Threshold
  • Shortest Path in a Grid with Obstacles Elimination
  • Find Numbers with Even Number of Digits
  • Divide Array in Sets of K Consecutive Numbers
  • Find N Unique Integers Sum up to Zero
  • All Elements in Two Binary Search Trees
  • Jump Game III
  • Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree
  • Convert Integer to the Sum of Two No-Zero Integers
  • Number of Operations to Make Network Connected
  • Number of Steps to Reduce a Number to Zero
  • Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold
  • Angle Between Hands of a Clock
  • Jump Game IV
  • Maximum 69 Number
  • Print Words Vertically
  • Delete Leaves With a Given Value
  • Remove Palindromic Subsequences
  • Filter Restaurants by Vegan-Friendly, Price and Distance
  • Sort Integers by The Number of 1 Bits
  • Apply Discount Every n Orders
  • Number of Substrings Containing All Three Characters
  • Count All Valid Pickup and Delivery Options
  • The K Weakest Rows in a Matrix
  • Reduce Array Size to The Half
  • Maximum Product of Splitted Binary Tree
  • Check If N and Its Double Exist
  • Minimum Number of Steps to Make Two Strings Anagram
  • Increasing Decreasing String
  • Longest ZigZag Path in a Binary Tree
  • Maximum Sum BST in Binary Tree
  • Count Negative Numbers in a Sorted Matrix
  • Product of the Last K Numbers
  • Maximum Number of Events That Can Be Attended
  • How Many Numbers Are Smaller Than the Current Number
  • Rank Teams by Votes
  • Linked List in Binary Tree
  • Find the Distance Value Between Two Arrays
  • Cinema Seat Allocation
  • Sort Integers by The Power Value
  • Generate a String With Characters That Have Odd Counts
  • Bulb Switcher III
  • Time Needed to Inform All Employees
  • Frog Position After T Seconds
  • Lucky Numbers in a Matrix
  • Design a Stack With Increment Operation
  • Maximum Performance of a Team
  • Count Largest Group
  • Circle and Rectangle Overlapping
  • Construct K Palindrome Strings
  • Reducing Dishes
  • Create Target Array in the Given Order
  • Check if There is a Valid Path in a Grid
  • Find Lucky Integer in an Array
  • Count Number of Teams
  • Design Underground System
  • Minimum Value to Get Positive Step by Step Sum
  • Find the Minimum Number of Fibonacci Numbers Whose Sum Is K
  • The k-th Lexicographical String of All Happy Strings of Length n
  • Restore The Array
  • Minimum Subsequence in Non-Increasing Order
  • Number of Steps to Reduce a Number in Binary Representation to One
  • Stone Game III
  • String Matching in an Array
  • Queries on a Permutation With Key
  • HTML Entity Parser
  • Kids With the Greatest Number of Candies
  • Max Difference You Can Get From Changing an Integer
  • Check If a String Can Break Another String
  • Reformat The String
  • Display Table of Food Orders in a Restaurant
  • Minimum Number of Frogs Croaking
  • Build Array Where You Can Find The Maximum Exactly K Comparisons
  • Maximum Score After Splitting a String
  • Maximum Points You Can Obtain from Cards
  • Diagonal Traverse II
  • Consecutive Characters
  • Simplified Fractions
  • Count Good Nodes in Binary Tree
  • Form Largest Integer With Digits That Add up to Target
  • Destination City
  • Check If All 1's Are at Least Length K Places Away
  • Find the Kth Smallest Sum of a Matrix With Sorted Rows
  • Build an Array With Stack Operations
  • Count Triplets That Can Form Two Arrays of Equal XOR
  • Minimum Time to Collect All Apples in a Tree
  • Make Two Arrays Equal by Reversing Sub-arrays
  • Check If a String Contains All Binary Codes of Size K
  • Course Schedule IV
  • Cherry Pickup II
  • Number of Students Doing Homework at a Given Time
  • Rearrange Words in a Sentence
  • People Whose List of Favorite Companies Is Not a Subset of Another List
  • Check If a Word Occurs As a Prefix of Any Word in a Sentence
  • Maximum Number of Vowels in a Substring of Given Length
  • Pseudo-Palindromic Paths in a Binary Tree
  • Max Dot Product of Two Subsequences
  • Maximum Product of Two Elements in an Array
  • Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
  • Reorder Routes to Make All Paths Lead to the City Zero
  • Shuffle the Array
  • Average Salary Excluding the Minimum and Maximum Salary
  • The kth Factor of n
  • Longest Subarray of 1's After Deleting One Element
  • Parallel Courses II
  • Running Sum of 1d Array
  • Least Number of Unique Integers after K Removals
  • Minimum Number of Days to Make m Bouquets
  • XOR Operation in an Array
  • Making File Names Unique
  • Range Sum of Sorted Subarray Sums
  • Minimum Difference Between Largest and Smallest Value in Three Moves
  • Path Crossing
  • Check If Array Pairs Are Divisible by k
  • Number of Subsequences That Satisfy the Given Sum Condition
  • Can Make Arithmetic Progression From Sequence
  • Last Moment Before All Ants Fall Out of a Plank
  • Count Submatrices With All Ones
  • Minimum Possible Integer After at Most K Adjacent Swaps On Digits
  • Number of Good Pairs
  • Number of Substrings With Only 1s
  • Best Position for a Service Centre
  • Number of Nodes in the Sub-Tree With the Same Label
  • Most Visited Sector in a Circular Track
  • Maximum Number of Coins You Can Get
  • Find Latest Group of Size M
  • Stone Game V
  • Special Positions in a Binary Matrix
  • Min Cost to Connect All Points

Uncrossed Lines

Description

We write the integers of A and B (in the order they are given) on two separate horizontal lines.

Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that:

  • A[i] == B[j];
  • The line we draw does not intersect any other connecting (non-horizontal) line.

Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line.

Return the maximum number of connecting lines we can draw in this way.

 

Example 1:

Input: A = [1,4,2], B = [1,2,4]
Output: 2
Explanation: We can draw 2 uncrossed lines as in the diagram.
We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2.

Example 2:

Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2]
Output: 3

Example 3:

Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1]
Output: 2

 

Note:

  1. 1 <= A.length <= 500
  2. 1 <= B.length <= 500
  3. 1 <= A[i], B[i] <= 2000

Solution(javascript)

// DP O(m * n)
const maxUncrossedLines = function (A = [], B = []) {
  const map = {}
  const aux = (indexA, indexB) => {
    map[indexA] = map[indexA] || {}
    if (map[indexA][indexB] !== undefined) {
      return map[indexA][indexB]
    }
    if (indexA >= A.length || indexB >= B.length) {
      return 0
    }
    let index = -1
    // 加起来是一轮遍历
    for (let i = indexB; i < B.length; i++) {
      if (A[indexA] === B[i]) {
        index = i
        break
      }
    }
    if (index > -1) {
      map[indexA][indexB] = Math.max(
        aux(indexA + 1, index + 1) + 1,
        aux(indexA + 1, indexB),
      )
      return map[indexA][indexB]
    }
    map[indexA][indexB] = aux(indexA + 1, indexB)
    return map[indexA][indexB]
  }
  return aux(0, 0)
}
← Path With Maximum Minimum ValueBinary Search Tree to Greater Sum Tree →
  • Description
  • Solution(javascript)
Powered By LeetCode Site Generator