Repository: gzc/leetcode Branch: master Commit: 0bdefea63a22 Files: 1143 Total size: 1003.6 KB Directory structure: gitextract_k9u05cp_/ ├── .gitignore ├── LICENSE ├── README.md ├── Solve the Equation.cpp ├── TODO ├── cpp/ │ ├── 001-010/ │ │ ├── Add Two Numbers.cpp │ │ ├── Longest Palindromic Substring.cpp │ │ ├── Longest Substring Without Repeating Characters.cpp │ │ ├── Median of Two Sorted Arrays.cpp │ │ ├── Palindrome Number.cpp │ │ ├── Regular Expression Matching.cpp │ │ ├── Reverse Integer.cpp │ │ ├── String to Integer (atoi).cpp │ │ ├── Two Sum.cpp │ │ └── ZigZag Conversion.cpp │ ├── 011-020/ │ │ ├── 3Sum Closest.cpp │ │ ├── 3Sum.cpp │ │ ├── 4Sum.cpp │ │ ├── Container With Most Water.cpp │ │ ├── Integer to Roman.cpp │ │ ├── Letter Combinations of a Phone Number.cpp │ │ ├── Longest Common Prefix.cpp │ │ ├── Remove Nth Node From End of List.cpp │ │ ├── Roman to Integer.cpp │ │ └── Valid Parentheses.cpp │ ├── 021-030/ │ │ ├── Divide Two Integers.cpp │ │ ├── Generate Parentheses.cpp │ │ ├── Implement strStr().cpp │ │ ├── Merge Two Sorted Lists.cpp │ │ ├── Merge k Sorted Lists.cpp │ │ ├── Remove Duplicates from Sorted Array.cpp │ │ ├── Remove Element.cpp │ │ ├── Reverse Nodes in k-Group.cpp │ │ ├── Substring with Concatenation of All Words.cpp │ │ └── Swap Nodes in Pairs.cpp │ ├── 031-040/ │ │ ├── Combination Sum II.cpp │ │ ├── Combination Sum.cpp │ │ ├── Count and Say.cpp │ │ ├── Longest Valid Parentheses.cpp │ │ ├── Next Permutation.cpp │ │ ├── Search Insert Position.cpp │ │ ├── Search for a Range.cpp │ │ ├── Search in Rotated Sorted Array.cpp │ │ ├── Sudoku Solver.cpp │ │ └── Valid Sudoku.cpp │ ├── 041-050/ │ │ ├── First Missing Positive.cpp │ │ ├── Group Anagrams.cpp │ │ ├── Jump Game II.cpp │ │ ├── Multiply Strings.cpp │ │ ├── Permutations II.cpp │ │ ├── Permutations.cpp │ │ ├── Pow.cpp │ │ ├── Rotate Image.cpp │ │ ├── Trapping Rain Water.cpp │ │ └── Wildcard Matching.cpp │ ├── 051-060/ │ │ ├── Insert Interval.cpp │ │ ├── Jump Game.cpp │ │ ├── Length of Last Word.cpp │ │ ├── Maximum_Subarray.cpp │ │ ├── Merge Intervals.cpp │ │ ├── N-Queens II.cpp │ │ ├── N-Queens.cpp │ │ ├── Permutation Sequence.cpp │ │ ├── Spiral Matrix II.cpp │ │ └── Spiral Matrix.cpp │ ├── 061-070/ │ │ ├── Add Binary.cpp │ │ ├── Climbing Stairs.cpp │ │ ├── Minimum Path Sum .cpp │ │ ├── Plus One.cpp │ │ ├── Rotate List.cpp │ │ ├── Sqrt.cpp │ │ ├── Text Justification.cpp │ │ ├── Unique Paths II .cpp │ │ ├── Unique Paths.cpp │ │ └── Valid Number.cpp │ ├── 071-080/ │ │ ├── Combinations.cpp │ │ ├── Edit Distance.cpp │ │ ├── Minimum Window Substring.cpp │ │ ├── Remove Duplicates from Sorted Array II.cpp │ │ ├── Search a 2D Matrix.cpp │ │ ├── Set Matrix Zeroes.cpp │ │ ├── Simplify Path.cpp │ │ ├── Sort Colors.cpp │ │ ├── Subsets.cpp │ │ └── Word Search.cpp │ ├── 081-090/ │ │ ├── Gray Code.cpp │ │ ├── Largest Rectangle in Histogram.cpp │ │ ├── Maximal Rectangle.cpp │ │ ├── Merge Sorted Array.cpp │ │ ├── Partition List.cpp │ │ ├── Remove Duplicates from Sorted List II.cpp │ │ ├── Remove Duplicates from Sorted List.cpp │ │ ├── Scramble String.cpp │ │ ├── Search in Rotated Sorted Array II.cpp │ │ └── Subsets II.cpp │ ├── 091-100/ │ │ ├── Binary Tree Inorder Traversal.cpp │ │ ├── Decode Ways.cpp │ │ ├── Interleaving String.cpp │ │ ├── Recover Binary Search Tree.cpp │ │ ├── Restore IP Addresses.cpp │ │ ├── Reverse Linked List II.cpp │ │ ├── Same Tree.cpp │ │ ├── Unique Binary Search Trees II.cpp │ │ ├── Unique Binary Search Trees.cpp │ │ └── Validate Binary Search Tree.cpp │ ├── 1001-10000/ │ │ ├── 1001-1010/ │ │ │ └── Construct Binary Search Tree from Preorder Traversal.cpp │ │ ├── 1011-1020/ │ │ │ ├── Best Sightseeing Pair.cpp │ │ │ ├── Binary Prefix Divisible By 5.cpp │ │ │ ├── Binary String With Substrings Representing 1 To N.cpp │ │ │ ├── Convert to Base -2.cpp │ │ │ ├── Next Greater Node In Linked List.cpp │ │ │ ├── Number of Enclaves.cpp │ │ │ └── Partition Array Into Three Parts With Equal Sum.cpp │ │ ├── 1021-1030/ │ │ │ ├── Camelcase Matching.cpp │ │ │ ├── Divisor Game.cpp │ │ │ ├── Longest Arithmetic Sequence.cpp │ │ │ ├── Matrix Cells in Distance Order.cpp │ │ │ ├── Maximum Difference Between Node and Ancestor.cpp │ │ │ ├── Recover a Tree From Preorder Traversal.cpp │ │ │ ├── Remove Outermost Parentheses.cpp │ │ │ ├── Sum of Root To Leaf Binary Numbers.cpp │ │ │ ├── Two City Scheduling.cpp │ │ │ └── Video Stitching.cpp │ │ ├── 1031-1040/ │ │ │ ├── Binary Search Tree to Greater Sum Tree.cpp │ │ │ ├── Coloring A Border.cpp │ │ │ ├── Escape a Large Maze.cpp │ │ │ ├── Maximum Sum of Two Non-Overlapping Subarrays.cpp │ │ │ ├── Minimum Score Triangulation of Polygon.cpp │ │ │ ├── Moving Stones Until Consecutive.cpp │ │ │ ├── Stream of Characters.cpp │ │ │ ├── Uncrossed Lines.cpp │ │ │ └── Valid Boomerang.cpp │ │ ├── 1041-1050/ │ │ │ ├── Flower Planting With No Adjacent.cpp │ │ │ ├── Last Stone Weight II.cpp │ │ │ ├── Last Stone Weight.cpp │ │ │ ├── Longest String Chain.cpp │ │ │ ├── Partition Array for Maximum Sum.cpp │ │ │ ├── Remove All Adjacent Duplicates In String.cpp │ │ │ └── Robot Bounded In Circle.cpp │ │ ├── 1051-1060/ │ │ │ ├── Distant Barcodes.cpp │ │ │ ├── Grumpy Bookstore Owner.cpp │ │ │ ├── Height Checker.cpp │ │ │ └── Previous Permutation With One Swap.cpp │ │ ├── 1071-1080/ │ │ │ ├── Adding Two Negabinary Numbers.cpp │ │ │ ├── Flip Columns For Maximum Number of Equal Rows.cpp │ │ │ ├── Greatest Common Divisor of Strings.cpp │ │ │ ├── Insufficient Nodes in Root to Leaf Paths.cpp │ │ │ ├── Letter Tile Possibilities.cpp │ │ │ ├── Number of Submatrices That Sum to Target.cpp │ │ │ └── Occurrences After Bigram.cpp │ │ ├── 1081-1090/ │ │ │ ├── Duplicate Zeros.cpp │ │ │ ├── Largest Values From Labels.cpp │ │ │ └── Smallest Subsequence of Distinct Characters.cpp │ │ ├── 1091-1100/ │ │ │ ├── Brace Expansion II.cpp │ │ │ ├── Car Pooling.cpp │ │ │ ├── Find in Mountain Array.cpp │ │ │ ├── Shortest Common Supersequence.cpp │ │ │ ├── Shortest Path in Binary Matrix.cpp │ │ │ ├── Statistics from a Large Sample.cpp │ │ │ └── Two Sum Less Than K.cpp │ │ ├── 1101-1110/ │ │ │ ├── Corporate Flight Bookings.cpp │ │ │ ├── Defanging an IP Address.cpp │ │ │ ├── Delete Nodes And Return Forest.cpp │ │ │ ├── Distribute Candies to People.cpp │ │ │ ├── Filling Bookcase Shelves.cpp │ │ │ ├── Parsing A Boolean Expression.cpp │ │ │ └── Path In Zigzag Labelled Binary Tree.cpp │ │ ├── 1111-1120/ │ │ │ ├── Maximum Nesting Depth of Two Valid Parentheses Strings.cpp │ │ │ ├── Print FooBar Alternately.cpp │ │ │ └── Print in Order.cpp │ │ ├── 1121-1130/ │ │ │ ├── Lowest Common Ancestor of Deepest Leaves.cpp │ │ │ ├── Minimum Cost Tree From Leaf Values.cpp │ │ │ ├── Number of Equivalent Domino Pairs.cpp │ │ │ ├── Relative Sort Array.cpp │ │ │ └── Smallest Sufficient Team.cpp │ │ ├── 1131-1140/ │ │ │ └── N-th Tribonacci Number.cpp │ │ ├── 1141-1150/ │ │ │ ├── Binary Tree Coloring Game.cpp │ │ │ ├── Decrease Elements To Make Array Zigzag.cpp │ │ │ ├── Longest Chunked Palindrome Decomposition.cpp │ │ │ ├── Longest Common Subsequence.cpp │ │ │ └── Snapshot Array.cpp │ │ ├── 1151-1160/ │ │ │ ├── Day of the Year.cpp │ │ │ ├── Find Words That Can Be Formed by Characters.cpp │ │ │ └── Number of Dice Rolls With Target Sum.cpp │ │ ├── 1161-1170/ │ │ │ ├── As Far from Land as Possible.cpp │ │ │ ├── Compare Strings by Frequency of the Smallest Character.cpp │ │ │ ├── Design File System.cpp │ │ │ ├── Invalid Transactions.cpp │ │ │ ├── Maximum Level Sum of a Binary Tree.cpp │ │ │ ├── Minimum Cost to Connect Sticks.cpp │ │ │ ├── Optimize Water Distribution in a Village.cpp │ │ │ └── Single-Row Keyboard.cpp │ │ ├── 1171-1180/ │ │ │ ├── Can Make Palindrome from Substring.cpp │ │ │ ├── Count Substrings with Only One Distinct Letter.cpp │ │ │ ├── Diet Plan Performance.cpp │ │ │ ├── Dinner Plate Stacks.cpp │ │ │ ├── Prime Arrangements.cpp │ │ │ └── Remove Zero Sum Consecutive Nodes from Linked List.cpp │ │ ├── 1181-1190/ │ │ │ ├── Before and After Puzzle.cpp │ │ │ ├── Day of the Week.cpp │ │ │ ├── Design Bounded Blocking Queue.cpp │ │ │ ├── Distance Between Bus Stops.cpp │ │ │ ├── Make Array Strictly Increasing.cpp │ │ │ ├── Maximum Subarray Sum with One Deletion.cpp │ │ │ └── Shortest Distance to Target Color.cpp │ │ ├── 1191-1200/ │ │ │ └── Minimum Knight Moves.cpp │ │ ├── 1201-1210/ │ │ │ ├── Design Skiplist.cpp │ │ │ └── Smallest String With Swaps.cpp │ │ ├── 1221-1230/ │ │ │ ├── Dice Roll Simulation.cpp │ │ │ ├── Queens That Can Attack the King.cpp │ │ │ └── Split a String in Balanced Strings.cpp │ │ ├── 1231-1240/ │ │ │ ├── Maximum Profit in Job Scheduling.cpp │ │ │ └── Replace the Substring for Balanced String.cpp │ │ ├── 1241-1250/ │ │ │ ├── Minimum Remove to Make Valid Parentheses.cpp │ │ │ └── Web Crawler Multithreaded.cpp │ │ ├── 1261-1270/ │ │ │ └── Greatest Sum Divisible by Three.cpp │ │ ├── 1281-1290/ │ │ │ ├── Convert Binary Number in a Linked List to Integer.cpp │ │ │ ├── Element Appearing More Than 25% In Sorted Array.cpp │ │ │ └── Remove Covered Intervals.cpp │ │ ├── 1291-1300/ │ │ │ ├── Maximum Side Length of a Square with Sum Less than or Equal to Threshold.cpp │ │ │ └── Sequential Digits.cpp │ │ ├── 1311-1320/ │ │ │ └── Minimum Distance to Type a Word Using Two Fingers.cpp │ │ ├── 1411-1420/ │ │ │ └── Minimum Value to Get Positive Step by Step Sum.cpp │ │ ├── 1421-1430/ │ │ │ └── Leftmost Column with at Least a One.cpp │ │ ├── 1481-1490/ │ │ │ ├── Avoid Flood in The City.cpp │ │ │ ├── Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree.cpp │ │ │ ├── Making File Names Unique.cpp │ │ │ └── XOR Operation in an Array.cpp │ │ ├── 1501-1510/ │ │ │ └── Stone Game IV.cpp │ │ ├── 1541-1550/ │ │ │ └── Minimum Insertions to Balance a Parentheses String.cpp │ │ ├── 1561-1570/ │ │ │ └── Dot Product of Two Sparse Vectors.cpp │ │ ├── 1621-1630/ │ │ │ ├── Arithmetic Subarrays.cpp │ │ │ └── Slowest Key.cpp │ │ ├── 1631-1640/ │ │ │ ├── Check Array Formation Through Concatenation.cpp │ │ │ ├── Number of Ways to Form a Target String Given a Dictionary.cpp │ │ │ ├── Path With Minimum Effort.cpp │ │ │ └── Rank Transform of a Matrix.cpp │ │ ├── 1641-1650/ │ │ │ ├── Count Sorted Vowel Strings.cpp │ │ │ ├── Create Sorted Array through Instructions.cpp │ │ │ ├── Furthest Building You Can Reach.cpp │ │ │ ├── Get Maximum in Generated Array.cpp │ │ │ ├── Kth Smallest Instructions.cpp │ │ │ ├── Lowest Common Ancestor of a Binary Tree II.cpp │ │ │ ├── Lowest Common Ancestor of a Binary Tree III.cpp │ │ │ ├── Minimum Deletions to Make Character Frequencies Unique.cpp │ │ │ └── Sell Diminishing-Valued Colored Balls.cpp │ │ ├── 1671-1680/ │ │ │ ├── Lowest Common Ancestor of a Binary Tree IV.cpp │ │ │ └── Minimum Moves to Make Array Complementary.cpp │ │ ├── 1681-1690/ │ │ │ ├── Delivering Boxes from Storage to Ports.cpp │ │ │ ├── Stone Game VI.cpp │ │ │ └── Sum of Absolute Differences in a Sorted Array.cpp │ │ ├── 1701-1710/ │ │ │ ├── Determine if String Halves Are Alike.cpp │ │ │ ├── Maximum Number of Eaten Apples.cpp │ │ │ ├── Maximum Units on a Truck.cpp │ │ │ ├── Maximum XOR With an Element From Array.cpp │ │ │ └── Where Will the Ball Fall.cpp │ │ ├── 1711-1720/ │ │ │ ├── Count Good Meals.cpp │ │ │ ├── Decode XORed Array.cpp │ │ │ ├── Minimum Operations to Make a Subsequence.cpp │ │ │ └── Ways to Split Array Into Three Subarrays.cpp │ │ ├── 1721-1730/ │ │ │ ├── Find Minimum Time to Finish All Jobs.cpp │ │ │ ├── Largest Submatrix With Rearrangements.cpp │ │ │ ├── Minimize Hamming Distance After Swap Operations.cpp │ │ │ ├── Number Of Rectangles That Can Form The Largest Square.cpp │ │ │ ├── Swapping Nodes in a Linked List.cpp │ │ │ └── Tuple with Same Product.cpp │ │ ├── 1731-1740/ │ │ │ └── Building Boxes.cpp │ │ ├── 1751-1760/ │ │ │ ├── Closest Subsequence Sum.cpp │ │ │ ├── Largest Merge Of Two Strings.cpp │ │ │ ├── Maximum Number of Events That Can Be Attended II.cpp │ │ │ └── Minimum Limit of Balls in a Bag.cpp │ │ ├── 1761-1770/ │ │ │ ├── Form Array by Concatenating Subarrays of Another Array.cpp │ │ │ ├── Map of Highest Peak.cpp │ │ │ ├── Maximum Score from Performing Multiplication Operations.cpp │ │ │ ├── Minimum Degree of a Connected Trio in a Graph.cpp │ │ │ └── Tree of Coprimes.cpp │ │ ├── 1771-1780/ │ │ │ ├── Car Fleet II.cpp │ │ │ ├── Check if Number is a Sum of Powers of Three.cpp │ │ │ ├── Closest Dessert Cost.cpp │ │ │ ├── Equal Sum Arrays With Minimum Number of Operations.cpp │ │ │ ├── Find Nearest Point That Has the Same X or Y Coordinate.cpp │ │ │ ├── Maximize Palindrome Length From Subsequences.cpp │ │ │ └── Shortest Path in a Hidden Grid.cpp │ │ ├── 1781-1790/ │ │ │ ├── Check if Binary String Has at Most One Segment of Ones.cpp │ │ │ ├── Check if One String Swap Can Make Strings Equal.cpp │ │ │ ├── Count Pairs Of Nodes.cpp │ │ │ ├── Make the XOR of All Segments Equal to Zero.cpp │ │ │ ├── Maximize the Beauty of the Garden.cpp │ │ │ ├── Minimum Elements to Add to Form a Given Sum.cpp │ │ │ ├── Number of Restricted Paths From First to Last Node.cpp │ │ │ └── Sum of Beauty of All Substrings.cpp │ │ ├── 1791-1800/ │ │ │ ├── Count Pairs of Equal Substrings With Minimum Difference.cpp │ │ │ ├── Design Authentication Manager.cpp │ │ │ ├── Find Center of Star Graph.cpp │ │ │ ├── Maximize Score After N Operations.cpp │ │ │ ├── Maximum Ascending Subarray Sum.cpp │ │ │ ├── Maximum Average Pass Ratio.cpp │ │ │ ├── Maximum Number of Consecutive Values You Can Make.cpp │ │ │ ├── Maximum Score of a Good Subarray.cpp │ │ │ └── Second Largest Digit in a String.cpp │ │ ├── 1801-1810/ │ │ │ ├── Count Pairs With XOR in a Range.cpp │ │ │ ├── Evaluate the Bracket Pairs of a String.cpp │ │ │ ├── Implement Trie II (Prefix Tree).cpp │ │ │ ├── Maximize Number of Nice Divisors.cpp │ │ │ ├── Maximum Value at a Given Index in a Bounded Array.cpp │ │ │ ├── Minimum Path Cost in a Hidden Grid.cpp │ │ │ ├── Number of Different Integers in a String.cpp │ │ │ └── Number of Orders in the Backlog.cpp │ │ ├── 1811-1820/ │ │ │ ├── Count Nice Pairs in an Array.cpp │ │ │ ├── Determine Color of a Chessboard Square.cpp │ │ │ ├── Finding the Users Active Minutes.cpp │ │ │ ├── Maximum Number of Accepted Invitations.cpp │ │ │ ├── Maximum Number of Groups Getting Fresh Donuts.cpp │ │ │ ├── Minimum Absolute Sum Difference.cpp │ │ │ ├── Number of Different Subsequences GCDs.cpp │ │ │ ├── Sentence Similarity III.cpp │ │ │ └── Truncate Sentence.cpp │ │ ├── 1821-1830/ │ │ │ ├── Faulty Sensor.cpp │ │ │ ├── Finding MK Average.cpp │ │ │ ├── Maximum XOR for Each Query.cpp │ │ │ ├── Minimum Number of Operations to Make String Sorted.cpp │ │ │ ├── Minimum Operations to Make the Array Increasing.cpp │ │ │ ├── Minimum Sideway Jumps.cpp │ │ │ ├── Queries on Number of Points Inside a Circle.cpp │ │ │ └── Sign of the Product of an Array.cpp │ │ ├── 1831-1840/ │ │ │ ├── Check if the Sentence Is Pangram.cpp │ │ │ ├── Find XOR Sum of All Pairs Bitwise AND.cpp │ │ │ ├── Longest Substring Of All Vowels in Order.cpp │ │ │ ├── Maximum Building Height.cpp │ │ │ ├── Maximum Ice Cream Bars.cpp │ │ │ ├── Remove Duplicates From an Unsorted Linked List.cpp │ │ │ ├── Single-Threaded CPU.cpp │ │ │ └── Sum of Digits in Base K.cpp │ │ ├── 1841-1850/ │ │ │ ├── Closest Room.cpp │ │ │ └── Minimum Adjacent Swaps to Reach the Kth Smallest Number.cpp │ │ └── 1851-1860/ │ │ └── Minimum Interval to Include Each Query.cpp │ ├── 101-110/ │ │ ├── Balanced Binary Tree.cpp │ │ ├── Binary Tree Level Order Traversal II.cpp │ │ ├── Binary Tree Level Order Traversal.cpp │ │ ├── Binary Tree Zigzag Level Order Traversal.cpp │ │ ├── Construct Binary Tree from Inorder and Postorder Traversal.cpp │ │ ├── Construct Binary Tree from Preorder and Inorder Traversal.cpp │ │ ├── Convert Sorted Array to Binary Search Tree.cpp │ │ ├── Convert Sorted List to Binary Search Tree.cpp │ │ ├── Maximum Depth of Binary Tree.cpp │ │ └── Symmetric Tree.cpp │ ├── 111-120/ │ │ ├── Distinct Subsequences.cpp │ │ ├── Flatten Binary Tree to Linked List.cpp │ │ ├── Minimum Depth of Binary Tree.cpp │ │ ├── Pascal's Triangle II.cpp │ │ ├── Pascal's Triangle.cpp │ │ ├── Path Sum II.cpp │ │ ├── Path Sum.cpp │ │ ├── Populating Next Right Pointers in Each Node II.cpp │ │ ├── Populating Next Right Pointers in Each Node.cpp │ │ └── Triangle.cpp │ ├── 121-130/ │ │ ├── Best Time to Buy and Sell Stock II.cpp │ │ ├── Best Time to Buy and Sell Stock III.cpp │ │ ├── Best Time to Buy and Sell Stock.cpp │ │ ├── Binary Tree Maximum Path Sum.cpp │ │ ├── Longest Consecutive Sequence.cpp │ │ ├── Sum Root to Leaf Numbers.cpp │ │ ├── Surrounded Regions.cpp │ │ ├── Valid Palindrome.cpp │ │ ├── Word Ladder II.cpp │ │ └── Word Ladder.cpp │ ├── 131-140/ │ │ ├── Candy.cpp │ │ ├── Clone Graph.cpp │ │ ├── Copy List with Random Pointer.cpp │ │ ├── Gas Station.cpp │ │ ├── Palindrome Partitioning II.cpp │ │ ├── Palindrome Partitioning.cpp │ │ ├── Single Number II.cpp │ │ ├── Single Number.cpp │ │ ├── Word Break II.cpp │ │ └── Word Break.cpp │ ├── 141-150/ │ │ ├── Binary Tree Postorder Traversal.cpp │ │ ├── Evaluate Reverse Polish Notation.cpp │ │ ├── Insertion Sort List.cpp │ │ ├── LRU Cache.cpp │ │ ├── Linked List Cycle II.cpp │ │ ├── Linked List Cycle.cpp │ │ ├── Max Points on a Line.cpp │ │ ├── Reorder List.cpp │ │ ├── Sort List.cpp │ │ └── Tree Preorder Traversal.cpp │ ├── 151-160/ │ │ ├── Binary Tree Upside Down.cpp │ │ ├── Find Minimum in Rotated Sorted Array II.cpp │ │ ├── Find Minimum in Rotated Sorted Array.cpp │ │ ├── Intersection of Two Linked Lists.cpp │ │ ├── Longest Substring with At Most Two Distinct Characters.cpp │ │ ├── Maximum Product Subarray.cpp │ │ ├── Min Stack.cpp │ │ ├── Read N Characters Given Read4 II - Call multiple times.cpp │ │ ├── Read N Characters Given Read4.cpp │ │ └── Reverse Words in a String.cpp │ ├── 161-170/ │ │ ├── Compare Version Numbers.cpp │ │ ├── Excel Sheet Column Title.cpp │ │ ├── Find Peak Element.cpp │ │ ├── Fraction to Recurring Decimal.cpp │ │ ├── Majority Element.cpp │ │ ├── Maximum Gap.cpp │ │ ├── Missing Ranges.cpp │ │ ├── One Edit Distance.cpp │ │ ├── Two Sum II - Input array is sorted.cpp │ │ └── Two Sum III - Data structure design.cpp │ ├── 171-180/ │ │ ├── Binary Search Tree Iterator.cpp │ │ ├── Dungeon Game.cpp │ │ ├── Excel Sheet Column Number.cpp │ │ ├── Factorial Trailing Zeroes.cpp │ │ └── Largest Number.cpp │ ├── 181-190/ │ │ ├── Best Time to Buy and Sell Stock IV.cpp │ │ ├── Repeated DNA Sequences.cpp │ │ ├── Reverse Bits.cpp │ │ ├── Reverse Words in a String II.cpp │ │ └── Rotate Array.cpp │ ├── 191-200/ │ │ ├── Binary Tree Right Side View.cpp │ │ ├── House Robber.cpp │ │ ├── Number of 1 Bits.cpp │ │ ├── Number of Islands.cpp │ │ └── Reverse Bits.cpp │ ├── 201-210/ │ │ ├── Bitwise AND of Numbers Range.cpp │ │ ├── Count Primes.cpp │ │ ├── Course Schedule II.cpp │ │ ├── Course Schedule.cpp │ │ ├── Happy Number.cpp │ │ ├── Implement Trie (Prefix Tree).cpp │ │ ├── Isomorphic Strings.cpp │ │ ├── Minimum Size Subarray Sum.cpp │ │ ├── Remove Linked List Elements.cpp │ │ └── Reverse Linked List.cpp │ ├── 211-220/ │ │ ├── Add and Search Word - Data structure design.cpp │ │ ├── Combination Sum III.cpp │ │ ├── Contains Duplicate II.cpp │ │ ├── Contains Duplicate III.cpp │ │ ├── Contains Duplicate.cpp │ │ ├── House Robber II.cpp │ │ ├── Kth Largest Element in an Array.cpp │ │ ├── Shortest Palindrome.cpp │ │ ├── The Skyline Problem.cpp │ │ └── Word Search II.cpp │ ├── 221-230/ │ │ ├── Basic Calculator II.cpp │ │ ├── Basic Calculator.cpp │ │ ├── Count Complete Tree Nodes.cpp │ │ ├── Implement Stack using Queues.cpp │ │ ├── Invert Binary Tree.cpp │ │ ├── Kth Smallest Element in a BST.cpp │ │ ├── Majority Element II.cpp │ │ ├── Maximal Square.cpp │ │ ├── Rectangle Area.cpp │ │ └── Summary Ranges.cpp │ ├── 231-240/ │ │ ├── Delete Node in a Linked List.cpp │ │ ├── Implement Queue using Stacks.cpp │ │ ├── Lowest Common Ancestor of a Binary Search Tree.cpp │ │ ├── Lowest Common Ancestor of a Binary Tree.cpp │ │ ├── Number of Digit One.cpp │ │ ├── Palindrome Linked List.cpp │ │ ├── Power of Two.cpp │ │ ├── Product of Array Except Self.cpp │ │ ├── Search a 2D Matrix II.cpp │ │ └── Sliding Window Maximum.cpp │ ├── 241-250/ │ │ ├── Count Univalue Subtrees.cpp │ │ ├── Different Ways to Add Parentheses.cpp │ │ ├── Group Shifted Strings.cpp │ │ ├── Shortest Word Distance II.cpp │ │ ├── Shortest Word Distance III.cpp │ │ ├── Shortest Word Distance.cpp │ │ ├── Strobogrammatic Number II.cpp │ │ ├── Strobogrammatic Number III.cpp │ │ ├── Strobogrammatic Number.cpp │ │ └── Valid Anagram.cpp │ ├── 251-260/ │ │ ├── 3Sum Smaller.cpp │ │ ├── Add Digits.cpp │ │ ├── Binary Tree Paths.cpp │ │ ├── Factor Combinations.cpp │ │ ├── Flatten 2D Vector.cpp │ │ ├── Meeting Rooms II.cpp │ │ ├── Meeting Rooms.cpp │ │ ├── Paint House.cpp │ │ ├── Single Number III.cpp │ │ └── Verify Preorder Sequence in Binary Search Tree.cpp │ ├── 261-270/ │ │ ├── Alien Dictionary.cpp │ │ ├── Closest Binary Search Tree Value.cpp │ │ ├── Factor Combinations.cpp │ │ ├── Graph Valid Tree.cpp │ │ ├── Missing Number.cpp │ │ ├── Paint House II.cpp │ │ ├── Palindrome Permutation II.cpp │ │ ├── Palindrome Permutation.cpp │ │ ├── Ugly Number II.cpp │ │ └── Ugly Number.cpp │ ├── 271-280/ │ │ ├── Closest Binary Search Tree Value II.cpp │ │ ├── Encode and Decode Strings.cpp │ │ ├── Find the Celebrity.cpp │ │ ├── First Bad Version.cpp │ │ ├── H-Index II.cpp │ │ ├── H-Index.cpp │ │ ├── Integer to English Words.cpp │ │ ├── Paint Fence.cpp │ │ ├── Perfect Squares.cpp │ │ └── Wiggle Sort.cpp │ ├── 281-290/ │ │ ├── Expression Add Operators.cpp │ │ ├── Find the Duplicate Number.cpp │ │ ├── Game of Life.cpp │ │ ├── Inorder Successor in BST.cpp │ │ ├── Move Zeroes.cpp │ │ ├── Peeking Iterator.cpp │ │ ├── Unique Word Abbreviation.cpp │ │ ├── Walls and Gates.cpp │ │ ├── Word Pattern.cpp │ │ └── Zigzag Iterator.cpp │ ├── 291-300/ │ │ ├── Best Meeting Point.cpp │ │ ├── Binary Tree Longest Consecutive Sequence.cpp │ │ ├── Bulls and Cows.cpp │ │ ├── Find Median from Data Stream.cpp │ │ ├── Flip Game II.cpp │ │ ├── Flip Game.cpp │ │ ├── Longest Increasing Subsequence.cpp │ │ ├── Nim Game.cpp │ │ ├── Serialize and Deserialize Binary Tree.cpp │ │ └── Word Pattern II.cpp │ ├── 301-310/ │ │ ├── Additive Number.cpp │ │ ├── Best Time to Buy and Sell Stock with Cooldown.cpp │ │ ├── Minimum Height Trees.cpp │ │ ├── Number of Islands II.cpp │ │ ├── Range Sum Query - Immutable.cpp │ │ ├── Range Sum Query - Mutable.cpp │ │ ├── Range Sum Query 2D - Immutable.cpp │ │ ├── Range Sum Query 2D - Mutable.cpp │ │ ├── Remove Invalid Parentheses.cpp │ │ └── Smallest Rectangle Enclosing Black Pixels.cpp │ ├── 311-320/ │ │ ├── Binary Tree Vertical Order Traversal.cpp │ │ ├── Bulb Switcher.cpp │ │ ├── Burst Balloons.cpp │ │ ├── Count of Smaller Numbers After Self.cpp │ │ ├── Generalized Abbreviation.cpp │ │ ├── Maximum Product of Word Lengths.cpp │ │ ├── Remove Duplicate Letters.cpp │ │ ├── Shortest Distance from All Buildings.cpp │ │ ├── Sparse Matrix Multiplication.cpp │ │ └── Super Ugly Number.cpp │ ├── 321-330/ │ │ ├── Coin Change.cpp │ │ ├── Count of Range Sum.cpp │ │ ├── Create Maximum Number.cpp │ │ ├── Longest Increasing Path in a Matrix.cpp │ │ ├── Maximum Size Subarray Sum Equals k.cpp │ │ ├── Number of Connected Components in an Undirected Graph.cpp │ │ ├── Odd Even Linked List.cpp │ │ ├── Patching Array.cpp │ │ ├── Power of Three.cpp │ │ └── Wiggle Sort II.cpp │ ├── 331-340/ │ │ ├── Counting Bits.cpp │ │ ├── House Robber III.cpp │ │ ├── Increasing Triplet Subsequence.cpp │ │ ├── Largest BST Subtree.cpp │ │ ├── Longest Substring with At Most K Distinct Characters.cpp │ │ ├── Nested List Weight Sum.cpp │ │ ├── Palindrome Pairs.cpp │ │ ├── Reconstruct Itinerary.cpp │ │ ├── Self Crossing.cpp │ │ └── Verify Preorder Serialization of a Binary Tree.cpp │ ├── 341-350/ │ │ ├── Design Tic-Tac-Toe.cpp │ │ ├── Flatten Nested List Iterator.cpp │ │ ├── Integer Break.cpp │ │ ├── Intersection of Two Arrays II.cpp │ │ ├── Intersection of Two Arrays.cpp │ │ ├── Moving Average from Data Stream.cpp │ │ ├── Power of Four.cpp │ │ ├── Reverse String.cpp │ │ ├── Reverse Vowels of a String.cpp │ │ └── Top K Frequent Elements.cpp │ ├── 351-360/ │ │ ├── Android Unlock Patterns.cpp │ │ ├── Count Numbers with Unique Digits.cpp │ │ ├── Data Stream as Disjoint Intervals.cpp │ │ ├── Design Snake Game.cpp │ │ ├── Design Twitter.cpp │ │ ├── Line Reflection.cpp │ │ ├── Logger Rate Limiter.cpp │ │ ├── Rearrange String k Distance Apart.cpp │ │ ├── Russian Doll Envelopes.cpp │ │ └── Sort Transformed Array.cpp │ ├── 361-370/ │ │ ├── Bomb Enemy.cpp │ │ ├── Design Hit Counter.cpp │ │ ├── Find Leaves of Binary Tree.cpp │ │ ├── Largest Divisible Subset.cpp │ │ ├── Max Sum of Rectangle No Larger Than K.cpp │ │ ├── Nested List Weight Sum II.cpp │ │ ├── Plus One Linked List.cpp │ │ ├── Range Addition.cpp │ │ ├── Valid Perfect Square.cpp │ │ └── Water and Jug Problem.cpp │ ├── 371-380/ │ │ ├── Combination Sum IV.cpp │ │ ├── Design Phone Directory.cpp │ │ ├── Find K Pairs with Smallest Sums.cpp │ │ ├── Guess Number Higher or Lower II.cpp │ │ ├── Guess Number Higher or Lower.cpp │ │ ├── Insert Delete GetRandom O(1).cpp │ │ ├── Kth Smallest Element in a Sorted Matrix.cpp │ │ ├── Sum of Two Integers.cpp │ │ ├── Super Pow.cpp │ │ └── Wiggle Subsequence.cpp │ ├── 381-390/ │ │ ├── Elimination Game.cpp │ │ ├── Find the Difference.cpp │ │ ├── First Unique Character in a String.cpp │ │ ├── Insert Delete GetRandom O(1) - Duplicates allowed.cpp │ │ ├── Lexicographical Numbers.cpp │ │ ├── Linked List Random Node.cpp │ │ ├── Longest Absolute File Path.cpp │ │ ├── Mini Parser.cpp │ │ ├── Ransom Note.cpp │ │ └── Shuffle an Array.cpp │ ├── 391-400/ │ │ ├── Decode String.cpp │ │ ├── Evaluate Division.cpp │ │ ├── Integer Replacement.cpp │ │ ├── Is Subsequence.cpp │ │ ├── Longest Substring with At Least K Repeating Characters.cpp │ │ ├── Nth Digit.cpp │ │ ├── Perfect Rectangle.cpp │ │ ├── Random Pick Index.cpp │ │ ├── Rotate Function.cpp │ │ └── UTF-8 Validation.cpp │ ├── 401-410/ │ │ ├── Binary Watch.cpp │ │ ├── Convert a Number to Hexadecimal.cpp │ │ ├── Frog Jump.cpp │ │ ├── Longest Palindrome.cpp │ │ ├── Queue Reconstruction by Height.cpp │ │ ├── Remove K Digits.cpp │ │ ├── Split Array Largest Sum.cpp │ │ ├── Sum of Left Leaves.cpp │ │ ├── Trapping Rain Water II.cpp │ │ └── Valid Word Abbreviation.cpp │ ├── 411-420/ │ │ ├── Add Strings.cpp │ │ ├── Arithmetic Slices.cpp │ │ ├── Battleships in a Board.cpp │ │ ├── Fizz Buzz.cpp │ │ ├── Minimum Unique Word Abbreviation.cpp │ │ ├── Pacific Atlantic Water Flow.cpp │ │ ├── Partition Equal Subset Sum.cpp │ │ ├── Sentence Screen Fitting.cpp │ │ └── Third Maximum Number.cpp │ ├── 421-430/ │ │ ├── Convert Binary Search Tree to Sorted Doubly Linked List.cpp │ │ ├── Maximum XOR of Two Numbers in an Array.cpp │ │ ├── Serialize and Deserialize N-ary Tree.cpp │ │ ├── Valid Word Square.cpp │ │ └── Word Squares.cpp │ ├── 431-440/ │ │ ├── All O`one Data Structure.cpp │ │ ├── Find All Anagrams in a String.cpp │ │ ├── Find Right Interval.cpp │ │ ├── K-th Smallest in Lexicographical Order.cpp │ │ ├── Minimum Genetic Mutation.cpp │ │ ├── Number of Segments in a String.cpp │ │ ├── Path Sum III.cpp │ │ └── Ternary Expression Parser.cpp │ ├── 441-450/ │ │ ├── Add Two Numbers II.cpp │ │ ├── Arithmetic Slices II - Subsequence.cpp │ │ ├── Arranging Coins.cpp │ │ ├── Delete Node in a BST.cpp │ │ ├── Find All Duplicates in an Array.cpp │ │ ├── Number of Boomerangs.cpp │ │ ├── Sequence Reconstruction.cpp │ │ ├── Serialize and Deserialize BST.cpp │ │ └── String Compression.cpp │ ├── 451-460/ │ │ ├── 132 Pattern.cpp │ │ ├── 4Sum II.cpp │ │ ├── Assign Cookies.cpp │ │ ├── LFU Cache.cpp │ │ ├── Minimum Moves to Equal Array Elements.cpp │ │ ├── Minimum Number of Arrows to Burst Balloons.cpp │ │ ├── Repeated Substring Pattern.cpp │ │ └── Sort Characters By Frequency.cpp │ ├── 461-470/ │ │ ├── Can I Win.cpp │ │ ├── Convex Polygon.cpp │ │ ├── Count The Repetitions.cpp │ │ ├── Hamming Distance.cpp │ │ ├── Island Perimeter.cpp │ │ ├── Minimum Moves to Equal Array Elements II.cpp │ │ ├── Optimal Account Balancing.cpp │ │ ├── Unique Substrings in Wraparound String.cpp │ │ └── Validate IP Address.cpp │ ├── 471-480/ │ │ ├── Concatenated Words.cpp │ │ ├── Encode String with Shortest Length.cpp │ │ ├── Heaters.cpp │ │ ├── Largest Palindrome Product.cpp │ │ ├── Matchsticks to Square.cpp │ │ ├── Number Complement.cpp │ │ ├── Ones and Zeroes.cpp │ │ ├── Sliding Window Median.cpp │ │ └── Total Hamming Distance.cpp │ ├── 481-490/ │ │ ├── Find Permutation.cpp │ │ ├── License Key Formatting.cpp │ │ ├── Magical String.cpp │ │ ├── Max Consecutive Ones II.cpp │ │ ├── Max Consecutive Ones.cpp │ │ ├── Predict the Winner.cpp │ │ ├── Robot Room Cleaner.cpp │ │ ├── Smallest Good Base.cpp │ │ ├── The Maze.cpp │ │ └── Zuma Game.cpp │ ├── 491-500/ │ │ ├── Construct the Rectangle.cpp │ │ ├── Diagonal Traverse.cpp │ │ ├── Increasing Subsequences.cpp │ │ ├── Keyboard Row.cpp │ │ ├── Next Greater Element I.cpp │ │ ├── Reverse Pairs.cpp │ │ ├── Target Sum.cpp │ │ ├── Teemo Attacking.cpp │ │ └── The Maze III.cpp │ ├── 501-510/ │ │ ├── Base 7.cpp │ │ ├── Find Mode in Binary Search Tree.cpp │ │ ├── IPO.cpp │ │ ├── Most Frequent Subtree Sum.cpp │ │ ├── Next Greater Element II.cpp │ │ ├── Perfect Number.cpp │ │ ├── Relative Ranks.cpp │ │ └── The Maze II.cpp │ ├── 511-520/ │ │ ├── Coin Change 2.cpp │ │ ├── Detect Capital.cpp │ │ ├── Find Bottom Left Tree Value.cpp │ │ ├── Find Largest Value in Each Tree Row.cpp │ │ ├── Freedom Trail.cpp │ │ ├── Longest Palindromic Subsequence.cpp │ │ └── Super Washing Machines.cpp │ ├── 521-530/ │ │ ├── Beautiful Arrangement.cpp │ │ ├── Contiguous Array.cpp │ │ ├── Continuous Subarray Sum.cpp │ │ ├── Longest Uncommon Subsequence I.cpp │ │ ├── Longest Uncommon Subsequence II.cpp │ │ ├── Longest Word in Dictionary through Deleting.cpp │ │ ├── Minimum Distance Between BST Nodes.cpp │ │ └── Word Abbreviation.cpp │ ├── 531-540/ │ │ ├── Complex Number Multiplication.cpp │ │ ├── Convert BST to Greater Tree.cpp │ │ ├── Encode and Decode TinyURL.cpp │ │ ├── Lonely Pixel I.cpp │ │ ├── Lonely Pixel II.cpp │ │ └── Single Element in a Sorted Array.cpp │ ├── 541-550/ │ │ ├── 01 Matrix.cpp │ │ ├── Binary Tree Longest Consecutive Sequence II.cpp │ │ ├── Boundary of Binary Tree.cpp │ │ ├── Diameter of Binary Tree.cpp │ │ ├── Friend Circles.cpp │ │ ├── Output Contest Matches.cpp │ │ ├── Reverse String II.cpp │ │ └── Split Array with Equal Sum.cpp │ ├── 551-560/ │ │ ├── Brick Wall.cpp │ │ ├── Next Greater Element III.cpp │ │ ├── Optimal Division.cpp │ │ ├── Reverse Words in a String III.cpp │ │ ├── Split Concatenated Strings.cpp │ │ ├── Student Attendance Record I.cpp │ │ ├── Student Attendance Record II.cpp │ │ └── Subarray Sum Equals K.cpp │ ├── 561-570/ │ │ ├── Array Nesting.cpp │ │ ├── Array Partition I.cpp │ │ ├── Binary Tree Tilt.cpp │ │ ├── Longest Line of Consecutive One in Matrix.cpp │ │ ├── Maximum Vacation Days.cpp │ │ ├── Permutation in String.cpp │ │ └── Reshape the Matrix.cpp │ ├── 571-580/ │ │ ├── Distribute Candies.cpp │ │ ├── Out of Boundary Paths.cpp │ │ ├── Squirrel Simulation.cpp │ │ └── Subtree of Another Tree.cpp │ ├── 581-590/ │ │ ├── Delete Operation for Two Strings.cpp │ │ ├── Design In-Memory File System.cpp │ │ ├── Erect the Fence.cpp │ │ ├── Kill Process.cpp │ │ └── Shortest Unsorted Continuous Subarray.cpp │ ├── 591-600/ │ │ ├── Fraction Addition and Subtraction.cpp │ │ ├── Longest Harmonious Subsequence.cpp │ │ ├── Minimum Index Sum of Two Lists.cpp │ │ ├── Non-negative Integers without Consecutive Ones.cpp │ │ ├── Range Addition II.cpp │ │ ├── Tag Validator.cpp │ │ └── Valid Square.cpp │ ├── 601-610/ │ │ ├── Can Place Flowers.cpp │ │ ├── Construct String from Binary Tree.cpp │ │ ├── Design Compressed String Iterator.cpp │ │ └── Find Duplicate File in System.cpp │ ├── 611-620/ │ │ ├── Add Bold Tag in String.cpp │ │ ├── Merge Two Binary Trees.cpp │ │ └── Valid Triangle Number.cpp │ ├── 621-630/ │ │ ├── Add One Row to Tree.cpp │ │ ├── Course Schedule III.cpp │ │ ├── Design Circular Queue.cpp │ │ ├── K Inverse Pairs Array.cpp │ │ ├── Maximum Distance in Arrays.cpp │ │ ├── Maximum Product of Three Numbers.cpp │ │ ├── Minimum Factorization.cpp │ │ └── Task Scheduler.cpp │ ├── 631-640/ │ │ ├── Average of Levels in Binary Tree.cpp │ │ ├── Decode Ways II.cpp │ │ ├── Design Excel Sum Formula.cpp │ │ ├── Design Log Storage System.cpp │ │ ├── Exclusive Time of Functions.cpp │ │ ├── Find the Derangement of An Array.cpp │ │ ├── Shopping Offers.cpp │ │ ├── Smallest Range.cpp │ │ ├── Solve the Equation.cpp │ │ └── Sum of Square Numbers.cpp │ ├── 641-650/ │ │ ├── 2 Keys Keyboard.cpp │ │ ├── Design Search Autocomplete System.cpp │ │ ├── Dota2 Senate.cpp │ │ ├── Maximum Average Subarray I.cpp │ │ ├── Maximum Average Subarray II.cpp │ │ ├── Maximum Length of Pair Chain.cpp │ │ ├── Palindromic Substrings.cpp │ │ ├── Replace Words.cpp │ │ └── Set Mismatch.cpp │ ├── 651-660/ │ │ ├── 4 Keys Keyboard.cpp │ │ ├── Coin Path.cpp │ │ ├── Find Duplicate Subtrees.cpp │ │ ├── Find K Closest Elements.cpp │ │ ├── Judge Route Circle.cpp │ │ ├── Maximum Binary Tree.cpp │ │ ├── Print Binary Tree.cpp │ │ ├── Remove 9.cpp │ │ ├── Split Array into Consecutive Subsequences.cpp │ │ └── Two Sum IV - Input is a BST.cpp │ ├── 661-670/ │ │ ├── Beautiful Arrangement II.cpp │ │ ├── Equal Tree Partition.cpp │ │ ├── Image Smoother.cpp │ │ ├── Kth largest Number in Multiplication Table.cpp │ │ ├── Maximum Swap.cpp │ │ ├── Maximum Width of Binary Tree.cpp │ │ ├── Non-decreasing Array.cpp │ │ ├── Path Sum IV.cpp │ │ ├── Strange Printer.cpp │ │ └── Trim a Binary Search Tree.cpp │ ├── 671-680/ │ │ ├── 24 Game.cpp │ │ ├── Cut Off Trees for Golf Event.cpp │ │ ├── Implement Magic Dictionary.cpp │ │ ├── Longest Continuous Increasing Subsequence.cpp │ │ ├── Map Sum Pairs.cpp │ │ ├── Number of Longest Increasing Subsequence.cpp │ │ ├── Second Minimum Node In a Binary Tree.cpp │ │ ├── Valid Palindrome II.cpp │ │ └── Valid Parenthesis String.cpp │ ├── 681-690/ │ │ ├── Baseball Game.cpp │ │ ├── Employee Importance.cpp │ │ ├── K Empty Slots.cpp │ │ ├── Knight Probability in Chessboard.cpp │ │ ├── Longest Univalue Path.cpp │ │ ├── Maximum Sum of 3 Non-Overlapping Subarrays.cpp │ │ ├── Next Closest Time.cpp │ │ ├── Redundant Connection II.cpp │ │ ├── Redundant Connection.cpp │ │ └── Repeated String Match.cpp │ ├── 691-700/ │ │ ├── Binary Number with Alternating Bits.cpp │ │ ├── Count Binary Substrings.cpp │ │ ├── Degree of an Array.cpp │ │ ├── Falling Squares.cpp │ │ ├── Max Area of Island.cpp │ │ ├── Number of Distinct Islands.cpp │ │ ├── Partition to K Equal Sum Subsets.cpp │ │ └── Top K Frequent Words.cpp │ ├── 701-710/ │ │ ├── Insert into a Binary Search Tree.cpp │ │ ├── Random Pick with Blacklist.cpp │ │ └── To Lower Case.cpp │ ├── 711-720/ │ │ ├── 1-bit and 2-bit Characters.cpp │ │ ├── Best Time to Buy and Sell Stock with Transaction Fee.cpp │ │ ├── Find K-th Smallest Pair Distance.cpp │ │ ├── Longest Word in Dictionary.cpp │ │ ├── Max Stack.cpp │ │ ├── Maximum Length of Repeated Subarray.cpp │ │ ├── Minimum ASCII Delete Sum for Two Strings.cpp │ │ ├── Number of Distinct Islands II.cpp │ │ ├── Range Module.cpp │ │ └── Subarray Product Less Than K.cpp │ ├── 721-730/ │ │ ├── Accounts Merge.cpp │ │ ├── Candy Crush.cpp │ │ ├── Count Different Palindromic Subsequences.cpp │ │ ├── Find Pivot Index.cpp │ │ ├── My Calendar I.cpp │ │ ├── Number of Atoms.cpp │ │ ├── Remove Comments.cpp │ │ ├── Self Dividing Numbers.cpp │ │ └── Split Linked List in Parts.cpp │ ├── 731-740/ │ │ ├── Asteroid Collision.cpp │ │ ├── Daily Temperatures.cpp │ │ ├── Delete and Earn.cpp │ │ ├── Flood Fill.cpp │ │ ├── Monotone Increasing Digits.cpp │ │ ├── My Calendar II.cpp │ │ ├── My Calendar III.cpp │ │ ├── Parse Lisp Expression.cpp │ │ ├── Sentence Similarity II.cpp │ │ └── Sentence Similarity.cpp │ ├── 741-750/ │ │ ├── Closest Leaf in a Binary Tree.cpp │ │ ├── Find Smallest Letter Greater Than Target.cpp │ │ ├── Largest Number At Least Twice of Others.cpp │ │ ├── Min Cost Climbing Stairs.cpp │ │ ├── Network Delay Time.cpp │ │ ├── Number Of Corner Rectangles.cpp │ │ ├── Prefix and Suffix Search.cpp │ │ └── Shortest Completing Word.cpp │ ├── 751-760/ │ │ ├── Bold Words in String.cpp │ │ ├── Cracking the Safe.cpp │ │ ├── Employee Free Time.cpp │ │ ├── Find Anagram Mappings.cpp │ │ ├── IP to CIDR.cpp │ │ ├── Open the Lock.cpp │ │ ├── Pour Water.cpp │ │ ├── Pyramid Transition Matrix.cpp │ │ ├── Reach a Number.cpp │ │ └── Set Intersection Size At Least Two.cpp │ ├── 761-770/ │ │ ├── Couples Holding Hands.cpp │ │ ├── Largest Plus Sign.cpp │ │ ├── Max Chunks To Make Sorted II.cpp │ │ ├── Max Chunks To Make Sorted.cpp │ │ ├── Partition Labels.cpp │ │ ├── Prime Number of Set Bits in Binary Representation.cpp │ │ ├── Reorganize String.cpp │ │ ├── Special Binary String.cpp │ │ └── Toeplitz Marix.cpp │ ├── 771-780/ │ │ ├── Basic Calculator III.cpp │ │ ├── Global and Local Inversions.cpp │ │ ├── Jewels and Stones.cpp │ │ ├── K-th Symbol in Grammar.cpp │ │ ├── Minimize Max Distance to Gas Station.cpp │ │ ├── Sliding Puzzle.cpp │ │ ├── Split BST.cpp │ │ ├── Swap Adjacent in LR String.cpp │ │ └── Swim in Rising Water.cpp │ ├── 781-790/ │ │ ├── Cheapest Flights Within K Stops.cpp │ │ ├── Escape The Ghosts.cpp │ │ ├── Is Graph Bipartite?.cpp │ │ ├── K-th Smallest Prime Fraction.cpp │ │ ├── Letter Case Permutation.cpp │ │ ├── Minimum Distance Between BST Nodes.cpp │ │ ├── Rabbits in Forest.cpp │ │ ├── Rotated Digits.cpp │ │ └── Transform to Chessboard.cpp │ ├── 791-800/ │ │ ├── All Paths From Source to Target.cpp │ │ ├── Champagne Tower.cpp │ │ ├── Custom Sort String.cpp │ │ ├── Number of Matching Subsequences.cpp │ │ ├── Number of Subarrays with Bounded Maximum.cpp │ │ ├── Preimage Size of Factorial Zeroes Function.cpp │ │ ├── Rotate String │ │ ├── Similar RGB Color.cpp │ │ └── Valid Tic-Tac-Toe State.cpp │ ├── 801-810/ │ │ ├── Bricks Falling When Hit.cpp │ │ ├── Chalkboard XOR Game.cpp │ │ ├── Expressive Words.cpp │ │ ├── Find Eventual Safe States.cpp │ │ ├── Max Increase to Keep City Skyline.cpp │ │ ├── Minimum Swaps To Make Sequences Increasing.cpp │ │ ├── Number of Lines To Write String.cpp │ │ ├── Soup Servings.cpp │ │ └── Unique Morse Code Words.cpp │ ├── 811-820/ │ │ ├── Ambiguous Coordinates.cpp │ │ ├── Binary Tree Pruning.cpp │ │ ├── Bus Routes.cpp │ │ ├── Largest Sum of Averages.cpp │ │ ├── Linked List Components.cpp │ │ ├── Most Common Word.cpp │ │ ├── Race Car.cpp │ │ ├── Short Encoding of Words.cpp │ │ └── Subdomain Visit Count.cpp │ ├── 821-830/ │ │ ├── Binary Trees With Factors.cpp │ │ ├── Card Flipping Game.cpp │ │ ├── Consecutive Numbers Sum.cpp │ │ ├── Friends Of Appropriate Ages.cpp │ │ ├── Goat Latin.cpp │ │ ├── Making A Large Island.cpp │ │ ├── Most Profit Assigning Work.cpp │ │ ├── Positions of Large Groups.cpp │ │ ├── Shortest Distance to a Character.cpp │ │ └── Unique Letter String.cpp │ ├── 831-840/ │ │ ├── Find And Replace in String.cpp │ │ ├── Flipping an Image.cpp │ │ ├── Image Overlap.cpp │ │ ├── Magic Squares In Grid.cpp │ │ ├── Masking Personal Information.cpp │ │ ├── New 21 Game.cpp │ │ ├── Push Dominoes.cpp │ │ ├── Rectangle Overlap.cpp │ │ ├── Similar String Groups.cpp │ │ └── Sum of Distances in Tree.cpp │ ├── 841-850/ │ │ ├── Backspace String Compare.cpp │ │ ├── Guess the Word.cpp │ │ ├── Hand of Straights.cpp │ │ ├── Keys and Rooms.cpp │ │ ├── Longest Mountain in Array.cpp │ │ ├── Maximize Distance to Closest Person.cpp │ │ ├── Shifting Letters.cpp │ │ ├── Shortest Path Visiting All Nodes.cpp │ │ └── Split Array into Fibonacci Sequence.cpp │ ├── 851-860/ │ │ ├── Buddy Strings.cpp │ │ ├── Car Fleet.cpp │ │ ├── Exam Room.cpp │ │ ├── K-Similar Strings.cpp │ │ ├── Lemonade Change.cpp │ │ ├── Loud and Rich.cpp │ │ ├── Peak Index in a Mountain Array.cpp │ │ └── Score of Parentheses.cpp │ ├── 861-870/ │ │ ├── Advantage Shuffle.cpp │ │ ├── All Nodes Distance K in Binary Tree.cpp │ │ ├── Binary Gap.cpp │ │ ├── Prime Palindrome.cpp │ │ ├── Reordered Power of 2.cpp │ │ ├── Score After Flipping Matrix.cpp │ │ ├── Smallest Subtree with all the Deepest Nodes.cpp │ │ └── Transpose Matrix.cpp │ ├── 871-880/ │ │ ├── Implement Rand10() Using Rand7().cpp │ │ ├── Koko Eating Bananas.cpp │ │ ├── Leaf-Similar Trees.cpp │ │ ├── Length of Longest Fibonacci Subsequence.cpp │ │ ├── Middle of the Linked List.cpp │ │ └── Stone Game.cpp │ ├── 881-890/ │ │ ├── Boats to Save People.cpp │ │ ├── Possible Bipartition.cpp │ │ ├── Projection Area of 3D Shapes.cpp │ │ └── Uncommon Words from Two Sentences.cpp │ ├── 891-900/ │ │ └── Maximum Frequency Stack.cpp │ ├── 911-920/ │ │ ├── Complete Binary Tree Inserter.cpp │ │ ├── Maximum Sum Circular Subarray.cpp │ │ ├── Number of Music Playlists.cpp │ │ ├── Online Election.cpp │ │ ├── Partition Array into Disjoint Intervals.cpp │ │ ├── Reverse Only Letters.cpp │ │ ├── Word Subsets.cpp │ │ └── X of a Kind in a Deck of Cards.cpp │ ├── 921-930/ │ │ ├── 3Sum With Multiplicity.cpp │ │ ├── Binary Subarrays With Sum.cpp │ │ ├── Flip String to Monotone Increasing.cpp │ │ ├── Long Pressed Name.cpp │ │ ├── Minimize Malware Spread.cpp │ │ ├── Minimum Add to Make Parentheses Valid.cpp │ │ ├── Sort Array By Parity II.cpp │ │ ├── Three Equal Parts.cpp │ │ └── Unique Email Addresses.cpp │ ├── 931-940/ │ │ ├── Beautiful Array.cpp │ │ ├── Distinct Subsequences II.cpp │ │ ├── Knight Dialer.cpp │ │ ├── Minimum Area Rectangle.cpp │ │ ├── Minimum Falling Path Sum.cpp │ │ ├── Number of Recent Calls.cpp │ │ ├── Range Sum of BST.cpp │ │ ├── Reorder Log Files.cpp │ │ ├── Shortest Bridge.cpp │ │ └── Stamping The Sequence.cpp │ ├── 941-950/ │ │ ├── Bag of Tokens.cpp │ │ ├── DI String Match.cpp │ │ ├── Delete Columns to Make Sorted.cpp │ │ ├── Minimum Increment to Make Array Unique.cpp │ │ ├── Most Stones Removed with Same Row or Column.cpp │ │ ├── Valid Mountain Array.cpp │ │ └── Validate Stack Sequences.cpp │ ├── 951-960/ │ │ ├── Check Completeness of a Binary Tree.cpp │ │ ├── Prison Cells After N Days.cpp │ │ ├── Regions Cut By Slashes.cpp │ │ └── Verifying an Alien Dictionary.cpp │ ├── 961-970/ │ │ ├── N-Repeated Element in Size 2N Array.cpp │ │ └── Pancake Sorting.cpp │ ├── 971-980/ │ │ ├── Distribute Coins in Binary Tree.cpp │ │ ├── K Closest Points to Origin.cpp │ │ ├── Largest Perimeter Triangle.cpp │ │ ├── Longest Turbulent Subarray.cpp │ │ ├── Squares of a Sorted Array.cpp │ │ ├── Subarray Sums Divisible by K.cpp │ │ └── Unique Paths III.cpp │ ├── 981-990/ │ │ ├── Add to Array-Form of Integer.cpp │ │ ├── Interval List Intersections.cpp │ │ ├── Satisfiability of Equality Equations.cpp │ │ ├── String Without AAA or BBB.cpp │ │ └── Time Based Key-Value Store.cpp │ └── 991-1000/ │ ├── Broken Calculator.cpp │ ├── Cousins in Binary Tree.cpp │ ├── Find the Town Judge.cpp │ ├── Maximum Binary Tree II.cpp │ ├── Minimum Number of K Consecutive Bit Flips.cpp │ ├── Number of Squareful Arrays.cpp │ └── Rotting Oranges.cpp ├── golang/ │ └── 001-010/ │ ├── Add Two Numbers.go │ ├── Longest Substring Without Repeating Characters.go │ └── Two Sum.go ├── java/ │ ├── 201-210/ │ │ └── Happy Number.java │ ├── 291-300/ │ │ └── Nim Game.java │ └── 331-340/ │ ├── Counting Bits.java │ └── Nested List Weight Sum.java ├── python/ │ ├── 001-010/ │ │ └── Median of Two Sorted Arrays.py │ ├── 011-020/ │ │ └── Valid Parentheses.py │ ├── 021-030/ │ │ └── Reverse Nodes in k-Group.py │ ├── 031-040/ │ │ ├── Combination Sum II.py │ │ ├── Combination Sum.py │ │ ├── Next Permutation.py │ │ ├── Search Insert Position.py │ │ ├── Search for a Range.py │ │ ├── Sudoku Solver.py │ │ └── Valid Sudoku.py │ ├── 041-050/ │ │ ├── Jump Game II.py │ │ └── Rotate Image.py │ ├── 051-060/ │ │ ├── Jump Game.py │ │ └── Permutation Sequence.py │ ├── 061-070/ │ │ ├── Minimum Path Sum.py │ │ ├── Sqrt(x).py │ │ ├── Unique Paths II.py │ │ ├── Unique Paths.py │ │ └── Valid Number.py │ ├── 071-080/ │ │ └── Edit Distance.py │ ├── 081-090/ │ │ ├── Largest Rectangle in Histogram.py │ │ ├── Maximal Rectangle.py │ │ ├── Remove Duplicates from Sorted List II.py │ │ └── Remove Duplicates from Sorted List.py │ ├── 091-100/ │ │ ├── Decode Ways.py │ │ └── Interleaving String.py │ ├── 101-110/ │ │ └── Symmetric Tree.py │ ├── 111-120/ │ │ ├── Path Sum.py │ │ ├── Populating Next Right Pointers in Each Node II.py │ │ └── Populating Next Right Pointers in Each Node.py │ ├── 121-130/ │ │ ├── Best Time to Buy and Sell Stock.py │ │ ├── Binary Tree Maximum Path Sum.py │ │ ├── Word Ladder II.py │ │ └── Word Ladder.py │ ├── 131-140/ │ │ ├── Candy.py │ │ ├── Clone Graph.py │ │ └── Single Number II.py │ ├── 141-150/ │ │ ├── Binary Tree Postorder Traversal.py │ │ └── LRU Cache.py │ ├── 151-160/ │ │ ├── Find Minimum in Rotated Sorted Array II.py │ │ └── Find Minimum in Rotated Sorted Array.py │ ├── 161-170/ │ │ ├── Majority Element.py │ │ └── Maximum Gap.py │ ├── 171-180/ │ │ └── Largest Number.py │ ├── 181-190/ │ │ ├── Best Time to Buy and Sell Stock IV.py │ │ └── Repeated DNA Sequences.py │ ├── 191-200/ │ │ ├── Binary Tree Right Side View.py │ │ └── House Robber.py │ ├── 201-210/ │ │ ├── Count Primes.py │ │ └── Implement Trie (Prefix Tree).py │ ├── 211-220/ │ │ └── House Robber II.py │ ├── 221-230/ │ │ └── Maximal Square.py │ └── 231-240/ │ ├── Palindrome Linked List.py │ ├── Product of Array Except Self.py │ └── a.py └── scala/ ├── 0001-0010/ │ ├── Add Two Numbers.scala │ ├── Longest Substring Without Repeating Characters.scala │ ├── Palindrome Number.scala │ └── Two Sum.scala └── 0011-0020/ ├── Longest Common Prefix.scala └── Roman to Integer.scala ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .DS_Store ================================================ FILE: LICENSE ================================================ Copyright (C) <2015> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # leetcode LeetCode solutions. LeetCode solutions in English. LeetCode中文解答。 I uploaded some codes [here](https://zhenchaogan.gitbook.io/leetcode-solution/) [Video solutions](https://www.youtube.com/watch?v=iZHDx-k2Mxw&list=PLSY2q1ZYmTARCSZvXIwO79Lb9LB5EBX-a&index=2) [中文解答](https://www.youtube.com/watch?v=6S1eKneFu8I&list=PLSY2q1ZYmTATCxSnwd_NohDmmt8PTBzrq) [中文bilibili解答](https://space.bilibili.com/1551381295/channel/detail?cid=167862)
Problem Video Solution
LeetCode 1. Two Sum English 中文Youtube 中文b站
LeetCode 2. Add Two Numbers English 中文Youtube 中文b站
LeetCode 3. Longest Substring Without Repeating Characters English 中文Youtube 中文b站
LeetCode 4. Median of Two Sorted Arrays English 中文Youtube 中文b站
LeetCode 5. Longest Palindromic Substring English 中文Youtube 中文b站
LeetCode 6. ZigZag Conversion English 中文Youtube 中文b站
LeetCode 7. Reverse Integer English 中文Youtube 中文b站
LeetCode 8. String to Integer (atoi) English 中文Youtube 中文b站
LeetCode 9. Palindrome Number English 中文Youtube 中文b站
LeetCode 10. Regular Expression Matching English 中文Youtube 中文b站
LeetCode 11. Container With Most Water English 中文Youtube 中文b站
LeetCode 12. Integer to Roman English 中文Youtube 中文b站
LeetCode 13. Roman to Integer English 中文Youtube 中文b站
LeetCode 14. Longest Common Prefix English 中文Youtube 中文b站
LeetCode 15. 3Sum English 中文Youtube 中文b站
LeetCode 16. 3Sum Closest English 中文Youtube 中文b站
LeetCode 17. Letter Combinations of a Phone Number English 中文Youtube 中文b站
LeetCode 18. 4Sum English 中文Youtube 中文b站
LeetCode 19. Remove Nth Node From End of List English 中文Youtube 中文b站
LeetCode 20. Valid Parentheses English 中文Youtube 中文b站
LeetCode 21. Merge Two Sorted Lists English 中文Youtube 中文b站
LeetCode 22. Generate Parentheses English 中文Youtube 中文b站
LeetCode 23. Merge k Sorted Lists English 中文Youtube 中文b站
LeetCode 24. Swap Nodes in Pairs English 中文Youtube 中文b站
LeetCode 25. Reverse Nodes in k-Group English 中文Youtube 中文b站
LeetCode 26. Remove Duplicates from Sorted Array English 中文Youtube 中文b站
LeetCode 27. Remove Element English 中文Youtube 中文b站
LeetCode 28. Implement strStr() English 中文Youtube 中文b站
LeetCode 29. Divide Two Integers English 中文Youtube 中文b站
LeetCode 30. Substring with Concatenation of All Words English 中文Youtube 中文b站
LeetCode 31. Next Permutation English 中文Youtube 中文b站
LeetCode 32. Longest Valid Parentheses English 中文Youtube 中文b站
LeetCode 33. Search in Rotated Sorted Array English 中文Youtube 中文b站
LeetCode 42. Trapping Rain Water English 中文Youtube 中文b站
LeetCode 56. Merge Intervals English 中文Youtube 中文b站
LeetCode 67. Add Binary English 中文Youtube 中文b站
LeetCode 81. Search in Rotated Sorted Array II English 中文Youtube 中文b站
LeetCode 125. Valid Palindrome English 中文Youtube 中文b站
LeetCode 153. Find Minimum in Rotated Sorted Array English 中文Youtube 中文b站
LeetCode 154. Find Minimum in Rotated Sorted Array II English 中文Youtube 中文b站
LeetCode 157. Read N Characters Given Read4 English 中文Youtube 中文b站
LeetCode 158. Read N Characters Given Read4 II - Call multiple times English 中文Youtube 中文b站
LeetCode 236. Lowest Common Ancestor of a Binary Tree English 中文Youtube 中文b站
LeetCode 238. Product of Array Except Self English 中文Youtube 中文b站
LeetCode 269. Alien Dictionary English 中文Youtube 中文b站
Leetcode 295. Find Median from Data Stream English 中文Youtube 中文b站
Leetcode 297. Serialize and Deserialize Binary Tree English 中文Youtube 中文b站
LeetCode 300. Longest Increasing Subsequence English 中文Youtube 中文b站
LeetCode 301. Remove Invalid Parentheses English 中文Youtube 中文b站
LeetCode 336. Palindrome Pairs English 中文Youtube 中文b站
LeetCode 407. Trapping Rain Water II English 中文Youtube 中文b站
LeetCode 415. Add Strings English 中文Youtube 中文b站
LeetCode 426. Convert Binary Search Tree to Sorted Doubly Linked List English 中文Youtube 中文b站
LeetCode 489. Robot Room Cleaner English 中文Youtube 中文b站
LeetCode 560. Subarray Sum Equals K English 中文Youtube 中文b站
LeetCode 680. Valid Palindrome II English 中文Youtube 中文b站
LeetCode 710. Random Pick with Blacklist English 中文Youtube 中文b站
LeetCode 721. Accounts Merge English 中文Youtube 中文b站
LeetCode 863. All Nodes Distance K in Binary Tree English 中文Youtube 中文b站
LeetCode 918. Maximum Sum Circular Subarray English 中文Youtube 中文b站
LeetCode 953. Verifying an Alien Dictionary English 中文Youtube 中文b站
LeetCode 973. K Closest Points to Origin English 中文Youtube 中文b站
LeetCode 1249. Minimum Remove to Make Valid Parentheses English 中文Youtube 中文b站
LeetCode 1428. Leftmost Column with at Least a One English 中文Youtube 中文b站
LeetCode 1570. Dot Product of Two Sparse Vectors English 中文Youtube 中文b站
LeetCode 1644. Lowest Common Ancestor of a Binary Tree II English 中文Youtube 中文b站
LeetCode 1650. Lowest Common Ancestor of a Binary Tree III English 中文Youtube 中文b站
LeetCode 1676. Lowest Common Ancestor of a Binary Tree IV English 中文Youtube 中文b站
LeetCode 1727. Largest Submatrix With Rearrangements English 中文Youtube 中文b站
LeetCode 1751. Maximum Number of Events That Can Be Attended II English 中文Youtube 中文b站
LeetCode 1754. Largest Merge Of Two Strings English 中文Youtube 中文b站
LeetCode 1755. Closest Subsequence Sum English 中文Youtube 中文b站
LeetCode 1760. Minimum Limit of Balls in a Bag English 中文Youtube 中文b站
LeetCode 1761. Minimum Degree of a Connected Trio in a Graph English 中文Youtube 中文b站
LeetCode 1764. Form Array by Concatenating Subarrays of Another Array English 中文Youtube 中文b站
LeetCode 1765. Map of Highest Peak English 中文Youtube 中文b站
LeetCode 1766. Tree of Coprimes English 中文Youtube 中文b站
LeetCode 1770. Maximum Score from Performing Multiplication Operations English 中文Youtube 中文b站
LeetCode 1771. Maximize Palindrome Length From Subsequences English 中文Youtube 中文b站
LeetCode 1774. Closest Dessert Cost English 中文Youtube 中文b站
LeetCode 1775. Equal Sum Arrays With Minimum Number of Operations English 中文Youtube 中文b站
LeetCode 1776. Car Fleet II English 中文Youtube 中文b站
LeetCode 1778. Shortest Path in a Hidden Grid English 中文Youtube 中文b站
LeetCode 1779. Find Nearest Point That Has the Same X or Y Coordinate English 中文Youtube 中文b站
LeetCode 1780. Check if Number is a Sum of Powers of Three English 中文Youtube 中文b站
LeetCode 1781. Sum of Beauty of All Substrings English 中文Youtube 中文b站
LeetCode 1782. Count Pairs Of Nodes English 中文Youtube 中文b站
LeetCode 1784. Check if Binary String Has at Most One Segment of Ones English 中文Youtube 中文b站
LeetCode 1785. Minimum Elements to Add to Form a Given Sum English 中文Youtube 中文b站
LeetCode 1786. Number of Restricted Paths From First to Last Node English 中文Youtube 中文b站
LeetCode 1787. Make the XOR of All Segments Equal to Zero English 中文Youtube 中文b站
LeetCode 1788. Maximize the Beauty of the Garden English 中文Youtube 中文b站
LeetCode 1790. Check if One String Swap Can Make Strings Equal English 中文Youtube 中文b站
LeetCode 1791. Find Center of Star Graph English 中文Youtube 中文b站
LeetCode 1792. Maximum Average Pass Ratio English 中文Youtube 中文b站
LeetCode 1793. Maximum Score of a Good Subarray English 中文Youtube 中文b站
LeetCode 1794. Count Pairs of Equal Substrings With Minimum Difference English 中文Youtube 中文b站
LeetCode 1796. Second Largest Digit in a String English 中文Youtube 中文b站
LeetCode 1797. Design Authentication Manager English 中文Youtube 中文b站
LeetCode 1798. Maximum Number of Consecutive Values You Can Make English 中文Youtube 中文b站
LeetCode 1799. Maximize Score After N Operations English 中文Youtube 中文b站
LeetCode 1800. Maximum Ascending Subarray Sum English 中文Youtube 中文b站
LeetCode 1801. Number of Orders in the Backlog English 中文Youtube 中文b站
LeetCode 1802. Maximum Value at a Given Index in a Bounded Array English 中文Youtube 中文b站
LeetCode 1803. Count Pairs With XOR in a Range English 中文Youtube 中文b站
LeetCode 1804. Implement Trie II (Prefix Tree) English 中文Youtube 中文b站
LeetCode 1805. Number of Different Integers in a String English 中文Youtube 中文b站
LeetCode 1807. Evaluate the Bracket Pairs of a String English 中文Youtube 中文b站
LeetCode 1808. Maximize Number of Nice Divisors English 中文Youtube 中文b站
LeetCode 1810. Minimum Path Cost in a Hidden Grid English 中文Youtube 中文b站
LeetCode 1812. Determine Color of a Chessboard Square English 中文Youtube 中文b站
LeetCode 1813. Sentence Similarity III English 中文Youtube 中文b站
LeetCode 1814. Count Nice Pairs in an Array English 中文Youtube 中文b站
LeetCode 1815. Maximum Number of Groups Getting Fresh Donuts English 中文Youtube 中文b站
LeetCode 1816. Truncate Sentence English 中文Youtube 中文b站
LeetCode 1817. Finding the Users Active Minutes English 中文Youtube 中文b站
LeetCode 1818. Minimum Absolute Sum Difference English 中文Youtube 中文b站
LeetCode 1819. Number of Different Subsequences GCDs English 中文Youtube 中文b站
LeetCode 1820. Maximum Number of Accepted Invitations English 中文Youtube 中文b站
LeetCode 1822. Sign of the Product of an Array English 中文Youtube 中文b站
LeetCode 1824. Minimum Sideway Jumps English 中文Youtube 中文b站
LeetCode 1825. Finding MK Average English 中文Youtube 中文b站
LeetCode 1826. Faulty Sensor English 中文Youtube 中文b站
LeetCode 1827. Minimum Operations to Make the Array Increasing English 中文Youtube 中文b站
LeetCode 1828. Queries on Number of Points Inside a Circle English 中文Youtube 中文b站
LeetCode 1829. Maximum XOR for Each Query English 中文Youtube 中文b站
LeetCode 1830. Minimum Number of Operations to Make String Sorted English 中文Youtube 中文b站
LeetCode 1832. Check if the Sentence Is Pangram English 中文Youtube 中文b站
LeetCode 1833. Maximum Ice Cream Bars English 中文Youtube 中文b站
LeetCode 1834. Single-Threaded CPU English 中文Youtube 中文b站
LeetCode 1835. Find XOR Sum of All Pairs Bitwise AND English 中文Youtube 中文b站
LeetCode 1836. Remove Duplicates From an Unsorted Linked List English 中文Youtube 中文b站
LeetCode 1837. Sum of Digits in Base K English 中文Youtube 中文b站
LeetCode 1839. Longest Substring Of All Vowels in Order English 中文Youtube 中文b站
LeetCode 1840. Maximum Building Height English 中文Youtube 中文b站
LeetCode 1847. Closest Room English 中文Youtube 中文b站
LeetCode 1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number English 中文Youtube 中文b站
LeetCode 1851. Minimum Interval to Include Each Query English 中文Youtube 中文b站
================================================ FILE: Solve the Equation.cpp ================================================ // https://discuss.leetcode.com/topic/95378/concise-c-solution-with-regular-expression-12-lines class Solution { public: string solveEquation(string equation) { // normalize the equation, add 1 for x's which have no coefficient: x => 1x equation = regex_replace(equation, regex("(^|[+=-])x"), "$011x"); // calculate coefficients for both sides auto pos = equation.find('='); auto l = coef(equation.substr(0, pos)); auto r = coef(equation.substr(pos + 1)); // l.first x + l.second = r.first x + r.second => ax = b int a = l.first - r.first; int b = r.second - l.second; return a != 0 ? "x=" + to_string(b/a) : b != 0 ? "No solution" : "Infinite solutions"; } pair coef(string s) { // split the side into form of (+/-)123x auto e = regex("(^|[+-])\\d+x?"); regex_token_iterator it(s.begin(), s.end(), e), end; int a = 0, b = 0; for (; it != end; it++) (it->str().back() == 'x' ? a : b) += stoi(*it); return {a, b}; } }; ================================================ FILE: TODO ================================================ 4 Median of Two Sorted Arrays 5 Longest Palindromic Substring 9 Palindrome Number 10 Regular Expression Matching(花了挺多时间,30分钟) 12 Integer to Roman 醉了啊 42 review later 43 need more practice 44 tricky ================================================ FILE: cpp/001-010/Add Two Numbers.cpp ================================================ class Solution { public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { ListNode *head = new ListNode(0); ListNode *pre = head; int carry = 0; while(l1 || l2 || carry) { int a = (l1 == NULL? 0 : l1->val); int b = (l2 == NULL? 0 : l2->val); int c = a + b + carry; carry = c > 9? 1 : 0; int v = c%10; ListNode *cur = new ListNode(v); pre->next = cur; pre = pre->next; if(l1) l1 = l1->next; if(l2) l2 = l2->next; } return head->next; } }; ================================================ FILE: cpp/001-010/Longest Palindromic Substring.cpp ================================================ class Solution { public: string longestPalindrome(string s) { int n = s.length(); int longestBegin = 0; int maxLen = 1; bool table[1000][1000] = {false}; for (int i = 0; i < n; i++) table[i][i] = true; for (int len = 2; len <= n; len++) { for (int i = 0; i < n-len+1; i++) { int j = i+len-1; if (s[i] == s[j] && (j-i == 1 || table[i+1][j-1])) { table[i][j] = true; longestBegin = i; maxLen = len; } } } return s.substr(longestBegin, maxLen); } }; ================================================ FILE: cpp/001-010/Longest Substring Without Repeating Characters.cpp ================================================ class Solution { public: int lengthOfLongestSubstring(string s) { unordered_map mymap; int start = 0; int ans = 0; for (int i = 0; i < s.length(); i++) { char ch = s[i]; auto it = mymap.find(ch); if (it != mymap.end()) { start = max(start, it->second + 1); } mymap[ch] = i; ans = max(ans, i - start + 1); } return ans; } }; ================================================ FILE: cpp/001-010/Median of Two Sorted Arrays.cpp ================================================ class Solution { public: double findMedianSortedArrays(vector& nums1, vector& nums2) { int m = nums1.size(), n = nums2.size(); if ((m + n) % 2 == 1) { return findKthElement((m + n) / 2 + 1, nums1, 0, nums2, 0); } else { return (findKthElement((m + n) / 2, nums1, 0 ,nums2, 0) + findKthElement((m + n) / 2 + 1, nums1, 0 ,nums2, 0)) / 2; } } double findKthElement(int k, const vector& nums1, int idx1, const vector& nums2, int idx2) { int l1 = nums1.size() - idx1; int l2 = nums2.size() - idx2; if (l1 > l2) { return findKthElement(k, nums2, idx2, nums1, idx1); } if (l1 == 0) { return nums2[idx2 + k - 1]; } if (k == 1) { return min(nums1[idx1], nums2[idx2]); } int cut1 = min(k/2, l1); int cut2 = k - cut1; if (nums1[idx1 + cut1 - 1] > nums2[idx2 + cut2 - 1]) { return findKthElement(k - cut2, nums1, idx1, nums2, idx2 + cut2); } else { return findKthElement(k - cut1, nums1, idx1 + cut1, nums2, idx2); } } }; ================================================ FILE: cpp/001-010/Palindrome Number.cpp ================================================ class Solution { public: bool isPalindrome(int x) { if (x == 0) return true; if (x < 0) return false; if (x % 10 == 0) return false; int sum = 0; while (x > sum) { sum = sum * 10 + x % 10; x /= 10; } return (x == sum) || (x == sum / 10); } }; ================================================ FILE: cpp/001-010/Regular Expression Matching.cpp ================================================ class Solution { bool isMatch(const string& s, int sidx, const string& p, int pidx) { if (pidx >= p.length()) { return sidx == s.length(); } if ((pidx + 1) < p.length() && p[pidx + 1] == '*') { if (isMatch(s, sidx, p, pidx + 2)) { return true; } if (sidx < s.length() && (p[pidx] == '.' || s[sidx] == p[pidx])) { return isMatch(s, sidx + 1, p, pidx); } } else if (sidx < s.length() && (p[pidx] == '.' || s[sidx] == p[pidx])) { return isMatch(s, sidx + 1, p, pidx + 1); } return false; } public: bool isMatch(string s, string p) { return isMatch(s, 0, p, 0); } }; ================================================ FILE: cpp/001-010/Reverse Integer.cpp ================================================ class Solution { public: int reverse(int x) { // INT_MAX: 2147483647 // INT_MIN: -2147483648 int result = 0; while (x != 0) { int mod = x % 10; if (result > 214748364 || (result == 214748364 && mod > 7)) { return 0; } if (result < -214748364 || (result == -214748364 && mod == -9)) { return 0; } result = 10 * result + mod; x /= 10; } return result; } }; ================================================ FILE: cpp/001-010/String to Integer (atoi).cpp ================================================ class Solution { public: int myAtoi(string str) { while (str[0] == ' ') { str.erase(0, 1); } int sign = 1; if (str[0] == '+' || str[0] == '-') { if (str[0] == '-') sign = -1; str.erase(0, 1); } int result = 0; for (int i = 0; i < str.length(); i++) { if (!isdigit(str[i])) { break; } int v = str[i] - '0'; if (result > INT_MAX/10) { if (sign == 1) return INT_MAX; if (sign == -1) return INT_MIN; } else if (result == INT_MAX/10) { if (sign == 1 && v >= 7) return INT_MAX; if (sign == -1 && v >= 8) return INT_MIN; } result = 10 * result + v; } return result * sign; } }; ================================================ FILE: cpp/001-010/Two Sum.cpp ================================================ class Solution { public: vector twoSum(vector &numbers, int target) { unordered_map m; vector result; for (int i = 0;i < numbers.size();i++) { int remain = target - numbers[i]; if (m.count(remain) > 0) { result.push_back(m[remain]); result.push_back(i); return result; } m[numbers[i]] = i; } return result; } }; ================================================ FILE: cpp/001-010/ZigZag Conversion.cpp ================================================ class Solution { public: string convert(string s, int numRows) { if (numRows == 1) { return s; } vector rows(numRows); int row = 0; int step = 1; for (char ch : s) { rows[row].push_back(ch); if (row == (numRows - 1)) { step = -1; } else if (row == 0) { step = 1; } row += step; } stringstream ss; for (const string& row : rows) { ss << row; } return ss.str(); } }; ================================================ FILE: cpp/011-020/3Sum Closest.cpp ================================================ class Solution { public: int threeSumClosest(vector& nums, int target) { int ans = 0; int diff = INT_MAX; sort(nums.begin(), nums.end()); for (int i = 0; i < nums.size(); i++) { if (i > 0 && nums[i - 1] == nums[i]) { continue; } int j = i + 1; int k = nums.size() - 1; while (j < k) { int sum = nums[i] + nums[j] + nums[k]; if (abs(sum - target) < diff) { ans = sum; diff = abs(sum - target); } if (sum < target) { j++; } else if (sum > target) { k--; } else { return target; } } } return ans; } }; ================================================ FILE: cpp/011-020/3Sum.cpp ================================================ class Solution { public: vector> threeSum(vector& nums) { vector> result; sort(nums.begin(), nums.end()); for (int i = 0; i < nums.size(); i++) { if (i > 0 && nums[i - 1] == nums[i]) { continue; } int j = i + 1; int k = nums.size() - 1; while (j < k) { int sum = nums[i] + nums[j] + nums[k]; if (sum < 0) { j++; } else if (sum > 0) { k--; } else { result.push_back({nums[i], nums[j], nums[k]}); while ((j + 1) < nums.size() && nums[j] == nums[j+1]) j++; j++; while ((k - 1) >= 0 && nums[k] == nums[k - 1]) k--; k--; } } } return result; } }; ================================================ FILE: cpp/011-020/4Sum.cpp ================================================ class Solution { public: vector > fourSum(vector &num, int target) { vector>result; int n = num.size(); sort(num.begin(), num.end()); for (int i = 0; i < n; i++) { if (i > 0 && num[i-1] == num[i]) { continue; } for (int j = i + 1; j < n; j++) { if (j > (i + 1) && num[j-1] == num[j]) { continue; } int l = j + 1, r = n - 1; int partial_sum = num[i] + num[j]; while (l < r) { int sum = partial_sum + num[l] + num[r]; if (sum < target) { l++; } else if (sum > target) { r--; } else { result.push_back({num[i], num[j], num[l], num[r]}); while ((l + 1) < num.size() && num[l] == num[l+1]) l++; l++; while ((r - 1) >= 0 && num[r] == num[r - 1]) r--; r--; } } } } return result; } }; ================================================ FILE: cpp/011-020/Container With Most Water.cpp ================================================ class Solution { public: int maxArea(vector& height) { int i(0), j(height.size()-1); int area(0); while (i < j) { area = max(area, (j-i)*min(height[i], height[j])); height[i] > height[j] ? j-- : i++; } return area; } }; ================================================ FILE: cpp/011-020/Integer to Roman.cpp ================================================ class Solution { public: string intToRoman(int num) { map mymap{ {1, "I"}, {5, "V"}, {10, "X"}, {50, "L"}, {100, "C"}, {500, "D"}, {1000, "M"}, {4, "IV"}, {9, "IX"}, {40, "XL"}, {90, "XC"}, {400, "CD"}, {900, "CM"} }; stringstream ss; for (auto it = mymap.rbegin(); it != mymap.rend(); it++) { int key = it->first; const string& code = it->second; while (num >= key) { num -= key; ss << code; } } return ss.str(); } }; ================================================ FILE: cpp/011-020/Letter Combinations of a Phone Number.cpp ================================================ class Solution { public: vector letterCombinations(string digits) { string symbols[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; vector result; if (digits.empty()) { return result; } result.push_back(""); for (char ch : digits) { int num = ch - '0'; vector new_result; for (const string& s : result) { for (char symbol : symbols[num]) { string tmp = s + symbol; new_result.push_back(tmp); } } result.swap(new_result); } return result; } }; ================================================ FILE: cpp/011-020/Longest Common Prefix.cpp ================================================ class Solution { public: string longestCommonPrefix(vector& strs) { if (strs.empty()) { return ""; } string prefix = strs[0]; for (int i = 1; i < strs.size(); i++) { const string& str = strs[i]; int k = 0; while (k < min(prefix.length(), str.length())) { if (prefix[k] != str[k]) { break; } k++; } prefix = prefix.substr(0, k); } return prefix; } }; ================================================ FILE: cpp/011-020/Remove Nth Node From End of List.cpp ================================================ class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { int len = 0; ListNode* head_copy = head; while (head_copy != nullptr) { head_copy = head_copy->next; len++; } if (n == len) { ListNode* new_head = head->next; delete head; return new_head; } head_copy = head; for (int i = 1; i < (len - n); i++) { head_copy = head_copy->next; } ListNode* to_delete = head_copy->next; head_copy->next = head_copy->next->next; delete to_delete; return head; } }; ================================================ FILE: cpp/011-020/Roman to Integer.cpp ================================================ class Solution { public: int romanToInt(string s) { map table { {'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000} }; int result = 0; for (int i = 0;i < s.length();i++) { if (i < s.length()-1 && table[s[i]] < table[s[i+1]] ) { result -= table[s[i]]; } else { result += table[s[i]]; } } return result; } }; ================================================ FILE: cpp/011-020/Valid Parentheses.cpp ================================================ class Solution { public: bool isValid(string s) { stack container; for (int i = 0;i < s.length();i++) { if (container.empty()) container.push(s[i]); else { char c = s[i]; char v = container.top(); if (c == '(' || c == '{' || c == '[') container.push(c); else { if ( (c == ')' && v == '(') || (c == '}' && v == '{') || (c == ']' && v == '[')) container.pop(); else return false; } } } return container.empty(); } }; ================================================ FILE: cpp/021-030/Divide Two Integers.cpp ================================================ /* * Solution 1: * Use long type */ class Solution { public: int divide(int dividend, int divisor) { if (dividend == INT_MIN && divisor == -1) { return INT_MAX; } bool positive = true; if ((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0)) { positive = false; } long new_dividend = abs((long)dividend); long new_divisor = abs((long)divisor); long result = 0; int power = 0; while (new_divisor <= (new_dividend >> 1)) { new_divisor = new_divisor << 1; power++; } while (power >= 0) { if (new_dividend >= new_divisor) { result += (1 << power); new_dividend -= new_divisor; } power--; new_divisor = new_divisor >> 1; } return positive ? result : -result; } }; /* * Solution 2: * Don't use long type */ class Solution { public: int divide(int dividend, int divisor) { if (dividend == INT_MIN) { if (divisor == -1) { return INT_MAX; } if (divisor > 0) { return -1 + divide(dividend + divisor, divisor); } else { return 1 + divide(dividend - divisor, divisor); } } if (divisor == INT_MIN) { return dividend == INT_MIN ? 1 : 0; } bool positive = true; if ((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0)) { positive = false; } int new_dividend = abs(dividend); int new_divisor = abs(divisor); int result = 0; int power = 0; while (new_divisor <= (new_dividend >> 1)) { new_divisor = new_divisor << 1; power++; } while (power >= 0) { if (new_dividend >= new_divisor) { result += (1 << power); new_dividend -= new_divisor; } power--; new_divisor = new_divisor >> 1; } return positive ? result : -result; } }; ================================================ FILE: cpp/021-030/Generate Parentheses.cpp ================================================ class Solution { void dfs(string s, int open, int close, vector& parentheses) { if (close < open) { return; } if (open == 0) { string temp(close, ')'); s += temp; parentheses.push_back(s); } else { dfs(s + "(", open - 1, close, parentheses); dfs(s + ")", open, close - 1, parentheses); } } public: vector generateParenthesis(int n) { vector parentheses; dfs("", n, n, parentheses); return parentheses; } }; ================================================ FILE: cpp/021-030/Implement strStr().cpp ================================================ class Solution { public: int strStr(string haystack, string needle) { int m = haystack.length(), n = needle.length(); for (int i = 0; i < m - n + 1; i++) { int j = 0; for (; j < n; j++) { if (haystack[i + j] != needle[j]) { break; } } if (j == n) { return i; } } return -1; } }; ================================================ FILE: cpp/021-030/Merge Two Sorted Lists.cpp ================================================ class Solution { public: ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { ListNode *head = new ListNode(-1); ListNode *fake_head = head; while (l1 != nullptr || l2 != nullptr) { if (l1 == nullptr) { head->next = l2; break; } else if(l2 == nullptr) { head->next = l1; break; } if (l1->val <= l2->val) { head->next = l1; head = l1; l1 = l1->next; } else { head->next = l2; head = l2; l2 = l2->next; } } return fake_head->next; } }; ================================================ FILE: cpp/021-030/Merge k Sorted Lists.cpp ================================================ class Solution { public: ListNode *mergeKLists(vector &lists) { auto cmp = [] (ListNode *n1, ListNode *n2) { return n1->val > n2->val; }; priority_queue, decltype(cmp)> nodes(cmp); for (ListNode *list : lists) { if (list != nullptr) { nodes.push(list); } } if (nodes.empty()) { return nullptr; } ListNode fake_head(0); ListNode* current = &fake_head; while (!nodes.empty()) { current->next = nodes.top(); current = current->next; nodes.pop(); if (current->next != nullptr) { nodes.push(current->next); } } return fake_head.next; } }; ================================================ FILE: cpp/021-030/Remove Duplicates from Sorted Array.cpp ================================================ class Solution { public: int removeDuplicates(vector& nums) { int pos = 0; for (int n : nums) { if (pos == 0 || n > nums[pos-1]) { nums[pos] = n; pos++; } } return pos; } }; ================================================ FILE: cpp/021-030/Remove Element.cpp ================================================ class Solution { public: int removeElement(vector& nums, int val) { int pos = 0; for (int n : nums) { if (n != val) { nums[pos] = n; pos++; } } return pos; } }; ================================================ FILE: cpp/021-030/Reverse Nodes in k-Group.cpp ================================================ class Solution { int length(ListNode* head) { int len = 0; while (head != nullptr) { head = head->next; len++; } return len; } ListNode* dfs(ListNode* head, int len, int k) { if (len < k) { return head; } ListNode* tail = head; ListNode* prev = nullptr, *tmp = nullptr; for (int i = 0; i < k; i++) { tmp = head->next; head -> next = prev; prev = head; head = tmp; } tail->next = dfs(head, len - k, k); return prev; } public: ListNode* reverseKGroup(ListNode* head, int k) { return dfs(head, length(head), k); } }; ================================================ FILE: cpp/021-030/Substring with Concatenation of All Words.cpp ================================================ class Solution { public: vector findSubstring(string s, vector& words) { vector res; unordered_map dict; int len = words[0].size(); int n = s.length(), m = words.size(); for (const string& word : words) { dict[word]++; } for (int i = 0; i < len; i++) { int cnt = 0; unordered_map copy = dict; for (int j = i; j <= n - len; j += len) { string cur = s.substr(j, len); copy[cur]--; if (copy[cur] >= 0) { cnt++; } int pop_start = j - m * len; if (pop_start >= 0) { string pop_word = s.substr(pop_start, len); copy[pop_word]++; if (copy[pop_word] > 0) { cnt--; } } if (cnt == m) { res.push_back(pop_start + len); } } } return res; } }; ================================================ FILE: cpp/021-030/Swap Nodes in Pairs.cpp ================================================ class Solution { public: ListNode* swapPairs(ListNode* head) { if (head == nullptr || head->next == nullptr) { return head; } ListNode* new_head = head->next; head->next = swapPairs(new_head->next); new_head->next = head; return new_head; } }; ================================================ FILE: cpp/031-040/Combination Sum II.cpp ================================================ #include #include #include #include #include using namespace std; class Solution { void help(vector& now, vector&candidates, int index, int target, vector>& results) { for(int i = index;i < candidates.size();i++) { if(candidates[i] < target) { now.push_back(candidates[i]); help(now, candidates, i+1, target-candidates[i], results); now.pop_back(); while(i < candidates.size()-1 && candidates[i] == candidates[i+1]) i++; } else if(candidates[i] == target) { now.push_back(candidates[i]); results.push_back(now); now.pop_back(); return; } } } public: vector > combinationSum2(vector &candidates, int target) { vector> results; vector tmp; sort(candidates.begin(), candidates.end()); help(tmp, candidates, 0, target, results); return results; } }; int main() { Solution s; return 0; } ================================================ FILE: cpp/031-040/Combination Sum.cpp ================================================ class Solution { void help(vector& now, vector&candidates, int index, int target, vector>& results) { for (int i = index;i < candidates.size();i++) { if (candidates[i] < target) { now.push_back(candidates[i]); help(now, candidates, i, target-candidates[i], results); now.pop_back(); } else if (candidates[i] == target) { now.push_back(candidates[i]); results.push_back(now); now.pop_back(); } } } public: vector > combinationSum(vector &candidates, int target) { vector> results; vectortmp; help(tmp, candidates, 0, target, results); return results; } }; ================================================ FILE: cpp/031-040/Count and Say.cpp ================================================ #include #include #include #include #include using namespace std; class Solution { string process(string &s) { int i = 0; string r; while(i < s.length()) { int l = 1; while(i < s.length()-1 && s[i] == s[i+1]) { l++; i++; } r = r + to_string(l) + s[i]; i++; } return r; } public: string countAndSay(int n) { string r = "1"; if(n == 1) return r; for(int i = 2;i <= n;i++) r = process(r); return r; } }; int main() { Solution s; cout << s.countAndSay(1); return 0; } ================================================ FILE: cpp/031-040/Longest Valid Parentheses.cpp ================================================ // Solution 1: DP class Solution { public: int longestValidParentheses(string s) { int n = s.size(); int res = 0; vector dp(n, 0); for (int i = 0; i < n; i++) { if (i > 0 && s[i] == ')') { if (s[i-1] == '(') { int val = i - 2 >= 0 ? dp[i-2] : 0; dp[i] = 2 + val; } else { int ind = i - dp[i-1] - 1; if (ind >= 0 && s[ind] == '(') { int val = ind > 0 ? dp[ind - 1] : 0; dp[i] = 2 + dp[i-1] + val; } } res = max(res, dp[i]); } } return res; } }; // Solution 2: stack class Solution { public: int longestValidParentheses(string s) { stack mystack; mystack.push(-1); int res = 0; for (int i = 0; i < s.size(); i++) { int t = mystack.top(); if (t != -1 && s[i] == ')' && s[t]=='(') { mystack.pop(); res = max(res, i - mystack.top()); } else { mystack.push(i); } } return res; } }; ================================================ FILE: cpp/031-040/Next Permutation.cpp ================================================ class Solution { public: void nextPermutation(vector &num) { if (num.empty()) { return; } int violation_index = num.size() - 2; for (; violation_index >= 0; violation_index--) { if (num[violation_index] < num[violation_index+1]) { break; } } reverse(begin(num) + violation_index + 1, end(num)); if (violation_index == -1) { return; } auto it = upper_bound(begin(num) + violation_index + 1, num.end(), num[violation_index]); swap(num[violation_index], *it); } }; ================================================ FILE: cpp/031-040/Search Insert Position.cpp ================================================ class Solution { public: int searchInsert(vector& nums, int target) { int lo = 0; int hi = nums.size() - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (target < nums[mid]) hi = mid - 1; else if (target > nums[mid]) lo = mid + 1; else return mid; } return lo; } }; ================================================ FILE: cpp/031-040/Search for a Range.cpp ================================================ class Solution { public: vector searchRange(vector& nums, int target) { std::vector::iterator low,up; low =std::lower_bound (nums.begin(), nums.end(), target); up = std::upper_bound (nums.begin(), nums.end(), target); vector result; if (low == up) { result.push_back(-1); result.push_back(-1); } else { result.push_back(low - nums.begin()); result.push_back(up - nums.begin() - 1); } return result; } }; class Solution { int FindFirst(const vector& nums, int target) { int i = 0; int j = nums.size() - 1; int pos = -1; while (i <= j) { int mid = (i + j) / 2; if (nums[mid] == target) { pos = mid; j = mid - 1; } else if (nums[mid] > target) { j = mid - 1; } else { i = mid + 1; } } return pos; } int FindLast(const vector& nums, int target) { int i = 0; int j = nums.size() - 1; int pos = -1; while (i <= j) { int mid = (i + j) / 2; if (nums[mid] == target) { pos = mid; i = mid + 1; } else if (nums[mid] > target) { j = mid - 1; } else { i = mid + 1; } } return pos; } public: vector searchRange(vector& nums, int target) { vector ans{FindFirst(nums, target), FindLast(nums, target)}; return ans; } }; ================================================ FILE: cpp/031-040/Search in Rotated Sorted Array.cpp ================================================ class Solution { public: int search(vector& nums, int target) { int i = 0; int j = nums.size() - 1; while (i <= j) { int mid = (i + j) / 2; if (nums[mid] == target) return mid; if (nums[mid] < nums[i]) { if (nums[mid] < target && nums[j] >= target) i = mid+1; else j = mid-1; } else { if (nums[mid] > target && nums[i] <= target) j = mid-1; else i = mid+1; } } return -1; } }; ================================================ FILE: cpp/031-040/Sudoku Solver.cpp ================================================ class Solution { bool rows[9][9]; bool cols[9][9]; bool rec[3][3][9]; bool help(vector > &board, int i, int j) { if(i == 9) return true; int nexti(i), nextj(0); if (j != 8) { nextj = j+1; } else { nexti = i+1; } if(board[i][j] != '.') { return help(board, nexti, nextj); } else { for(int k = 0;k < 9;k++) { if(rows[i][k] == false && cols[k][j] == false && rec[i/3][j/3][k] == false) { rows[i][k] = true; cols[k][j] = true; rec[i/3][j/3][k] = true; board[i][j] = (k+'1'); bool t = help(board, nexti, nextj); if(t) return true; rows[i][k] = false; cols[k][j] = false; rec[i/3][j/3][k] = false; board[i][j] = '.'; } } } return false; } public: void solveSudoku(vector > &board) { memset(rows, false, sizeof(rows)); memset(cols, false, sizeof(cols)); memset(rec, false, sizeof(rec)); for (int i = 0;i < 9;i++) { for(int j = 0;j < 9;j++) { if(board[i][j] != '.') { int d = board[i][j] - '1'; rows[i][d] = true; cols[d][j] = true; rec[i/3][j/3][d] = true; } } } help(board, 0, 0); } }; ================================================ FILE: cpp/031-040/Valid Sudoku.cpp ================================================ class Solution { public: bool isValidSudoku(vector > &board) { bool r[9][9], c[9][9], s[3][3][9]; memset(r, false, 9*9); memset(c, false, 9*9); memset(s, false, 3*3*9); for(int i = 0;i < 9;i++) { for(int j = 0;j < 9;j++) { char ch = board[i][j]; if (!isdigit(ch)) continue; int num = ch - '1'; if (r[i][num] == true) return false; r[i][num] = true; if (c[j][num] == true) return false; c[j][num] = true; int ii = i/3; int jj = j/3; if (s[ii][jj][num]) return false; s[ii][jj][num] = true; } } return true; } }; ================================================ FILE: cpp/041-050/First Missing Positive.cpp ================================================ class Solution { public: int firstMissingPositive(vector& nums) { if (nums.empty()) return 1; int i(0); while (i < nums.size()) { if (nums[i] != i+1 && nums[i] > 0 && nums[i] < nums.size() && nums[i] != nums[nums[i]-1]) { swap(nums[i], nums[nums[i]-1]); continue; } i++; } for (int i = 0;i < nums.size();i++) if(nums[i] != i+1) return i+1; return nums.back()+1; } }; ================================================ FILE: cpp/041-050/Group Anagrams.cpp ================================================ class Solution { public: vector> groupAnagrams(vector& strs) { map> mymap; for (const string& str : strs) { string key(str); sort(key.begin(), key.end()); mymap[key].emplace_back(str); } vector> result; for (const auto& it : mymap) result.emplace_back(it.second); return result; } }; ================================================ FILE: cpp/041-050/Jump Game II.cpp ================================================ class Solution { public: int jump(vector& nums) { if (nums.size() < 2) return 0; int count(0); int step(0); int nextstep(0); for (int i = 0; i < nums.size(); i++) { if (i + nums[i] > nextstep) nextstep = i + nums[i]; if (i == step && i != nums.size()-1) { step = nextstep; count++; } } return count; } }; ================================================ FILE: cpp/041-050/Multiply Strings.cpp ================================================ class Solution { public: string multiply(string num1, string num2) { string result(num1.length()+num2.length(), '0'); reverse(num1.begin(), num1.end()); reverse(num2.begin(), num2.end()); for (int i = 0;i < num1.length();i++) { int carry = 0; int j = 0; while (j < num2.size() || carry > 0) { int digit = result[i+j] - '0'; int v = j < num2.size() ? num2[j] : '0'; int num = (num1[i] - '0') * (v - '0'); int res = digit + num + carry; result[i+j] = (res % 10) + '0'; carry = res / 10; j++; } } reverse(result.begin(), result.end()); while(result[0] == '0' && result.length() > 1) result = result.substr(1); return result; } }; ================================================ FILE: cpp/041-050/Permutations II.cpp ================================================ class Solution { void help(vector>& result, int begin, vector num) { if (begin == num.size()) { result.emplace_back(num); return; } for (int i = begin; i < num.size();i++) { if (i != begin && num[i] == num[begin]) continue; swap(num[begin], num[i]); help(result, begin+1, num); } } public: vector > permuteUnique(vector &num) { vector> result; sort(num.begin(), num.end()); help(result, 0, num); return result; } }; ================================================ FILE: cpp/041-050/Permutations.cpp ================================================ class Solution { void help(vector>& result, int begin, vector &num) { if (begin == num.size()) { result.emplace(result.end(), num); return; } for (int i = begin; i < num.size();i++) { swap(num[begin], num[i]); help(result, begin+1, num); swap(num[begin], num[i]); } } public: vector > permute(vector &num) { vector> result; help(result, 0, num); return result; } }; ================================================ FILE: cpp/041-050/Pow.cpp ================================================ class Solution { public: double myPow(double x, int n) { double res = 1.0; double tmp = x; bool sign = (n >= 0); n = abs(n); while (n > 0) { if (n & 1) { res *= tmp; } tmp *= tmp; n = n >> 1; } return sign ? res : 1/res; } }; ================================================ FILE: cpp/041-050/Rotate Image.cpp ================================================ class Solution { public: void rotate(vector > &matrix) { int n = matrix[0].size() -1; for (int i = 0;i <= n - i;i++) { for (int j = i;j <= n - i - 1;j++) { int tmp = matrix[j][n-i]; matrix[j][n-i] = matrix[i][j]; matrix[i][j] = matrix[n-j][i]; matrix[n-j][i] = matrix[n-i][n-j]; matrix[n-i][n-j] = tmp; } } } }; ================================================ FILE: cpp/041-050/Trapping Rain Water.cpp ================================================ class Solution { public: int trap(vector& height) { int i = 0; int j = height.size() - 1; int maxleft = 0, maxright = 0; int res = 0; while(i < j) { if(height[i] <= height[j]) { if (height[i] > maxleft) maxleft = height[i]; else res += (maxleft - height[i]); i++; } else { if (height[j] > maxright) maxright = height[j]; else res += (maxright - height[j]); j--; } } return res; } }; ================================================ FILE: cpp/041-050/Wildcard Matching.cpp ================================================ class Solution { public: bool isMatch(string s, string p) { int i(0),j(0),ss(0),pp(-1); while (i < s.length()) { if(s[i] == p[j] || p[j] == '?') {i++;j++;continue;} else if(p[j] == '*'){ss = i;pp = ++j;continue;} else if(pp != -1) {i = ++ss;j = pp;continue;} return false; } while (j < p.length()) if(p[j++] != '*') return false; return true; } }; ================================================ FILE: cpp/051-060/Insert Interval.cpp ================================================ class Solution { vector merge(vector &intervals) { if(intervals.size() < 2) return intervals; auto comp = [&](Interval m,Interval n) { return m.start < n.start; }; vector result; sort(intervals.begin(), intervals.end(), comp); Interval now = intervals[0]; for(int i = 1;i < intervals.size();i++) { Interval then = intervals[i]; if(now.end >= then.start) { now.end = max(now.end, then.end); } else { result.push_back(now); now = then; } } result.push_back(now); return result; } public: vector insert(vector &intervals, Interval newInterval) { intervals.push_back(newInterval); return merge(intervals); } }; ================================================ FILE: cpp/051-060/Jump Game.cpp ================================================ class Solution { public: bool canJump(vector& nums) { int maxpos(0); for (int i = 0; i < nums.size(); i++) { if (i <= maxpos) { int tmp = i + nums[i]; if(tmp >= (nums.size()-1)) return true; maxpos = max(tmp, maxpos); } else return false; } return false; } }; ================================================ FILE: cpp/051-060/Length of Last Word.cpp ================================================ class Solution { public: int lengthOfLastWord(string s) { int len = 0, tail = s.length() - 1; while (tail >= 0 && s[tail] == ' ') tail--; while (tail >= 0 && s[tail] != ' ') { len++; tail--; } return len; } }; ================================================ FILE: cpp/051-060/Maximum_Subarray.cpp ================================================ /************************************************************************* > File Name: Maximum_Subarray.cpp > Author: Louis1992 > Mail: zhenchaogan@gmail.com > Blog: http://gzc.github.io > Created Time: Sat Apr 18 19:14:47 2015 ************************************************************************/ #include #include #include #include #include #include #include #include #include #include #include using namespace std; class Solution { public: int maxSubArray(std::vector& A) { int n = A.size(); int a1(0), a2(0); int m = INT_MIN; for(int i = 0;i < n;i++) { if(i == 0) a2 = A[i]; else if (a1 < 0) a2 = A[i]; else a2 = A[i]+a1; m = max(m,a2); a1 = a2; } return m; } }; int main() { Solution s; return 0; } ================================================ FILE: cpp/051-060/Merge Intervals.cpp ================================================ class Solution { public: vector> merge(vector> &intervals) { auto comp = [](const vector& m, const vector& n) { return m[0] < n[0]; }; sort(intervals.begin(), intervals.end(), comp); vector now = intervals[0]; vector> result; for (int i = 1;i < intervals.size();i++) { const vector& then = intervals[i]; if (now[1] >= then[0]) { now[1] = max(now[1], then[1]); } else { result.push_back(now); now = then; } } result.push_back(now); return result; } }; ================================================ FILE: cpp/051-060/N-Queens II.cpp ================================================ class Solution { bool *cols; bool *add; bool *diff; int n; bool valid(int i, int j) { if (!cols[j] && !add[i+j] && !diff[i-j+n]) return true; return false; } void help(int i, int &res) { if (i == n) { res++; return; } for (int j = 0;j < n;j++) { if(valid(i, j)) { cols[j] = add[i+j] = diff[i-j+n] = true; help(i+1, res); cols[j] = add[i+j] = diff[i-j+n] = false; } } } public: int totalNQueens(int n) { cols = new bool[n]; add = new bool[2*n]; diff = new bool[2*n]; memset(cols, 0, n); memset(add, 0, 2*n); memset(diff, 0, 2*n); this->n = n; int res = 0; help(0, res); return res; } }; ================================================ FILE: cpp/051-060/N-Queens.cpp ================================================ class Solution { bool *cols; bool *add; bool *diff; int n; bool valid(int i, int j) { if(!cols[j] && !add[i+j] && !diff[i-j+n]) return true; return false; } void help(vector> &result, vector> &tmp, int i) { if(i == n) { string s(n, '.'); vectort{n,s}; for(int k = 0;k < tmp.size();k++) t[tmp[k].first][tmp[k].second] = 'Q'; result.push_back(t); return; } for(int j = 0;j < n;j++) { if(valid(i, j)) { cols[j] = add[i+j] = diff[i-j+n] = true; tmp.push_back(make_pair(i, j)); help(result, tmp, i+1); tmp.pop_back(); cols[j] = add[i+j] = diff[i-j+n] = false; } } } public: vector > solveNQueens(int n) { cols = new bool[n]; add = new bool[2*n]; diff = new bool[2*n]; this->n = n; vector> result; vector> tmp; help(result, tmp, 0); return result; } }; ================================================ FILE: cpp/051-060/Permutation Sequence.cpp ================================================ class Solution { public: string getPermutation(int n, int k) { int pTable[10] = {1}; for (int i = 1; i <= 9; i++) { pTable[i] = i * pTable[i - 1]; } string result; char a[] = {'1','2','3','4','5','6','7','8','9'}; vector numSet(a, a+9); while (n > 0) { int temp = (k - 1) / pTable[n - 1]; result += numSet[temp]; numSet.erase(numSet.begin() + temp); k = k - temp * pTable[n - 1]; n--; } return result; } }; ================================================ FILE: cpp/051-060/Spiral Matrix II.cpp ================================================ #include #include #include #include #include using namespace std; class Solution { public: vector > generateMatrix(int n) { vector > result(n ,vector(n)); if(n == 0) return result; int h = n; int w = n; int step = 1; int i(0),j(0); int z = 1; while(w > 0 && h > 0) { for(int k = 0;k < w;k++) { result[i][j] = z++; j += step; } j -= step; i += step; h--; for(int k = 0;k < h;k++) { result[i][j] = z++; i += step; } i -= step; step *= -1; j += step; w--; } return result; } }; int main() { Solution s; return 0; } ================================================ FILE: cpp/051-060/Spiral Matrix.cpp ================================================ #include #include #include #include #include using namespace std; class Solution { public: vector spiralOrder(vector > &matrix) { vectorresult; if(matrix.size() == 0) return result; int h = matrix.size(); int w = matrix[0].size(); int step = 1; int i(0),j(0); while(w > 0 && h > 0) { for(int k = 0;k < w;k++) { result.push_back(matrix[i][j]); j += step; } j -= step; i += step; h--; for(int k = 0;k < h;k++) { result.push_back(matrix[i][j]); i += step; } i -= step; step *= -1; j += step; w--; } return result; } }; int main() { Solution s; return 0; } ================================================ FILE: cpp/061-070/Add Binary.cpp ================================================ class Solution { public: string addBinary(string a, string b) { string result; int carry = 0; int i1 = a.length() - 1; int i2 = b.length() - 1; while (i1 >= 0 || i2 >= 0 || carry > 0) { int v1 = i1 >= 0 ? a[i1] - '0' : 0; int v2 = i2 >= 0 ? b[i2] - '0' : 0; int sum = v1 + v2 + carry; result.push_back((sum & 1) + '0'); carry = (sum >> 1) & 1; i1--; i2--; } reverse(begin(result), end(result)); return result; } }; ================================================ FILE: cpp/061-070/Climbing Stairs.cpp ================================================ class Solution { public: int climbStairs(int n) { vector dp(n, 0); dp[0] = 1; dp[1] = 2; for (int i =2;i < n;i++) { dp[i] = dp[i-1]+dp[i-2]; } return dp[n-1]; } }; ================================================ FILE: cpp/061-070/Minimum Path Sum .cpp ================================================ public: int minPathSum(vector > &grid) { int n = grid.size(); int m = grid[0].size(); int p[n][m]; p[0][0] = grid[0][0]; for(int k = 1;k < n;k++) p[k][0] = p[k-1][0]+grid[k][0]; for(int k = 1;k < m;k++) p[0][k] = p[0][k-1]+grid[0][k]; for(int i = 1;i < n;i++) for(int j = 1;j < m;j++) p[i][j] = min(p[i-1][j], p[i][j-1]) + grid[i][j]; return p[n-1][m-1]; } }; ================================================ FILE: cpp/061-070/Plus One.cpp ================================================ class Solution { public: vector plusOne(vector& digits) { int carry(1); for (int i = digits.size()-1; i >= 0; i--) { int tmp = digits[i] + carry; carry = tmp/10; digits[i] = tmp%10; } if (carry) digits.emplace(digits.begin(), 1); return digits; } }; ================================================ FILE: cpp/061-070/Rotate List.cpp ================================================ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *rotateRight(ListNode *head, int k) { if(!head || !head->next || !k) return head; int len = 1; ListNode *tail(head), *head2(head); while (tail && tail->next) { len++; tail = tail->next; } k = k % len; if(!k) return head; int n = len-k; while(--n) head2 = head2->next; ListNode *tmp = head2->next; head2->next = nullptr; head2 = tmp; tail->next = head; return head2; } }; ================================================ FILE: cpp/061-070/Sqrt.cpp ================================================ class Solution { public: int mySqrt(int x) { if (x == 0) return 0; int left(1), right(x); while (true) { int mid = left + (right - left)/2; if (mid > x/mid) { right = mid - 1; } else { if (mid + 1 > x/(mid + 1)) return mid; left = mid + 1; } } return -1; } }; class Solution { public: int mySqrt(int x) { if (x == 0) return 0; int left = 1, right = x/2; while (left < right) { int mid = left + (right - left)/2; if ((long)mid * (long)mid <= (long)x && (long)(mid+1)*(long)(mid+1) > (long)x) { return mid; } else if ((long)mid * (long)mid > (long)x) { right = mid - 1; } else { left = mid + 1; } } return left; } }; ================================================ FILE: cpp/061-070/Text Justification.cpp ================================================ class Solution { vector help(vector &words, int start, int end, int L) { int wordCount = end - start; if(words.size() == end) return vector(wordCount-1,1); int sum = L; for(int i = start;i < end;i++) sum -= words[i].length(); int Count = wordCount - 1; int average = sum / Count; vector blocks(wordCount-1, average); sum -= average * Count; int index = 0; while(sum--) blocks[index++]++; return blocks; } public: vector fullJustify(vector &words, int L) { vector result; if(words.size() == 0) return result; int from = 0; while(from < words.size()) { string temp(L, ' '); int start = from; int len = words[from].length(); while(len <= L && from < words.size()){ from ++; if(from == words.size()) break; len = len + words[from].length() + 1; } if(from - start == 1){ for(int n = 0;n < words[start].length();n++) temp[n] = words[start][n]; } else { vector blocks = help(words, start, from, L); int index = 0; int skip = 0; for(int i = start;i < from;i++) { string now = words[i]; for(int j = 0;j < now.length();j++) temp[index++] = now[j]; index += blocks[skip++]; } } result.push_back(temp); } return result; } }; ================================================ FILE: cpp/061-070/Unique Paths II .cpp ================================================ class Solution { public: int uniquePathsWithObstacles(vector > &obstacleGrid) { int m(obstacleGrid.size()), n(obstacleGrid[0].size()); vector> dp(m+1,vector(n+1,0)); if(obstacleGrid[0][0] == 1 || obstacleGrid[m-1][n-1] == 1) return 0; dp[1][1] = 1; for(int i = 1;i <= m;i++) { for(int j = 1;j <= n;j++) { if(i == 1 && j == 1) continue; if(obstacleGrid[i-1][j-1] == 1) dp[i][j] = 0; else dp[i][j] = dp[i-1][j] + dp[i][j-1]; } } return dp[m][n]; } }; ================================================ FILE: cpp/061-070/Unique Paths.cpp ================================================ class Solution { public: int uniquePaths(int m, int n) { vector > path(m, vector (n, 1)); for (int i = 1; i < m; i++) for (int j = 1; j < n; j++) path[i][j] = path[i - 1][j] + path[i][j - 1]; return path[m - 1][n - 1]; } }; ================================================ FILE: cpp/061-070/Valid Number.cpp ================================================ class Solution { public: bool isNumber(string str) { int state=0, flag=0; // flag to judge the special case "." while(str[0]==' ') str.erase(0,1);//delete the prefix whitespace while(str[str.length()-1]==' ') str.erase(str.length()-1, 1);//delete the suffix whitespace for(int i=0; i&tmp, vector>&v) { if(k == 0) { v.push_back(tmp); return; } else if(index > n) return; help(n,k,index+1,tmp,v); tmp.push_back(index); help(n,k-1,index+1,tmp,v); tmp.pop_back(); } public: vector > combine(int n, int k) { vector>v; vectortmp; help(n,k,1,tmp,v); return v; } }; ================================================ FILE: cpp/071-080/Edit Distance.cpp ================================================ class Solution { public: int minDistance(string word1, string word2) { int m = word1.length(); int n = word2.length(); vector> p(m+1, vector(n+1)); for (int i = 0;i <= m;i++) p[i][0] = i; for (int j = 0;j <= n;j++) p[0][j] = j; for (int i = 1;i <= m;i++) { for (int j = 1;j <= n;j++) { if (word1[i-1] == word2[j-1]) { p[i][j] = p[i-1][j-1]; } else { p[i][j] = min(1 + p[i-1][j-1], 1+min(p[i][j-1], p[i-1][j])); } } } return p[m][n]; } }; ================================================ FILE: cpp/071-080/Minimum Window Substring.cpp ================================================ class Solution { public: string minWindow(string s, string t) { unordered_map dict; int cnt = 0, start = 0, len = INT_MAX, first = 0; for (char c : t) { dict[c]++; } for (int i = 0; i < s.size(); i++) { dict[s[i]]--; if (dict[s[i]] >= 0) { cnt++; } while (cnt == t.size()) { dict[s[start]]++; if (dict[s[start]] > 0) { cnt--; } if (i - start + 1 < len) { len = i - start + 1; first = start; } start++; } } return len == INT_MAX ? "" : s.substr(first, len); } }; ================================================ FILE: cpp/071-080/Remove Duplicates from Sorted Array II.cpp ================================================ class Solution { public: int removeDuplicates(vector& nums) { int rear(1), n(nums.size()); if (n <= 2) return n; for (int i = 2; i < n; i++) if (!(nums[i] == nums[rear] && nums[i] == nums[rear -1])) nums[++rear] = nums[i]; return rear+1; } }; ================================================ FILE: cpp/071-080/Search a 2D Matrix.cpp ================================================ class Solution { public: bool searchMatrix(vector > &matrix, int target) { int row(matrix.size()), col(matrix[0].size()); int i(0), j(row*col-1); while (i <= j) { int mid = (i+j) >> 1; int v = matrix[mid/col][mid%col]; if (target < v) j = mid - 1; else if (target > v) i = mid + 1; else if (target == v) return true; } return false; } }; ================================================ FILE: cpp/071-080/Set Matrix Zeroes.cpp ================================================ class Solution { public: void setZeroes(vector > &matrix) { bool col0 = false; int outer = matrix.size(); int inner = matrix[0].size(); for (int i = 0; i < outer; i++) { if (matrix[i][0] == 0) col0 = true; for (int j = 1; j < inner; j++) { if (matrix[i][j] == 0) { matrix[i][0] = 0; matrix[0][j] = 0; } } } for (int i = outer-1; i >= 0; i--) { for (int j = inner-1; j >= 1; j--) { if (matrix[i][0] == 0 || matrix[0][j] == 0) { matrix[i][j] = 0; } } if(col0) matrix[i][0] = 0; } } }; ================================================ FILE: cpp/071-080/Simplify Path.cpp ================================================ class Solution { public: string simplifyPath(string path) { string res, tmp; vector stk; stringstream ss(path); while(getline(ss,tmp,'/')) { if (tmp == "" or tmp == ".") continue; if (tmp == ".." and !stk.empty()) stk.pop_back(); else if (tmp != "..") stk.push_back(tmp); } for(auto str : stk) res += "/"+str; return res.empty() ? "/" : res; } }; ================================================ FILE: cpp/071-080/Sort Colors.cpp ================================================ class Solution { public: void sortColors(vector& nums) { int i = 0, j = 0; for (int r = 0; r < nums.size(); r++) { if (nums[r] == 0) { swap(nums[j], nums[r]); swap(nums[i], nums[j]); i++; j++; } else if (nums[r] == 1) { swap(nums[r], nums[j]); j++; } } } }; ================================================ FILE: cpp/071-080/Subsets.cpp ================================================ class Solution { public: vector > subsets(vector &S) { sort(S.begin(),S.end()); vector> sets; vector empty; sets.push_back(empty); int num = 1; for(int i = 0;i < S.size();i++) { for(int k = 0;k < num;k++) { vector tmp = sets[k]; tmp.push_back(S[i]); sets.push_back(tmp); } num *= 2; } return sets; } }; ================================================ FILE: cpp/071-080/Word Search.cpp ================================================ class Solution { public: bool dfs(vector>& board, const string &word, int i, int j, int ind) { if (ind == word.size()) { return true; } if (i >= board.size() || j >= board[0].size() || i < 0 || j < 0) return false; if (board[i][j] == 0 || board[i][j] != word[ind]) return false; board[i][j] = 0; if (dfs(board, word, i+1, j, ind + 1)) return true; if (dfs(board, word, i, j+1, ind + 1)) return true; if (dfs(board, word, i-1, j, ind + 1)) return true; if (dfs(board, word, i, j-1, ind + 1)) return true; board[i][j] = word[ind]; return false; } bool exist(vector>& board, string word) { int m = board.size(); if (m == 0) return false; int n = board[0].size(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (dfs(board, word, i, j, 0)) return true; } } return false; } }; ================================================ FILE: cpp/081-090/Gray Code.cpp ================================================ class Solution { public: vector grayCode(int n) { vector v{0}; for (int i = 0; i < n; i++) { int len = v.size(); for (int j = len-1; j >= 0; j--) v.push_back(v[j] | (1 << i) ); } return v; } }; ================================================ FILE: cpp/081-090/Largest Rectangle in Histogram.cpp ================================================ class Solution { public: int largestRectangleArea(vector &hist) { int res(0); stack s; hist.push_back(0); for (int i = 0;i < hist.size();i++) { while (!s.empty() && hist[i] < hist[s.top()]) { int tp = s.top(); int h = hist[tp]; s.pop(); int tmp = h * (s.empty() ? i : i-s.top()-1); res = max(res, tmp); } s.push(i); } return res; } }; ================================================ FILE: cpp/081-090/Maximal Rectangle.cpp ================================================ class Solution { public: int maximalRectangle(vector>& matrix) { if (matrix.size() <= 0) return 0; int h[matrix[0].size()+1]; memset(h, 0, sizeof(int) * (matrix[0].size()+1)); int res(0); for (int i = 0;i < matrix.size();i++) { stack s; matrix[i].push_back('0'); for (int j = 0;j < matrix[0].size();j++) { if (matrix[i][j] == '0') h[j] = 0; else h[j]++; while (!s.empty() && h[j] < h[s.top()]) { int tp = s.top(); s.pop(); int height = h[tp]; int tmp = height * (s.empty() ? j : j - s.top() - 1); res = max(res, tmp); } s.push(j); } } return res; } }; ================================================ FILE: cpp/081-090/Merge Sorted Array.cpp ================================================ class Solution { public: void merge(vector& nums1, int m, vector& nums2, int n) { int i = m - 1; int j = n - 1; int k = m + n - 1; while (i >= 0 && j >= 0) { if (nums1[i] >= nums2[j]) { nums1[k] = nums1[i]; i--; } else { nums1[k] = nums2[j]; j--; } k--; } while (i >= 0) { nums1[k] = nums1[i]; k--; i--; } while (j >= 0) { nums1[k] = nums2[j]; k--; j--; } } }; ================================================ FILE: cpp/081-090/Partition List.cpp ================================================ class Solution { public: ListNode *partition(ListNode *head, int x) { ListNode *head1 = new ListNode(0); ListNode *head2 = new ListNode(0); ListNode *h1 = head1; ListNode *h2 = head2; while(head) { int v = head->val; if(v < x) { head1->next = head; head1 = head1->next; } else { head2->next = head; head2 = head2->next; } head = head->next; } head2->next = NULL; head1->next = h2->next;; return h1->next; } }; ================================================ FILE: cpp/081-090/Remove Duplicates from Sorted List II.cpp ================================================ #include #include #include #include #include #include using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *deleteDuplicates(ListNode *head) { ListNode *result = new ListNode(INT_MIN); ListNode *_head = result; int prev(INT_MIN); while(head) { if(head->val != prev && ( (!head->next) || head->val != head->next->val) ) { _head->next = head; _head = head; } prev = head->val; head = head->next; } _head->next = NULL; return result->next; } }; int main() { Solution s; ListNode *n1 = new ListNode(1); ListNode *n2 = new ListNode(2); ListNode *n3 = new ListNode(2); n1->next = n2; n2->next = n3; ListNode *head = s.deleteDuplicates(n1); while(head) { cout << head->val << " "; head = head->next; } } ================================================ FILE: cpp/081-090/Remove Duplicates from Sorted List.cpp ================================================ #include #include #include #include #include #include using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* deleteDuplicates(ListNode* head) { ListNode *node(head); while(node && node->next) { if (node->val == node->next->val) node->next = node->next->next; else node = node->next; } return head; } }; int main() { Solution s; ListNode *n1 = new ListNode(1); ListNode *n2 = new ListNode(2); ListNode *n3 = new ListNode(2); n1->next = n2; n2->next = n3; ListNode *head = s.deleteDuplicates(n1); while(head) { cout << head->val << " "; head = head->next; } } ================================================ FILE: cpp/081-090/Scramble String.cpp ================================================ class Solution { public: bool isScramble(string s1, string s2) { // Note: The Solution object is instantiated only once. if (s1.length() != s2.length()) return false; if (s1 == s2) return true; int A[26] = {0}; for (int i = 0; i < s1.length(); i++) ++A[s1[i]-'a']; for (int j = 0; j < s2.length(); j++) --A[s2[j]-'a']; for (int k = 0; k < 26; k++) if(A[k] != 0) return false; for(int i = 1; i < s1.length(); i++) { bool result = isScramble(s1.substr(0,i), s2.substr(0,i)) && isScramble(s1.substr(i), s2.substr(i)); result = result || (isScramble(s1.substr(0,i), s2.substr(s2.length()-i, i)) && isScramble(s1.substr(i), s2.substr(0,s2.length()-i))); if (result) return true; } return false; } }; ================================================ FILE: cpp/081-090/Search in Rotated Sorted Array II.cpp ================================================ class Solution { public: bool search(vector& nums, int target) { int i = 0; int j = nums.size() - 1; while (i <= j) { int mid = (i + j) / 2; if (nums[mid] == target) return true; if (nums[mid] < nums[i]) { if (nums[mid] < target && nums[j] >= target) i = mid + 1; else j = mid - 1; } else if (nums[mid] > nums[i]) { if (nums[mid] > target && nums[i] <= target) j = mid - 1; else i = mid + 1; } else { i++; } } return false; } }; ================================================ FILE: cpp/081-090/Subsets II.cpp ================================================ class Solution { public: vector> subsetsWithDup(vector& nums) { sort(nums.begin(), nums.end()); vector> sets; vector empty; sets.push_back(empty); int num = 1; int prev(INT_MIN); for(int i = 0;i < nums.size();i++) { int number = nums[i]; if(number != prev) { num = sets.size(); for(int k = 0;k < num;k++) { vector tmp = sets[k]; tmp.push_back(number); sets.push_back(tmp); } prev = number; } else { int index = sets.size()-num; for(int k = 0;k < num;k++) { vector tmp = sets[k+index]; tmp.push_back(number); sets.push_back(tmp); } } } return sets; } }; ================================================ FILE: cpp/091-100/Binary Tree Inorder Traversal.cpp ================================================ class Solution { public: vector inorderTraversal(TreeNode* root) { vector result; stack node_in_path; TreeNode* current_node = root; while (current_node || !node_in_path.empty()) { while (current_node) { node_in_path.emplace(current_node); current_node = current_node->left; } current_node = node_in_path.top(); node_in_path.pop(); result.push_back(current_node->val); current_node = current_node->right; } return result; } }; ================================================ FILE: cpp/091-100/Decode Ways.cpp ================================================ class Solution { bool valid(char ch1, char ch2) { if(ch1 == '1') return true; else if(ch1 == '2') { if(ch2 <= '6') return true; return false; } return false; } public: int numDecodings(string s) { int n = s.length(); if(n == 0) return 0; int *p = new int[n+1]; p[0] = 1; p[1] = 1; if(s[0] == '0') p[1] = 0; for(int i = 0;i < n-1;i++) { if(s[i+1] == '0') { if (s[i] >= '1' && s[i] <= '2') p[i+2] = p[i]; else p[i+2] = 0; } else if(s[i] == '0') { p[i+2] = p[i+1]; } else if(valid(s[i], s[i+1])) p[i+2] = p[i]+p[i+1]; else p[i+2] = p[i+1]; } return p[n]; } }; ================================================ FILE: cpp/091-100/Interleaving String.cpp ================================================ class Solution { public: bool isInterleave(string s1, string s2, string s3) { if(s1.length() + s2.length() != s3.length()) return false; bool table[s1.length()+1][s2.length()+1]; for(int i = 0;i <= s1.length();i++) for(int j = 0;j <= s2.length();j++) table[i][j] = false; table[0][0] = true; for(int i = 1;i <= s1.length();i++) if(s3[i-1] == s1[i-1] && table[i-1][0]) table[i][0] = true; for(int j = 1;j <= s2.length();j++) if(s3[j-1] == s2[j-1] && table[0][j-1]) table[0][j] = true; for(int i = 1;i <= s1.length();i++) { for(int j = 1;j <= s2.length();j++) { if(s3[i+j-1] == s1[i-1] && table[i-1][j] == true) table[i][j] = true; if(s3[i+j-1] == s2[j-1] && table[i][j-1] == true) table[i][j] = true; } } return table[s1.length()][s2.length()]; } }; ================================================ FILE: cpp/091-100/Recover Binary Search Tree.cpp ================================================ class Solution { public: void recoverTree(TreeNode* root) { stacks; TreeNode *p = root; TreeNode *prev(nullptr); bool fff(false); TreeNode *n1(nullptr), *n2(nullptr); while (p || !s.empty()) { while (p) { s.push(p); p = p->left; } p = s.top(); s.pop(); if (prev && prev->val > p->val) { n2 = p; if (!fff){ fff = true; n1 = prev; } else { swap(n1->val, n2->val); return; } } prev = p; p = p->right; } swap(n1->val, n2->val); } }; ================================================ FILE: cpp/091-100/Restore IP Addresses.cpp ================================================ class Solution { public: vector restoreIpAddresses(string s) { vector ret; string ans; for (int a=1; a<=3; a++) for (int b=1; b<=3; b++) for (int c=1; c<=3; c++) for (int d=1; d<=3; d++) if (a+b+c+d == s.length()) { int A = stoi(s.substr(0, a)); int B = stoi(s.substr(a, b)); int C = stoi(s.substr(a+b, c)); int D = stoi(s.substr(a+b+c, d)); if (A <= 255 && B <= 255 && C <= 255 && D <= 255) // 000000 => false if ( (ans=to_string(A)+"."+to_string(B)+"."+to_string(C)+"."+to_string(D)).length() == s.length()+3) ret.push_back(ans); } return ret; } }; ================================================ FILE: cpp/091-100/Reverse Linked List II.cpp ================================================ class Solution { public: ListNode *reverseBetween(ListNode *head, int m, int n) { int d = n - m; if(m == n) return head; int ttt = m; ListNode *answer = new ListNode(0); answer->next = head; while(--m > 1) head = head->next; ListNode *left = ttt == 1 ? answer : head; ListNode *r_head = left->next; head = r_head; ListNode *tmp = head->next; while(d-- > 0) { ListNode *n = tmp->next; tmp -> next = head; head = tmp; tmp = n; } left->next = head; r_head->next = tmp; return answer->next; } }; ================================================ FILE: cpp/091-100/Same Tree.cpp ================================================ class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { if (p == nullptr && q == nullptr) return true; if ( (p && !q) || (q && !p) ) return false; if (p->val != q->val) return false; return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); } }; ================================================ FILE: cpp/091-100/Unique Binary Search Trees II.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { vector generate(int beg, int end) { vector ret; if (beg > end) { ret.push_back(nullptr); return ret; } for (int i = beg; i <= end; i++) { vector leftTree = generate(beg, i - 1); vector rightTree = generate(i + 1, end); for (int j = 0; j < leftTree.size(); j++) { for (int k = 0; k < rightTree.size(); k++) { TreeNode *node = new TreeNode(i); ret.push_back(node); node->left = leftTree[j]; node->right = rightTree[k]; } } } return ret; } public: vector generateTrees(int n) { if (n == 0) return vector(); return generate(1, n); } }; ================================================ FILE: cpp/091-100/Unique Binary Search Trees.cpp ================================================ class Solution { public: int numTrees(int n) { vector dp(n+1, 0); dp[0] = dp[1] = 1; for (int i = 2;i <= n;i++) for (int k = 0;k < n;k++) dp[i] += dp[k]*dp[i-k-1]; return dp[n]; } }; ================================================ FILE: cpp/091-100/Validate Binary Search Tree.cpp ================================================ class Solution { public: bool isValidBST(TreeNode* root) { stacks; TreeNode *p = root; int prev(INT_MIN); bool first(true); while (p!= nullptr || !s.empty()) { while (p != nullptr) { s.push(p); p = p->left; } p = s.top(); s.pop(); if (first) { prev = p->val; first = false; } else if (p->val <= prev) { return false; } prev = p->val; p = p->right; } return true; } }; ================================================ FILE: cpp/1001-10000/1001-1010/Construct Binary Search Tree from Preorder Traversal.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { TreeNode* dfs(int& i, vector& preorder, int lower, int upper) { if (i >= preorder.size()) return nullptr; int v = preorder[i]; if (v < lower || v > upper) return nullptr; TreeNode* root = new TreeNode(v); i++; root->left = dfs(i, preorder, lower, v); root->right = dfs(i, preorder, v, upper); return root; } public: TreeNode* bstFromPreorder(vector& preorder) { int i = 0; return dfs(i, preorder, -99999999, 99999999); } }; ================================================ FILE: cpp/1001-10000/1011-1020/Best Sightseeing Pair.cpp ================================================ class Solution { public: int maxScoreSightseeingPair(vector& A) { int best_i = 0; int ans = 0; for (int i = 1; i < A.size(); i++) { ans = max(ans, A[best_i] + A[i] + best_i - i); if (i + A[i] >= best_i + A[best_i]) { best_i = i; } } return ans; } }; ================================================ FILE: cpp/1001-10000/1011-1020/Binary Prefix Divisible By 5.cpp ================================================ class Solution { public: vector prefixesDivBy5(vector& A) { vector answer(A.size()); int v = 0; int i = 0; for (int e : A) { v = 2*v + e; v %= 5; answer[i] = v == 0; i++; } return answer; } }; ================================================ FILE: cpp/1001-10000/1011-1020/Binary String With Substrings Representing 1 To N.cpp ================================================ class Solution { public: bool queryString(string S, int N) { for (int i = N; i >= 1; i--) { int number = i; string str_num = ""; // Convert the number to string while(number!=0) { str_num += number%2 + '0'; number = number/2; } reverse(str_num.begin(), str_num.end()); if(S.find(str_num)==string::npos) return false; } return true; } }; ================================================ FILE: cpp/1001-10000/1011-1020/Convert to Base -2.cpp ================================================ class Solution { public: string baseNeg2(int N) { if (N == 0) return "0"; string ans; while(N != 0) { if (N % 2 != 0) { ans = '1' + ans; N--; } else { ans = '0' + ans; } N = -(N/2); } return ans; } }; ================================================ FILE: cpp/1001-10000/1011-1020/Next Greater Node In Linked List.cpp ================================================ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: vector nextLargerNodes(ListNode* head) { int current_index = 0; vector ans(10001, 0); stack> mystack; while (head) { while (!mystack.empty() && mystack.top().second < head->val) { pair e = mystack.top(); mystack.pop(); ans[e.first] = head->val; } mystack.push({current_index, head->val}); head = head->next; current_index++; } ans.resize(current_index); return ans; } }; ================================================ FILE: cpp/1001-10000/1011-1020/Number of Enclaves.cpp ================================================ class Solution { pair tmp[4] = {{1,0}, {-1,0}, {0,1}, {0,-1}}; int m; int n; void dfs(vector>& A, int i, int j) { if (A[i][j] == 0) return; A[i][j] = 2; for (int k = 0; k < 4; k++) { int n_i = i + tmp[k].first; int n_j = j + tmp[k].second; if (n_i < 0 || n_j < 0 || n_i >= m || n_j >= n) continue; if (A[n_i][n_j] == 1) dfs(A, n_i, n_j); } } public: int numEnclaves(vector>& A) { m = A.size(); n = A.front().size(); for (int i = 0; i < m; i++) { dfs(A, i, 0); dfs(A, i, n-1); } for (int j = 0; j < n; j++) { dfs(A, 0, j); dfs(A, m-1, j); } int ans = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (A[i][j] == 1) { ans++; } } } return ans; } }; ================================================ FILE: cpp/1001-10000/1011-1020/Partition Array Into Three Parts With Equal Sum.cpp ================================================ class Solution { public: bool canThreePartsEqualSum(vector& A) { int target = std::accumulate(A.begin(), A.end(), 0) / 3; int sum = 0; int times = 0; for (int e : A) { sum += e; if (sum == target) { times++; sum = 0; } } return times >= 3; } }; ================================================ FILE: cpp/1001-10000/1021-1030/Camelcase Matching.cpp ================================================ class Solution { public: vector camelMatch(vector& queries, string pattern) { vector ans; for (const string& query : queries) { int i = 0; bool find = true; for (int j = 0; j < query.length(); j++) { if (i >= pattern.size()) { if (isupper(query[j])) { find = false; break; } continue; } char target = pattern[i]; if (target == query[j]) { i++; } else if (isupper(query[j])) { find = false; break; } } find &= i >= pattern.size(); ans.push_back(find); } return ans; } }; ================================================ FILE: cpp/1001-10000/1021-1030/Divisor Game.cpp ================================================ class Solution { map dp; public: bool divisorGame(int N) { if (N == 0) return false; if (dp.count(N) > 0) return dp[N]; for (int i = 1; i < N; i++) { if (N % i == 0) { bool win = !divisorGame(N - i); if (win) { return dp[N] = win; } } } return dp[N] = false; } }; ================================================ FILE: cpp/1001-10000/1021-1030/Longest Arithmetic Sequence.cpp ================================================ class Solution { public: int longestArithSeqLength(vector& A) { unordered_map dp; int ans = 0; for (int i = 0; i < A.size(); i++) { for (int j = 0; j < i; j++) { int d = A[i] - A[j]; int key1 = i * 20001 + d; int key2 = j * 20001 + d; dp[key1] = max(dp[key1], 1 + dp[key2]); ans = max(ans, dp[key1]); } } return ans + 1; } }; ================================================ FILE: cpp/1001-10000/1021-1030/Matrix Cells in Distance Order.cpp ================================================ class Solution { public: vector> allCellsDistOrder(int R, int C, int r0, int c0) { vector> myqueue; myqueue.push_back({r0, c0}); int i = 0; int dis = 0; pair tmp[4] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; while (i < myqueue.size()) { int next_i = myqueue.size(); dis++; unordered_set visited; for (int k = i; k < next_i; k++) { int x = myqueue[k][0]; int y = myqueue[k][1]; for (int j = 0; j < 4; j++) { int n_x = x + tmp[j].first; int n_y = y + tmp[j].second; if (n_x < 0 || n_y < 0 || n_x >= R || n_y >= C) continue; int d = abs(r0 - n_x) + abs(c0 - n_y); if (dis != d) continue; int hash_ = n_x * 101 + n_y; if (visited.count(hash_) > 0) continue; myqueue.push_back({n_x, n_y}); visited.insert(hash_); } } i = next_i; } return myqueue; } }; ================================================ FILE: cpp/1001-10000/1021-1030/Maximum Difference Between Node and Ancestor.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { int dfs(TreeNode* root, int min_, int max_) { if (!root) return 0; int current = max(abs(min_ - root->val), abs(max_ - root->val)); min_ = min(min_, root->val); max_ = max(max_, root->val); return max(current, max(dfs(root->left, min_, max_), dfs(root->right, min_, max_))); } public: int maxAncestorDiff(TreeNode* root) { return dfs(root, root->val, root->val); } }; ================================================ FILE: cpp/1001-10000/1021-1030/Recover a Tree From Preorder Traversal.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { TreeNode* dfs(const string& S, int& i, int d) { int dash_count = 0; int i_ = i; while (i_ < S.length() && S[i_] == '-') { dash_count++; i_++; } if (dash_count != d) return nullptr; int num = 0; while (i_ < S.length() && isdigit(S[i_])) { num = 10 * num + (S[i_] - '0'); i_++; } i = i_; TreeNode* node = new TreeNode(num); node->left = dfs(S, i, d+1); node->right = dfs(S, i, d+1); return node; } public: TreeNode* recoverFromPreorder(string S) { int i = 0; return dfs(S, i, 0); } }; ================================================ FILE: cpp/1001-10000/1021-1030/Remove Outermost Parentheses.cpp ================================================ class Solution { public: string removeOuterParentheses(string S) { string return_ans; stack mystack; for (char ch : S) { if (mystack.empty()) { mystack.push(ch); } else { if (ch == '(') { mystack.push(ch); return_ans += '('; } else { mystack.pop(); if (!mystack.empty()) { return_ans += ')'; } } } } return return_ans; } }; ================================================ FILE: cpp/1001-10000/1021-1030/Sum of Root To Leaf Binary Numbers.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { int dfs(TreeNode* root, int carry) { if (!root) return 0; if (!root->left && !root->right) { return 2*carry + root->val; } carry = 2 * carry + root->val; return dfs(root->left, carry) + dfs(root->right, carry); } public: int sumRootToLeaf(TreeNode* root) { return dfs(root, 0); } }; ================================================ FILE: cpp/1001-10000/1021-1030/Two City Scheduling.cpp ================================================ class Solution { public: int twoCitySchedCost(vector>& costs) { sort(begin(costs), end(costs), [](vector &v1, vector &v2) { return abs(v1[0] - v1[1]) > abs(v2[0] - v2[1]); }); int a = costs.size()/2; int b = costs.size()/2; int ans = 0; for (const vector& cost : costs) { if (a == 0) { ans += cost[1]; continue; } if (b == 0) { ans += cost[0]; continue; } if (cost[0] <= cost[1]) { ans += cost[0]; a--; } else { ans += cost[1]; b--; } } return ans; } }; ================================================ FILE: cpp/1001-10000/1021-1030/Video Stitching.cpp ================================================ class Solution { public: int videoStitching(vector>& clips, int T) { auto cmp = [](const vector& a, const vector& b) { return a[0] <= b[0]; }; sort(clips.begin(), clips.end(), cmp); int k = 0; int next_k = -1; int ans = 0; for (const vector& clip : clips) { if (clip[0] > k && clip[0] <= next_k) { ans++; k = next_k; } if (clip[0] <= k) { next_k = max(next_k, clip[1]); if (next_k >= T) return ans + 1; } } return next_k >= T ? ans : -1; } }; ================================================ FILE: cpp/1001-10000/1031-1040/Binary Search Tree to Greater Sum Tree.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { void dfs(TreeNode* root, int& v) { if (!root) return; dfs(root->right, v); v += root->val; root->val = v; dfs(root->left, v); } public: TreeNode* bstToGst(TreeNode* root) { int v = 0; dfs(root, v); return root; } }; ================================================ FILE: cpp/1001-10000/1031-1040/Coloring A Border.cpp ================================================ class Solution { int old_color; int new_color; int row; int col; pair tmp[4] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; void dfs(vector>& grid, int i, int j, vector>& visited) { visited[i][j] = true; bool has_non_connected_cells = false; for (int k = 0; k < 4; k++) { int new_i = i + tmp[k].first; int new_j = j + tmp[k].second; if (new_i < 0 || new_j < 0 || new_i >= row || new_j >= col || visited[new_i][new_j]) continue; if (grid[new_i][new_j] == old_color) { dfs(grid, new_i, new_j, visited); } else { has_non_connected_cells = true; } } has_non_connected_cells |= (i == 0 || j == 0 || i == row-1 || j == col-1); if (has_non_connected_cells) { grid[i][j] = new_color; } } public: vector> colorBorder(vector>& grid, int r0, int c0, int color) { old_color = grid[r0][c0]; new_color = color; row = grid.size(); col = grid.front().size(); vector> visited(row, vector(col, false)); dfs(grid, r0, c0, visited); return grid; } }; ================================================ FILE: cpp/1001-10000/1031-1040/Escape a Large Maze.cpp ================================================ class Solution { bool find = false; pair tmp[4] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; bool isEscapePossibleInternal(vector>& blocked, vector& source, vector& target) { set> visited; for (const vector& b : blocked) { visited.insert({b[0], b[1]}); } stack> mystack; mystack.push({source[0], source[1]}); visited.insert({source[0], source[1]}); while (!mystack.empty()) { pair ele = mystack.top(); mystack.pop(); if (ele.first == target[0] && ele.second == target[1]) { find = true; return true; } int dis = abs(ele.first - source[0]) + abs(ele.second - source[1]); if (dis > blocked.size()) return true; for (int k = 0; k < 4; k++) { int n_i = ele.first + tmp[k].first; int n_j = ele.second + tmp[k].second; if (n_i < 0 || n_j < 0 || n_i >= 1e6 || n_j >= 1e6) continue; if (visited.count({n_i, n_j}) > 0) continue; visited.insert({n_i, n_j}); mystack.push({n_i, n_j}); } } return false; } public: bool isEscapePossible(vector>& blocked, vector& source, vector& target) { if (!isEscapePossibleInternal(blocked, source, target)) return false; if (find) return true; return isEscapePossibleInternal(blocked, target, source); } }; ================================================ FILE: cpp/1001-10000/1031-1040/Maximum Sum of Two Non-Overlapping Subarrays.cpp ================================================ class Solution { public: int maxSumTwoNoOverlap(vector& A, int L, int M) { vector sum = {0}; for(auto x:A) sum.push_back(sum.back()+x); return max(help(sum, L, M), help(sum, M,L)); } int help(const vector& sum, int L, int M) { int maxSumL = sum[L], maxSumLM = sum[L+M]; for(int i=L+M+1;i& A, map, int>& cache, int start_index, int end_index) { pair key = {start_index, end_index}; auto it = cache.find(key); if (it != cache.end()) return it->second; if (end_index - start_index < 2) { return 0; } if (end_index - start_index == 2) { return A[start_index] * A[start_index+1] * A[start_index+2]; } int ans = INT_MAX; for (int i = start_index+1; i < end_index; i++) { int current = A[start_index] * A[i] * A[end_index]; current += dfs(A, cache, start_index, i); current += dfs(A, cache, i, end_index); ans = min(ans, current); } return cache[key] = ans; } public: int minScoreTriangulation(vector& A) { map, int> cache; return dfs(A, cache, 0, A.size() - 1); } }; ================================================ FILE: cpp/1001-10000/1031-1040/Moving Stones Until Consecutive.cpp ================================================ class Solution { public: vector numMovesStones(int a, int b, int c) { vector v{a,b,c}; sort(v.begin(), v.end()); int maximum_move = v[2] - v[0] - 2; int d1 = v[1] - v[0]; int d2 = v[2] - v[1]; int minimum_move = 0; if (d1 == 1 && d2 == 1) return {0, maximum_move}; if (d1 == 1 || d2 == 1 || d1 == 2 || d2 == 2) return {1, maximum_move}; return {2, maximum_move}; } }; ================================================ FILE: cpp/1001-10000/1031-1040/Stream of Characters.cpp ================================================ struct TrieNode { TrieNode *nodes[26]; bool word; // Initialize your data structure here. TrieNode(): word(false) { memset(nodes, 0, sizeof(nodes)); } }; class Trie { public: Trie() { root = new TrieNode(); } // Inserts a word into the trie. void insert(const string& s) { TrieNode *tmp = root; for(char ch : s) { int index = ch - 'a'; if(tmp->nodes[index] == nullptr) { tmp->nodes[index] = new TrieNode(); } tmp = tmp->nodes[index]; } tmp->word = true; } bool eat(char ch) { vector tmp; if (root->nodes[ch - 'a'] != nullptr) { tmp.push_back(root->nodes[ch - 'a']); } for (TrieNode* node : state) { if (node->nodes[ch - 'a'] != nullptr) { tmp.push_back(node->nodes[ch - 'a']); } } swap(state, tmp); bool return_val = false; for (TrieNode* node : state) { if (node->word) { return_val = true; break; } } return return_val; } private: TrieNode* root; vector state; }; class StreamChecker { Trie trie; public: StreamChecker(vector& words) { for (const string& word : words) { trie.insert(word); } } bool query(char letter) { return trie.eat(letter); } }; /** * Your StreamChecker object will be instantiated and called as such: * StreamChecker* obj = new StreamChecker(words); * bool param_1 = obj->query(letter); */ ================================================ FILE: cpp/1001-10000/1031-1040/Uncrossed Lines.cpp ================================================ class Solution { public: int maxUncrossedLines(vector& A, vector& B) { int m = A.size(); int n = B.size(); vector> dp(m+1, vector(n+1, 0)); for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (A[i-1] == B[j-1]) { dp[i][j] = 1 + dp[i-1][j-1]; } else { dp[i][j] = max(dp[i-1][j], dp[i][j-1]); } } } return dp[m][n]; } }; ================================================ FILE: cpp/1001-10000/1031-1040/Valid Boomerang.cpp ================================================ class Solution { public: bool isBoomerang(vector>& points) { sort(points.begin(), points.end()); if (points[0] == points[1] || points[1] == points[2]) return false; int x1 = points[1][0] - points[0][0]; int y1 = points[1][1] - points[0][1]; int x2 = points[2][0] - points[1][0]; int y2 = points[2][1] - points[1][1]; if (x1 == 0 || x2 == 0) { return x1 != 0 || x2 != 0; } return fabs(1.0*y1/x1 - 1.0*y2/x2) > 10e-5; } }; ================================================ FILE: cpp/1001-10000/1041-1050/Flower Planting With No Adjacent.cpp ================================================ class Solution { vector colors; void dfs(int u, map>& edges) { vector neighbors = edges[u]; set excluded_colors; for (int neighbor : neighbors) { if (colors[neighbor-1] > 0) { excluded_colors.insert(colors[neighbor-1]); } } for (int i = 1; i <= 4; i++) { if (excluded_colors.count(i) == 0) { colors[u-1] = i; for (int neighbor : neighbors) { if (colors[neighbor-1] == 0) { dfs(neighbor, edges); } } break; } } } public: vector gardenNoAdj(int N, vector>& paths) { map> edges; for (const vector& path : paths) { edges[path[0]].push_back(path[1]); edges[path[1]].push_back(path[0]); } colors.resize(N, 0); for (int garden = 1; garden <= N; garden++) { if (colors[garden - 1] == 0) { dfs(garden, edges); } } return colors; } }; ================================================ FILE: cpp/1001-10000/1041-1050/Last Stone Weight II.cpp ================================================ class Solution { public: int lastStoneWeightII(vector& stones) { int sum = 0; bool dp[1501] = {false}; dp[0] = true; for (int v : stones) { sum += v; for (int start = sum; start >= v; start--) { // we need to start from back to make it not affected by itself dp[start] = dp[start] | dp[start-v]; } } for (int i = sum/2; i > 0; i--) { if (dp[i] == true) { return sum - 2 * i; } } return 0; } }; ================================================ FILE: cpp/1001-10000/1041-1050/Last Stone Weight.cpp ================================================ class Solution { public: int lastStoneWeight(vector& stones) { std::priority_queue, std::less > myqueue (stones.begin(), stones.end()); while (myqueue.size() > 1) { int v1 = myqueue.top(); myqueue.pop(); int v2 = myqueue.top(); myqueue.pop(); int v = abs(v1 - v2); if (v > 0) myqueue.push(v); } return myqueue.empty() ? 0 : myqueue.top(); } }; ================================================ FILE: cpp/1001-10000/1041-1050/Longest String Chain.cpp ================================================ class Solution { int dfs(const string& word, const unordered_set& dictionary, unordered_map& cache) { unordered_map::iterator it = cache.find(word); if (it != cache.end()) { return it->second; } int ans = 1; for (int i = 0; i < word.size(); i++) { string c_word = word.substr(0, i) + word.substr(i+1); if (dictionary.count(c_word) > 0) { ans = max(ans, 1 + dfs(c_word, dictionary, cache)); } } return cache[word] = ans; } public: int longestStrChain(vector& words) { unordered_set dictionary(begin(words), end(words)); unordered_map cache; int ans = 1; for (const string& word : words) { ans = max(ans, dfs(word, dictionary, cache)); } return ans; } }; ================================================ FILE: cpp/1001-10000/1041-1050/Partition Array for Maximum Sum.cpp ================================================ class Solution { public: int maxSumAfterPartitioning(vector& A, int K) { vector dp(A.size()+1, 0); for (int i = 0; i < A.size(); i++) { int p_i = max(-1, i - K); int maximum_i_sum = 0; int temp_max = -1; int n_elements = 0; for (int j = i; j > p_i; j--) { n_elements++; temp_max = max(temp_max, A[j]); maximum_i_sum = max(maximum_i_sum, dp[j] + n_elements * temp_max); } dp[i+1] = maximum_i_sum; } return dp.back(); } }; ================================================ FILE: cpp/1001-10000/1041-1050/Remove All Adjacent Duplicates In String.cpp ================================================ class Solution { public: string removeDuplicates(string S) { int i = 0; for (char ch : S) { if (i != 0 && ch == S[i-1]) { i--; } else { S[i] = ch; i++; } } return S.substr(0, i); } }; ================================================ FILE: cpp/1001-10000/1041-1050/Robot Bounded In Circle.cpp ================================================ class Solution { pair getNextDirection(pair d, char ch) { if (ch == 'L') { if (d.first == 0 && d.second == 1) { return {-1, 0}; } if (d.first == -1 && d.second == 0) { return {0, -1}; } if (d.first == 0 && d.second == -1) { return {1, 0}; } if (d.first == 1 && d.second == 0) { return {0, 1}; } } else { if (d.first == 0 && d.second == 1) { return {1, 0}; } if (d.first == 1 && d.second == 0) { return {0, -1}; } if (d.first == 0 && d.second == -1) { return {-1, 0}; } if (d.first == -1 && d.second == 0) { return {0, 1}; } } return {0, 0}; } string GetKey(int x, int y, pair d) { return to_string(x) + '-' + to_string(y) + '-' + to_string(d.first) + '-' + to_string(d.second); } public: bool isRobotBounded(string instructions) { pair d = {0, 1}; int x = 0, y = 0; for (char ch : instructions) { if (ch == 'G') { x += d.first; y += d.second; } else { d = getNextDirection(d, ch); } } if (x == 0 && y == 0) return true; if (d.first == 0 && d.second == 1) return false; return true; } }; ================================================ FILE: cpp/1001-10000/1051-1060/Distant Barcodes.cpp ================================================ class Solution { public: vector rearrangeBarcodes(vector& barcodes) { auto cmp = [](const pair &a, const pair &b) { return a.second < b.second || (a.second == b.second && a.first > b.first); }; priority_queue, vector>, decltype(cmp)> pq(cmp); map mymap; for (int e : barcodes) { mymap[e]++; } for (auto it : mymap) { pq.push(it); } vector ans; while (!pq.empty()) { pair e1 = pq.top(); pq.pop(); ans.push_back(e1.first); if (!pq.empty()) { pair e2 = pq.top(); pq.pop(); ans.push_back(e2.first); if (e2.second > 1) { pq.push({e2.first, e2.second - 1}); } } if (e1.second > 1) { pq.push({e1.first, e1.second - 1}); } } return ans; } }; ================================================ FILE: cpp/1001-10000/1051-1060/Grumpy Bookstore Owner.cpp ================================================ class Solution { public: int maxSatisfied(vector& customers, vector& grumpy, int X) { int gained = 0; int max_gained = 0; int normal_gained = 0; for (int i = 0; i < grumpy.size(); i++) { if (grumpy[i] == 0) normal_gained += customers[i]; gained += (grumpy[i] == 1 ? customers[i] : 0); if (i >= X) { gained -= (grumpy[i-X] == 1 ? customers[i-X] : 0); } max_gained = max(max_gained, gained); } return normal_gained + max_gained; } }; ================================================ FILE: cpp/1001-10000/1051-1060/Height Checker.cpp ================================================ class Solution { public: int heightChecker(vector& heights) { int returned_ans = 0; vector copy = heights; sort(begin(heights), end(heights)); for (int i = 0; i < heights.size(); i++) { returned_ans += (heights[i] != copy[i]); } return returned_ans; } }; ================================================ FILE: cpp/1001-10000/1051-1060/Previous Permutation With One Swap.cpp ================================================ class Solution { public: vector prevPermOpt1(vector& A) { if (A.empty()) return A; // in reverse order, find the first number which is in decreasing trend (we call it violated number here) int i(0); for (i = A.size()-2; i >= 0; --i) if (A[i] > A[i+1]) break; if (i == -1) return A; auto itr = lower_bound(A.begin()+i+1, A.end(), A[i]); if (itr != A.begin()) { itr--; auto copy = itr; while (itr != A.begin()) { int e1 = *itr; itr--; int e2 = *itr; if (e1 != e2) break; copy = itr; } swap(A[i], *copy); return A; } return A; } }; ================================================ FILE: cpp/1001-10000/1071-1080/Adding Two Negabinary Numbers.cpp ================================================ class Solution { public: vector addNegabinary(vector& arr1, vector& arr2) { vector ans; reverse(arr1.begin(), arr1.end()); reverse(arr2.begin(), arr2.end()); int i = 0, j = 0; int add_on = 0; while (i < arr1.size() || j < arr2.size() || add_on != 0) { int a = i < arr1.size() ? arr1[i] : 0; int b = j < arr2.size() ? arr2[j] : 0; int v = a + b + add_on; if (v == -1) { v = 1; add_on = 1; } else if (v >= 2) { v = v%2; add_on = -1; } else { add_on = 0; } ans.push_back(v); i++; j++; } reverse(ans.begin(), ans.end()); while (ans.size() > 1 && ans[0] == 0) ans.erase(begin(ans)); return ans; } }; ================================================ FILE: cpp/1001-10000/1071-1080/Flip Columns For Maximum Number of Equal Rows.cpp ================================================ class Solution { void process(map& mymap, const vector& vec) { string str1, str2; for (int e : vec) { str1 += ('0' + e); str2 += ('0' + (1-e)); } mymap[str1]++; mymap[str2]++; } public: int maxEqualRowsAfterFlips(vector>& matrix) { map mymap; for (const vector& vec : matrix) { process(mymap, vec); } int ans = 0; for (auto e : mymap) { ans = max(ans, e.second); } return ans; } }; ================================================ FILE: cpp/1001-10000/1071-1080/Greatest Common Divisor of Strings.cpp ================================================ class Solution { bool IsValid(const string& str, const string& candidate) { for (int i = 0; i < str.length(); i += candidate.length()) { if (str.substr(i, candidate.length()) != candidate) { return false; } } return true; } public: string gcdOfStrings(string str1, string str2) { int m = str1.length(); int n = str2.length(); int gcd = __gcd(m, n); string candidate = str1.substr(0, gcd); if (!IsValid(str1, candidate)) return ""; if (!IsValid(str2, candidate)) return ""; return candidate; } }; ================================================ FILE: cpp/1001-10000/1071-1080/Insufficient Nodes in Root to Leaf Paths.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* sufficientSubset(TreeNode* root, int limit) { if (root->left == root->right) // leaf node return root->val < limit ? nullptr : root; if (root->left) root->left = sufficientSubset(root->left, limit - root->val); if (root->right) root->right = sufficientSubset(root->right, limit - root->val); return root->left == root->right ? nullptr : root; } }; ================================================ FILE: cpp/1001-10000/1071-1080/Letter Tile Possibilities.cpp ================================================ class Solution { int fact[8] = { 1, 1, 2, 6, 24, 120, 720, 5040 }; set st; int uniquePerms(const string& s) { int cnt[26] = {}; for (char ch : s) cnt[ch - 'A']++; int res = fact[s.size()]; for (int n : cnt) res /= fact[n]; return res; } int dfs(const string& s, string seq = "", int pos = 0) { if (pos >= s.size()) { return st.insert(seq).second ? uniquePerms(seq) : 0; } return dfs(s, seq, pos + 1) + dfs(s, seq + s[pos], pos + 1); } public: int numTilePossibilities(string tiles) { sort(begin(tiles), end(tiles)); return dfs(tiles) - 1; } }; ================================================ FILE: cpp/1001-10000/1071-1080/Number of Submatrices That Sum to Target.cpp ================================================ class Solution { public: int numSubmatrixSumTarget(vector>& matrix, int target) { int m = matrix.size(), n = matrix[0].size(); for (int i = 0; i < m; i++) for (int j = 1; j < n; j++) matrix[i][j] += matrix[i][j - 1]; int res = 0; for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { unordered_map counter; counter[0] = 1; int cur = 0; for (int k = 0; k < m; k++) { cur += matrix[k][j] - (i > 0 ? matrix[k][i - 1] : 0); res += counter[cur - target]; counter[cur]++; } } } return res; } }; ================================================ FILE: cpp/1001-10000/1071-1080/Occurrences After Bigram.cpp ================================================ class Solution { public: vector findOcurrences(string text, string first, string second) { string matched_string = first + " " + second; vector return_ans; int idx = 0; while ((idx = text.find(matched_string, idx)) >= 0) { int start = idx + matched_string.size() + 1; if (start >= text.size()) break; int end = start; while (end < text.size() && text[end] != ' ') { end++; } string third = text.substr(start, end-start); return_ans.push_back(third); idx = start; } return return_ans; } }; ================================================ FILE: cpp/1001-10000/1081-1090/Duplicate Zeros.cpp ================================================ class Solution { public: void duplicateZeros(vector& arr) { int zeros_now = 0; for (int e : arr) { zeros_now += (e == 0); } int n = arr.size(); for (int i = arr.size()-1; i >= 0; i--) { if (arr[i] != 0) { int pos = i + zeros_now; int copy = arr[i]; arr[i] = 0; if (pos < n) { arr[pos] = copy; } } else { zeros_now--; } } } }; ================================================ FILE: cpp/1001-10000/1081-1090/Largest Values From Labels.cpp ================================================ class Solution { public: int largestValsFromLabels(vector& values, vector& labels, int num_wanted, int use_limit) { vector> myvec(values.size()); for (int i = 0; i < values.size(); i++) { myvec[i] = make_pair(values[i], labels[i]); } sort(myvec.begin(), myvec.end()); map counts; int ans = 0; for (int i = myvec.size() - 1; i >= 0; i--) { if (num_wanted == 0) break; int label = myvec[i].second; if (counts[label] < use_limit) { counts[label]++; ans += myvec[i].first; num_wanted--; } } return ans; } }; ================================================ FILE: cpp/1001-10000/1081-1090/Smallest Subsequence of Distinct Characters.cpp ================================================ class Solution { public: string smallestSubsequence(string text) { bool visited[26] = {false}; int count[26] = {0}; stack temp_answers; for (char ch : text) { count[ch - 'a']++; } // bcabc, b -> bc -> a -> ab -> abc // cbacdcbc, c -> b -> a -> ac -> acd -> acd -> acdb for (char ch : text) { int index = ch - 'a'; count[index]--; if (visited[index]) continue; while (!temp_answers.empty() && temp_answers.top() > ch && count[temp_answers.top() - 'a'] > 0) { char c = temp_answers.top(); temp_answers.pop(); visited[c - 'a'] = false; } temp_answers.push(ch); visited[index] = true; } string res(""); while (!temp_answers.empty()) { res = temp_answers.top() + res; temp_answers.pop(); } return res; } }; ================================================ FILE: cpp/1001-10000/1091-1100/Brace Expansion II.cpp ================================================ class Solution { set merge(const set& set1, const set& set2) { set ans; for (const string& str1 : set1) { for (const string& str2 : set2) { ans.insert(str1+str2); } } return ans; } void process(stack>& mystack, stack& ops) { char op = ops.top(); ops.pop(); set set1 = mystack.top(); mystack.pop(); set set2 = mystack.top(); mystack.pop(); if (op == '*') { set merged = merge(set2, set1); mystack.push(merged); } else if (op == ',') { set1.insert(set2.begin(), set2.end()); mystack.push(set1); } } public: vector braceExpansionII(string expression) { stack ops; stack> mystack; expression = "{" + expression + "}"; string word; for (int i = 0; i < expression.length(); i++) { if (!word.empty() && (expression[i] < 'a' || expression[i] > 'z' || i + 1 == expression.length())) { set set_; set_.insert(word); mystack.push(set_); word.clear(); } if (expression[i] == '{') { if (i != 0 && (expression[i-1] != ',' && expression[i-1] != '{')) { ops.push('*'); } ops.push('{'); } else if (expression[i] == '}') { while (ops.top() != '{') { process(mystack, ops); } ops.pop(); } else if (expression[i] == ',') { while (ops.top() == '*') { process(mystack, ops); } ops.push(','); } else { if (word.empty() && i != 0 && expression[i-1] == '}') { ops.push('*'); } word = word + expression[i]; } } return vector(mystack.top().begin(), mystack.top().end()); } }; ================================================ FILE: cpp/1001-10000/1091-1100/Car Pooling.cpp ================================================ class Solution { public: bool carPooling(vector>& trips, int capacity) { vector> v; for (const vector& trip : trips) { v.push_back({trip[1], trip[0]}); v.push_back({trip[2], -trip[0]}); } sort(v.begin(), v.end()); int passengers = 0; for (const pair& e : v) { passengers += e.second; if (passengers > capacity) { return false; } } return true; } }; ================================================ FILE: cpp/1001-10000/1091-1100/Find in Mountain Array.cpp ================================================ /** * // This is the MountainArray's API interface. * // You should not implement it, or speculate about its implementation * class MountainArray { * public: * int get(int index); * int length(); * }; */ class Solution { public: int findInMountainArray(int target, MountainArray &mountainArr) { int left = 0; int right = mountainArr.length() - 1; while (left <= right) { if (right - left < 6) { for (int k = left; k <= right; k++) { if (mountainArr.get(k) == target) return k; } return -1; } int mid = (left+right)/2; int nmid = mid+1; int v = mountainArr.get(mid); if (v == target) return mid; int vv = mountainArr.get(nmid); if (vv == target) return nmid; bool isup = vv > v; if (isup) { // [left, mid - 1] if (target < v) { int l = left; int r = mid - 1; while (r - l >= 2) { int mid_ = (l+r)/2; int v_ = mountainArr.get(mid_); if (v_ == target) return mid_; if (v_ < target) l = mid_ + 1; else r = mid_ - 1; } while (l <= r) { if (mountainArr.get(l) == target) return l; l++; } } left = nmid + 1; } else { // [mid+1, right] if (target < vv) { int l = mid+1; int r = right; while (r - l >= 2) { int mid_ = (l+r)/2; int v_ = mountainArr.get(mid_); if (v_ == target) return mid_; if (v_ > target) l = mid_ + 1; else r = mid_ - 1; } while (l <= r) { if (mountainArr.get(l) == target) return l; l++; } } right = mid - 1; } } return -1; } }; ================================================ FILE: cpp/1001-10000/1091-1100/Shortest Common Supersequence.cpp ================================================ class Solution { public: string shortestCommonSupersequence(string str1, string str2) { int m = str1.size(); int n = str2.size(); vector> dp(m+1, vector(n+1, 0)); map, pair> from; for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0) { dp[i][j] = 0; from[{i, j}] = {0, j-1}; } else if (j == 0) { dp[i][j] = 0; from[{i,j}] = {i-1, 0}; } else if (str1[i-1] == str2[j-1]) { dp[i][j] = dp[i-1][j-1] + 1; from[{i, j}] = {i-1, j-1}; } else { if (dp[i-1][j] > dp[i][j-1]) { from[{i, j}] = {i-1, j}; } else { from[{i, j}] = {i, j-1}; } dp[i][j] = max(dp[i-1][j], dp[i][j-1]); } } } int i = m; int j = n; string ans; while (!(i == 0 && j == 0)) { auto p = from[{i, j}]; if (i == p.first + 1 && j == p.second + 1) { ans = str1[i-1] + ans; } else if (i == p.first) { ans = str2[j-1] + ans; } else { ans = str1[i-1] + ans; } i = p.first; j = p.second; } return ans; } }; ================================================ FILE: cpp/1001-10000/1091-1100/Shortest Path in Binary Matrix.cpp ================================================ class Solution { public: int shortestPathBinaryMatrix(vector>& grid) { int m = grid.size(); int n = grid[0].size(); if (grid[0][0] == 1 || grid[m-1][n-1] == 1) return -1; set> visited; visited.insert({0, 0}); queue, int>> myqueue; myqueue.push({{0, 0}, 1}); while (!myqueue.empty()) { auto ele = myqueue.front(); myqueue.pop(); int m_ = ele.first.first; int n_ = ele.first.second; int d = ele.second; if (m_ == m - 1 && n_ == n - 1) return d; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) continue; int new_m = m_ + i - 1; int new_n = n_ + j - 1; if (new_m < 0 || new_n < 0 || new_m >= m || new_n >= n) continue; if (visited.count({new_m, new_n}) > 0) continue; if (grid[new_m][new_n] == 1) continue; visited.insert({new_m, new_n}); myqueue.push({{new_m, new_n}, d+1}); } } } return -1; } }; ================================================ FILE: cpp/1001-10000/1091-1100/Statistics from a Large Sample.cpp ================================================ class Solution { public: vector sampleStats(vector& count) { vector res{256, -1, 0, 0, 0}; int n_sample = accumulate(count.begin(), count.end(), 0); long sum = 0; int nth = (n_sample-1) / 2 + 1; int nnth = n_sample % 2 == 1 ? nth : nth + 1; int n_sample_so_far = 0; int mode_samples = 0; for (int i = 0; i < count.size(); i++) { if (count[i] > 0) { if (res[0] > 255) { res[0] = i; } res[1] = i; sum += i*count[i]; if (count[i] > mode_samples) { res[4] = i; mode_samples = count[i]; } int previous_sample = n_sample_so_far; n_sample_so_far += count[i]; if (nth > previous_sample && nth <= n_sample_so_far) res[3] += i; if (nnth > previous_sample && nnth <= n_sample_so_far) res[3] += i; } } res[2] = sum*1.0/n_sample; res[3] /= 2.0; return res; } }; ================================================ FILE: cpp/1001-10000/1091-1100/Two Sum Less Than K.cpp ================================================ class Solution { public: int twoSumLessThanK(vector& A, int K) { sort(begin(A), end(A)); int i = 0, j = A.size() - 1; int ans = -1; while (i < j) { int sum = A[i] + A[j]; if (sum < K) { ans = max(ans, sum); i++; } else { j--; } } return ans; } }; ================================================ FILE: cpp/1001-10000/1101-1110/Corporate Flight Bookings.cpp ================================================ class Solution { public: vector corpFlightBookings(vector>& bookings, int n) { unordered_map record; for (const vector& booking : bookings) { record[booking[0]-1] += booking[2]; record[booking[1]] -= booking[2]; } vector ans(n, -1); int current = 0; for (int i = 0; i < n; i++) { current += record[i]; ans[i] = current; } return ans; } }; ================================================ FILE: cpp/1001-10000/1101-1110/Defanging an IP Address.cpp ================================================ class Solution { public: string defangIPaddr(string address) { string ans; for (char ch : address) { if (ch == '.') { ans = ans + '[' + '.' + ']'; } else { ans = ans + ch; } } return ans; } }; ================================================ FILE: cpp/1001-10000/1101-1110/Delete Nodes And Return Forest.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { vector ans; TreeNode* dfs (TreeNode* root, set& to_deleted, bool is_root) { if (root == nullptr) { return nullptr; } if (to_deleted.count(root->val) > 0) { dfs(root->left, to_deleted, true); dfs(root->right, to_deleted, true); return nullptr; } root->left = dfs(root->left, to_deleted, false); root->right = dfs(root->right, to_deleted, false); if (is_root) ans.push_back(root); return root; } public: vector delNodes(TreeNode* root, vector& to_delete) { set to_deleted(to_delete.begin(), to_delete.end()); dfs(root, to_deleted, true); return ans; } }; ================================================ FILE: cpp/1001-10000/1101-1110/Distribute Candies to People.cpp ================================================ class Solution { public: vector distributeCandies(int candies, int num_people) { vector ans(num_people, 0); int k = 1; int index = 0; while (candies > 0) { int c = min(k, candies); ans[index] += c; k++; candies -= c; index = (index+1) % num_people; } return ans; } }; ================================================ FILE: cpp/1001-10000/1101-1110/Filling Bookcase Shelves.cpp ================================================ class Solution { public: int minHeightShelves(vector>& books, int shelf_width) { vector dp(books.size()+1, 0); for (int i = 0; i < books.size(); i++) { int minimum_h = 1001*1001; int current_shelf_height = -1; int n_elements = 0; int current_shelf_width = 0; for (int j = i; j >= 0; j--) { n_elements++; current_shelf_width += books[j][0]; if (current_shelf_width > shelf_width) break; current_shelf_height = max(current_shelf_height, books[j][1]); minimum_h = min(minimum_h, dp[j] + current_shelf_height); } dp[i+1] = minimum_h; } return dp.back(); } }; class Solution { public: int dfs(vector>& books, int shelf_width, int ind, int remain_width, int current_height, map, int>& cache) { if (ind == books.size()) { return current_height; } auto it = cache.find({ind, remain_width}); if (it != cache.end()) return it->second; // 1) we can put current book on a new shelf. int minimum_height = INT_MAX; minimum_height = current_height + dfs(books, shelf_width, ind+1, shelf_width - books[ind][0], books[ind][1], cache); // 2) If we have plenty width in current shelf, we can also put in current shelf. if (books[ind][0] <= remain_width) { current_height = max(current_height, books[ind][1]); minimum_height = min(minimum_height, dfs(books, shelf_width, ind+1, remain_width - books[ind][0], current_height, cache)); } return cache[{ind, remain_width}] = minimum_height; } int minHeightShelves(vector>& books, int shelf_width) { map, int> cache; // {ith_book}, {how many width remained in current shelf} // This cache means when I process ith book and in a w position, how many remain minimum height I need for remaining books in that state. return dfs(books, shelf_width, 0, shelf_width, 0, cache); } }; ================================================ FILE: cpp/1001-10000/1101-1110/Parsing A Boolean Expression.cpp ================================================ class Solution { public: bool parseBoolExpr(string expression) { stack ops; stack nums; for (char ch : expression) { if (ch == '(' || ch == '&' || ch == '!' || ch == '|' || ch ==',') { ops.push(ch); } else if (ch == 't') { nums.push(true); } else if (ch == 'f') { nums.push(false); } else if (ch == ')') { vector tmp; tmp.push_back(nums.top()); nums.pop(); while (ops.top() == ',') { tmp.push_back(nums.top()); nums.pop(); ops.pop(); } ops.pop(); char op = ops.top(); ops.pop(); bool result = tmp.front(); if (op == '&') { for (int i = 1; i < tmp.size(); i++) { result &= tmp[i]; } } else if (op == '|') { for (int i = 1; i < tmp.size(); i++) { result |= tmp[i]; } } else if (op == '!') { result = 1 - result; } nums.push(result); } } return nums.top(); } }; ================================================ FILE: cpp/1001-10000/1101-1110/Path In Zigzag Labelled Binary Tree.cpp ================================================ class Solution { public: vector pathInZigZagTree(int label) { int row = 0; int tmp = label; int start_number = 1; while (tmp > 0) { row++; tmp = tmp >> 1; if (tmp > 0) start_number *= 2; } vector ans; while (label > 0) { if (label == 1) { ans.insert(ans.begin(), label); break; } int a1 = start_number/2; int a2 = a1*2 - 1; int sum = a1+a2; ans.insert(ans.begin(), label); int t = label/2; start_number /= 2; label = sum - t; } return ans; } }; ================================================ FILE: cpp/1001-10000/1111-1120/Maximum Nesting Depth of Two Valid Parentheses Strings.cpp ================================================ class Solution { public: vector maxDepthAfterSplit(string seq) { int n = seq.size(); vector ans(n, 0); int depth = 0; for (int i = 0; i < seq.size(); i++) { if (seq[i] == '(') { depth++; if (depth % 2 == 0) ans[i] = 1; } else { depth--; if (depth % 2 == 1) ans[i] = 1; } } return ans; } }; ================================================ FILE: cpp/1001-10000/1111-1120/Print FooBar Alternately.cpp ================================================ class FooBar { mutex m1,m2; private: int n; public: FooBar(int n) { this->n = n; m1.lock(); } void foo(function printFoo) { for (int i = 0; i < n; i++) { // printFoo() outputs "foo". Do not change or remove this line. m2.lock(); printFoo(); m1.unlock(); } } void bar(function printBar) { for (int i = 0; i < n; i++) { // printBar() outputs "bar". Do not change or remove this line. m1.lock(); printBar(); m2.unlock(); } } }; ================================================ FILE: cpp/1001-10000/1111-1120/Print in Order.cpp ================================================ class Foo { std::promise p1; std::promise p2; public: Foo() { } void first(function printFirst) { // printFirst() outputs "first". Do not change or remove this line. printFirst(); p1.set_value(); } void second(function printSecond) { p1.get_future().wait(); // printSecond() outputs "second". Do not change or remove this line. printSecond(); p2.set_value(); } void third(function printThird) { p2.get_future().wait(); // printThird() outputs "third". Do not change or remove this line. printThird(); } }; ================================================ FILE: cpp/1001-10000/1121-1130/Lowest Common Ancestor of Deepest Leaves.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { pair dfs(TreeNode* root) { if (root == nullptr) { return {0, root}; } pair l_ans = dfs(root->left); pair r_ans = dfs(root->right); if (l_ans.first == r_ans.first) { return {l_ans.first+1, root}; } else if (l_ans.first > r_ans.first) { return {l_ans.first+1, l_ans.second}; } else { return {r_ans.first+1, r_ans.second}; } } public: TreeNode* lcaDeepestLeaves(TreeNode* root) { return dfs(root).second; } }; ================================================ FILE: cpp/1001-10000/1121-1130/Minimum Cost Tree From Leaf Values.cpp ================================================ class Solution { public: int mctFromLeafValues(vector& arr) { int n = arr.size(); vector> max_array(n, vector(n, 0)); vector> dp(n, vector(n, 0)); for (int k = 0; k < n; k++) { for (int i = 0; i+k < n; i++) { int j = i+k; if (j >= n) continue; if (k == 0) { max_array[i][j] = arr[i]; continue; } if (k==1) { max_array[i][j] = max(arr[i], arr[j]); dp[i][j] += arr[i] * arr[j]; } else { max_array[i][j] = max(max_array[i][j-1], arr[j]); int temp = INT_MAX; for (int t = i; t < j; t++) { temp = min(temp, dp[i][t] + dp[t+1][j] + max_array[i][t] * max_array[t+1][j]); } dp[i][j] = temp; } } } return dp[0][n-1]; } }; ================================================ FILE: cpp/1001-10000/1121-1130/Number of Equivalent Domino Pairs.cpp ================================================ class Solution { public: int numEquivDominoPairs(vector>& dominoes) { map, int> mymap; for (const vector& domi : dominoes) { mymap[{min(domi[0], domi[1]), max(domi[0], domi[1])}]++; } int ans = 0; for (auto it : mymap) { if (it.second > 0) { ans += it.second * (it.second-1) / 2; } } return ans; } }; ================================================ FILE: cpp/1001-10000/1121-1130/Relative Sort Array.cpp ================================================ class Solution { public: vector relativeSortArray(vector& arr1, vector& arr2) { map mymap; for (int e : arr1) { mymap[e]++; } vector ans; for (int e : arr2) { int times = mymap[e]; for (int i = 0; i < times; i++) { ans.push_back(e); } mymap[e] = 0; } for (auto it : mymap) { if (it.second > 0) { int times = it.second; for (int i = 0; i < times; i++) { ans.push_back(it.first); } } } return ans; } }; ================================================ FILE: cpp/1001-10000/1121-1130/Smallest Sufficient Team.cpp ================================================ class Solution { vector ans; map> skill_to_ppl; bool dfs(int need_skills, int n, vector& used, map& skills_picked, const vector>& people) { if (need_skills == 0) { for (int i = 0; i < used.size(); i++) { if (used[i]) { ans.push_back(i); } } return true; } if (n == 0) return false; for (auto& it : skills_picked) { if (it.second == false) { // we only focus on this skill. const string& skill = it.first; vector& ppl_index = skill_to_ppl[skill]; for (int k : ppl_index) { if (used[k]) continue; used[k] = true; const vector& current_person_skills = people[k]; int new_skills = 0; vector new_skill_vec; for (const string& current_person_skill : current_person_skills) { if (!skills_picked[current_person_skill]) { skills_picked[current_person_skill] = true; new_skills++; new_skill_vec.push_back(current_person_skill); } } if (dfs(need_skills - new_skills, n-1, used, skills_picked, people)) return true; for (const string& new_skill : new_skill_vec) { skills_picked[new_skill] = false; } used[k] = false; } return false; } } return false; } public: vector smallestSufficientTeam(vector& req_skills, vector>& people) { for (int i = 0; i < people.size(); i++) { for (const string& skill : people[i]) { skill_to_ppl[skill].push_back(i); } } map skills_picked; for (const string& req_skill : req_skills) { skills_picked[req_skill] = false; } for (int i = 1; i <= req_skills.size(); i++) { vector used(people.size(), false); if (dfs(req_skills.size(), i, used, skills_picked, people)) { return ans; } } return vector(); } }; ================================================ FILE: cpp/1001-10000/1131-1140/N-th Tribonacci Number.cpp ================================================ class Solution { public: int tribonacci(int n) { int dp[50] = {0}; dp[1] = 1; dp[2] = 1; if (n <= 2) return dp[n]; for (int i = 3; i <= n; i++) { dp[i] = dp[i-3] + dp[i-2] + dp[i-1]; } return dp[n]; } }; ================================================ FILE: cpp/1001-10000/1141-1150/Binary Tree Coloring Game.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { int l_num_; int r_num_; int dfs(TreeNode* root, int x) { if (!root) return 0; int l = dfs(root->left, x); int r = dfs(root->right, x); if (root->val == x) { l_num_ = l; r_num_ = r; return 0; } return l + r + 1; } public: bool btreeGameWinningMove(TreeNode* root, int n, int x) { l_num_ = 0; r_num_ = 0; int l_p = dfs(root, x); return (l_num_ > n/2 || r_num_ > n/2 || l_p > n/2); } }; ================================================ FILE: cpp/1001-10000/1141-1150/Decrease Elements To Make Array Zigzag.cpp ================================================ class Solution { public: int movesToMakeZigzag(vector& nums) { int temp1 = 0; for (int i = 1; i < nums.size(); i += 2) { int ele = nums[i-1]; if (i+1 < nums.size()) ele = min(ele, nums[i+1]); if (nums[i] >= ele) { temp1 += (nums[i] - ele + 1); } } int temp2 = 0; for (int i = 0; i < nums.size(); i += 2) { int ele = min(i-1 >= 0 ? nums[i-1] : 10000, i+1 < nums.size() ? nums[i+1] : 10000); if (nums[i] >= ele) { temp2 += (nums[i] - ele + 1); } } return min(temp1, temp2); } }; ================================================ FILE: cpp/1001-10000/1141-1150/Longest Chunked Palindrome Decomposition.cpp ================================================ class Solution { public: int longestDecomposition(string text) { if (text.length() <= 1) return text.length(); int i_start = 0; int i_end = i_start + 1; int j_start = text.length() - 1; while (true) { if (j_start < i_end) { return 1; } string str1 = text.substr(i_start, i_end - i_start); string str2 = text.substr(j_start); if (str1 == str2) { int len = text.length() - 2 * (i_end - i_start); return 2 + longestDecomposition(text.substr(i_end, len)); } i_end++; j_start--; } return 1; } }; ================================================ FILE: cpp/1001-10000/1141-1150/Longest Common Subsequence.cpp ================================================ class Solution { public: int longestCommonSubsequence(string text1, string text2) { int m = text1.length(); int n = text2.length(); vector> dp(m+1, vector(n+1, 0)); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (text1[i] == text2[j]) { dp[i+1][j+1] = 1 + dp[i][j]; } else { dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j]); } } } return dp[m][n]; } }; ================================================ FILE: cpp/1001-10000/1141-1150/Snapshot Array.cpp ================================================ class SnapshotArray { map, int> mymap_; int snapshot_id_; map> index_to_snaps_; public: SnapshotArray(int length) { snapshot_id_ = 0; } void set(int index, int val) { mymap_[{snapshot_id_, index}] = val; index_to_snaps_[index].push_back(snapshot_id_); } int snap() { snapshot_id_++; return snapshot_id_-1; } int get(int index, int snap_id) { auto up = std::upper_bound (index_to_snaps_[index].begin(), index_to_snaps_[index].end(), snap_id); if (up == index_to_snaps_[index].begin()) return 0; --up; int target_snap_id =*up; return mymap_[{target_snap_id, index}]; } }; /** * Your SnapshotArray object will be instantiated and called as such: * SnapshotArray* obj = new SnapshotArray(length); * obj->set(index,val); * int param_2 = obj->snap(); * int param_3 = obj->get(index,snap_id); */ ================================================ FILE: cpp/1001-10000/1151-1160/Day of the Year.cpp ================================================ class Solution { public: int dayOfYear(string date) { vector daysOfMonth{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int y = stoi(date.substr(0, 4)), m = stoi(date.substr(5, 2)), d = stoi(date.substr(8, 2)); if ((y % 100 != 0 && y % 4 == 0) || y % 400 == 0) daysOfMonth[1] = 29; return accumulate(daysOfMonth.begin(), daysOfMonth.begin() + m - 1, 0) + d; } }; ================================================ FILE: cpp/1001-10000/1151-1160/Find Words That Can Be Formed by Characters.cpp ================================================ class Solution { public: int countCharacters(vector& words, string chars) { map mymap; for (char ch : chars) { mymap[ch]++; } int res = 0; map copy = mymap; for (const string& word : words) { bool ok = true; for (char ch : word) { mymap[ch]--; if (mymap[ch] < 0) { ok = false; break; } } if (ok) res += word.length(); mymap = copy; } return res; } }; ================================================ FILE: cpp/1001-10000/1151-1160/Number of Dice Rolls With Target Sum.cpp ================================================ class Solution { unordered_map cache; public: int numRollsToTarget(int d, int f, int target) { if (target == 0) { if (d == 0) return 1; return 0; } if (d <= 0 || target <= 0) return 0; int key = d * 1001 + target; if (cache.count(key) > 0) return cache[key]; long res = 0; for (int i = 1; i <= f; i++) { res = (res + (long)numRollsToTarget(d-1, f, target - i)) % 1000000007L; } return cache[key] = res; } }; ================================================ FILE: cpp/1001-10000/1161-1170/As Far from Land as Possible.cpp ================================================ class Solution { public: int maxDistance(vector>& grid) { queue> myqueue; set> visited; for (int i = 0; i < grid.size(); i++) { for (int j = 0; j < grid.front().size(); j++) { if (grid[i][j] == 1) { myqueue.push({i, j}); visited.insert({i, j}); } } } pair tmp[4] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; int dis = 1; int res = -1; while (!myqueue.empty()) { int sizes = myqueue.size(); for (int i = 0; i < sizes; i++) { pair ele = myqueue.front(); myqueue.pop(); int i_ = ele.first; int j_ = ele.second; for (const pair& p : tmp) { int new_i = i_ + p.first; int new_j = j_ + p.second; if (new_i < 0 || new_j < 0 || new_i >= grid.size() || new_j >= grid.front().size()) continue; if (grid[new_i][new_j] == 1) continue; if (visited.count({new_i, new_j}) > 0) continue; visited.insert({new_i, new_j}); myqueue.push({new_i, new_j}); res = dis; } } dis++; } return res; } }; ================================================ FILE: cpp/1001-10000/1161-1170/Compare Strings by Frequency of the Smallest Character.cpp ================================================ class Solution { int getF(const string& word) { char ch = word[0]; for (int i = 1; i < word.size(); i++) { if (ch > word[i]) ch = word[i]; } int f = 0; for (char c : word) if (c == ch) f++; return f; } public: vector numSmallerByFrequency(vector& queries, vector& words) { vector v; for (auto& word : words) { int f = getF(word); v.push_back(f); } vector ans; for (auto& query : queries) { int f = getF(query); int c = 0; for (int e : v) if (f < e) c++; ans.push_back(c); } return ans; } }; ================================================ FILE: cpp/1001-10000/1161-1170/Design File System.cpp ================================================ class FileSystem { map mymap; public: FileSystem() { mymap[""] = 0; } bool create(string path, int value) { size_t pos = path.find_last_of('//'); if (pos == string::npos) { return false; } string parent = path.substr(0, pos); if (mymap.count(parent) == 0) return false; mymap[path] = value; return true; } int get(string path) { if (mymap.count(path) == 0) return -1; return mymap[path]; } }; /** * Your FileSystem object will be instantiated and called as such: * FileSystem* obj = new FileSystem(); * bool param_1 = obj->create(path,value); * int param_2 = obj->get(path); */ ================================================ FILE: cpp/1001-10000/1161-1170/Invalid Transactions.cpp ================================================ class Solution { vector split(const string &s, char delim) { vector elems; stringstream ss(s); string item; while (getline(ss, item, delim)) { if (item.length() > 0) { elems.push_back(item); } } return elems; } public: vector invalidTransactions(vector& transactions) { vector ans; for (int i = 0; i < transactions.size(); i++) { vector to_check = split(transactions[i], ','); int amount = stoi(to_check[2]); if (amount > 1000) { ans.push_back(transactions[i]); continue; } int i_time = stoi(to_check[1]); for (int j = 0; j < transactions.size(); j++) { if (i == j) continue; vector v = split(transactions[j], ','); if (to_check[0] != v[0]) continue; if (to_check[3] == v[3]) continue; int j_time = stoi(v[1]); if (abs(i_time - j_time ) > 60) continue; ans.push_back(transactions[i]); break; } } return ans; } }; ================================================ FILE: cpp/1001-10000/1161-1170/Maximum Level Sum of a Binary Tree.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { map mymap; void dfs(TreeNode* root, int level) { if (root == nullptr) return; mymap[level] += root->val; dfs(root->left, level+1); dfs(root->right, level+1); } public: int maxLevelSum(TreeNode* root) { int level = 1; int max_sum = INT_MIN; dfs(root, 1); for (auto& it : mymap) { if (it.second > max_sum) { max_sum = it.second; level = it.first; } } return level; } }; ================================================ FILE: cpp/1001-10000/1161-1170/Minimum Cost to Connect Sticks.cpp ================================================ class Solution { public: int connectSticks(vector& sticks) { priority_queue, std::greater> myqueue; for (int e : sticks) myqueue.push(e); int ans = 0; while (myqueue.size() > 1) { int e1 = myqueue.top(); myqueue.pop(); int e2 = myqueue.top(); myqueue.pop(); ans += (e1 + e2); myqueue.push(e1 + e2); } return ans; } }; ================================================ FILE: cpp/1001-10000/1161-1170/Optimize Water Distribution in a Village.cpp ================================================ class UF { private: vector parent; vector rank; int count; int N; public: UF(int N) : parent(N), rank(N, 0), N(N), count(N) { for (int i = 0; i < N; i++) { parent[i] = i; } } int find(int p) { while (p != parent[p]) { parent[p] = parent[parent[p]]; // path compression by halving p = parent[p]; } return p; } bool connected(int p, int q) { return find(p) == find(q); } void Union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make root of smaller rank point to root of larger rank if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ; else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP; else { parent[rootQ] = rootP; rank[rootP]++; } count--; } }; class Solution { public: int minCostToSupplyWater(int n, vector& wells, vector>& pipes) { UF uf(n+1); for (auto& pipe : pipes) swap(pipe[0], pipe[2]); for (int i = 0; i < n; i++) pipes.push_back({wells[i], 0, i+1}); sort(pipes.begin(), pipes.end()); int ans = 0; for (auto& pipe : pipes) { int u = pipe[1]; int v = pipe[2]; if (!uf.connected(u, v)) { uf.Union(u, v); ans += pipe[0]; } } return ans; } }; ================================================ FILE: cpp/1001-10000/1161-1170/Single-Row Keyboard.cpp ================================================ class Solution { public: int calculateTime(string keyboard, string word) { map kmap; for (int i = 0; i < keyboard.size(); i++) { kmap[keyboard[i]] = i; } int res = 0; for (int i = 0; i < word.length(); i++) { res += abs(kmap[word[i]] - (i == 0 ? 0 : kmap[word[i-1]])); } return res; } }; ================================================ FILE: cpp/1001-10000/1171-1180/Can Make Palindrome from Substring.cpp ================================================ class Solution { public: vector canMakePaliQueries(string s, vector>& queries) { vector> data(s.length()+1, vector(26, 0)); for (int i = 0; i < s.length(); i++) { for (int j = 0; j < 26; j++) { data[i+1][j] = data[i][j] + (s[i] - 'a' == j ? 1 : 0); } } vector answers; for (const vector& query : queries) { int needed = 0; for (int j = 0; j < 26; j++) { int d = data[query[1]+1][j] - data[query[0]][j]; if (d % 2 == 1) needed++; } if ((query[1] - query[0]) % 2 == 0) needed--; if (needed <= 2*query[2]) answers.push_back(true); else answers.push_back(false); } return answers; } }; ================================================ FILE: cpp/1001-10000/1171-1180/Count Substrings with Only One Distinct Letter.cpp ================================================ class Solution { public: int countLetters(string S) { int i = 0; int j = 0; int ans = 0; while (i < S.length()) { while (S[j] == S[i]) { j++; } int num = j - i; ans += ((1+num) * num / 2); i = j; } return ans; } }; ================================================ FILE: cpp/1001-10000/1171-1180/Diet Plan Performance.cpp ================================================ class Solution { public: int dietPlanPerformance(vector& calories, int k, int lower, int upper) { int ans = 0; int sum = accumulate(calories.begin(), calories.begin() + k, 0); for (int i = k; i <= calories.size(); i++) { if (sum > upper) ans++; if (sum < lower) ans--; if (i >= calories.size()) break; sum = sum - calories[i - k]; sum = sum + calories[i]; } return ans; } }; ================================================ FILE: cpp/1001-10000/1171-1180/Dinner Plate Stacks.cpp ================================================ class DinnerPlates { vector> v; int capacity; int bestindex; public: DinnerPlates(int capacity) { this->capacity = capacity; bestindex = 0; } void push(int val) { for (int i = bestindex; i < v.size(); i++) { stack& s = v[i]; if (s.size() < capacity) { s.push(val); bestindex = i; return; } } stack ss; ss.push(val); v.emplace_back(ss); bestindex = v.size() - 1; } int pop() { for (int i = v.size() - 1; i >= 0; i--) { stack& s = v[i]; if (!s.empty()) { int ret = s.top(); s.pop(); bestindex = min(bestindex, i); return ret; } v.pop_back(); bestindex = max(0, min(bestindex, (int)v.size()-1)); } return -1; } int popAtStack(int index) { stack& s = v[index]; if (!s.empty()) { int ret = s.top(); s.pop(); bestindex = min(bestindex, index); return ret; } return -1; } }; /** * Your DinnerPlates object will be instantiated and called as such: * DinnerPlates* obj = new DinnerPlates(capacity); * obj->push(val); * int param_2 = obj->pop(); * int param_3 = obj->popAtStack(index); */ ================================================ FILE: cpp/1001-10000/1171-1180/Prime Arrangements.cpp ================================================ class Solution { bool isPrime(int k) { if (k == 1) return false; if (k <= 3) return true; int limit = sqrt(k); for (int i = 2; i <= limit; i++) { if (k % i == 0) return false; } return true; } public: int numPrimeArrangements(int n) { int pn = 0; for (int i = 1; i <= n; i++) { if (isPrime(i)) { pn++; } } int npn = n - pn; long ans = 1; int mod = 1000000007; for (int i = 1; i <= pn; i++) { ans = (ans * i) % mod; } for (int i = 1; i <= npn; i++) { ans = (ans * i) % mod; } return ans; } }; ================================================ FILE: cpp/1001-10000/1171-1180/Remove Zero Sum Consecutive Nodes from Linked List.cpp ================================================ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* removeZeroSumSublists(ListNode* head) { map mymap; ListNode* phead = new ListNode(0); mymap[0] = phead; phead->next = head; int sum = 0; while (head) { sum += head->val; if (mymap.count(sum) > 0) { ListNode* prev = mymap[sum]; ListNode* deleted = prev->next; int mysum = sum; while (deleted != head) { mysum += deleted->val; mymap.erase(mysum); deleted = deleted->next; } prev->next = head->next; } else { mymap[sum] = head; } head = head->next; } return phead->next; } }; ================================================ FILE: cpp/1001-10000/1181-1190/Before and After Puzzle.cpp ================================================ class Solution { string getfirst(string& s) { size_t pos = s.find(' '); if (pos == string::npos) return s; return s.substr(0, pos); } string getlast(string& s) { size_t pos = s.find_last_of(' '); if (pos == string::npos) return s; return s.substr(pos+1); } public: vector beforeAndAfterPuzzles(vector& phrases) { map> firstmap; map> lastmap; for (int i = 0; i < phrases.size(); i++) { string& s = phrases[i]; string first = getfirst(s); firstmap[first].push_back(i); string last = getlast(s); lastmap[last].push_back(i); } set ans; for (auto& it : lastmap) { const string& s = it.first; if (firstmap.count(s) > 0) { vector& seconds = firstmap[s]; vector& firsts = it.second; for (int i : firsts) { string original_first = phrases[i]; string f; size_t pos = original_first.find_last_of(' '); if (pos == string::npos) f = ""; else f = original_first.substr(0, pos+1); for (int j : seconds) { if (i == j) continue; string original_second = phrases[j]; ans.insert(f + original_second); } } } } vector return_ans(ans.begin(), ans.end()); return return_ans; } }; ================================================ FILE: cpp/1001-10000/1181-1190/Day of the Week.cpp ================================================ class Solution { public: string dayOfTheWeek(int day, int month, int year) { vector t {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4}; year -= (month < 3); int v = (year + year / 4 - year / 100 + year / 400 + t[month - 1] + day) % 7; if (v == 1) return "Monday"; if (v == 2) return "Tuesday"; if (v == 3) return "Wednesday"; if (v == 4) return "Thursday"; if (v == 5) return "Friday"; if (v == 6) return "Saturday"; return "Sunday"; } }; ================================================ FILE: cpp/1001-10000/1181-1190/Design Bounded Blocking Queue.cpp ================================================ // copy form https://leetcode.com/problems/design-bounded-blocking-queue/discuss/394855/C%2B%2B-Mutex-and-Condition-Variable-w-Predicate class BoundedBlockingQueue { private: mutex m_queue_mutex; condition_variable m_queue_changed; queue m_queue; // m_queue_mutex int m_capacity; // m_queue_mutex public: BoundedBlockingQueue(int capacity) { // Initialize queue and capacity m_capacity = capacity; } void enqueue(int element) { // Add to front of queue // If full, block caller until enqueue succeeds { unique_lock lk(m_queue_mutex); // Grab the lock with queue size < capacity m_queue_changed.wait(lk, [this] {return m_queue.size() < m_capacity;}); m_queue.push(element); } // Avoid waiters waking up and immediately blocking by unlocking // before notifying m_queue_changed.notify_all(); } int dequeue() { // Remove from front of queue // If empty, block caller until dequeue succeeds int ret; { unique_lock lk(m_queue_mutex); // Grab the lock with queue size > 0 m_queue_changed.wait(lk, [this] {return !m_queue.empty();}); ret = m_queue.front(); m_queue.pop(); } m_queue_changed.notify_all(); return ret; } int size() { // returns size of queue unique_lock lk(m_queue_mutex); return m_queue.size(); } }; ================================================ FILE: cpp/1001-10000/1181-1190/Distance Between Bus Stops.cpp ================================================ class Solution { public: int distanceBetweenBusStops(vector& distance, int start, int destination) { int dis_a = 0; int dis_b = 0; int n = distance.size(); int s = start; int d = destination; while (s != d) { dis_a += distance[s]; s = (s+1) % n; } s = start; d = destination; while (s != d) { s = ( (s-1) + n) % n; dis_b += distance[s]; } return min(dis_a, dis_b); } }; ================================================ FILE: cpp/1001-10000/1181-1190/Make Array Strictly Increasing.cpp ================================================ class Solution { map, int> cache; public: int makeArrayIncreasing(vector& arr1, vector& arr2) { sort(arr2.begin(), arr2.end()); int val= dfs(arr1, arr2, 0, -1); if(val>=2000) return -1; else return val; } int dfs(vector& arr1, vector& arr2, int i, int prev) { if (i >= arr1.size()) return 0; pair key = {i, prev}; if (cache.count(key) > 0) return cache[key]; // find the next greater element in arr2 than prev auto it = upper_bound(arr2.begin(), arr2.end(), prev); int j = it - arr2.begin(); int val; if (arr1[i] <= prev) { // Current value is not valid. if (j >= arr2.size()) { // we cannot find any value in arr2 to replace val = 2500; } else { val = 1 + dfs(arr1, arr2, i+1, arr2[j]); } } else { // Current value in arr1 is ok. // If we cannot make use of arr2 or arr1[i] is smaller than arr2[j](greedy). if (j >= arr2.size() || arr1[i] <= arr2[j]) { val = dfs(arr1, arr2, i+1, arr1[i]); } else { val = min(dfs(arr1, arr2, i+1, arr1[i]), 1+dfs(arr1, arr2, i+1, arr2[j])); } } return cache[key] = val; } }; ================================================ FILE: cpp/1001-10000/1181-1190/Maximum Subarray Sum with One Deletion.cpp ================================================ class Solution { int getV(vector& dp, int i) { if (i < 0 || i >= dp.size()) return -100000; return dp[i]; } public: int maximumSum(vector& arr) { int n = arr.size(); if (n == 1) return arr[0]; vector dp1(n, 0); vector dp2(n, 0); dp1[0] = arr[0]; for (int i = 1; i < n; i++) { dp1[i] = max(arr[i], dp1[i-1] + arr[i]); } dp2[n-1] = arr[n-1]; for (int i = n-2; i >= 0; i--) { dp2[i] = max(arr[i], dp2[i+1] + arr[i]); } int ans = INT_MIN; for (int i = 0; i < n; i++) { ans = max(ans, max(getV(dp1, i-1), getV(dp2, i+1))); ans = max(ans, getV(dp1, i-1) + getV(dp2, i+1)); } return ans; } }; ================================================ FILE: cpp/1001-10000/1181-1190/Shortest Distance to Target Color.cpp ================================================ class Solution { public: vector shortestDistanceColor(vector& colors, vector>& queries) { int n = colors.size(); vector> dp(n, vector(3, INT_MAX)); vector pos(3, -1); for (int i = 0; i < colors.size(); i++) { int color = colors[i]; pos[color-1] = i; for (int k = 0; k < 3; k++) { dp[i][k] = pos[k] >= 0 ? i - pos[k] : INT_MAX; } } pos[0] = pos[1] = pos[2] = -1; for (int i = colors.size()-1; i >= 0; i--) { int color = colors[i]; pos[color-1] = i; for (int k = 0; k < 3; k++) { dp[i][k] = min(dp[i][k], pos[k] >= 0 ? pos[k] - i : INT_MAX); } } vector ans; for (auto& query : queries) { int v = dp[query[0]][query[1]-1]; ans.push_back(v == INT_MAX ? -1 : v); } return ans; } }; ================================================ FILE: cpp/1001-10000/1191-1200/Minimum Knight Moves.cpp ================================================ class Solution { public: int minKnightMoves(int x, int y) { queue> myqueue; unordered_set visited; myqueue.push({0, 0}); visited.insert(0); int step = 0; vector> directions = {{1,2},{2,1},{2,-1},{1,-2},{-1,2},{-2,1},{-1,-2},{-2,-1}}; while (!myqueue.empty()) { int k = myqueue.size(); for (int i = 0; i < k; i++) { pair cur = myqueue.front(); myqueue.pop(); if (cur.first == x && cur.second == y) { return step; } for (const auto& d : directions) { int nx = cur.first + d.first; int ny = cur.second + d.second; if (nx < -300 || ny < -300 || ny > 300 || nx > 300) continue; if ((abs(nx) + abs(ny)) > 300) continue; int key = nx * 1000 + ny; if (visited.count(key) > 0) continue; visited.insert(key); myqueue.push({nx, ny}); } } step++; } return step; } }; ================================================ FILE: cpp/1001-10000/1201-1210/Design Skiplist.cpp ================================================ class Skiplist { struct Node { Node *right, *down; int val; Node(Node *right, Node *down, int val): right(right), down(down), val(val) {} }; Node* head; public: Skiplist() { head = new Node(nullptr, nullptr, -1); } bool search(int num) { Node *cur = head; while (cur != nullptr) { while (cur->right != nullptr && cur->right->val < num) { cur = cur->right; } if (cur->right == nullptr || cur->right->val > num) { cur = cur->down; } else { return true; } } return false; } void add(int num) { stack insertPoints; Node *cur = head; while (cur != nullptr) { while (cur->right != nullptr && cur->right->val < num) { cur = cur->right; } insertPoints.push(cur); cur = cur->down; } Node* downNode = nullptr; bool insertUp = true; while (insertUp && !insertPoints.empty()) { Node *ins = insertPoints.top(); insertPoints.pop(); ins->right = new Node(ins->right, downNode, num); downNode = ins->right; insertUp = ((rand() & 1) == 0); } if (insertUp) { head = new Node(new Node(NULL, downNode, num), head, -1); } } bool erase(int num) { Node *cur = head; bool seen = false; while (cur != nullptr) { while (cur->right != nullptr && cur->right->val < num) { cur = cur->right; } if (cur->right == nullptr || cur->right->val > num) { cur = cur->down; } else { seen = true; Node* to_delete = cur->right; cur->right = cur->right->right; cur = cur->down; delete to_delete; } } return seen; } }; ================================================ FILE: cpp/1001-10000/1201-1210/Smallest String With Swaps.cpp ================================================ class Solution { void dfs(int node, vector& group, vector& colors, map>& graph) { colors[node] = 1; group.push_back(node); for (int neighbor : graph[node]) { if (colors[neighbor] == 0) { dfs(neighbor, group, colors, graph); } } } public: string smallestStringWithSwaps(string s, vector>& pairs) { map> graph; for (const auto& pair : pairs) { graph[pair[0]].push_back(pair[1]); graph[pair[1]].push_back(pair[0]); } int n = s.length(); vector colors(n, 0); for (int i = 0; i < n; i++) { if (colors[i] == 0) { vector group; dfs(i, group, colors, graph); sort(group.begin(), group.end()); string temp; for (int index : group) temp += s[index]; sort(temp.begin(), temp.end()); for (int k = 0; k < group.size(); k++) { s[group[k]] = temp[k]; } } } return s; } }; ================================================ FILE: cpp/1001-10000/1221-1230/Dice Roll Simulation.cpp ================================================ class Solution { public: int dieSimulator(int n, vector& rollMax) { long cnt = 0; long MOD = 1e9+7; vector> dp(7, vector(16, 0)); dp[1][1] = dp[2][1] = dp[3][1] = dp[4][1] = dp[5][1] = dp[6][1] = 1; for (int k = 2; k <= n; k++) { vector> dp_tmp(7, vector(16, 0)); // 这一层循环,是骰子有6种可能性 for (int i = 1; i <= 6; i++) { // 这一层循环,是前一次骰子有6种可能性 for (int j = 1; j <= 6; j++) { // 这一层循环,是前一次骰子在最后重复的次数 for (int m = 1; m < 16; m++) { long v = dp[j][m]; if (i == j) { if (m+1 <= rollMax[i-1]) { dp_tmp[i][m+1] = (dp_tmp[i][m+1] + v) % MOD; } } else { dp_tmp[i][1] = (dp_tmp[i][1] + v) % MOD; } } } } swap(dp, dp_tmp); } for (int i = 1; i <= 6; i++) { for (int j = 1; j <= 15; j++) { cnt = (cnt + dp[i][j]) % MOD; } } return cnt; } }; ================================================ FILE: cpp/1001-10000/1221-1230/Queens That Can Attack the King.cpp ================================================ class Solution { public: vector> queensAttacktheKing(vector>& queens, vector& king) { vector> ans; vector> directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}; set> q; for (auto& queen : queens) { q.insert({queen[0], queen[1]}); } for (auto& dir : directions) { int x = king[0]; int y = king[1]; while (true) { x += dir.first; y += dir.second; if (x < 0 || y < 0 || x >= 8 || y >= 8) break; if (q.count({x,y}) > 0) { ans.push_back({x, y}); break; } } } return ans; } }; ================================================ FILE: cpp/1001-10000/1221-1230/Split a String in Balanced Strings.cpp ================================================ class Solution { public: int balancedStringSplit(string s) { int ans = 0; int num = 0; for (char ch : s) { num += (ch == 'L') ? 1 : -1; if (num == 0) ans++; } return ans; } }; ================================================ FILE: cpp/1001-10000/1231-1240/Maximum Profit in Job Scheduling.cpp ================================================ struct Entry { int start_time; int end_time; int profit; }; class Solution { public: int jobScheduling(vector& startTime, vector& endTime, vector& profit) { map dp; int maximum_profit = 0; int n = profit.size(); vector entries; for (int i = 0; i < n; i++) { Entry entry; entry.start_time = startTime[i]; entry.end_time = endTime[i]; entry.profit = profit[i]; entries.push_back(entry); } auto cmp = [](const Entry& lhs, const Entry& rhs) { return lhs.end_time <= rhs.end_time; }; sort(entries.begin(), entries.end(), cmp); for (const Entry& entry : entries) { auto it = dp.upper_bound(entry.start_time); int max_profit_until_start_time = 0; if (it != dp.begin()) { max_profit_until_start_time = (--it)->second; } int current_profit = max_profit_until_start_time + entry.profit; maximum_profit = max(maximum_profit, current_profit); dp[entry.end_time] = maximum_profit; } return maximum_profit; } }; ================================================ FILE: cpp/1001-10000/1231-1240/Replace the Substring for Balanced String.cpp ================================================ class Solution { public: int balancedString(string s) { map sum; int n = s.length(); int needed = n/4; for (char ch : s) sum[ch]++; int ans = INT_MAX; map chInSubString; int i = 0, j = -1; while (j < n) { int temp = 0; for (char ch : {'Q', 'W', 'E', 'R'}) { int ch_needed = needed - (sum[ch] - chInSubString[ch]); if (ch_needed > 0) temp += ch_needed; } if (temp <= (j-i+1)) { ans = min(ans, temp); chInSubString[s[i]]--; i++; } else { j++; chInSubString[s[j]]++; } } return ans; } }; ================================================ FILE: cpp/1001-10000/1241-1250/Minimum Remove to Make Valid Parentheses.cpp ================================================ class Solution { public: string minRemoveToMakeValid(string s) { stack mystack; for (int i = 0; i < s.length(); i++) { char ch = s[i]; if (ch == '(') { mystack.push(i); } else if (ch == ')') { if (!mystack.empty()) { mystack.pop(); } else { s[i] = '?'; } } } while (!mystack.empty()) { s[mystack.top()] = '?'; mystack.pop(); } // https://www.geeksforgeeks.org/remove-spaces-from-a-given-string/ s.erase(remove(s.begin(), s.end(), '?'), s.end()); return s; } }; ================================================ FILE: cpp/1001-10000/1241-1250/Web Crawler Multithreaded.cpp ================================================ /** * // This is the HtmlParser's API interface. * // You should not implement it, or speculate about its implementation * class HtmlParser { * public: * vector getUrls(string url); * }; */ class Solution { private: int thread_num; string hostname; queue q; unordered_set seen; int working = 0; bool done; mutex m; condition_variable cv; string extractHostName(const string& url){ int start = url.find('/') + 2; int end = url.find('/', start); if(end == string::npos) return url.substr(start); return url.substr(start, end - start); } vector workers; // this a worker thread that will be doing tasks. void startWorker(HtmlParser* parser){ while (done == false) { unique_lock ul(m); cv.wait(ul, [&]() { return !q.empty() || done; }); if (done) { return; } string item = q.front(); q.pop(); working++; ul.unlock(); vector urls = parser->getUrls(item); ul.lock(); for (const string& url : urls) { if (seen.count(url) > 0 || (extractHostName(url) != hostname)) continue; seen.insert(url); q.push(url); } working--; if (q.empty() && working == 0) { done = true; } cv.notify_all(); } } public: vector crawl(string startUrl, HtmlParser htmlParser) { // get the hostname for this url. // mark it as seen. hostname = extractHostName(startUrl); seen.insert(startUrl); done = false; // get number of supported threads thread_num = thread::hardware_concurrency(); // push the first task to do. q.push(startUrl); // start bunch of worker threads. for(int i = 0; i < thread_num; i++){ workers.emplace_back(&Solution::startWorker, this, &htmlParser); } // join those threads so that crawl is a blocking call for(auto &t : workers){ t.join(); } // return every unique processed string return vector(seen.begin(), seen.end()); } }; ================================================ FILE: cpp/1001-10000/1261-1270/Greatest Sum Divisible by Three.cpp ================================================ class Solution { public: int maxSumDivThree(vector& nums) { vector dp(3, 0); for (int v : nums) { vector dp_copy = dp; for (int i = 0; i < 3; i++) { int tmp = v + dp[i]; int mod = tmp % 3; dp_copy[mod] = max(dp_copy[mod], tmp); } dp = dp_copy; } return dp[0]; } }; ================================================ FILE: cpp/1001-10000/1281-1290/Convert Binary Number in a Linked List to Integer.cpp ================================================ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: int getDecimalValue(ListNode* head) { int ans = 0; while(head) { ans = 2*ans + head->val; head = head->next; } return ans; } }; ================================================ FILE: cpp/1001-10000/1281-1290/Element Appearing More Than 25% In Sorted Array.cpp ================================================ class Solution { public: int findSpecialInteger(vector& arr) { int pv = arr[0]-1; int times = 0; for (int v : arr) { if (v == pv) { times++; if (times >= arr.size()/4) return v; } else { times = 0; pv = v; } } return arr.back(); } }; ================================================ FILE: cpp/1001-10000/1281-1290/Remove Covered Intervals.cpp ================================================ class Solution { public: int removeCoveredIntervals(vector>& intervals) { int ans = intervals.size(); sort(intervals.begin(), intervals.end()); int left = intervals[0][0]; int right = intervals[0][1]; for (int i = 1; i < intervals.size(); i++) { int l = intervals[i][0]; int r = intervals[i][1]; if (l >= left && r <= right) ans--; else { left = l; right = r; } } return ans; } }; ================================================ FILE: cpp/1001-10000/1291-1300/Maximum Side Length of a Square with Sum Less than or Equal to Threshold.cpp ================================================ class Solution { bool check(const vector>& sum, int side_length, int m, int n, int threshold) { for (int i = 0; i <= m-side_length; i++) { for (int j = 0; j <= n-side_length; j++) { int x = i + side_length; int y = j + side_length; long current_sum = sum[x][y] - sum[i][y] - sum[x][j] + sum[i][j]; if (current_sum <= threshold) return true; } } return false; } public: int maxSideLength(vector>& mat, int threshold) { int m = mat.size(); int n = mat[0].size(); vector> sum(m+1, vector(n+1, 0)); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { sum[i+1][j+1] = sum[i][j+1] + sum[i+1][j] - sum[i][j] + mat[i][j]; } } int left = 1; int right = min(m, n); int ans = 0; while (left <= right) { int mid = (left + right) / 2; bool ok = check(sum, mid, m, n, threshold); if (ok) { ans = mid; left = mid + 1; } else { right = mid - 1; } } return ans; } }; ================================================ FILE: cpp/1001-10000/1291-1300/Sequential Digits.cpp ================================================ class Solution { public: vector sequentialDigits(int low, int high) { string tmp = "123456789"; vector res; for (int i = 0; i < 9; i++) { for (int j = i+1; j <= 9; j++) { int len = j - i; string str = tmp.substr(i, len); int v = stol(str); if (v >= low && v <= high) res.push_back(v); } } sort(res.begin(), res.end()); return res; } }; ================================================ FILE: cpp/1001-10000/1311-1320/Minimum Distance to Type a Word Using Two Fingers.cpp ================================================ class Solution { int distance(int from, int to) { if (from == 26) return 0; int row_1 = from / 6; int col_1 = from%6; int row_2 = to / 6; int col_2 = to%6; return abs(row_1 - row_2) + abs(col_1 - col_2); } int dfs(vector>>& dp, const string& word, int index, int left, int right) { if (index >= word.length()) return 0; if (dp[left][right][index] != 0) return dp[left][right][index]; char ch = word[index]; int chv = ch - 'A'; int temp = min(dfs(dp, word, index+1, chv, right) + distance(left, chv), dfs(dp, word, index+1, left, chv) + distance(right, chv)); return dp[left][right][index] = temp; } public: int minimumDistance(string word) { vector>> dp(27, vector>(27, vector(301, 0))); return dfs(dp, word, 0, 26, 26); } }; ================================================ FILE: cpp/1001-10000/1411-1420/Minimum Value to Get Positive Step by Step Sum.cpp ================================================ class Solution { public: int minStartValue(vector& nums) { int sum = 0; int minVal = INT_MAX; for (int v : nums) { sum += v; minVal = min(minVal, sum); } return 1 - minVal <= 0 ? 1 : 1 - minVal; } }; ================================================ FILE: cpp/1001-10000/1421-1430/Leftmost Column with at Least a One.cpp ================================================ /** * // This is the BinaryMatrix's API interface. * // You should not implement it, or speculate about its implementation * class BinaryMatrix { * public: * int get(int row, int col); * vector dimensions(); * }; */ class Solution { public: int leftMostColumnWithOne(BinaryMatrix &binaryMatrix) { vector dimension = binaryMatrix.dimensions(); int row = dimension[0]; int col = dimension[1]; int res = -1; for (int i = 0; i < row; i++) { int left = 0; int right = (res == -1 ? col - 1 : res - 1); while (left < right) { int mid = left + (right - left) / 2; if (binaryMatrix.get(i, mid) == 0) { left = mid + 1; } else { right = mid; } } if (binaryMatrix.get(i, left) == 1) { res = left; } } return res; } }; ================================================ FILE: cpp/1001-10000/1481-1490/Avoid Flood in The City.cpp ================================================ class Solution { public: vector avoidFlood(vector& rains) { unordered_map days_to_clear; set available_days; vector ans(rains.size(), 1); for (int i = 0; i < rains.size(); i++) { if (rains[i] == 0) { available_days.insert(i); } else { if (days_to_clear.count(rains[i]) > 0) { auto it = available_days.lower_bound(days_to_clear[rains[i]]); if (it == available_days.end()) { return vector(); } else { ans[*it] = rains[i]; days_to_clear.erase(rains[i]); available_days.erase(it); } } days_to_clear[rains[i]] = i; ans[i] = -1; } } return ans; } }; ================================================ FILE: cpp/1001-10000/1481-1490/Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree.cpp ================================================ class UF { private: vector parent; vector rank; int count; int N; public: UF(int N) : parent(N), rank(N, 0), N(N), count(N) { for (int i = 0; i < N; i++) { parent[i] = i; } } int find(int p) { while (p != parent[p]) { parent[p] = parent[parent[p]]; // path compression by halving p = parent[p]; } return p; } int getCount() const { return count; } bool connected(int p, int q) { return find(p) == find(q); } void Union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make root of smaller rank point to root of larger rank if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ; else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP; else { parent[rootQ] = rootP; rank[rootP]++; } count--; } ~UF() {} }; class Solution { public: vector> findCriticalAndPseudoCriticalEdges(int n, vector>& edges) { vector> all_edges(1001); for (int i = 0; i < edges.size(); i++) { all_edges[edges[i][2]].push_back(i); } vector> ans(2); UF uf(n); for (int i = 1; i <= 1000; i++) { vector candidates; for (int index : all_edges[i]) { const vector& edge = edges[index]; if (!uf.connected(edge[0], edge[1])) { candidates.push_back(index); } } for (int check_index = 0; check_index < candidates.size(); check_index++) { UF copy = uf; for (int k = 0; k < candidates.size(); k++) { if (check_index == k) continue; const vector& k_edge = edges[candidates[k]]; if (!copy.connected(k_edge[0], k_edge[1])) { copy.Union(k_edge[0], k_edge[1]); } } const vector& check_edge = edges[candidates[check_index]]; if (!copy.connected(check_edge[0], check_edge[1])) { ans[0].push_back(candidates[check_index]); } else { ans[1].push_back(candidates[check_index]); } } for (int k = 0; k < candidates.size(); k++) { const vector& current_edge = edges[candidates[k]]; if (!uf.connected(current_edge[0], current_edge[1])) { uf.Union(current_edge[0], current_edge[1]); } } } return ans; } }; ================================================ FILE: cpp/1001-10000/1481-1490/Making File Names Unique.cpp ================================================ class Solution { public: vector getFolderNames(vector& names) { unordered_map visited; vector ans; for (const string& name : names) { if (visited.count(name) == 0) { ans.push_back(name); visited[name]++; } else { int i = visited[name]; while (true) { string new_name = name + "(" + to_string(i) + ")"; if (visited.count(new_name) == 0) { ans.push_back(new_name); visited[name] = i; visited[new_name]++; break; } i++; } } } return ans; } }; ================================================ FILE: cpp/1001-10000/1481-1490/XOR Operation in an Array.cpp ================================================ class Solution { public: int xorOperation(int n, int start) { if (n == 1) return start; int last = start + 2 * (n - 1); if (start % 4 <= 1) { if (n % 4 == 0) return 0; if (n % 4 == 1) return last; if (n % 4 == 2) return 2; else return 2 ^ last; } return start ^ xorOperation(n-1, start + 2); } }; ================================================ FILE: cpp/1001-10000/1501-1510/Stone Game IV.cpp ================================================ class Solution { public: bool winnerSquareGame(int n) { vector dp(n+1, false); dp[0] = false; vector squares; for (int i = 1; i*i <= n; i++) { squares.push_back(i*i); } for (int i = 1; i <= n; i++) { for (int square : squares) { if (i - square < 0) { break; } if (dp[i-square] == false) { dp[i] = true; break; } } } return dp[n]; } }; ================================================ FILE: cpp/1001-10000/1541-1550/Minimum Insertions to Balance a Parentheses String.cpp ================================================ class Solution { public: int minInsertions(string s) { int res = 0; int close_needed = 0; for (int i = 0; i < s.length(); i++) { if (s[i] == '(') { if (close_needed % 2 == 1) { // Handle previous case like '()(' res++; close_needed--; } close_needed += 2; // Add 2 required close for current '(' } else { if (close_needed == 0) { res++; close_needed++; } else { close_needed--; } } } return res + close_needed; } }; ================================================ FILE: cpp/1001-10000/1561-1570/Dot Product of Two Sparse Vectors.cpp ================================================ class SparseVector { public: vector> idx_value_pairs; SparseVector(vector &nums) { for (int i = 0; i < nums.size(); i++) { if (nums[i] == 0) continue; idx_value_pairs.push_back({i, nums[i]}); } } // Return the dotProduct of two sparse vectors int dotProduct(SparseVector& vec) { int i = 0, j = 0; int result = 0; while (i < idx_value_pairs.size() && j < vec.idx_value_pairs.size()) { if (idx_value_pairs[i].first < vec.idx_value_pairs[j].first) { i++; } else if (idx_value_pairs[i].first > vec.idx_value_pairs[j].first) { j++; } else { result += (idx_value_pairs[i].second * vec.idx_value_pairs[j].second); i++; j++; } } return result; } }; // Your SparseVector object will be instantiated and called as such: // SparseVector v1(nums1); // SparseVector v2(nums2); // int ans = v1.dotProduct(v2); ================================================ FILE: cpp/1001-10000/1621-1630/Arithmetic Subarrays.cpp ================================================ class Solution { bool check(const vector& vec) { for (int i = 2; i < vec.size(); i++) { if ((vec[i] - vec[i-1]) != (vec[i-1] - vec[i-2])) return false; } return true; } public: vector checkArithmeticSubarrays(vector& nums, vector& l, vector& r) { vector ans; int m = l.size(); for (int i = 0; i < m; i++) { int a1 = l[i]; int a2 = r[i]; vector tmp(nums.begin()+a1, nums.begin()+a2+1); sort(tmp.begin(), tmp.end()); ans.push_back(check(tmp)); } return ans; } }; ================================================ FILE: cpp/1001-10000/1621-1630/Slowest Key.cpp ================================================ class Solution { public: char slowestKey(vector& releaseTimes, string keysPressed) { int max_time = -1; char ans; for (int i = 0; i < releaseTimes.size(); i++) { int time = (i == 0 ? releaseTimes[0] : releaseTimes[i] - releaseTimes[i-1]); if (time > max_time) { max_time = time; ans = keysPressed[i]; } else if (time == max_time) { ans = max(ans, keysPressed[i]); } } return ans; } }; ================================================ FILE: cpp/1001-10000/1631-1640/Check Array Formation Through Concatenation.cpp ================================================ class Solution { public: bool canFormArray(vector& arr, vector>& pieces) { map mymap; for (int i = 0; i < arr.size(); i++) { mymap[arr[i]] = i; } for (const vector& piece : pieces) { for (int i = 0; i < piece.size(); i++) { if (mymap.count(piece[i]) == 0) { return false; } } } for (const vector& piece : pieces) { for (int i = 1; i < piece.size(); i++) { if (mymap[piece[i-1]] > mymap[piece[i]]) { return false; } } } return true; } }; ================================================ FILE: cpp/1001-10000/1631-1640/Number of Ways to Form a Target String Given a Dictionary.cpp ================================================ class Solution { public: int numWays(vector& words, string target) { int n = target.length(); long mod = 1e9 + 7; vector res(n + 1); res[0] = 1; for (int i = 0; i < words[0].length(); ++i) { vector count(26, 0); for (const string& w : words) { count[w[i] - 'a']++; } for (int j = n - 1; j >= 0; --j) { res[j + 1] += res[j] * count[target[j] - 'a'] % mod; res[j + 1] %= mod; } } return res[n]; } }; ================================================ FILE: cpp/1001-10000/1631-1640/Path With Minimum Effort.cpp ================================================ class Solution { public: int minimumEffortPath(vector>& heights) { int m = heights.size(); int n = heights[0].size(); auto cmp = [](const pair>& a, pair>& b) { return a.first > b.first; }; priority_queue>, vector>>, decltype(cmp)> myqueue(cmp); myqueue.push({0, {0, 0}}); set> visited; while (!myqueue.empty()) { pair> cur = myqueue.top(); myqueue.pop(); int height = cur.first; pair pos = cur.second; if (pos.first == m-1 && pos.second == n-1) return height; if (visited.count(cur.second) > 0) continue; visited.insert(cur.second); pair dirs[4] = {{1,0}, {-1,0}, {0,1}, {0,-1}}; for (pair dir : dirs) { int pos_x = pos.first + dir.first; int pos_y = pos.second + dir.second; if (pos_x < 0 || pos_x >= m || pos_y < 0 || pos_y >= n) continue; int new_height = max(height, abs(heights[pos_x][pos_y] - heights[pos.first][pos.second])); myqueue.push({new_height, {pos_x, pos_y}}); } } return -1; } }; ================================================ FILE: cpp/1001-10000/1631-1640/Rank Transform of a Matrix.cpp ================================================ class UF { private: vector parent; vector rank; int count; int N; bool validate(int p) { return (p >= 0 && p < N); } public: UF(int N) : parent(N), rank(N, 0), N(N), count(N) { for (int i = 0; i < N; i++) { parent[i] = i; } } int find(int p) { if (!validate(p)) return -1; while (p != parent[p]) { parent[p] = parent[parent[p]]; // path compression by halving p = parent[p]; } return p; } int getCount() const { return count; } bool connected(int p, int q) { return find(p) == find(q); } void Union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make root of smaller rank point to root of larger rank if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ; else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP; else { parent[rootQ] = rootP; rank[rootP]++; } count--; } ~UF() {} }; class Solution { vector>> group(const vector>& positions) { int n = positions.size(); UF uf(n); unordered_map> rows; unordered_map> cols; for (int i = 0; i < positions.size(); i++) { pair pos = positions[i]; rows[pos.first].push_back(i); cols[pos.second].push_back(i); } for (auto &it : rows) { vector eles = it.second; for (int i = 1; i < eles.size(); i++) { uf.Union(eles[0], eles[i]); } } for (auto &it : cols) { vector eles = it.second; for (int i = 1; i < eles.size(); i++) { uf.Union(eles[0], eles[i]); } } map>> groups; for (int i = 0; i < n; i++) { groups[uf.find(i)].push_back(positions[i]); } vector>> res; for (auto& it : groups) { res.push_back(it.second); } return res; } public: vector> matrixRankTransform(vector>& matrix) { int m = matrix.size(); int n = matrix[0].size(); map>> mymap; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { int v = matrix[i][j]; mymap[v].push_back({i, j}); } } vector> rank(m, vector(n, 0)); unordered_map rank_x_max; unordered_map rank_y_max; for (auto& it : mymap) { int val = it.first; const vector>& positions = it.second; vector>> positions_group = group(positions); for (const vector>& positions : positions_group) { int current_rank = 1; for (const pair& cur : positions) { int x = cur.first; int y = cur.second; int rank_1 = 1; if (rank_x_max.count(x) > 0) { rank_1 = rank_x_max[x]+1; } int rank_2 = 1; if (rank_y_max.count(y) > 0) { rank_2 = rank_y_max[y]+1; } current_rank = max(current_rank, max(rank_1, rank_2)); } for (const pair& cur : positions) { int x = cur.first; int y = cur.second; rank[x][y] = current_rank; rank_x_max[x] = current_rank; rank_y_max[y] = current_rank; } } } return rank; } }; ================================================ FILE: cpp/1001-10000/1641-1650/Count Sorted Vowel Strings.cpp ================================================ class Solution { public: int countVowelStrings(int n) { map dp; dp['a'] = 1; dp['e'] = 1; dp['i'] = 1; dp['o'] = 1; dp['u'] = 1; for (int i = 1; i < n; i++) { map tmp; tmp['a'] = dp['a']; tmp['e'] = dp['a'] + dp['e']; tmp['i'] = dp['a'] + dp['e'] + dp['i']; tmp['o'] = dp['a'] + dp['e'] + dp['i'] + dp['o']; tmp['u'] = dp['a'] + dp['e'] + dp['i'] + dp['o'] + dp['u']; dp = tmp; } return dp['a'] + dp['e'] + dp['i'] + dp['o'] + dp['u']; } }; ================================================ FILE: cpp/1001-10000/1641-1650/Create Sorted Array through Instructions.cpp ================================================ // Solution 1 class Solution { vector sums; int left(int i) { return 2 * i + 1; } int right(int i) { return 2 * i + 2; } int query(int v_min, int v_max, int l, int r, int root) { if (v_min <= l && v_max >= r) { return sums[root]; } if (v_min > r || v_max < l) { return 0; } int mid = (l+r)/2; return query(v_min, v_max, l, mid, left(root)) + query(v_min, v_max, mid+1, r, right(root)); } void update(int v, int l, int r, int root) { if (v < l || v > r) { return; } sums[root]++; if (l == r) { return; } int mid = (l+r)/2; if (v <= mid) update(v, l, mid, left(root)); else update(v, mid+1, r, right(root)); } public: int createSortedArray(vector& instructions) { long mod = 1e9+7; long cost = 0; int N = *max_element(instructions.begin(), instructions.end()) + 1; sums.resize(4*N+4); vector count(N+1, 0); for (int i = 0; i < instructions.size(); i++) { int v = instructions[i]; int small = query(0, v-1, 0, N-1, 0); int great = i - small -count[v]; cost += min(small, great); cost %= mod; update(v, 0, N-1, 0); count[v]++; } return cost; } }; // Solution 2 class Solution { vector sums; int left(int i) { return 2 * i + 1; } int right(int i) { return 2 * i + 2; } int query(int v_min, int v_max, int l, int r, int root) { if (v_min <= l && v_max >= r) { return sums[root]; } if (v_min > r || v_max < l) { return 0; } int mid = (l+r)/2; return query(v_min, v_max, l, mid, left(root)) + query(v_min, v_max, mid+1, r, right(root)); } void update(int v, int l, int r, int root) { if (v < l || v > r) { return; } sums[root]++; if (l == r) { return; } int mid = (l+r)/2; if (v <= mid) update(v, l, mid, left(root)); else update(v, mid+1, r, right(root)); } public: int createSortedArray(vector& instructions) { long mod = 1e9+7; long cost = 0; int N = *max_element(instructions.begin(), instructions.end()) + 1; sums.resize(4*N+4); for (int v : instructions) { int small = query(0, v-1, 0, N-1, 0); int great = query(v+1, 9999999, 0, N-1, 0); cost += min(small, great); cost %= mod; update(v, 0, N-1, 0); } return cost; } }; ================================================ FILE: cpp/1001-10000/1641-1650/Furthest Building You Can Reach.cpp ================================================ class Solution { public: int furthestBuilding(vector& heights, int bricks, int ladders) { priority_queue, std::greater> myqueue; for (int i = 0; i < heights.size() - 1; i++) { if (heights[i+1] > heights[i]) { myqueue.push(heights[i+1] - heights[i]); } if (myqueue.size() > ladders) { int h = myqueue.top(); myqueue.pop(); bricks -= h; if (bricks < 0) return i; } } return heights.size() - 1; } }; ================================================ FILE: cpp/1001-10000/1641-1650/Get Maximum in Generated Array.cpp ================================================ class Solution { public: int getMaximumGenerated(int n) { vector ans(n+1, 0); int val = 0; for (int i = 0; i <= n; i++) { if (i == 0) ans[i] = 0; else if (i == 1) ans[i] = 1; else if (i % 2 == 0) ans[i] = ans[i/2]; else ans[i] = ans[i/2] + ans[i/2+1]; val = max(val, ans[i]); } return val; } }; ================================================ FILE: cpp/1001-10000/1641-1650/Kth Smallest Instructions.cpp ================================================ class Solution { public: string kthSmallestPath(vector& destination, int k) { int m = destination[0]+1; int n = destination[1]+1; vector> dp(m, vector(n, 0)); dp[m-1][n-1] = 1; for (int i = m - 1; i >= 0; i--) { for (int j = n - 1; j >= 0; j--) { if (i != m -1) dp[i][j] += dp[i+1][j]; if (j != n - 1) dp[i][j] += dp[i][j+1]; } } string ans; int i = 0; int j = 0; while ( !(i == m-1 && j == n-1) ) { if (i == m-1) { ans += 'H'; j++; continue; } else if (j == n-1) { ans += 'V'; i++; continue; } int h = dp[i][j+1]; int v = dp[i+1][j]; if (k <= h) { ans += 'H'; j++; } else { k -= h; ans += 'V'; i++; } } return ans; } }; ================================================ FILE: cpp/1001-10000/1641-1650/Lowest Common Ancestor of a Binary Tree II.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { pair dfs(TreeNode* root, TreeNode* p, TreeNode* q) { if (root == nullptr) { return {nullptr, 0}; } pair l_res = dfs(root->left, p, q); pair r_res = dfs(root->right, p, q); if (root == p || root == q) { return {root, 1 + l_res.second + r_res.second}; } if (l_res.first && r_res.first) { return {root, 2}; } return l_res.first ? l_res : r_res; } public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { pair res = dfs(root, p, q); if (res.second < 2) { return nullptr; } return res.first; } }; ================================================ FILE: cpp/1001-10000/1641-1650/Lowest Common Ancestor of a Binary Tree III.cpp ================================================ /* // Definition for a Node. class Node { public: int val; Node* left; Node* right; Node* parent; }; */ class Solution { public: Node* lowestCommonAncestor(Node* p, Node * q) { Node* a = p, *b = q; while (a != b) { a = (a == nullptr ? q : a->parent); b = (b == nullptr ? p : b->parent); } return a; } }; ================================================ FILE: cpp/1001-10000/1641-1650/Minimum Deletions to Make Character Frequencies Unique.cpp ================================================ class Solution { public: int minDeletions(string s) { map mymap; for (char ch : s) { mymap[ch]++; } set used; int ans = 0; for (const auto& it : mymap) { int freq = it.second; while(used.count(freq) > 0) { freq--; ans++; } if (freq > 0) { used.insert(freq); } } return ans; } }; ================================================ FILE: cpp/1001-10000/1641-1650/Sell Diminishing-Valued Colored Balls.cpp ================================================ class Solution { long get(long a, long b) { return (a+b) * (b-a+1) / 2; } public: int maxProfit(vector& inventory, int orders) { int n = inventory.size(); long mod = 1e9+7; long ans = 0; map mymap; for (int v : inventory) { mymap[v]++; } priority_queue> myqueue; for (const auto& it : mymap) { myqueue.push({it.first, it.second}); } while (orders > 0) { pair top = myqueue.top(); myqueue.pop(); pair second; bool has_second = false; long to_num = 0; if (myqueue.size() > 0) { has_second = true; second = myqueue.top(); myqueue.pop(); to_num = second.first; } long from_num = top.first; long from_freq = top.second; int total_orders = (from_num - to_num) * from_freq; if (total_orders > orders) { int consume = orders/from_freq; to_num = from_num - consume; ans += (get(to_num+1, from_num) % mod) * from_freq % mod; orders -= from_freq*consume; while (orders > 0) { ans += to_num; ans %= mod; orders--; } } else { ans += (get(to_num+1, from_num) % mod) * from_freq % mod; orders -= total_orders; myqueue.push({to_num, from_freq+second.second}); } } ans %= mod; return ans; } }; ================================================ FILE: cpp/1001-10000/1671-1680/Lowest Common Ancestor of a Binary Tree IV.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { TreeNode* lowestCommonAncestor(TreeNode* root, const set& nodes_set) { if (root == nullptr) { return nullptr; } if (nodes_set.count(root) > 0) { return root; } TreeNode* l = lowestCommonAncestor(root->left, nodes_set); TreeNode* r = lowestCommonAncestor(root->right, nodes_set); if (l && r) { return root; } return l ? l : r; } public: TreeNode* lowestCommonAncestor(TreeNode* root, vector &nodes) { setnodes_set(nodes.begin(), nodes.end()); return lowestCommonAncestor(root, nodes_set); } }; ================================================ FILE: cpp/1001-10000/1671-1680/Minimum Moves to Make Array Complementary.cpp ================================================ class Solution { public: int minMoves(vector& nums, int limit) { int n = nums.size(); vector delta(2*limit+2, 0); for (int i = 0; i < n/2; i++) { int a = min(nums[i], nums[n-1-i]); int b = max(nums[i], nums[n-1-i]); delta[2] += 2; delta[a + 1]--; delta[a + b]--; delta[a + b + 1]++; delta[b + limit + 1]++; } int res = 2 * n; int curr = 0; for (int i = 2; i <= 2 * limit; i++) { curr += delta[i]; res = min(res, curr); } return res; } }; ================================================ FILE: cpp/1001-10000/1681-1690/Delivering Boxes from Storage to Ports.cpp ================================================ class Solution { public: int boxDelivering(vector>& boxes, int portsCount, int maxBoxes, int maxWeight) { int n = boxes.size(); vector dp(n+1, INT_MAX); dp[0] = 0; int weight = 0; int trips = 2; int left = 0; for (int right = 0; right < n; right++) { weight += boxes[right][1]; // If current box is different than previous one, need to make one more trip. if (right > 0 && boxes[right][0] != boxes[right-1][0]) { trips++; } while ((right - left) >= maxBoxes || weight > maxWeight || (left < right && dp[left] == dp[left+1])) { weight -= boxes[left][1]; if (boxes[left][0] != boxes[left+1][0]) { trips--; } left++; } dp[right+1] = dp[left] + trips; } return dp.back(); } }; ================================================ FILE: cpp/1001-10000/1681-1690/Stone Game VI.cpp ================================================ class Solution { public: int stoneGameVI(vector& aliceValues, vector& bobValues) { vector> values; for (int i = 0; i < aliceValues.size(); i++) { values.push_back({aliceValues[i], bobValues[i]}); } auto cmp = [](const pair& l, const pair& r) { return (l.first+l.second) > (r.first+r.second); }; sort(values.begin(), values.end(), cmp); int alice = 0; int bob = 0; for (int i = 0; i < values.size(); i++) { if (i % 2 == 0) { alice += values[i].first; } else { bob += values[i].second; } } if (alice > bob) return 1; else if (alice < bob) return -1; return 0; } }; ================================================ FILE: cpp/1001-10000/1681-1690/Sum of Absolute Differences in a Sorted Array.cpp ================================================ class Solution { public: vector getSumAbsoluteDifferences(vector& nums) { vector ans; int tmp = 0; for (int i = 1; i < nums.size(); i++) { tmp += (nums[i] - nums[0]); } ans.push_back(tmp); for (int i = 1; i < nums.size(); i++) { int diff = (nums[i] - nums[i-1]); int left = i - 1; int right = nums.size() - left - 2; tmp += (left*diff - right*diff); ans.push_back(tmp); } return ans; } }; ================================================ FILE: cpp/1001-10000/1701-1710/Determine if String Halves Are Alike.cpp ================================================ class Solution { public: bool halvesAreAlike(string s) { map mymap; int n = s.length()/2; for (int i = 0; i < n; i++) { mymap[tolower(s[i])]++; } for (int i = n; i < s.length(); i++) { mymap[tolower(s[i])]--; } return (mymap['a'] + mymap['e'] + mymap['i'] + mymap['o'] + mymap['u']) == 0; } }; ================================================ FILE: cpp/1001-10000/1701-1710/Maximum Number of Eaten Apples.cpp ================================================ class Solution { public: int eatenApples(vector& apples, vector& days) { auto cmp = [](const pair& l, const pair& r) { return l.first > r.first; }; priority_queue, vector>, decltype(cmp)> pq(cmp); int n = apples.size(); int ans = 0; int i = 0; for (; i < n; i++) { if (apples[i] > 0) { pq.push({i+days[i], apples[i]}); } while (!pq.empty()) { pair ele = pq.top(); pq.pop(); if (ele.first > i) { ans++; ele.second--; if (ele.second > 0) { pq.push(ele); } break; } } } while (!pq.empty()) { pair ele = pq.top(); pq.pop(); if (ele.first > i) { ans++; ele.second--; if (ele.second > 0) { pq.push(ele); } i++; } } return ans; } }; ================================================ FILE: cpp/1001-10000/1701-1710/Maximum Units on a Truck.cpp ================================================ class Solution { public: int maximumUnits(vector>& boxTypes, int truckSize) { auto cmp = [](const vector& l, const vector& r) { return l[1] > r[1]; }; sort(boxTypes.begin(), boxTypes.end(), cmp); int ans = 0; for (int i = 0; i < boxTypes.size(); i++) { if (truckSize <= 0) { break; } int num = boxTypes[i][0]; int units = boxTypes[i][1]; ans += min(num, truckSize) * units; truckSize = max(0, truckSize - num); } return ans; } }; ================================================ FILE: cpp/1001-10000/1701-1710/Maximum XOR With an Element From Array.cpp ================================================ class Solution { class TreeNode { public: TreeNode* next[2]; TreeNode () {next[0] = nullptr; next[1] = nullptr;}; }; TreeNode* buildTree(vector& nums) { TreeNode* root = new TreeNode(), *cur; int n = nums.size(); for (int i = 0; i < n; i++) { int num = nums[i]; cur = root; for (int j = 31; j >= 0; j--) { int index = ((num >> j) & 1); if (cur->next[index] == nullptr) cur->next[index] = new TreeNode(); cur = cur->next[index]; } } return root; } int dfs(TreeNode* root, int x, int limit, int value, int height) { if (value > limit) return -1; if (height == -1) return x^value; int bit_x = (x >> height) & 1; if (root->next[1-bit_x] != nullptr) { int v = dfs(root->next[1-bit_x], x, limit, (value | ((1-bit_x) << height)), height-1); if (v >= 0) return v; } if (root->next[bit_x] != nullptr) { int v = dfs(root->next[bit_x], x, limit, (value | (bit_x << height)), height-1); if (v >= 0) return v; } return -1; } public: vector maximizeXor(vector& nums, vector>& queries) { vector ans; TreeNode* root = buildTree(nums); for (const vector& query : queries) { int tmp = dfs(root, query[0], query[1], 0, 31); ans.push_back(tmp); } return ans; } }; ================================================ FILE: cpp/1001-10000/1701-1710/Where Will the Ball Fall.cpp ================================================ class Solution { public: vector findBall(vector>& grid) { vector ans; int m = grid.size(); int n = grid.front().size(); for (int i = 0; i < n; i++) { int row = 0; int col = i; while(row < m) { if (grid[row][col] == 1) { if (col == n-1 || grid[row][col+1] == -1) break; col++; } else { if (col == 0 || grid[row][col-1] == 1) break; col--; } row++; } ans.push_back(row == m ? col : -1); } return ans; } }; ================================================ FILE: cpp/1001-10000/1711-1720/Count Good Meals.cpp ================================================ class Solution { public: int countPairs(vector& deliciousness) { vector delicious_vec; int base = 1; for (int i = 0; i <= 21; i++) { delicious_vec.push_back(base); base *= 2; } reverse(delicious_vec.begin(), delicious_vec.end()); unordered_map mymap; long answer = 0; for (int d : deliciousness) { for (int sum : delicious_vec) { int target = sum - d; if (target < 0) break; answer += mymap[target]; } mymap[d]++; } long mod = 1e9+7; answer = answer % mod; return answer; } }; ================================================ FILE: cpp/1001-10000/1711-1720/Decode XORed Array.cpp ================================================ class Solution { public: vector decode(vector& encoded, int first) { vector ans; ans.push_back(first); for (int i = 0; i < encoded.size(); i++) { ans.push_back(ans[i] ^ encoded[i]); } return ans; } }; ================================================ FILE: cpp/1001-10000/1711-1720/Minimum Operations to Make a Subsequence.cpp ================================================ class Solution { int lengthOfLIS(vector& nums) { vector res; for(int i=0; i& target, vector& arr) { unordered_map mymap; int base = 1; for (int t : target) { mymap[t] = base; base++; } vector new_arr; for (int e : arr) { if (mymap.count(e) > 0) { new_arr.push_back(mymap[e]); } } return target.size() - lengthOfLIS(new_arr); } }; ================================================ FILE: cpp/1001-10000/1711-1720/Ways to Split Array Into Three Subarrays.cpp ================================================ class Solution { public: int waysToSplit(vector& nums) { int n = nums.size(); vector sums; int sum = 0; for (int num : nums) { sum += num; sums.push_back(sum); } long ans = 0; long mod = 1e9+7; int sum_left = 0; int j = 0; int k = 0; for (int i = 0; i < n; i++) { sum_left += nums[i]; if (sum_left*3 > sum) break; j = max(j, i+1); while (j < n-1 && ((sums[j] - sums[i]) < sum_left)) j++; int sum_remain = sum - sum_left; k = max(k, j); while (k < n-1) { int l = sums[k] - sums[i]; int r = sum_remain - l; if (l > r) { break; } else k++; } ans += (k - j); } return ans % mod; } }; class Solution { public: int waysToSplit(vector& nums) { int n = nums.size(); vector sums; int sum = 0; for (int num : nums) { sum += num; sums.push_back(sum); } long ans = 0; long mod = 1e9+7; int sum_left = 0; for (int left = 0; left < n; left++) { sum_left += nums[left]; auto it1 = lower_bound(sums.begin()+left+1, sums.end(), 2*sum_left); if (it1 == sums.end()) break; int target = (sum - sum_left )/2 + sum_left; auto it2 = upper_bound(it1, --sums.end(), target); if (it2 == sums.end()) break; ans += (it2 - it1); } return ans % mod; } }; ================================================ FILE: cpp/1001-10000/1721-1730/Find Minimum Time to Finish All Jobs.cpp ================================================ class Solution { int ans; void dfs(vector& jobs, int k, vector& workers, int curr) { if (curr == jobs.size()) { ans = min(ans, *max_element(workers.begin(), workers.end())); return; } set seen; for (int i = 0; i < k; i++) { if (seen.count(workers[i]) > 0) continue; if (workers[i] + jobs[curr] >= ans) continue; seen.insert(workers[i]); workers[i] += jobs[curr]; dfs(jobs, k, workers, curr+1); workers[i] -= jobs[curr]; } } public: int minimumTimeRequired(vector& jobs, int k) { int n = jobs.size(); vector workers(k, 0); ans = INT_MAX; dfs(jobs, k, workers, 0); return ans; } }; ================================================ FILE: cpp/1001-10000/1721-1730/Largest Submatrix With Rearrangements.cpp ================================================ class Solution { public: int largestSubmatrix(vector>& matrix) { int m = matrix.size(); int n = matrix[0].size(); for (int j = 0; j < n; j++) { for (int i = m-1; i >= 0; i--) { if (matrix[i][j] == 1 && i != (m-1)) { matrix[i][j] = 1 + matrix[i+1][j]; } } } int ans = 0; for (int i = 0; i < m; i++) { sort(matrix[i].begin(), matrix[i].end(), std::greater()); for (int w = 0; w < matrix[i].size(); w++) { if (matrix[i][w] == 0) break; ans = max(ans, (w+1) * matrix[i][w]); } } return ans; } }; ================================================ FILE: cpp/1001-10000/1721-1730/Minimize Hamming Distance After Swap Operations.cpp ================================================ class UF { private: vector parent; vector rank; int count; int N; bool validate(int p) { return (p >= 0 && p < N); } public: UF(int N) : parent(N), rank(N, 0), N(N), count(N) { for (int i = 0; i < N; i++) { parent[i] = i; } } int find(int p) { if (!validate(p)) return -1; while (p != parent[p]) { parent[p] = parent[parent[p]]; // path compression by halving p = parent[p]; } return p; } int getCount() const { return count; } bool connected(int p, int q) { return find(p) == find(q); } void Union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make root of smaller rank point to root of larger rank if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ; else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP; else { parent[rootQ] = rootP; rank[rootP]++; } count--; } ~UF() {} }; class Solution { public: int minimumHammingDistance(vector& source, vector& target, vector>& allowedSwaps) { int n = source.size(); int ans = n; UF uf(n); for (const vector& allowedSwap : allowedSwaps) { uf.Union(allowedSwap[0], allowedSwap[1]); } unordered_map> groups; for (int i = 0; i < n; i++) { int parent = uf.find(i); groups[parent].push_back(i); } unordered_map visited; for (int i = 0; i < n; i++) { int parent = uf.find(i); if (visited[parent]) { continue; } vector group = groups[parent]; unordered_map mymap; for (int index : group) { mymap[target[index]]++; } for (int index : group) { if (mymap[source[index]] > 0) { mymap[source[index]]--; ans--; } } visited[parent] = true; } return ans; } }; ================================================ FILE: cpp/1001-10000/1721-1730/Number Of Rectangles That Can Form The Largest Square.cpp ================================================ class Solution { public: int countGoodRectangles(vector>& rectangles) { unordered_map mymap; int max_square = 0; for (const vector& rec : rectangles) { int v = *min_element(rec.begin(), rec.end()); max_square = max(max_square, v); mymap[v]++; } return mymap[max_square]; } }; ================================================ FILE: cpp/1001-10000/1721-1730/Swapping Nodes in a Linked List.cpp ================================================ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* swapNodes(ListNode* head, int k) { ListNode* l1 = head, *l2 = head; for (int i = 1; i < k; i++) { l1 = l1->next; } int len = 0; while (l2 != nullptr) { len++; l2 = l2->next; } l2 = head; for (int i = 1; i <= (len - k); i++) { l2 = l2->next; } swap(l1->val, l2->val); return head; } }; ================================================ FILE: cpp/1001-10000/1721-1730/Tuple with Same Product.cpp ================================================ class Solution { public: int tupleSameProduct(vector& nums) { unordered_map mymap; for (int i = 0; i < nums.size(); i++) { for (int j = i+1; j < nums.size(); j++) { mymap[nums[i] * nums[j]]++; } } int ans = 0; for (const auto& pair : mymap) { if (pair.second > 1) { int v = pair.second; int tmp = v * (v-1) * 4; ans += tmp; } } return ans; } }; ================================================ FILE: cpp/1001-10000/1731-1740/Building Boxes.cpp ================================================ class Solution { public: int minimumBoxes(int n) { int ans = 0; int tmp = 0; for (int i = 1;;i++) { tmp += i; if (n <= tmp) { int k = 1; while (n > 0) { n -= k; ans++; k++; } break; } n -= tmp; ans += i; } return ans; } }; ================================================ FILE: cpp/1001-10000/1751-1760/Closest Subsequence Sum.cpp ================================================ class Solution { public: int maxValue(vector>& events, int k) { auto cmp = [](const vector& lhs, const vector& rhs) { return lhs[1] < rhs[1]; }; sort(events.begin(), events.end(), cmp); int n = events.size(); vector> dp(n+1, vector(k+1, 0)); for (int i = 1; i <= n; i++) { int non_overlap_index = 0; for (int l = i - 1; l >= 1; l--) { if (events[l-1][1] < events[i-1][0]) { non_overlap_index = l; break; } } for (int j = 1; j <= k; j++) { dp[i][j] = max(dp[non_overlap_index][j-1] + events[i-1][2], dp[i-1][j]); } } return dp[n][k]; } }; ================================================ FILE: cpp/1001-10000/1751-1760/Largest Merge Of Two Strings.cpp ================================================ class Solution { public: string largestMerge(string word1, string word2) { string ans; int i = 0, j = 0; while(i < word1.size() && j < word2.size()) { if(word1.substr(i) > word2.substr(j)) { ans.push_back(word1[i]); i++; } else { ans.push_back(word2[j]); j++; } } if(i == word1.size()) { ans += word2.substr(j); } else if(j == word2.size()) { ans += word1.substr(i); } return ans; } }; ================================================ FILE: cpp/1001-10000/1751-1760/Maximum Number of Events That Can Be Attended II.cpp ================================================ class Solution { public: int maxValue(vector>& events, int k) { auto cmp = [](const vector& lhs, const vector& rhs) { return lhs[1] < rhs[1]; }; sort(events.begin(), events.end(), cmp); int n = events.size(); vector> dp(n+1, vector(k+1, 0)); for (int i = 1; i <= n; i++) { int non_overlap_index = 0; for (int l = i - 1; l >= 1; l--) { if (events[l-1][1] < events[i-1][0]) { non_overlap_index = l; break; } } for (int j = 1; j <= k; j++) { dp[i][j] = max(dp[non_overlap_index][j-1] + events[i-1][2], dp[i-1][j]); } } return dp[n][k]; } }; ================================================ FILE: cpp/1001-10000/1751-1760/Minimum Limit of Balls in a Bag.cpp ================================================ class Solution { bool check(const vector& nums, int maxOperations, int penalty) { int ops = 0; for (int num : nums) { ops += (num-1) / penalty; } return ops <= maxOperations; } public: int minimumSize(vector& nums, int maxOperations) { int left = 1, right = *max_element(nums.begin(), nums.end()); while (left < right) { int mid = (left + right) / 2; bool can_do_it = check(nums, maxOperations, mid); if (can_do_it) { right = mid; } else { left = mid + 1; } } return left; } }; ================================================ FILE: cpp/1001-10000/1761-1770/Form Array by Concatenating Subarrays of Another Array.cpp ================================================ class Solution { int MatchGroup(const vector& group, const vector& nums, int index) { for (int start = index; start <= nums.size() - group.size(); start++) { bool match = true; for (int l = 0; l < group.size(); l++) { if (group[l] != nums[start+l]) { match = false; break; } } if (match) { return start + group.size(); } } return -1; } public: bool canChoose(vector>& groups, vector& nums) { int index = 0; for (const vector& group : groups) { index = MatchGroup(group, nums, index); if (index < 0) { return false; } } return true; } }; ================================================ FILE: cpp/1001-10000/1761-1770/Map of Highest Peak.cpp ================================================ class Solution { public: vector> highestPeak(vector>& isWater) { int m = isWater.size(); int n = isWater.front().size(); vector> result(m, vector(n, -1)); queue> myqueue; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (isWater[i][j] == 1) { myqueue.push({i, j}); result[i][j] = 0; } } } int cur_height = 0; while (!myqueue.empty()) { int total = myqueue.size(); for (int k = 0; k < total; k++) { pair pos = myqueue.front(); myqueue.pop(); pair directions[4] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; for (pair direction : directions) { int new_pos_x = pos.first + direction.first; int new_pos_y = pos.second + direction.second; if (new_pos_x < 0 || new_pos_x >= m|| new_pos_y < 0 || new_pos_y >= n || result[new_pos_x][new_pos_y] != -1) { continue; } myqueue.push({new_pos_x, new_pos_y}); result[new_pos_x][new_pos_y] = cur_height + 1; } } cur_height++; } return result; } }; ================================================ FILE: cpp/1001-10000/1761-1770/Maximum Score from Performing Multiplication Operations.cpp ================================================ class Solution { public: int maximumScore(vector& nums, vector& multipliers) { int n = nums.size(); int m = multipliers.size(); vector> dp(m+1, vector(m+1, 0)); int score = INT_MIN; for (int k = 1; k <= m; k++) { for (int l = 0; l <= k; l++) { int pick_left = (l == 0 ? INT_MIN : dp[l-1][k-l] + multipliers[k-1] * nums[l-1]); int pick_right = (l == k ? INT_MIN : dp[l][k-l-1] + multipliers[k-1] * nums[n-k+l]); dp[l][k-l] = max(pick_left, pick_right); if (k == m) { score = max(score, dp[l][k-l]); } } } return score; } }; ================================================ FILE: cpp/1001-10000/1761-1770/Minimum Degree of a Connected Trio in a Graph.cpp ================================================ class Solution { public: int minTrioDegree(int n, vector>& edges) { vector> graph(n+1); for (const vector& edge : edges) { graph[edge[0]].insert(edge[1]); graph[edge[1]].insert(edge[0]); } int ans = INT_MAX; for (int i = 1; i <= n; i++) { const unordered_set& neighbors = graph[i]; int tmp_a = graph[i].size() - 2; if (tmp_a >= ans) { continue; } for (int b : neighbors) { int tmp_b = tmp_a + graph[b].size() - 2; if (b < i || tmp_b >= ans) { continue; } for (int c : graph[b]) { if (neighbors.count(c) > 0) { ans = min(ans, tmp_b + (int)graph[c].size() - 2); } } } } return ans == INT_MAX? -1 : ans; } }; ================================================ FILE: cpp/1001-10000/1761-1770/Tree of Coprimes.cpp ================================================ class Solution { void dfs(int node, const vector& nums, const vector>& graph, vector& result, map>& ancestors /*value, {node, depth}*/, int depth, int parent) { int closest_ancestor = -1; int distance = INT_MAX; for (const auto& pair : ancestors) { if (__gcd(nums[node], pair.first) == 1 && (depth - pair.second.second) < distance) { distance = depth - pair.second.second; closest_ancestor = pair.second.first; } } result[node] = closest_ancestor; bool has_original_node = (ancestors.count(nums[node])) > 0; pair original_node = ancestors[nums[node]]; ancestors[nums[node]] = {node, depth}; for (int neighbor : graph[node]) { if (neighbor == parent) { continue; } dfs(neighbor, nums, graph, result, ancestors, depth + 1, node); } ancestors.erase(nums[node]); if (has_original_node) { ancestors[nums[node]] = original_node; } } public: vector getCoprimes(vector& nums, vector>& edges) { int n = nums.size(); vector> graph(n); for (const vector& edge : edges) { graph[edge[0]].push_back(edge[1]); graph[edge[1]].push_back(edge[0]); } map> ancestors; vector result(n, -1); dfs(/*node=*/0, nums, graph, result, ancestors, /*depth=*/0, /*parent=*/-1); return result; } }; ================================================ FILE: cpp/1001-10000/1771-1780/Car Fleet II.cpp ================================================ class Solution { public: vector getCollisionTimes(vector>& cars) { vector result(cars.size(), -1.0); stack mystack; for (int i = cars.size() - 1; i >= 0; i--) { // We don't need faster cars behind current car. while (!mystack.empty() && cars[i][1] <= cars[mystack.top()][1]) { mystack.pop(); } while (!mystack.empty()) { int candidate = mystack.top(); double current_time = 1.0 * (cars[candidate][0] - cars[i][0]) / (cars[i][1] - cars[candidate][1]); if (current_time <= result[candidate] || result[candidate] < 0) { result[i] = current_time; break; } // This car will collide with cars after candidate. mystack.pop(); } mystack.push(i); } return result; } }; ================================================ FILE: cpp/1001-10000/1771-1780/Check if Number is a Sum of Powers of Three.cpp ================================================ class Solution { public: bool checkPowersOfThree(int n) { int tmp = 3; while (tmp < n) { tmp *= 3; } while (tmp > 0) { if (n >= tmp) { n -= tmp; } tmp = tmp/3; } return n == 0; } }; ================================================ FILE: cpp/1001-10000/1771-1780/Closest Dessert Cost.cpp ================================================ class Solution { public: int closestCost(vector& baseCosts, vector& toppingCosts, int target) { bool table[20010] = {false}; int ans = -999999; for (int base : baseCosts) { table[base] = true; } for (int cost : toppingCosts) { for (int k = 1; k <= 2; k++) { for (int v = 20000; v >= 0; v--) { if (v - cost >= 0 && table[v - cost] == true) { table[v] = true; } } } } for (int i = 1; i <= 20001; i++) { if (table[i] == true && abs(i - target) < abs(ans - target)) { ans = i; } } return ans; } }; ================================================ FILE: cpp/1001-10000/1771-1780/Equal Sum Arrays With Minimum Number of Operations.cpp ================================================ class Solution { int process(int* table1, int* table2, int diff) { int ans = 0; for (int k = 1; k <= 5 && diff > 0; k++) { int contrib = 6 - k; while (table2[k] > 0 && diff > 0) { diff -= contrib; ans++; table2[k]--; } while (table1[7 - k] > 0 && diff > 0) { diff -= contrib; ans++; table1[7 - k]--; } } return ans; } public: int minOperations(vector& nums1, vector& nums2) { if (6 * nums1.size() < nums2.size()) return -1; if (6 * nums2.size() < nums1.size()) return -1; int sum1 = 0; int table1[7] = {0}; int sum2 = 0; int table2[7] = {0}; for (int num : nums1) { sum1 += num; table1[num]++; } for (int num : nums2) { sum2 += num; table2[num]++; } if (sum1 == sum2) return 0; else if (sum1 > sum2) return process(table1, table2, sum1 - sum2); else return process(table2, table1, sum2 - sum1); } }; ================================================ FILE: cpp/1001-10000/1771-1780/Find Nearest Point That Has the Same X or Y Coordinate.cpp ================================================ class Solution { public: int nearestValidPoint(int x, int y, vector>& points) { int index = -1; int distance = INT_MAX; for (int i = 0; i < points.size(); i++) { if (x == points[i][0] || y == points[i][1]) { int current_dis = abs(x - points[i][0]) + abs(y - points[i][1]); if (current_dis < distance) { distance = current_dis; index = i; } } } return index; } }; ================================================ FILE: cpp/1001-10000/1771-1780/Maximize Palindrome Length From Subsequences.cpp ================================================ class Solution { public: int longestPalindrome(string word1, string word2) { string s = word1 + word2; int n = s.size(); vector> dp(n, vector(n,0)); int res = 0; for (int i = n - 1; i >= 0; i--) { dp[i][i] = 1; for (int j = i + 1; j < n; j++) { if (s[i]==s[j]) { dp[i][j] = dp[i+1][j-1] + 2; if (i < word1.length() && j >= word1.length()) { res = max(res, dp[i][j]); } } else { dp[i][j] = max(dp[i+1][j], dp[i][j-1]); } } } return res; } }; ================================================ FILE: cpp/1001-10000/1771-1780/Shortest Path in a Hidden Grid.cpp ================================================ /** * // This is the GridMaster's API interface. * // You should not implement it, or speculate about its implementation * class GridMaster { * public: * bool canMove(char direction); * void move(char direction); * boolean isTarget(); * }; */ class Solution { public: // 0 is blocked, 1 is empty, 2 is target void ConstructGrid(vector>& grid, GridMaster &master, int row, int col, const map>& directions) { grid[row][col] = 1; if (master.isTarget()) { grid[row][col] = 2; } for (const auto& direction : directions) { int new_row = row + direction.second.first; int new_col = col + direction.second.second; if (grid[new_row][new_col] != -1) { continue; } if (master.canMove(direction.first)) { master.move(direction.first); ConstructGrid(grid, master, new_row, new_col, directions); if (direction.first == 'U') master.move('D'); else if (direction.first == 'D') master.move('U'); else if (direction.first == 'L') master.move('R'); else master.move('L'); } else { grid[new_row][new_col] = 0; } } } int findShortestPath(GridMaster &master) { map> directions = { {'U', {0, 1}}, {'D', {0, -1}}, {'L', {-1, 0}}, {'R', {1, 0}}, }; vector> grid(1001, vector(1001, -1)); ConstructGrid(grid, master, 501, 501, directions); queue> myqueue; myqueue.push({501, 501}); grid[501][501] = 0; int distance = 1; while (!myqueue.empty()) { int queue_size = myqueue.size(); for (int k = 0; k < queue_size; k++) { pair cur = myqueue.front(); myqueue.pop(); for (const auto& direction : directions) { int new_row = cur.first + direction.second.first; int new_col = cur.second + direction.second.second; if (grid[new_row][new_col] == 2) { return distance; } if (grid[new_row][new_col] <= 0) { continue; } // Mark as 'visited'. grid[new_row][new_col] = 0; myqueue.push({new_row, new_col}); } } distance++; } return -1; } }; ================================================ FILE: cpp/1001-10000/1781-1790/Check if Binary String Has at Most One Segment of Ones.cpp ================================================ class Solution { public: bool checkOnesSegment(string s) { return s.find("01") == string::npos; } }; ================================================ FILE: cpp/1001-10000/1781-1790/Check if One String Swap Can Make Strings Equal.cpp ================================================ class Solution { public: bool areAlmostEqual(string s1, string s2) { int idx1 = -1, idx2 = -1; for (int i = 0; i < s1.length(); i++) { if (s1[i] != s2[i]) { if (idx1 == -1) { idx1 = i; } else if (idx2 == -1) { idx2 = i; } else { return false; } } } if (idx1 < 0 && idx2 < 0) return true; if (idx2 < 0) return false; if (s1[idx1] == s2[idx2] && s1[idx2] == s2[idx1]) return true; return false; } }; ================================================ FILE: cpp/1001-10000/1781-1790/Count Pairs Of Nodes.cpp ================================================ class Solution { public: vector countPairs(int n, vector>& edges, vector& queries) { vector sizes(n+1, 0); vector> graph(n + 1); for (const vector& edge : edges) { graph[edge[0]][edge[1]]++; graph[edge[1]][edge[0]]++; sizes[edge[0]]++; sizes[edge[1]]++; } vector prefix_sum(100001, 0); for (int i = 1; i < sizes.size(); i++) { prefix_sum[sizes[i]]++; } for (int i = 100000; i >= 1; i--) { prefix_sum[i-1] += prefix_sum[i]; } vector answer; for (int query : queries) { int total = 0; for (int i = 1; i <= n; i++) { const unordered_map& mymap = graph[i]; int target = query - sizes[i]; int current = 0; for (const auto& it : mymap) { int neighbor = it.first; if (sizes[neighbor] > target) { current--; } int count = sizes[i] + sizes[neighbor] - it.second; if (count > query) { current++; } } if (sizes[i] > target) { current--; } current += prefix_sum[target < 0 ? 0 : target+1]; total += current; } answer.push_back(total / 2); } return answer; } }; ================================================ FILE: cpp/1001-10000/1781-1790/Make the XOR of All Segments Equal to Zero.cpp ================================================ class Solution { public: int minChanges(vector& nums, int k) { int n = nums.size(); vector> freq(k, vector(1025, 0)); for (int i = 0; i < n; i++) { freq[i%k][nums[i]]++; } vector> dp(k + 1, vector(1025, 2001)); dp[0][0] = 0; for (int i = 0; i < k; i++) { int total = (n + k - i - 1) / k; int previous_minimum_changes = *min_element(dp[i].begin(), dp[i].end()); for (int target = 0; target <= 1024; target++) { dp[i+1][target] = total + previous_minimum_changes; for (int index = i; index < n; index += k) { int picked = nums[index]; int previous_target = picked ^ target; if (previous_target > 1024) { continue; } dp[i+1][target] = min(dp[i+1][target], dp[i][previous_target] + total - freq[i][picked]); } } } return dp[k][0]; } }; ================================================ FILE: cpp/1001-10000/1781-1790/Maximize the Beauty of the Garden.cpp ================================================ class Solution { public: int maximumBeauty(vector& flowers) { unordered_map mymap; int res = INT_MIN; int sum = 0; for (int beauty : flowers) { if (mymap.count(beauty) > 0) { res = max(res, sum - mymap[beauty] + 2 * beauty); } if (beauty > 0) { sum += beauty; } if (mymap.count(beauty) == 0) { mymap[beauty] = sum; } } return res; } }; ================================================ FILE: cpp/1001-10000/1781-1790/Minimum Elements to Add to Form a Given Sum.cpp ================================================ class Solution { public: int minElements(vector& nums, int limit, int goal) { long sum = 0; for (int num : nums) { sum += num; } return (abs(goal - sum) + limit - 1) / limit; } }; ================================================ FILE: cpp/1001-10000/1781-1790/Number of Restricted Paths From First to Last Node.cpp ================================================ class Solution { public: void bfs(int n, const vector>>& graph, vector& distances, vector& closest_nodes) { auto cmp = [](const pair &a, const pair &b) { return a.second > b.second; }; priority_queue, vector>, decltype(cmp)> pq(cmp); vector visited(n+1, false); pq.push({n, 0}); while (!pq.empty()) { pair current = pq.top(); pq.pop(); int node = current.first; int dis = current.second; if (visited[node] == true) { continue; } distances[node] = dis; visited[node] = true; closest_nodes.push_back(node); for (pair neighbor : graph[node]) { int neighbor_node = neighbor.first; if (visited[neighbor_node] == false) { pq.push({neighbor_node, dis + neighbor.second}); } } } } int countRestrictedPaths(int n, vector>& edges) { vector>> graph(n+1); for (const vector& edge : edges) { graph[edge[0]].push_back({edge[1], edge[2]}); graph[edge[1]].push_back({edge[0], edge[2]}); } vector distances(n + 1, 0); vector closest_nodes; bfs(n, graph, distances, closest_nodes); vector dp(n+1, 0); dp[1] = 1; int mod = 1e9+7; for (int i = closest_nodes.size() - 1; i >= 0; i--) { int node = closest_nodes[i]; for (pair neighbor : graph[node]) { int neighbor_node = neighbor.first; if (distances[neighbor_node] < distances[node]) { dp[neighbor_node] += dp[node]; dp[neighbor_node] %= mod; } } } return dp[n]; } }; ================================================ FILE: cpp/1001-10000/1781-1790/Sum of Beauty of All Substrings.cpp ================================================ class Solution { public: int beautySum(string s) { int answer = 0; for (int i = 0; i < s.length(); i++) { int array[26] = {0}; for (int j = i; j < s.length(); j++) { char ch = s[j]; array[ch-'a']++; int maximum = INT_MIN; int minimum = INT_MAX; int diff_chars = 0; for (int k = 0; k < 26; k++) { maximum = max(maximum, array[k]); if (array[k] > 0) { minimum = min(minimum, array[k]); diff_chars++; } } if (diff_chars >= 2) { answer += (maximum - minimum); } } } return answer; } }; ================================================ FILE: cpp/1001-10000/1791-1800/Count Pairs of Equal Substrings With Minimum Difference.cpp ================================================ class Solution { public: int countQuadruples(string firstString, string secondString) { unordered_map last_occurence; for (int i = 0; i < secondString.length(); i++) { last_occurence[secondString[i]] = i; } int minimum_j_minus_a = INT_MAX; int cnt = 0; for (int i = 0; i < firstString.length(); i++) { char ch = firstString[i]; if (last_occurence.count(ch) > 0) { int j_minus_a = i - last_occurence[ch]; if (j_minus_a < minimum_j_minus_a) { minimum_j_minus_a = j_minus_a; cnt = 1; } else if (j_minus_a == minimum_j_minus_a) { cnt++; } } } return cnt; } }; ================================================ FILE: cpp/1001-10000/1791-1800/Design Authentication Manager.cpp ================================================ class AuthenticationManager { int ttl = 0; unordered_map tokens; public: AuthenticationManager(int timeToLive) { ttl = timeToLive; } void generate(string tokenId, int currentTime) { tokens[tokenId] = currentTime + ttl; } void renew(string tokenId, int currentTime) { auto it = tokens.find(tokenId); if (it == tokens.end()) { return; } if (it->second <= currentTime) { tokens.erase(it); } else { it->second = currentTime + ttl; } } int countUnexpiredTokens(int currentTime) { auto it = tokens.begin(); while (it != tokens.end()) { if (it->second <= currentTime) { it = tokens.erase(it); } else { it++; } } return tokens.size(); } }; /** * Your AuthenticationManager object will be instantiated and called as such: * AuthenticationManager* obj = new AuthenticationManager(timeToLive); * obj->generate(tokenId,currentTime); * obj->renew(tokenId,currentTime); * int param_3 = obj->countUnexpiredTokens(currentTime); */ ================================================ FILE: cpp/1001-10000/1791-1800/Find Center of Star Graph.cpp ================================================ class Solution { public: int findCenter(vector>& edges) { if (edges[0][0] == edges[1][0] || edges[0][0] == edges[1][1]) { return edges[0][0]; } else { return edges[0][1]; } } }; ================================================ FILE: cpp/1001-10000/1791-1800/Maximize Score After N Operations.cpp ================================================ class Solution { int dfs(const vector& nums, int round, int state, unordered_map& cache) { if (round > nums.size() / 2) { return 0; } if (cache.count(state) > 0) { return cache[state]; } int ans = 0; for (int i = 0; i < nums.size(); i++) { for (int j = i + 1; j < nums.size(); j++) { int picked = (1 << i) | (1 << j); if ((state & picked) == 0) { ans = max(ans, round * __gcd(nums[i], nums[j]) + dfs(nums, round + 1, state | picked, cache)); } } } return cache[state] = ans; } public: int maxScore(vector& nums) { unordered_map cache; return dfs(nums, /*round=*/1, /*state=*/0, cache); } }; ================================================ FILE: cpp/1001-10000/1791-1800/Maximum Ascending Subarray Sum.cpp ================================================ class Solution { public: int maxAscendingSum(vector& nums) { int ans = nums[0]; int cur = nums[0]; for (int i = 1; i < nums.size(); i++) { if (nums[i] > nums[i-1]) { cur += nums[i]; } else { cur = nums[i]; } ans = max(ans, cur); } return ans; } }; ================================================ FILE: cpp/1001-10000/1791-1800/Maximum Average Pass Ratio.cpp ================================================ /* * Solution 1: Compute increase every time. It's a bit slow. */ class Solution { public: double maxAverageRatio(vector>& classes, int extraStudents) { auto cmp = [](const pair& a, const pair& b) { double a_original = a.first * 1.0 / a.second; double a_new = (a.first + 1) *1.0 / (a.second + 1); double b_original = b.first * 1.0 / b.second; double b_new = (b.first + 1) *1.0 / (b.second + 1); return (a_new - a_original) < (b_new - b_original); }; priority_queue, vector>, decltype(cmp)> pq(cmp); for (vector& myclass : classes) { pq.push({myclass[0], myclass[1]}); } for (int i = 0; i < extraStudents; i++) { pair cur = pq.top(); pq.pop(); cur.first++; cur.second++; pq.push(cur); } double sum = 0.0; while (!pq.empty()) { pair cur = pq.top(); pq.pop(); sum += (1.0 * cur.first / cur.second); } return sum / classes.size(); } }; /* * Solution 2: Pre-compute increase. */ class Solution { double GetIncrease(int dividend, int divisor) { double original_value = dividend * 1.0 / divisor; double new_value = (dividend + 1) * 1.0 / (divisor + 1); return new_value - original_value; } public: double maxAverageRatio(vector>& classes, int extraStudents) { auto cmp = [](const pair, double>& a, const pair, double>& b) { return a.second < b.second; }; priority_queue, double>, vector, double>>, decltype(cmp)> pq(cmp); for (vector& myclass : classes) { pq.push({{myclass[0], myclass[1]}, GetIncrease(myclass[0], myclass[1])}); } for (int i = 0; i < extraStudents; i++) { pair, double> cur = pq.top(); pq.pop(); cur.first.first++; cur.first.second++; cur.second = GetIncrease(cur.first.first, cur.first.second); pq.push(cur); } double sum = 0.0; while (!pq.empty()) { pair, double> cur = pq.top(); pq.pop(); sum += cur.first.first * 1.0 / cur.first.second; } return sum / classes.size(); } }; ================================================ FILE: cpp/1001-10000/1791-1800/Maximum Number of Consecutive Values You Can Make.cpp ================================================ class Solution { public: int getMaximumConsecutive(vector& coins) { sort(coins.begin(), coins.end()); int cur = 0; for (int coin : coins) { if (cur + 1 >= coin) { cur += coin; } else { break; } } return cur + 1; } }; ================================================ FILE: cpp/1001-10000/1791-1800/Maximum Score of a Good Subarray.cpp ================================================ class Solution { public: int maximumScore(vector& nums, int k) { int mini = nums[k]; int ans = mini; int i = k; int j = k; while (i > 0 || j < nums.size() - 1) { if (i == 0 || (j+1 < nums.size() && nums[i-1] <= nums[j+1])) { j++; mini = min(mini, nums[j]); ans = max(ans, mini * (j - i + 1)); } else { i--; mini = min(mini, nums[i]); ans = max(ans, mini * (j - i + 1)); } } return ans; } }; ================================================ FILE: cpp/1001-10000/1791-1800/Second Largest Digit in a String.cpp ================================================ class Solution { public: int secondHighest(string s) { set nums; for (char ch : s) { if (isdigit(ch)) { nums.insert(ch); } } if (nums.size() < 2) { return -1; } return *(++nums.rbegin()) - '0'; } }; ================================================ FILE: cpp/1001-10000/1801-1810/Count Pairs With XOR in a Range.cpp ================================================ class Solution { const int HEIGHT = 14; class TreeNode { public: TreeNode* next[2]; int cnt; TreeNode () { next[0] = nullptr; next[1] = nullptr; cnt = 0; }; }; void insert(TreeNode* root, int num) { TreeNode* cur = root; for (int j = HEIGHT; j >= 0; j--) { int index = ((num >> j) & 1); if (cur->next[index] == nullptr) cur->next[index] = new TreeNode(); cur = cur->next[index]; cur->cnt++; } } int GetCount(TreeNode* root, int num, int limit) { TreeNode* cur = root; int cnt = 0; for (int j = HEIGHT; j >= 0; j--) { int bit_num = ((num >> j) & 1); int bit_limit = ((limit >> j) & 1); if (bit_limit == 1) { // For bit_num branch, its values are all < limit if (cur->next[bit_num] != nullptr) { cnt += cur->next[bit_num]->cnt; } // we try to pick the side so that it XOR bit_num is 1. cur = cur->next[1 - bit_num]; } else { // we pick 'bit_num' child so that it does not exceed limit. cur = cur->next[bit_num]; } if (cur == nullptr) break; } return cnt; } public: int countPairs(vector& nums, int low, int high) { TreeNode* root = new TreeNode(); int ans = 0; for (int num : nums) { ans += GetCount(root, num, high + 1) - GetCount(root, num, low); insert(root, num); } return ans; } }; ================================================ FILE: cpp/1001-10000/1801-1810/Evaluate the Bracket Pairs of a String.cpp ================================================ class Solution { public: string evaluate(string s, vector>& knowledge) { map mymap; for (const vector& k : knowledge) { mymap[k[0]] = k[1]; } string ans; string key; bool in_bracket = false; for (char ch : s) { if (ch == '(') { in_bracket = true; } else if (ch == ')') { in_bracket = false; if (mymap.count(key) > 0) { ans += mymap[key]; } else { ans += "?"; } key.clear(); } else { if (in_bracket) { key += ch; } else { ans += ch; } } } return ans; } }; ================================================ FILE: cpp/1001-10000/1801-1810/Implement Trie II (Prefix Tree).cpp ================================================ class Trie { struct TrieNode { TrieNode* nodes[26]; int word_cnt; int prefix_cnt; // Initialize your data structure here. TrieNode() { memset(nodes, 0, sizeof(nodes)); word_cnt = 0; prefix_cnt = 0; } }; TrieNode* root; public: Trie() { root = new TrieNode(); } void insert(string word) { TrieNode* tmp = root; for(char ch : word) { int index = ch - 'a'; if(tmp->nodes[index] == nullptr) { tmp->nodes[index] = new TrieNode(); } tmp = tmp->nodes[index]; tmp->prefix_cnt++; } tmp->word_cnt++; } int countWordsEqualTo(string word) { TrieNode* tmp = root; for(char ch : word) { int index = ch - 'a'; if(tmp->nodes[index] == nullptr) { return 0; } tmp = tmp->nodes[index]; } return tmp->word_cnt; } int countWordsStartingWith(string prefix) { TrieNode* tmp = root; for(char ch : prefix) { int index = ch - 'a'; if(tmp->nodes[index] == nullptr) { return 0; } tmp = tmp->nodes[index]; } return tmp->prefix_cnt; } void erase(string word) { TrieNode* tmp = root; TrieNode* to_be_deleted = nullptr; for(char ch : word) { int index = ch - 'a'; TrieNode* parent = tmp; tmp = tmp->nodes[index]; tmp->prefix_cnt--; if (to_be_deleted != nullptr) { delete to_be_deleted; } if (tmp->prefix_cnt == 0) { if (to_be_deleted == nullptr) { parent->nodes[index] = nullptr; } to_be_deleted = tmp; } } tmp->word_cnt--; if (to_be_deleted != nullptr) { delete to_be_deleted; } } }; /** * Your Trie object will be instantiated and called as such: * Trie* obj = new Trie(); * obj->insert(word); * int param_2 = obj->countWordsEqualTo(word); * int param_3 = obj->countWordsStartingWith(prefix); * obj->erase(word); */ ================================================ FILE: cpp/1001-10000/1801-1810/Maximize Number of Nice Divisors.cpp ================================================ class Solution { long mod = 1e9+7; public: int maxNiceDivisors(int primeFactors) { int groups_of_3 = primeFactors/3; int groups_of_2 = 0; int remain = primeFactors - groups_of_3 * 3; if (remain == 1) { if (groups_of_3 > 0) { groups_of_3--; groups_of_2 = 2; } } else if (remain == 2) { groups_of_2 = 1; } long ans = 1; int num_3_used = 0; int limit = sqrt(primeFactors); int temp = 1; while (groups_of_3 > 0) { ans *= 3; ans %= mod; groups_of_3--; num_3_used++; if (num_3_used == limit) { temp = ans; break; } } while (groups_of_3 >= limit) { ans *= temp; ans %= mod; groups_of_3 -= limit; } while (groups_of_3 > 0) { ans *= 3; ans %= mod; groups_of_3--; num_3_used++; } while (groups_of_2 > 0) { ans *= 2; ans %= mod; groups_of_2--; } return ans; } }; ================================================ FILE: cpp/1001-10000/1801-1810/Maximum Value at a Given Index in a Bounded Array.cpp ================================================ class Solution { long getSumInRange(long peak, int length) { long sum = 0; if (length > peak) { sum += (1 + peak) * peak / 2; sum += (length - peak); } else { long minimum = peak - length + 1; sum += (minimum + peak) * length / 2; } return sum; } bool check(int n, int index, int maxSum, int peak) { long sum = getSumInRange(peak, index + 1) + getSumInRange(peak, n - index) - peak; return sum > (long)maxSum; } public: int maxValue(int n, int index, int maxSum) { int left = 1; int right = maxSum; int ans = 1; while (left <= right) { int mid = (left + right) / 2; bool exceed = check(n, index, maxSum, mid); if (exceed) { right = mid - 1; } else { ans = mid; left = mid + 1; } } return ans; } }; ================================================ FILE: cpp/1001-10000/1801-1810/Minimum Path Cost in a Hidden Grid.cpp ================================================ /** * // This is the GridMaster's API interface. * // You should not implement it, or speculate about its implementation * class GridMaster { * public: * bool canMove(char direction); * int move(char direction); * boolean isTarget(); * }; */ class Solution { pair target; public: // 0 is blocked void ConstructGrid(vector>& grid, GridMaster &master, int row, int col, const map>& directions, int cost) { grid[row][col] = cost; if (master.isTarget()) { target.first = row; target.second = col; } for (const auto& direction : directions) { int new_row = row + direction.second.first; int new_col = col + direction.second.second; if (grid[new_row][new_col] != -1) { continue; } if (master.canMove(direction.first)) { int cost = master.move(direction.first); ConstructGrid(grid, master, new_row, new_col, directions, cost); if (direction.first == 'U') master.move('D'); else if (direction.first == 'D') master.move('U'); else if (direction.first == 'L') master.move('R'); else master.move('L'); } else { grid[new_row][new_col] = 0; } } } int findShortestPath(GridMaster &master) { map> directions = { {'U', {-1, 0}}, {'D', {1, 0}}, {'L', {0, -1}}, {'R', {0, 1}}, }; vector> grid(300, vector(300, -1)); ConstructGrid(grid, master, 150, 150, directions, /*cost=*/1); auto cmp = [](const pair, int> &a, const pair, int> &b) { return a.second > b.second; }; priority_queue, int>, vector, int>>, decltype(cmp)> myqueue(cmp); myqueue.push({{150, 150}, 0}); // mark as visited. grid[150][150] = -1; while (!myqueue.empty()) { pair, int> cur = myqueue.top(); myqueue.pop(); if (cur.first == target) { return cur.second; } int r = cur.first.first; int c = cur.first.second; grid[r][c] = -1; for (auto& [ch, direction] : directions) { int new_row = r + direction.first; int new_col = c + direction.second; if (grid[new_row][new_col] <= 0) { continue; } myqueue.push({{new_row, new_col}, cur.second + grid[new_row][new_col]}); } } return -1; } }; ================================================ FILE: cpp/1001-10000/1801-1810/Number of Different Integers in a String.cpp ================================================ class Solution { public: int numDifferentIntegers(string word) { word += 'a'; set s; string tmp; for (char ch : word) { if (isdigit(ch)) { tmp += ch; } else { while (tmp.length() > 1 && tmp[0] == '0') { tmp = tmp.substr(1); } if (!tmp.empty()) s.insert(tmp); tmp = ""; } } return s.size(); } }; ================================================ FILE: cpp/1001-10000/1801-1810/Number of Orders in the Backlog.cpp ================================================ class Solution { public: int getNumberOfBacklogOrders(vector>& orders) { auto cmp1 = [](const vector &a, const vector &b) { return a[0] < b[0]; }; auto cmp2 = [](const vector &a, const vector &b) { return a[0] > b[0]; }; priority_queue, vector>, decltype(cmp1)> buy_backlog(cmp1); priority_queue, vector>, decltype(cmp2)> sell_backlog(cmp2); for (vector order : orders) { if (order[2] == 0) { // buy order while (order[1] > 0 && !sell_backlog.empty()) { if (sell_backlog.top()[0] > order[0]) { break; } vector sell_order = sell_backlog.top(); sell_backlog.pop(); if (order[1] >= sell_order[1]) { order[1] -= sell_order[1]; } else { sell_order[1] -= order[1]; order[1] = 0; sell_backlog.push(sell_order); } } if (order[1] > 0) { buy_backlog.push(order); } } else { while (order[1] > 0 && !buy_backlog.empty()) { if (buy_backlog.top()[0] < order[0]) { break; } vector buy_order = buy_backlog.top(); buy_backlog.pop(); if (order[1] >= buy_order[1]) { order[1] -= buy_order[1]; } else { buy_order[1] -= order[1]; order[1] = 0; buy_backlog.push(buy_order); } } if (order[1] > 0) { sell_backlog.push(order); } } } int mod = 1e9+7; int ans = 0; while (!buy_backlog.empty()) { ans += buy_backlog.top()[1]; ans %= mod; buy_backlog.pop(); } while (!sell_backlog.empty()) { ans += sell_backlog.top()[1]; ans %= mod; sell_backlog.pop(); } return ans; } }; ================================================ FILE: cpp/1001-10000/1811-1820/Count Nice Pairs in an Array.cpp ================================================ class Solution { public: int reverse(int x) { int result = 0; while (x > 0) { result = result * 10 + (x % 10); x /= 10; } return result; } int countNicePairs(vector& nums) { unordered_map mymap; int mod = 1e9+7; int res = 0; for (int num : nums) { int rnum = reverse(num); int diff = num - rnum; res += mymap[diff]; res %= mod; mymap[diff]++; } return res; } }; ================================================ FILE: cpp/1001-10000/1811-1820/Determine Color of a Chessboard Square.cpp ================================================ class Solution { public: bool squareIsWhite(string coordinates) { return ((coordinates[0] - 'a') % 2) == ((coordinates[1] - '0') % 2); } }; ================================================ FILE: cpp/1001-10000/1811-1820/Finding the Users Active Minutes.cpp ================================================ class Solution { public: vector findingUsersActiveMinutes(vector>& logs, int k) { vector res(k, 0); map> activities; for (const vector& log : logs) { activities[log[0]].insert(log[1]); } for (auto [id, activity] : activities) { res[activity.size() - 1]++; } return res; } }; ================================================ FILE: cpp/1001-10000/1811-1820/Maximum Number of Accepted Invitations.cpp ================================================ class Solution { int m, n; public: bool BipartiteMatch(const vector>& grid, int u, vector& visited, vector& girls) { for (int v = 0; v < n; v++) { if (grid[u][v] == 0 || visited[v]) { continue; } visited[v] = true; if (girls[v] < 0 || BipartiteMatch(grid, girls[v], visited, girls)) { girls[v] = u; return true; } } return false; } int maximumInvitations(vector>& grid) { m = grid.size(); n = grid[0].size(); vector grils(n, -1); int matches = 0; for (int u = 0; u < m; u++) { vector visited(n, false); if (BipartiteMatch(grid, u, visited, grils)) { matches++; } } return matches; } }; ================================================ FILE: cpp/1001-10000/1811-1820/Maximum Number of Groups Getting Fresh Donuts.cpp ================================================ class Solution { public: string GetKey(const vector& cnts) { stringstream ss; for (int i = 1; i < cnts.size(); i++) { ss << i << ":" << cnts[i] << ":"; } return ss.str(); } int dfs(vector& cnts, int remain, int batchSize, unordered_map& cache) { string key = GetKey(cnts); if (cache.count(key) > 0) { return cache[key]; } int res = 0; for (int i = 1; i < cnts.size(); i++) { if (cnts[i] == 0) continue; int tmp = (remain == 0 ? 1 : 0); cnts[i]--; tmp += dfs(cnts, (remain - i + batchSize) % batchSize, batchSize, cache); cnts[i]++; res = max(res, tmp); } return cache[key] = res; } int maxHappyGroups(int batchSize, vector& groups) { int res = 0; vector cnts(batchSize, 0); for (int group : groups) { int g = group % batchSize; if (g == 0) { res++; } else if (cnts[batchSize - g] > 0) { res++; cnts[batchSize - g]--; } else { cnts[g]++; } } // batchSize = 4, groups = [1,3,2,5,2,2,1,6] // cnts = [0, 3, 4, 1] -> [0, 2, 0, 0] res = 3 unordered_map cache; return res + dfs(cnts, /*remain=*/0, batchSize, cache); } }; ================================================ FILE: cpp/1001-10000/1811-1820/Minimum Absolute Sum Difference.cpp ================================================ class Solution { public: int minAbsoluteSumDiff(vector& nums1, vector& nums2) { int mod = 1e9 + 7; int res = 0; for (int i = 0; i < nums1.size(); i++) { res += abs(nums1[i] - nums2[i]); res %= mod; } int minus = 0; vector copy_nums = nums1; sort(copy_nums.begin(), copy_nums.end()); for (int i = 0; i < nums1.size(); i++) { int original = abs(nums1[i] - nums2[i]); int dis = 0; auto it = lower_bound(copy_nums.begin(), copy_nums.end(), nums2[i]); if (it == copy_nums.end()) { it--; dis = abs(*it - nums2[i]); } else { dis = abs(*it - nums2[i]); if (it != copy_nums.begin()) { it--; dis = min(dis, abs(*it - nums2[i])); } } minus = max(minus, original - dis); } res -= minus; if (res < 0) res += mod; return res; } }; ================================================ FILE: cpp/1001-10000/1811-1820/Number of Different Subsequences GCDs.cpp ================================================ class Solution { public: int countDifferentSubsequenceGCDs(vector& nums) { int max_num = *max_element(nums.begin(), nums.end()); vector vec(max_num + 1, false); for (int num: nums) { vec[num] = true; } int ans = 0; for (int i = 1; i <= max_num; i++) { int gcd = 0; for (int j = i; j <= max_num; j += i) { if (vec[j] == true) { gcd = __gcd(gcd, j); } } if (gcd == i) ans++; } return ans; } }; ================================================ FILE: cpp/1001-10000/1811-1820/Sentence Similarity III.cpp ================================================ class Solution { public: vector split(const string &s, char delim) { vector elems; stringstream ss(s); string item; while (getline(ss, item, delim)) { if (item.length() > 0) { elems.push_back(item); } } return elems; } bool areSentencesSimilar(string sentence1, string sentence2) { vector words1 = split(sentence1, ' '); vector words2 = split(sentence2, ' '); int i1 = 0, i2 = 0; int j1 = words1.size() - 1, j2 = words2.size() - 1; while (i1 <= j1 && i2 <= j2) { if (words1[i1] == words2[i2]) { i1++; i2++; } else if (words1[j1] == words2[j2]) { j1--; j2--; } else { return false; } } return true; } }; ================================================ FILE: cpp/1001-10000/1811-1820/Truncate Sentence.cpp ================================================ class Solution { public: string truncateSentence(string s, int k) { int space_idx = -1; int num_spaces = 0; for (int i = 0; i < s.length(); i++) { if (s[i] == ' ') { num_spaces++; } if (num_spaces == k) { space_idx = i; break; } } if (space_idx < 0) { return s; } else { return s.substr(0, space_idx); } } }; ================================================ FILE: cpp/1001-10000/1821-1830/Faulty Sensor.cpp ================================================ class Solution { public: int badSensor(vector& sensor1, vector& sensor2) { int n = sensor1.size(); for (int i = 0; i < n - 1; i++) { if (sensor1[i] == sensor2[i]) { continue; } bool is_sensor_1 = true; for (int j = i; j < n - 1; j++) { if (sensor1[j] != sensor2[j+1]) { is_sensor_1 = false; break; } } if (is_sensor_1) return 1; bool is_sensor_2 = true; for (int j = i; j < n - 1; j++) { if (sensor1[j+1] != sensor2[j]) { is_sensor_2 = false; break; } } if (is_sensor_2) return 2; } return -1; } }; ================================================ FILE: cpp/1001-10000/1821-1830/Finding MK Average.cpp ================================================ class MKAverage { int m; int k; queue window; multiset smaller_nums; multiset larger_nums; multiset middles; long middles_sum = 0; void InitializeMultiset() { vector nums; queue current_window = window; while (!current_window.empty()) { nums.push_back(current_window.front()); current_window.pop(); } sort(nums.begin(), nums.end()); for (int i = 0; i < m; i++) { if (i < k) { smaller_nums.insert(nums[i]); } else if (i > m - k - 1) { larger_nums.insert(nums[i]); } else { middles_sum += nums[i]; middles.insert(nums[i]); } } } public: MKAverage(int m, int k) { this->m = m; this->k = k; } void AddElement(int val) { window.push(val); if (middles.empty()) { // It only run once. if (window.size() == m) { InitializeMultiset(); } } else if (val < *smaller_nums.rbegin()) { int middle_candidate = *smaller_nums.rbegin(); smaller_nums.erase(--smaller_nums.end()); smaller_nums.insert(val); middles.insert(middle_candidate); middles_sum += middle_candidate; } else if (val > *larger_nums.begin()) { int middle_candidate = *larger_nums.begin(); larger_nums.erase(larger_nums.begin()); larger_nums.insert(val); middles.insert(middle_candidate); middles_sum += middle_candidate; } else { middles.insert(val); middles_sum += val; } } void RemoveElement() { int val = window.front(); window.pop(); if (val <= *smaller_nums.rbegin()) { smaller_nums.erase(smaller_nums.lower_bound(val)); int small_candidate = *middles.begin(); smaller_nums.insert(small_candidate); middles.erase(middles.begin()); middles_sum -= small_candidate; } else if (val >= * larger_nums.begin()) { larger_nums.erase(larger_nums.lower_bound(val)); int large_candidate = *middles.rbegin(); larger_nums.insert(large_candidate); middles.erase(--middles.end()); middles_sum -= large_candidate; } else { middles.erase(middles.lower_bound(val)); middles_sum -= val; } } void addElement(int num) { AddElement(num); if (window.size() > m) { RemoveElement(); } } int calculateMKAverage() { return window.size() < m ? -1 : middles_sum / middles.size(); } }; ================================================ FILE: cpp/1001-10000/1821-1830/Maximum XOR for Each Query.cpp ================================================ class Solution { public: vector getMaximumXor(vector& nums, int maximumBit) { int n = nums.size(); vector ans; int sum = 0; for (int num : nums) sum ^= num; int max_num = 0; for (int k = 1; k <= maximumBit; k++) { max_num *= 2; max_num++; } for (int i = nums.size() - 1; i >= 0; i--) { ans.push_back(max_num ^ sum); sum ^= nums[i]; } return ans; } }; ================================================ FILE: cpp/1001-10000/1821-1830/Minimum Number of Operations to Make String Sorted.cpp ================================================ class Solution { int mod = 1e9 + 7; long pow(long a, long p, long mod) { long ans = 1; while (p > 0) { if (p & 1) { ans = ans * a % mod; } a = a * a % mod; p = p >> 1; } return ans; } public: int makeStringSorted(string s) { map freq; for (char ch: s) { freq[ch - 'a']++; } int n = s.length(); vector fact(s.size() + 1, 1); for (int i = 1; i <= s.size(); i++) { fact[i] = (fact[i - 1] * i) % mod; } long ans = 0; for (char ch : s) { long freq_sum = 0; long duplicates = 1; for (int i = 0; i < 26; i++) { if (i < (ch - 'a')) { freq_sum += freq[i]; } duplicates = (duplicates * fact[freq[i]]) % mod; } ans += (freq_sum * fact[n - 1] % mod) * pow(duplicates, mod - 2, mod); ans %= mod; n--; freq[ch - 'a']--; } return ans; } }; ================================================ FILE: cpp/1001-10000/1821-1830/Minimum Operations to Make the Array Increasing.cpp ================================================ class Solution { public: int minOperations(vector& nums) { int ans = 0; for (int i = 1; i < nums.size(); i++) { int previous = nums[i-1]; int current = nums[i]; if (current <= previous) { current = previous + 1; ans += (current - nums[i]); nums[i] = current; } } return ans; } }; ================================================ FILE: cpp/1001-10000/1821-1830/Minimum Sideway Jumps.cpp ================================================ class Solution { public: int minSideJumps(vector& obstacles) { int n = obstacles.size(); vector> dp (n, vector(3, 99999999)); dp[0][1] = 0; dp[0][0] = dp[0][2] = 1; for (int i = 1; i < n; i++) { for (int k = 0; k < 3; k++) { if (obstacles[i - 1] == (k + 1) || obstacles[i] == (k + 1)) { dp[i][k] = 99999999; } else { int a_lane = (k + 1) % 3; int b_lane = (k + 2) % 3; dp[i][k] = min(dp[i - 1][k], min(dp[i - 1][a_lane], dp[i - 1][b_lane]) + 1); } } } return min(dp[n-1][0], min(dp[n-1][1], dp[n-1][2])); } }; ================================================ FILE: cpp/1001-10000/1821-1830/Queries on Number of Points Inside a Circle.cpp ================================================ class Solution { public: vector countPoints(vector>& points, vector>& queries) { vector ans; for (const vector& query : queries) { int num = 0; int threshold = query[2] * query[2]; for (const vector& point : points) { int dis_square = (point[0] - query[0]) * (point[0] - query[0]) + (point[1] - query[1]) * (point[1] - query[1]); if (dis_square <= threshold) { num++; } } ans.push_back(num); } return ans; } }; ================================================ FILE: cpp/1001-10000/1821-1830/Sign of the Product of an Array.cpp ================================================ class Solution { public: int arraySign(vector& nums) { int res = 1; for (int num : nums) { if (num > 0) continue; else if (num == 0) return 0; else res *= -1; } return res; } }; ================================================ FILE: cpp/1001-10000/1831-1840/Check if the Sentence Is Pangram.cpp ================================================ class Solution { public: bool checkIfPangram(string sentence) { set letters; for (char ch : sentence) { letters.insert(ch); } return letters.size() == 26; } }; ================================================ FILE: cpp/1001-10000/1831-1840/Find XOR Sum of All Pairs Bitwise AND.cpp ================================================ class Solution { public: int getXORSum(vector& arr1, vector& arr2) { vector bits(32, 0); for (int v : arr2) { int pos = 0; while (v > 0) { if (v & 1) { bits[pos]++; } v = v >> 1; pos++; } } int res = 0; for (int v : arr1) { int pos = 0; int tmp = 0; while (v > 0) { if (v & 1) { if (bits[pos] % 2 == 1) { tmp |= (1 << pos); } } v = v >> 1; pos++; } res ^= tmp; } return res; } }; ================================================ FILE: cpp/1001-10000/1831-1840/Longest Substring Of All Vowels in Order.cpp ================================================ class Solution { public: int longestBeautifulSubstring(string word) { int cnt = 1; int len = 1; int max_len = 0; for (int i = 1; i != word.size(); ++i) { if (word[i - 1] == word[i]) { ++len; } else if (word[i - 1] < word[i]) { ++len; ++cnt; } else { cnt = 1; len = 1; } if (cnt == 5) { max_len = max(max_len, len); } } return max_len; } }; ================================================ FILE: cpp/1001-10000/1831-1840/Maximum Building Height.cpp ================================================ class Solution { public: int maxBuilding(int n, vector>& restrictions) { restrictions.push_back({1, 0}); restrictions.push_back({n, n - 1}); sort(restrictions.begin(), restrictions.end()); for (int i = 1; i < restrictions.size(); i++) { restrictions[i][1] = min(restrictions[i][1], restrictions[i-1][1] + restrictions[i][0] - restrictions[i-1][0]); } for (int i = restrictions.size() - 2; i >= 0; --i) { restrictions[i][1] = min(restrictions[i][1], restrictions[i+1][1] + restrictions[i+1][0] - restrictions[i][0]); } int res = 0; for (int i = 1; i < restrictions.size(); i++) { int left_restriction = restrictions[i-1][1]; int right_restriction = restrictions[i][1]; res = max(res, max(left_restriction, right_restriction) + (restrictions[i][0] - restrictions[i-1][0] - abs(left_restriction - right_restriction)) / 2); } return res; } }; ================================================ FILE: cpp/1001-10000/1831-1840/Maximum Ice Cream Bars.cpp ================================================ class Solution { public: int maxIceCream(vector& costs, int coins) { sort(begin(costs), end(costs)); int num = 0; for (int cost : costs) { if (coins >= cost) { num++; coins -= cost; } else { break; } } return num; } }; ================================================ FILE: cpp/1001-10000/1831-1840/Remove Duplicates From an Unsorted Linked List.cpp ================================================ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* deleteDuplicatesUnsorted(ListNode* head) { ListNode sudo_head(-1); unordered_map mymap; for (ListNode* tmp = head; tmp != nullptr; tmp = tmp->next) { mymap[tmp->val]++; } ListNode* p = &sudo_head; for (ListNode* tmp = head; tmp != nullptr; tmp = tmp->next) { if (mymap[tmp->val] > 1) { continue; } p->next = tmp; p = tmp; } p->next = nullptr; return sudo_head.next; } }; ================================================ FILE: cpp/1001-10000/1831-1840/Single-Threaded CPU.cpp ================================================ class Solution { public: vector getOrder(vector>& tasks) { vector idx(tasks.size()); iota(begin(idx), end(idx), 0); sort(begin(idx), end(idx), [&](int i, int j) { return tasks[i][0] < tasks[j][0]; }); vector res; priority_queue, vector>, greater<>> pq; long time = 1; for (int i = 0; i < idx.size() || !pq.empty();) { while (i < idx.size() && tasks[idx[i]][0] <= time) { pq.push({tasks[idx[i]][1], idx[i]}); ++i; } if (!pq.empty()) { auto [processing_time, j] = pq.top(); pq.pop(); time += processing_time; res.push_back(j); } else { time = tasks[idx[i]][0]; } } return res; } }; ================================================ FILE: cpp/1001-10000/1831-1840/Sum of Digits in Base K.cpp ================================================ class Solution { public: int sumBase(int n, int k) { int res = 0; while (n > 0) { res += (n % k); n /= k; } return res; } }; ================================================ FILE: cpp/1001-10000/1841-1850/Closest Room.cpp ================================================ class Solution { public: vector closestRoom(vector>& rooms, vector>& queries) { int m = queries.size(); vector idx(m); std::iota(idx.begin(), idx.end(), 0); std::sort(idx.begin(), idx.end(), [&queries](int idx1, int idx2) { return queries[idx1][1] > queries[idx2][1]; }); std::sort(rooms.begin(), rooms.end(), [](const vector& room1, const vector& room2) { return room1[1] > room2[1]; }); vector ans(m, -1); int room_idx = 0; set valid_rooms; for (int e : idx) { int preferred = queries[e][0]; int min_size = queries[e][1]; while (room_idx < rooms.size() && rooms[room_idx][1] >= min_size) { valid_rooms.insert(rooms[room_idx][0]); room_idx++; } if (valid_rooms.empty()) { continue; } auto it = valid_rooms.upper_bound(preferred); if (it != valid_rooms.end()) { ans[e] = *it; } if (it != valid_rooms.begin()) { it--; if (ans[e] == -1) { ans[e] = *it; } else if (preferred - *it <= ans[e] - preferred) { ans[e] = *it; } } } return ans; } }; ================================================ FILE: cpp/1001-10000/1841-1850/Minimum Adjacent Swaps to Reach the Kth Smallest Number.cpp ================================================ class Solution { public: int getMinSwaps(string num, int k) { string copy = num; while (k > 0) { std::next_permutation(begin(copy), end(copy)); k--; } int res = 0; for (int i = 0; i < num.length(); i++) { if (num[i] == copy[i]) continue; int j = i + 1; for (; j < copy.length(); j++) { if (num[i] == copy[j]) { break; } } res += (j - i); copy = copy.substr(0, i) + copy[j] + copy.substr(i, j - i) + copy.substr(j + 1); } return res; } }; ================================================ FILE: cpp/1001-10000/1851-1860/Minimum Interval to Include Each Query.cpp ================================================ class Solution { public: vector minInterval(vector>& intervals, vector& queries) { int m = queries.size(); sort(intervals.begin(), intervals.end(),[](const vector& lhs, const vector& rhs){ return lhs[1] - lhs[0] < rhs[1] - rhs[0]; }); set> myset; for (int i = 0; i < m; i++) { myset.insert({queries[i], i}); } vector ans(m, -1); for (const vector& interval : intervals) { auto it = myset.lower_bound({interval[0], 0}); while (it != myset.end() && it->first <= interval[1]) { ans[it->second] = interval[1] - interval[0] + 1; it = myset.erase(it); } } return ans; } }; ================================================ FILE: cpp/101-110/Balanced Binary Tree.cpp ================================================ class Solution { int help(TreeNode *root, bool& flag) { if (root == nullptr) return 0; int left = 1 + help(root->left, flag); int right = 1 + help(root->right, flag); if (abs(left - right) > 1) flag = false; return max(left, right); } public: bool isBalanced(TreeNode *root) { bool flag = true; help(root, flag); return flag; } }; ================================================ FILE: cpp/101-110/Binary Tree Level Order Traversal II.cpp ================================================ class Solution { void help(TreeNode *root, int level, vector>& results) { if(root) { if(results.size() == level) { vector v; results.push_back(v); } results[level].push_back(root->val); help(root->left, level+1, results); help(root->right, level+1, results); } } public: vector > levelOrderBottom(TreeNode *root) { vector> results; help(root, 0, results); reverse(results.begin(), results.end()); return results; } }; ================================================ FILE: cpp/101-110/Binary Tree Level Order Traversal.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector> levelOrder(TreeNode* root) { vector> result; if (!root) return result; queue myqueue({root, nullptr}); vector tmp; while (!myqueue.empty()) { TreeNode* currentNode = myqueue.front(); myqueue.pop(); if (currentNode == nullptr) { result.push_back(tmp); tmp.clear(); if (!myqueue.empty()) myqueue.push(nullptr); } else { tmp.push_back(currentNode->val); if (currentNode->left) myqueue.push(currentNode->left); if (currentNode->right) myqueue.push(currentNode->right); } } return result; } }; ================================================ FILE: cpp/101-110/Binary Tree Zigzag Level Order Traversal.cpp ================================================ class Solution { public: vector > zigzagLevelOrder(TreeNode *root) { vector> result; if (!root) return result; queue myqueue; myqueue.push(root); bool flag = true; while (!myqueue.empty()) { int size_ = myqueue.size(); vector n_vec(size_, 0); for (int i = 0; i < size_; i++) { TreeNode* ele = myqueue.front(); myqueue.pop(); if (flag) n_vec[i] = ele->val; else n_vec[size_ - i - 1] = ele->val; if (ele->left) { myqueue.push(ele->left); } if (ele->right) { myqueue.push(ele->right); } } flag = !flag; result.emplace_back(n_vec); } return result; } }; ================================================ FILE: cpp/101-110/Construct Binary Tree from Inorder and Postorder Traversal.cpp ================================================ class Solution { TreeNode* helper(vector& postorder,int i,int j,vector& inorder,int ii,int jj) { if (i >= j) return nullptr; int mid = postorder[j-1]; auto f = find(inorder.begin() + ii,inorder.begin() + jj,mid); int dis = f - inorder.begin() - ii; TreeNode* root = new TreeNode(mid); root -> left = helper(postorder, i, i + dis, inorder, ii, ii + dis); root -> right = helper(postorder, i + dis, j-1, inorder, ii + dis + 1, jj); return root; } public: TreeNode* buildTree(vector& inorder, vector& postorder) { return helper(postorder,0,postorder.size(),inorder,0,inorder.size()); } }; ================================================ FILE: cpp/101-110/Construct Binary Tree from Preorder and Inorder Traversal.cpp ================================================ class Solution { TreeNode* helper(vector& preorder,int i,int j,vector& inorder,int ii,int jj) { if(i >= j) return nullptr; int mid = preorder[i]; auto f = find(inorder.begin() + ii,inorder.begin() + jj,mid); int dis = f - inorder.begin() - ii; TreeNode* root = new TreeNode(mid); root -> left = helper(preorder,i + 1,i + 1 + dis,inorder,ii,ii + dis); root -> right = helper(preorder,i + 1 + dis,j,inorder,ii + dis + 1,jj); return root; } public: TreeNode* buildTree(vector& preorder, vector& inorder) { return helper(preorder,0,preorder.size(),inorder,0,inorder.size()); } }; ================================================ FILE: cpp/101-110/Convert Sorted Array to Binary Search Tree.cpp ================================================ class Solution { TreeNode *help(vector::iterator it1, vector::iterator it2) { if (it1 == it2) return new TreeNode(*it1); if (it1 > it2) return nullptr; vector::iterator midit = it1+(it2-it1)/2; TreeNode *node = new TreeNode(*midit); node->left = help(it1,midit-1); node->right = help(midit+1, it2); return node; } public: TreeNode *sortedArrayToBST(vector &num) { if (num.size() == 0) return nullptr; return help(num.begin(), num.end()-1); } }; ================================================ FILE: cpp/101-110/Convert Sorted List to Binary Search Tree.cpp ================================================ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { ListNode *mylist; int len(ListNode *head) { int l = 0; while(head) { l++; head = head->next; } return l; } TreeNode *help(int n) { if(n == 0) return nullptr; TreeNode *l = help(n/2); TreeNode *newnode = new TreeNode(mylist->val); newnode->left = l; mylist = mylist->next; newnode->right = help(n - n/2 - 1); return newnode; } public: TreeNode *sortedListToBST(ListNode *head) { this->mylist = head; return help(len(head)); } }; ================================================ FILE: cpp/101-110/Maximum Depth of Binary Tree.cpp ================================================ class Solution { public: int maxDepth(TreeNode *root) { if(!root) return 0; return 1 + max(maxDepth(root->left), maxDepth(root->right)); } }; ================================================ FILE: cpp/101-110/Symmetric Tree.cpp ================================================ class Solution { public: bool isSymmetric(TreeNode *root) { queue low; if(!root) return true; low.push(root->left); low.push(root->right); while(!low.empty()) { TreeNode *left = low.front(); low.pop(); TreeNode *right = low.front(); low.pop(); if(!left && !right) continue; if( (left && !right) || (!left && right) ) return false; if( left->val != right->val ) return false; low.push(left->left); low.push(right->right); low.push(left->right); low.push(right->left); } return true; } }; ================================================ FILE: cpp/111-120/Distinct Subsequences.cpp ================================================ class Solution { public: int numDistinct(string s, string t) { int n = s.length(); int m = t.length(); vector> dp(n+1, vector(m + 1, 0)); for(int k = 0; k <= n; k++) dp[k][0] = 1; for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { dp[i][j] = dp[i-1][j]; if(s[i-1] == t[j-1]) dp[i][j] += dp[i-1][j-1]; } } return dp[n][m]; } }; ================================================ FILE: cpp/111-120/Flatten Binary Tree to Linked List.cpp ================================================ class Solution { TreeNode* flatten(TreeNode* root, TreeNode* pre) { if (root == nullptr) return pre; pre = flatten(root->right, pre); pre = flatten(root->left, pre); root->right = pre; root->left = nullptr; pre = root; return root; } public: void flatten(TreeNode* root) { flatten(root, nullptr); } }; ================================================ FILE: cpp/111-120/Minimum Depth of Binary Tree.cpp ================================================ class Solution { int help(TreeNode *root) { if(!root->left && !root->right) return 1; else if(root->left && root->right) return 1+min(help(root->left), help(root->right)); else if(!root->left && root->right) return 1+help(root->right); else return 1+help(root->left); } public: int minDepth(TreeNode *root) { if(!root) return 0; return help(root); } }; ================================================ FILE: cpp/111-120/Pascal's Triangle II.cpp ================================================ class Solution { public: vector getRow(int rowIndex) { vector result(rowIndex + 1, 1); for (int row = 0; row < rowIndex; row++) { for (int col = row; col > 0; col--) { result[col] += result[col - 1]; } } return result; } }; ================================================ FILE: cpp/111-120/Pascal's Triangle.cpp ================================================ class Solution { public: vector > generate(int numRows) { vector > result; if (numRows <= 0) return result; for(int i = 0; i < numRows; i++) { vector row(i+1); row[0] = row[i] = 1; for(int j = 1; j < i; j++) row[j] = result[i-1][j-1] + result[i-1][j]; result.push_back(row); } return result; } }; ================================================ FILE: cpp/111-120/Path Sum II.cpp ================================================ class Solution { public: vector> pathSum(TreeNode* root, int sum) { vector > paths; vector path; findPaths(root, sum, path, paths); return paths; } private: void findPaths(TreeNode* node, int sum, vector& path, vector >& paths) { if (node == nullptr) return; path.push_back(node -> val); if (!(node -> left) && !(node -> right) && sum == node -> val) paths.push_back(path); findPaths(node -> left, sum - node -> val, path, paths); findPaths(node -> right, sum - node -> val, path, paths); path.pop_back(); } }; ================================================ FILE: cpp/111-120/Path Sum.cpp ================================================ class Solution { public: bool hasPathSum(TreeNode *root, int sum) { if (root == nullptr) return false; if (root->left == nullptr && root->right == nullptr && sum == root->val) return true; return hasPathSum(root->left,sum - root->val) || hasPathSum(root->right,sum - root->val); } }; ================================================ FILE: cpp/111-120/Populating Next Right Pointers in Each Node II.cpp ================================================ /** * Definition for binary tree with next pointer. * struct TreeLinkNode { * int val; * TreeLinkNode *left, *right, *next; * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} * }; */ class Solution { public: void connect(TreeLinkNode *root) { while (root) { TreeLinkNode *tln = root; TreeLinkNode *prev = new TreeLinkNode(0); TreeLinkNode *temp = prev; while (tln) { if (tln->left) { prev->next = tln->left; prev = prev->next; } if(tln->right) { prev->next = tln->right; prev = prev->next; } tln = tln->next; } root = temp -> next; } } }; ================================================ FILE: cpp/111-120/Populating Next Right Pointers in Each Node.cpp ================================================ class Solution { public: void connect(TreeLinkNode *root) { TreeLinkNode *ancestor = root; while(ancestor) { TreeLinkNode *tln = ancestor; if(!tln->left) break; while(tln) { tln->left->next = tln->right; if(tln->next) tln->right->next = tln->next->left; tln = tln->next; } ancestor = ancestor->left; } } }; ================================================ FILE: cpp/111-120/Triangle.cpp ================================================ class Solution { public: int minimumTotal(vector > &triangle) { // Dp method, record the minimum value for that position vector dp {triangle[0][0]}; for (int i = 1; i < triangle.size(); i++) { vector temp(dp.size() + 1); for (int j = 0; j < triangle[i].size(); j++) { if(j == 0) { temp[j] = triangle[i][j] + dp.front(); } else if(j == triangle[i].size()-1) { temp[j] = triangle[i][j]+dp.back(); } else { temp[j] = triangle[i][j] + min(dp[j-1], dp[j]); } } // swap if faster than dp = temp dp.swap(temp); } return *min_element(dp.begin(), dp.end()); } }; ================================================ FILE: cpp/121-130/Best Time to Buy and Sell Stock II.cpp ================================================ class Solution { public: int maxProfit(vector &prices) { if(prices.size() < 2) return 0; int profit(0); for(int i = 0;i < prices.size()-1;i++) if(prices[i+1] > prices[i]) profit += (prices[i+1] - prices[i]); return profit; } }; ================================================ FILE: cpp/121-130/Best Time to Buy and Sell Stock III.cpp ================================================ class Solution { public: int maxProfit(vector &prices) { if(prices.size() < 2) return 0; int n = prices.size(); vector> p (2, vector(n,0)); int minimum(INT_MAX),result(0); for(int i = 0;i < prices.size();i++) { minimum = min(minimum, prices[i]); result = max(result, prices[i]-minimum); p[0][i] = result; } int maximum = INT_MIN; result = 0; for(int i = n-1;i >= 0;i--) { maximum = max(maximum, prices[i]); result = max(result, maximum - prices[i]); p[1][i] = result; } int profit(0); for(int k = 0;k < n;k++) { if(k == n-1) profit = max(profit, p[0][k]); else profit = max(profit, p[0][k]+p[1][k+1]); } return profit; } }; ================================================ FILE: cpp/121-130/Best Time to Buy and Sell Stock.cpp ================================================ class Solution { public: int maxProfit(vector &prices) { int minimum(INT_MAX),result(0); for(vector::iterator it = prices.begin(); it != prices.end(); it++) { minimum = min(minimum, *it); result = max(result, *it-minimum); } return result; } }; ================================================ FILE: cpp/121-130/Binary Tree Maximum Path Sum.cpp ================================================ class Solution { int dfs(TreeNode *root, int& result) { if (root == nullptr) { return 0; } int l = max(0, dfs(root->left, result)); int r = max(0, dfs(root->right, result)); result = max(result, l + r + root->val); return root->val + max(l, r); } public: int maxPathSum(TreeNode *root) { int result = INT_MIN; dfs(root, result); return result; } }; ================================================ FILE: cpp/121-130/Longest Consecutive Sequence.cpp ================================================ class Solution { public: int longestConsecutive(vector& nums) { int longest = 0; unordered_map mymap; for (int v : nums) { if (mymap.count(v) > 0) { continue; } mymap[v] = 1; int end = v; int begin = v; if(mymap.count(v + 1) > 0) { end = v + mymap[v + 1]; } if(mymap.count(v - 1) > 0) { begin = v - mymap[v - 1]; } longest = max(longest, end - begin + 1); mymap[end] = end - begin + 1; mymap[begin] = end - begin + 1; } return longest; } }; ================================================ FILE: cpp/121-130/Sum Root to Leaf Numbers.cpp ================================================ class Solution { int help(TreeNode *root, int pVal) { if(!root->left && !root->right) return root->val + 10*pVal; root->val += 10*pVal; if(root->left && root->right) return help(root->left, root->val)+help(root->right, root->val); else if(root->left && !root->right) return help(root->left, root->val); else return help(root->right, root->val); } public: int sumNumbers(TreeNode *root) { if(!root) return 0; return help(root, 0); } }; ================================================ FILE: cpp/121-130/Surrounded Regions.cpp ================================================ class Solution { void help(vector> &board, int ii, int jj) { if (board[ii][jj] == 0 || board[ii][jj] == 'X') return; board[ii][jj] = 0; queue>q; q.push(make_pair(ii,jj)); while (!q.empty()) { pair cur = q.front(); q.pop(); pair adjs[4] = {{cur.first-1, cur.second}, {cur.first+1, cur.second}, {cur.first, cur.second-1}, {cur.first, cur.second+1}}; for (int i = 0; i < 4; ++i) { int adjW = adjs[i].first; int adjL = adjs[i].second; if ((adjW >= 0) && (adjW < board.size()) && (adjL >= 0) && (adjL < board[adjW].size()) && (board[adjW][adjL] == 'O')) { q.push(make_pair(adjW, adjL)); board[adjW][adjL] = 0; } } } return; } public: void solve(vector> &board) { if (board.empty()) return; for (int i = 0;i < board.size();i++) { if (board[i].front() == 'O') help(board, i, 0); if (board[i].back() == 'O') help(board, i, board[i].size()-1); } for (int i = 0;i < board[0].size();i++) { if (board.front()[i] == 'O') help(board, 0, i); if (board.back()[i] == 'O') help(board, board.size()-1, i); } for (int i = 0;i < board.size();i++) { for (int j = 0;j < board[i].size();j++) { if (board[i][j] == 'O') board[i][j] = 'X'; else if (board[i][j] == 0) board[i][j] = 'O'; } } } }; ================================================ FILE: cpp/121-130/Valid Palindrome.cpp ================================================ class Solution { public: bool isPalindrome(string s) { int i = 0, j = s.length() - 1; while (i < j) { while (!isalpha(s[i]) && !isdigit(s[i]) && i <= j) { i++; } while (!isalpha(s[j]) && !isdigit(s[j]) && i <= j) { j--; } if (i >= j) { break; } if (toupper(s[i]) != toupper(s[j])) { return false; } i++; j--; } return true; } }; ================================================ FILE: cpp/121-130/Word Ladder II.cpp ================================================ class Solution { public: vector> findLadders(string beginWord, string endWord, vector& wordList) { unordered_set dict(begin(wordList), end(wordList)); unordered_map> traces; unordered_map dis; queue q; dis[beginWord] = 1; q.push(beginWord); while (!q.empty()) { string word = q.front(); q.pop(); if (word == endWord) break; for (int i = 0; i < word.size(); i++) { for (int j = 0; j < 26; j++) { string newWord = word; newWord[i] = 'a' + j; if (dict.count(newWord) > 0) { if( dis.count(newWord) == 0 ) { dis[newWord] = dis[word] + 1; vector tmp; tmp.push_back(word); traces[newWord] = tmp; q.push(newWord); } else if(dis[word] + 1 == dis[newWord]){ traces[newWord].push_back(word); } } } } } vector>paths; vector empty; helper(beginWord, endWord, traces, paths, empty); return paths; } void helper(string start, string end, unordered_map>& traces, vector>& path, vector onepath) { onepath.insert(onepath.begin(), end); if(start == end) path.push_back(onepath); else { vector node = traces[end]; for(int i = 0;i < node.size();i++) { string end = node[i]; helper(start, end, traces, path, onepath); } } } }; ================================================ FILE: cpp/121-130/Word Ladder.cpp ================================================ class Solution { public: int ladderLength(string beginWord, string endWord, vector& wordList) { unordered_set dict(begin(wordList), end(wordList)); queue q; q.push(beginWord); unordered_set visited; visited.insert(beginWord); int step = 1; while (!q.empty()) { int k = q.size(); for (int i = 0; i < k; i++) { string word = q.front(); q.pop(); if (word == endWord) { return step; } for (int i = 0; i < word.size(); i++) { char ch = word[i]; for (int j = 0; j < 26; j++) { word[i] = 'a' + j; if (visited.count(word) == 0 && dict.count(word) > 0) { visited.insert(word); q.push(word); } } word[i] = ch; } } step++; } return 0; } }; ================================================ FILE: cpp/131-140/Candy.cpp ================================================ class Solution { public: int candy(vector& ratings) { int len = ratings.size(); vectorv(len, 1); for (int i = 1;i < len;i++) if (ratings[i] > ratings[i-1]) v[i] = v[i-1] + 1; for (int i = len-1;i > 0;i--) if(ratings[i-1] > ratings[i]) v[i-1] = max(v[i]+1, v[i-1]); int result(0); for (auto e : v) result += e; return result; } }; ================================================ FILE: cpp/131-140/Clone Graph.cpp ================================================ /* // Definition for a Node. class Node { public: int val; vector neighbors; Node() {} Node(int _val, vector _neighbors) { val = _val; neighbors = _neighbors; } }; */ class Solution { unordered_map dict; public: Node* cloneGraph(Node* node) { //if (!node) return nullptr; if (dict.count(node) == 0) { dict[node] = new Node(); dict[node]->val = node->val; for (Node* neighbor : node->neighbors) { dict[node]->neighbors.push_back(cloneGraph(neighbor)); } } return dict[node]; } }; ================================================ FILE: cpp/131-140/Copy List with Random Pointer.cpp ================================================ class Solution { public: RandomListNode *copyRandomList(RandomListNode *head) { if(!head) return NULL; RandomListNode *n = head; RandomListNode *h = new RandomListNode(0); RandomListNode *result = h; unordered_mapmaps; while(head) { RandomListNode *newnode = new RandomListNode(head->label); maps[head] = newnode; h -> next = newnode; h = h->next; head = head->next; } RandomListNode *r = result->next; while(n) { r->random = maps[n->random]; r = r->next; n = n->next; } return result->next; } }; ================================================ FILE: cpp/131-140/Gas Station.cpp ================================================ class Solution { public: int canCompleteCircuit(vector& gas, vector& cost) { int totalSum(0), start(0), now(0); for (int i = 0;i < gas.size();i++) { int tmp = gas[i] - cost[i]; totalSum += tmp; now += tmp; if(now < 0) { start = i+1; now = 0; } } return totalSum >= 0 ? start : -1; } }; ================================================ FILE: cpp/131-140/Palindrome Partitioning II.cpp ================================================ class Solution { public: int minCut(string s) { vector >p(s.length(), vector(s.length(), 100000)); for(int i = 0;i < s.length();i++) for(int j = 0;j < s.length()-i;j++) if(s[j] == s[j+i]) p[j][j+i] = j+1 <= j+i-1 ? p[j+1][j+i-1] : 0; for(int j = 1;j < s.length();j++) for(int i = 0;i < j;i++) p[0][j] = min(p[0][j], p[0][i]+p[i+1][j]+1); return p[0][s.length()-1]; } }; ================================================ FILE: cpp/131-140/Palindrome Partitioning.cpp ================================================ class Solution { void dfs(int index, string& s, vector& path, vector >& ret, vector> &p) { if (index == s.size()) { ret.push_back(path); return; } for(int i = index; i < s.size(); ++i) { if(p[index][i]) { path.push_back(s.substr(index, i - index + 1)); dfs(i+1, s, path, ret, p); path.pop_back(); } } } public: vector> partition(string s) { vector > ret; if(s.empty()) return ret; vector>p(s.length(), vector(s.length(), false)); for (int i = 0;i < s.length();i++) { for (int j = 0;j < s.length()-i;j++) { if(i == 0) p[j][j] = true; else { if(s[j] == s[j+i]) p[j][j+i] = j+1 <= j+i-1 ? p[j+1][j+i-1] : true; else p[j][j+i] = false; } } } vector path; dfs(0, s, path, ret, p); return ret; } }; ================================================ FILE: cpp/131-140/Single Number II.cpp ================================================ class Solution { public: int singleNumber(vector& nums) { vector v(32, 0); for(auto e : nums) { for(int i = 0;i < 32;i++) { v[i] += e & 1; e = e >> 1; } } int result(0); for(int i = 0;i < 32;i++) if(v[i] % 3 != 0) result |= (1 << i); return result; } }; ================================================ FILE: cpp/131-140/Single Number.cpp ================================================ class Solution { public: int singleNumber(vector& nums) { int r(0); for(auto e : nums) r ^= e; return r; } }; ================================================ FILE: cpp/131-140/Word Break II.cpp ================================================ class Solution { unordered_map>m; vector dfs(string s, unordered_set& dict) { if (m.count(s) > 0) return m[s]; vector words; int len = s.length(); for(int i = 1;i <= len;i++) { string first = s.substr(0, i); unordered_set::const_iterator got = dict.find(first); if (got != dict.end()) { if(i == len) words.push_back(first); else { string remain = s.substr(i); vector remainVec = dfs(remain, dict); for (int k = 0;k < remainVec.size();k++) words.push_back(first + " " + remainVec[k]); } } } m[s] = words; return words; } public: vector wordBreak(string s, vector& wordDict) { unordered_set dict(begin(wordDict), end(wordDict)); return dfs(s, dict); } }; ================================================ FILE: cpp/131-140/Word Break.cpp ================================================ class Solution { public: bool wordBreak(string s, vector& wordDict) { unordered_set dict(begin(wordDict), end(wordDict)); vector p(s.length()+1, false); p[0]=true; for(int i = 0;i < s.length();i++) { for(int j = 0;j <= i;j++) { if(p[j] == true) { string tmp = s.substr(j,i+1-j); if (dict.find (tmp) != dict.end()) { p[i+1] = true; break; } } } } return p[s.length()]; } }; ================================================ FILE: cpp/141-150/Binary Tree Postorder Traversal.cpp ================================================ class Solution { public: vector postorderTraversal(TreeNode* root) { vector result; if (root == nullptr) return result; stack nodes_ready_for_visiting; nodes_ready_for_visiting.emplace(root); while (!nodes_ready_for_visiting.empty()) { root = nodes_ready_for_visiting.top(); nodes_ready_for_visiting.pop(); result.emplace(result.end(), root->val); if (root->left) nodes_ready_for_visiting.emplace(root->left); if (root->right) nodes_ready_for_visiting.emplace(root->right); } reverse(result.begin(), result.end()); return result; } }; ================================================ FILE: cpp/141-150/Evaluate Reverse Polish Notation.cpp ================================================ class Solution { public: int evalRPN(vector &tokens) { stack nums; for (int i = 0; i < tokens.size(); i++) { string s = tokens[i]; if (isdigit(s[0]) || s.size() > 1) { nums.push(stoi(s)); continue; } int a = nums.top(); nums.pop(); int b = nums.top(); nums.pop(); if (s == "+") { nums.push(a+b); } else if (s == "-") { nums.push(b-a); } else if (s == "*") { nums.push(a*b); } else { nums.push(b/a); } } return nums.top(); } }; ================================================ FILE: cpp/141-150/Insertion Sort List.cpp ================================================ class Solution { public: ListNode *insertionSortList(ListNode *head) { ListNode result(INT_MIN); while (head) { ListNode* iter = &result; while (iter->next && iter->next->val < head->val) iter = iter->next; ListNode* next = head->next; head->next = iter->next; iter->next = head; head = next; } return result.next; } }; ================================================ FILE: cpp/141-150/LRU Cache.cpp ================================================ class LRUCache { public: LRUCache(int capacity) : _capacity(capacity) {} int get(int key) { auto it = cache.find(key); if (it == cache.end()) return -1; touch(it); return it->second.first; } void set(int key, int value) { auto it = cache.find(key); if (it != cache.end()) touch(it); else { if (cache.size() == _capacity) { cache.erase(used.back()); used.pop_back(); } used.push_front(key); } cache[key] = { value, used.begin() }; } private: typedef list LI; typedef pair PII; typedef unordered_map HIPII; void touch(HIPII::iterator it) { int key = it->first; used.erase(it->second.second); used.push_front(key); it->second.second = used.begin(); } HIPII cache; LI used; int _capacity; }; ================================================ FILE: cpp/141-150/Linked List Cycle II.cpp ================================================ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *detectCycle(ListNode *head) { if (head == nullptr) return nullptr; ListNode *slow(head), *fast(head); while (fast && fast->next) { slow = slow->next; fast = fast->next->next; if (slow == fast) break; } if (fast == nullptr || fast->next == nullptr) return nullptr; slow = head; while (slow != fast) { slow = slow->next; fast = fast->next; } return slow; } }; ================================================ FILE: cpp/141-150/Linked List Cycle.cpp ================================================ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: bool hasCycle(ListNode *head) { if (head == nullptr) return false; ListNode *first = head, *second = head->next; while (second != nullptr) { if (first == second) return true; first = first->next; second = second->next; if (second != nullptr) second = second->next; } return false; } }; ================================================ FILE: cpp/141-150/Max Points on a Line.cpp ================================================ class Solution { public: int maxPoints(vector> &points) { if (points.size() <= 2) { return points.size(); } int maxNum = 0; for (int i = 0; i < points.size(); i++) { int localmax = 0, overlap = 0; map, int> statistic; for (int j = i + 1; j < points.size(); j++) { if (points[j][0] == points[i][0] && points[j][1] == points[i][1]) { overlap++; continue; } else { int x = points[j][0] - points[i][0]; int y = points[j][1] - points[i][1]; int divide = __gcd(x,y); x /= divide; y /= divide; pairp(x,y); statistic[p]++; localmax = max(statistic[p], localmax); } } maxNum=max(maxNum, localmax + overlap + 1); } return maxNum; } }; ================================================ FILE: cpp/141-150/Reorder List.cpp ================================================ class Solution { ListNode* reverse(ListNode *head) { ListNode* tmp = head->next; ListNode* p = nullptr; head->next = NULL; while (tmp) { p = tmp->next; tmp -> next = head; head = tmp; tmp = p; } return head; } public: void reorderList(ListNode *head) { if (!head || !head->next) return; ListNode *head1 = head; ListNode *head2 = head->next; while (head2 && head2->next) { head1 = head1->next; head2 = head2->next->next; } head2 = head1 -> next; head1 -> next = nullptr; head1 = head; head2 = reverse(head2); ListNode *tmp = head1 -> next; while (head2){ head1 -> next = head2; head1 = head2; head2 = tmp; tmp = head1->next; } } }; ================================================ FILE: cpp/141-150/Sort List.cpp ================================================ class Solution { public: ListNode* merge(ListNode *node1, int n1, ListNode *node2, int n2, ListNode *before) { ListNode *first(node1), *second(node2); int len1(n1), len2(n2); if(node1 -> val > node2 ->val) { first = node2; second = node1; len1 = n2; len2 = n1; } ListNode *head(first), *answer(first); while(1) { if(first->val <= second->val) { if(len1 == 1) { first -> next = second; break; } else { len1--; head = first; first = first -> next; continue; } } else { len2--; ListNode *temp = second; second = second->next; temp->next = first; head->next = temp; head = temp; if(len2 == 0) break; } } if(before) before->next = answer; ListNode *t = answer; int l = n1+n2; while(l-- > 1) t = t->next; t->next = NULL; return t; } int lengthOfList(ListNode *node) { int len = 0; while(node) { len++; node = node->next; } return len; } ListNode* find(ListNode* node, int L) { while(node && L > 0) { node = node->next; L--; } return node; } ListNode *sortList(ListNode *head) { int num = 1; int len = lengthOfList(head); ListNode *ans = head; ListNode *tmp = head; while(num < len) { for(int i = num;i > 0&&tmp->next;i--) tmp = tmp->next; if(ans->val > tmp->val) ans = tmp; ListNode *tail = NULL; ListNode *node1(head), *node2(tmp); while(node2) { ListNode *nextnode = node2; int p = num; while(nextnode && p > 0) { nextnode = nextnode->next; p--; } nextnode = find(node2,num); tail = merge(node1, num, node2, num-p, tail); node1 = nextnode; node2 = find(node1,num); if(node1 || !node2) tail->next = node1; } head = ans; tmp = head; num *= 2; } return ans; } }; ================================================ FILE: cpp/141-150/Tree Preorder Traversal.cpp ================================================ class Solution { public: vector preorderTraversal(TreeNode *root) { vector result; if (root == nullptr) return result; stack nodes_ready_for_visiting; nodes_ready_for_visiting.emplace(root); while (!nodes_ready_for_visiting.empty()) { root = nodes_ready_for_visiting.top(); nodes_ready_for_visiting.pop(); result.emplace(result.end(), root->val); if (root->right) nodes_ready_for_visiting.push(root->right); if (root->left) nodes_ready_for_visiting.push(root->left); } return result; } }; ================================================ FILE: cpp/151-160/Binary Tree Upside Down.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* upsideDownBinaryTree(TreeNode* root) { if (!root || !root->left) return root; TreeNode* cur_left = root->left; TreeNode* cur_right = root->right; TreeNode* new_root = upsideDownBinaryTree(root->left); cur_left->right = root; cur_left->left = cur_right; root->left = nullptr; root->right = nullptr; return new_root; } }; ================================================ FILE: cpp/151-160/Find Minimum in Rotated Sorted Array II.cpp ================================================ class Solution { public: int findMin(vector& nums) { int i = 0; int j = nums.size() - 1; while (i < j) { int mid = (i + j) / 2; if (nums[mid] < nums[j]) { j = mid; } else if (nums[mid] > nums[j]) { i = mid + 1; } else { j--; } } return nums[i]; } }; ================================================ FILE: cpp/151-160/Find Minimum in Rotated Sorted Array.cpp ================================================ class Solution { public: int findMin(vector& nums) { int i = 0; int j = nums.size() - 1; while (i < j) { int mid = (i + j) / 2; if (nums[mid] < nums[j]) { j = mid; } else { i = mid + 1; } } return nums[i]; } }; ================================================ FILE: cpp/151-160/Intersection of Two Linked Lists.cpp ================================================ class Solution { int getLen(ListNode *head) { int len(0); while (head) { head = head->next; len++; } return len; } public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { int len1 = getLen(headA); int len2 = getLen(headB); if (len2 > len1) { swap(headA, headB); swap(len1, len2); } while (len1-- != len2) headA = headA->next; while (headA != headB) { headA = headA->next; headB = headB->next; } return headA; } }; ================================================ FILE: cpp/151-160/Longest Substring with At Most Two Distinct Characters.cpp ================================================ class Solution { public: int lengthOfLongestSubstringTwoDistinct(string s) { int current = 0; int longest = 0; int previouspos = 0; unordered_map m; for (int i = 0; i < s.length(); i++) { m[s[i]]++; if (m[s[i]] == 1) { current++; } while (current > 2) { char ch = s[previouspos]; previouspos++; m[ch]--; if (m[ch] == 0) { current--; } } longest = max(longest, i - previouspos + 1); } return longest; } }; ================================================ FILE: cpp/151-160/Maximum Product Subarray.cpp ================================================ class Solution { public: int maxProduct(vector& nums) { if (nums.size() == 0) return 0; int maxEndHere = nums[0]; int minEndHere = nums[0]; int maxSoFar = nums[0]; for (int i = 1; i < nums.size(); i++) { int num = nums[i]; if (num >= 0) { maxEndHere = max(maxEndHere * num, num); minEndHere = min(minEndHere * num, num); } else { int temp = maxEndHere; maxEndHere = max(minEndHere * num, num); minEndHere = min(temp * num, num); } maxSoFar = max(maxEndHere, maxSoFar); } return maxSoFar; } }; ================================================ FILE: cpp/151-160/Min Stack.cpp ================================================ class MinStack { stack s1; stack s2; public: void push(int x) { s1.push(x); if (s2.empty() || s2.top() >= x) s2.push(x); } void pop() { int tmp = s1.top(); s1.pop(); if (tmp == s2.top()) s2.pop(); } int top() { return s1.top(); } int getMin() { return s2.top(); } }; /** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */ ================================================ FILE: cpp/151-160/Read N Characters Given Read4 II - Call multiple times.cpp ================================================ class Solution { private: char cache[4]; int cache_ind = 0; int cache_cnt = 0; public: /** * @param buf Destination buffer * @param n Number of characters to read * @return The number of actual characters read */ int read(char *buf, int n) { int ind = 0; while (true) { while (cache_cnt > 0 && ind < n) { buf[ind] = cache[cache_ind]; ind++; cache_ind++; cache_cnt--; } if (ind == n) { return ind; } cache_ind = 0; cache_cnt = read4(cache); if (cache_cnt == 0) { break; } } return ind; } }; ================================================ FILE: cpp/151-160/Read N Characters Given Read4.cpp ================================================ /** * The read4 API is defined in the parent class Reader4. * int read4(char *buf4); */ class Solution { public: int read(char *buf, int n) { int ind = 0; while (ind < n) { char cache[4]; int cache_cnt = read4(cache); if (cache_cnt == 0) { break; } int cache_ind = 0; while (cache_cnt > 0 && ind < n) { buf[ind] = cache[cache_ind]; cache_ind++; ind++; cache_cnt--; } } return ind; } }; ================================================ FILE: cpp/151-160/Reverse Words in a String.cpp ================================================ class Solution { public: void reverseWords(string &s) { reverse(s.begin(), s.end()); int storeIndex(0); for (int i = 0; i < s.size(); i++) { if (s[i] != ' ') { if (storeIndex != 0) s[storeIndex++] = ' '; int j = i; while (j < s.size() && s[j] != ' ') { s[storeIndex++] = s[j++]; } reverse(s.begin() + storeIndex - (j - i), s.begin() + storeIndex); i = j; } } s.resize(storeIndex); } }; ================================================ FILE: cpp/161-170/Compare Version Numbers.cpp ================================================ class Solution { public: int compareVersion(string version1, string version2) { int i(0), j(0); int n1(version1.size()), n2(version2.size()); int num1(0), num2(0); while (inum2) return 1; else if (num1 < num2) return -1; num1 = 0; num2 = 0; i++; j++; } return 0; } }; ================================================ FILE: cpp/161-170/Excel Sheet Column Title.cpp ================================================ class Solution { public: string convertToTitle(int n) { return n == 0 ? "" : convertToTitle((n-1) / 26) + (char) ((n-1) % 26 + 'A'); } }; ================================================ FILE: cpp/161-170/Find Peak Element.cpp ================================================ class Solution { public: int findPeakElement(const vector &num) { int low(0), high(num.size()-1); while(low < high) { int mid1 = (low+high)/2; int mid2 = mid1+1; num[mid1] < num[mid2] ? low = mid2 : high = mid1; } return low; } }; ================================================ FILE: cpp/161-170/Fraction to Recurring Decimal.cpp ================================================ class Solution { public: string fractionToDecimal(int64_t numerator, int64_t denominator) { bool flag = false; if (numerator > 0 && denominator < 0) { flag = true; } else if (numerator < 0 && denominator > 0) { flag = true; } numerator = abs(numerator); denominator = abs(denominator); int64_t remain = numerator % denominator; int64_t d = numerator/denominator; string result = to_string(d); if (flag) result = "-"+result; if (remain == 0) return result; unordered_mapp; string small = ""; int index = 0; while (remain > 0) { p[remain] = index; int64_t tmp = remain*10; int64_t digit = tmp/denominator; remain = tmp%denominator; small += to_string(digit); if (p.count(remain) > 0) { small.insert(p[remain], "("); small += ")"; break; } index++; } return result+"."+small; } }; ================================================ FILE: cpp/161-170/Majority Element.cpp ================================================ class Solution { public: int majorityElement(vector &num) { stack s; for(int i = 0;i < num.size();i++) { if(s.empty()) s.push(num[i]); else{ int t = s.top(); if(t != num[i]) s.pop(); else s.push(num[i]); } } return s.top(); } }; ================================================ FILE: cpp/161-170/Maximum Gap.cpp ================================================ class Solution { public: int maximumGap(vector &num) { if(num.size() < 2) return 0; int minium = *min_element(num.begin(), num.end()); int maxium = *max_element(num.begin(), num.end()); int gap = (int)ceil((maxium - minium)*1.0/(num.size()-1)); int* maxBucket = new int[num.size()]; int* minBucket = new int[num.size()]; fill(maxBucket, maxBucket+num.size(), INT_MIN); fill(minBucket, minBucket+num.size(), INT_MAX); for(int i = 0;i < num.size();i++) { int idx = (num[i] - minium)/gap; maxBucket[idx] = max(maxBucket[idx], num[i]); minBucket[idx] = min(minBucket[idx], num[i]); } int MaxGap = -1; int temp = minium; for(int i = 0;i < num.size();i++) { if(maxBucket[i] == INT_MIN) continue; MaxGap = max(MaxGap, minBucket[i] - temp); temp = maxBucket[i]; } return MaxGap; } }; ================================================ FILE: cpp/161-170/Missing Ranges.cpp ================================================ class Solution { inline string get_range(int start, int end) { return start==end? to_string(start) : to_string(start)+"->"+to_string(end); } public: vector findMissingRanges(vector& nums, int lower, int upper) { vector result; int pre = lower-1; for (int i = 0; i <= nums.size(); i++) { int cur = (i==nums.size()? upper+1:nums[i]); if (cur-pre>=2) result.push_back(get_range(pre+1,cur-1)); pre = cur; } return result; } }; ================================================ FILE: cpp/161-170/One Edit Distance.cpp ================================================ class Solution { public: bool isOneEditDistance(string s, string t) { if (abs((int)s.length() - (int)t.length()) >= 2) return false; if (s == t) return false; if (s.length() == t.length()) { int diff(0); for (int i = 0;i < s.length();i++) { if (s[i] != t[i]) diff++; if (diff >= 2) return false; } return true; } if (s.length() > t.length()) return isOneEditDistance(t, s); int i(0), j(0); while (i < s.length() && j < t.length()) { if (s[i] == t[j]){ i++; j++; } else { j++; } } if (i == s.length() && j == t.length()) return true; if (j == i) return true; return false; } }; ================================================ FILE: cpp/161-170/Two Sum II - Input array is sorted.cpp ================================================ class Solution { public: vector twoSum(vector& numbers, int target) { int i(0), j(numbers.size()-1); vector result; while (i < j) { int sum = numbers[i] + numbers[j]; if (sum == target) { result.push_back(i+1); result.push_back(j+1); return result; } sum > target? j-- : i++; } return result; } }; ================================================ FILE: cpp/161-170/Two Sum III - Data structure design.cpp ================================================ class TwoSum { unordered_multiset nums; public: void add(int number) { nums.insert(number); } bool find(int value) { for (int i : nums) { int count = i == value - i ? 1 : 0; if (nums.count(value - i) > count) { return true; } } return false; } }; // Your TwoSum object will be instantiated and called as such: // TwoSum twoSum; // twoSum.add(number); // twoSum.find(value); ================================================ FILE: cpp/171-180/Binary Search Tree Iterator.cpp ================================================ class BSTIterator { stack s; public: BSTIterator(TreeNode *root) { while(root) { s.push(root); root = root->left; } } /** @return whether we have a next smallest number */ bool hasNext() { return !s.empty(); } /** @return the next smallest number */ int next() { TreeNode *cur = s.top(); s.pop(); int val = cur->val; if(cur->right) { cur = cur->right; while(cur) { s.push(cur); cur = cur->left; } } return val; } }; ================================================ FILE: cpp/171-180/Dungeon Game.cpp ================================================ class Solution { public: int calculateMinimumHP(vector > &dungeon) { int M = dungeon.size(); int N = dungeon[0].size(); vector> v(M, vector(N, 0) ); for(int i = M-1;i >= 0;i--) { for(int j = N-1;j >=0;j--) { if(i == M-1 && j == N-1) { v[i][j] = max(1, 1 - dungeon[i][j]); } else if(i == M-1) { v[i][j] = max(1, v[i][j+1] - dungeon[i][j]); } else if(j == N-1) { v[i][j] = max(1, v[i+1][j] - dungeon[i][j]); } else { v[i][j] = max(1, min(v[i+1][j],v[i][j+1]) - dungeon[i][j]); } } } return v[0][0]; } }; ================================================ FILE: cpp/171-180/Excel Sheet Column Number.cpp ================================================ class Solution { public: int titleToNumber(string s) { return s.length() == 0 ? 0 : (s.back() - 'A' + 1 ) + 26*titleToNumber(s.substr(0,s.length()-1)); } }; ================================================ FILE: cpp/171-180/Factorial Trailing Zeroes.cpp ================================================ class Solution { public: int trailingZeroes(int n) { return n == 0 ? 0 : n/5 + trailingZeroes(n/5); } }; ================================================ FILE: cpp/171-180/Largest Number.cpp ================================================ class Solution { public: string largestNumber(vector& nums) { string res; bool flag = false; vector numStr; for (int num : nums) { if (num != 0) flag = true; numStr.emplace_back(to_string(num)); } auto cmp = [](const string& i, const string& j) { return i + j > j + i; }; sort(numStr.begin(), numStr.end(), cmp); for (const string& str : numStr) { res += str; } return flag ? res : "0"; } }; ================================================ FILE: cpp/181-190/Best Time to Buy and Sell Stock IV.cpp ================================================ class Solution { int help(vector &prices) { int res(0); for(int i = 0;i < prices.size()-1;i++) if(prices[i+1] > prices[i]) res += (prices[i+1] - prices[i]); return res; } public: int maxProfit(int k, vector &prices) { int len = prices.size(); if(len < 2) return 0; if(k >= len/2) return help(prices); vector >p(k+1, vector(len+1, 0)); for(int i = 1;i <= k;i++) { int tmp = -prices[0]; for(int j = 1;j <= len;j++) { p[i][j] = max(p[i][j-1], tmp+prices[j-1]); tmp = max(tmp, p[i-1][j-1] - prices[j-1]); } } return p[k][len]; } }; ================================================ FILE: cpp/181-190/Repeated DNA Sequences.cpp ================================================ class Solution { private: inline int change(char ch) { if (ch == 'A') return 0; if (ch == 'C') return 1; if (ch == 'G') return 2; return 3; } public: vector findRepeatedDnaSequences(string s) { unordered_map m; int len = s.length(); vectorresults; int tmp(0); for(int i = 0;i < 10;i++) { tmp *= 4; tmp += change(s[i]); } m[tmp] = 1; for (int i = 1; i <= len-10; i++) { tmp = tmp - change(s[i-1])*262144; tmp *= 4; tmp += change(s[i+9]); if (m[tmp] == -1) continue; else if(m[tmp] == 1) { results.push_back(s.substr(i,10)); m[tmp] = -1; } else m[tmp] = 1; } return results; } }; ================================================ FILE: cpp/181-190/Reverse Bits.cpp ================================================ class Solution { public: uint32_t reverseBits(uint32_t n) { uint32_t result(0); for(int i = 0; i < 32; i++) result = (result<<1) + (n>>i &1); return result; } }; ================================================ FILE: cpp/181-190/Reverse Words in a String II.cpp ================================================ class Solution { public: void reverseWords(string &s) { reverse(s.begin(), s.end()); int storeIndex(0); for (int i = 0; i < s.size(); i++) { if (s[i] != ' ') { if (storeIndex != 0) s[storeIndex++] = ' '; int j = i; while (j < s.size() && s[j] != ' ') { s[storeIndex++] = s[j++]; } reverse(s.begin() + storeIndex - (j - i), s.begin() + storeIndex); i = j; } } s.resize(storeIndex); } }; ================================================ FILE: cpp/181-190/Rotate Array.cpp ================================================ class Solution { public: void rotate(vector& nums, int k) { int base(0); int n = nums.size(); for(; k %= n; n -= k) for(int i = 0;i < k;i++) swap(nums[base++], nums[n-k+base]); } }; ================================================ FILE: cpp/191-200/Binary Tree Right Side View.cpp ================================================ #include #include #include using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: vector rightSideView(TreeNode *root) { vector r; if(root == NULL) return r; vectornode; node.push_back(root); while(node.size() > 0) { r.push_back(node.back()->val); size_t len = node.size(); for(int i = 0;i < len;i++) { if(node[i]->left)node.push_back(node[i]->left); if(node[i]->right)node.push_back(node[i]->right); } node.erase(node.begin(), node.begin()+len); } return r; } }; int main() { Solution s; struct TreeNode* root = new TreeNode(1); root->left = new TreeNode(2); root->right = new TreeNode(3); root->left->left = new TreeNode(4); root->left->right = new TreeNode(5); root->right->left = new TreeNode(6); root->right->right = new TreeNode(7); root->right->left->right = new TreeNode(8); cout << s.rightSideView(root).size(); return 0; } ================================================ FILE: cpp/191-200/House Robber.cpp ================================================ class Solution { public: int rob(vector &num) { if (num.empty()) return 0; int p[num.size()]; p[0] = num[0]; p[1] = max(num[0], num[1]); for (int i = 2;i < num.size();i++) p[i] = max(p[i-2] + num[i], p[i-1]); return p[num.size()-1]; } }; ================================================ FILE: cpp/191-200/Number of 1 Bits.cpp ================================================ class Solution { public: int hammingWeight(uint32_t n) { int hamming_weight(0); while (n > 0) { n = n & (n-1); hamming_weight++; } return hamming_weight; } }; ================================================ FILE: cpp/191-200/Number of Islands.cpp ================================================ class Solution { inline bool valid(int i, int j) { if (i >= 0 && j >= 0 && i < M && j < N) return true; return false; } void mark(vector> &grid, int i, int j) { if (grid[i][j] == '0') return; grid[i][j] = '0'; if (valid(i+1,j)) mark(grid, i+1, j); if (valid(i-1,j)) mark(grid, i-1, j); if (valid(i,j+1)) mark(grid, i, j+1); if (valid(i,j-1)) mark(grid, i, j-1); } size_t M; size_t N; public: int numIslands(vector> &grid) { int result(0); if (grid.empty() || grid[0].empty()) return 0; M = grid.size(); N = grid[0].size(); for (int i = 0;i < M;i++) { for (int j = 0;j < N;j++) { if(grid[i][j] == '1') { result++; mark(grid, i, j); } } } return result; } }; ================================================ FILE: cpp/191-200/Reverse Bits.cpp ================================================ #include #include #include using namespace std; class Solution { public: uint32_t reverseBits(uint32_t n) { uint32_t r(0); for(int i = 0;i < 32;i++) r += ((n >> i) & 1) * (1 << (31-i)); return r; } }; int main() { Solution s; cout << s.reverseBits(43261596); } ================================================ FILE: cpp/201-210/Bitwise AND of Numbers Range.cpp ================================================ class Solution { int maxBit(int num) { int ans = 0; while(num > 0) { num = num >> 1; if(ans == 0) ans = 1; else ans *= 2; } return ans; } public: int rangeBitwiseAnd(int m, int n) { if(m == 0) return 0; int m_maxbit = maxBit(m); int n_maxbit = maxBit(n); if(m_maxbit != n_maxbit) return 0; return m_maxbit + rangeBitwiseAnd(m - m_maxbit, n - n_maxbit); } }; ================================================ FILE: cpp/201-210/Count Primes.cpp ================================================ #include #include #include #include using namespace std; class Solution { public: int countPrimes(int n) { if(n < 3) return 0; int limit = sqrt(n); int r(n-2); bool *A = new bool[n+1]; memset(A, true, n+1); for(int i = 2;i <= limit;i++) { if(A[i] == true) { for(int j = i*i;j < n;j += i) { if(A[j] == true) r--; A[j] = false; } } } return r; } }; int main() { Solution s; cout << s.countPrimes(2); } ================================================ FILE: cpp/201-210/Course Schedule II.cpp ================================================ struct Node { int state; vector edges; Node() : state(0) { } }; class Solution { vector Nodes; bool DFS_VISIT(int u, vector& v) { Nodes[u].state = 1; for (int i = 0;i < Nodes[u].edges.size();i++) { int num = Nodes[u].edges[i]; if (Nodes[num].state == 0) { bool hascircle = !DFS_VISIT(num, v); if(hascircle) return false; } else if (Nodes[num].state == 1) { return false; } } Nodes[u].state = 2; v.push_back(u); return true; } public: vector findOrder(int numCourses, vector>& prerequisites) { vectororders; Nodes.resize(numCourses); for (int i = 0;i < prerequisites.size();i++) Nodes[prerequisites[i].first].edges.push_back(prerequisites[i].second); for (int i = 0;i < numCourses;i++) { if (Nodes[i].state != 0) continue; bool hascircle = !DFS_VISIT(i, orders); if (hascircle) return vector(); } return orders; } }; ================================================ FILE: cpp/201-210/Course Schedule.cpp ================================================ struct Node { int state; vector edges; Node() : state(0) { } }; class Solution { vector Nodes; bool dfs_visit(int u) { Nodes[u].state = 1; for (int i = 0;i < Nodes[u].edges.size();i++) { int num = Nodes[u].edges[i]; if(Nodes[num].state == 0) { bool hascircle = !dfs_visit(num); if(hascircle) return false; } else if(Nodes[num].state == 1) { return false; } } Nodes[u].state = 2; return true; } public: bool canFinish(int numCourses, vector>& prerequisites) { Nodes.resize(numCourses); for (int i = 0;i < prerequisites.size();i++) Nodes[prerequisites[i].first].edges.push_back(prerequisites[i].second); for (int i = 0;i < numCourses;i++) { bool hascircle = !dfs_visit(i); if(hascircle) return false; } return true; } }; ================================================ FILE: cpp/201-210/Happy Number.cpp ================================================ class Solution { int SumSquare(int n) { int r(0); while(n > 0) { int tmp = n%10; n = (n - tmp)/10; r += tmp*tmp; } return r; } public: bool isHappy(int n) { set _set; while(true) { if (_set.count(n) == 1) return false; if (n == 1) return true; _set.insert(n); n = SumSquare(n); } return false; } }; ================================================ FILE: cpp/201-210/Implement Trie (Prefix Tree).cpp ================================================ struct TrieNode { TrieNode *nodes[26]; bool word; // Initialize your data structure here. TrieNode(): word(false) { memset(nodes, 0, sizeof(nodes)); } }; class Trie { public: Trie() { root = new TrieNode(); } // Inserts a word into the trie. void insert(const string& s) { TrieNode *tmp = root; for(char ch : s) { int index = ch - 'a'; if(tmp->nodes[index] == nullptr) { tmp->nodes[index] = new TrieNode(); } tmp = tmp->nodes[index]; } tmp->word = true; } // Returns if the word is in the trie. bool search(const string& key) const { TrieNode *tmp = root; for(char ch : key) { int index = ch - 'a'; if(tmp->nodes[index] == nullptr) { return false; } tmp = tmp->nodes[index]; } return tmp->word; } // Returns if there is any word in the trie // that starts with the given prefix. bool startsWith(const string& prefix) const { TrieNode *tmp = root; for(char ch : prefix) { int index = ch - 'a'; if(tmp->nodes[index] == nullptr) { return false; } tmp = tmp->nodes[index]; } return true; } private: TrieNode* root; }; ================================================ FILE: cpp/201-210/Isomorphic Strings.cpp ================================================ class Solution { public: bool isIsomorphic(string s, string t) { map_m; bool _p[256] = {false}; int len1 = s.length(); for (int i = 0;i < len1;i++) { char c1 = s[i]; char c2 = t[i]; if (_m.count(c1) == 0) { if(_p[c2]) return false; _m[c1] = c2; _p[c2] = true; } else { if (_m[c1] != c2) return false; } } return true; } }; ================================================ FILE: cpp/201-210/Minimum Size Subarray Sum.cpp ================================================ class Solution { public: int minSubArrayLen(int s, vector& nums) { int i(0),j(0),sum(0); int len(INT_MAX); nums.push_back(-1); while (j < nums.size()) { if (sum >= s) { len = min(len, j-i); sum -= nums[i]; i++; } else { sum += nums[j]; j++; } } if (len == INT_MAX) return 0; return len; } }; ================================================ FILE: cpp/201-210/Remove Linked List Elements.cpp ================================================ class Solution { public: ListNode* removeElements(ListNode* head, int val) { ListNode* res = new ListNode(1); res->next = head; ListNode* backup = res; //res -> head -> head->next while (head) { if (head->val == val) res->next = head->next; else res = head; head = head->next; } return backup->next; } }; ================================================ FILE: cpp/201-210/Reverse Linked List.cpp ================================================ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { ListNode *tmp(nullptr), *prev(nullptr); while (head != nullptr) { tmp = head->next; head->next = prev; prev = head; head = tmp; } return prev; } }; ================================================ FILE: cpp/211-220/Add and Search Word - Data structure design.cpp ================================================ class TrieNode { public: TrieNode *nodes[26]; bool word; // Initialize your data structure here. TrieNode() { word = false; for(int i = 0;i < 26;i++) nodes[i] = nullptr; } }; class Trie { bool _search(string word, int offset, TrieNode *node) { if (node == nullptr) return false; if (offset == word.length()) return node->word; if (word[offset] == '.') { for (int j = 0; j < 26; j++) { bool fff = _search(word, offset+1, node->nodes[j]); if (fff) return true; } return false; } else { return _search(word, offset+1, node->nodes[word[offset]-'a']); } } public: Trie() { root = new TrieNode(); } // Inserts a word into the trie. void insert(string s) { TrieNode *tmp = root; for (int i = 0; i < s.length(); i++) { int index = s[i] - 'a'; if(tmp->nodes[index] == nullptr) tmp->nodes[index] = new TrieNode(); tmp = tmp->nodes[index]; } tmp->word = true; } // Returns if the word is in the trie. bool search(string word) { return _search(word, 0, root); } private: TrieNode* root; }; class WordDictionary { Trie trie; public: // Adds a word into the data structure. void addWord(string word) { trie.insert(word); } // Returns if the word is in the data structure. A word could // contain the dot character '.' to represent any one letter. bool search(string word) { return trie.search(word); } }; // Your WordDictionary object will be instantiated and called as such: // WordDictionary wordDictionary; // wordDictionary.addWord("word"); // wordDictionary.search("pattern"); ================================================ FILE: cpp/211-220/Combination Sum III.cpp ================================================ class Solution { void help(vector& now, int index, int num, int target, vector>& results) { if (num == 0) { return; } for (int i = index; i <= 9; i++) { if (i < target) { now.push_back(i); help(now, i+1, num-1, target-i, results); now.pop_back(); } else if (i == target && num == 1) { now.push_back(i); results.push_back(now); now.pop_back(); } } } public: vector> combinationSum3(int k, int n) { vector> results; vectortmp; help(tmp, 1, k, n, results); return results; } }; ================================================ FILE: cpp/211-220/Contains Duplicate II.cpp ================================================ class Solution { public: bool containsNearbyDuplicate(vector& nums, int k) { unordered_map m; for (int i = 0; i < nums.size(); i++) { if (m.find(nums[i]) != m.end() && i - m[nums[i]] <= k)return true; else m[nums[i]] = i; } return false; } }; ================================================ FILE: cpp/211-220/Contains Duplicate III.cpp ================================================ class Solution { public: bool containsNearbyAlmostDuplicate(vector& nums, int k, int t) { set window; // set is ordered automatically for (int i = 0; i < nums.size(); i++) { if (i > k) window.erase(nums[i-k-1]); // keep the set contains nums i j at most k // -t <= x - nums[i] <= t; auto pos = window.lower_bound((long)nums[i] - (long)t); // x >= nums[i] - t if (pos != window.end() && *pos - nums[i] <= t) // x <= nums[i] + t return true; window.insert(nums[i]); } return false; } }; ================================================ FILE: cpp/211-220/Contains Duplicate.cpp ================================================ class Solution { public: bool containsDuplicate(std::vector& nums) { std::sort(nums.begin(), nums.end()); for (int i = 1; i < nums.size(); ++i) if (nums[i] == nums[i - 1]) return true; return false; } }; ================================================ FILE: cpp/211-220/House Robber II.cpp ================================================ class Solution { public: int rob(vector& nums) { if (nums.size() == 0) return 0; if (nums.size() == 1) return nums[0]; int pre1(0), cur1(0); for (int i = 0; i < nums.size() - 1; ++ i) { int temp = pre1; pre1 = cur1; cur1 = max(temp + nums[i], pre1); } int pre2(0), cur2(0); for (int i = 1; i < nums.size(); ++ i) { int temp = pre2; pre2 = cur2; cur2 = max(temp + nums[i], pre2); } return max(cur1, cur2); } }; ================================================ FILE: cpp/211-220/Kth Largest Element in an Array.cpp ================================================ class Solution { int kthSmallest(vector& arr, int l, int r, int k) { if (k > 0 && k <= r - l + 1) { int pos = randomPartition(arr, l, r); if (pos-l == k-1) return arr[pos]; else if (pos-l > k-1) return kthSmallest(arr, l, pos-1, k); else return kthSmallest(arr, pos+1, r, k-pos+l-1); } return INT_MAX; } int partition(vector& arr, int l, int r) { int x = arr[r], i = l; for (int j = l; j <= r - 1; j++) { if (arr[j] <= x) { swap(arr[i], arr[j]); i++; } } swap(arr[i], arr[r]); return i; } int randomPartition(vector& arr, int l, int r) { int n = r-l+1; int pivot = rand() % n; swap(arr[l + pivot], arr[r]); return partition(arr, l, r); } public: int findKthLargest(vector& nums, int k) { return kthSmallest(nums, 0, nums.size()-1, nums.size()-k+1); } }; ================================================ FILE: cpp/211-220/Shortest Palindrome.cpp ================================================ class Solution { private: string preProcess(string s) { int n = s.length(); if (n == 0) return "^$"; string ret = "^"; for (int i = 0; i < n; i++) ret += "#" + s.substr(i, 1); ret += "#$"; return ret; } public: string shortestPalindrome(string s) { string T = preProcess(s); int n = T.length(); int P[n]; int c = 0,r = 0; for(int i = 1;i < n;i++) { int mirror_i = 2*c-i; P[i] = r > i ? min(P[mirror_i], r-i) : 0; while (T[i + 1 + P[i]] == T[i - 1 - P[i]]) P[i]++; if (i + P[i] > r) { c = i; r = i + P[i]; } } int maxLen = 0; int centerIndex = 0; for (int i = 1; i < n-1; i++) { if (1==i-P[i]) maxLen = P[i]; } string temp = s.substr(maxLen); reverse(temp.begin(),temp.end()); return temp+s; } }; ================================================ FILE: cpp/211-220/The Skyline Problem.cpp ================================================ class Solution { public: vector> getSkyline(vector>& buildings) { vector > ret; auto cmp = [&](const pair &a, const pair &b){ return a.first >= b.first; }; priority_queue, vector>, decltype(cmp)> points(cmp); for(const auto& e : buildings) { points.push(make_pair(e[0], e[2])); points.push(make_pair(e[1], e[2] * -1)); } multiset> sky; sky.insert(0); while (!points.empty()){ int last_height = *sky.begin(); int cur = points.top().first; while (!points.empty() && points.top().first == cur){ int height = points.top().second; if (height > 0){ sky.insert(height); }else{ sky.erase(sky.find(height * -1)); } points.pop(); } if (*sky.begin() != last_height){ ret.push_back(make_pair(cur, *sky.begin())); } } return ret; } }; ================================================ FILE: cpp/211-220/Word Search II.cpp ================================================ const int ALPHA_NUM = 26; struct TrieNode{ TrieNode* childs[ALPHA_NUM]; TrieNode* father; char ch; bool isEndOfWord; TrieNode() :isEndOfWord(false), father(NULL), ch(0) { fill_n(childs, ALPHA_NUM, nullptr); } }; class Solution { TrieNode *root; unordered_set visitedNodes; vector res; public: Solution(){ root = new TrieNode(); } void insert(string word){ TrieNode *curnode = root; for (auto ch : word) { int curidx = ch - 'a'; if (curnode->childs[curidx] == NULL) { curnode->childs[curidx] = new TrieNode(); curnode->childs[curidx]->father = curnode; curnode->childs[curidx]->ch = ch; } curnode = curnode->childs[curidx]; } curnode->isEndOfWord = true; } string getWord(TrieNode *curnode){ string res = ""; while (curnode->father != NULL) { res.push_back(curnode->ch); curnode = curnode->father; } reverse(res.begin(), res.end()); return res; } void DFS(vector>& board, int r, int c, TrieNode *curnode){ if (curnode->isEndOfWord) { if (visitedNodes.find(curnode) == visitedNodes.end()) { visitedNodes.insert(curnode); res.push_back(getWord(curnode)); } } pair pos[4] = {{0,1},{0,-1},{1,0},{-1,0}}; for(int i = 0;i < 4;i++) { int nr = r + pos[i].first; int nc = c + pos[i].second; if(nr >= 0 && nr < board.size() && nc >= 0 && nc < board[0].size() && board[nr][nc] != '-') { int curidx = board[nr][nc] - 'a'; if (curnode->childs[curidx] != NULL) { board[nr][nc] = '-'; DFS(board, nr, nc, curnode->childs[curidx]); board[nr][nc] = curidx + 'a'; } } } } vector findWords(vector>& board, vector& words) { for (int i = 0;i < words.size();i++) insert(words[i]); for (int j = 0; j < board.size(); ++j) { for (int k = 0; k < board[j].size(); ++k) { int curidx = board[j][k] - 'a'; if (root->childs[curidx] != NULL) { board[j][k] = '-'; DFS(board, j, k, root->childs[curidx]); board[j][k] = curidx + 'a'; } } } return res; } }; ================================================ FILE: cpp/221-230/Basic Calculator II.cpp ================================================ class Solution { void apply(stack& s, stack& symbol) { char c = symbol.top();symbol.pop(); int b = s.top();s.pop(); int a = s.top();s.pop(); if (c == '+') s.push(a+b); else if (c == '-') s.push(a-b); else if (c == '*') s.push(a*b); else s.push(a/b); } public: int calculate(string s) { stack symbol; stackss; int v = 0; bool number = false; for (char e : s) { if (number && !isdigit(e)) { ss.push(v); v = 0; number = false; } if (e == ' ') continue; if (isdigit(e)) { v = 10*v + (e-'0'); number = true; } else if (e == '+' || e == '-') { while (!symbol.empty()) { apply(ss, symbol); } symbol.push(e); } else if (e == '*' || e == '/') { if (!symbol.empty()) { if (symbol.top() == '*' || symbol.top() == '/') { apply(ss, symbol); } } symbol.push(e); } } if (number) ss.push(v); while (!symbol.empty()) { apply(ss, symbol); } return ss.top(); } }; ================================================ FILE: cpp/221-230/Basic Calculator.cpp ================================================ class Solution { void apply(stack& s, stack& symbol) { char c = symbol.top(); symbol.pop(); int b = s.top();s.pop(); int a = s.top();s.pop(); if(c == '+') s.push(a+b); else s.push(a-b); } public: int calculate(string s) { s = "(" + s + ")"; stack symbol; stack nums; int v = 0; bool number = false; for (char e : s) { if (number && !isdigit(e)) { nums.push(v); v = 0; number = false; } if (e == ')') { while (symbol.top() != '(') { apply(nums, symbol); } symbol.pop(); } else if (e == '(') { symbol.push('('); } else if (isdigit(e)) { v = 10*v + (e-'0'); number = true; } else if (e == '+' || e == '-') { if (!symbol.empty() && symbol.top() != '(') { apply(nums, symbol); } symbol.push(e); } } return nums.top(); } }; ================================================ FILE: cpp/221-230/Count Complete Tree Nodes.cpp ================================================ class Solution { public: int countNodes(TreeNode* root) { if(!root) return 0; int lh(0),rh(0); TreeNode *l(root), *r(root); while(l) { lh++; l = l->left; } while(r) { rh++; r = r->right; } if(lh == rh) return pow(2, lh) - 1; else return 1 + countNodes(root->left) + countNodes(root->right); } }; ================================================ FILE: cpp/221-230/Implement Stack using Queues.cpp ================================================ class Stack { queue q1; queue q2; int v; public: // Push element x onto stack. void push(int x) { if (!q1.empty()) q1.push(x); else q2.push(x); v = x; } // Removes the element on top of the stack. void pop() { if (!q1.empty()) { while (!q1.empty()) { int tmp = q1.front(); if (q1.size() > 1) q2.push(tmp); if (q1.size() == 2) v= tmp; q1.pop(); } } else { while (!q2.empty()) { int tmp = q2.front(); if (q2.size() > 1) q1.push(tmp); if (q2.size() == 2) v= tmp; q2.pop(); } } } // Get the top element. int top() { return v; } // Return whether the stack is empty. bool empty() { return q1.empty() && q2.empty(); } }; ================================================ FILE: cpp/221-230/Invert Binary Tree.cpp ================================================ class Solution { public: TreeNode* invertTree(TreeNode* root) { if(!root) return nullptr; swap(root->left, root->right); invertTree(root->left); invertTree(root->right); return root; } }; ================================================ FILE: cpp/221-230/Kth Smallest Element in a BST.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int kthSmallest(TreeNode* root, int k) { stacks; TreeNode *p = root; while(p || !s.empty()) { while(p) { s.push(p); p = p->left; } p = s.top(); s.pop(); k--; if (k == 0) return p->val; p = p->right; } return -1; } }; ================================================ FILE: cpp/221-230/Majority Element II.cpp ================================================ class Solution { public: vector majorityElement(vector& nums) { int cnt1 = 0, cnt2 = 0, a = 0, b = 1; for(int n: nums){ if (a == n) { cnt1++; } else if (b == n) { cnt2++; } else if (cnt1 == 0) { a = n; cnt1 = 1; } else if (cnt2 == 0){ b = n; cnt2 = 1; } else { cnt1--; cnt2--; } } cnt1 = cnt2 = 0; for (int n: nums){ if (n == a) cnt1++; else if (n == b) cnt2++; } vector res; if (cnt1 > nums.size()/3) res.push_back(a); if (cnt2 > nums.size()/3) res.push_back(b); return res; } }; ================================================ FILE: cpp/221-230/Maximal Square.cpp ================================================ class Solution { public: int maximalSquare(vector>& matrix) { if (matrix.empty() || matrix.front().empty()) return 0; int m = matrix.size(); int n = matrix.front().size(); vector> dp(m, vector(n, 0)); int maxLen = 0; for (int i = 0; i < m; i++) { for (int j = 0;j < n; j++) { if (matrix[i][j] == '1') { dp[i][j] = 1; if (i > 0 && j > 0) { int tmp = min(dp[i-1][j-1], min(dp[i][j-1], dp[i-1][j])); dp[i][j] = max(dp[i][j], tmp+1); } } maxLen = max(maxLen, dp[i][j]); } } return maxLen*maxLen; } }; ================================================ FILE: cpp/221-230/Rectangle Area.cpp ================================================ class Solution { int overlapLen(int a1, int a2, int b1, int b2) { if (a1 > b1) return overlapLen(b1, b2, a1, a2); int left = b1; int right = min(a2, b2); if (right <= left) return 0; return right - left; } public: int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int area1 = (C - A) * (D - B); int area2 = (G - E) * (H - F); int width = overlapLen(A, C, E, G); int height = overlapLen(B, D, F, H); return area1 + area2 - width*height; } }; ================================================ FILE: cpp/221-230/Summary Ranges.cpp ================================================ class Solution { public: vector summaryRanges(vector& nums) { vector res; if (nums.empty()) return res; int i(0); while (i < nums.size()) { int start(nums[i]); while (i+1 < nums.size() && nums[i] == nums[i+1]-1) i++; if (start == nums[i]) res.push_back(to_string(start)); else res.push_back(to_string(start)+"->"+to_string(nums[i])); i++; } return res; } }; ================================================ FILE: cpp/231-240/Delete Node in a Linked List.cpp ================================================ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: void deleteNode(ListNode* node) { ListNode* nextNode = node->next; *node = *nextNode; delete nextNode; } }; ================================================ FILE: cpp/231-240/Implement Queue using Stacks.cpp ================================================ class MyQueue { stacks1; stacks2; public: /** Initialize your data structure here. */ MyQueue() { } /** Push element x to the back of queue. */ void push(int x) { s1.push(x); } /** Removes the element from in front of queue and returns that element. */ int pop() { int x = peek(); s2.pop(); return x; } /** Get the front element. */ int peek() { if(s2.empty()) transit(); return s2.top(); } void transit() { while(!s1.empty()) { int v = s1.top(); s1.pop(); s2.push(v); } } /** Returns whether the queue is empty. */ bool empty() { return s1.empty() && s2.empty(); } }; /** * Your MyQueue object will be instantiated and called as such: * MyQueue obj = new MyQueue(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.peek(); * bool param_4 = obj.empty(); */ ================================================ FILE: cpp/231-240/Lowest Common Ancestor of a Binary Search Tree.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { int v1(p->val), v2(q->val); while (root) { int v = root->val; if ((v > v1 && v > v2)) root = root->left; else if (v < v1 && v < v2) root = root->right; else return root; } return root; } }; ================================================ FILE: cpp/231-240/Lowest Common Ancestor of a Binary Tree.cpp ================================================ class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (root == nullptr) { return nullptr; } if (root == p || root == q) { return root; } TreeNode* l = lowestCommonAncestor(root->left, p, q); TreeNode* r = lowestCommonAncestor(root->right, p, q); if (l && r) { return root; } return l ? l : r; } }; ================================================ FILE: cpp/231-240/Number of Digit One.cpp ================================================ class Solution { public: int countDigitOne(int n) { int res(0), m(1), r(1); while(n > 0) { res += ((n+8)/10 * m + (n%10 == 1? r : 0)); r += (n%10)*m; m *= 10; n /= 10; } return res; } }; ================================================ FILE: cpp/231-240/Palindrome Linked List.cpp ================================================ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: bool isPalindrome(ListNode* head) { if(!head || !head->next) return true; ListNode *slow(head),*fast(head); while(fast->next && fast->next->next){ slow = slow->next; fast = fast->next->next; } slow = reverseList(slow->next); while(slow){ if(head->val != slow->val) return false; head = head->next; slow = slow->next; } return true; } ListNode* reverseList(ListNode* head) { ListNode *tmp(NULL),*prev(NULL); while(head) { tmp = head->next; head->next = prev; prev = head; head = tmp; } return prev; } }; ================================================ FILE: cpp/231-240/Power of Two.cpp ================================================ class Solution { public: bool isPowerOfTwo(int n) { return n > 0 && !(n & (n-1)); } }; ================================================ FILE: cpp/231-240/Product of Array Except Self.cpp ================================================ class Solution { public: vector productExceptSelf(vector& nums) { vectorres(nums.size(), 1); for (int i = 1; i < nums.size(); i++) { res[i] = res[i-1] * nums[i-1]; } int tmp = 1; for (int i = nums.size() - 1; i >= 0; i--) { res[i] *= tmp; tmp *= nums[i]; } return res; } }; ================================================ FILE: cpp/231-240/Search a 2D Matrix II.cpp ================================================ class Solution { public: bool searchMatrix(vector>& matrix, int target) { if (matrix.empty() || matrix.front().empty()) return false; int i = matrix.size()-1; int j = 0; while (i >= 0 && j <= matrix[0].size()-1) { if(matrix[i][j] == target) return true; else if(matrix[i][j] < target) j++; else i--; } return false; } }; ================================================ FILE: cpp/231-240/Sliding Window Maximum.cpp ================================================ class Solution { public: vector maxSlidingWindow(vector& nums, int k) { deque myqueue; vector res; for(int i = 0;i < nums.size();i++){ if(!myqueue.empty() && myqueue.front() == i - k) myqueue.pop_front(); while(!myqueue.empty() && nums[myqueue.back()] < nums[i]) myqueue.pop_back(); myqueue.push_back(i); if(i >= k - 1) res.push_back(nums[myqueue.front()]); } return res; } }; ================================================ FILE: cpp/241-250/Count Univalue Subtrees.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { int result; bool help(TreeNode* root) { if(!root) return true; if(!root->left && !root->right) {result++;return true;} bool left = help(root->left); bool right = help(root->right); if(!left || !right) return false; if(root->left && root->right) { if(root->left->val == root->val && root->right->val == root->val) { result++; return true; } else return false; } else if(root->left && root->left->val == root->val) { result++; return true; } else if(root->right && root->right->val == root->val) { result++; return true; } return false; } public: int countUnivalSubtrees(TreeNode* root) { result = 0; help(root); return result; } }; ================================================ FILE: cpp/241-250/Different Ways to Add Parentheses.cpp ================================================ class Solution { public: vector diffWaysToCompute(string input) { vector output; for (int i=0; i{stoi(input)}; } }; ================================================ FILE: cpp/241-250/Group Shifted Strings.cpp ================================================ class Solution { bool pattern_match(const string &s1, const string &s2) { if (s1.length() != s2.length()) return false; int v(-1); for (int i = 0; i < s1.length(); i++) { int temp = (s2[i]-s1[i])%26; if (temp < 0) temp += 26; if (v < 0) v= temp; if (temp != v) return false; } return true; } public: vector> groupStrings(vector& strings) { vector> result; for (int i = 0; i < strings.size(); i++) { string cur = strings[i]; bool match(false); for (int j = 0; j < result.size(); j++) { if (pattern_match(cur, result[j][0])) { result[j].push_back(cur); match = true; break; } } if (!match) { vector pattern; pattern.push_back(cur); result.push_back(pattern); } } for (int i = 0; i < result.size(); i++) sort(result[i].begin(), result[i].end()); return result; } }; ================================================ FILE: cpp/241-250/Shortest Word Distance II.cpp ================================================ class WordDistance { unordered_map> m; public: WordDistance(vector& words) { for (int i = 0; i < words.size(); i++) { m[words[i]].push_back(i); } } int shortest(string word1, string word2) { const vector& v1 = m[word1]; const vector& v2 = m[word2]; int i = 0; int j = 0; int res = INT_MAX; while (i < v1.size() && j < v2.size()) { int i1 = v1[i]; int i2 = v2[j]; res = min(abs(i1-i2), res); if(i1 > i2) { j++; } else { i++; } } return res; } }; ================================================ FILE: cpp/241-250/Shortest Word Distance III.cpp ================================================ class Solution { public: int shortestWordDistance(vector& words, string word1, string word2) { int index1(-1), index2(-1), shortest(INT_MAX); if(word1 == word2) { int i = 0; while(index1 == -1) { if(words[i] == word1) index1 = i; i++; } while(i < words.size()) { if(words[i] == word1) { shortest = min(i - index1, shortest); index1 = i; } i++; } } else { for(int i = 0;i < words.size();i++) { if(words[i] == word1) { index1 = i; } else if(words[i] == word2) { index2 = i; } if(index1 == -1 || index2 == -1) continue; shortest = min(abs(index1 - index2), shortest); } } return shortest; } }; ================================================ FILE: cpp/241-250/Shortest Word Distance.cpp ================================================ class Solution { public: int shortestDistance(vector& words, string word1, string word2) { int index1(-1), index2(-1), shortest(INT_MAX); for(int i = 0;i < words.size();i++) { if(words[i] == word1) { index1 = i; } else if(words[i] == word2) { index2 = i; } if(index1 == -1 || index2 == -1) continue; shortest = min(abs(index1 - index2), shortest); } return shortest; } }; ================================================ FILE: cpp/241-250/Strobogrammatic Number II.cpp ================================================ class Solution { public: vector findStrobogrammatic(int n) { return helper(n , n); } vector helper(int m, int n){ if(m == 0) return vector({""}); if(m == 1) return vector({"0", "1", "8"}); vector tmp = helper(m - 2, n), res; for(int i = 0; i < tmp.size(); i++){ if(m != n) res.push_back("0" + tmp[i] + "0"); res.push_back("1" + tmp[i] + "1"); res.push_back("6" + tmp[i] + "9"); res.push_back("8" + tmp[i] + "8"); res.push_back("9" + tmp[i] + "6"); } return res; } }; ================================================ FILE: cpp/241-250/Strobogrammatic Number III.cpp ================================================ class Solution { int r = 0; map m; char chs[5] = {'1','6','9','8','0'}; bool check(const string& low, const string& high) { if (high.length() > low.length()) return true; if (high.length() < low.length()) return false; return high >= low; } void help(string temp, int cur, int n, const string& low, const string& high) { if (n >= 2 && temp[0] == '0') return; if (cur == (n+1)/2) { if (check(low, temp) && check(temp, high)) {r++;} return; } for (int i = 0; i <= 4; i++) { temp[cur] = chs[i]; temp[n - cur - 1] = m[chs[i]]; if (n % 2 == 1 && cur == n/2 && chs[i] != m[chs[i]]) {} else help(temp, cur+1, n, low, high); } } public: int strobogrammaticInRange(string low, string high) { m['6'] = '9'; m['9'] = '6'; m['1'] = '1'; m['8'] = '8'; m['0'] = '0'; int n1 = low.length(); int n2 = high.length(); for (int n = n1; n <= n2; n++) { string temp(n,'1'); help(temp, 0, n, low, high); } return r; } }; ================================================ FILE: cpp/241-250/Strobogrammatic Number.cpp ================================================ class Solution { public: bool isStrobogrammatic(string num) { unordered_map m = {{'0', '0'}, {'1', '1'}, {'6','9'}, {'8','8'}, {'9', '6'}}; int len(num.length()); for (int i = 0;i < (len+1)/2;i++) { if(m.count(num[i]) == 0) return false; if(m[num[i]] != num[len - i - 1]) return false; } return true; } }; ================================================ FILE: cpp/241-250/Valid Anagram.cpp ================================================ class Solution { public: bool isAnagram(string s, string t) { int a[255] = {0}; for(auto e : s) a[e]++; for(auto e : t) a[e]--; for(int i = 0;i < 255;i++) if(a[i] != 0) return false; return true; } }; ================================================ FILE: cpp/251-260/3Sum Smaller.cpp ================================================ class Solution { public: int threeSumSmaller(vector& nums, int target) { if (nums.size() < 3) return 0; sort(nums.begin(), nums.end()); int result(0); for (int i = 0;i < nums.size()-2;i++) { int j(i+1), k(nums.size()-1); int remain = target - nums[i]; while(j < k) { if(nums[j] + nums[k] >= remain) { k--; } else { result += (k - j); j++; } } } return result; } }; ================================================ FILE: cpp/251-260/Add Digits.cpp ================================================ class Solution { public: int addDigits(int num) { return 1 + (num - 1) % 9; } }; ================================================ FILE: cpp/251-260/Binary Tree Paths.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { void help(TreeNode* root, string path, vector&paths) { path = path+to_string(root->val); if(root->left) help(root->left, path+"->", paths); if(root->right) help(root->right, path+"->", paths); if(!root->left && !root->right) paths.push_back(path); } public: vector binaryTreePaths(TreeNode* root) { vector res; if(root == nullptr) return res; help(root, "", res); return res; } }; ================================================ FILE: cpp/251-260/Factor Combinations.cpp ================================================ class Solution { private: vector> res; public: vector> getFactors(int n) { getFHelp(n, 2, vector()); return res; } void getFHelp(int n, int bottom, vector line) { for (int i = bottom; i<=sqrt(n); i++){ if (n%i == 0) { vector new_line(line); new_line.push_back(i); getFHelp(n/i, i, new_line); new_line.push_back(n/i); res.push_back(new_line); } } } }; ================================================ FILE: cpp/251-260/Flatten 2D Vector.cpp ================================================ class Vector2D { int j; vector>::iterator i, iEnd; public: Vector2D(vector>& vec2d) { j = 0; i = vec2d.begin(); iEnd = vec2d.end(); } int next() { hasNext(); return (*i)[j++]; } bool hasNext() { while (i != iEnd && j == (*i).size()) { i++; j = 0; } return i != iEnd; } }; /** * Your Vector2D object will be instantiated and called as such: * Vector2D i(vec2d); * while (i.hasNext()) cout << i.next(); */ ================================================ FILE: cpp/251-260/Meeting Rooms II.cpp ================================================ /** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class Solution { public: int minMeetingRooms(vector& intervals) { map mymap; for (const Interval& interval : intervals) { mymap[interval.start]++; mymap[interval.end]--; } int cnt = 0, maxCnt = 0; for (auto it = mymap.begin(); it != mymap.end(); it++) { cnt += it->second; maxCnt = max(cnt, maxCnt); } return maxCnt; } }; ================================================ FILE: cpp/251-260/Meeting Rooms.cpp ================================================ /** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class Solution { public: bool canAttendMeetings(vector& intervals) { auto comp = [&](const Interval &a, const Interval &b) { return a.start < b.start; }; sort(intervals.begin(), intervals.end(), comp); int n = intervals.size(); for (int i = 0; i < n - 1; i++) if (overlap(intervals[i], intervals[i + 1])) return false; return true; } private: bool overlap(Interval& interval1, Interval& interval2) { return interval1.end > interval2.start; } }; ================================================ FILE: cpp/251-260/Paint House.cpp ================================================ class Solution { public: int minCost(vector>& costs) { if(costs.size() == 0) return 0; int i1(costs[0][0]), i2(costs[0][1]), i3(costs[0][2]); for(int i = 1;i < costs.size();i++) { int o1(i1),o2(i2),o3(i3); i1 = min(o2,o3) + costs[i][0]; i2 = min(o1,o3) + costs[i][1]; i3 = min(o1,o2) + costs[i][2]; } int result = min(i1,i2); result = min(result, i3); return result; } }; ================================================ FILE: cpp/251-260/Single Number III.cpp ================================================ class Solution { public: vector singleNumber(vector& nums) { int diff = accumulate(nums.begin(), nums.end(), 0, bit_xor()); diff &= -diff; vector res(2, 0); for (int e : nums) { if(e & diff) res[0] ^= e; else res[1] ^= e; } return res; } }; ================================================ FILE: cpp/251-260/Verify Preorder Sequence in Binary Search Tree.cpp ================================================ /* 10 5 15 1 6 12 17 10 5 1 6 15 12 17 */ class Solution { public: bool verifyPreorder(vector& preorder) { stack mystack; int lower_bound_num(INT_MIN); for (int v : preorder) { if (v < lower_bound_num) return false; while (!mystack.empty() && v > mystack.top()) { lower_bound_num = mystack.top(); mystack.pop(); } mystack.push(v); } return true; } }; ================================================ FILE: cpp/261-270/Alien Dictionary.cpp ================================================ class Solution { bool dfs(char ch, unordered_map>& graph, unordered_map& colors, string& order) { colors[ch] = 1; for (char neighbor : graph[ch]) { if (colors[neighbor] == 1) { return true; } if (colors[neighbor] == 0) { bool has_circle = dfs(neighbor, graph, colors, order); if (has_circle) { return true; } } } order.push_back(ch); colors[ch] = 2; return false; } public: string alienOrder(vector& words) { unordered_map> graph; for (int i = 1; i < words.size(); i++) { int len = min(words[i-1].size(), words[i].size()); for (int j = 0; j < len; j++) { if (words[i-1][j] != words[i][j]) { graph[words[i-1][j]].push_back(words[i][j]); break; } if (j == len - 1 && words[i].size() < words[i-1].size()) { return ""; } } } unordered_map colors; for (const string& word : words) { for (char ch : word) { colors[ch] = 0; } } string res; for (const auto& [ch, color] : colors) { if (color == 0) { if (dfs(ch, graph, colors, res)) { return ""; } } } reverse(res.begin(), res.end()); return res; } }; ================================================ FILE: cpp/261-270/Closest Binary Search Tree Value.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int closestValue(TreeNode* root, double target) { int v = root->val; double diff(fabs(v - target)); while (root != nullptr) { if(fabs(root->val - target) <= diff) { diff = fabs(root->val - target); v = root->val; } if (target <= root->val) { root = root->left; } else { root = root->right; } } return v; } }; ================================================ FILE: cpp/261-270/Factor Combinations.cpp ================================================ class Solution { void help(vector>& result, vector& factors, vector temp, int cur, int n) { if(n == 1 && temp.size() > 0) { result.push_back(temp); return; } if(cur == factors.size() || n < factors[cur]) return; if(n % factors[cur] == 0) { temp.push_back(factors[cur]); help(result, factors, temp, cur, n/factors[cur]); temp.pop_back(); } help(result, factors, temp, cur+1, n); } public: vector> getFactors(int n) { vector> result; vector factors; for(int i = 2; i <= n/2;i++) if(n % i == 0 && n > i) factors.push_back(i); vector temp; help(result, factors, temp, 0, n); return result; } }; ================================================ FILE: cpp/261-270/Graph Valid Tree.cpp ================================================ class Solution { int findParent(const vector& vec, int node) { while (node != vec[node]) { node = vec[node]; } return node; } public: bool validTree(int n, vector>& edges) { if (edges.size() + 1 != n) { return false; } vector vec(n, 0); for (int i = 0; i < n; i++) { vec[i] = i; } for (const vector& edge : edges) { int p1 = findParent(vec, edge[0]); int p2 = findParent(vec, edge[1]); if (p1 == p2) return false; vec[p1] = p2; } return true; } }; ================================================ FILE: cpp/261-270/Missing Number.cpp ================================================ class Solution { public: int missingNumber(vector& nums) { int s = accumulate(nums.begin(), nums.end(), 0); int n = nums.size(); int v = (1+n)*n/2; return v - s; } }; class Solution { public: int missingNumber(vector& nums) { int ans = 0; for (int i = 0; i < nums.size(); i++) { ans ^= i; ans ^= nums[i]; } ans ^= nums.size(); return ans; } }; ================================================ FILE: cpp/261-270/Paint House II.cpp ================================================ class Solution { public: int minCostII(vector>& costs) { if(costs.size() == 0) return 0; vector > v(2, vector(costs[0].size(), 0)); for(int i = 0;i < costs[0].size();i++) v[0][i] = costs[0][i]; int k = 0; for(int i = 1;i < costs.size();i++) { int minimum1 = min(v[k][0], v[k][1]); int minimum2 = max(v[k][0], v[k][1]); for(int j = 2;j < costs[0].size();j++) { if(v[k][j] < minimum1) { minimum2 = minimum1; minimum1 = v[k][j]; } else if(v[k][j] >= minimum1 && v[k][j] < minimum2) { minimum2 = v[k][j]; } } k = (k+1)%2; for(int j = 0;j < costs[0].size();j++) { if(minimum1 != v[(k+1)%2][j]) v[k][j] = minimum1 + costs[i][j]; else v[k][j] = minimum2 + costs[i][j]; } } return *min_element(v[k].begin(), v[k].end()); } }; ================================================ FILE: cpp/261-270/Palindrome Permutation II.cpp ================================================ class Solution { const static int M = 128; int chs[M] = {0}; void help(vector& result, string &temp, const string &s, int cur) { int mid = s.length() / 2; if(s.length() % 2 == 0 && cur == mid) { result.push_back(temp); return;} if(s.length() % 2 == 1 && cur == mid) { for(int i = 0;i < M;i++){ if(chs[i] == 1) { temp[mid] = i; result.push_back(temp); return; } } } for(int i = 0;i < M;i++) { if(chs[i] >= 2) { temp[cur] = i; temp[s.length() - 1 - cur] = i; chs[i] -= 2; help(result, temp, s, cur+1); chs[i] += 2; } } } public: vector generatePalindromes(string s) { vector result; for (int i = 0;i < s.length();i++) chs[s[i]]++; int odd(0),even(0); for (int i = 0;i < M;i++) { if(chs[i] == 0) continue; if(chs[i] % 2 == 0) even++; else odd++; } if (odd >= 2) return result; if (s.length() % 2 == 0 && odd > 0) return result; string tmp(s.length(), 0); help(result, tmp, s, 0); return result; } }; ================================================ FILE: cpp/261-270/Palindrome Permutation.cpp ================================================ class Solution { public: bool canPermutePalindrome(string s) { int MAGIC(128); int ch[MAGIC] = {0}; for (int i = 0;i < s.length();i++) ch[s[i]]++; int odd(0), even(0); for (int i = 0;i < MAGIC;i++) if (ch[i] > 0) ch[i] % 2 == 1 ? odd++ : even++; if (odd >= 2) return false; else if (odd == 1) { if (s.length() % 2 == 1) return true; return false; } else return true; } }; ================================================ FILE: cpp/261-270/Ugly Number II.cpp ================================================ class Solution { public: int nthUglyNumber(int n) { vector v = {1}; int index2(0), index3(0), index5(0); int val = 1; while (--n) { val = min(v[index2]*2, min(v[index3]*3, v[index5]*5)); v.push_back(val); if (val == v[index2]*2) ++index2; if (val == v[index3]*3) ++index3; if (val == v[index5]*5) ++index5; } return val; } }; ================================================ FILE: cpp/261-270/Ugly Number.cpp ================================================ class Solution { public: bool isUgly(int num) { if (num <= 0) return false; if (num == 1) return true; while (num % 2 == 0) num /= 2; while (num % 3 == 0) num /= 3; while (num % 5 == 0) num /= 5; return num == 1; } }; ================================================ FILE: cpp/271-280/Closest Binary Search Tree Value II.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { void dfs(TreeNode* root, priority_queue>& pq, double target, int k) { if(!root) return; pq.push(make_pair(fabs(target - double(root->val)), root->val)); if(pq.size() > k) pq.pop(); dfs(root->left, pq, target, k); dfs(root->right, pq, target, k); } public: vector closestKValues(TreeNode* root, double target, int k) { priority_queue> pq; vector result; dfs(root, pq, target, k); while(!pq.empty()) { result.push_back(pq.top().second); pq.pop(); } return result; } }; ================================================ FILE: cpp/271-280/Encode and Decode Strings.cpp ================================================ class Codec { public: // Encodes a list of strings to a single string. string encode(vector& strs) { string result(""); for (const string& str : strs) { string len = to_string(str.length()); result = result + len + "#" + str; } return result; } // Decodes a single string to a list of strings. vector decode(string s) { vector result; size_t i = 0; while (i < s.length()) { size_t index = s.find('#', i); int len = stoi(s.substr(i, index-i)); result.push_back(s.substr(index+1, len)); i = index + len + 1; } return result; } }; // Your Codec object will be instantiated and called as such: // Codec codec; // codec.decode(codec.encode(strs)); ================================================ FILE: cpp/271-280/Find the Celebrity.cpp ================================================ // Forward declaration of the knows API. bool knows(int a, int b); class Solution { public: int findCelebrity(int n) { int i(0), j(n-1); while (i < j) { if (knows(i, j)) i++; else j--; } for(int k = 0;k < n;k++) { if (k == i) continue; if (knows(i, k) || !knows(k, i)) return -1; } return i; } }; ================================================ FILE: cpp/271-280/First Bad Version.cpp ================================================ // Forward declaration of isBadVersion API. bool isBadVersion(int version); class Solution { public: int firstBadVersion(int n) { int lower = 1, upper = n, mid; while(lower < upper) { mid = lower + (upper - lower) / 2; if(!isBadVersion(mid)) lower = mid + 1; else upper = mid; } return lower; } }; ================================================ FILE: cpp/271-280/H-Index II.cpp ================================================ class Solution { public: int hIndex(vector& citations) { int i(0),j(citations.size()-1); if(citations.size() == 0) return 0; while(i < j) { int mid = (i+j) >> 1; int citation = citations[mid]; if(citation >= (citations.size() - mid)) j = mid - 1; else i = mid + 1; } if(citations[i] >= citations.size() - i) return citations.size() - i; else return citations.size() - i - 1; } }; ================================================ FILE: cpp/271-280/H-Index.cpp ================================================ class Solution { public: int hIndex(vector& citations) { if(citations.empty()) return 0; int n = citations.size(); vector hash(n + 1, 0); for (int i = 0; i < n; ++i) { if(citations[i] >= n) hash[n]++; else hash[citations[i]]++; } int paper = 0; for(int i = n; i >= 0; --i){ paper += hash[i]; if(paper >= i) return i; } return 0; } }; ================================================ FILE: cpp/271-280/Integer to English Words.cpp ================================================ class Solution { public: string hundredStr(int num){ vector arr1={"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten", "Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"}; vector arr2={"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"}; string ret; ret=num%100<20?arr1[num%100]:arr2[(num%100)/10]+(num%10?" "+arr1[num%10]:""); if(num>99)ret=arr1[num/100]+" Hundred"+(num%100?" "+ret:""); return ret; } string numberToWords(int num) { string ret; vector strarr={"Thousand","Million","Billion"}; ret=hundredStr(num%1000); for(int i=0;i<3;i++){ num/=1000; ret=num%1000?hundredStr(num%1000)+" "+strarr[i]+" "+ ret:ret; } while(ret.back()==' ')ret.pop_back(); return ret.empty()?"Zero":ret; } }; ================================================ FILE: cpp/271-280/Paint Fence.cpp ================================================ class Solution { public: int numWays(int n, int k) { vector> dp(2, vector(n+2, 0)); dp[0][0] = 0; dp[0][1] = k; dp[1][0] = k; dp[1][1] = k*(k-1); for (int i = 2; i < n; i++) { dp[0][i] = dp[1][i-1]; dp[1][i] = (k-1) * (dp[0][i-1] + dp[1][i-1]); } return dp[0][n-1] + dp[1][n-1]; } }; ================================================ FILE: cpp/271-280/Perfect Squares.cpp ================================================ class Solution { public: int numSquares(int n) { vector p {0}; while (p.size() <= n) { int res = INT_MAX; for (int i = 1; i*i <= p.size(); i++) res = min(res, p[p.size()-i*i]+1); p.push_back(res); } return p[n]; } }; ================================================ FILE: cpp/271-280/Wiggle Sort.cpp ================================================ class Solution { public: void wiggleSort(vector& nums) { for (int i = 0;i < nums.size();i++) { if (i % 2 == 0 && (i+1) < nums.size() && nums[i] > nums[i+1]) swap(nums[i], nums[i+1]); if (i % 2 == 1 && (i+1) < nums.size() && nums[i] < nums[i+1]) swap(nums[i], nums[i+1]); } } }; ================================================ FILE: cpp/281-290/Expression Add Operators.cpp ================================================ class Solution { void help(vector& result, string& num, int& target, int index, char op, int pv, int nv, string res) { if (index == num.size() && nv == target) { result.push_back(res); return; } for (int i = 1; i <= num.size()-index; i++) { string curnum = num.substr(index, i); int v = stol(curnum); if (curnum.length() != to_string(v).length()) continue; help(result, num, target, index+i, '+', v, nv+v, res+'+'+curnum); help(result, num, target, index+i, '-', v, nv-v, res+'-'+curnum); help(result, num, target, index+i, op, pv*v, op == '+'? nv - pv + pv*v : (op == '-'? nv + pv - pv*v : pv*v), res+'*'+curnum); } } public: vector addOperators(string num, int target) { vector result; for (int i = 1; i <= num.size(); i++) { string curnum = num.substr(0, i); int v = stol(curnum); if (curnum.length() != to_string(v).length()) continue; help(result, num, target, i, '!', v, v, curnum); } return result; } }; ================================================ FILE: cpp/281-290/Find the Duplicate Number.cpp ================================================ class Solution { public: int findDuplicate(vector& nums) { int n = nums.size(); int left(1), right(n); while (left < right) { int mid = (left+right)/2; int less(0), duplicate(0); for (int i = 0;i < n;i++) { if (nums[i] < mid) less++; else if(nums[i] == mid) duplicate++; } if (duplicate > 1) return mid; less > mid - 1 ? right = mid - 1 : left = mid + 1; } return left; } }; ================================================ FILE: cpp/281-290/Game of Life.cpp ================================================ class Solution { public: void gameOfLife(vector>& board) { int h = board.size(); int w = board[0].size(); for (int i = 0;i < h;i++) { for (int j = 0;j < w;j++) { int old = board[i][j]; int lives(0); int deads(0); for (int m = -1;m <= 1;m++) { for (int n = -1;n <= 1;n++) { if (m == 0 && n == 0) continue; int ix = j + n; int iy = i + m; if (ix < 0 || iy < 0 || ix >= w || iy >= h) continue; if ( (board[iy][ix] & 0x1) == 0) deads++; else if ( (board[iy][ix] & 0x1) == 1) lives++; } } if (old == 1) { if (lives < 2) continue; else if (lives == 2 || lives == 3) board[i][j] |= 0x2; else continue; } else { if (lives == 3) board[i][j] |= 0x2; } } } for (int i = 0;i < h;i++) { for (int j = 0;j < w;j++) { if ((board[i][j] & 0x2) > 0) board[i][j] = 1; else board[i][j] = 0; } } } }; ================================================ FILE: cpp/281-290/Inorder Successor in BST.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) { if (root == nullptr) return nullptr; if (root->val <= p->val) { return inorderSuccessor(root->right, p); } else { TreeNode* left = inorderSuccessor(root->left, p); return (left != nullptr) ? left : root; } } }; ================================================ FILE: cpp/281-290/Move Zeroes.cpp ================================================ class Solution { public: void moveZeroes(vector& nums) { int first(0); for (int i = 0;i < nums.size(); i++) if (nums[i] != 0) swap(nums[i],nums[first++]); } }; ================================================ FILE: cpp/281-290/Peeking Iterator.cpp ================================================ class PeekingIterator : public Iterator { int peekele; bool peeked; public: PeekingIterator(const vector& num) : Iterator(num) { // Initialize any member here. peeked = false; } // Returns the next element in the iteration without advancing the iterator. int peek() { if(!peeked) { peekele = Iterator::next(); peeked = true; } return peekele; } // hasNext() and next() should behave the same as in the Iterator interface. // Override them if needed. int next() { if(!peeked) return Iterator::next(); peeked = false; return peekele; } bool hasNext() const { if(peeked) return true; if(Iterator::hasNext()) return true; return false; } }; ================================================ FILE: cpp/281-290/Unique Word Abbreviation.cpp ================================================ class ValidWordAbbr { map m; public: ValidWordAbbr(vector &dictionary) { for(int i = 0;i < dictionary.size();i++) { string abbr = dictionary[i].front() + to_string(dictionary[i].length()-2) + dictionary[i].back(); if(m.count(abbr) > 0 && m[abbr] != dictionary[i]) m[abbr] = "0"; else m[abbr] = dictionary[i]; } } bool isUnique(string word) { string abbr = word.front() + to_string(word.length()-2) + word.back(); if(m.count(abbr) > 0 && m[abbr] == "0") return false; if(m.count(abbr) > 0 && m[abbr] != word) return false; return true; } }; ================================================ FILE: cpp/281-290/Walls and Gates.cpp ================================================ struct point { int i; int j; int v; point(int _i, int _j, int _v):i(_i), j(_j), v(_v) { } }; class mycomparison { public: mycomparison() { } bool operator() (const point& lhs, const point &rhs) const { return lhs.v > rhs.v; } }; class Solution { pair cors[4] = {{1,0},{0,1},{-1,0},{0,-1}}; public: void wallsAndGates(vector>& rooms) { priority_queue, mycomparison> myqueue; int height = rooms.size(); if (height == 0) return; int width = rooms[0].size(); if (width == 0) return; for (int j = 0;j < height;j++) for (int i = 0;i < width;i++) if (rooms[j][i] == 0) myqueue.push(point(i, j, 0)); while (!myqueue.empty()) { point p = myqueue.top(); myqueue.pop(); for (int m = 0;m <= 3;m++) { int ox = p.i + cors[m].first; int oy = p.j + cors[m].second; int ov = p.v; if (ox >= 0 && ox < width && oy >= 0 && oy < height) { if(rooms[oy][ox] == INT_MAX) { rooms[oy][ox] = p.v + 1; myqueue.push(point(ox,oy,rooms[oy][ox])); } } } } } }; ================================================ FILE: cpp/281-290/Word Pattern.cpp ================================================ class Solution { public: bool wordPattern(string pattern, string str) { stringstream ss(str); // bijection, so need two maps mapm; mapm2; for (int i = 0;i < pattern.length();i++) { char ch = pattern[i]; string temp; ss >> temp; if (temp == "") return false; if (m.count(ch) == 0) { if (m2[temp] == true) return false; m[ch] = temp; m2[temp] = true; } else { if (m[ch] != temp) return false; } } string test; ss >> test; if (test.length() > 0) return false; return true; } }; ================================================ FILE: cpp/281-290/Zigzag Iterator.cpp ================================================ class ZigzagIterator { queue::iterator> myqueue; set::iterator> dead; public: ZigzagIterator(vector& v1, vector& v2) { if(v1.begin() != v1.end()) myqueue.push(v1.begin()); if(v2.begin() != v2.end()) myqueue.push(v2.begin()); dead.insert(v1.end()); dead.insert(v2.end()); } int next() { vector::iterator it = myqueue.front(); myqueue.pop(); int v = *it; it++; if(dead.count(it) == 0) myqueue.push(it); return v; } bool hasNext() { return !myqueue.empty(); } }; /** * Your ZigzagIterator object will be instantiated and called as such: * ZigzagIterator i(v1, v2); * while (i.hasNext()) cout << i.next(); */ ================================================ FILE: cpp/291-300/Best Meeting Point.cpp ================================================ class Solution { public: int minTotalDistance(vector>& grid) { int result(0); vectorvx, vy; for (int i = 0;i < grid.size();i++) { for (int j = 0;j < grid[i].size();j++) { if (grid[i][j] == 1) { vx.push_back(j); vy.push_back(i); } } } int half_num = vx.size()/2; std::nth_element (vx.begin(), vx.begin()+half_num, vx.end()); std::nth_element (vy.begin(), vy.begin()+half_num, vy.end()); int midx = vx[half_num]; int midy = vy[half_num]; for (int i = 0;i < vx.size();i++) result += abs(vx[i] - midx) + abs(vy[i] - midy); return result; } }; ================================================ FILE: cpp/291-300/Binary Tree Longest Consecutive Sequence.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { int result; void help(TreeNode* root, int h) { result = max(result, h); if (root->left) { if (root->val == root->left->val -1) help(root->left, h+1); else help(root->left, 1); } if (root->right) { if (root->val == root->right->val -1) help(root->right, h+1); else help(root->right, 1); } } public: int longestConsecutive(TreeNode* root) { if(!root) return 0; help(root, 1); return result; } }; ================================================ FILE: cpp/291-300/Bulls and Cows.cpp ================================================ class Solution { public: string getHint(string secret, string guess) { int A(0),B(0); map mymap1; map mymap2; for(int i = 0;i < secret.length();i++) { if(secret[i] == guess[i]) A++; else { mymap1[secret[i]]++; mymap2[guess[i]]++; } } for(int i = 0;i <= 9;i++) B += min(mymap1['0'+i],mymap2['0'+i]); return to_string(A)+"A"+to_string(B)+"B"; } }; ================================================ FILE: cpp/291-300/Find Median from Data Stream.cpp ================================================ class MedianFinder { priority_queue, std::less> maximum_heap; priority_queue, std::greater> minimum_heap; public: /** initialize your data structure here. */ MedianFinder() { } void addNum(int num) { minimum_heap.push(num); maximum_heap.push(minimum_heap.top()); minimum_heap.pop(); if (minimum_heap.size() < maximum_heap.size()) { minimum_heap.push(maximum_heap.top()); maximum_heap.pop(); } } double findMedian() { if (maximum_heap.size() == minimum_heap.size()) { return (minimum_heap.top()+maximum_heap.top()) / 2.0; } return minimum_heap.top(); } }; ================================================ FILE: cpp/291-300/Flip Game II.cpp ================================================ class Solution { int len; string ss; bool help() { for (int is = 0; is <= len-2; ++is) { if (ss[is] == '+' && ss[is+1] == '+') { ss[is] = ss[is+1] = '-'; bool wins = !help(); ss[is] = ss[is+1] = '+'; if (wins) return true; } } return false; } public: bool canWin(string s) { len = s.size(); ss = s; return help(); } }; ================================================ FILE: cpp/291-300/Flip Game.cpp ================================================ class Solution { public: vector generatePossibleNextMoves(string s) { vector result; for (int i = 1;i < s.length();i++) { if (s[i-1] == '+' && s[i] == '+') { s[i-1] = s[i] = '-'; result.push_back(s); s[i-1] = s[i] = '+'; } } return result; } }; ================================================ FILE: cpp/291-300/Longest Increasing Subsequence.cpp ================================================ class Solution { public: int lengthOfLIS(vector& nums) { vector res; for(int i=0; i> str; if(str[0] == '#') { isnumber = false; } else { val = stoi(str); isnumber = true; } return; } TreeNode* help(stringstream& ss) { bool isnumber; int val; TreeNode *root = nullptr; readNext(ss, val, isnumber); if (isnumber) { root = new TreeNode(val); root->left = help(ss); root->right = help(ss); } return root; } // Encodes a tree to a single string. string _serialize(TreeNode* root) { if (root == nullptr) return "# "; else return to_string(root->val) + " " + _serialize(root->left) + _serialize(root->right); } public: // Encodes a tree to a single string. string serialize(TreeNode* root) { string serialized_data = _serialize(root); return serialized_data; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { stringstream ss(data); return help(ss); } }; /* * Solution 2 * Write 4 bytes for each integer. * Write a 'Y' or 'N' for each node. No separator is need. */ class Codec { void preorderDFS(TreeNode* root, string& serialized_data) { if (root == nullptr) { serialized_data.push_back('Y'); return; } serialized_data.push_back('N'); char buf[4]; memcpy(buf, &(root->val), sizeof(int)); for (int i = 0; i < 4; i++) serialized_data.push_back(buf[i]); preorderDFS(root->left, serialized_data); preorderDFS(root->right, serialized_data); } inline TreeNode* reconstruct(const string& buffer, int& pos) { if (pos >= buffer.size()) return nullptr; char indicator = buffer[pos]; pos++; if (indicator == 'Y') { return nullptr; } int value; memcpy(&value, &buffer[pos], sizeof(int)); TreeNode* node = new TreeNode(value); pos += sizeof(int); node->left = reconstruct(buffer, pos); node->right = reconstruct(buffer, pos); return node; } public: // Encodes a tree to a single string. string serialize(TreeNode* root) { string serialized_data; preorderDFS(root, serialized_data); return serialized_data; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { int pos = 0; return reconstruct(data, pos); } }; ================================================ FILE: cpp/291-300/Word Pattern II.cpp ================================================ class Solution { bool help(int pindex, int sindex, string &pattern, string &str, map& m, map& check) { if(pindex == pattern.length() && sindex == str.length()) return true; if(pindex == pattern.length() || sindex == str.length()) return false; char cur = pattern[pindex]; if(m.count(cur) == 0) { int maxlength = str.length() - sindex; for(int l = 1; l <= maxlength; l++) { string s = str.substr(sindex, l); if(check[s] == true) continue; m[cur] = s; check[s] = true; bool fff = help(pindex+1, sindex+l, pattern, str, m, check); if(fff) return true; m.erase(cur); check[s] = false; } return false; } else { string temp = m[cur]; if(str.substr(sindex, temp.length()) == temp) { bool fff = help(pindex+1, sindex+temp.length(), pattern, str, m, check); if(fff) return true; else return false; } else { return false; } } } public: bool wordPatternMatch(string pattern, string str) { map m; map check; bool fff = help(0, 0, pattern, str, m, check); return fff; } }; ================================================ FILE: cpp/301-310/Additive Number.cpp ================================================ class Solution { bool check(string add1, string add2, int index, string &num) { while(1) { if(add1.length() > 1 && add1[0] == '0') return false; if(add2.length() > 1 && add2[0] == '0') return false; long res = stol(add1) + stol(add2); string strres = to_string(res); if(index + strres.length() > num.length()) return false; string cmp = num.substr(index, strres.length()); if(cmp != strres) return false; index += strres.length(); if(index == num.length()) return true; add1 = add2; add2 = strres; } return false; } public: bool isAdditiveNumber(string num) { if(num.length() < 3) return false; for(int len1 = 1;len1 <= num.length() - 2; len1++) { for(int len2 = 1; len1+len2 <= num.length() - 1;len2++) { bool f = check(num.substr(0, len1), num.substr(len1, len2), len1+len2, num); if(f) return true; } } return false; } }; ================================================ FILE: cpp/301-310/Best Time to Buy and Sell Stock with Cooldown.cpp ================================================ class Solution { public: int maxProfit(vector& prices) { if (prices.empty()) return 0; int buy = -prices[0]; int sell = 0; int cooldown = 0; for (int i = 1; i < prices.size(); i++) { int old_cooldown = cooldown; cooldown = sell; sell = max(sell, buy + prices[i]); buy = max(buy, old_cooldown - prices[i]); } return max(sell, cooldown); } }; ================================================ FILE: cpp/301-310/Minimum Height Trees.cpp ================================================ class Solution { public: vector findMinHeightTrees(int n, vector>& edges) { vector res; if(n <= 2) { for(int i = 0;i < n;i++) res.push_back(i); return res; } int k = 0; vector> myvec(n, set()); queue myqueue; for(auto e : edges) { myvec[e.first].insert(e.second); myvec[e.second].insert(e.first); } for(int i = 0;i < n;i++) { if(myvec[i].size() == 1) { myqueue.push(i); k++; } } while(1) { int j = myqueue.size(); for(int i = 0;i < j;i++) { int v = myqueue.front(); myqueue.pop(); for(auto e : myvec[v]) { myvec[e].erase(v); if(myvec[e].size() == 1) { myqueue.push(e); k++; } } } if(n == k) break; } while(!myqueue.empty()) { res.push_back(myqueue.front()); myqueue.pop(); } sort(res.begin(), res.end()); return res; } }; ================================================ FILE: cpp/301-310/Number of Islands II.cpp ================================================ class UF { private: vector parent; vector rank; int count; int N; public: UF(int N) { parent.resize(N); rank.resize(N); this->N = N; count = N; for(int i = 0;i < N;i++) { parent[i] = i; rank[i] = 0; } } int find(int p) { while (p != parent[p]) { parent[p] = parent[parent[p]]; // path compression by halving p = parent[p]; } return p; } int getCount() { return count; } bool connected(int p, int q) { return find(p) == find(q); } void Union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make root of smaller rank point to root of larger rank if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ; else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP; else { parent[rootQ] = rootP; rank[rootP]++; } count--; } }; class Solution { inline int convert(int m, int n, int col) { return col*m + n; } public: vector numIslands2(int m, int n, vector>& positions) { vector res; UF uf(m*n); int count = 0; pair pos[4] = {{0,1},{0,-1},{1,0},{-1,0}}; vector marked(m*n+10, false); for(auto& e : positions) { count++; int curisland = convert(e.first, e.second, n); marked[curisland] = true; for(int i = 0;i < 4;i++) { int posi = e.first + pos[i].first; int posj = e.second + pos[i].second; int neighborisland = convert(posi, posj, n); if(posi < 0 || posj < 0 || posi >= m || posj >= n || !marked[neighborisland]) continue; if(!uf.connected(curisland, neighborisland)) { uf.Union(curisland, neighborisland); count--; } } res.push_back(count); } return res; } }; ================================================ FILE: cpp/301-310/Range Sum Query - Immutable.cpp ================================================ class NumArray { int *a; public: NumArray(vector &nums) { a = new int[nums.size()+1]; a[0] = 0; for (int i = 0; i < nums.size(); i++) { a[i+1] = nums[i] + a[i]; } } int sumRange(int i, int j) { return a[j+1] - a[i]; } }; // Your NumArray object will be instantiated and called as such: // NumArray numArray(nums); // numArray.sumRange(0, 1); // numArray.sumRange(1, 2); ================================================ FILE: cpp/301-310/Range Sum Query - Mutable.cpp ================================================ class SegmentTreeNode { public: int start, end, sum; SegmentTreeNode *left, *right; SegmentTreeNode(int start, int end, int sum) { this->start = start; this->end = end; this->sum = sum; this->left = this->right = NULL; } }; class NumArray { SegmentTreeNode *root; SegmentTreeNode * build(int start, int end, vector& A) { // write your code here if(start > end) return nullptr; if(start == end) { SegmentTreeNode *tree = new SegmentTreeNode(start, end, A[start]); return tree; } if(start < end) { SegmentTreeNode *left = build(start, (start+end)/2, A); SegmentTreeNode *right = build((start+end)/2+1, end, A); SegmentTreeNode *tree = new SegmentTreeNode(start, end, left->sum + right->sum); tree -> left = left; tree -> right = right; return tree; } } void modify(SegmentTreeNode *root, int i, int val) { if(root->start == root->end) { root->sum = val; return; } if(i <= root->left->end) modify(root->left, i, val); else modify(root->right, i, val); root->sum = root->left->sum + root->right->sum; } int query(SegmentTreeNode *root, int i, int j) { if(root->start == root->end) return root->sum; if(root->start == i && root->end == j) return root->sum; if(j <= root->left->end) { return query(root->left, i, j); } else if(i >= root->right->start) { return query(root->right, i, j); } else { return query(root->left, i, root->left->end) + query(root->right, root->right->start, j); } } public: NumArray(vector &nums) { root = build(0, nums.size()-1, nums); } void update(int i, int val) { modify(root, i, val); } int sumRange(int i, int j) { return query(root, i, j); } }; // Your NumArray object will be instantiated and called as such: // NumArray numArray(nums); // numArray.sumRange(0, 1); // numArray.update(1, 10); // numArray.sumRange(1, 2); ================================================ FILE: cpp/301-310/Range Sum Query 2D - Immutable.cpp ================================================ class NumMatrix { vector> dp; public: NumMatrix(vector> &matrix) { if(matrix.size() < 1) return; vector> dp(matrix.size(), vector(matrix[0].size(), 0)); dp[0][0] = matrix[0][0]; for(int i = 1;i < matrix.size();i++) dp[i][0] = dp[i-1][0] + matrix[i][0]; for(int i = 1;i < matrix[0].size();i++) dp[0][i] = dp[0][i-1] + matrix[0][i]; for(int i = 1;i < matrix.size();i++) for(int j = 1;j < matrix[0].size();j++) dp[i][j] = dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1] + matrix[i][j]; this->dp = dp; } int sumRegion(int row1, int col1, int row2, int col2) { return (dp[row2][col2] - (row1 == 0? 0 : dp[row1-1][col2]) - (col1 == 0? 0 :dp[row2][col1-1]) + (row1 == 0 || col1 == 0? 0 : dp[row1-1][col1-1])); } }; ================================================ FILE: cpp/301-310/Range Sum Query 2D - Mutable.cpp ================================================ class NumMatrix { vector> dp; vector> matrix; public: NumMatrix(vector> &matrix) { if (matrix.empty() || matrix[0].empty()) return; for (int i = 0; i < matrix.size(); i++) { vector temp(matrix[0].size()+1,0); for (int j = 0; j < matrix[0].size(); j++) { temp[j+1] = temp[j] + matrix[i][j]; } dp.emplace_back(temp); } this->matrix = matrix; } void update(int row, int col, int val) { int diff = val - matrix[row][col]; for (int j = col; j < matrix[0].size(); j++) { dp[row][j+1] = dp[row][j+1] + diff; } matrix[row][col] = val; } int sumRegion(int row1, int col1, int row2, int col2) { int res = 0; for (int i = row1; i <= row2; i++) { res += (dp[i][col2+1] - dp[i][col1]); } return res; } }; // Your NumMatrix object will be instantiated and called as such: // NumMatrix numMatrix(matrix); // numMatrix.sumRegion(0, 1, 2, 3); // numMatrix.update(1, 1, 10); // numMatrix.sumRegion(1, 2, 3, 4); ================================================ FILE: cpp/301-310/Remove Invalid Parentheses.cpp ================================================ // Solution 1: BFS class Solution { int GetErrors(const string &s) { stack mystack; int valid = 0; for (char ch : s) { if (ch == '(') { mystack.push(ch); } else if (ch == ')') { if (!mystack.empty()) { valid += 2; mystack.pop(); } } else { valid++; } } return s.length() - valid; } public: vector removeInvalidParentheses(string s) { queue myqueue; unordered_set visited; myqueue.push(s); visited.insert(s); int errors = GetErrors(s); while (!myqueue.empty() && errors > 0) { int queue_size = myqueue.size(); for (int k = 0; k < queue_size; k++) { string str = myqueue.front(); myqueue.pop(); int i = 0; while (i < str.length()) { if (str[i] != '(' && str[i] != ')') { i++; continue; } string tmp = str.substr(0,i) + str.substr(i+1); if (visited.count(tmp) == 0) { int current_errors = GetErrors(tmp); if (current_errors < errors) { myqueue.push(tmp); visited.insert(tmp); } } while (i+1 < str.length() && str[i] == str[i+1]) i++; i++; } } errors--; } vector result; while (!myqueue.empty()) { string tmp = myqueue.front(); myqueue.pop(); result.push_back(tmp); } return result; } }; // Solution 2: DFS class Solution { int GetErrors(const string &s) { stack mystack; int valid = 0; for (char ch : s) { if (ch == '(') { mystack.push(ch); } else if (ch == ')') { if (!mystack.empty()) { valid += 2; mystack.pop(); } } else { valid++; } } return s.length() - valid; } public: void dfs(const string& s, int ind, int validLen, int leftCnt, int rightCnt, string cur, unordered_set& visited, unordered_set& res_set) { if (cur.size() == validLen) { if (leftCnt == rightCnt) { res_set.insert(cur); } return; } if (ind >= s.size()) { return; } string key = to_string(ind) + cur; if (visited.count(key) > 0) return; visited.insert(key); if (s[ind] == '(' || s[ind] == ')') { if (cur.length() + (s.size() - ind) > validLen) { dfs(s, ind+1, validLen, leftCnt, rightCnt, cur, visited, res_set); } if (s[ind] == '(') { if (leftCnt < validLen / 2) { dfs(s, ind+1, validLen, leftCnt+1, rightCnt, cur + '(', visited, res_set); } } else if (leftCnt > rightCnt) { dfs(s, ind+1, validLen, leftCnt, rightCnt+1, cur + ')', visited, res_set); } } else { dfs(s, ind+1, validLen, leftCnt, rightCnt, cur + s[ind], visited, res_set); } } vector removeInvalidParentheses(string s) { int validLen = s.size() - GetErrors(s); unordered_set visited; unordered_set res_set; dfs(s, 0, validLen, 0, 0, "", visited, res_set); return vector(res_set.begin(), res_set.end()); } }; ================================================ FILE: cpp/301-310/Smallest Rectangle Enclosing Black Pixels.cpp ================================================ class Solution { int top; int left; int right; int bottom; pair pos[4] = { {-1,0},{1,0},{0,-1},{0,1} }; void bfs(vector>& image, int x, int y) { image[x][y] = '0'; left = min(left, y); right = max(right, y); top = min(top, x); bottom = max(bottom, x); for(auto e : pos) { int nx = x + e.first; int ny = y + e.second; if(nx >= 0 && nx < image.size() && ny >= 0 && ny < image[0].size() && image[nx][ny] == '1') bfs(image, nx, ny); } } public: int minArea(vector>& image, int x, int y) { top = bottom = x; left = right = y; bfs(image, x, y); int res = (right - left + 1) * (bottom - top + 1); return res; } }; ================================================ FILE: cpp/311-320/Binary Tree Vertical Order Traversal.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector> verticalOrder(TreeNode* root) { map> mymap; vector> res; if (root == nullptr) return res; queue nodequeue; queueidqueue; nodequeue.push(root); idqueue.push(0); while (!nodequeue.empty()) { TreeNode* cur = nodequeue.front(); int id = idqueue.front(); nodequeue.pop(); idqueue.pop(); if (mymap.count(id) == 0) { vector temp; mymap[id] = temp; } mymap[id].push_back(cur->val); if (cur -> left != nullptr) { nodequeue.push(cur->left); idqueue.push(id-1); } if (cur -> right != nullptr) { nodequeue.push(cur->right); idqueue.push(id+1); } } for (const auto& e : mymap) res.emplace_back(e.second); return res; } }; ================================================ FILE: cpp/311-320/Bulb Switcher.cpp ================================================ class Solution { public: int bulbSwitch(int n) { return sqrt(n); } }; ================================================ FILE: cpp/311-320/Burst Balloons.cpp ================================================ class Solution { int getValue(vector& nums, int i) { if(i < 0 || i >= nums.size()) return 1; return nums[i]; } public: int maxCoins(vector& nums) { if(nums.size() == 0) return 0; int n = nums.size(); vector> dp(n, vector(n, 0)); for(int len = 1; len <= n; len++) { for(int start = 0;start <= n-len;start++) { int end = start + len - 1; for(int i = start; i <= end; i++) { int coins = nums[i] * getValue(nums, start - 1) * getValue(nums, end + 1); coins += i != start ? dp[start][i - 1] : 0; coins += i != end ? dp[i + 1][end] : 0; dp[start][end] = max(dp[start][end], coins); } } } return dp[0][n - 1]; } }; ================================================ FILE: cpp/311-320/Count of Smaller Numbers After Self.cpp ================================================ struct tree{ int val; tree* left; tree* right; int count; tree(int v):val(v),left(nullptr),right(nullptr),count(1){} }; class Solution { public: vector countSmaller(vector& nums) { tree* root(nullptr); vector res(nums.size(), 0); for (int i = nums.size() - 1; i >= 0; i--) { if (root == nullptr) { root = new tree(nums[i]); } else { int temp(0); tree* cur = root; while (cur != nullptr) { if (nums[i] <= cur->val) { cur->count++; if(cur -> left == nullptr) { tree* node = new tree(nums[i]); cur->left = node; break; } cur = cur->left; } else { temp += cur->count; if (cur -> right == nullptr) { tree* node = new tree(nums[i]); cur->right = node; break; } cur = cur->right; } } res[i] = temp; } } return res; } }; ================================================ FILE: cpp/311-320/Generalized Abbreviation.cpp ================================================ class Solution { void help(int i, string &word, vector& result, int previous, string temp) { if(i >= word.length()) { if(previous != 0) temp = temp + to_string(previous); result.push_back(temp); return; } string num(""); if(previous != 0) num = to_string(previous); string _temp = temp+num+word[i]; help(i+1, word, result, 0, _temp); help(i+1, word, result, previous+1, temp); } public: vector generateAbbreviations(string word) { vector result; help(0, word, result, 0, ""); return result; } }; ================================================ FILE: cpp/311-320/Maximum Product of Word Lengths.cpp ================================================ class Solution { public: int maxProduct(vector& words) { vector mask(words.size(), 0); int res = 0; for(int i = 0;i < words.size(); i++) { for(auto ch : words[i]) mask[i] |= (1 << (ch - 'a')); for(int j = 0;j < i;j++) { if( (mask[i] & mask[j]) == 0) res = max(res, int(words[i].length() * words[j].length())); } } return res; } }; ================================================ FILE: cpp/311-320/Remove Duplicate Letters.cpp ================================================ class Solution { public: string removeDuplicateLetters(string s) { bool visited[26] = {false}; int count[26] = {0}; stack temp_answers; for (char ch : s) { count[ch - 'a']++; } // bcabc, b -> bc -> a -> ab -> abc // cbacdcbc, c -> b -> a -> ac -> acd -> acd -> acdb for (char ch : s) { int index = ch - 'a'; count[index]--; if (visited[index]) continue; while (!temp_answers.empty() && temp_answers.top() > ch && count[temp_answers.top() - 'a'] > 0) { char c = temp_answers.top(); temp_answers.pop(); visited[c - 'a'] = false; } if (visited[index] == false) { temp_answers.push(ch); visited[index] = true; } } string res(""); while (!temp_answers.empty()) { res = temp_answers.top() + res; temp_answers.pop(); } return res; } }; ================================================ FILE: cpp/311-320/Shortest Distance from All Buildings.cpp ================================================ struct point { int i; int j; int v; point(int _i, int _j, int _v){i = _i; j = _j; v = _v;} }; class Solution { void BFS(int i, int j, vector>& grid, vector>& records) { int m = grid.size(); int n = grid[0].size(); vector > visited(m, vector(n, false)); queue myqueue; point cur(i, j, 0); myqueue.push(cur); visited[i][j] = true; while (!myqueue.empty()) { cur = myqueue.front(); myqueue.pop(); if(records[cur.i][cur.j] >= 0) records[cur.i][cur.j] += cur.v; pair pos[4] = {{-1,0},{1,0},{0,1},{0,-1}}; for (int k = 0;k < 4;k++) { int curi = cur.i + pos[k].first; int curj = cur.j + pos[k].second; if (curi >= 0 && curi < m && curj >= 0 && curj < n && !visited[curi][curj] && grid[curi][curj] == 0 && records[curi][curj] >= 0) { point p(curi, curj, cur.v+1); visited[curi][curj] = true; myqueue.push(p); } } } for (int i = 0;i < m;i++) for (int j = 0;j < n;j++) if (!visited[i][j]) records[i][j] = INT_MIN; } public: int shortestDistance(vector>& grid) { int m = grid.size(); int n = grid[0].size(); vector > records(m, vector(n, 0)); for(int i = 0;i < m;i++) for(int j = 0;j < n;j++) if(grid[i][j] == 1) BFS(i, j, grid, records); int result(INT_MAX); for(int i = 0;i < m;i++) for(int j = 0;j < n;j++) if(records[i][j] > 0) result = min(result, records[i][j]); if(result == INT_MAX) return -1; return result; } }; ================================================ FILE: cpp/311-320/Sparse Matrix Multiplication.cpp ================================================ class Solution { public: vector> multiply(vector>& A, vector>& B) { int row1 = A.size(); int col1 = A[0].size(); int row2 = B.size(); int col2 = B[0].size(); vector> res(row1, vector(col2, 0)); vector> CacheB(col2); for (int i = 0;i < row2;i++) for (int j = 0;j < col2;j++) if (B[i][j] != 0) CacheB[j][i] = B[i][j]; for (int i = 0;i < row1;i++) { for (int j = 0;j < col2;j++) { unordered_map right = CacheB[j]; if (right.size() == 0) continue; for (int k = 0;k < col1;k++) { if (A[i][k] != 0 && right.count(k) > 0) { res[i][j] += A[i][k] * right[k]; } } } } return res; } }; ================================================ FILE: cpp/311-320/Super Ugly Number.cpp ================================================ class Solution { public: int nthSuperUglyNumber(int n, vector& primes) { int k = primes.size(); vectorindex(k, 0); vectorv(n, INT_MAX); v[0] = 1; int val = 1; for (int i=1; i& coins, int amount) { if(amount == 0) return 0; int *dp = new int[amount+1]; for(int i = 1;i <= amount;i++) dp[i] = -1; dp[0] = 0; for(int i = 1;i <= amount;i++) { for(int e : coins) { if(i - e < 0 || dp[i-e] < 0) continue; int v = dp[i-e] + 1; if(dp[i] <= 0) dp[i] = v; else dp[i] = min(v, dp[i]); } } return dp[amount] <= 0 ? -1 : dp[amount]; } }; ================================================ FILE: cpp/321-330/Count of Range Sum.cpp ================================================ typedef long long LL; struct SegmentTreeNode { LL L, R; int cnt; SegmentTreeNode *left, *right; SegmentTreeNode(LL L, LL R) :L(L), R(R), cnt(0), left(NULL), right(NULL) {} }; class SegmentTree { SegmentTreeNode * root; SegmentTreeNode * buildTree(vector &nums, int L, int R) { if (L > R) return NULL; SegmentTreeNode * root = new SegmentTreeNode(nums[L], nums[R]); if (L == R) return root; int mid = (L + R) >> 1; root->left = buildTree(nums, L, mid); root->right = buildTree(nums, mid + 1, R); return root; } void update(SegmentTreeNode * root, LL val) { if (root && root->L <= val && val <= root->R) { root->cnt++; update(root->left, val); update(root->right, val); } } int sum(SegmentTreeNode * root, LL L, LL R) { if (!root || root->R < L || R < root->L ) return 0; if (L <= root->L && root->R <= R) return root->cnt; return sum(root->left, L, R) + sum(root->right, L, R); } public: SegmentTree(vector &nums, int L, int R) { root = buildTree(nums, L, R); } int sum(LL L, LL R) { return sum(root, L, R); } void update(LL val) { update(root, val); } }; class Solution { public: int countRangeSum(vector& nums, int lower, int upper) { if (nums.size() == 0) return 0; vector sum_array (nums.size(),0); sum_array[0] = nums[0]; for (int i = 1; i < sum_array.size(); i++) { sum_array[i] = nums[i] + sum_array[i - 1]; } LL sum = sum_array[sum_array.size() - 1]; sort(sum_array.begin(), sum_array.end()); auto t = unique(sum_array.begin(), sum_array.end()); SegmentTree tree(sum_array, 0, t - sum_array.begin() - 1); int ans = 0; for (int i = nums.size() - 1; i >= 0; i--) { tree.update(sum); sum -= nums[i]; ans += tree.sum(lower + sum,upper + sum); } return ans; } }; ================================================ FILE: cpp/321-330/Create Maximum Number.cpp ================================================ class Solution { vector merge(vector nums1, vector nums2) { vector ans; int i = 0, j = 0; while(i < nums1.size() && j < nums2.size()) { if(greater(nums1, nums2, i, j)) { ans.push_back(nums1[i]); i++; } else { ans.push_back(nums2[j]); j++; } } if(i == nums1.size()) while(j < nums2.size()) ans.push_back(nums2[j++]); else if(j == nums2.size()) while(i < nums1.size()) ans.push_back(nums1[i++]); return ans; } vector getMax(const vector& nums, int t) { stack ans; vector res; for(int i = 0;i < nums.size();i++) { while(!ans.empty() && (ans.size() + nums.size() - i > t) && ans.top() < nums[i]) ans.pop(); if(ans.size() < t) ans.push(nums[i]); } while(!ans.empty()) { res.insert(res.begin(), ans.top()); ans.pop(); } return res; } bool greater(const vector &nums1, const vector &nums2, int i, int j) { while (i < nums1.size() && j < nums2.size()) { if (nums1[i] > nums2[j]) return true; if (nums1[i] < nums2[j]) return false; i++; j++; } return (nums1.size()-i) >= (nums2.size()-j); } public: vector maxNumber(vector& nums1, vector& nums2, int k) { int len1 = nums1.size(); int len2 = nums2.size(); vector res; int start = max(0, k - len2); int end = min(k, len1) + 1; for (int i = start; i < end; i++) { vector tmp = merge(getMax(nums1, i), getMax(nums2, k - i)); if (greater(tmp, res, 0, 0)) res = tmp; } return res; } }; ================================================ FILE: cpp/321-330/Longest Increasing Path in a Matrix.cpp ================================================ class Solution { int dfsvisit(int i, int j, vector> &visited, vector>& lens, vector>& matrix) { pair pos[4] = {{0,1}, {0,-1}, {1,0}, {-1,0}}; for (int k = 0;k < 4;k++) { int ni = i + pos[k].first; int nj = j + pos[k].second; if(ni < 0 || nj < 0 || ni >= matrix.size() || nj >= matrix[0].size()) continue; if(matrix[i][j] >= matrix[ni][nj]) continue; if(visited[ni][nj]) lens[i][j] = max(lens[i][j], lens[ni][nj]+1); else lens[i][j] = max(lens[i][j], 1 + dfsvisit(ni, nj, visited, lens, matrix)); } visited[i][j] = true; return lens[i][j]; } public: int longestIncreasingPath(vector>& matrix) { int m = matrix.size(); if (m == 0) return 0; int n = matrix[0].size(); vector> visited(m,vector(n, false)); vector> lens(m,vector(n, 1)); int _max(0); for (int i = 0;i < m;i++) { for (int j = 0;j < n;j++) { if (!visited[i][j]) { _max = max(_max, dfsvisit(i, j, visited, lens, matrix)); } } } return _max; } }; ================================================ FILE: cpp/321-330/Maximum Size Subarray Sum Equals k.cpp ================================================ /* * a[5] = 1 -1 5 -2 3 * sum 1 0 5 3 6 * if k = 2, when i = 3, mymap[1] = 0. the sum in the range is k. */ class Solution { public: int maxSubArrayLen(vector& nums, int k) { map mymap; int sum(0), res(0); for (int i = 0;i < nums.size();i++) { sum += nums[i]; if (sum == k) res = i+1; else { if (mymap.count(sum - k) > 0) res = max(res, i - mymap[sum-k]); } if (mymap.count(sum) == 0) mymap[sum] = i; } return res; } }; ================================================ FILE: cpp/321-330/Number of Connected Components in an Undirected Graph.cpp ================================================ class Solution { int findroot(int c, vector &u) { while (c != u[c]) c = u[c]; return c; } public: int countComponents(int n, vector>& edges) { vector u(n, 0); for (int i = 0;i < n;i++) { u[i] = i; } for (int i = 0;i < edges.size();i++) { int root1 = findroot(edges[i].first, u); int root2 = findroot(edges[i].second, u); if(root1 != root2) { u[root2] = root1; n--; } } return n; } }; ================================================ FILE: cpp/321-330/Odd Even Linked List.cpp ================================================ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* oddEvenList(ListNode* head) { ListNode* oddhead = new ListNode(0); ListNode* res = oddhead; ListNode* evenhead = new ListNode(0); ListNode* res2 = evenhead; int count(1); while(head) { if(count % 2 == 1) { oddhead -> next = head; oddhead = oddhead->next; } else { evenhead -> next = head; evenhead = evenhead->next; } head = head->next; count++; } evenhead->next = nullptr; oddhead -> next = res2 -> next; return res->next; } }; ================================================ FILE: cpp/321-330/Patching Array.cpp ================================================ class Solution { public: int minPatches(vector& nums, int n) { int i(0), res(0); long miss(0); while (miss < n) { if (i < nums.size() && miss >= (nums[i] - 1) ) { miss += nums[i]; i++; } else { res++; miss += (miss+1); } } return res; } }; ================================================ FILE: cpp/321-330/Power of Three.cpp ================================================ class Solution { public: bool isPowerOfThree(int n) { return n > 0 && (1162261467 % n) == 0; } }; ================================================ FILE: cpp/321-330/Wiggle Sort II.cpp ================================================ class Solution { public: void wiggleSort(vector& nums) { int n = nums.size(); // Find a median. auto midptr = nums.begin() + n / 2; nth_element(nums.begin(), midptr, nums.end()); int mid = *midptr; // Index-rewiring. #define A(i) nums[(1+2*(i)) % (n|1)] // 3-way-partition-to-wiggly in O(n) time with O(1) space. int i = 0, j = 0, k = n - 1; while (j <= k) { if (A(j) > mid) swap(A(i++), A(j++)); else if (A(j) < mid) swap(A(j), A(k--)); else j++; } } }; ================================================ FILE: cpp/331-340/Counting Bits.cpp ================================================ /* * 0000 0001 0010 0011 0100 0101 0110 0111 1000 * 0 1 1 2 1 2 2 3 1 */ class Solution { public: vector countBits(int num) { vector myvec(num+1, 0); if(num == 0) return myvec; int loops = 1; while(1) { int _size = loops; for(int k = 0;k < loops;k++) { int index = k+_size; if(index > num) return myvec; myvec[index] = myvec[k]+1; } loops *= 2; } } }; ================================================ FILE: cpp/331-340/House Robber III.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { void help(TreeNode* root, int &a, int &b) { if (root == nullptr) { a = b = 0; return; } // a is including current root, b is not int a1, a2, b1, b2; help(root->left, a1, b1); help(root->right, a2, b2); a = root->val + b1 + b2; b = max(a1 + a2, a1 + b2); b = max(b, a2 + b1); b = max(b, b1 + b2); return; } public: int rob(TreeNode* root) { int a, b; help(root, a, b); return max(a, b); } }; ================================================ FILE: cpp/331-340/Increasing Triplet Subsequence.cpp ================================================ class Solution { public: bool increasingTriplet(vector& nums) { int min1(INT_MAX), min2(INT_MAX); for(int i = 0;i < nums.size();i++) { if(nums[i] > min2) return true; if(nums[i] > min1) min2 = min(min2, nums[i]); else min1 = nums[i]; } return false; } }; ================================================ FILE: cpp/331-340/Largest BST Subtree.cpp ================================================ class Solution { bool isBST(TreeNode* node, int& res, int& mini, int& maxi) { if (!node) return true; int left_size=0, right_size=0; int left_mini, left_maxi, right_mini, right_maxi; bool leftB = isBST(node->left, left_size, left_mini, left_maxi); bool rightB = isBST(node->right, right_size, right_mini, right_maxi); if (leftB && rightB) { if ( (!node->left || node->val >= left_maxi) && (!node->right || node->val <= right_mini) ) { /* The tree rooted at this node is a binary search tree */ res = left_size+right_size+1; mini = node->left ? left_mini : node->val; maxi = node->right ? right_maxi : node->val; return true; } } /* The tree rooted at this node is not a binary search tree, so take the maximum size of the BST in the left or right subtrees */ res = max(left_size, right_size); return false; } public: int largestBSTSubtree(TreeNode* root) { int res = 0; int mini, maxi; bool b = isBST(root, res, mini, maxi); return res; } }; ================================================ FILE: cpp/331-340/Longest Substring with At Most K Distinct Characters.cpp ================================================ class Solution { public: int lengthOfLongestSubstringKDistinct(string s, int k) { int longest = 0; int previouspos = 0; unordered_mapm; int cnt = 0; for (int i = 0; i < s.length(); i++) { m[s[i]]++; if (m[s[i]] == 1) { cnt++; } while (cnt > k) { char ch = s[previouspos]; previouspos++; m[ch]--; if(m[ch] == 0) { cnt--; } } longest = max(longest, i-previouspos+1); } return longest; } }; ================================================ FILE: cpp/331-340/Nested List Weight Sum.cpp ================================================ /** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * class NestedInteger { * public: * // Return true if this NestedInteger holds a single integer, rather than a nested list. * bool isInteger() const; * * // Return the single integer that this NestedInteger holds, if it holds a single integer * // The result is undefined if this NestedInteger holds a nested list * int getInteger() const; * * // Return the nested list that this NestedInteger holds, if it holds a nested list * // The result is undefined if this NestedInteger holds a single integer * const vector &getList() const; * }; */ class Solution { int DFS(vector& nestedList, int depth){ int sum(0); for (int i = 0;i < nestedList.size();i++){ if(nestedList[i].isInteger()) sum += nestedList[i].getInteger()*depth; else sum += DFS(nestedList[i].getList(),depth+1); } return sum; } public: int depthSum(vector& nestedList) { return DFS(nestedList, 1); } }; ================================================ FILE: cpp/331-340/Palindrome Pairs.cpp ================================================ class Solution { unordered_map word_idx; bool isPalindrome(const string& s) { int left = 0; int right = s.size() - 1; while (left < right) { if (s[left] == s[right]) { left++; right--; } else { return false; } } return true; } public: vector> palindromePairs(vector& words) { vector> res; for (int i = 0; i < words.size(); i++) word_idx[words[i]] = i; for (int i = 0; i < words.size(); i++) { const string& word = words[i]; if (!word.empty() && word_idx.count("") > 0 && isPalindrome(word)) { int bidx = word_idx[""]; res.push_back({i, bidx}); res.push_back({bidx, i}); } string rword = string(word.rbegin(), word.rend()); if (word_idx.count(rword) > 0) { int ridx = word_idx[rword]; if (i != ridx) { res.push_back({i, ridx}); } } for (int j = 1; j < word.length(); j++) { string left = word.substr(0, j); string rleft = string(left.rbegin(), left.rend()); string right = word.substr(j); string rright = string(right.rbegin(), right.rend()); if (isPalindrome(left) && word_idx.count(rright) > 0) { res.push_back({word_idx[rright], i}); } if (isPalindrome(right) && word_idx.count(rleft) > 0) { res.push_back({i, word_idx[rleft]}); } } } return res; } }; /* * Trie Solution */ class Trie { bool isPalindrome(const string& s) { int left = 0; int right = s.size() - 1; while (left < right) { if (s[left] == s[right]) { left++; right--; } else { return false; } } return true; } struct TrieNode { TrieNode *nodes[26]; bool isWord; vector indices; int ind; TrieNode(): isWord(false) { memset(nodes, 0, sizeof(nodes)); } }; TrieNode* root_; public: Trie() { root_ = new TrieNode(); } void insert(string& s, int wordIndex) { TrieNode* tmp = root_; int n = s.size(); for (int i = 0; i < n; i++) { int ind = s[i]-'a'; if (tmp->nodes[ind] == nullptr) { tmp->nodes[ind] = new TrieNode(); } if (isPalindrome(s.substr(i))) { tmp->indices.push_back(wordIndex); } tmp = tmp->nodes[ind]; } tmp->indices.push_back(wordIndex); tmp->ind = wordIndex; tmp->isWord = true; } void findPalindrome(const vector& words, int wordIndex, vector>& res) { TrieNode* root = root_; int m = words[wordIndex].size(); bool consume_whole_word = true; for (int j = 0; j < m; j++) { int ind = words[wordIndex][j] - 'a'; if (root->isWord && isPalindrome(words[wordIndex].substr(j))) { if (root->ind != wordIndex) { res.push_back({wordIndex, root->ind}); } } root = root->nodes[ind]; if (root == nullptr) { consume_whole_word = false; break; } } if (consume_whole_word) { for (int index : root->indices) { if (index != wordIndex) { res.push_back({wordIndex, index}); } } } } }; class Solution { public: vector> palindromePairs(vector& words) { int n = words.size(); vector> res; Trie trie; for (int i = 0; i < n; i++) { string current = words[i]; reverse(current.begin(), current.end()); trie.insert(current, i); } for (int i = 0; i < n; i++) { trie.findPalindrome(words, i, res); } return res; } }; ================================================ FILE: cpp/331-340/Reconstruct Itinerary.cpp ================================================ class Solution { public: vector findItinerary(vector> tickets) { vector ans; unordered_map > g; for (int i = 0; i < tickets.size(); ++ i) { g[tickets[i].first].insert(tickets[i].second); } dfs("JFK", ans, g); reverse(ans.begin(), ans.end()); return ans; } private: void dfs(string u, vector &ans, unordered_map >& g){ while (!g[u].empty()) { string v = *g[u].begin(); g[u].erase(g[u].begin()); dfs(v, ans, g); } ans.push_back(u); } }; ================================================ FILE: cpp/331-340/Self Crossing.cpp ================================================ class Solution { public: bool isSelfCrossing(vector& x) { for(int i=3, l=x.size(); i=x[i-2] && x[i-1]<=x[i-3]) return true; // Case 2: current line crosses the line 4 steps ahead of it else if(i>=4 && x[i-1]==x[i-3] && x[i]+x[i-4]>=x[i-2]) return true; // Case 3: current line crosses the line 6 steps ahead of it else if(i>=5 && x[i-2]>=x[i-4] && x[i]+x[i-4]>=x[i-2] && x[i-1]<=x[i-3] && x[i-1]+x[i-5]>=x[i-3]) return true; } return false; } /* i-2 case 1 : i-1┌─┐ └─┼─>i i-3 i-2 case 2 : i-1 ┌────┐ └─══>┘i-3 i i-4 (i overlapped i-4) case 3 : i-4 ┌──┐ │i<┼─┐ i-3│ i-5│i-1 └────┘ i-2 */ }; ================================================ FILE: cpp/331-340/Verify Preorder Serialization of a Binary Tree.cpp ================================================ class Solution { public: bool isValidSerialization(string preorder) { if (preorder.empty()) return false; preorder += ','; int capacity = 1; for (int idx = 0; idx < preorder.size(); idx++) { if (preorder[idx]!=',') continue; capacity--; if (capacity < 0) return false; if (preorder[idx-1] != '#') capacity += 2; } return capacity == 0; } }; ================================================ FILE: cpp/341-350/Design Tic-Tac-Toe.cpp ================================================ class TicTacToe { private: //count parameter: player 1 + : player 2: - vector rowJudge; vector colJudge; int diag, anti; int total; public: /** Initialize your data structure here. */ TicTacToe(int n):total(n), rowJudge(n), colJudge(n),diag(0),anti(0){} int move(int row, int col, int player) { int add = player == 1 ? 1 : -1; diag += row == col ? add : 0; anti += row == total - col - 1 ? add : 0; rowJudge[row] += add; colJudge[col] += add; if(abs(rowJudge[row]) == total || abs(colJudge[col]) == total || abs(diag) == total || abs(anti) == total) return player; return 0; } }; ================================================ FILE: cpp/341-350/Flatten Nested List Iterator.cpp ================================================ /** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * class NestedInteger { * public: * // Return true if this NestedInteger holds a single integer, rather than a nested list. * bool isInteger() const; * * // Return the single integer that this NestedInteger holds, if it holds a single integer * // The result is undefined if this NestedInteger holds a nested list * int getInteger() const; * * // Return the nested list that this NestedInteger holds, if it holds a nested list * // The result is undefined if this NestedInteger holds a single integer * const vector &getList() const; * }; */ class NestedIterator { stack mystack; bool cached; int v; public: NestedIterator(vector &nestedList) { for (int i = nestedList.size()-1;i >= 0;i--) mystack.push(nestedList[i]); cached = false; } int next() { hasNext(); cached = false; return v; } bool hasNext() { if (cached) return true; while (!mystack.empty()) { NestedInteger tmp = mystack.top(); mystack.pop(); if (tmp.isInteger()) { v = tmp.getInteger(); cached = true; return true; } vector nlist = tmp.getList(); for (int i = nlist.size()-1;i >= 0;i--) mystack.push(nlist[i]); } return false; } }; /** * Your NestedIterator object will be instantiated and called as such: * NestedIterator i(nestedList); * while (i.hasNext()) cout << i.next(); */ // pointer /** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * class NestedInteger { * public: * // Return true if this NestedInteger holds a single integer, rather than a nested list. * bool isInteger() const; * * // Return the single integer that this NestedInteger holds, if it holds a single integer * // The result is undefined if this NestedInteger holds a nested list * int getInteger() const; * * // Return the nested list that this NestedInteger holds, if it holds a nested list * // The result is undefined if this NestedInteger holds a single integer * const vector &getList() const; * }; */ class NestedIterator { stack mystack; int cache = 0; bool cached = false; public: NestedIterator(vector &nestedList) { for (int i = nestedList.size() - 1; i >= 0; i--) { mystack.push(&nestedList[i]); } } int next() { hasNext(); cached = false; return cache; } bool hasNext() { if (cached == true) { return true; } while (!mystack.empty()) { NestedInteger* ni = mystack.top(); mystack.pop(); if (ni->isInteger()) { cached = true; cache = ni->getInteger(); return true; } for (int i = ni->getList().size() - 1; i >= 0; i--) { mystack.push(&ni->getList()[i]); } } return false; } }; /** * Your NestedIterator object will be instantiated and called as such: * NestedIterator i(nestedList); * while (i.hasNext()) cout << i.next(); */ ================================================ FILE: cpp/341-350/Integer Break.cpp ================================================ class Solution { public: long long integerBreak(long long n) { if(n == 2) return 1; if(n == 3) return 2; if(n == 4) return 4; if(n == 5) return 6; if(n == 6) return 9; return 3 * integerBreak(n - 3); } }; ================================================ FILE: cpp/341-350/Intersection of Two Arrays II.cpp ================================================ class Solution { public: vector intersect(vector& nums1, vector& nums2) { map mymap; vector ans; for(int ele : nums1) mymap[ele] += 1; for(int ele : nums2) { if(mymap.count(ele) > 0 && mymap[ele] > 0) { ans.push_back(ele); mymap[ele] -= 1; } } return ans; } }; ================================================ FILE: cpp/341-350/Intersection of Two Arrays.cpp ================================================ class Solution { public: vector intersection(vector& nums1, vector& nums2) { set myset, ans; for (int ele : nums1) myset.insert(ele); for (int ele : nums2) if(myset.count(ele) > 0) ans.insert(ele); return vector(ans.begin(), ans.end()); } }; ================================================ FILE: cpp/341-350/Moving Average from Data Stream.cpp ================================================ class MovingAverage { queue myqueue; int size; int sum; public: /** Initialize your data structure here. */ MovingAverage(int size) { this->size = size; this->sum = 0; } double next(int val) { if(myqueue.size() < size) { myqueue.push(val); sum += val; } else { myqueue.push(val); sum += val; sum -= myqueue.front(); myqueue.pop(); } return sum*1.0/myqueue.size(); } }; /** * Your MovingAverage object will be instantiated and called as such: * MovingAverage obj = new MovingAverage(size); * double param_1 = obj.next(val); */ ================================================ FILE: cpp/341-350/Power of Four.cpp ================================================ class Solution { public: bool isPowerOfFour(int num) { return ((num-1)&num)==0 && (num-1)%3==0; } }; ================================================ FILE: cpp/341-350/Reverse String.cpp ================================================ class Solution { public: string reverseString(string s) { for(int i = 0;i < s.length()/2;i++) { swap(s[i], s[s.length()-1-i]); } return s; } }; ================================================ FILE: cpp/341-350/Reverse Vowels of a String.cpp ================================================ class Solution { public: string reverseVowels(string s) { int dict[256] = {0}; dict['a'] = 1, dict['A'] = 1; dict['e'] = 1, dict['E'] = 1; dict['i'] = 1, dict['I'] = 1; dict['o'] = 1, dict['O'] = 1; dict['u'] = 1, dict['U'] = 1; int start = 0, end = (int)s.size() - 1; while(start < end){ while(start < end && dict[s[start]] == 0) start++; while(start < end && dict[s[end]] == 0) end--; swap(s[start++],s[end--]); } return s; } }; ================================================ FILE: cpp/341-350/Top K Frequent Elements.cpp ================================================ class Solution { struct greater_than { inline bool operator() (const pair& left, const pair& right) { return (left.second > right.second); } }; public: vector topKFrequent(vector& nums, int k) { map mymap; vector > myvec; for(int ele : nums) mymap[ele] += 1; for(auto ele : mymap) myvec.push_back(make_pair(ele.first, ele.second)); sort(myvec.begin(), myvec.end(), greater_than()); vector result; for(int i = 0;i < k;i++) result.push_back(myvec[i].first); return result; } }; class Solution { struct greater_than{ bool operator() (const pair&lhs, const pair&rhs) { return lhs.second > rhs.second; } }; public: vector topKFrequent(vector& nums, int k) { unordered_mapdict; priority_queue, vector>,greater_than> q; vector res(k); for(int v : nums) dict[v]++; for(const auto &m:dict) { q.push({m.first,m.second}); if(q.size() > k) { q.pop(); } } while (!q.empty()) { res[--k] = q.top().first; q.pop(); } return res; } }; ================================================ FILE: cpp/351-360/Android Unlock Patterns.cpp ================================================ class Solution { int DFS(vector &vis, vector> &skip, int cur, int remain) { if(remain == 0) return 1; vis[cur] = true; int rst = 0; for (int i = 1; i <= 9; ++i) { if(!vis[i] && (skip[i][cur] == 0 || (vis[skip[i][cur]]))) { rst += DFS(vis, skip, i, remain - 1); } } vis[cur] = false; return rst; } public: int numberOfPatterns(int m, int n) { vector> skip(10, vector(10, 0)); skip[1][3] = skip[3][1] = 2; skip[1][7] = skip[7][1] = 4; skip[3][9] = skip[9][3] = 6; skip[7][9] = skip[9][7] = 8; skip[1][9] = skip[9][1] = skip[2][8] = skip[8][2] = skip[3][7] = skip[7][3] = skip[4][6] = skip[6][4] = 5; vector vis(10); int rst = 0; // DFS search each length from m to n for(int i = m; i <= n; ++i) { rst += DFS(vis, skip, 1, i - 1) * 4; // 1, 3, 7, 9 are symmetric rst += DFS(vis, skip, 2, i - 1) * 4; // 2, 4, 6, 8 are symmetric rst += DFS(vis, skip, 5, i - 1); // 5 } return rst; } }; ================================================ FILE: cpp/351-360/Count Numbers with Unique Digits.cpp ================================================ class Solution { public: int countNumbersWithUniqueDigits(int n) { vector p(n+1, 10); p[0] = 1; p[1] = 10; int temp(9); int base(9); for(int i = 2;i <= n;i++) { temp *= base; base --; p[i] = p[i-1] + temp; } return p[n]; } }; ================================================ FILE: cpp/351-360/Data Stream as Disjoint Intervals.cpp ================================================ /** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class SummaryRanges { vector vec; public: void addNum(int val) { //anonymous function auto Cmp = [](Interval a, Interval b) { return a.start < b.start; }; auto it = lower_bound(vec.begin(), vec.end(), Interval(val, val), Cmp); int start = val, end = val; if (it != vec.begin() && (it-1)->end + 1 >= val) it--; while (it != vec.end() && val+1 >= it->start && val-1 <= it->end) { start = min(start, it->start); end = max(end, it->end); it = vec.erase(it); } vec.insert(it,Interval(start, end)); } vector getIntervals() { return vec; } }; /** * Your SummaryRanges object will be instantiated and called as such: * SummaryRanges obj = new SummaryRanges(); * obj.addNum(val); * vector param_2 = obj.getIntervals(); */ ================================================ FILE: cpp/351-360/Design Snake Game.cpp ================================================ class SnakeGame { queue> myqueue; set> myset; vector> food; int width; int height; int idx; int curi,curj; int score; public: /** Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. */ SnakeGame(int width, int height, vector> food) { myqueue.push(make_pair(0,0)); myset.insert(make_pair(0,0)); this->width = width; this->height = height; this->food = food; this->idx = 0; curi = curj = 0; score = 0; } /** Moves the snake. @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down @return The game's score after the move. Return -1 if game over. Game over when snake crosses the screen boundary or bites its body. */ int move(string direction) { int move_row = 0; int move_col = 0; if(direction == "U") { move_row = -1; } else if(direction == "D") { move_row = 1; } else if(direction == "L") { move_col = -1; } else if(direction == "R") { move_col = 1; } int nexti = curi + move_row; int nextj = curj + move_col; if (nexti < 0 || nexti >= height || nextj < 0 || nextj >= width) return -1; pair head = make_pair(nexti, nextj); myqueue.push(head); if (food[idx] == head) { myset.insert(head); ++score; ++idx; } else { pair tail = myqueue.front(); myqueue.pop(); myset.erase(tail); if (myset.count(head) > 0) return -1; myset.insert(head); } curi = nexti; curj = nextj; return score; } }; /** * Your SnakeGame object will be instantiated and called as such: * SnakeGame obj = new SnakeGame(width, height, food); * int param_1 = obj.move(direction); */ ================================================ FILE: cpp/351-360/Design Twitter.cpp ================================================ class Twitter { map tweetTimeMap; int time; map> userTweetMap; map> followMap; public: /** Initialize your data structure here. */ Twitter() { time = 0; } /** Compose a new tweet. */ void postTweet(int userId, int tweetId) { if(userTweetMap.count(userId) == 0) { vector myvec; userTweetMap[userId] = myvec; } userTweetMap[userId].push_back(tweetId); tweetTimeMap[tweetId] = ++time; } /** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */ vector getNewsFeed(int userId) { vector res; vector follows = followMap[userId]; follows.push_back(userId); vector idxs(follows.size(), 0); for(int i = 0;i < follows.size(); i++) { idxs[i] = userTweetMap[follows[i]].size() - 1; } for(int k = 0; k < 10; k++) { int tempidx; int tweetId; int latestTime(-1); for(int i = 0;i < idxs.size();i++) { if(idxs[i] < 0) continue; int tweetid = userTweetMap[follows[i]][idxs[i]]; int thisTime = tweetTimeMap[tweetid]; if(thisTime > latestTime) { tempidx = i; tweetId = tweetid; latestTime = thisTime; } } if(latestTime < 0) break; idxs[tempidx]--; res.push_back(tweetId); } return res; } /** Follower follows a followee. If the operation is invalid, it should be a no-op. */ void follow(int followerId, int followeeId) { if(followerId == followeeId) return; if(followMap.count(followerId) == 0) { vector myvec; followMap[followerId] = myvec; } vector myvec = followMap[followerId]; for(int i = 0;i < myvec.size();i++) if(myvec[i] == followeeId) return; followMap[followerId].push_back(followeeId); } /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */ void unfollow(int followerId, int followeeId) { if(followerId == followeeId) return; int idx(-1); vector myvec = followMap[followerId]; for(int i = 0;i < myvec.size();i++) { if(myvec[i] == followeeId) { idx = i; break; } } if(idx < 0) return; myvec.erase(myvec.begin() + idx); followMap[followerId] = myvec; } }; /** * Your Twitter object will be instantiated and called as such: * Twitter obj = new Twitter(); * obj.postTweet(userId,tweetId); * vector param_2 = obj.getNewsFeed(userId); * obj.follow(followerId,followeeId); * obj.unfollow(followerId,followeeId); */ ================================================ FILE: cpp/351-360/Line Reflection.cpp ================================================ class Solution { set> myset; public: bool isReflected(vector>& points) { int small(INT_MAX); int large(INT_MIN); for(auto e : points) { small = min(small, e.first); large = max(large, e.first); myset.insert(e); } int mid2 = small+large; for(auto e : points) { pair ref = make_pair(mid2 - e.first, e.second); if(myset.count(ref) == 0) return false; } return true; } }; ================================================ FILE: cpp/351-360/Logger Rate Limiter.cpp ================================================ class Logger { map mymap; public: /** Initialize your data structure here. */ Logger() { } /** Returns true if the message should be printed in the given timestamp, otherwise returns false. The timestamp is in seconds granularity. */ bool shouldPrintMessage(int timestamp, string message) { if(mymap.count(message) == 0) { mymap[message] = timestamp; return true; } int t = mymap[message]; if(timestamp - t < 10) return false; mymap[message] = timestamp; return true; } }; /** * Your Logger object will be instantiated and called as such: * Logger obj = new Logger(); * bool param_1 = obj.shouldPrintMessage(timestamp,message); */ ================================================ FILE: cpp/351-360/Rearrange String k Distance Apart.cpp ================================================ class Solution { public: string rearrangeString(string str, int k) { if(k <= 1) return str; string res; int len = str.length(); map mymap; priority_queue< pair > mypq; for(char c : str) mymap[c]++; for(auto e : mymap) mypq.push({e.second, e.first}); while(!mypq.empty()) { int cnt = min(len, k); vector> myvec; for(int i = 0;i < cnt;i++) { if(mypq.empty()) return ""; pair mypair = mypq.top(); mypq.pop(); res.push_back(mypair.second); if(mypair.first > 1) { myvec.push_back({mypair.first-1, mypair.second}); } } for(auto e : myvec) mypq.push(e); len -= cnt; } return res; } }; ================================================ FILE: cpp/351-360/Russian Doll Envelopes.cpp ================================================ class Solution { public: int maxEnvelopes(vector>& envelopes) { auto Cmp = [&](const pair a, const pair b) { if(a.first < b.first) return true; if(a.first == b.first && a.second > b.second) return true; return false; }; auto Cmp2 = [&](const pair a, const pair b) { return a.second < b.second; }; sort(envelopes.begin(), envelopes.end(), Cmp); vector> res; for (int i=0; i sortTransformedArray(vector& nums, int a, int b, int c) { vector res(nums.size()); if (nums.size() == 0) return res; int i = 0, j = nums.size() - 1; if (a >= 0) { int index = nums.size() - 1; while (i <= j) { if (transform(nums[i], a, b, c) > transform(nums[j], a, b, c)) { res[index--] = transform(nums[i], a, b, c); i++; } else { res[index--] = transform(nums[j], a, b, c); j--; } } } else { int index = 0; while (i <= j) { if (transform(nums[i], a, b, c) < transform(nums[j], a, b, c)) { res[index++] = transform(nums[i], a, b, c); i++; } else { res[index++] = transform(nums[j], a, b, c); j--; } } } return res; } }; ================================================ FILE: cpp/361-370/Bomb Enemy.cpp ================================================ class Solution { public: int maxKilledEnemies(vector>& grid) { int rows = grid.size(); if(rows == 0) return 0; int cols = grid.back().size(); if(cols == 0) return 0; vector> l2r(rows, vector(cols, 0)); vector> r2l(rows, vector(cols, 0)); vector> u2d(rows, vector(cols, 0)); vector> d2u(rows, vector(cols, 0)); for(int i = 0;i < rows;i++) { int cnt(0); for(int j = 0;j < cols;j++) { if(grid[i][j] == 'W') { cnt = 0; } else if(grid[i][j] == 'E') { cnt++; } else { l2r[i][j] = cnt; } } } for(int i = 0;i < rows;i++) { int cnt(0); for(int j = cols-1;j >= 0;j--) { if(grid[i][j] == 'W') { cnt = 0; } else if(grid[i][j] == 'E') { cnt++; } else { r2l[i][j] = cnt; } } } for(int i = 0;i < cols;i++) { int cnt(0); for(int j = 0;j < rows;j++) { if(grid[j][i] == 'W') { cnt = 0; } else if(grid[j][i] == 'E') { cnt++; } else { u2d[j][i] = cnt; } } } for(int i = 0;i < cols;i++) { int cnt(0); for(int j = rows-1;j >= 0;j--) { if(grid[j][i] == 'W') { cnt = 0; } else if(grid[j][i] == 'E') { cnt++; } else { d2u[j][i] = cnt; } } } int res(0); for(int i = 0;i < rows;i++) { for(int j = 0;j < cols;j++) { res = max(res, l2r[i][j]+r2l[i][j]+u2d[i][j]+d2u[i][j]); } } return res; } }; ================================================ FILE: cpp/361-370/Design Hit Counter.cpp ================================================ class HitCounter { map mymap; int total; public: /** Initialize your data structure here. */ HitCounter() { total = 0; } /** Record a hit. @param timestamp - The current timestamp (in seconds granularity). */ void hit(int timestamp) { mymap[timestamp]++; total++; } /** Return the number of hits in the past 5 minutes. @param timestamp - The current timestamp (in seconds granularity). */ int getHits(int timestamp) { while(!mymap.empty()) { auto it = mymap.begin(); if(timestamp - it->first >= 300) { total -= it->second; mymap.erase(it); } else { break; } } return total; } }; /** * Your HitCounter object will be instantiated and called as such: * HitCounter obj = new HitCounter(); * obj.hit(timestamp); * int param_2 = obj.getHits(timestamp); */ ================================================ FILE: cpp/361-370/Find Leaves of Binary Tree.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { int dfs(TreeNode* root, vector> &myvec) { if (root == nullptr) return 0; int ldepth = dfs(root->left, myvec); int rdepth = dfs(root->right, myvec); int depth = 1 + max(ldepth, rdepth); if (myvec.size() < depth) { myvec.resize(myvec.size()+1); } myvec[depth-1].push_back(root->val); return depth; } public: vector> findLeaves(TreeNode* root) { vector> myvec; dfs(root, myvec); return myvec; } }; ================================================ FILE: cpp/361-370/Largest Divisible Subset.cpp ================================================ class Solution { public: vector largestDivisibleSubset(vector& nums) { vector res; if(nums.size() == 0) return res; sort(nums.begin(), nums.end()); vector previous(nums.size(), -1); vector size(nums.size(), 1); int result_idx(0); int max_size(0); for(int i = 1;i < nums.size();i++) { int idx(-1); int msize(1); for(int j = 0;j < i;j++) { if(nums[i] % nums[j] == 0) { if(size[j] + 1 > msize) { msize = size[j]+1; idx = j; } } } previous[i] = idx; size[i] = msize; if(msize > max_size) { result_idx = i; max_size = msize; } } while(result_idx >= 0) { res.push_back(nums[result_idx]); result_idx = previous[result_idx]; } reverse(res.begin(), res.end()); return res; } }; ================================================ FILE: cpp/361-370/Max Sum of Rectangle No Larger Than K.cpp ================================================ class Solution { public: int maxSumSubmatrix(vector>& matrix, int k) { if (matrix.empty()) return 0; int rows = matrix.size(); int cols = matrix[0].size(); int res(INT_MIN); for(int col1 = 0; col1 < cols;col1++) { vector vec(rows, 0); for(int col2 = col1; col2 < cols;col2++) { for(int k = 0;k < rows;k++) { vec[k] += matrix[k][col2]; } set cumset; cumset.insert(0); int best=INT_MIN, cum=0; for(int i = 0;i < rows;i++) { cum+=vec[i]; set::iterator sit=cumset.lower_bound(cum-k); if(sit!=cumset.end())best=max(best,cum-*sit); cumset.insert(cum); } res = max(res, best); } } return res; } }; ================================================ FILE: cpp/361-370/Nested List Weight Sum II.cpp ================================================ /** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * class NestedInteger { * public: * // Return true if this NestedInteger holds a single integer, rather than a nested list. * bool isInteger() const; * * // Return the single integer that this NestedInteger holds, if it holds a single integer * // The result is undefined if this NestedInteger holds a nested list * int getInteger() const; * * // Return the nested list that this NestedInteger holds, if it holds a nested list * // The result is undefined if this NestedInteger holds a single integer * const vector &getList() const; * }; */ class Solution { public: int depthSumInverse(vector& nestedList) { int unweighted = 0, weighted = 0; while (nestedList.size() > 0) { vector nextLevel; for (NestedInteger ni : nestedList) { if (ni.isInteger()) { unweighted += ni.getInteger(); } else { for(NestedInteger e : ni.getList()) nextLevel.push_back(e); } } weighted += unweighted; nestedList = nextLevel; } return weighted; } }; ================================================ FILE: cpp/361-370/Plus One Linked List.cpp ================================================ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { ListNode* reverseList(ListNode* head) { ListNode *tmp(nullptr), *prev(nullptr); while (head != nullptr) { tmp = head->next; head->next = prev; prev = head; head = tmp; } return prev; } public: ListNode* plusOne(ListNode* head) { ListNode* tail = reverseList(head); ListNode* tmptail = tail; int carry(1); while (tail || carry > 0) { if (tail->val + carry < 10) { tail->val ++; break; } else { tail->val = 0; if (tail->next != nullptr) { tail = tail->next; } else { ListNode *newtail = new ListNode(1); tail->next = newtail; break; } } } return reverseList(tmptail); } }; ================================================ FILE: cpp/361-370/Range Addition.cpp ================================================ class Solution { public: vector getModifiedArray(int length, vector>& updates) { //unordered_map mymap; int mymap[150000] = {0}; for(const vector &vec : updates) { mymap[vec[0]] += vec[2]; mymap[vec[1]+1] -= vec[2]; } vector myvec(length, 0); int v(0); for(int i = 0;i < length;i++) { v = v + mymap[i]; myvec[i] = v; } return myvec; } }; ================================================ FILE: cpp/361-370/Valid Perfect Square.cpp ================================================ class Solution { public: bool isPerfectSquare(int num) { int i = 1; int j = num; while (i <= j) { int mid = i + (j - i) / 2; if ((long)mid * (long)mid == (long)num) return true; if ((long)mid * (long)mid > (long)num) { j = mid - 1; } else { i = mid + 1; } } return false; } }; ================================================ FILE: cpp/361-370/Water and Jug Problem.cpp ================================================ class Solution { public: bool canMeasureWater(int x, int y, int z) { if(x > y) return canMeasureWater(y, x, z); if(z == 0) return true; int g = gcd(x,y); if(z <= (x+y) && z % g == 0) return true; return false; } private: int gcd(int a, int b){ return b == 0?a:gcd(b, a%b); } }; ================================================ FILE: cpp/371-380/Combination Sum IV.cpp ================================================ class Solution { public: int combinationSum4(vector& nums, int target) { vector dp(target+1, 0); dp[0] = 1; for (int i = 1;i <= target;i++) for (int k = 0;k < nums.size();k++) if (i - nums[k] >= 0) dp[i] += dp[i - nums[k]]; return dp[target]; } }; ================================================ FILE: cpp/371-380/Design Phone Directory.cpp ================================================ class PhoneDirectory { bool *used; queue avaliable; public: /** Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory. */ PhoneDirectory(int maxNumbers) { for(int i = 0;i < maxNumbers;i++) { avaliable.emplace(i); } used = new bool[maxNumbers]; memset(used, false, maxNumbers); } /** Provide a number which is not assigned to anyone. @return - Return an available number. Return -1 if none is available. */ int get() { if (!avaliable.empty()) { int value = avaliable.front(); avaliable.pop(); used[value] = true; return value; } return -1; } /** Check if a number is available or not. */ bool check(int number) { return !used[number]; } /** Recycle or release a number. */ void release(int number) { if (used[number]) { used[number] = false; avaliable.emplace(number); } } }; /** * Your PhoneDirectory object will be instantiated and called as such: * PhoneDirectory obj = new PhoneDirectory(maxNumbers); * int param_1 = obj.get(); * bool param_2 = obj.check(number); * obj.release(number); */ ================================================ FILE: cpp/371-380/Find K Pairs with Smallest Sums.cpp ================================================ class Solution { typedef pair::iterator> mm; public: vector> kSmallestPairs(vector& nums1, vector& nums2, int k) { vector> res; auto cmp = [] (const mm& p1, const mm& p2) { return p1.first + *(p1.second) > p2.first + *(p2.second); }; priority_queue, decltype(cmp)> pq(cmp); // Given nums1 = [1,7,11], nums2 = [2,4,6], k = 3 // {1, iter} {7, iter} {11, iter} for (int v : nums1) { pq.push({v, nums2.begin()}); } for (int i = 0; i < k && !pq.empty(); i++) { auto ele = pq.top(); pq.pop(); res.push_back({ele.first, *(ele.second)}); ele.second++; if (ele.second != nums2.end()) { pq.push({ele.first, ele.second}); } } return res; } }; ================================================ FILE: cpp/371-380/Guess Number Higher or Lower II.cpp ================================================ class Solution { public: int getMoneyAmount(int n) { vector>table(n+1, vector(n+1,0)); for (int j = 2;j <= n; j++) { for (int i = j-1; i > 0; i--) { int temp_min = INT_MAX; for (int k = i; k < j; k++) { int localMax = k + max(table[i][k==i?k:k-1], table[k+1][j]); temp_min = min(temp_min, localMax); } table[i][j] = temp_min; } } return table[1][n]; } }; ================================================ FILE: cpp/371-380/Guess Number Higher or Lower.cpp ================================================ // Forward declaration of guess API. // @param num, your guess // @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 int guess(int num); class Solution { public: int guessNumber(int n) { int low = 1, high = n; while (low <= high) { int mid = ((long)low+(long)high)/2; int flag = guess(mid); if(flag == 0) return mid; else if(flag == 1) low = mid + 1; else high = mid - 1; } return -1; } }; ================================================ FILE: cpp/371-380/Insert Delete GetRandom O(1).cpp ================================================ class RandomizedSet { unordered_map value_index_map; vector values; public: /** Initialize your data structure here. */ RandomizedSet() { } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ bool insert(int val) { if (value_index_map.count(val) > 0) { return false; } value_index_map[val] = values.size(); values.push_back(val); return true; } /** Removes a value from the set. Returns true if the set contained the specified element. */ bool remove(int val) { if (value_index_map.count(val) == 0) { return false; } int index = value_index_map[val]; value_index_map[values.back()] = index; value_index_map.erase(val); swap(values[index], values.back()); values.erase(values.end() - 1); return true; } /** Get a random element from the set. */ int getRandom() { return values[rand() % values.size()]; } }; /** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet obj = new RandomizedSet(); * bool param_1 = obj.insert(val); * bool param_2 = obj.remove(val); * int param_3 = obj.getRandom(); */ ================================================ FILE: cpp/371-380/Kth Smallest Element in a Sorted Matrix.cpp ================================================ class Solution { public: int kthSmallest(vector>& matrix, int k) { int n = matrix.size(); int L = matrix[0][0], R = matrix[n - 1][n - 1]; while (L < R) { int mid = L + ((R - L) >> 1); int temp = search_lower_than_mid(matrix, mid); if (temp < k) L = mid + 1; else R = mid; } return L; } int search_lower_than_mid(const vector>& matrix, int x) { int n = matrix.size(); int i = n - 1, j = 0, cnt = 0; while (i >= 0 && j < n) { if (matrix[i][j] <= x) { j++; cnt += i + 1; } else i--; } return cnt; } }; ================================================ FILE: cpp/371-380/Sum of Two Integers.cpp ================================================ class Solution { public: int getSum(int a, int b) { if(a == 0) return b; return getSum( (a&b) << 1, a ^ b); } }; ================================================ FILE: cpp/371-380/Super Pow.cpp ================================================ class Solution { int help(int a, int b) { int res(1); a %= 1337; for (int i = 0; i < b; i++) { res = (res * a) % 1337; } return res; } public: int superPow(int a, vector& b) { if (b.empty()) return 1; int last_digit = b.back(); b.pop_back(); return help(superPow(a, b), 10) * help(a, last_digit) % 1337; } }; ================================================ FILE: cpp/371-380/Wiggle Subsequence.cpp ================================================ class Solution { public: int wiggleMaxLength(vector& nums) { int flag(0), count(1); for (int i = 1; i < nums.size(); ++i) { if (nums[i] > nums[i-1] && (flag == -1 || count == 1)) { ++count; flag = 1; } else if (nums[i] < nums[i-1] && (flag == 1 || count == 1)) { ++count; flag = -1; } } return nums.size() == 0 ? 0 : count; } }; ================================================ FILE: cpp/381-390/Elimination Game.cpp ================================================ /* 1 2 3 4 5 6 7 8 9 2 4 6 8(1 2 3 4) */ class Solution { public: // https://discuss.leetcode.com/topic/58042/c-1-line-solution-with-explanation/2 // After first elimination, all the rest numbers are even numbers. // Divide by 2, we get a continuous new sequence from 1 to n / 2. // For this sequence we start from right to left as the first elimination. // Then the original result should be two times the mirroring result of lastRemaining(n / 2). int lastRemaining(int n) { // Great answer. In fact, we can prove that "ML(1...n) + MR(1...n) = 1 + n" holds for any n >= 2, where ML(1...n) means removing elements from left to right first and MR(1...n) means removing elements from right to left first. return n == 1 ? 1 : 2 * (1 + n / 2 - lastRemaining(n / 2)); } }; ================================================ FILE: cpp/381-390/Find the Difference.cpp ================================================ class Solution { public: char findTheDifference(string s, string t) { char onemore(0); for (char ch : s) onemore ^= ch; for (char ch : t) onemore ^= ch; return onemore; } }; ================================================ FILE: cpp/381-390/First Unique Character in a String.cpp ================================================ class Solution { public: int firstUniqChar(string s) { map mymap; for (char ch : s) { mymap[ch]++; } for (int i = 0; i < s.length(); i++) { if (mymap[s[i]] == 1) { return i; } } return -1; } }; ================================================ FILE: cpp/381-390/Insert Delete GetRandom O(1) - Duplicates allowed.cpp ================================================ class RandomizedCollection { unordered_map> value_index_map; vector values; public: /** Initialize your data structure here. */ RandomizedCollection() { } /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */ bool insert(int val) { if (value_index_map.count(val) == 0) { set tmp; value_index_map[val] = tmp; } value_index_map[val].insert(values.size()); values.push_back(val); return value_index_map[val].size() == 1; } /** Removes a value from the collection. Returns true if the collection contained the specified element. */ bool remove(int val) { if (value_index_map.count(val) == 0 || value_index_map[val].empty()) { return false; } int index = *value_index_map[val].begin(); value_index_map[values.back()].insert(index); value_index_map[values.back()].erase(values.size()-1); value_index_map[val].erase(index); swap(values[index], values.back()); values.erase(values.end() - 1); return true; } /** Get a random element from the collection. */ int getRandom() { return values[rand() % values.size()]; } }; /** * Your RandomizedCollection object will be instantiated and called as such: * RandomizedCollection obj = new RandomizedCollection(); * bool param_1 = obj.insert(val); * bool param_2 = obj.remove(val); * int param_3 = obj.getRandom(); */ ================================================ FILE: cpp/381-390/Lexicographical Numbers.cpp ================================================ class Solution { void dfs(int curr, int n, vector& result, int& index) { if (curr <= n) { result[index++] = curr; } else { return; } for (int i = 0; i <= 9; i++) { dfs(curr*10 + i, n, result, index); } } public: vector lexicalOrder(int n) { vector result(n); int index = 0; for (int i = 1; i <= 9; i++) dfs(i, n, result, index); return result; } }; ================================================ FILE: cpp/381-390/Linked List Random Node.cpp ================================================ class Solution { vector myvec; public: /** @param head The linked list's head. Note that the head is guanranteed to be not null, so it contains at least one node. */ Solution(ListNode* head) { while (head != nullptr) { myvec.push_back(head->val); head = head->next; } } /** Returns a random node's value. */ int getRandom() { return myvec[rand()%myvec.size()]; } }; /** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(head); * int param_1 = obj.getRandom(); */ ================================================ FILE: cpp/381-390/Longest Absolute File Path.cpp ================================================ class Solution { public: int lengthLongestPath(string input) { stack myfiles; int index = 0; int ans = 0; int temp = 0; while (true) { int nIndex = input.find("\n", index); string str = nIndex >= 0 ? input.substr(index, nIndex - index) : input.substr(index); int level = 0; while (str[level] == '\t') { level++; } string filename = str.substr(level); while (level < myfiles.size()) { string topFile = myfiles.top(); myfiles.pop(); temp -= topFile.length() ; } myfiles.push(filename); temp += filename.length(); if (filename.find('.') != -1) { ans = max(ans, temp + (int)myfiles.size() - 1); } if (nIndex < 0) break; index = nIndex + 1; } return ans; } }; ================================================ FILE: cpp/381-390/Mini Parser.cpp ================================================ /** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * class NestedInteger { * public: * // Constructor initializes an empty nested list. * NestedInteger(); * * // Constructor initializes a single integer. * NestedInteger(int value); * * // Return true if this NestedInteger holds a single integer, rather than a nested list. * bool isInteger() const; * * // Return the single integer that this NestedInteger holds, if it holds a single integer * // The result is undefined if this NestedInteger holds a nested list * int getInteger() const; * * // Set this NestedInteger to hold a single integer. * void setInteger(int value); * * // Set this NestedInteger to hold a nested list and adds a nested integer to it. * void add(const NestedInteger &ni); * * // Return the nested list that this NestedInteger holds, if it holds a nested list * // The result is undefined if this NestedInteger holds a single integer * const vector &getList() const; * }; */ class Solution { public: NestedInteger deserialize(string s) { if (s.empty()) { return NestedInteger(); } if (isdigit(s[0]) || s[0] == '-') { return NestedInteger(stoi(s)); } s = s.substr(1, s.length()-2); NestedInteger result; int i(0); while (i < s.length()) { int j = i; int counter(0); while (j < s.length()) { if (s[j] == '[') { counter++; } else if (s[j] == ']') { counter--; } else if (s[j] == ',') { if (counter == 0) { result.add(deserialize(s.substr(i, j-i))); break; } } j++; } if (j >= s.length()) { result.add(deserialize(s.substr(i))); break; } i = j+1; } return result; } }; ================================================ FILE: cpp/381-390/Ransom Note.cpp ================================================ class Solution { public: bool canConstruct(string ransomNote, string magazine) { int chs[128] = {0}; for (char ch : magazine) chs[ch]++; for (char ch : ransomNote) if (--chs[ch] < 0) return false; return true; } }; ================================================ FILE: cpp/381-390/Shuffle an Array.cpp ================================================ class Solution { vector nums; public: Solution(vector nums) { this->nums = nums; } /** Resets the array to its original configuration and return it. */ vector reset() { return nums; } /** Returns a random shuffling of the array. */ vector shuffle() { vector result(nums); for (int i = 0;i < result.size();i++) { int pos = rand()%(result.size()-i); swap(result[i+pos], result[i]); } return result; } }; /** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(nums); * vector param_1 = obj.reset(); * vector param_2 = obj.shuffle(); */ ================================================ FILE: cpp/391-400/Decode String.cpp ================================================ class Solution { string solve(const string& s, int& i) { string result; while (i < s.length() && s[i] != ']') { int d = 0; while (isdigit(s[i])) { d = 10 * d + (s[i] - '0'); i++; } if (s[i] == '[') { i++; string temp = solve(s, i); while (d-- > 0) result += temp; } else { result += s[i]; } i++; } return result; } public: string decodeString(string s) { int i = 0; return solve(s, i); } }; ================================================ FILE: cpp/391-400/Evaluate Division.cpp ================================================ class Solution { public: vector calcEquation(vector> equations, vector& values, vector> query) { unordered_map varID; // map var name to its ID vector par; // par[v2]==v1 ; v1 is v2's parent vector parEq; // parEq[v2]==t ; v1 is t times of v2 for (int i=0; i res; for (const auto& q : query) { int v1, v2; if (varID.count(q.first)==1 && varID.count(q.second)==1 ) { v1 = varID[q.first]; v2 = varID[q.second]; } else { res.push_back(-1); continue; } double t1, t2; int r1 = findRoot(par, parEq, v1, t1); //r1 is t1 times of v1 int r2 = findRoot(par, parEq, v2, t2); //r2 is t2 times of v2 if (r1 != r2) res.push_back(-1); else res.push_back(t2/t1); } return res; } int findRoot(vector& par, vector& parEq, int v, double& t) { t = 1; while (v != par[v]) { // path compression parEq[v] = parEq[v] * parEq[par[v]]; par[v] = par[par[v]]; // climb up t *= parEq[v]; v = par[v]; } return v; } }; ================================================ FILE: cpp/391-400/Integer Replacement.cpp ================================================ class Solution { public: int integerReplacement(int n) { if (n == 1) return 0; if (n == 3) return 2; if (n == INT_MAX) return 32; if (n & 1) if ((n + 1) % 4 == 0) return 1+integerReplacement(n + 1); else return 1+integerReplacement(n - 1); else return 1+integerReplacement(n / 2); } }; ================================================ FILE: cpp/391-400/Is Subsequence.cpp ================================================ class Solution { public: bool isSubsequence(string s, string t) { if (s.empty()) return true; int i = 0; for (char ch : t) { if (ch == s[i]) { i++; } if (i >= s.length()) return true; } return i == s.length(); } }; ================================================ FILE: cpp/391-400/Longest Substring with At Least K Repeating Characters.cpp ================================================ class Solution { int dfs(const string& s, int k, int start, int end) { int size = end-start+1; if(size == 0 || k > size) return 0; if(k == 0) return size; int Map[26] = {0}; for(int i = start; i <= end; i++){ Map[s[i]-'a']++; } int idx = start; while(idx <= end && Map[s[idx]-'a'] >= k) idx++; if(idx == end+1) return size; int left = dfs(s, k, start, idx-1); int right = dfs(s, k, idx+1, end); return max(left, right); } public: int longestSubstring(string s, int k) { return dfs(s, k, 0, s.length()-1); } }; ================================================ FILE: cpp/391-400/Nth Digit.cpp ================================================ class Solution { int process(long long num, long long n) { int digit = (n-1)/num; int base = 1; for (int i = 1;i < num;i++) base *= 10; base += digit; return to_string(base)[(n-1)%num] - '0'; } public: int findNthDigit(int n) { long long temp = 9, num = 1; while (true) { if (n - temp*num <= 0) break; n = n - temp*num; temp *= 10; num++; } return process(num, n); } }; ================================================ FILE: cpp/391-400/Perfect Rectangle.cpp ================================================ class Solution { public: bool isRectangleCover(vector>& rectangles) { set points; int area = 0; int leftBottomX = INT_MAX, leftBottomY = INT_MAX, rightTopX = 0, rightTopY = 0; for (const auto& rectangle : rectangles) { leftBottomX = min(leftBottomX, rectangle[0]); leftBottomY = min(leftBottomY, rectangle[1]); rightTopX = max(rightTopX, rectangle[2]); rightTopY = max(rightTopY, rectangle[3]); string p1 = to_string(rectangle[0]) + ":" + to_string(rectangle[1]); string p2 = to_string(rectangle[2]) + ":" + to_string(rectangle[3]); string p3 = to_string(rectangle[0]) + ":" + to_string(rectangle[3]); string p4 = to_string(rectangle[2]) + ":" + to_string(rectangle[1]); vector four{p1, p2, p3, p4}; for (const string p : four) { if (points.count(p) > 0) { points.erase(p); } else { points.insert(p); } } area += (rectangle[2] - rectangle[0]) * (rectangle[3] - rectangle[1]); } if (area != (rightTopX - leftBottomX) * (rightTopY - leftBottomY)) return false; if (points.size() != 4) return false; // Verfify thet are corner points if (points.count(to_string(leftBottomX) + ":" + to_string(leftBottomY)) == 0) return false; if (points.count(to_string(leftBottomX) + ":" + to_string(rightTopY)) == 0) return false; if (points.count(to_string(rightTopX) + ":" + to_string(leftBottomY)) == 0) return false; if (points.count(to_string(rightTopX) + ":" + to_string(rightTopY)) == 0) return false; return true; } }; ================================================ FILE: cpp/391-400/Random Pick Index.cpp ================================================ class Solution { public: vector n; Solution(vector nums) { n = nums; } int pick(int target) { int count = 0, res = -1; for (int i = 0; i < n.size(); ++i) { if (n[i] != target) continue; if (++count == 1) res = i; else if (!(rand()%count)) res = i; } return res; } }; /** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(nums); * int param_1 = obj.pick(target); */ ================================================ FILE: cpp/391-400/Rotate Function.cpp ================================================ class Solution { public: int maxRotateFunction(vector& A) { int res(INT_MIN), sum(0), temp(0); int n = A.size(); int i(1), j(0); int times = 1; for (int k = 1; k < n; k++) { sum += A[k]; temp += times * A[k]; times++; } res = temp; while (j < A.size()) { temp -= sum; temp += (n-1) * A[j]; sum = sum - A[i] + A[j]; i = (++i)%n; j++; res = max(res, temp); } return res; } }; ================================================ FILE: cpp/391-400/UTF-8 Validation.cpp ================================================ class Solution { public: bool validUtf8(vector& data) { int count = 0; for (auto c : data) { if (count == 0) { if ((c >> 5) == 0b110) count = 1; else if ((c >> 4) == 0b1110) count = 2; else if ((c >> 3) == 0b11110) count = 3; else if ((c >> 7)) return false; } else { if ((c >> 6) != 0b10) return false; count--; } } return count == 0; } }; ================================================ FILE: cpp/401-410/Binary Watch.cpp ================================================ class Solution { public: vector readBinaryWatch(int num) { vector rs; for (int h = 0; h < 12; h++) for (int m = 0; m < 60; m++) if (bitset<10>((h << 6) + m).count() == num) rs.emplace_back(to_string(h) + (m < 10 ? ":0" : ":") + to_string(m)); return rs; } }; ================================================ FILE: cpp/401-410/Convert a Number to Hexadecimal.cpp ================================================ class Solution { public: string toHex(int num) { if (num == 0) return "0"; vector toHexChar = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; string result; while (num != 0 && result.size()<8){ result = toHexChar[num&15] + result; num = num >> 4; } return result; } }; ================================================ FILE: cpp/401-410/Frog Jump.cpp ================================================ class Solution { bool dfs(const vector& stones, int stone_index, int speed, unordered_map& cache) { if (stone_index == stones.size() - 1) return true; int key = (stone_index) | (speed << 12); if (cache.count(key) > 0) { return cache[key]; } for (int i = stone_index + 1; i < stones.size(); i++) { int distance = stones[i] - stones[stone_index]; if (distance >= (speed - 1) && distance <= (speed + 1)) { if (dfs(stones, i, distance, cache)) { return cache[key] = true; } } } return cache[key] = false; } public: bool canCross(vector& stones) { unordered_map cache; return dfs(stones, 0, 0, cache); } }; ================================================ FILE: cpp/401-410/Longest Palindrome.cpp ================================================ class Solution { public: int longestPalindrome(string s) { map mymap; for (char ch : s) { mymap[ch]++; } int res = 0; bool odd = false; for (const auto& ele : mymap) { if (ele.second >= 2) { res += ele.second % 2 == 0 ? ele.second : ele.second - 1; } if (ele.second % 2 == 1) { odd = true; } } return odd ? res + 1 : res; } }; ================================================ FILE: cpp/401-410/Queue Reconstruction by Height.cpp ================================================ class Solution { public: vector> reconstructQueue(vector>& people) { auto comp = [](const pair& p1, const pair& p2) { return p1.first > p2.first || (p1.first == p2.first && p1.second < p2.second); }; sort(people.begin(), people.end(), comp); vector> res; for (const auto& p : people) res.insert(res.begin() + p.second, p); return res; } }; ================================================ FILE: cpp/401-410/Remove K Digits.cpp ================================================ class Solution { public: string removeKdigits(string num, int k) { string res = ""; int n = num.size(), keep = n - k; for (char c : num) { while (k && res.size() && res.back() > c) { res.pop_back(); --k; } res.push_back(c); } res.resize(keep); while (!res.empty() && res[0] == '0') res.erase(res.begin()); return res.empty() ? "0" : res; } }; ================================================ FILE: cpp/401-410/Split Array Largest Sum.cpp ================================================ class Solution { public: typedef long long ll; bool canSplit(vector& nums, int m, ll sum) { int c = 1; ll s = 0; for (int num : nums) { s += num; if (s > sum) { s = num; ++c; } } return c <= m; } int splitArray(vector& nums, int m) { ll left = 0, right = 0; for (int num : nums) { left = max(left, (ll)num); right += num; } while (left <= right) { ll mid = left + (right-left)/2; if (canSplit(nums, m, mid)) right = mid-1; else left = mid+1; } return left; } }; ================================================ FILE: cpp/401-410/Sum of Left Leaves.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int sumOfLeftLeaves(TreeNode* root) { if (!root) return 0; if (root && root->left) { if (!root->left->left && !root->left->right) return root->left->val + sumOfLeftLeaves(root->right); } return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right); } }; ================================================ FILE: cpp/401-410/Trapping Rain Water II.cpp ================================================ class Solution { public: int trapRainWater(vector>& heightMap) { priority_queue, vector>, greater>> que; int row = heightMap.size(), col = heightMap[0].size(); vector> visited(row, vector(col, false)); int minimum = INT_MAX; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (!(i==0 || i==row-1 || j==0 || j==col-1)) continue; que.push({heightMap[i][j], i * col + j}); visited[i][j] = true; minimum = min(minimum, heightMap[i][j]); } } pair dir[4] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; int ans = 0; while (!que.empty()) { pair val = que.top(); que.pop(); int height = val.first; int x = val.second / col; int y = val.second % col; minimum = max(minimum, height); for (const pair& d: dir) { int nx = x + d.first; int ny = y + d.second; if (nx >= row || nx < 0 || ny < 0 || ny >= col || visited[nx][ny]) continue; visited[nx][ny] = true; if (heightMap[nx][ny] < minimum) { ans += minimum - heightMap[nx][ny]; } que.push({heightMap[nx][ny], nx * col + ny}); } } return ans; } }; ================================================ FILE: cpp/401-410/Valid Word Abbreviation.cpp ================================================ class Solution { public: bool validWordAbbreviation(string word, string abbr) { int p1 = 0, p2 = 0; while (p1 < word.size() && p2 < abbr.size()) { //If a digit starts with 0, abbr is invalid if (abbr[p2] == '0') return false; //get the next digit int num = 0; while (p2 < abbr.size() && isdigit(abbr[p2])) { num = num * 10 + abbr[p2] - '0'; p2++; } //increment the pointer in words p1 += num; //check current state is match or unmatch. if (p1 == word.size() && p2 == abbr.size()) { return true; } else if (p1 >= word.size() || p2 >= abbr.size() || word[p1] != abbr[p2]) { return false; } p1++; p2++; } return p1 == word.size() && p2 == abbr.size(); } }; ================================================ FILE: cpp/411-420/Add Strings.cpp ================================================ class Solution { public: string addStrings(string num1, string num2) { string result; int carry = 0; int i1 = num1.length() - 1; int i2 = num2.length() - 1; while (i1 >= 0 || i2 >= 0 || carry > 0) { int v1 = i1 >= 0 ? num1[i1] - '0' : 0; int v2 = i2 >= 0 ? num2[i2] - '0' : 0; int sum = v1 + v2 + carry; result.push_back(sum % 10 + '0'); carry = sum / 10; i1--; i2--; } reverse(begin(result), end(result)); return result; } }; ================================================ FILE: cpp/411-420/Arithmetic Slices.cpp ================================================ class Solution { public: int numberOfArithmeticSlices(vector& A) { int n = A.size(); if (n < 3) return 0; vector dp(n, 0); // dp[i] means the number of arithmetic slices ending with A[i] if (A[2]-A[1] == A[1]-A[0]) dp[2] = 1; // if the first three numbers are arithmetic or not int result = dp[2]; for (int i = 3; i < n; ++i) { // if A[i-2], A[i-1], A[i] are arithmetic, then the number of arithmetic slices ending with A[i] (dp[i]) // equals to: // the number of arithmetic slices ending with A[i-1] (dp[i-1], all these arithmetic slices appending A[i] are also arithmetic) // + // A[i-2], A[i-1], A[i] (a brand new arithmetic slice) // it is how dp[i] = dp[i-1] + 1 comes if (A[i]-A[i-1] == A[i-1]-A[i-2]) dp[i] = dp[i-1] + 1; result += dp[i]; // accumulate all valid slices } return result; } }; ================================================ FILE: cpp/411-420/Battleships in a Board.cpp ================================================ class Solution { public: int countBattleships(vector>& board) { if (board.empty() || board[0].empty()) { return 0; } int m = board.size(), n = board[0].size(), cnt = 0; for (int r = 0; r < m; r++) for (int c = 0; c < n; c++) cnt += board[r][c] == 'X' && (r == 0 || board[r - 1][c] != 'X') && (c == 0 || board[r][c - 1] != 'X'); return cnt; } }; ================================================ FILE: cpp/411-420/Fizz Buzz.cpp ================================================ class Solution { public: vector fizzBuzz(int n) { vector ret_vec(n); for (int i = 1; i <= n; ++i) { if (i%3 == 0) ret_vec[i-1] = "Fizz"; if (i%5 == 0) ret_vec[i-1] += "Buzz"; if (ret_vec[i-1] == "") ret_vec[i-1] += to_string(i); } return ret_vec; } }; ================================================ FILE: cpp/411-420/Minimum Unique Word Abbreviation.cpp ================================================ class Solution { struct TrieNode { TrieNode* childs[26]; TrieNode () { memset(childs, 0, sizeof(childs)); } }; public: string minAbbreviation(string target, vector& dictionary) { int n = target.size(); vector dic; // select word with the same length as target for (const string& s:dictionary) { if (s.size() == n) dic.emplace_back(s); } // build a trie; the depth of all leaves is the same TrieNode* root = build(dic); // generate abbreviation of target with length 1 until n-1; If it is valid, return // For example, if the target is "apple", abbreviation has format of "11p11", whose length is 3 // This is to help function valid; for (int i = 1; i <= n-1; i++) { vector abbrs; generate_abb(abbrs, target, "", 0, i); for (const string& s: abbrs) { // encode(s) reformat "11p11" to "2p2" if (valid(root, s, 0)) return encode(s); } } return target; } private: void generate_abb(vector& abbrs, string& s, string cur, int pos, int len) { // backtracking, ending cases are len = 0 or len = 1; if (pos == s.size()) { if (len == 0) abbrs.push_back(cur); return; } else if (len == 0) return; if (len == 1) { if (pos != s.size()) { for (int i = pos; i < s.size(); i++) cur += '1'; abbrs.push_back(cur); } return; } //next char can be at any index [pos s.size()] // if next char at pos, len = len-1; // else len = len-2 because we add both a number and a char generate_abb(abbrs, s, cur+s[pos], pos+1, len-1); for (int i = pos+1; i < s.size(); i++) { cur += '1'; generate_abb(abbrs, s, cur+s[i], i+1, len-2); } } TrieNode* build(vector& dic) { TrieNode* root = new TrieNode(); for (string s:dic) { TrieNode* p = root; for (int i = 0; i < s.size(); i++) { if (p->childs[s[i]-'a'] == nullptr) p->childs[s[i]-'a'] = new TrieNode(); p = p->childs[s[i]-'a']; } } return root; } // if search continues to leaves, there is an conflict, return false; bool valid(TrieNode* root, const string& s, int i) { if (i == s.size()) return false; if (s[i] == '1') { for (int j = 0; j < 26; j++) { // if any path results in conflict, return false if (root->childs[j] && !valid(root->childs[j], s, i+1)) return false; } return true; } else { if (root->childs[s[i]-'a'] == nullptr) return true;; return valid(root->childs[s[i]-'a'], s, i+1); } } string encode(const string& s) { string ans; int cnt = 0; for (int i = 0; i < s.size(); i++) { if (s[i] == '1') cnt++; else if (cnt == 0) ans += s[i]; else { ans += to_string(cnt)+s[i]; cnt = 0; } } if (cnt) ans += to_string(cnt); return ans; } }; ================================================ FILE: cpp/411-420/Pacific Atlantic Water Flow.cpp ================================================ class Solution { vector> res; vector> visited; public: void dfs(vector>& matrix, int x, int y, int pre, int preval){ if (x < 0 || x >= matrix.size() || y < 0 || y >= matrix[0].size() || matrix[x][y] < pre || (visited[x][y] & preval) == preval) return; visited[x][y] |= preval; if (visited[x][y] == 3) res.push_back({x, y}); dfs(matrix, x + 1, y, matrix[x][y], visited[x][y]); dfs(matrix, x - 1, y, matrix[x][y], visited[x][y]); dfs(matrix, x, y + 1, matrix[x][y], visited[x][y]); dfs(matrix, x, y - 1, matrix[x][y], visited[x][y]); } vector> pacificAtlantic(vector>& matrix) { if (matrix.empty()) return res; int m = matrix.size(), n = matrix[0].size(); visited.resize(m, vector(n, 0)); for (int i = 0; i < m; i++) { dfs(matrix, i, 0, INT_MIN, 1); dfs(matrix, i, n - 1, INT_MIN, 2); } for (int i = 0; i < n; i++) { dfs(matrix, 0, i, INT_MIN, 1); dfs(matrix, m - 1, i, INT_MIN, 2); } return res; } }; ================================================ FILE: cpp/411-420/Partition Equal Subset Sum.cpp ================================================ class Solution { public: bool canPartition(vector& nums) { if (nums.size() <= 1) return false; int sum = 0; for (int num : nums) sum += num; if (sum % 2 == 1) return false; sum /= 2; vector dp(sum+1, false); dp[0] = true; sort(nums.begin(), nums.end()); for (int num : nums) for (int i = 0;i <= sum-num;i++) if (dp[i] == true) dp[i + num] = true; return dp[sum]; } }; ================================================ FILE: cpp/411-420/Sentence Screen Fitting.cpp ================================================ class Solution { public: int wordsTyping(vector& sentence, int rows, int cols) { unordered_map umap; int num = 0, n = sentence.size(); for (int i = 0; i < rows; i++){ int start = num % n; if (umap.count(start) == 0){ int cnt = 0, len = 0; for (int i = start; len < cols; i = (i+1) % n, cnt++) { if (len + sentence[i].size() > cols) break; len += sentence[i].size() + 1; } umap[start] = cnt; } num += umap[start]; } return num / n; } }; ================================================ FILE: cpp/411-420/Third Maximum Number.cpp ================================================ class Solution { public: int thirdMax(vector& nums) { set top3; for (int num : nums) { top3.insert(num); if (top3.size() > 3) top3.erase(top3.begin()); } return top3.size() == 3 ? *top3.begin() : *top3.rbegin(); } }; ================================================ FILE: cpp/421-430/Convert Binary Search Tree to Sorted Doubly Linked List.cpp ================================================ class Solution { void inorder(Node* cur, Node*& prev, Node*& head) { if (head == nullptr && cur->left == nullptr) { head = cur; } Node* left = cur->left; Node* right = cur->right; if (left != nullptr) { inorder(left, prev, head); } if (prev != nullptr) { prev->right = cur; } cur->left = prev; prev = cur; if (right != nullptr) { inorder(right, prev, head); } } public: Node* treeToDoublyList(Node* root) { if (root == nullptr) { return nullptr; } Node* prev = nullptr; Node* head = nullptr; inorder(root, prev, head); prev->right = head; head->left = prev; return head; } }; ================================================ FILE: cpp/421-430/Maximum XOR of Two Numbers in an Array.cpp ================================================ class Solution { public: class TreeNode { public: TreeNode* next[2]; TreeNode () {next[0] = NULL; next[1] = NULL;}; }; TreeNode* buildTree(vector& nums) { TreeNode* root = new TreeNode(), *cur; int n = nums.size(); for (int i = 0; i < n; i++) { int num = nums[i]; cur = root; for (int j = 31; j >= 0; j--) { int index = ((num >> j) & 1); if (cur->next[index] == NULL) cur->next[index] = new TreeNode(); cur = cur->next[index]; } } return root; } int helper(TreeNode* cur, int num) { int res = 0; for (int i = 31; i >= 0; i--) { int index = ((num >> i) & 1) ? 0 : 1; if (cur->next[index]) { res <<= 1; res |= 1; cur = cur->next[index]; } else { res <<= 1; res |= 0; cur = cur->next[index ? 0 : 1]; } } return res; } int findMaximumXOR(vector& nums) { int res = 0; TreeNode* root = buildTree(nums); for (int i : nums) { res = max(res, helper(root, i)); } return res; } }; ================================================ FILE: cpp/421-430/Serialize and Deserialize N-ary Tree.cpp ================================================ /* // Definition for a Node. class Node { public: int val; vector children; Node() {} Node(int _val) { val = _val; } Node(int _val, vector _children) { val = _val; children = _children; } }; */ class Codec { public: // rule: root, number of child, each child // Encodes a tree to a single string. string serialize(Node* root) { string data; encode_dfs(root, data); return data; } void encode_dfs(Node* root, string& data){ if (root == nullptr) return; data += to_string(root->val) + " " + to_string(root->children.size()) + " "; for (Node* child : root->children) { encode_dfs(child, data); } } // Decodes your encoded data to tree. Node* deserialize(string data) { stringstream ss(data); return decode(ss); } Node* decode(stringstream& ss) { int val, child_size; if (ss >> val >> child_size) { Node* root = new Node(val); for (int i = 0; i < child_size; i++) { root->children.push_back(decode(ss)); } return root; } return nullptr; } }; // Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root)); ================================================ FILE: cpp/421-430/Valid Word Square.cpp ================================================ class Solution { public: bool validWordSquare(vector& words) { for(int i = 0; i < words.size(); ++i) { for(int j = 0; j < words[i].size(); ++j) { if(j >= words.size() || words[j].size() <= i || words[j][i] != words[i][j]) return false; } } return true; } }; ================================================ FILE: cpp/421-430/Word Squares.cpp ================================================ class Solution { public: struct TrieNode { vector indexs; vector children; TrieNode(): children(26, nullptr) { } }; TrieNode* buildTrie(const vector& words) { TrieNode* root = new TrieNode(); for (int j = 0; j < words.size(); j++) { TrieNode* t = root; for (int i = 0; i < words[j].size(); i++) { if (!t->children[words[j][i] - 'a']) t->children[words[j][i] - 'a'] = new TrieNode(); t = t->children[words[j][i] - 'a']; t->indexs.push_back(j); } } return root; } vector> res; vector vec; void backtrack(const vector& words, int level, TrieNode* root) { if (level >= words[0].size()) { res.emplace_back(vec); return; } string str; for (int i = 0; i < level; i++) str += vec[i][level]; TrieNode* t = root; for (int i = 0; i < str.size(); i++) if (!(t = t->children[str[i] - 'a'])) return; for (int index : t->indexs) { vec[level] = words[index]; backtrack(words, level + 1, root); } } vector> wordSquares(vector& words) { if (words.empty()) return res; TrieNode* root = buildTrie(words); vec.resize((int)words[0].size()); for (const string& word : words) { vec[0] = word; backtrack(words, 1, root); } return res; } }; ================================================ FILE: cpp/431-440/All O`one Data Structure.cpp ================================================ class AllOne { public: void inc(string key) { // If the key doesn't exist, insert it with value 0. if (!bucketOfKey.count(key)) bucketOfKey[key] = buckets.insert(buckets.begin(), {0, {key}}); // Insert the key in next bucket and update the lookup. auto next = bucketOfKey[key], bucket = next++; if (next == buckets.end() || next->value > bucket->value + 1) next = buckets.insert(next, {bucket->value + 1, {}}); next->keys.insert(key); bucketOfKey[key] = next; // Remove the key from its old bucket. bucket->keys.erase(key); if (bucket->keys.empty()) buckets.erase(bucket); } void dec(string key) { // If the key doesn't exist, just leave. if (!bucketOfKey.count(key)) return; // Maybe insert the key in previous bucket and update the lookup. list::iterator prev = bucketOfKey[key], bucket = buckets.begin(); if (prev != buckets.begin()) bucket = prev--; bucketOfKey.erase(key); if (bucket->value > 1) { if (bucket == buckets.begin() || prev->value < bucket->value - 1) prev = buckets.insert(bucket, {bucket->value - 1, {}}); prev->keys.insert(key); bucketOfKey[key] = prev; } // Remove the key from its old bucket. bucket->keys.erase(key); if (bucket->keys.empty()) buckets.erase(bucket); } string getMaxKey() { return buckets.empty() ? "" : *(buckets.rbegin()->keys.begin()); } string getMinKey() { return buckets.empty() ? "" : *(buckets.begin()->keys.begin()); } private: struct Bucket { int value; unordered_set keys; }; list buckets; unordered_map::iterator> bucketOfKey; }; ================================================ FILE: cpp/431-440/Find All Anagrams in a String.cpp ================================================ class Solution { public: vector findAnagrams(string s, string p) { unordered_map mymap; int psize = p.size(); vector ans; for (char ch : p) mymap[ch]++; int cnt = 0; for (int i = 0; i < s.size(); i++) { char ch = s[i]; mymap[ch]--; if (mymap[ch] >= 0) cnt++; if (i >= psize) { char poped_ch = s[i - psize]; int times = ++mymap[poped_ch]; if (times > 0) cnt--; } if (cnt == psize) ans.push_back(i - psize + 1); } return ans; } }; ================================================ FILE: cpp/431-440/Find Right Interval.cpp ================================================ /** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class Solution { public: vector findRightInterval(vector& intervals) { map hash; vector res; int n = intervals.size(); for (int i = 0; i < n; ++i) hash[intervals[i].start] = i; for (auto in : intervals) { auto itr = hash.lower_bound(in.end); if (itr == hash.end()) res.push_back(-1); else res.push_back(itr->second); } return res; } }; ================================================ FILE: cpp/431-440/K-th Smallest in Lexicographical Order.cpp ================================================ class Solution { int dfs(string prefix, int n) { string n_string = to_string(n); string ptrfix_of_n = n_string.substr(0, prefix.length()); if (prefix.length() == n_string.length()) { return prefix <= n_string ? 1 : 0; } if (prefix > ptrfix_of_n) { int temp = 1; for (int k = 0; k < (n_string.length() - prefix.length() - 1); k++) { temp = temp * 10 + 1; } return temp; } if (prefix < ptrfix_of_n) { int temp = 1; for (int k = 0; k < (n_string.length() - prefix.length()); k++) { temp = temp * 10 + 1; } return temp; } int ans = 1; for (int i = 0; i <= 9; i++) { ans += dfs(prefix+to_string(i), n); } return ans; } public: int findKthNumber(int n, int k) { string prefix = ""; while (k > 0) { for (int i = 0; i <= 9; i++) { if (prefix.empty() && i == 0) continue; string new_prefix = prefix + to_string(i); int tmp = dfs(new_prefix, n); if (tmp >= k) { prefix = new_prefix; k -= 1; break; } else { k -= tmp; } } } return stoi(prefix); } }; ================================================ FILE: cpp/431-440/Minimum Genetic Mutation.cpp ================================================ class Solution { public: int minMutation(string start, string end, vector& bank) { queue toVisit; unordered_set dict(bank.begin(), bank.end()); int dist = 0; if(!dict.count(end)) return -1; toVisit.push(start); dict.insert(start); dict.insert(end); while(!toVisit.empty()) { int n = toVisit.size(); for(int i=0; i& dict, queue& toVisit) { for(int i=0; i& mymap, int currentSum, int target) { if (!root) return; currentSum += root->val; res += mymap[currentSum - target]; mymap[currentSum]++; dfs(root->left, mymap, currentSum, target); dfs(root->right, mymap, currentSum, target); mymap[currentSum]--; } public: int pathSum(TreeNode* root, int sum) { res = 0; map mymap; mymap[0] = 1; dfs(root, mymap, 0, sum); return res; } }; ================================================ FILE: cpp/431-440/Ternary Expression Parser.cpp ================================================ class Solution { public: string parseTernary(string expression) { stack s; for (int i = expression.size() - 1; i >= 0; --i) { char c = expression[i]; if (!s.empty() && s.top() == '?') { s.pop(); char first = s.top(); s.pop(); s.pop(); char second = s.top(); s.pop(); s.push(c == 'T' ? first : second); } else { s.push(c); } } return string(1, s.top()); } }; ================================================ FILE: cpp/441-450/Add Two Numbers II.cpp ================================================ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { ListNode* addToFront(int val, ListNode* head){ ListNode* temp = new ListNode(val); temp->next = head; return temp; } int length(ListNode* head) { int len = 0; while (head) { len++; head = head->next; } return len; } public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { int n1 = length(l1); int n2 = length(l2); int carry = 0; ListNode *curr1 = l1, *curr2 = l2, *res = nullptr; while (n1 > 0 || n2 > 0){ int sum = 0; if( n1 >= n2 ){ sum += curr1->val; curr1=curr1->next; n1--;} if( n2 > n1 ){ sum += curr2->val; curr2=curr2->next; n2--;} res = addToFront( sum, res ); } curr1 = res; res = nullptr; while( curr1 || carry) { int tmp = curr1 ? curr1->val : 0; tmp += carry; carry = tmp/10; res = addToFront(tmp%10, res); if (!curr1) break; curr2 = curr1; curr1 = curr1->next; delete curr2; } return res; } }; ================================================ FILE: cpp/441-450/Arithmetic Slices II - Subsequence.cpp ================================================ class Solution { public: int numberOfArithmeticSlices(vector& A) { int n = A.size(); vector> dp(n); int ans = 0; for (int i = 0; i < n; i++) { // dp[x][delta] += dp[y][delta] + 1(y∈[0, x - 1]) for (int j = 0; j < i; j++) { long delta = (long)A[i] - (long)A[j]; if (delta > INT_MAX || delta < INT_MIN) continue; dp[i][delta]++; if (dp[j].find(delta) != dp[j].end()) { dp[i][delta] += dp[j][delta]; ans += dp[j][delta]; } } } return ans; } }; ================================================ FILE: cpp/441-450/Arranging Coins.cpp ================================================ class Solution { public: int arrangeCoins(int n) { long ans = 0; long level = 1; while (ans + level <= n) { ans += level; level++; } return level - 1; } }; ================================================ FILE: cpp/441-450/Delete Node in a BST.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* deleteNode(TreeNode* root, int key) { if (!root) return nullptr; if (root->val == key) { if (root->right == nullptr) { TreeNode* left = root->left; delete root; return left; } else { TreeNode* right = root->right; while (right->left) right = right->left; swap(root->val, right->val); root->right = deleteNode(root->right, key); return root; } } if (key < root->val) { root->left = deleteNode(root->left, key); } else { root->right = deleteNode(root->right, key); } return root; } }; ================================================ FILE: cpp/441-450/Find All Duplicates in an Array.cpp ================================================ class Solution { public: vector findDuplicates(vector& nums) { vector res; int i = 0; while (i < nums.size()) { if (nums[i] != nums[nums[i]-1]) swap(nums[i], nums[nums[i]-1]); else i++; } for (i = 0; i < nums.size(); i++) { if (nums[i] != i + 1) res.push_back(nums[i]); } return res; } }; ================================================ FILE: cpp/441-450/Number of Boomerangs.cpp ================================================ class Solution { public: int numberOfBoomerangs(vector>& points) { int res = 0; // iterate over all the points for (int i = 0; i < points.size(); ++i) { unordered_map group; // iterate over all points other than points[i] for (int j = 0; j < points.size(); ++j) { if (j == i) continue; int dy = points[i].second - points[j].second; int dx = points[i].first - points[j].first; // compute squared euclidean distance from points[i] int key = dy * dy + dx * dx; // accumulate # of such "j"s that are "key" distance from "i" ++group[key]; } for (auto& p : group) { if (p.second > 1) { /* * for all the groups of points, * number of ways to select 2 from n = * nP2 = n!/(n - 2)! = n * (n - 1) */ res += p.second * (p.second - 1); } } } return res; } }; ================================================ FILE: cpp/441-450/Sequence Reconstruction.cpp ================================================ class Solution { public: bool sequenceReconstruction(vector& org, vector>& seqs) { map> graph; map idxs; for (int i = 0; i < org.size(); i++) idxs[org[i]] = i; for (int j = 0; j < seqs.size(); j++) { vector seq = seqs[j]; for (int i = 0; i < seq.size(); i++) { if (idxs.count(seq[i]) == 0) return false; if (i > 0 && idxs[seq[i - 1]] >= idxs[seq[i]]) return false; graph[seq[i-1]].insert(seq[i]); } } if (graph.empty()) return false; for (int i = 0; i < org.size() - 1; i++) if (graph[org[i]].count(org[i+1]) == 0) return false; return true; } }; ================================================ FILE: cpp/441-450/Serialize and Deserialize BST.cpp ================================================ class Codec { public: // Encodes a tree to a single string. string serialize(TreeNode* root) { string order; preorderDFS(root, order); return order; } void preorderDFS(TreeNode* root, string& order) { if (!root) return; char buf[4]; memcpy(buf, &(root->val), sizeof(int)); //burn the int into 4 chars for (int i = 0; i < 4; i++) order.push_back(buf[i]); preorderDFS(root->left, order); preorderDFS(root->right, order); } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { int pos = 0; return reconstruct(data, pos, INT_MIN, INT_MAX); } inline TreeNode* reconstruct(const string& buffer, int& pos, int minValue, int maxValue) { if (pos >= buffer.size()) return nullptr; int value; memcpy(&value, &buffer[pos], sizeof(int)); if (value < minValue || value > maxValue) return nullptr; TreeNode* node = new TreeNode(value); pos += sizeof(int); node->left = reconstruct(buffer, pos, minValue, value); node->right = reconstruct(buffer, pos, value, maxValue); return node; } }; ================================================ FILE: cpp/441-450/String Compression.cpp ================================================ class Solution { public: int compress(vector& chars) { int cnt = 1; char cur = chars[0]; int writePos = 0; for (int i = 0; i < chars.size(); i++) { bool shouldWrite = i == chars.size() - 1 || cur != chars[i+1]; if (shouldWrite) { chars[writePos++] = cur; if (cnt > 1) { string tmp = to_string(cnt); for (char t : tmp) { chars[writePos++] = t; } } cur = chars[i+1]; cnt = 1; } else { cnt++; } } return writePos; } }; ================================================ FILE: cpp/451-460/132 Pattern.cpp ================================================ class Solution { public: bool find132pattern(vector& nums) { int third = INT_MIN; stack mystack; for (int i = nums.size()-1; i >= 0; i--) { if (nums[i] < third) return true; while (!mystack.empty() && nums[i] > mystack.top()) { third = mystack.top(); mystack.pop(); } mystack.push(nums[i]); } return false; } }; ================================================ FILE: cpp/451-460/4Sum II.cpp ================================================ class Solution { public: void fillMap(const vector& A, const vector& B, unordered_map &m) { int n = A.size(); for(int i = 0; i < n; ++i) for(int j = 0; j < n; ++j) m[A[i] + B[j]]++; } int fourSumCount(vector& A, vector& B, vector& C, vector& D) { unordered_map m1, m2; fillMap(A, B, m1); fillMap(C, D, m2); int res = 0; for(auto it = m1.begin(); it != m1.end(); ++it) { auto it2 = m2.find(-it->first); if(it2 != m2.end()) res += it->second*it2->second; } return res; } }; ================================================ FILE: cpp/451-460/Assign Cookies.cpp ================================================ class Solution { public: int findContentChildren(vector& g, vector& s) { sort(g.begin(),g.end()); sort(s.begin(),s.end()); int i = g.size()-1, j = s.size()-1, res = 0; while(i>=0 && j>=0) { if (g[i] > s[j]) i--; else if (g[i--] <= s[j--]) res++; } return res; } }; ================================================ FILE: cpp/451-460/LFU Cache.cpp ================================================ class LFUCache { int capacity; int size; int minFreq; unordered_map> m; //key to {value,freq}; unordered_map::iterator> mIter; //key to list iterator; unordered_map> fm; //freq to key list; public: LFUCache(int capacity) { this->capacity = capacity; size = 0; } int get(int key) { if (m.count(key) == 0) return -1; fm[m[key].second].erase(mIter[key]); m[key].second++; fm[m[key].second].push_back(key); mIter[key] = --fm[m[key].second].end(); if (fm[minFreq].empty()) minFreq++; return m[key].first; } void put(int key, int value) { if (capacity <= 0) return; int oldValue = get(key); // only update the value if(oldValue != -1) { m[key].first=value; return; } // evict the least frequent item if (size >= capacity ) { int badKey = fm[minFreq].front(); m.erase(badKey); mIter.erase(badKey); fm[minFreq].pop_front(); size--; } m[key] = {value, 1}; fm[1].push_back(key); mIter[key] = --fm[1].end(); minFreq = 1; size++; } }; ================================================ FILE: cpp/451-460/Minimum Moves to Equal Array Elements.cpp ================================================ class Solution { public: int minMoves(vector& nums) { return accumulate(begin(nums), end(nums), 0) - nums.size() * *min_element(begin(nums), end(nums)); } }; ================================================ FILE: cpp/451-460/Minimum Number of Arrows to Burst Balloons.cpp ================================================ class Solution { public: int findMinArrowShots(vector>& points) { int count = 0, arrow = INT_MIN; auto cmp = [&] (const pair& a, const pair& b) { return a.second == b.second ? a.first < b.first : a.second < b.second; }; sort(points.begin(), points.end(), cmp); for (int i = 0; i < points.size(); i++) { if (arrow != INT_MIN && points[i].first <= arrow) { continue; } //former arrow shot points[i] arrow = points[i].second; // new arrow shot the end of points[i] count++; } return count; } }; ================================================ FILE: cpp/451-460/Repeated Substring Pattern.cpp ================================================ class Solution { public: bool repeatedSubstringPattern(string str) { int len = str.length(); for (int i = 1; i <= len/2; i++) { if (len % i != 0) continue; string part = str.substr(0, i); int dups = len / i; bool ff = true; for (int k = 0; k < dups; k++) { int idx = k * i; bool f = true; for (int j = 0; j < i; j++) { if (str[idx + j] != str[j]) { f = false; break; } } if (f == false) { ff = false; break; } } if (ff == false) continue; return true; } return false; } }; ================================================ FILE: cpp/451-460/Sort Characters By Frequency.cpp ================================================ class Solution { public: string frequencySort(string s) { map freq; vector bucket(s.size()+1, ""); string res; //count frequency of each character for (char c : s) freq[c]++; //put character into frequency bucket for (const auto& it : freq) { int n = it.second; char c = it.first; bucket[n].append(n, c); } //form descending sorted string for (int i = s.size(); i>0; i--) { if (!bucket[i].empty()) res.append(bucket[i]); } return res; } }; ================================================ FILE: cpp/461-470/Can I Win.cpp ================================================ class Solution { int buildkey (bool *nums, int N) { int key = 0; for (int i = 1; i <= N;i++) if (nums[i] == true) key |= (1 << i); return key; } bool caniwin (bool *nums, int N, int desiredTotal, map &cache) { int key = buildkey(nums, N); if (cache.count(key) > 0) return cache[key]; for (int i = 1; i <= N; i++) { if (nums[i] == false) { if (i >= desiredTotal) return true; nums[i] = true; bool win = !caniwin(nums, N, desiredTotal - i, cache); nums[i] = false; if (win) return cache[key] = true; } } return cache[key] = false; } public: bool canIWin(int maxChoosableInteger, int desiredTotal) { if (desiredTotal == 0) return true; if ( (1 + maxChoosableInteger) * maxChoosableInteger / 2 < desiredTotal) return false; bool nums[maxChoosableInteger+1] = {false}; mapcache; return caniwin(nums, maxChoosableInteger, desiredTotal, cache); } }; ================================================ FILE: cpp/461-470/Convex Polygon.cpp ================================================ class Solution { public: bool isConvex(vector>& points) { if (points.size() < 3) return false; int last = 0; for (int i = 0; i < points.size(); i++) { auto pre = i == 0 ? points.back() : points[i - 1]; auto after = i == points.size() - 1 ? points[0] : points[i + 1]; int x1 = points[i][0] - pre[0], y1 = points[i][1] - pre[1]; int x2 = after[0] - points[i][0], y2 = after[1] - points[i][1]; long flag = x1 * y2 - x2 * y1; if (last * flag < 0) return false; if (flag != 0) { last = flag; } } return true; } }; ================================================ FILE: cpp/461-470/Count The Repetitions.cpp ================================================ /* 0 1 2 3 0 1 2 3 0 1 2 3 0 S1 --------------> abacb | abacb | abacb | abacb | abacb | abacb repeatCount -----> 0 | 1 | 1 | 2 | 2 | 3 Increment of repeatCount -> 0 | 1 | 0 | 1 | 0 | 1 nextIndex -------> 2 | 1 | 2 | 1 | 2 | 1 "nlhqgllunmelayl" 10000 "lnl" 10 1 2 10000 20000 0 1 2 1 3 5 1 1 1 "niconiconi" 99981 "nico" 81 0 1 2 3 2 4 2 2 "nlhqgllunmelayl" 2 "lnl" 1 0 1 1 3 1 */ class Solution { public: int getMaxRepetitions(string s1, int n1, string s2, int n2) { map mymap1, mymap2; // mymap1 : index -> count, mymap2 : nextindex -> s1_pattern_count int index = 0; int repeatCount = 0; for (int i = 1; i <= n1; i++) { for (int j = 0; j < s1.size(); j++) { if (s1[j] == s2[index]) { index++; if (index == s2.size()) { repeatCount++; index = 0; } } } mymap1[i] = repeatCount; if (mymap2.count(index) > 0) { int start = mymap2[index]; int cycle = i - start; int diff = repeatCount - mymap1[start]; int pattern_repeat = diff * ( (n1 - start) / cycle); int remain = mymap1[start + (n1 - start) % cycle]; return (pattern_repeat + remain) / n2; } mymap2[index] = i; } return mymap1[n1-1]/n2; } }; // mymap2[index] ================================================ FILE: cpp/461-470/Hamming Distance.cpp ================================================ class Solution { public: int hammingDistance(int x, int y) { return __builtin_popcount(x^y); } }; ================================================ FILE: cpp/461-470/Island Perimeter.cpp ================================================ class Solution { public: int islandPerimeter(vector>& grid) { int count=0, repeat=0; for (int i = 0; i < grid.size(); i++) { for (int j = 0; j < grid[i].size(); j++) { if (grid[i][j] == 1) { count ++; if (i != 0 && grid[i-1][j] == 1) repeat++; if (j != 0 && grid[i][j-1] == 1) repeat++; } } } return 4*count-repeat*2; } }; ================================================ FILE: cpp/461-470/Minimum Moves to Equal Array Elements II.cpp ================================================ class Solution { public: int minMoves2(vector& nums) { std::nth_element(nums.begin(), nums.begin() + nums.size()/2, nums.end()); int median = nums[nums.size()/2]; int res = 0; for (int v : nums) res += abs(median - v); return res; } }; ================================================ FILE: cpp/461-470/Optimal Account Balancing.cpp ================================================ class Solution { int helper(vector& a, int start, int n) { int ans = INT_MAX; while(start < n && a[start] == 0) start++; for (int i = start + 1; i < n; ++i) { if ( (a[i] * a[start] < 0) ) { a[i] += a[start]; ans = min(ans, 1 + helper(a, start + 1, n)); a[i] -= a[start]; } } return ans == INT_MAX ? 0 : ans; } public: int minTransfers(vector>& transactions) { map net; for (const auto& t : transactions) { net[t[0]] -= t[2]; net[t[1]] += t[2]; } vector a; for (const auto& ele : net) { if (ele.second != 0) { a.push_back(ele.second); } } return helper(a, 0, a.size()); } }; ================================================ FILE: cpp/461-470/Unique Substrings in Wraparound String.cpp ================================================ class Solution { public: int findSubstringInWraproundString(string p) { vector cnt(26, 0); int len = 0; for (int i = 0; i < p.size(); ++i) { if (i > 0 && (p[i] - p[i-1] + 26) % 26 == 1) { ++len; } else { len = 1; } cnt[p[i] - 'a'] = max(cnt[p[i] - 'a'], len); } return accumulate(cnt.begin(), cnt.end(), 0); } }; ================================================ FILE: cpp/461-470/Validate IP Address.cpp ================================================ class Solution { void split(const std::string &s, char delim, std::vector &elems) { std::stringstream ss; ss.str(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } } std::vector split(const std::string &s, char delim) { std::vector elems; split(s, delim, elems); return elems; } static bool validateV4num(const string& num) { if (num.empty() || num.length() > 3) return false; for (char c : num) if (!isdigit(c)) return false; int v = stoi(num); if (v >= 0 && v <= 255 && to_string(v).length() == num.length()) return true; return false; } static bool validateV6num(const string& num) { if (num.empty() || num.length() > 4) return false; for (char c : num) { if (isdigit(c)) continue; if (c >= 'a' && c <= 'f') continue; if (c >= 'A' && c <= 'F') continue; return false; } return true; } string checkV4(const string& IP) { vector nums = split(IP, '.'); if (nums.size() != 4) return "Neither"; if ( std::all_of(nums.begin(), nums.end(), validateV4num) ) return "IPv4"; return "Neither"; } string checkV6(const string& IP) { vector nums = split(IP, ':'); if (nums.size() != 8) return "Neither"; if ( std::all_of(nums.begin(), nums.end(), validateV6num) ) return "IPv6"; return "Neither"; } public: string validIPAddress(string IP) { if (!isalnum(IP.back())) return "Neither"; if (IP.find('.') != std::string::npos) return checkV4(IP); else if (IP.find(':') != std::string::npos) return checkV6(IP); else return "Neither"; } }; ================================================ FILE: cpp/471-480/Concatenated Words.cpp ================================================ class Solution { public: vector findAllConcatenatedWordsInADict(vector& words) { vector result; if(words.empty()) return result; auto mycomp = [&](const string& str1, const string& str2){return str1.size() < str2.size();}; sort(words.begin(), words.end(), mycomp); unordered_set mp; for(string& word: words) { if(wordBreak(word, mp)) result.push_back(word); // We don't need to insert this word, because it can be concatenated from other words. else mp.insert(word); } return result; } private: bool wordBreak(const string& s, const unordered_set& wordDict) { if(s.empty() || wordDict.empty()) return false; vector dp(s.size()+1, false); dp[0] = true; for(int i = 1; i <= s.size(); i++) { for(int k = i-1; k >= 0; k--) { if(dp[k] && wordDict.find(s.substr(k, i-k)) != wordDict.end()) { dp[i] = true; break; } } } return dp.back(); } }; ================================================ FILE: cpp/471-480/Encode String with Shortest Length.cpp ================================================ class Solution { int numRepetition(const string &s, const string &t) { int cnt = 0,i = 0; while (i < s.length()) { if (s.substr(i, t.length()) != t) break; cnt++; i += t.length(); } return cnt; } string dfs(const string& s, unordered_map &m) { if (s.length() < 5) return s; if (m.count(s) > 0) return m[s]; string res(s); for (int i = 0; i < s.length(); i++) { string s1 = s.substr(0, i+1); int cnt = numRepetition(s, s1); string t; for (int k = 1; k <= cnt; k++) { if (k == 1) t = s1 + dfs(s.substr(i+1), m); else t = to_string(k) + "[" + dfs(s1, m) + "]" + dfs(s.substr(k*s1.length()), m); if (t.length() < res.length()) res=t; } } return m[s] = res; } public: string encode(string s) { unordered_map m; return dfs(s,m); } }; ================================================ FILE: cpp/471-480/Heaters.cpp ================================================ class Solution { public: int findRadius(vector& houses, vector& heaters) { sort(heaters.begin(), heaters.end()); int res = -1; for (int i = 0; i < houses.size(); i++) { auto it = lower_bound(heaters.begin(), heaters.end(), houses[i]); int tmp = INT_MAX; if (it != heaters.end()) tmp = *it - houses[i]; if (it != heaters.begin()) tmp = min(tmp, houses[i] - *(it-1)); res = max(res, tmp); } return res; } }; ================================================ FILE: cpp/471-480/Largest Palindrome Product.cpp ================================================ class Solution { public: int largestPalindrome(int n) { if (n == 1) return 9; int upper = pow(10, n) - 1; int lower = pow(10, n-1); for (int i = upper; i >= lower; i--) { long cand = buildPalindrome(i); for (long j = upper; j*j >= cand; j--) { if (cand % j == 0 && cand / j <= upper) { return cand % 1337; } } } return -1; } long buildPalindrome(int n) { string s = to_string(n); reverse(s.begin(), s.end()); return stol(to_string(n) + s); } }; ================================================ FILE: cpp/471-480/Matchsticks to Square.cpp ================================================ class Solution { map cache; int genKey(const vector& nums) { int key = 0; for (int v : nums) { key *= 2; if (v > 0) key += 1; } return key; } bool dfs(vector& nums, int sidelength, int remain, int sideidx, int currentlength) { int key = genKey(nums); if (cache.count(key) > 0) return cache[key]; if (sideidx >= 4) return cache[key] = true; if (currentlength > sidelength) return cache[key]=false; if (remain <= 0) return cache[key]=false; for (int i = 0; i < nums.size(); i++) { if (nums[i] <= 0) continue; int temp = currentlength + nums[i]; if (temp > sidelength) continue; int v = nums[i]; nums[i] = -1; if (temp == sidelength) { bool fff = dfs(nums, sidelength, remain-1, sideidx+1, 0); if (fff) return true; } else if (temp < sidelength) { bool fff = dfs(nums, sidelength, remain-1, sideidx, temp); if (fff) return true; } nums[i] = v; } return cache[key]=false; } public: bool makesquare(vector& nums) { int sum = accumulate(nums.begin(), nums.end(), 0); if (sum % 4 != 0) return false; int sidelength = sum/4; return dfs(nums, sidelength, nums.size(), 0, 0); } }; ================================================ FILE: cpp/471-480/Number Complement.cpp ================================================ class Solution { public: int findComplement(int num) { int mask = 0xffffffff; while (num & mask) mask <<= 1; return ~mask & ~num; } }; ================================================ FILE: cpp/471-480/Ones and Zeroes.cpp ================================================ class Solution { pair count(const string& str) { int x = 0, y = 0; for (char ch : str) { if (ch == '0') x++; else y++; } return {x, y}; } public: int findMaxForm(vector& strs, int m, int n) { vector> dp(m+1, vector(n+1, 0)); for (const auto& str : strs) { auto pairs = count(str); for (int i = m; i >= pairs.first; i--) for (int j = n; j >= pairs.second; j--) dp[i][j] = max(1 + dp[i-pairs.first][j-pairs.second], dp[i][j]); } return dp[m][n]; } }; ================================================ FILE: cpp/471-480/Sliding Window Median.cpp ================================================ class Solution { public: vector medianSlidingWindow(vector& nums, int k) { multiset window(nums.begin(), nums.begin() + k); auto mid = next(window.begin(), k / 2); vector medians; for (int i=k; ; i++) { // Push the current median. medians.push_back((double(*mid) + *next(mid, k%2 - 1)) / 2); // If all done, return. if (i == nums.size()) return medians; // Insert nums[i]. window.insert(nums[i]); if (nums[i] < *mid) mid--; // Erase nums[i-k]. if (nums[i-k] <= *mid) mid++; window.erase(window.lower_bound(nums[i-k])); } } }; I prefer this solution. https://leetcode.com/problems/sliding-window-median/discuss/96347/O(n*log(n))-Time-C%2B%2B-Solution-Using-Two-Heaps-and-a-Hash-Table ================================================ FILE: cpp/471-480/Total Hamming Distance.cpp ================================================ class Solution { public: int totalHammingDistance(vector& nums) { vector> stats(2, vector(32, 0)); int totalhammingdistance = 0; for (int v : nums) { for (int i = 0; i < 32; i++, v/=2) { int key = v & 0x1; totalhammingdistance += stats[1-key][i]; stats[key][i] ++; } } return totalhammingdistance; } }; ================================================ FILE: cpp/481-490/Find Permutation.cpp ================================================ class Solution { public: vector findPermutation(string s) { vector result; for (int i = 0; i <= s.size(); i++) { if (s[i] == 'I' || i == s.size()) { int curL = result.size(); for (int j = i+1; j > curL; j--) { result.push_back(j); } } } return result; } }; ================================================ FILE: cpp/481-490/License Key Formatting.cpp ================================================ class Solution { public: string licenseKeyFormatting(string S, int K) { string ans; int cnt = 0; for(int i = S.size() - 1; i >= 0; i--) { if(S[i] != '-') { if(cnt == 0 && !ans.empty()) ans.push_back('-'); ans.push_back(toupper(S[i])); cnt = (cnt + 1) % K; } } reverse(ans.begin(), ans.end()); return ans; } }; ================================================ FILE: cpp/481-490/Magical String.cpp ================================================ class Solution { public: int magicalString(int n) { if (n <= 3) return n > 0; queue q; int res = 1; bool one = true; q.push(2); n -= 3; //122, start from second 2 while (n) { int cnt = q.front(); q.pop(); while (n && cnt--) { q.push(one ? 1 : 2); n--; res += one; } one = !one; } return res; } }; ================================================ FILE: cpp/481-490/Max Consecutive Ones II.cpp ================================================ class Solution { public: int findMaxConsecutiveOnes(vector& nums) { int i = 0, j = 0, zeros = 0, res = 0; for (; j < nums.size(); j++) { if (nums[j] == 0) zeros++; if (zeros > 1) { while (nums[i] == 1) i++; i++; zeros--; } res = max(res, j-i+1); } return res; } }; ================================================ FILE: cpp/481-490/Max Consecutive Ones.cpp ================================================ class Solution { public: int findMaxConsecutiveOnes(vector& nums) { bool flag = false; int res = 0, tmp = 0; for (int v : nums) { if (v == 1) { tmp++; flag = true; } else { res = max(res, tmp); flag = false; tmp = 0; } } res = max(res, tmp); return res; } }; ================================================ FILE: cpp/481-490/Predict the Winner.cpp ================================================ class Solution { public: bool PredictTheWinner(vector& nums) { int sum = accumulate(begin(nums), end(nums), 0); int n = nums.size(); vector> dp(n, vector(n)); for (int i = 0; i < n; i++) dp[i][i] = nums[i]; for (int i = 0; i < n-1; i++) dp[i][i+1] = max(nums[i], nums[i+1]); for (int k = 2; k < n; k++) { for (int i = 0; i+k < n; i++) { int v1 = nums[i] + dp[i+2][i+k]; int v2 = nums[i] + dp[i+1][i+k-1]; int v3 = nums[i+k] + dp[i][i+k-2]; int v4 = nums[i+k] + dp[i+1][i+k-1]; dp[i][i+k] = max(min(v1,v2), min(v3,v4)); } } return dp[0][n-1] >= sum - dp[0][n-1]; } }; ================================================ FILE: cpp/481-490/Robot Room Cleaner.cpp ================================================ /** * // This is the robot's control interface. * // You should not implement it, or speculate about its implementation * class Robot { * public: * // Returns true if the cell in front is open and robot moves into the cell. * // Returns false if the cell in front is blocked and robot stays in the current cell. * bool move(); * * // Robot will stay in the same cell after calling turnLeft/turnRight. * // Each turn will be 90 degrees. * void turnLeft(); * void turnRight(); * * // Clean the current cell. * void clean(); * }; */ class Solution { void dfs(Robot &robot, set>& visited, int i, int j, int dir) { robot.clean(); visited.insert({i, j}); pair directions[4] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; for (int k = 0; k < 4; k++) { int new_i = i + directions[dir].first; int new_j = j + directions[dir].second; if (visited.count({new_i, new_j}) == 0 && robot.move()) { dfs(robot, visited, new_i, new_j, dir); robot.turnRight(); robot.turnRight(); robot.move(); robot.turnRight(); robot.turnRight(); } dir = (dir + 1) % 4; robot.turnRight(); } } public: void cleanRoom(Robot& robot) { set> visited; dfs(robot, visited, /*i=*/0, /*j=*/0, /*dir=*/0); } }; ================================================ FILE: cpp/481-490/Smallest Good Base.cpp ================================================ class Solution { public: string smallestGoodBase(string n) { long long num = stol(n); for (int i = log(num + 1) / log(2); i >= 2; --i) { long long left = 2, right = pow(num, 1.0 / (i - 1)) + 1; while (left < right) { long long mid = left + (right - left) / 2, sum = 0; for (int j = 0; j < i; ++j) { sum = sum * mid + 1; } if (sum == num) return to_string(mid); else if (sum < num) left = mid + 1; else right = mid; } } return to_string(num - 1); } }; ================================================ FILE: cpp/481-490/The Maze.cpp ================================================ class Solution { int isStone(vector>& maze, int i, int j) { int N1 = maze.size(); int N2 = maze[0].size(); if (i < 0 || j < 0 || i >= N1 || j >= N2) return 1; return maze[i][j]; } public: bool hasPath(vector>& maze, vector& start, vector& destination) { queue> myqueue; set> visited; myqueue.push({start[0], start[1]}); visited.insert({start[0], start[1]}); pair directions[4] = {{0,1},{0,-1},{1,0},{-1,0}}; while (!myqueue.empty()) { pair pos = myqueue.front(); myqueue.pop(); if (pos.first == destination[0] && pos.second == destination[1]) return true; for (int i = 0;i < 4;i++) { int nx = pos.first; int ny = pos.second; while (!isStone(maze, nx, ny)) { nx += directions[i].first; ny += directions[i].second; } nx -= directions[i].first; ny -= directions[i].second; pair n_pos{nx, ny}; if (visited.count(n_pos) == 0) { myqueue.push(n_pos); visited.insert(n_pos); } } } return false; } }; ================================================ FILE: cpp/481-490/Zuma Game.cpp ================================================ class Solution { int dfs(string board, string hand, unordered_map& cache) { if (board.empty()) return 0; if (hand.empty()) return 999; string key = board + ":" + hand; if (cache.count(key) > 0) return cache[key]; int step = 10; for (int i = 0;i <= board.size();i++) { int res = 0; int idx = hand.find(board[i]); if (idx < 0) continue; if (i+1 < board.size() && board[i] == board[i+1]) { string nhand = hand.substr(0, idx) + hand.substr(idx+1); string after_board = board.substr(0,i) + board.substr(i+2); simplify(after_board); if (after_board.empty()) return 1; res = 1 + dfs(after_board, nhand, cache); } else if (idx + 1 < hand.size() && hand[idx] == hand[idx+1]) { string nhand = hand.substr(0, idx) + hand.substr(idx+2); string after_board = board.substr(0,i) + board.substr(i+1); simplify(after_board); if (after_board.empty()) return 2; res = 2 + dfs(after_board, nhand, cache); } else { continue; } step = min(step, res); while (i+1 < board.size() && board[i] == board[i+1]) i++; } return cache[key] = step; } public: int findMinStep(string board, string hand) { sort(hand.begin(), hand.end()); unordered_map cache; int step = dfs(board, hand, cache); return step > 5 ? -1 : step; } void simplify(string& str) { while(str.size() > 0) { int start = 0; bool done = true; for (int i = 0; i <= str.size(); i++) { if (i == str.size() || str[i] != str[start]) { if (i - start >= 3) { str = str.substr(0, start) + str.substr(i); done = false; break; } start = i; } } if (done) break; } } }; ================================================ FILE: cpp/491-500/Construct the Rectangle.cpp ================================================ class Solution { public: vector constructRectangle(int area) { vector output(2); output[0] = 1; output[1] = area; int length = 0; for (int width = 1; width <= (int)sqrt(area); width++) { length = area/width; if ((length * width) == area && abs(length - width) <= abs(output[0] - output[1])) { output[0] = length; output[1] = width; } } return output; } }; ================================================ FILE: cpp/491-500/Diagonal Traverse.cpp ================================================ class Solution { public: vector findDiagonalOrder(vector>& matrix) { if (matrix.empty() || matrix.front().empty()) return vector(); int m = matrix.size(); int n = matrix.front().size(); int total = m * n; vector ans(total); bool up = true; int i = 0, j = 0; for (int k = 0; k < total; k++) { ans[k] = matrix[i][j]; if (up && (i == 0 || j == n - 1)) { if (j == n - 1) i++; else j++; up = !up; } else if (!up && (j == 0 || i == m - 1)) { if (i == m - 1) j++; else i++; up = !up; } else { if (up) { i--; j++; } else { i++; j--; } } } return ans; } }; ================================================ FILE: cpp/491-500/Increasing Subsequences.cpp ================================================ class Solution { private: void findSubsequences(const vector &nums, vector &subsequence, set > &result, int index) { if (subsequence.size() >= 2) result.insert(subsequence); for (int i = index; i < nums.size(); ++i) { if (subsequence.size() == 0 || nums[i] >= subsequence.back()) { subsequence.push_back(nums[i]); findSubsequences(nums, subsequence, result, i + 1); subsequence.pop_back(); } } } public: vector> findSubsequences(vector& nums) { set> resultSet; vector subsequence; findSubsequences(nums, subsequence, resultSet, 0); return vector>(begin(resultSet), end(resultSet)); } }; ================================================ FILE: cpp/491-500/Keyboard Row.cpp ================================================ class Solution { public: vector findWords(vector& words) { string a[3] = { "QWERTYUIOPqwertyuiop", "ASDFGHJKLasdfghjkl", "ZXCVBNMzxcvbnm", }; vector ans; for (int index = 0; index < 3; ++ index) { for (auto& word: words) { int cnt = 0; for (auto ch: word) { if (a[index].find(ch) != string::npos) { cnt ++; } } if (cnt == word.size()) { ans.push_back(word); } } } return ans; } }; ================================================ FILE: cpp/491-500/Next Greater Element I.cpp ================================================ class Solution { public: vector nextGreaterElement(vector& findNums, vector& nums) { map mymap; stack mystack; for (int i = nums.size()-1; i >= 0; i--) { while (!mystack.empty() && mystack.top() < nums[i]) { mystack.pop(); } mymap[nums[i]] = mystack.empty() ? -1 : mystack.top(); mystack.push(nums[i]); } vector result; for (int v : findNums) { result.push_back(mymap[v]); } return result; } }; ================================================ FILE: cpp/491-500/Reverse Pairs.cpp ================================================ class Solution { private: int count; void merge(vector& nums, int start, int mid, int end){ int l = start, r = mid + 1; while(l <= mid && r <= end){ if((long)nums[l] > (long) 2 * nums[r]){ count += (mid - l + 1); r++; } else{ l++; } } sort(nums.begin() + start, nums.begin() + end + 1); } void mergeSort(vector& nums, int start, int end){ if(start == end) return; int mid = (start + end)/2; mergeSort(nums, start, mid); mergeSort(nums, mid+1, end); merge(nums, start, mid, end); } public: int reversePairs(vector& nums) { if (nums.empty()) return 0; count = 0; mergeSort(nums, 0, nums.size()-1); return count; } }; ================================================ FILE: cpp/491-500/Target Sum.cpp ================================================ class Solution { int dfs(const vector& nums, int i, int S, map, int>& cache) { pair key = {i, S}; if (cache.count(key) > 0) return cache[key]; if (i == nums.size()) return S == 0 ? 1 : 0; int curNum = nums[i]; int v1 = dfs(nums, i + 1, S - curNum, cache); int v2 = dfs(nums, i + 1, S + curNum, cache); return cache[key] = v1+v2; } public: int findTargetSumWays(vector& nums, int S) { map, int> cache; return dfs(nums, 0, S, cache); } }; ================================================ FILE: cpp/491-500/Teemo Attacking.cpp ================================================ class Solution { public: int findPoisonedDuration(vector& timeSeries, int duration) { if (timeSeries.empty()) return 0; int begin = timeSeries[0], result = 0; for (int v : timeSeries) { result += begin + duration >= v ? v - begin : duration; begin = v; } return result + duration; } }; ================================================ FILE: cpp/491-500/The Maze III.cpp ================================================ class Solution { int isStone(vector>& maze, int i, int j) { int N1 = maze.size(); int N2 = maze[0].size(); if (i < 0 || j < 0 || i >= N1 || j >= N2) return 1; return maze[i][j]; } public: string findShortestWay(vector>& maze, vector& ball, vector& hole) { queue> myqueue; map, pair> distance; myqueue.push({ball[0], ball[1]}); distance[{ball[0], ball[1]}] = {0, ""}; pair directions[4] = {{1,0},{0,-1},{0,1},{-1,0}}; string dis = "dlru"; string res = "impossible"; int minimum_distance = INT_MAX; while (!myqueue.empty()) { pair pos = myqueue.front(); myqueue.pop(); for (int i = 0;i < 4;i++) { int nx = pos.first; int ny = pos.second; int step = 0; while (!isStone(maze, nx, ny)) { if (nx == hole[0] && ny == hole[1]) { if (minimum_distance > distance[pos].first + step) { minimum_distance = distance[pos].first + step; res = distance[pos].second + dis[i]; } else if (minimum_distance == distance[pos].first + step) { res = min(res, distance[pos].second + dis[i]); } } nx += directions[i].first; ny += directions[i].second; step++; } nx -= directions[i].first; ny -= directions[i].second; step--; pair n_pos{nx, ny}; if (distance.count(n_pos) == 0 || distance[pos].first + step < distance[n_pos].first) { myqueue.push(n_pos); distance[n_pos].first = distance[pos].first + step; distance[n_pos].second = distance[pos].second + dis[i]; } else if (distance[pos].first + step == distance[n_pos].first) { if (distance[pos].second + dis[i] < distance[n_pos].second) { distance[n_pos].second = distance[pos].second + dis[i]; myqueue.push(n_pos); } } } } return res; } }; ================================================ FILE: cpp/501-510/Base 7.cpp ================================================ class Solution { public: string convertToBase7(int num) { bool negative = false; if (num < 0) { negative = true; num = -num; } int result = 0; int base = 1; while (num > 0) { int temp = num % 7; num = (num - temp)/7; result += base * temp; base *= 10; } string resultStr = to_string(result); if (negative) resultStr = "-" + resultStr; return resultStr; } }; ================================================ FILE: cpp/501-510/Find Mode in Binary Search Tree.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { void dfs(TreeNode* root, int& maximum_count, map& mymap) { if (!root) return; int v = root->val; mymap[v]++; maximum_count = max(maximum_count, mymap[v]); dfs(root->left, maximum_count, mymap); dfs(root->right, maximum_count, mymap); } public: vector findMode(TreeNode* root) { map mymap; vector result; int maximum_count(0); dfs(root, maximum_count, mymap); for (auto it : mymap) if (it.second == maximum_count) result.push_back(it.first); return result; } }; ================================================ FILE: cpp/501-510/IPO.cpp ================================================ class Compare1 { public: bool operator() (const pair& p1, const pair& p2) { return p1.second - p2.second >= 0; } }; class Compare2 { public: bool operator() (const pair& p1, const pair& p2) { return p2.first - p1.first >= 0; } }; class Solution { public: int findMaximizedCapital(int k, int W, vector& Profits, vector& Capital) { priority_queue, vector>, Compare1> stocks; priority_queue, vector>, Compare2> avaliable; for (int i = 0; i < Profits.size(); i++) { stocks.push({Profits[i], Capital[i]}); } for (int i = 0; i < k; i++) { while (!stocks.empty() && stocks.top().second <= W) { avaliable.push(stocks.top()); stocks.pop(); } if (!avaliable.empty()) { W += avaliable.top().first; avaliable.pop(); } } return W; } }; ================================================ FILE: cpp/501-510/Most Frequent Subtree Sum.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector findFrequentTreeSum(TreeNode* root) { unordered_map counts; int maxCount = 0; countSubtreeSums(root, counts, maxCount); vector maxSums; for(const auto& x : counts){ if(x.second == maxCount) maxSums.push_back(x.first); } return maxSums; } int countSubtreeSums(TreeNode *r, unordered_map &counts, int& maxCount){ if(r == nullptr) return 0; int sum = r->val; sum += countSubtreeSums(r->left, counts, maxCount); sum += countSubtreeSums(r->right, counts, maxCount); ++counts[sum]; maxCount = max(maxCount, counts[sum]); return sum; } }; ================================================ FILE: cpp/501-510/Next Greater Element II.cpp ================================================ class Solution { public: vector nextGreaterElements(vector& nums) { stack mystack; int n = nums.size(); nums.resize(2*nums.size()); copy(nums.begin(), nums.begin()+n, nums.begin()+n); vector result(n, 0); for (int i = nums.size()-1; i >= 0; i--) { while (!mystack.empty() && mystack.top() <= nums[i]) { mystack.pop(); } if (i < n) { result[i] = mystack.empty() ? -1 : mystack.top(); } mystack.push(nums[i]); } return result; } }; ================================================ FILE: cpp/501-510/Perfect Number.cpp ================================================ class Solution { public: bool checkPerfectNumber(int num) { if (num <= 1) { return false; } int sum = 1; for (int i = 2; i * i <= num; i++) { if (num % i == 0) { sum += i; if (i * i != num) { sum += num / i; } } } return sum == num; } }; ================================================ FILE: cpp/501-510/Relative Ranks.cpp ================================================ class Solution { public: vector findRelativeRanks(vector& nums) { priority_queue > pq; for(int i=0;i res(nums.size(),""); int count = 1; for(int i=0; i>& maze, int i, int j) { int N1 = maze.size(); int N2 = maze[0].size(); if (i < 0 || j < 0 || i >= N1 || j >= N2) return 1; return maze[i][j]; } public: int shortestDistance(vector>& maze, vector& start, vector& destination) { queue> myqueue; map, int> distance; myqueue.push({start[0], start[1]}); distance[{start[0], start[1]}] = 0; pair directions[4] = {{0,1},{0,-1},{1,0},{-1,0}}; while (!myqueue.empty()) { pair pos = myqueue.front(); myqueue.pop(); for (int i = 0;i < 4;i++) { int nx = pos.first; int ny = pos.second; int step = 0; while (!isStone(maze, nx, ny)) { nx += directions[i].first; ny += directions[i].second; step++; } nx -= directions[i].first; ny -= directions[i].second; step--; pair n_pos{nx, ny}; if (distance.count(n_pos) == 0 || distance[pos] + step < distance[n_pos]) { myqueue.push(n_pos); distance[n_pos] = distance[pos] + step; } } } return distance[{destination[0], destination[1]}] == 0 ? -1 : distance[{destination[0], destination[1]}]; } }; ================================================ FILE: cpp/511-520/Coin Change 2.cpp ================================================ class Solution { public: int change(int amount, vector& coins) { if (amount == 0) return 1; if (coins.empty()) return 0; vector dp(amount + 1 , 0); dp[0] = 1; for (int val : coins) { for (int i = val; i <= amount; i++) { dp[i] += (dp[i - val]); } } return dp[amount]; } }; ================================================ FILE: cpp/511-520/Detect Capital.cpp ================================================ class Solution { public: bool detectCapitalUse(string word) { bool isUpper = isupper(word[0]); if (isUpper) { isUpper = isupper(word[1]); for (int i = 2; i < word.length(); i++) { if (islower(word[i])) { if (isUpper) return false; } else { if (!isUpper) return false; } } } else { for (int i = 1; i < word.length(); i++) { if (!islower(word[i])) { return false; } } } return true; } }; ================================================ FILE: cpp/511-520/Find Bottom Left Tree Value.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int findBottomLeftValue(TreeNode* root) { queue q; q.push(root); q.push(nullptr); int ans = root->val; while (!q.empty()) { TreeNode* t = q.front(); q.pop(); if (t == nullptr) { if (!q.empty()) { ans = q.front()->val; q.push(nullptr); } } else { if (t->left) q.push(t->left); if (t->right) q.push(t->right); } } return ans; } }; ================================================ FILE: cpp/511-520/Find Largest Value in Each Tree Row.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector largestValues(TreeNode* root) { queue q; q.push(root); q.push(nullptr); vector ans; if (!root) return ans; int current = INT_MIN; while (!q.empty()) { TreeNode* t = q.front(); q.pop(); if (t == nullptr) { ans.push_back(current); current = INT_MIN; if (!q.empty()) { q.push(nullptr); } } else { current = max(current, t->val); if (t->left) q.push(t->left); if (t->right) q.push(t->right); } } return ans; } }; ================================================ FILE: cpp/511-520/Freedom Trail.cpp ================================================ class Solution { int dfs(const string& ring, const string& key, int index, map& mymap){ if (index == key.length()) { return 0; } string hashKey = ring + to_string(index); if (mymap.find(hashKey) != mymap.end()) return mymap[hashKey]; int minSteps = INT_MAX; for (int i = 0; i < ring.length(); i ++) { if (ring[i] == key[index]){ string s = ring.substr(i, ring.length()) + ring.substr(0, i); int steps = 1 + min(i, (int)ring.length() - i); steps += dfs(s, key, index + 1, mymap); minSteps = min(minSteps, steps); } } return mymap[hashKey] = minSteps; } public: int findRotateSteps(string ring, string key) { map mymap; return dfs(ring, key, 0, mymap); } }; ================================================ FILE: cpp/511-520/Longest Palindromic Subsequence.cpp ================================================ class Solution { public: int longestPalindromeSubseq(string s) { int n = s.length(); vector> dp(n, vector(n, 0)); for (int step = 0; step < n; step++) { for (int i = 0; i + step < n; i++) { int j = i + step; if (i == j) dp[i][j] = 1; else if (i+1 == j) dp[i][j] = ( s[i] == s[j] ? 2 : 1); else { if (s[i] == s[j]) { dp[i][j] = 2 + dp[i+1][j-1]; } else { dp[i][j] = max(dp[i+1][j], dp[i][j-1]); } } } } return dp[0][n-1]; } }; ================================================ FILE: cpp/511-520/Super Washing Machines.cpp ================================================ class Solution { public: int findMinMoves(vector& machines) { int n = machines.size(); int sum = accumulate(machines.begin(), machines.end(), 0); if (sum % n != 0) return -1; int avg = sum / n; int ans = 0; int peak = 0; for (int machine : machines) { peak = peak + machine - avg; ans = max(ans, abs(peak)); ans = max(ans, machine - avg); } return ans; } }; ================================================ FILE: cpp/521-530/Beautiful Arrangement.cpp ================================================ class Solution { public: int countArrangement(int N) { vector vs; for (int i=0; i& vs) { if (n <= 0) return 1; int ans = 0; for (int i=0; i& nums) { if (nums.empty()) return 0; int n = nums.size(); vector dp(n, 0); map mymap; mymap[0] = -1; int result = 0; for (int i = 0; i < nums.size(); i++) { if (i == 0) dp[0] = get(nums[i]); else dp[i] = dp[i - 1] + get(nums[i]); auto itt = mymap.find(dp[i]); if (itt != mymap.end()) { result = max(result, i - itt->second); } else { mymap[dp[i]] = i; } } return result; } }; ================================================ FILE: cpp/521-530/Continuous Subarray Sum.cpp ================================================ class Solution { public: bool checkSubarraySum(vector& nums, int k) { if (nums.size() < 2) return false; long K = abs(long(k)); map record; record[0] = -1; for (int i = 1; i < nums.size(); i++) { if (nums[i-1] + nums[i] == 0) { return true; } } int sum = 0; for (int i = 0; i < nums.size(); i++) { int e = nums[i]; sum += e; if (sum == 0 && e != 0) return true; if (k == 0) continue; // Make it a positive number to avoid bad mod. if (sum < 0) sum += (-1*sum / K) * K + K; int target = sum % K; // You can also remove following line. sum = target; if (record.count(target) > 0) { if (i - record[target] > 1) return true; } else { record[target] = i; } } return false; } }; ================================================ FILE: cpp/521-530/Longest Uncommon Subsequence I.cpp ================================================ class Solution { public: int findLUSlength(string a, string b) { if (a.length() > b.length()) return a.length(); if (b.length() > a.length()) return b.length(); if (a == b) return -1; return a.length(); } }; ================================================ FILE: cpp/521-530/Longest Uncommon Subsequence II.cpp ================================================ class Solution { bool isS1subsOfS2(const string &s1, const string &s2){ if (s1.length() >= s2.length()) return false; int j = 0, i = 0; for(; i < s1.size(); ++i){ while(j < s2.size() && s1[i] != s2[j]) ++j; if(j == s2.size()) return false; ++j; } return true; } public: int findLUSlength(vector& strs) { unordered_map m; for(const string& str : strs) ++m[str]; vector> v; for(const auto &e : m) v.push_back(e); auto cmp = [](const pair &a, const pair &b) { return a.first.size() > b.first.size(); }; sort(v.begin(), v.end(), cmp); for (int i = 0; i < v.size(); ++i) { if(v[i].second == 1) { int j = 0; for(; j < i; ++j) if(isS1subsOfS2(v[i].first, v[j].first)) break; if(j == i) return v[i].first.size(); } } return -1; } }; ================================================ FILE: cpp/521-530/Longest Word in Dictionary through Deleting.cpp ================================================ class Solution { public: string findLongestWord(string s, vector& d) { string ans; for (int i = 0; i < d.size(); i++) { int pi = 0, pj = 0; for (; pi < s.size() && pj < d[i].size(); pi++) { pj += s[pi] == d[i][pj]; } if (pj == d[i].size() && (ans.size() < d[i].size() || (ans.size() == d[i].size() && ans > d[i]))) ans = d[i]; } return ans; } }; ================================================ FILE: cpp/521-530/Minimum Distance Between BST Nodes.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { void dfs(TreeNode* root, int &pv, int& result) { if (!root) return; dfs(root->left, pv, result); if (pv != INT_MIN) result = min(result, abs(pv - root->val)); pv = root->val; dfs(root->right, pv, result); } public: int getMinimumDifference(TreeNode* root) { int pv = INT_MIN; int result = INT_MAX; dfs(root, pv, result); return result; } }; ================================================ FILE: cpp/521-530/Word Abbreviation.cpp ================================================ class Solution { public: vector wordsAbbreviation(vector& dict) { int n = dict.size(); vector abbres; vector lens(n, 1); for (const string& word : dict) { abbres.push_back(abbreviate(word, 1)); } for (int i = 0; i < n; i++) { bool unique = false; while (!unique) { string abbre = abbres[i]; unique = true; for(int j = i + 1; j < n; j++) { if(abbre == abbres[j]) { abbres[j] = abbreviate(dict[j], lens[j]+1); lens[j]++; unique = false; } } if(unique == false) { abbres[i] = abbreviate(dict[i], lens[i]+1); lens[i]++; } } } return abbres; } string abbreviate(const string& s, int len) { int num = s.length() - len - 1; if (num <= 1) return s; return s.substr(0, len) + to_string(num) + s.back(); } }; ================================================ FILE: cpp/531-540/Complex Number Multiplication.cpp ================================================ class Solution { public: string complexNumberMultiply(string a, string b) { int ra, ia, rb, ib; char buff; stringstream aa(a), bb(b), ans; aa >> ra >> buff >> ia >> buff; bb >> rb >> buff >> ib >> buff; ans << ra*rb - ia*ib << "+" << ra*ib + rb*ia << "i"; return ans.str(); } }; ================================================ FILE: cpp/531-540/Convert BST to Greater Tree.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { void dfs(TreeNode* root, int& sum) { if (!root) return; dfs(root->right, sum); sum += root->val; root->val = sum; dfs(root->left, sum); } public: TreeNode* convertBST(TreeNode* root) { int sum = 0; dfs(root, sum); return root; } }; ================================================ FILE: cpp/531-540/Encode and Decode TinyURL.cpp ================================================ class Solution { int count = 0; unordered_map mymap; public: // Encodes a URL to a shortened URL. string encode(string longUrl) { string short_url = "http://tinyurl.com/" + to_string(count); mymap[count] = longUrl; count++; return short_url; } // Decodes a shortened URL to its original URL. string decode(string shortUrl) { string num = shortUrl.substr(19); return mymap[stoi(num)]; } }; // Your Solution object will be instantiated and called as such: // Solution solution; // solution.decode(solution.encode(url)); ================================================ FILE: cpp/531-540/Lonely Pixel I.cpp ================================================ class Solution { public: int findLonelyPixel(vector>& picture) { int ans = 0; map col, row; for (int i = 0; i < picture.size(); i++) { for (int j = 0; j < picture[0].size(); j++) { if (picture[i][j] == 'B') { row[i]++; col[j]++; } } } for (int i = 0; i < picture.size(); i++) { for (int j = 0; j < picture[0].size(); j++) { if (picture[i][j] == 'B' && row[i] == 1 && col[j] == 1) { ans++; } } } return ans; } }; ================================================ FILE: cpp/531-540/Lonely Pixel II.cpp ================================================ class Solution { public: int findBlackPixel(vector>& picture, int N) { map row, col; map rowSig; for (int i = 0; i < picture.size(); i++) { string signature; for (int j = 0; j < picture[0].size(); j++) { signature = signature + picture[i][j]; if (picture[i][j] == 'B') { row[i]++; col[j]++; } } rowSig[i] = signature; } int ans = 0; set processed; for (int i = 0; i < picture.size(); i++) { for (int j = 0; j < picture[0].size(); j++) { if (picture[i][j] == 'B') { if (row[i] != col[j]) continue; if (row[i] != N) continue; if (processed.count(j) > 0) continue; string signature = rowSig[i]; bool flag = true; for (int k = 0; k < picture.size(); k++) { if (picture[k][j] == 'B' && signature != rowSig[k]) { flag = false; } } if (flag) ans += N; processed.insert(j); } } } return ans; } }; ================================================ FILE: cpp/531-540/Single Element in a Sorted Array.cpp ================================================ class Solution { public: int singleNonDuplicate(vector& nums) { int n = nums.size(), left = 0, right = n - 1; while (left < right) { int mid = left + (right - left) / 2; if (mid % 2 == 0) { if (nums[mid] == nums[mid-1]) right = mid - 2; else if (nums[mid] == nums[mid+1]) left = mid + 2; else return nums[mid]; } else { if (nums[mid] == nums[mid-1]) left = mid + 1; else if (nums[mid] == nums[mid+1]) right = mid - 1; } } return nums[left]; } }; ================================================ FILE: cpp/541-550/01 Matrix.cpp ================================================ class Solution { struct point { int i; int j; int d; point (int _i, int _j, int _d): i(_i), j(_j), d(_d) { } }; public: vector> updateMatrix(vector>& matrix) { int row = matrix.size(); int column = matrix[0].size(); vector> result(row, vector(column, -1)); queue myqueue; vector> pos{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { if (matrix[i][j] == 0) { result[i][j] = 0; myqueue.emplace(point(i, j, 0)); } } } while (!myqueue.empty()) { point current = myqueue.front(); myqueue.pop(); for (const auto& e : pos) { int nexti = current.i + e.first; int nextj = current.j + e.second; if (nexti < 0 || nexti >= row || nextj < 0 || nextj >= column) continue; if (result[nexti][nextj] < 0) { if (result[nexti][nextj] < 0) { result[nexti][nextj] = current.d + 1; myqueue.push(point(nexti, nextj, current.d + 1)); } } } } return result; } }; ================================================ FILE: cpp/541-550/Binary Tree Longest Consecutive Sequence II.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int longestConsecutive(TreeNode* root) { int longest = 0; dfs(root, root, longest); return longest; } pair dfs(TreeNode * node, TreeNode * parent, int & longest) { if (node == nullptr) { return make_pair(0, 0); } auto left = dfs(node->left, node, longest); auto right = dfs(node->right, node, longest); longest = max(longest, left.first + right.second + 1); longest = max(longest, left.second + right.first + 1); int inc = 0, dec = 0; if ( node->val == parent->val + 1 ) { inc = max(left.first, right.first) + 1; } if ( node->val == parent->val - 1 ) { dec = max(left.second, right.second) + 1; } return make_pair(inc, dec); } }; ================================================ FILE: cpp/541-550/Boundary of Binary Tree.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { void leftBoundary(TreeNode* root, vector& nodes) { if(root == nullptr || (root->left == nullptr && root->right == nullptr)) return; nodes.push_back(root->val); if(root->left == nullptr) leftBoundary(root->right, nodes); else leftBoundary(root->left, nodes); } void rightBoundary(TreeNode* root, vector& nodes) { if(root == nullptr || (root->left == nullptr && root->right == nullptr)) return; if(root->right == nullptr) rightBoundary(root->left, nodes); else rightBoundary(root->right, nodes); nodes.push_back(root->val); // add after child visit(reverse) } void leaves(TreeNode* root, vector& nodes) { if(root == nullptr) return; if(root->left == nullptr && root->right == nullptr) { nodes.push_back(root->val); return; } leaves(root->left, nodes); leaves(root->right, nodes); } public: vector boundaryOfBinaryTree(TreeNode* root) { vector nodes; if (root == nullptr) return nodes; nodes.push_back(root->val); leftBoundary(root->left, nodes); leaves(root->left, nodes); leaves(root->right, nodes); rightBoundary(root->right, nodes); return nodes; } }; ================================================ FILE: cpp/541-550/Diameter of Binary Tree.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { int dfs(TreeNode* root, int& ans) { if (!root) return 0; int leftD = dfs(root->left, ans); int rightD = dfs(root->right, ans); ans = max(ans, 1 + leftD + rightD); return max(leftD, rightD) + 1; } public: int diameterOfBinaryTree(TreeNode* root) { if (!root) return 0; int ans = 0; dfs(root, ans); return ans - 1; } }; ================================================ FILE: cpp/541-550/Friend Circles.cpp ================================================ class Solution { public: void dfs(int i, vector>& M, vector& colors) { colors[i] = 1; int m = M.size(); for (int j = 0; j < m; j++) { if (M[i][j] == 0) continue; if (colors[j] == 0) { dfs(j, M, colors); } } } int findCircleNum(vector>& M) { int m = M.size(); if (m == 0) return 0; int res = 0; vector colors(m, 0); for (int i = 0; i < m; i++) { if (colors[i] == 0) { res++; dfs(i, M, colors); } } return res; } }; ================================================ FILE: cpp/541-550/Output Contest Matches.cpp ================================================ class Solution { public: string findContestMatch(int n) { vector m(n); for (int i = 0; i < n; i++) { m[i] = to_string(i + 1); } while (n > 1) { for (int i = 0; i < n / 2; i++) { m[i] = "(" + m[i] + "," + m[n - 1 - i] + ")"; } n /= 2; } return m[0]; } }; ================================================ FILE: cpp/541-550/Reverse String II.cpp ================================================ class Solution { void _reverse(string &str, int i, int j) { while (i < j) swap(str[i++], str[j--]); } public: string reverseStr(string s, int k) { int i = 0; while (true) { if (i >= s.length()) break; int start = i; int end = min(i + 2*k, (int)s.length()) - 1; _reverse(s, start, min(end, start + k - 1) ); i = end + 1; } return s; } }; ================================================ FILE: cpp/541-550/Split Array with Equal Sum.cpp ================================================ class Solution { public: bool splitArray(vector& nums) { if (nums.size() < 7) return false; vector sum(nums.size(), 0); sum[0] = nums[0]; for (int i = 1; i < nums.size(); i++) { sum[i] = sum[i - 1] + nums[i]; } for (int j = 3; j < nums.size() - 3; j++) { unordered_set candidate; for (int i = 1; i < j - 1; i++) { if (sum[i - 1] == sum[j - 1] - sum[i]) candidate.insert(sum[i - 1]); } for (int k = j + 2; k < nums.size() - 1; k++) { if (sum[nums.size() - 1] - sum[k] == sum[k - 1] - sum[j] && candidate.count(sum[k - 1] - sum[j]) > 0) return true; } } return false; } }; ================================================ FILE: cpp/551-560/Brick Wall.cpp ================================================ class Solution { public: int leastBricks(vector>& wall) { map mymap; // pos -> count int maxCount = 0; for (const vector& wal : wall) { int sum = 0; for (int i = 0; i < wal.size() - 1; i++) { sum += wal[i]; mymap[sum]++; maxCount = max(maxCount, mymap[sum]); } } return wall.size() - maxCount; } }; ================================================ FILE: cpp/551-560/Next Greater Element III.cpp ================================================ class Solution { void nextPermutation(vector &num) { if (num.empty()) return; // in reverse order, find the first number which is in increasing trend (we call it violated number here) int i(0); for (i = num.size()-2; i >= 0; --i) if (num[i] < num[i+1]) break; // reverse all the numbers after violated number reverse(begin(num)+i+1, end(num)); // if violated number not found, because we have reversed the whole array, then we are done! if (i == -1) return; // else binary search find the first number larger than the violated number auto itr = upper_bound(num.begin()+i+1, num.end(), num[i]); // swap them, done! swap(num[i], *itr); } public: int nextGreaterElement(int n) { vector myvec; int nn = n; while (nn > 0) { int digit = nn % 10; nn /= 10; myvec.emplace(myvec.begin(), digit); } nextPermutation(myvec); int ans = 0; for (int e : myvec) { ans = 10 * ans + e; } if (ans > n) return ans; return -1; } }; ================================================ FILE: cpp/551-560/Optimal Division.cpp ================================================ class Solution { public: string optimalDivision(vector& nums) { string result = to_string(nums[0]); if (nums.size() == 1) return result; if (nums.size() == 2) return result + "/" + to_string(nums[1]); result = result + "/(" + to_string(nums[1]); for (int i = 2; i < nums.size(); i++) { result = result + "/" + to_string(nums[i]); } return result + ")"; } }; ================================================ FILE: cpp/551-560/Reverse Words in a String III.cpp ================================================ class Solution { public: string reverseWords(string s) { size_t front = 0; for(int i = 0; i <= s.length(); ++i){ if(i == s.length() || s[i] == ' '){ reverse(&s[front], &s[i]); front = i + 1; } } return s; } }; ================================================ FILE: cpp/551-560/Split Concatenated Strings.cpp ================================================ class Solution { public: string splitLoopedString(vector& strs) { for (string& str: strs) { string copyStr(str); reverse(copyStr.begin(), copyStr.end()); if (copyStr > str) str = copyStr; } string ans; for (int i = 0; i < strs.size(); i++) { string str = strs[i]; string before, after; for (int k = 0; k < i; k++) before += strs[k]; for (int k = i+1; k < strs.size(); k++) after += strs[k]; for (int k = 0; k < str.length(); k++) { string strPrev = str.substr(0, k); string strNext = str.substr(k); string finalStr = strNext + after + before + strPrev; if (finalStr > ans) ans = finalStr; } reverse(str.begin(), str.end()); for (int k = 0; k < str.length(); k++) { string strPrev = str.substr(0, k); string strNext = str.substr(k); string finalStr = strNext + after + before + strPrev; if (finalStr > ans) ans = finalStr; } } return ans; } }; ================================================ FILE: cpp/551-560/Student Attendance Record I.cpp ================================================ class Solution { public: bool checkRecord(string s) { int n = s.length(); int A = 0; for (int i = 0; i < n; i++) { char ch = s[i]; if (ch == 'A') A++; if (ch == 'L' && (i+1 < n && s[i+1] == 'L') && (i+2& nums, int k) { unordered_map prefix_sum; prefix_sum[0] = 1; int sum = 0; int ans = 0; for (int num : nums) { sum += num; int target = sum - k; ans += prefix_sum[target]; prefix_sum[sum]++; } return ans; } }; ================================================ FILE: cpp/561-570/Array Nesting.cpp ================================================ class Solution { public: int arrayNesting(vector& nums) { vector visited(nums.size(), false); int result = 0; for (int i = 0; i < nums.size(); i++) { if (visited[i]) continue; int count = 0; int j = i; while (!visited[j]) { visited[j] = true; j = nums[j]; count++; } result = max(result, count); } return result; } }; ================================================ FILE: cpp/561-570/Array Partition I.cpp ================================================ class Solution { public: int arrayPairSum(vector& nums) { int sum = 0; sort(nums.begin(), nums.end()); for (int i = 0; i < nums.size(); i++) { if (i % 2 == 0) { sum += nums[i]; } } return sum; } }; ================================================ FILE: cpp/561-570/Binary Tree Tilt.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { int dfs(TreeNode* root, int &result) { if (!root) return 0; int left = dfs(root->left, result); int right = dfs(root->right, result); result += abs(left - right); return left + right + root->val; } public: int findTilt(TreeNode* root) { int result = 0; dfs(root, result); return result; } }; ================================================ FILE: cpp/561-570/Longest Line of Consecutive One in Matrix.cpp ================================================ class Solution { public: int longestLine(vector>& M) { if (M.size() == 0) return 0; int ones = 0; vector>> dp = vector>>(M.size(), vector>(M[0].size(), vector(4,0))); for (int i = 0; i < M.size(); i++) { for (int j = 0; j < M[0].size(); j++) { if (M[i][j] == 1) { dp[i][j][0] = j > 0 ? dp[i][j - 1][0] + 1 : 1; dp[i][j][1] = i > 0 ? dp[i - 1][j][1] + 1 : 1; dp[i][j][2] = (i > 0 && j > 0) ? dp[i - 1][j - 1][2] + 1 : 1; dp[i][j][3] = (i > 0 && j < M[0].size() - 1) ? dp[i - 1][j + 1][3]+1 : 1; ones = max(ones, max(max(dp[i][j][0], dp[i][j][1]), max(dp[i][j][2], dp[i][j][3]))); } } } return ones; } }; ================================================ FILE: cpp/561-570/Maximum Vacation Days.cpp ================================================ class Solution { public: int maxVacationDays(vector>& flights, vector>& days) { int n = days.size(), k = days[0].size(); // n city , k weeks vector> dp(n, vector(k, -1)); // dp[i][j] - max days play if you spent week j in city i; return dfs(0, 0, dp, flights, days); } int dfs(int city, int week, vector>& dp, const vector>& flights, const vector>& days) { int n = days.size(), k = days[0].size(); // n city , k weeks if (week >= k) return 0; if (dp[city][week] >= 0) return dp[city][week]; int max_days = 0; for (int i = 0; i < n; i++) { if (flights[city][i] == 1 || city == i) { max_days = max(dfs(i, week+1, dp, flights, days) + days[i][week], max_days); } } return dp[city][week] = max_days; } }; ================================================ FILE: cpp/561-570/Permutation in String.cpp ================================================ class Solution { public: bool checkInclusion(string s1, string s2) { if (s1.length() > s2.length()) return false; vector mymap(256, 0); vector stats(256, 0); int count = s1.length(); for (char ch : s1) { mymap[ch]++; } for (int i = 0; i < s1.length(); i++) { char ch = s2[i]; if(mymap[ch] > 0) { stats[ch]++; if (stats[ch] <= mymap[ch]) { count--; } } } if (count == 0) return true; for (int i = s1.length(); i < s2.length(); i++) { char oldChar = s2[i - s1.length()]; char newChar = s2[i]; if (oldChar == newChar) continue; if (mymap[oldChar] > 0) { stats[oldChar]--; if (stats[oldChar] < mymap[oldChar] && stats[oldChar] >= 0) { count++; } } if (mymap[newChar] > 0) { stats[newChar]++; if (stats[newChar] <= mymap[newChar] && stats[newChar] >= 0) { count--; } } if (count == 0) return true; } return false; } }; ================================================ FILE: cpp/561-570/Reshape the Matrix.cpp ================================================ class Solution { public: vector> matrixReshape(vector>& nums, int r, int c) { int m = nums.size(), n = nums[0].size(); if (r * c != m * n) return nums; vector> reshaped(r, vector(c, 0)); for (int i = 0; i < r * c; i++) reshaped[i/c][i%c] = nums[i/n][i%n]; return reshaped; } }; ================================================ FILE: cpp/571-580/Distribute Candies.cpp ================================================ class Solution { public: int distributeCandies(vector& candies) { int n = candies.size(); set myset; for (int e : candies) { myset.insert(e); } if (myset.size() >= n / 2) { return n/2; } else { return myset.size(); } } }; ================================================ FILE: cpp/571-580/Out of Boundary Paths.cpp ================================================ class Solution { bool inBox(int i, int j, int m, int n) { if (i < 0 || j < 0 || i >= m || j >= n) return false; return true; } long get(int i, int j, int k, vector>>& dp, int m, int n) { if (!inBox(j, k, m, n)) return 0; return dp[i][j][k]; } int coeff(int i, int j, int m, int n) { int coe = 0; if (!inBox(i, j - 1, m, n)) coe++; if (!inBox(i, j + 1, m, n)) coe++; if (!inBox(i - 1, j, m, n)) coe++; if (!inBox(i + 1, j, m, n)) coe++; return coe; } public: int findPaths(int m, int n, int N, int i, int j) { if (N == 0) return 0; vector>> dp(N + 1, vector>(m, vector(n, 0))); dp[0][i][j] = 1; long result = 1 * coeff(i, j, m, n); for (int i = 1; i < N; i++) { for (int j = 0; j < m; j++) { for (int k = 0; k < n; k++) { dp[i][j][k] = (get(i - 1, j - 1, k, dp , m, n) + get(i - 1, j + 1, k, dp , m, n) + get(i - 1, j, k - 1, dp , m, n) + get(i - 1, j, k + 1, dp , m, n)) % 1000000007; result += coeff(j, k, m, n) * dp[i][j][k]; result %= 1000000007; } } } return result; } }; ================================================ FILE: cpp/571-580/Squirrel Simulation.cpp ================================================ class Solution { public: int minDistance(int height, int width, vector& tree, vector& squirrel, vector>& nuts) { int sum = 0; int save = INT_MAX; for (const auto& nut : nuts) { int d = dis(tree[0], nut[0], tree[1], nut[1]); sum += d*2; int d2 = dis(squirrel[0], nut[0], squirrel[1], nut[1]); save = min(save, d2 - d); } return sum + save; } int dis(int a1, int b1, int a2, int b2) { return abs(a1 - b1) + abs(a2 - b2); } }; ================================================ FILE: cpp/571-580/Subtree of Another Tree.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { // Encodes a tree to a single string. string serialize(TreeNode* root) { if (root == nullptr) return "# "; else return to_string(root->val) + " " + serialize(root->left) + serialize(root->right); } string serialize2(TreeNode* root, const string& target, bool &b) { if (root == nullptr) return "# "; string res = to_string(root->val) + " " + serialize2(root->left, target, b) + serialize2(root->right, target, b); if (res == target) b = true; return res; } public: bool isSubtree(TreeNode* s, TreeNode* t) { string tstr = serialize(t); bool res = false; serialize2(s, tstr, res); return res; } }; ================================================ FILE: cpp/581-590/Delete Operation for Two Strings.cpp ================================================ class Solution { int lcs(const string& X, const string& Y) { int m = X.size(); int n = Y.size(); vector> dp(m+1, vector(n+1, 0)); for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) dp[i][j] = 0; else if (X[i-1] == Y[j-1]) dp[i][j] = dp[i-1][j-1] + 1; else dp[i][j] = max(dp[i-1][j], dp[i][j-1]); } } return dp[m][n]; } public: int minDistance(string word1, string word2) { int len = lcs(word1, word2); return word1.size() + word2.size() - 2 * len; } }; ================================================ FILE: cpp/581-590/Design In-Memory File System.cpp ================================================ class FileSystem { private: struct TrieNode { bool isFile; string content; unordered_map children; TrieNode() : isFile(false) {} }; TrieNode *root; vector getPaths(const string &path) { vector elems; stringstream ss(path); string item; while (std::getline(ss, item, '/')) { if (!item.empty()) { elems.push_back(item); } } return elems; } public: FileSystem() { root = new TrieNode(); } vector ls(string path) { vector paths = getPaths(path); TrieNode *curr = root; for (const string &path : paths) curr = curr->children[path]; if (curr->isFile) return {paths.back()}; vector ans; for (auto &p : curr->children) ans.push_back(p.first); sort(ans.begin(), ans.end()); return ans; } void mkdir(string path) { vector paths = getPaths(path); TrieNode *curr = root; for (const string &path : paths) { if (!curr->children.count(path)) curr->children[path] = new TrieNode(); curr = curr->children[path]; } } void addContentToFile(string filePath, string content) { vector paths = getPaths(filePath); TrieNode *curr = root; for (const string &path : paths) { if (!curr->children.count(path)) curr->children[path] = new TrieNode(); curr = curr->children[path]; } curr->isFile = true; curr->content += content; } string readContentFromFile(string filePath) { vector paths = getPaths(filePath); TrieNode *curr = root; for (const string &path : paths) curr = curr->children[path]; return curr->content; } }; ================================================ FILE: cpp/581-590/Erect the Fence.cpp ================================================ /** * Definition for a point. * struct Point { * int x; * int y; * Point() : x(0), y(0) {} * Point(int a, int b) : x(a), y(b) {} * }; */ // Ref: http://www.algorithmist.com/index.php/Monotone_Chain_Convex_Hull.cpp class Solution { public: typedef int coord_t; // coordinate type typedef long long coord2_t; // must be big enough to hold 2*max(|coordinate|)^2 // 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross // product. Returns a positive value, if OAB makes a counter-clockwise turn, // negative for clockwise turn, and zero if the points are collinear. coord2_t cross(const Point &O, const Point &A, const Point &B) { return (A.x - O.x) * (coord2_t)(B.y - O.y) - (A.y - O.y) * (coord2_t)(B.x - O.x); } static bool cmp(Point &p1, Point &p2) { return p1.x < p2.x || (p1.x == p2.x && p1.y < p2.y); } static bool equ(Point &p1, Point &p2) { return p1.x == p2.x && p1.y == p2.y; } // Returns a list of points on the convex hull in counter-clockwise order. // Note: the last point in the returned list is the same as the first one. vector outerTrees(vector &P) { int n = P.size(), k = 0; vector H(2 * n); // Sort points lexicographically sort(P.begin(), P.end(), cmp); // Build lower hull for (int i = 0; i < n; i++) { while (k >= 2 && cross(H[k - 2], H[k - 1], P[i]) < 0) k--; H[k++] = P[i]; } // Build upper hull for (int i = n - 2, t = k + 1; i >= 0; i--) { while (k >= t && cross(H[k - 2], H[k - 1], P[i]) < 0) k--; H[k++] = P[i]; } // Remove duplicates H.resize(k); sort(H.begin(), H.end(), cmp); H.erase(unique(H.begin(), H.end(), equ), H.end()); return H; } }; ================================================ FILE: cpp/581-590/Kill Process.cpp ================================================ class Solution { public: vector killProcess(vector& pid, vector& ppid, int kill) { map> ppids; for (int i = 0; i < pid.size(); i++) { ppids[ppid[i]].push_back(pid[i]); } vector results; queue myqueue; myqueue.push(kill); while (!myqueue.empty()) { int id = myqueue.front(); myqueue.pop(); results.push_back(id); if (ppids.count(id) > 0) { vector ids = ppids[id]; for (int e : ids) myqueue.push(e); } } return results; } }; ================================================ FILE: cpp/581-590/Shortest Unsorted Continuous Subarray.cpp ================================================ class Solution { public: int findUnsortedSubarray(vector& nums) { int minimum = INT_MAX; int lastBadIndex = -1; for (int i = nums.size() - 1; i >= 0; i--) { minimum = min(minimum, nums[i]); if (minimum != nums[i]) lastBadIndex = i; } int maximum = INT_MIN; int lastBadIndex2 = -1; for (int i = 0; i < nums.size(); i++) { maximum = max(maximum, nums[i]); if (maximum != nums[i]) lastBadIndex2 = i; } if (lastBadIndex2 <= lastBadIndex) return 0; return lastBadIndex2 - lastBadIndex + 1; } }; ================================================ FILE: cpp/591-600/Fraction Addition and Subtraction.cpp ================================================ // https://discuss.leetcode.com/topic/90061/small-and-simple-c-and-java/2 class Solution { public: string fractionAddition(string expression) { istringstream in(expression); int A = 0, B = 1, a, b; char _; while (in >> a >> _ >> b) { A = A * b + a * B; B *= b; int g = abs(__gcd(A, B)); A /= g; B /= g; } return to_string(A) + '/' + to_string(B); } }; ================================================ FILE: cpp/591-600/Longest Harmonious Subsequence.cpp ================================================ class Solution { public: int findLHS(vector& nums) { map mymap; for (int num : nums) { mymap[num]++; } int result = 0; for (auto it : mymap) { if (mymap.count(it.first+1)) { result = max(result, mymap[it.first + 1] + mymap[it.first]); } } return result; } }; ================================================ FILE: cpp/591-600/Minimum Index Sum of Two Lists.cpp ================================================ class Solution { public: vector findRestaurant(vector& list1, vector& list2) { map mymap; for (int i = 0; i < list1.size(); i++) { mymap[list1[i]] = i; } vector result; int minSum = INT_MAX; for (int i = 0; i < list2.size(); i++) { auto it = mymap.find(list2[i]); if (it == mymap.end()) continue; int idx = it->second + i; if (idx == minSum) { result.push_back(list2[i]); } if (idx < minSum) { minSum = idx; result.clear(); result.push_back(list2[i]); } } return result; } }; ================================================ FILE: cpp/591-600/Non-negative Integers without Consecutive Ones.cpp ================================================ class Solution { int help(int num, int highestPos) { // 110010 -> 001111 if ( (num >> (highestPos-2)) % 2 == 1) { int mask = 0; for (int i = 0; i < (highestPos - 2); i++) { mask = mask*2+1; } return mask; } else { // 1010 -> 0010 int mask = 1 << (highestPos-1); return num ^ mask; } } public: int findIntegers(int num) { if (num == 0) return 1; if (num == 1) return 2; if (num == 2 || num == 3) return 3; int dp[33] = {0}; dp[0] = dp[1] = dp[2] = 1; int sum = 3; int highestPos = 0; int temp = num; while (temp > 0) { highestPos++; temp = temp >> 1; } for (int i = 3; i < highestPos; i++) { dp[i] = dp[i-2] + dp[i-1]; sum += dp[i]; } int remain = help(num, highestPos); return sum + findIntegers(remain); } }; ================================================ FILE: cpp/591-600/Range Addition II.cpp ================================================ class Solution { public: int maxCount(int m, int n, vector>& ops) { int a = m, b = n; for (const vector& op : ops) { a = min(a, op[0]); b = min(b, op[1]); } return a*b; } }; ================================================ FILE: cpp/591-600/Tag Validator.cpp ================================================ class Solution { public: bool isValid(string code) { stack stk; for (int i = 0; i < code.length(); i++) { if (i > 0 && stk.empty()) return false; if (code.substr(i, 9) == "", j); if (i < 0) return false; i += 2; } else if (code.substr(i, 2) == "', j); string s = code.substr(j, i - j); if (stk.empty() || s != stk.top()) return false; stk.pop(); } else if (code.substr(i, 1) == "<") { int j = i + 1; i = code.find('>', j); if (i < 0 || i == j || i - j > 9) return false; for (int k = j; k < i; k++) { if (!isupper(code[k])) return false; } string s = code.substr(j, i - j); stk.push(s); } } return stk.empty(); } }; ================================================ FILE: cpp/591-600/Valid Square.cpp ================================================ class Solution { int dSquare(vector& p1, vector& p2) { return (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]); } public: bool validSquare(vector& p1, vector& p2, vector& p3, vector& p4) { unordered_set s({ dSquare(p1, p2), dSquare(p1, p3), dSquare(p1, p4), dSquare(p2, p3), dSquare(p2, p4), dSquare(p3, p4) }); return !s.count(0) && s.size() == 2; } }; ================================================ FILE: cpp/601-610/Can Place Flowers.cpp ================================================ class Solution { public: bool canPlaceFlowers(vector& flowerbed, int n) { if (n <= 0) { return true; } flowerbed.insert(flowerbed.begin(), 0); flowerbed.push_back(0); for (int i = 1; i < flowerbed.size() - 1; ++i) { if (flowerbed[i-1] + flowerbed[i] + flowerbed[i+1] == 0) { --n; ++i; } if (n == 0) { return true; } } return false; } }; ================================================ FILE: cpp/601-610/Construct String from Binary Tree.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: string tree2str(TreeNode* t) { if (!t) return ""; string s = to_string(t->val); if (t->left) { s += "(" + tree2str(t->left) + ")"; } else if (t->right) { s += "()"; } if (t->right) { s += "(" + tree2str(t->right) + ")"; } return s; } }; ================================================ FILE: cpp/601-610/Design Compressed String Iterator.cpp ================================================ class StringIterator { string str; char current; int times; int index; public: StringIterator(string compressedString) { str = compressedString; times = 0; index = 0; } char next() { if (hasNext()) { times--; return current; } return ' '; } bool hasNext() { if (times > 0) return true; if (index >= str.length()) return false; current = str[index++]; int temp = 0; while (index < str.length() && isdigit(str[index])) { temp = 10 * temp + (str[index] - '0'); index++; } times = temp; return true; } }; /** * Your StringIterator object will be instantiated and called as such: * StringIterator obj = new StringIterator(compressedString); * char param_1 = obj.next(); * bool param_2 = obj.hasNext(); */ ================================================ FILE: cpp/601-610/Find Duplicate File in System.cpp ================================================ class Solution { public: vector> findDuplicate(vector& paths) { unordered_map> files; vector> result; for (const auto& path : paths) { stringstream ss(path); string root; string s; getline(ss, root, ' '); while (getline(ss, s, ' ')) { string fileName = root + '/' + s.substr(0, s.find('(')); string fileContent = s.substr(s.find('(') + 1, s.find(')') - s.find('(') - 1); files[fileContent].emplace_back(fileName); } } for (const auto& file : files) { if (file.second.size() > 1) result.emplace_back(file.second); } return result; } }; ================================================ FILE: cpp/611-620/Add Bold Tag in String.cpp ================================================ class Solution { public: string addBoldTag(string s, vector& dict) { vector> ranges = findpairs(s, dict); ranges = merge(ranges); for (auto it = ranges.rbegin(); it != ranges.rend(); it++) { s.insert(it->second, ""); s.insert(it->first, ""); } return s; } private: vector> findpairs(const string& s, const vector& dict) { vector> res; for (const string& w : dict) { int n = w.size(); for (int i = 0; (i = s.find(w, i)) != string::npos; i++) { res.emplace_back(make_pair(i, i + n)); } } return res; } vector> merge(vector>& a) { vector> r; auto cmp = [&](const pair& a, const pair& b) { return a.first < b.first || a.first == b.first && a.second < b.second; }; sort(a.begin(), a.end(), cmp); for (int i = 0, j = -1; i < a.size(); i++) { if (j < 0 || a[i].first > r[j].second) { r.push_back(a[i]); j++; } else { r[j].second = max(r[j].second, a[i].second); } } return r; } }; ================================================ FILE: cpp/611-620/Merge Two Binary Trees.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { if (t1 == nullptr && t2 == nullptr) return nullptr; TreeNode *root = new TreeNode(0); if (t1 != nullptr && t2 != nullptr) { root->val = t1->val + t2->val; root->left = mergeTrees(t1->left, t2->left); root->right = mergeTrees(t1->right, t2->right); } else if (t1 != nullptr) { root->val = t1->val; root->left = mergeTrees(t1->left, nullptr); root->right = mergeTrees(t1->right, nullptr); } else { root->val = t2->val; root->left = mergeTrees(nullptr, t2->left); root->right = mergeTrees(nullptr, t2->right); } return root; } }; ================================================ FILE: cpp/611-620/Valid Triangle Number.cpp ================================================ class Solution { public: int triangleNumber(vector& nums) { int n = nums.size(); int result = 0; sort(nums.begin(), nums.end()); for (int i = n - 1; i >= 0; i--) { int left = 0; int right = i - 1; while (left < right) { if ((nums[left] + nums[right]) > nums[i]) { result += (right - left); right--; } else { left++; } } } return result; } }; ================================================ FILE: cpp/621-630/Add One Row to Tree.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { void dfs(TreeNode* root, TreeNode* parent, int v, int d, bool left) { if (root == nullptr && d > 1) return; if (d == 1) { TreeNode* node = new TreeNode(v); if (left) { node->left = root; parent->left = node; } else { node->right = root; parent->right = node; } return; } dfs(root->left, root, v, d - 1, true); dfs(root->right, root, v, d - 1, false); } public: TreeNode* addOneRow(TreeNode* root, int v, int d) { if (d == 1) { TreeNode* newRoot = new TreeNode(v); newRoot->left = root; return newRoot; } dfs(root, nullptr, v, d, true); return root; } }; ================================================ FILE: cpp/621-630/Course Schedule III.cpp ================================================ class Solution { public: int scheduleCourse(vector>& courses) { auto cmp = [](const vector &a, const vector &b) { return a[0] < b[0] || (a[0] == b[0] && a[1] > b[1]); }; priority_queue, vector>, decltype(cmp)> pq(cmp); sort(begin(courses), end(courses), [](const vector &a, const vector &b) { return a[1] < b[1] || (a[1] == b[1] && a[0] < b[0]); }); int totalTime = 0; for (int i = 0; i < courses.size(); i++) { vector current = courses[i]; if (current[0] + totalTime <= current[1]) { totalTime += current[0]; pq.push(current); } else if (!pq.empty()) { vector mayDiscard = pq.top(); if (current[0] < mayDiscard[0]) { pq.pop(); pq.push(current); totalTime += (current[0] - mayDiscard[0]); } } } return pq.size(); } }; ================================================ FILE: cpp/621-630/Design Circular Queue.cpp ================================================ class MyCircularQueue { vector vec; int head; int tail; int size; int capacity; public: /** Initialize your data structure here. Set the size of the queue to be k. */ MyCircularQueue(int k) { vec.resize(k, 0); capacity = k; head = 0; tail = -1; size = 0; } /** Insert an element into the circular queue. Return true if the operation is successful. */ bool enQueue(int value) { if (size == capacity) return false; tail = (tail+1) % capacity; vec[tail] = value; size++; return true; } /** Delete an element from the circular queue. Return true if the operation is successful. */ bool deQueue() { if (size == 0) return false; head = (head+1) % capacity; size--; return true; } /** Get the front item from the queue. */ int Front() { if (size == 0) return -1; return vec[head]; } /** Get the last item from the queue. */ int Rear() { if (size == 0) return -1; return vec[tail]; } /** Checks whether the circular queue is empty or not. */ bool isEmpty() { return size == 0; } /** Checks whether the circular queue is full or not. */ bool isFull() { return size == capacity; } }; /** * Your MyCircularQueue object will be instantiated and called as such: * MyCircularQueue* obj = new MyCircularQueue(k); * bool param_1 = obj->enQueue(value); * bool param_2 = obj->deQueue(); * int param_3 = obj->Front(); * int param_4 = obj->Rear(); * bool param_5 = obj->isEmpty(); * bool param_6 = obj->isFull(); */ ================================================ FILE: cpp/621-630/K Inverse Pairs Array.cpp ================================================ class Solution { const int mod = pow(10, 9) + 7; public: int kInversePairs(int n, int k) { vector> dp(n+1, vector(k+1, -1)); return dfs(n, k, dp); } long dfs(int n, int k, vector>& dp) { if (n == 0) return 0; if (n == 1 && k == 0) return 1; if (n == 1 && k == 1) return 0; if (k == 0) return 1; if (n == 2 && k == 1) return 1; int bound = (n-1)*n/2; if (k > bound) return 0; if (dp[n][k] > -1) return dp[n][k]; int temp = 0; if (k > bound/2) return dp[n][k] = ( dfs(n, bound - k, dp) % mod); else temp = (dfs(n - 1, k, dp) + dfs(n, k - 1, dp)) % mod; int nonused = k - n; if (nonused >= 0) temp = (temp + mod - dfs(n - 1, nonused, dp)) % mod; return dp[n][k] = temp; } }; ================================================ FILE: cpp/621-630/Maximum Distance in Arrays.cpp ================================================ class Solution { public: int maxDistance(vector>& arrays) { int left = arrays[0].front(); int right = arrays[0].back(); int ans = 0; for (int i = 1; i < arrays.size(); i++) { ans = max(ans, max(abs(arrays[i].front() - right), abs(arrays[i].back() - left))); left = min(left, arrays[i].front()); right = max(right, arrays[i].back()); } return ans; } }; ================================================ FILE: cpp/621-630/Maximum Product of Three Numbers.cpp ================================================ class Solution { public: int maximumProduct(vector& nums) { sort(nums.begin(), nums.end()); int n = nums.size(); int temp1 = nums[n-1] * nums[n-2] * nums[n-3]; int temp2 = nums[0] * nums[1] * nums[n-1]; return max(temp1, temp2); } }; ================================================ FILE: cpp/621-630/Minimum Factorization.cpp ================================================ class Solution { public: int smallestFactorization(int a) { if (a == 1) return 1; string result = ""; int temp = 9; while (temp > 1) { if (a % temp == 0) { result = to_string(temp) + result; a /= temp; } else { temp--; } } if (a > 10) return 0; if (result.length() > 10) return 0; if (result.length() < 10) return stoi(result); string mm = to_string(INT_MAX); if (result > mm) return 0; return stoi(result); } }; ================================================ FILE: cpp/621-630/Task Scheduler.cpp ================================================ class Solution { public: int leastInterval(vector& tasks, int n) { map mymap; int maximumTimes = 0; for (char ch : tasks) { mymap[ch]++; maximumTimes = max(maximumTimes, mymap[ch]); } int ans = (maximumTimes - 1) * (n + 1); for (const auto& ele : mymap) { if (maximumTimes == ele.second) { ans++; } } return max(int(tasks.size()), ans); } }; ================================================ FILE: cpp/631-640/Average of Levels in Binary Tree.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector averageOfLevels(TreeNode* root) { vector ret; double sum = 0, count = 0; queue q; q.push(root); q.push(nullptr); while (!q.empty()) { TreeNode* t = q.front(); q.pop(); if (t == nullptr) { ret.push_back(sum / count); sum = count = 0; if (!q.empty()) q.push(nullptr); } else { sum += t->val; ++count; if (t->left) q.push(t->left); if (t->right) q.push(t->right); } } return ret; } }; ================================================ FILE: cpp/631-640/Decode Ways II.cpp ================================================ class Solution { const int mod = 1000000007; int ways(char ch) { if (ch == '*') return 9; if (ch == '0') return 0; return 1; } int ways(char ch1, char ch2) { if (ch1 == '0') return 0; if (ch1 == '*') { if (ch2 == '*') return 15; if (ch2 <= '6') return 2; return 1; } if (ch1 == '1') { if (ch2 == '*') return 9; return 1; } if (ch1 == '2') { if (ch2 == '*') return 6; if (ch2 <= '6') return 1; return 0; } return 0; } public: int numDecodings(string s) { int n = s.length(); vector dp(n, 0); for (int i = 0; i < n; i++) { if (i == 0) { dp[0] = ways(s[0]); } else if (i == 1) { dp[1] = dp[0] * ways(s[1]) + ways(s[0], s[1]); } else { dp[i] = (dp[i - 1] * ways(s[i]) + dp[i - 2] * ways(s[i - 1], s[i])) % mod; } } return dp[n - 1]; } }; ================================================ FILE: cpp/631-640/Design Excel Sum Formula.cpp ================================================ class Excel { vector> matrix; map, vector> cellStrMapping; int c2i(char ch) { return ch - 'A'; } pair parseNum(const string& num) { int row = stoi(num.substr(1)); return {row, num[0]}; } public: Excel(int H, char W) { matrix = vector>(H, vector(c2i(W) + 1, 0)); } void set(int r, char c, int v) { int col = c2i(c); pair mypair = {r, col}; if (cellStrMapping.count(mypair) != 0) { cellStrMapping.erase(mypair); } matrix[r-1][c2i(c)] = v; } int get(int r, char c) { int col = c2i(c); pair mypair = {r, col}; if (cellStrMapping.count(mypair) == 0) { return matrix[r-1][col]; } else { vector allStrs = cellStrMapping[mypair]; int result = 0; for (const string& num : allStrs) { int idx = num.find(':'); if (idx >= 0) { pair cellStart = parseNum(num.substr(0, idx)); pair cellEnd = parseNum(num.substr(idx + 1)); int row1 = cellStart.first; int row2 = cellEnd.first; int col1 = cellStart.second - 'A'; int col2 = cellEnd.second - 'A'; for (int i = row1; i <= row2; i++) { for (int j = col1; j <= col2; j++) { char ch = 'A' + j; result += (get(i, ch)); } } } else { pair cell = parseNum(num); result += get(cell.first, cell.second); } } return result; } } int sum(int r, char c, vector strs) { int col = c2i(c); pair mypair = {r, col}; cellStrMapping[mypair] = strs; return get(r, c); } }; /** * Your Excel object will be instantiated and called as such: * Excel obj = new Excel(H, W); * obj.set(r,c,v); * int param_2 = obj.get(r,c); * int param_3 = obj.sum(r,c,strs); */ ================================================ FILE: cpp/631-640/Design Log Storage System.cpp ================================================ class LogSystem { vector> logs; public: LogSystem() { } void put(int id, string timestamp) { logs.push_back({id, timestamp}); } vector retrieve(string s, string e, string gra) { int length = 0; if (gra == "Year") { length = 4; } else if (gra == "Month") { length = 7; } else if (gra == "Day") { length = 10; } else if (gra == "Hour") { length = 13; } else if (gra == "Minute") { length = 16; } else if (gra == "Second") { length = 19; } s = s.substr(0, length); e = e.substr(0, length); vector result; for (const auto& ele : logs) { string str = ele.second.substr(0, length); if (str >= s && str <= e) { result.push_back(ele.first); } } return result; } }; /** * Your LogSystem object will be instantiated and called as such: * LogSystem obj = new LogSystem(); * obj.put(id,timestamp); * vector param_2 = obj.retrieve(s,e,gra); */ ================================================ FILE: cpp/631-640/Exclusive Time of Functions.cpp ================================================ class Solution { vector split(const string &s, char delim) { vector elems; stringstream ss(s); string item; while (getline(ss, item, delim)) { elems.push_back(item); } return elems; } public: vector exclusiveTime(int n, vector& logs) { vector result(n, 0); stack> mystack; // pair for (const string& log : logs) { vector myvec = split(log, ':'); int id = stoi(myvec[0]); bool flag = myvec[1] == "start" ? true : false; // true start; false end int time = stoi(myvec[2]); if (flag) { mystack.push({id, time}); } else { pair currentPair = mystack.top(); mystack.pop(); int timeSpent = time - currentPair.second + 1; result[currentPair.first] += timeSpent; if (!mystack.empty()) { pair callerPair = mystack.top(); result[callerPair.first] -= timeSpent; } } } return result; } }; ================================================ FILE: cpp/631-640/Find the Derangement of An Array.cpp ================================================ class Solution { const int mod = 1000000007; public: int findDerangement(int n) { vector dp(n, 0); bool flag = true; for (int i = 2; i <= n; i++) { if (flag) { dp[i - 1] = (dp[i - 2] * i + 1) % mod; flag = false; } else { dp[i - 1] = (dp[i - 2] * i - 1) % mod; flag = true; } } return dp[n - 1]; } }; ================================================ FILE: cpp/631-640/Shopping Offers.cpp ================================================ class Solution { void dfs(int currentPrice, int offerIndex, vector& price, vector>& special, vector needs, int& result) { int n = price.size(); int nextOffer = offerIndex + 1; if (nextOffer < special.size()) dfs(currentPrice, nextOffer, price, special, needs, result); for (int k = 0; ; k++) { bool finished = true; for (int i = 0; i < special[offerIndex].size() - 1; i++) { needs[i] -= special[offerIndex][i]; if (needs[i] < 0) return; if (needs[i] > 0) finished = false; } currentPrice += special[offerIndex].back(); if (finished) { result = min(currentPrice, result); return; } if (nextOffer < special.size()) dfs(currentPrice, nextOffer, price, special, needs, result); } } public: int shoppingOffers(vector& price, vector>& special, vector& needs) { int n = price.size(); int result = INT_MAX; for (int i = 0; i < n; i++) { vector temp(n + 1, 0); temp[temp.size() - 1] = price[i]; temp[i] = 1; special.push_back(temp); } dfs(0, 0, price, special, needs, result); return result == INT_MAX ? 0 : result; } }; ================================================ FILE: cpp/631-640/Smallest Range.cpp ================================================ class Solution { public: vector smallestRange(vector>& nums) { map counters; int n = nums.size(); int start = INT_MAX; int end = INT_MIN; auto cmp = [](const pair> &a, const pair> &b) { return a.first >= b.first; }; priority_queue>, vector>>, decltype(cmp)> pq(cmp); for (int i = 0; i < n; i++) { pq.push({nums[i][0], {i, 0}}); // {value, {index of vector, index of element in this vector}} start = min(start, nums[i][0]); end = max(end, nums[i][0]); } vector result{start, end}; while (true) { if (end - start < result[1] - result[0]) { result[0] = start; result[1] = end; } pair> ele = pq.top(); pq.pop(); int v = ele.first; int numsIndex = ele.second.first; int eleIndex = ele.second.second; if (eleIndex + 1 < nums[numsIndex].size()) { pq.push({nums[numsIndex][eleIndex + 1], {numsIndex, eleIndex + 1}}); end = max(end, nums[numsIndex][eleIndex + 1]); } else { break; } start = pq.top().first; } return result; } }; ================================================ FILE: cpp/631-640/Solve the Equation.cpp ================================================ class Solution { pair parse(string str) { int xCount = 0, dCount = 0; int i = 0; int sign = 1; while (i < str.length()) { if (str[i] == '+') { sign = 1; i++; continue;} if (str[i] == '-') { sign = -1; i++; continue;} int num = -1; if (isdigit(str[i])) { while (i < str.length() && isdigit(str[i])) { if (num < 0) num = str[i] - '0'; else num = num * 10 + (str[i] - '0'); i++; } if (i >= str.length()) { dCount += (sign * num); break; } } if (str[i] == 'x') { if (num == -1) num = 1; xCount += (sign * num); i++; } else { dCount += (sign * num); } } return {xCount, dCount}; } public: string solveEquation(string equation) { int index = equation.find("="); string left = equation.substr(0, index); string right = equation.substr(index + 1); pair temp1 = parse(left); pair temp2 = parse(right); int d = temp2.second - temp1.second; int x = temp1.first - temp2.first; if (x == 0) { if (d == 0) { return "Infinite solutions"; } return "No solution"; } return "x=" + to_string(d/x); } }; ================================================ FILE: cpp/631-640/Sum of Square Numbers.cpp ================================================ class Solution { public: bool judgeSquareSum(int c) { if (c < 0) { return false; } int left = 0, right = (int)sqrt(c); while (left <= right) { int cur = left * left + right * right; if (cur < c) { left++; } else if (cur > c) { right--; } else { return true; } } return false; } }; ================================================ FILE: cpp/641-650/2 Keys Keyboard.cpp ================================================ class Solution { public: int minSteps(int n) { if (n == 1) return 0; if (n == 2) return 2; if (n == 3) return 3; for (int i = 2; i <= n; i++) { if (n % i != 0) continue; int temp = n / i; if (temp < i) return n; if (temp * i == n) { return i + minSteps(temp); } } return n; } }; ================================================ FILE: cpp/641-650/Design Search Autocomplete System.cpp ================================================ class AutocompleteSystem { unordered_map dict; string prefix; public: AutocompleteSystem(vector sentences, vector times) { for (int i = 0; i < times.size(); i++) dict[sentences[i]] += times[i]; } vector input(char c) { if (c == '#') { dict[prefix]++; prefix.clear(); return {}; } prefix.push_back(c); auto cmp = [](const pair &a, const pair &b) { return a.second > b.second || (a.second == b.second && a.first < b.first); }; priority_queue, vector>, decltype(cmp)> pq(cmp); for (const auto& ele : dict) { auto res = std::mismatch(prefix.begin(), prefix.end(), ele.first.begin()); if (res.first == prefix.end()){ pq.push(ele); if (pq.size() > 3) { pq.pop(); } } } vector res(pq.size()); for (int i = pq.size() - 1; i >= 0; i--) { res[i] = pq.top().first; pq.pop(); } return res; } }; ================================================ FILE: cpp/641-650/Dota2 Senate.cpp ================================================ class Solution { public: string predictPartyVictory(string senate) { queue rQ, dQ; for (int i = 0; i < senate.length(); i++) { if (senate[i] == 'R') { rQ.push(i); } else { dQ.push(i); } } while (!rQ.empty() && !dQ.empty()) { int rIndex = rQ.front(); int dIndex = dQ.front(); rQ.pop(); dQ.pop(); if (rIndex < dIndex) { rQ.push(rIndex + senate.length()); } else { dQ.push(dIndex + senate.length()); } } return rQ.empty() ? "Dire" : "Radiant"; } }; ================================================ FILE: cpp/641-650/Maximum Average Subarray I.cpp ================================================ class Solution { public: double findMaxAverage(vector& nums, int k) { double sum = accumulate(nums.begin(), nums.begin() + k, 0); double res = sum/k; for (int i = 0; i < nums.size() - k; i++) { sum = sum - nums[i] + nums[i+k]; res = max(res, sum/k); } return res; } }; ================================================ FILE: cpp/641-650/Maximum Average Subarray II.cpp ================================================ class Solution { bool validate(const vector& nums, int k, double mid) { vector numsCopy(nums.size()); for (int i = 0; i < nums.size(); i++) numsCopy[i] = nums[i] - mid; double sum = 0; double prevSum = 0; double minPrevSum = 0; for (int i = 0; i < numsCopy.size(); i++) { sum += numsCopy[i]; if (i >= k) { prevSum += numsCopy[i - k]; minPrevSum = min(minPrevSum, prevSum); if (sum > minPrevSum) return true; } if (i == k - 1) { if (sum >= 0) return true; } } return false; } public: double findMaxAverage(vector& nums, int k) { auto result = std::minmax_element(nums.begin(), nums.end()); double left = *result.first; double right = *result.second; while (abs(right - left) > 1e-5) { double mid = (left + right) / 2; if (validate(nums, k, mid)) { left = mid; } else { right = mid; } } return left; } }; ================================================ FILE: cpp/641-650/Maximum Length of Pair Chain.cpp ================================================ class Solution { public: int findLongestChain(vector>& pairs) { int n = pairs.size(); sort(pairs.begin(), pairs.end(), [](const vector& a, const vector&b) { return a[1] < b[1] || a[1] == b[1] && a[0] < b[0]; }); int cnt = 0; vector& pair = pairs[0]; for (const vector& ele : pairs) { if (cnt == 0 || ele[0] > pair[1]) { pair = ele; cnt++; } } return cnt; } }; ================================================ FILE: cpp/641-650/Palindromic Substrings.cpp ================================================ class Solution { public: int countSubstrings(string s) { int res = 0; vector> dp(s.length(), vector(s.length(), false)); for (int i = 0; i < s.length(); i++) { dp[i][i] = true; res++; } for (int i = 0; i < s.length() - 1; i++) { if (s[i] == s[i+1]) { dp[i][i+1] = true; res++; } } for (int step = 2; step < s.length(); step++) { for (int i = 0; i < s.length() - step; i++) { int j = i + step; if (s[i] == s[j] && dp[i+1][j-1]) { dp[i][j] = true; res++; } } } return res; } }; ================================================ FILE: cpp/641-650/Replace Words.cpp ================================================ vector split(const string &s, char delim) { vector elems; stringstream ss(s); string item; while (getline(ss, item, delim)) { if (item.length() > 0) { elems.push_back(item); } } return elems; } struct TrieNode { TrieNode *nodes[26]; bool word; // Initialize your data structure here. TrieNode(): word(false) { memset(nodes, 0, sizeof(nodes)); } }; class Trie { public: Trie() { root = new TrieNode(); } // Inserts a word into the trie. void insert(const string& s) { TrieNode *tmp = root; for(char ch : s) { int index = ch - 'a'; if(tmp->nodes[index] == nullptr) { tmp->nodes[index] = new TrieNode(); } tmp = tmp->nodes[index]; } tmp->word = true; } // Returns if the word is in the trie. string findShortestRoot(const string& word) { TrieNode *tmp = root; for(int i = 0; i < word.length(); i++) { int index = word[i] - 'a'; if(tmp->nodes[index] == nullptr) { return word; } tmp = tmp->nodes[index]; if (tmp->word == true) { return word.substr(0, i + 1); } } return word; } private: TrieNode* root; }; class Solution { public: string replaceWords(vector& dict, string sentence) { string returnSentence; Trie myTrie; for (const string& str : dict) { myTrie.insert(str); } vector words = split(sentence, ' '); for (int i = 0; i < words.size(); i++) { returnSentence += myTrie.findShortestRoot(words[i]); if (i != words.size() - 1) { returnSentence += ' '; } } return returnSentence; } }; ================================================ FILE: cpp/641-650/Set Mismatch.cpp ================================================ class Solution { public: vector findErrorNums(vector& nums) { vector result; int n = nums.size(); int sum = accumulate(nums.begin(), nums.end(), 0); unordered_set hashset; int i = 0; while (hashset.count(nums[i]) == 0) { hashset.insert(nums[i]); i++; } result.push_back(nums[i]); result.push_back((1+n)*n/2 - sum + nums[i]); return result; } }; ================================================ FILE: cpp/651-660/4 Keys Keyboard.cpp ================================================ class Solution { public: int maxA(int N) { if (N <= 6) return N; return max(3*maxA(N - 4), 4*maxA(N-5)); } }; ================================================ FILE: cpp/651-660/Coin Path.cpp ================================================ class Solution { public: vector cheapestJump(vector& A, int B) { vector ans; if (A.empty() || A.back() == -1) return ans; int n = A.size(); vector dp(n, INT_MAX), pos(n, -1); dp[n-1] = A[n-1]; // working backward for (int i = n-2; i >= 0; i--) { if (A[i] == -1) continue; for (int j = i+1; j <= min(i+B, n-1); j++) { if (dp[j] == INT_MAX) continue; if (A[i]+dp[j] < dp[i]) { dp[i] = A[i]+dp[j]; pos[i] = j; } } } // cannot jump to An if (dp[0] == INT_MAX) return ans; int k = 0; while (k != -1) { ans.push_back(k+1); k = pos[k]; } return ans; } }; ================================================ FILE: cpp/651-660/Find Duplicate Subtrees.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector findDuplicateSubtrees(TreeNode* root) { vector result; map> mymap; merkle(root, mymap); for (const auto& ele : mymap) { if (ele.second.size() > 1) { result.push_back(ele.second[0]); } } return result; } string merkle(TreeNode* root, map>& mymap) { if (root == nullptr) { return "#"; } string left = merkle(root->left, mymap); string right = merkle(root->right, mymap); size_t current = hash{}(left + to_string(root->val) + right); mymap[current].push_back(root); return to_string(current); } }; ================================================ FILE: cpp/651-660/Find K Closest Elements.cpp ================================================ // Solution 1. class Solution { public: vector findClosestElements(vector& arr, int k, int x) { auto it = lower_bound(arr.begin(), arr.end(), x); int idx = it - arr.begin(); if (idx == arr.size()) { idx--; } else if (idx > 0) { if (abs(arr[idx - 1] - x) <= abs(arr[idx] - x)) { idx = idx - 1; } } int l = idx - 1; int r = idx + 1; for (int i = 2; i <= k; i++) { if (l < 0) { r++; } else if (r >= arr.size()) { l--; } else { if (abs(arr[l] - x) <= abs(arr[r] - x)) { l--; } else { r++; } } } return vector(arr.begin() + l + 1, arr.begin() + r); } }; // Solution 2. class Solution { public: vector findClosestElements(vector& arr, int k, int x) { int left = 0; int right = arr.size() - k; while (left < right) { int mid = (left + right) / 2; if (x - arr[mid] > arr[mid + k] - x) { left = mid + 1; } else { right = mid; } } return vector(arr.begin() + left, arr.begin() + left + k); } }; ================================================ FILE: cpp/651-660/Judge Route Circle.cpp ================================================ class Solution { public: bool judgeCircle(string moves) { pair pos{0, 0}; for (char ch : moves) { if (ch == 'U') { pos.second++; } else if (ch == 'D') { pos.second--; } else if (ch == 'L') { pos.first--; } else { pos.first++; } } if (pos.first == 0 && pos.second == 0) return true; return false; } }; ================================================ FILE: cpp/651-660/Maximum Binary Tree.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { TreeNode* dfs(std::vector::iterator start, std::vector::iterator end) { if (start > end) { return nullptr; } if (start == end) { return new TreeNode(*start); } std::vector::iterator result; result = std::max_element(start, end+1); TreeNode* temp = new TreeNode(*result); temp->left = dfs(start, result-1); temp->right = dfs(result+1, end); return temp; } public: TreeNode* constructMaximumBinaryTree(vector& nums) { if (nums.size() == 0) return nullptr; return dfs(nums.begin(), --nums.end()); } }; ================================================ FILE: cpp/651-660/Print Binary Tree.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { int height(TreeNode* root, int h) { if (root == nullptr) { return 0; } int hl = height(root->left, h + 1); int hr = height(root->right, h + 1); return max(hl, hr) + 1; } void dfs(TreeNode* root, vector>& result, int height, int pos, int base) { if (root == nullptr) return; result[height][pos] = to_string(root->val); dfs(root->left, result, height+1, pos - base/2, base/2); dfs(root->right, result, height+1, pos + base/2, base/2); } public: vector> printTree(TreeNode* root) { int h = height(root, 0); int cols = 1; for (int i = 2; i <= h; i++) { cols = cols * 2 + 1; } vector> result(h, vector(cols, "")); dfs(root, result , 0, cols/2, (cols+1)/2); return result; } }; ================================================ FILE: cpp/651-660/Remove 9.cpp ================================================ class Solution { public: int newInteger(int n) { int result = 0; int base = 1; while (n > 0) { int temp = n % 9; n = (n - temp)/9; result += base * temp; base *= 10; } return result; } }; ================================================ FILE: cpp/651-660/Split Array into Consecutive Subsequences.cpp ================================================ class Solution { public: bool isPossible(vector& nums) { unordered_map, std::greater>> backs; // Keep track of the number of sequences with size < 3 int need_more = 0; for (int num : nums) { if (! backs[num - 1].empty()) { // There exists a sequence that ends in num-1 // Append 'num' to this sequence // Remove the existing sequence // Add a new sequence ending in 'num' with size incremented by 1 int count = backs[num - 1].top(); backs[num - 1].pop(); backs[num].push(++count); if (count == 3) need_more--; } else { // There is no sequence that ends in num-1 // Create a new sequence with size 1 that ends with 'num' backs[num].push(1); need_more++; } } return need_more == 0; } }; ================================================ FILE: cpp/651-660/Two Sum IV - Input is a BST.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { bool found; void dfs(TreeNode* root, unordered_set& myset, int k) { if (root == nullptr) return; if (found) return; if (myset.count(k - root->val) > 0) { found = true; return; } myset.insert(root->val); dfs(root->left, myset, k); dfs(root->right, myset, k); } public: bool findTarget(TreeNode* root, int k) { found = false; unordered_set myset; dfs(root, myset, k); return found; } }; ================================================ FILE: cpp/661-670/Beautiful Arrangement II.cpp ================================================ class Solution { public: vector constructArray(int n, int k) { vector result(n, 1); bool flag = false; int i = 2; for (; i <= k; i++) { flag = !flag; if (flag == false) { result[i-1] = result[i-3]+1; } else { result[i-1] = i-3 >= 0 ? result[i-3]-1 : n; } } if (flag == false) { while (i-1 < n && result[i-1] == 1) { result[i-1] = result[i-2]+1; i++; } } else { while (i-1 < n && result[i-1] == 1) { result[i-1] = result[i-2]-1; i++; } } return result; } }; ================================================ FILE: cpp/661-670/Equal Tree Partition.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { set myset; int dfs(TreeNode* root) { if (!root) return 0; int sum = root->val + dfs(root->left) + dfs(root->right); myset.insert(sum); return sum; } public: bool checkEqualTree(TreeNode* root) { if (!root) return false; int sum1 = dfs(root->left); int sum2 = dfs(root->right); int sum = root->val + sum1 + sum2; if (sum % 2 != 0) return false; int target = sum / 2; if (myset.count(target) > 0) return true; return false; } }; ================================================ FILE: cpp/661-670/Image Smoother.cpp ================================================ class Solution { public: vector> imageSmoother(vector>& M) { int m = M.size(); int n = M[0].size(); vector> result(m, vector(n, 0)); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { int gray = 0; int total = 0; for (int k1 = -1; k1 <= 1; k1++) { for (int k2 = -1; k2 <= 1; k2++) { int newi = i + k1; int newj = j + k2; if (newi < 0 || newj < 0 || newi >= m || newj >= n) continue; total++; gray += M[newi][newj]; } } result[i][j] = gray / total; } } return result; } }; ================================================ FILE: cpp/661-670/Kth largest Number in Multiplication Table.cpp ================================================ class Solution { bool validate(int p, int m, int n, int k){ int cnt = 0; for (int i = 0; i < n; i++) { if (m * (i + 1) <= p) cnt += m; else cnt += p / (i+1); } return cnt >= k; } public: int findKthNumber(int m, int n, int k) { int left = 0; int right = n * m +1; while(right - left > 1){ int mid = (left + right) >> 1; if(validate(mid, m, n, k)) { right = mid; } else left = mid; } return right; } }; ================================================ FILE: cpp/661-670/Maximum Swap.cpp ================================================ class Solution { public: int maximumSwap(int num) { vector records(10, -1); string numStr = to_string(num); for (int i = 0; i < numStr.size(); i++) { records[numStr[i] - '0'] = i; } for (int i = 0; i < numStr.size(); i++) { for (int j = 9; j >= 0; j--) { if (records[j] > i && j > (numStr[i] - '0')) { swap(numStr[i], numStr[records[j]]); return stoi(numStr); } } } return num; } }; ================================================ FILE: cpp/661-670/Maximum Width of Binary Tree.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int widthOfBinaryTree(TreeNode* root) { if (!root) return 0; int result = 0; vector> trees; trees.push_back({root, 0}); while (!trees.empty()) { auto left = trees.front(); auto right = trees.back(); result = max(result, right.second - left.second + 1); vector> temp; for (const auto& ele : trees) { TreeNode *node = ele.first; int v = ele.second; if (node->left) { temp.push_back({node->left, 2*v}); } if (node->right) { temp.push_back({node->right, 2*v+1}); } } trees = temp; } return result; } }; ================================================ FILE: cpp/661-670/Non-decreasing Array.cpp ================================================ class Solution { public: bool checkPossibility(vector& nums) { int n = nums.size(); int cnt = 0; for (int i = 0; i < n - 1; i++) { if(nums[i] > nums[i+1]) { ++cnt; // 2 3 3 2 4 => 2 3 3 3 4 // 4 2 3 => 2 2 3 // 4 2 1 => 4 4 1 // 3 4 2 3 => 3 4 4 3 if (i > 0 && nums[i+1] < nums[i-1]) { nums[i+1] = nums[i]; } else nums[i] = nums[i+1]; } } return cnt <= 1; } }; ================================================ FILE: cpp/661-670/Path Sum IV.cpp ================================================ class Solution { int getLeftChild(int key) { int d = key/10; int p = key%10; return 10*(d+1) + (2*p-1); } public: int pathSum(vector& nums) { map mymap; for (int num : nums) { int key = num/10; int value = num%10; mymap[key] = value; } int result = 0; for (auto it : mymap) { int key = it.first; if ( mymap.count(getLeftChild(key)) == 0 && mymap.count(getLeftChild(key)+1) == 0) { // this is leaf while (mymap.count(key) > 0) { result += mymap[key]; int d = key/10; int p = key%10; key = 10*(d-1)+(p+1)/2; } } } return result; } }; ================================================ FILE: cpp/661-670/Strange Printer.cpp ================================================ class Solution { public: int strangePrinter(string s) { if (s.length() == 1) return 1; if (s.empty()) return 0; string str = ""; str += s[0]; for (int i = 1; i < s.length(); i++) { if (s[i] != str.back()) { str += s[i]; } } int n = str.length(); vector> dp(n, vector(n, 1)); for (int step = 1; step < n; step++) { for (int i = 0; i < n - step; i ++) { int j = i + step; int temp = INT_MAX; for (int k = i; k < j; k++) { int v = dp[i][k] + dp[k+1][j]; if (str[k] == str[j]) v--; temp = min(temp, v); } dp[i][j] = temp; } } return dp[0][n-1]; } }; ================================================ FILE: cpp/661-670/Trim a Binary Search Tree.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* trimBST(TreeNode* root, int L, int R) { if (!root) return nullptr; if (root->val < L) { return trimBST(root->right, L, R); } else if (root->val > R) { return trimBST(root->left, L, R); } else { root->left = trimBST(root->left, L, R); root->right = trimBST(root->right, L, R); return root; } } }; ================================================ FILE: cpp/671-680/24 Game.cpp ================================================ class Solution { vector op(double d1, double d2) { vector result; result.push_back(d1 + d2); result.push_back(d1 - d2); result.push_back(d2 - d1); result.push_back(d1 * d2); if (fabs(d2) > 1e-5) result.push_back(d1 / d2); if (fabs(d1) > 1e-5) result.push_back(d2 / d1); return result; } bool almost(double num) { return fabs(num - 24.0) < 1e-5; } bool dfs(vector nums) { if (nums.size() == 2) { vector result = op(nums[0], nums[1]); for (double e : result) if (almost(e)) return true; return false; } for (int i = 0; i < nums.size(); i++) { for (int j = i+1; j < nums.size(); j++) { vector opResult = op(nums[i], nums[j]); for (double e : opResult) { vector temp; for (int k = 0; k < nums.size(); k++) { if (k != i && k != j) { temp.push_back(nums[k]); } } temp.push_back(e); bool r = dfs(temp); if (r) return true; } } } return false; } public: bool judgePoint24(vector& nums) { vector temp; for (int e : nums) temp.push_back(e * 1.0); return dfs (temp); } }; ================================================ FILE: cpp/671-680/Cut Off Trees for Golf Event.cpp ================================================ class Solution { public: int cutOffTree(vector>& forest) { if (forest.empty() || forest[0].empty()) return 0; int m = forest.size(), n = forest[0].size(); vector> trees; // get all the tree positions and sort based on height // trees[i][0] is height. The default comparison of vector compare first element before other elements. for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (forest[i][j] > 1) trees.push_back({forest[i][j], i, j}); } } sort(trees.begin(), trees.end()); int ans = 0; // accumulate all the paths for (int i = 0, cur_row = 0, cur_col = 0; i < trees.size(); i++) { int step = next_step(forest, cur_row, cur_col, trees[i][1], trees[i][2]); // if next tree cannot be reached, step = -1; if (step == -1) return -1; ans += step; cur_row = trees[i][1]; cur_col = trees[i][2]; } return ans; } private: // BFS to find shortest path to next tree; if cannot reach next tree, return -1 int next_step(vector>& forest, int sr, int sc, int er, int ec) { if (sr == er && sc == ec) return 0; int m = forest.size(), n = forest[0].size(); queue> myq; myq.push({sr, sc}); vector> visited(m, vector(n, 0)); visited[sr][sc] = 1; int step = 0; vector dir = {-1, 0, 1, 0, -1}; while (!myq.empty()) { step++; int sz = myq.size(); for (int i = 0; i < sz; i++) { int row = myq.front().first, col = myq.front().second; myq.pop(); for (int i = 0; i < 4; i++) { int r = row + dir[i], c = col + dir[i+1]; if (r < 0 || r >= m || c < 0 || c >= n || visited[r][c] == 1 || forest[r][c] == 0) continue; if (r == er && c == ec) return step; visited[r][c] = 1; myq.push({r, c}); } } } return -1; } }; ================================================ FILE: cpp/671-680/Implement Magic Dictionary.cpp ================================================ struct TrieNode { TrieNode *nodes[26]; bool word; // Initialize your data structure here. TrieNode(): word(false) { memset(nodes, 0, sizeof(nodes)); } }; class Trie { public: Trie() { root = new TrieNode(); } // Inserts a word into the trie. void insert(const string& s) { TrieNode *tmp = root; for(char ch : s) { int index = ch - 'a'; if(tmp->nodes[index] == nullptr) { tmp->nodes[index] = new TrieNode(); } tmp = tmp->nodes[index]; } tmp->word = true; } // Returns if the word is in the trie. bool search(TrieNode* tmp, const string& key, int strIndex, int count) { if (tmp == nullptr) return false; if (count > 1) return false; if (strIndex == key.length()) { return count == 1 && tmp->word; } char ch = key[strIndex]; int index = ch - 'a'; for (int i = 0; i < 26; i++) { int added = index == i ? 0 : 1; if (search(tmp->nodes[i], key, strIndex+1, count+added)) return true; } return false; } TrieNode* root; }; class MagicDictionary { Trie trie; public: /** Initialize your data structure here. */ MagicDictionary() { } /** Build a dictionary through a list of words */ void buildDict(vector dict) { for (const string& word : dict) trie.insert(word); } /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */ bool search(string word) { return trie.search(trie.root, word, 0, 0); } }; /** * Your MagicDictionary object will be instantiated and called as such: * MagicDictionary obj = new MagicDictionary(); * obj.buildDict(dict); * bool param_2 = obj.search(word); */ ================================================ FILE: cpp/671-680/Longest Continuous Increasing Subsequence.cpp ================================================ class Solution { public: int findLengthOfLCIS(vector& nums) { int res = 0, cnt = 0; for (int i = 0; i < nums.size(); i++){ if (i == 0 || nums[i-1] < nums[i]) { res = max(res, ++cnt); } else { cnt = 1; } } return res; } }; ================================================ FILE: cpp/671-680/Map Sum Pairs.cpp ================================================ struct TrieNode { TrieNode *nodes[26]; bool word; int value; // Initialize your data structure here. TrieNode(): word(false) { memset(nodes, 0, sizeof(nodes)); } }; class Trie { int dfs(TrieNode *tmp) { if (tmp == nullptr) return 0; int v = 0; if (tmp->word) v += tmp->value; for (int i = 0; i < 26; i++) v += dfs(tmp->nodes[i]); return v; } public: Trie() { root = new TrieNode(); } // Inserts a word into the trie. void insert(const string& s, int val) { TrieNode *tmp = root; for(char ch : s) { int index = ch - 'a'; if(tmp->nodes[index] == nullptr) { tmp->nodes[index] = new TrieNode(); } tmp = tmp->nodes[index]; } tmp->word = true; tmp->value = val; } int startsWith(const string& prefix) { TrieNode *tmp = root; for(char ch : prefix) { int index = ch - 'a'; if(tmp->nodes[index] == nullptr) { return 0; } tmp = tmp->nodes[index]; } return dfs(tmp); } private: TrieNode* root; }; class MapSum { Trie trie; public: /** Initialize your data structure here. */ MapSum() { } void insert(string key, int val) { trie.insert(key, val); } int sum(string prefix) { return trie.startsWith(prefix); } }; /** * Your MapSum object will be instantiated and called as such: * MapSum obj = new MapSum(); * obj.insert(key,val); * int param_2 = obj.sum(prefix); */ ================================================ FILE: cpp/671-680/Number of Longest Increasing Subsequence.cpp ================================================ class Solution { public: int findNumberOfLIS(vector& nums) { if(nums.empty()) return 0; int n = nums.size(), maxCnt=0, maxLen=0; vector dp(n,1), cnt(n,1); for(int i=0; i nums[j]) { if(dp[j] + 1 == dp[i]) cnt[i] += cnt[j]; else if(dp[j] + 1 > dp[i]){ dp[i] = dp[j] + 1; cnt[i] = cnt[j]; } } maxLen = max(maxLen, dp[i]); } for(int i=0; ival); } private: int minval(TreeNode* p, int first) { if (p == nullptr) return -1; if (p->val != first) return p->val; int left = minval(p->left, first), right = minval(p->right, first); if (left == -1) return right; if (right == -1) return left; return min(left, right); } }; ================================================ FILE: cpp/671-680/Valid Palindrome II.cpp ================================================ class Solution { public: bool validPalindrome(string s) { for (int i = 0, j = s.size() - 1; i < j; i++, j--) { if (s[i] != s[j]) { int i1 = i, j1 = j - 1, i2 = i + 1, j2 = j; while (i1 < j1 && s[i1] == s[j1]) { i1++; j1--; }; if (i1 >= j1) { return true; } while (i2 < j2 && s[i2] == s[j2]) { i2++; j2--; }; if (i2 >= j2) { return true; } return false; } } return true; } }; ================================================ FILE: cpp/671-680/Valid Parenthesis String.cpp ================================================ class Solution { public: bool checkValidString(string s) { int minLeft = 0, maxLeft = 0; for (char ch : s) { if (ch == '(') { minLeft++; maxLeft++; } else if (ch == ')') { minLeft--; maxLeft--; } else { minLeft--; maxLeft++; } if (maxLeft < 0) { return false; } minLeft = max(0, minLeft); } return minLeft == 0; } }; ================================================ FILE: cpp/681-690/Baseball Game.cpp ================================================ class Solution { public: int calPoints(vector& ops) { int sum = 0, score = 0; vector rounds; for (string op : ops) { if (op == "C") { sum -= rounds.back(); rounds.pop_back(); continue; } else if (op == "D") { sum += score = rounds.back() * 2; } else if (op == "+") { sum += score = rounds[rounds.size() - 1] + rounds[rounds.size() - 2]; } else { sum += score = stoi(op); } rounds.push_back(score); } return sum; } }; ================================================ FILE: cpp/681-690/Employee Importance.cpp ================================================ /* // Employee info class Employee { public: // It's the unique ID of each node. // unique id of this employee int id; // the importance value of this employee int importance; // the id of direct subordinates vector subordinates; }; */ class Solution { int dfs(const map& mymap, int id) { int sum = mymap.at(id)->importance; for (int sub_id : mymap.at(id)->subordinates) { sum += dfs(mymap, sub_id); } return sum; } public: int getImportance(vector employees, int id) { map mymap; for (Employee* employee : employees) { mymap[employee->id] = employee; } return dfs(mymap, id); } }; ================================================ FILE: cpp/681-690/K Empty Slots.cpp ================================================ class Solution { public: int kEmptySlots(vector& flowers, int k) { int n = flowers.size(); vector days(n, 0); for (int i = 0; i < n; i++) { days[flowers[i]-1] = i; } int ans = INT_MAX; int left = 0; while (left + k + 1 < n) { int right = left + k + 1; int startDay = days[left]; int endDay = days[right]; bool invalid = false; for (int i = left + 1; i < right; i++) { if (days[i] > startDay && days[i] > endDay) continue; invalid = true; left = i; break; } if (!invalid) { ans = min(ans, 1 + max(startDay, endDay)); left = right; } } return ans == INT_MAX ? -1 : ans; } }; ================================================ FILE: cpp/681-690/Knight Probability in Chessboard.cpp ================================================ class Solution { public: double knightProbability(int N, int K, int r, int c) { vector>> dp(K+1, vector>(N, vector(N, -1.0))); return helper(dp, N, K, r, c)/pow(8, K); } private: double helper(vector>>& dp, int N, int k, int r, int c) { // if out of board, return 0.0 if (r < 0 || r >= N || c < 0 || c >= N) return 0.0; // when k = 0, no more move, so it's 100% safe if (k == 0) return 1.0; if (dp[k][r][c] > -0.000001) return dp[k][r][c]; dp[k][r][c] = 0.0; for (int i = -2; i <= 2; i++) { if (i == 0) continue; dp[k][r][c] += helper(dp, N, k-1, r+i, c+3-abs(i)) + helper(dp, N, k-1, r+i, c-(3-abs(i))); } return dp[k][r][c]; } }; ================================================ FILE: cpp/681-690/Longest Univalue Path.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { int res; int dfs(TreeNode* root) { if (root == nullptr) return 0; int left = root->left ? dfs(root->left) : 0; int right = root->right ? dfs(root->right) : 0; int temp = 0; int returnValue = 0; if (root->left && root->left->val == root->val) { temp += left; returnValue = max(returnValue, left); } if (root->right && root->right->val == root->val) { temp += right; returnValue = max(returnValue, right); } res = max(res, temp); return returnValue + 1; } public: int longestUnivaluePath(TreeNode* root) { dfs(root); return res; } }; ================================================ FILE: cpp/681-690/Maximum Sum of 3 Non-Overlapping Subarrays.cpp ================================================ class Solution { public: vector maxSumOfThreeSubarrays(vector& nums, int k) { int n = nums.size(), maxsum = 0; vector sum = {0}, posLeft(n, 0), posRight(n, n-k), ans(3, 0); for (int i : nums) { sum.push_back(sum.back() + i); } for (int i = k, tot = sum[k]-sum[0]; i < n; i++) { if (sum[i+1]-sum[i+1-k] > tot) { posLeft[i] = i+1-k; tot = sum[i+1]-sum[i+1-k]; } else { posLeft[i] = posLeft[i-1]; } } for (int i = n-k-1, tot = sum[n] - sum[n-k]; i >= 0; i--) { // >= for lexicographical ordering if (sum[i+k]-sum[i] >= tot) { posRight[i] = i; tot = sum[i+k]-sum[i]; } else { posRight[i] = posRight[i+1]; } } // test all possible middle interval for (int i = k; i <= n-2*k; i++) { int l = posLeft[i-1]; int r = posRight[i+k]; int tot = (sum[i+k]-sum[i]) + (sum[l+k]-sum[l]) + (sum[r+k]-sum[r]); if (tot > maxsum) { maxsum = tot; ans = {l, i, r}; } } return ans; } }; ================================================ FILE: cpp/681-690/Next Closest Time.cpp ================================================ class Solution { public: string nextClosestTime(string time) { int cur = 60 * stoi(time.substr(0, 2)) + stoi(time.substr(3)); set allowed; for (char c : time) if (c != ':') allowed.insert(c - '0'); while (true) { bool found = true; cur = (cur + 1) % (24 * 60); int digits[4] = {cur / 60 / 10, cur / 60 % 10, cur % 60 / 10, cur % 60 % 10}; for (int d: digits) if (allowed.count(d) == 0) { found = false; break; }; if (!found) continue; string result; if (cur / 60 < 10) { result += "0"; } result += to_string(cur / 60); result += ":"; if (cur % 60 < 10) { result += "0"; } result += to_string(cur % 60); return result; } } }; ================================================ FILE: cpp/681-690/Redundant Connection II.cpp ================================================ class UF { private: vector parent; vector rank; int count; int N; public: UF(int N) : parent(N), rank(N, 0), N(N), count(N) { for (int i = 0; i < N; i++) { parent[i] = i; } } int find(int p) { while (p != parent[p]) { parent[p] = parent[parent[p]]; // path compression by halving p = parent[p]; } return p; } bool connected(int p, int q) { return find(p) == find(q); } void Union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make root of smaller rank point to root of larger rank if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ; else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP; else { parent[rootQ] = rootP; rank[rootP]++; } count--; } }; class Solution { public: vector findRedundantDirectedConnection(vector>& edges) { int n = edges.size(); UF uf(n+1); map mymap; int c(-1), canA, canB; for (const auto& edge : edges) { int u = edge[0]; int v = edge[1]; // two parent, must incorrect if (mymap.find(v) != mymap.end()) { c = v; canA = mymap[v]; canB = u; } mymap[v] = u; } for (const auto& edge : edges) { int u = edge[0]; int v = edge[1]; if (u == canB && v == c) continue; if (uf.connected(u, v)) { if (c == -1) { // Every node has only one parent // The edge causes the circle must be the bad one return edge; } return vector{canA, c}; } uf.Union(u, v); } return vector{canB, c}; } }; ================================================ FILE: cpp/681-690/Redundant Connection.cpp ================================================ class UF { private: vector parent; vector rank; int count; int N; public: UF(int N) : parent(N), rank(N, 0), N(N), count(N) { for (int i = 0; i < N; i++) { parent[i] = i; } } int find(int p) { while (p != parent[p]) { parent[p] = parent[parent[p]]; // path compression by halving p = parent[p]; } return p; } bool connected(int p, int q) { return find(p) == find(q); } void Union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make root of smaller rank point to root of larger rank if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ; else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP; else { parent[rootQ] = rootP; rank[rootP]++; } count--; } }; class Solution { public: vector findRedundantConnection(vector>& edges) { int n = edges.size(); UF uf(n+1); for (const auto& edge : edges) { int u = edge[0]; int v = edge[1]; if (uf.connected(u, v)) return edge; uf.Union(u, v); } return edges.back(); } }; ================================================ FILE: cpp/681-690/Repeated String Match.cpp ================================================ class Solution { public: int repeatedStringMatch(string A, string B) { int l = B.length() / A.length(); string temp; for (int i = 0; i < l; i++) temp += A; if (temp.find(B) != string::npos) { return l; } temp += A; if (temp.find(B) != string::npos) { return l+1; } temp += A; if (temp.find(B) != string::npos) { return l+2; } return -1; } }; ================================================ FILE: cpp/691-700/Binary Number with Alternating Bits.cpp ================================================ class Solution { public: bool hasAlternatingBits(int n) { while (n > 0) { if (n%2 == ((n>>1)%2)) { return false; } n=n>>1; } return true; } }; ================================================ FILE: cpp/691-700/Count Binary Substrings.cpp ================================================ class Solution { public: int countBinarySubstrings(string s) { int result = 0; char current = s[0]; int previousCount = 0; int count = 1; for (int i = 1; i < s.length(); i++) { if (s[i] == current) { count++; } else { current = s[i]; previousCount = count; count = 1; } if (count <= previousCount) { result++; } } return result; } }; ================================================ FILE: cpp/691-700/Degree of an Array.cpp ================================================ class Solution { public: int findShortestSubArray(vector& nums) { if (nums.size() < 2) return nums.size(); map startIndex, count; int len = nums.size(), fre = 0; for (int i = 0; i < nums.size() ;i++) { if (startIndex.count(nums[i]) == 0) startIndex[nums[i]] = i; count[nums[i]]++; if (count[nums[i]] == fre) { len = min(i - startIndex[nums[i]] + 1, len); } if (count[nums[i]] > fre) { len = i - startIndex[nums[i]] + 1; fre = count[nums[i]]; } } return len; } }; ================================================ FILE: cpp/691-700/Falling Squares.cpp ================================================ class Solution { public: vector fallingSquares(vector>& positions) { vector ans; vector> points; // x, y, sidelength int current = 0; for (const pair& position : positions) { int top = position.second; // Find all previous squares that are in current width range for (const auto& point : points) { int x = get<0>(point); int y = get<1>(point); int length = get<2>(point); if (x + length <= position.first) continue; if (position.first + position.second <= x) continue; top = max(top, y + position.second); } points.emplace_back(make_tuple(position.first, top, position.second)); current = max(current, top); ans.push_back(current); } return ans; } }; ================================================ FILE: cpp/691-700/Max Area of Island.cpp ================================================ class Solution { public: int maxAreaOfIsland(vector>& grid) { int max_area = 0; for(int i = 0; i < grid.size(); i++) for(int j = 0; j < grid[0].size(); j++) if(grid[i][j] == 1)max_area = max(max_area, AreaOfIsland(grid, i, j)); return max_area; } int AreaOfIsland(vector>& grid, int i, int j){ if( i >= 0 && i < grid.size() && j >= 0 && j < grid[0].size() && grid[i][j] == 1){ grid[i][j] = 0; return 1 + AreaOfIsland(grid, i+1, j) + AreaOfIsland(grid, i-1, j) + AreaOfIsland(grid, i, j-1) + AreaOfIsland(grid, i, j+1); } return 0; } }; ================================================ FILE: cpp/691-700/Number of Distinct Islands.cpp ================================================ class Solution { public: int numDistinctIslands(vector>& grid) { int m = grid.size(), n = grid[0].size(); set> islands; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { vector island; if (dfs(i, j, i, j, grid, m, n, island)) islands.insert(island); } } return islands.size(); } private: int delta[4][2] = { 0, 1, 1, 0, 0, -1, -1, 0}; bool dfs(int i0, int j0, int i, int j, vector>& grid, int m, int n, vector& island) { if (i < 0 || m <= i || j < 0 || n <= j || grid[i][j] <= 0) return false; island.push_back(i - i0); island.push_back(j - j0); grid[i][j] = -1; for (int d = 0; d < 4; d++) { dfs(i0, j0, i + delta[d][0], j + delta[d][1], grid, m, n, island); } return true; } }; ================================================ FILE: cpp/691-700/Partition to K Equal Sum Subsets.cpp ================================================ class Solution { bool isKPartitionPossibleRec(const vector& nums, int subsetSum, bool taken[], int target, int K, int limitIdx) { if (subsetSum == target) { if (K == 2) return true; return isKPartitionPossibleRec(nums, 0, taken, target, K - 1, 0); } for (int i = limitIdx; i < nums.size(); i++) { if (taken[i]) continue; int tmp = subsetSum + nums[i]; if (tmp <= target) { taken[i] = true; bool nxt = isKPartitionPossibleRec(nums, subsetSum + nums[i], taken, target, K, i + 1); taken[i] = false; if (nxt) return true; } } return false; } public: bool canPartitionKSubsets(vector& nums, int k) { int N = nums.size(); if (k == 1) return true; if (N < k) return false; int sum = accumulate(nums.begin(), nums.end(), 0); if (sum % k != 0) return false; int subset = sum / k; bool taken[N]; fill(taken, taken + N, false); taken[0] = true; // call recursive method to check K-substitution condition return isKPartitionPossibleRec(nums, nums[0], taken, subset, k, 0); } }; ================================================ FILE: cpp/691-700/Top K Frequent Words.cpp ================================================ class Solution { public: vector topKFrequent(vector& words, int k) { unordered_map freq; for(auto w : words){ freq[w]++; } auto comp = [&](const pair& a, const pair& b) { return a.second > b.second || (a.second == b.second && a.first < b.first); }; typedef priority_queue< pair, vector>, decltype(comp) > my_priority_queue_t; my_priority_queue_t pq(comp); for(auto w : freq ){ pq.emplace(w.first, w.second); if(pq.size()>k) pq.pop(); } vector output; while(!pq.empty()){ output.insert(output.begin(), pq.top().first); pq.pop(); } return output; } }; ================================================ FILE: cpp/701-710/Insert into a Binary Search Tree.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* insertIntoBST(TreeNode* root, int val) { if (root == nullptr) { return new TreeNode(val); } if (root->val > val) { root->left = insertIntoBST(root->left, val); } else { root->right = insertIntoBST(root->right, val); } return root; } }; /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* insertIntoBST(TreeNode* root, int val) { if (root == nullptr) { return new TreeNode(val); } TreeNode* parent = nullptr; TreeNode* cur = root; while (cur != nullptr) { parent = cur; if (cur->val > val) { cur = cur->left; if (cur == nullptr) { parent->left = new TreeNode(val); } } else { cur = cur->right; if (cur == nullptr) { parent->right = new TreeNode(val); } } } return root; } }; ================================================ FILE: cpp/701-710/Random Pick with Blacklist.cpp ================================================ // Solution 1: Binary Search. O(log) class Solution { vector v; std::random_device rd; int mod; public: Solution(int N, vector blacklist) { mod = N - blacklist.size(); sort(blacklist.begin(), blacklist.end()); v = blacklist; v.push_back(N); for (int i = 0; i < v.size(); i++) v[i] -= i; } int pick() { int index = rd() % mod; auto it = upper_bound(v.begin(), v.end(), index); return index + (it - v.begin()); } }; // Solution 2: hash_map; O(1) class Solution { random_device rd; unordered_map updated_index; int mod; public: Solution(int N, vector& blacklist) { mod = N - blacklist.size(); set blacklist_set(blacklist.begin(), blacklist.end()); int swap_num = N - 1; for (int blacklist_element : blacklist_set) { if (blacklist_element >= mod) break; while (blacklist_set.count(swap_num) > 0) { swap_num--; } updated_index[blacklist_element] = swap_num; swap_num--; } } int pick() { int index = rd() % mod; if (updated_index.count(index) > 0) { return updated_index[index]; } return index; } }; ================================================ FILE: cpp/701-710/To Lower Case.cpp ================================================ class Solution { public: string toLowerCase(string str) { int d = 'A' - 'a'; for (char& ch : str) { if (ch >= 'A' && ch <= 'Z') { ch -= d; } } return str; } }; ================================================ FILE: cpp/711-720/1-bit and 2-bit Characters.cpp ================================================ class Solution { public: bool isOneBitCharacter(vector& bits) { int i = 0; while (i < bits.size()) { if (i == bits.size() - 1) return true; if (bits[i] == 1) { i = i + 2; } else { i++; } } return false; } }; ================================================ FILE: cpp/711-720/Best Time to Buy and Sell Stock with Transaction Fee.cpp ================================================ class Solution { public: int maxProfit(vector& prices, int fee) { int n = prices.size(); int holdStock = -prices[0]; int noStock = 0; for (int e : prices) { int tmpHoldStock = holdStock; holdStock = max(holdStock, noStock - e); noStock = max(noStock, tmpHoldStock + e - fee); } return noStock; } }; ================================================ FILE: cpp/711-720/Find K-th Smallest Pair Distance.cpp ================================================ class Solution { public: int smallestDistancePair(vector& nums, int k) { if (nums.empty() || k <= 0) return INT_MIN; sort (nums.begin(), nums.end()); int n = nums.size(), low = 0, high = nums[n-1] - nums[0]; while (low < high) { int mid = low + (high-low) / 2; int left = 0; int right = 1; int cnt = 0; while (right < n) { if (nums[right] - nums[left] > mid) { ++left; } else { cnt += (right-left); ++right; } } if (cnt < k) low = mid+1; else high = mid; } return low; } }; ================================================ FILE: cpp/711-720/Longest Word in Dictionary.cpp ================================================ class Solution { public: string longestWord(vector& words) { sort(words.begin(), words.end()); unordered_set built; string res; for (string w : words) { if (w.size() == 1 || built.count(w.substr(0, w.size() - 1))) { res = w.size() > res.size() ? w : res; built.insert(w); } } return res; } }; ================================================ FILE: cpp/711-720/Max Stack.cpp ================================================ class MaxStack { stack s1; stack s2; public: /** initialize your data structure here. */ MaxStack() { } void push(int x) { s1.push(x); if (s2.empty() || s2.top() <= x) s2.push(x); } int pop() { int tmp = s1.top(); s1.pop(); if (tmp == s2.top()) s2.pop(); return tmp; } int top() { return s1.top(); } int peekMax() { return s2.top(); } int popMax() { int tmp = s2.top(); s2.pop(); stack tmpStack; while (s1.top() < tmp) { tmpStack.push(s1.top()); s1.pop(); } s1.pop(); while (!tmpStack.empty()) { push(tmpStack.top()); tmpStack.pop(); } return tmp; } }; /** * Your MaxStack object will be instantiated and called as such: * MaxStack obj = new MaxStack(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.peekMax(); * int param_5 = obj.popMax(); */ ================================================ FILE: cpp/711-720/Maximum Length of Repeated Subarray.cpp ================================================ class Solution { public: int findLength(vector& A, vector& B) { int maxlen = 0; vector>dp (A.size(), vector(B.size(), 0)); for(int i = 0; i < A.size(); ++i) { for(int j = 0; j < B.size(); ++j) { if(A[i] == B[j]) { if(i && j) { dp[i][j] = dp[i-1][j-1] + 1; } else if(i == 0 || j == 0) { dp[i][j] = 1; } if(dp[i][j] > maxlen) { maxlen = dp[i][j]; } } } } return maxlen; } }; ================================================ FILE: cpp/711-720/Minimum ASCII Delete Sum for Two Strings.cpp ================================================ class Solution { public: int minimumDeleteSum(string s1, string s2) { int m = s1.length(); int n = s2.length(); vector> dp (m + 1, vector(n + 1, 0)); for (int i = 1; i <= m; i++) { dp[i][0] = dp[i-1][0] + s1[i-1]; } for (int i = 1; i <= n; i++) { dp[0][i] = dp[0][i-1] + s2[i-1]; } for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (s1[i-1] == s2[j-1]) { dp[i][j] = dp[i-1][j-1]; } else { dp[i][j] = min(dp[i][j-1] + s2[j-1], dp[i-1][j] + s1[i-1]); } } } return dp[m][n]; } }; ================================================ FILE: cpp/711-720/Number of Distinct Islands II.cpp ================================================ class Solution { public: map>> mp; void dfs(int r, int c, vector> &g, int cnt) { if ( r < 0 || c < 0 || r >= g.size() || c >= g[0].size()) return; if (g[r][c] != 1) return; g[r][c] = cnt; mp[cnt].push_back({r,c}); dfs(r+1,c,g,cnt); dfs(r-1,c,g,cnt); dfs(r,c+1,g,cnt); dfs(r,c-1,g,cnt); } vector> norm(vector> v) { vector>> s(8); // compute rotations/reflections. for (auto p:v) { int x = p.first, y = p.second; s[0].push_back({x,y}); s[1].push_back({x,-y}); s[2].push_back({-x,y}); s[3].push_back({-x,-y}); s[4].push_back({y,-x}); s[5].push_back({-y,x}); s[6].push_back({-y,-x}); s[7].push_back({y,x}); } for (auto &l:s) sort(l.begin(),l.end()); for (auto &l:s) { for (int i = 1; i < v.size(); ++i) l[i] = {l[i].first-l[0].first, l[i].second - l[0].second}; l[0] = {0,0}; } sort(s.begin(),s.end()); return s[0]; } int numDistinctIslands2(vector>& g) { int cnt = 1; set>> s; for (int i = 0; i < g.size(); ++i) for (int j = 0; j < g[i].size(); ++j) if (g[i][j] == 1) { dfs(i,j,g, ++cnt); s.insert(norm(mp[cnt])); } return s.size(); } }; ================================================ FILE: cpp/711-720/Range Module.cpp ================================================ class RangeModule { public: void addRange(int left, int right) { int n = invals.size(); vector> tmp; for (int i = 0; i <= n; i++) { if (i == n || invals[i].first > right) { tmp.push_back({left, right}); while (i < n) tmp.push_back(invals[i++]); } else if (invals[i].second < left) tmp.push_back(invals[i]); else { left = min(left, invals[i].first); right = max(right, invals[i].second); } } invals = tmp; } bool queryRange(int left, int right) { int n = invals.size(), l = 0, r = n-1; while (l <= r) { int m = l+(r-l)/2; if (invals[m].first >= right) r = m-1; else if (invals[m].second <= left) l = m+1; else return invals[m].first <= left && invals[m].second >= right; } return false; } void removeRange(int left, int right) { int n = invals.size(); vector> tmp; for (int i = 0; i < n; i++) { if (invals[i].second <= left || invals[i].first >= right) tmp.push_back(invals[i]); else { if (invals[i].first < left) tmp.push_back({invals[i].first, left}); if (invals[i].second > right) tmp.push_back({right, invals[i].second}); } } invals = tmp; } private: vector> invals; }; ================================================ FILE: cpp/711-720/Subarray Product Less Than K.cpp ================================================ class Solution { public: int numSubarrayProductLessThanK(vector& nums, int k) { int i = 0, j = 0, result = 0, product = 1; while (i < nums.size()) { while (j < nums.size() && nums[j] * product < k) { product *= nums[j]; j++; } if (i == j) { i++; j++; continue; } result += (j-i); product /= nums[i]; i++; } return result; } }; ================================================ FILE: cpp/721-730/Accounts Merge.cpp ================================================ /* * Solution 1: DFS, slower when building graph. */ class Solution { void dfs(const vector>& graph, const vector>& accounts, int ind, vector& visited, set& emails) { visited[ind] = true; for (int i = 1; i < accounts[ind].size(); i++) { emails.insert(accounts[ind][i]); } for (int neighbor : graph[ind]) { if (!visited[neighbor]) { dfs(graph, accounts, neighbor, visited, emails); } } } public: vector> accountsMerge(vector>& accounts) { vector> res; int n = accounts.size(); vector> graph(n); vector visited(n, false); for (int i = 0; i < n; i++) { unordered_set emails(accounts[i].begin()+1, accounts[i].end()); for (int j = 0; j < i; j++) { if (accounts[i][0] != accounts[j][0]) { continue; } for (int k = 1; k < accounts[j].size(); k++) { if (emails.count(accounts[j][k]) > 0) { graph[i].push_back(j); graph[j].push_back(i); break; } } } } for (int i = 0; i < accounts.size(); i++) { if (!visited[i]) { set emailSet; dfs(graph, accounts, i, visited, emailSet); res.resize(res.size() + 1); res.back().push_back(accounts[i][0]); for (const string& email : emailSet) { res.back().push_back(email); } } } return res; } }; /********************************************************************************/ /* * Solution 2: DFS, faster when building graph. */ class Solution { void dfs(const vector>& graph, const vector>& accounts, int ind, vector& visited, set& emails) { visited[ind] = true; for (int i = 1; i < accounts[ind].size(); i++) { emails.insert(accounts[ind][i]); } for (int neighbor : graph[ind]) { if (!visited[neighbor]) { dfs(graph, accounts, neighbor, visited, emails); } } } public: vector> accountsMerge(vector>& accounts) { vector> res; int n = accounts.size(); vector> graph(n); vector visited(n, false); unordered_map> email_to_ids; for (int i = 0; i < n; i++) { for (int j = 1; j < accounts[i].size(); j++) { email_to_ids[accounts[i][j]].push_back(i); } } for (const auto& pair : email_to_ids) { const vector& ids = pair.second; for (int i = 1; i < ids.size(); i++) { graph[ids[0]].push_back(ids[i]); graph[ids[i]].push_back(ids[0]); } } for (int i = 0; i < accounts.size(); i++) { if (!visited[i]) { set emailSet; dfs(graph, accounts, i, visited, emailSet); res.resize(res.size() + 1); res.back().push_back(accounts[i][0]); for (const string& email : emailSet) { res.back().push_back(email); } } } return res; } }; /********************************************************************************/ /* * Solution 3: Union-Find. */ class UF { private: vector parent; vector rank; int count; int N; public: UF(int N) : parent(N), rank(N, 0), N(N), count(N) { for (int i = 0; i < N; i++) { parent[i] = i; } } int find(int p) { while (p != parent[p]) { parent[p] = parent[parent[p]]; // path compression by halving p = parent[p]; } return p; } int getCount() const { return count; } bool connected(int p, int q) { return find(p) == find(q); } void Union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make root of smaller rank point to root of larger rank if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ; else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP; else { parent[rootQ] = rootP; rank[rootP]++; } count--; } }; class Solution { public: vector> accountsMerge(vector>& accounts) { int n = accounts.size(); map> mymap; for (int i = 0; i < n; i++) { for (int j = 1; j < accounts[i].size(); j++) { mymap[accounts[i][j]].push_back(i); } } UF uf(n); for (const auto& it : mymap) { for (int i = 1; i < it.second.size(); i++) { uf.Union(it.second[0], it.second[i]); } } vector> result; unordered_map root_2_result_idx; for (const auto& it : mymap) { int root = uf.find(it.second[0]); int resultSize = root_2_result_idx.size(); if (root_2_result_idx.count(root) == 0) { root_2_result_idx[root] = resultSize; vector temp; temp.push_back(accounts[root][0]); result.push_back(temp); } int index = root_2_result_idx[root]; result[index].push_back(it.first); } return result; } }; ================================================ FILE: cpp/721-730/Candy Crush.cpp ================================================ class Solution { public: vector> candyCrush(vector>& board) { int n = board.size(), m = board[0].size(); while (true) { vector> vp; for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) if (board[i][j]) { int i0 = i, i1 = i, j0 = j, j1 = j; while (i1 < n && i1 < i + 3 && board[i1][j] == board[i][j]) ++i1; while (i0 >= 0 && i0 > i - 3 && board[i0][j] == board[i][j]) --i0; while (j1 < m && j1 < j + 3 && board[i][j1] == board[i][j]) ++j1; while (j0 >= 0 && j0 > j - 3 && board[i][j0] == board[i][j]) --j0; if (i1 - i0 >3 || j1 -j0 > 3) vp.push_back({i,j}); } if (vp.empty()) break; for (auto p:vp) board[p.first][p.second] = 0; for (int j = 0; j < m; ++j) { int t = n-1; for (int i = n-1; i >=0; --i) if (board[i][j]) swap(board[i][j], board[t--][j]); } } return board; } }; ================================================ FILE: cpp/721-730/Count Different Palindromic Subsequences.cpp ================================================ class Solution { public: int countPalindromicSubsequences(string S) { int n = S.size(); int mod = 1000000007; auto dp_ptr = new vector>>(4, vector>(n, vector(n))); auto& dp = *dp_ptr; for (int i = n-1; i >= 0; --i) { for (int j = i; j < n; ++j) { for (int k = 0; k < 4; ++k) { char c = 'a' + k; if (j == i) { if (S[i] == c) dp[k][i][j] = 1; else dp[k][i][j] = 0; } else { // j > i if (S[i] != c) dp[k][i][j] = dp[k][i+1][j]; else if (S[j] != c) dp[k][i][j] = dp[k][i][j-1]; else { // S[i] == S[j] == c if (j == i+1) dp[k][i][j] = 2; // "aa" : {"a", "aa"} else { // length is > 2 dp[k][i][j] = 2; for (int m = 0; m < 4; ++m) { // count each one within subwindows [i+1][j-1] dp[k][i][j] += dp[m][i+1][j-1]; dp[k][i][j] %= mod; } } } } } } } int ans = 0; for (int k = 0; k < 4; ++k) { ans += dp[k][0][n-1]; ans %= mod; } return ans; } }; ================================================ FILE: cpp/721-730/Find Pivot Index.cpp ================================================ class Solution { public: int pivotIndex(vector& nums) { if (nums.empty()) return -1; int rightSum = std::accumulate(nums.begin() + 1, nums.end(), 0); if (rightSum == 0) return 0; int leftSum = 0; for (int i = 1; i < nums.size(); i++) { leftSum += nums[i - 1]; rightSum -= nums[i]; if (leftSum == rightSum) return i; } return -1; } }; ================================================ FILE: cpp/721-730/My Calendar I.cpp ================================================ class MyCalendar { vector> books; public: MyCalendar() { } bool book(int start, int end) { for (const pair& p : books) if (max(p.first, start) < min(end, p.second)) return false; books.push_back({start, end}); return true; } }; /** * Your MyCalendar object will be instantiated and called as such: * MyCalendar obj = new MyCalendar(); * bool param_1 = obj.book(start,end); */ ================================================ FILE: cpp/721-730/Number of Atoms.cpp ================================================ class Solution { void merge(map &local, const map& inners) { for (auto it : inners) { local[it.first] += it.second; } } void multiply(map &local, int k) { for (auto it : local) { local[it.first] = it.second * k; } } int parseValue(const string& formula, int& i) { int start = i; while (i < formula.size() && isdigit(formula[i])) { i++; } int value = 1; if (i > start) { value = stoi(formula.substr(start, i - start)); } return value; } void parseOneItem(map &local, const string& formula, int& i) { int start = i; while (i+1 < formula.size() && islower(formula[i+1])) { i++; } i++; string key = formula.substr(start, i - start); local[key] += parseValue(formula, i); } map dfs(const string& formula, int& i) { map locals; while (i < formula.size() && formula[i] != ')') { if (formula[i] == '(') { i++; map inners = dfs(formula, i); merge(locals, inners); } else { parseOneItem(locals, formula, i); } } int k = 1; if (formula[i] == ')') { i++; k = parseValue(formula, i); } multiply(locals, k); return locals; } public: string countOfAtoms(string formula) { int i = 0; map counts = dfs(formula, i); string result = ""; for (auto it : counts) { result += (it.first + (it.second > 1 ? to_string(it.second) : "")); } return result; } }; ================================================ FILE: cpp/721-730/Remove Comments.cpp ================================================ class Solution { public: vector removeComments(vector& source) { vector ans; bool inBlock = false; string sf; for (const string &t : source) { for (int i = 0; i < t.size();) { if (!inBlock) { if (i + 1 == t.size()) sf += t[i++]; else { string m = t.substr(i,2); if (m == "/*") inBlock = true, i+=2; else if (m == "//") break; else sf += t[i++]; } } else { if (i + 1 == t.size()) i++; else { string m = t.substr(i,2); if (m == "*/") inBlock = false, i+=2; else i++; } } } if (sf.size() && !inBlock) ans.push_back(sf), sf = ""; } return ans; } }; ================================================ FILE: cpp/721-730/Self Dividing Numbers.cpp ================================================ class Solution { public: vector selfDividingNumbers(int left, int right) { vector v; for (int i = left; i <= right; ++i) { int j = i; bool ok = 1; while (j) { int d= (j%10); if (d == 0 || i % d) ok = 0; j/=10; } if (ok) v.push_back(i); } return v; } }; ================================================ FILE: cpp/721-730/Split Linked List in Parts.cpp ================================================ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: vector splitListToParts(ListNode* root, int k) { vector parts(k, nullptr); int len = 0; for (ListNode* node = root; node != nullptr; node = node->next) len++; int n = len / k, r = len % k; // n : minimum guaranteed part size; r : extra nodes spread to the first r parts; ListNode* node = root, *prev = nullptr; for (int i = 0; i < k; i++, r--) { parts[i] = node; for (int j = 0; j < n + (r > 0); j++) { prev = node; node = node->next; } if (prev) prev->next = nullptr; } return parts; } }; ================================================ FILE: cpp/731-740/Asteroid Collision.cpp ================================================ class Solution { public: vector asteroidCollision(vector& asteroids) { stack mystack; for (int ast : asteroids) { bool eat = false; while (!mystack.empty() && ast < 0 && 0 < mystack.top()) { if (mystack.top() < -ast) { mystack.pop(); continue; } else if (mystack.top() == -ast) { eat = true; mystack.pop(); } else { eat = true; } break; } if (!eat) mystack.push(ast); } vector ans(mystack.size()); for (int t = ans.size() - 1; t >= 0; --t) { ans[t] = mystack.top(); mystack.pop(); } return ans; } }; ================================================ FILE: cpp/731-740/Daily Temperatures.cpp ================================================ class Solution { public: vector dailyTemperatures(vector& temperatures) { vector res(temperatures.size(), 0); stack> mystack; for (int i = 0; i < temperatures.size(); i++) { while (!mystack.empty() && mystack.top().first < temperatures[i]) { res[mystack.top().second] = i - mystack.top().second; mystack.pop(); } mystack.push({temperatures[i], i}); } return res; } }; ================================================ FILE: cpp/731-740/Delete and Earn.cpp ================================================ class Solution { int rob(vector &num) { if (num.empty()) return 0; int p[num.size()]; p[0] = num[0]; p[1] = max(num[0], num[1]); for (int i = 2;i < num.size();i++) p[i] = max(p[i-2] + num[i], p[i-1]); return p[num.size()-1]; } public: int deleteAndEarn(vector& nums) { int n = 10001; vector values(n, 0); for (int num : nums) values[num] += num; return rob(values); } }; ================================================ FILE: cpp/731-740/Flood Fill.cpp ================================================ class Solution { public: vector> floodFill(vector>& image, int sr, int sc, int newColor) { if (image[sr][sc] != newColor) dfs(image, sr, sc, image[sr][sc], newColor); return image; } private: void dfs(vector>& image, int i, int j, int c0, int c1) { if (i < 0 || j < 0 || i >= image.size() || j >= image[0].size() || image[i][j] != c0) return; image[i][j] = c1; dfs(image, i, j - 1, c0, c1); dfs(image, i, j + 1, c0, c1); dfs(image, i - 1, j, c0, c1); dfs(image, i + 1, j, c0, c1); } }; ================================================ FILE: cpp/731-740/Monotone Increasing Digits.cpp ================================================ class Solution { public: int monotoneIncreasingDigits(int N) { string n_str = to_string(N); int marker = n_str.size(); for(int i = n_str.size()-1; i > 0; i --) { if(n_str[i] < n_str[i-1]) { marker = i; n_str[i-1] = n_str[i-1]-1; } } for(int i = marker; i < n_str.size(); i ++) n_str[i] = '9'; return stoi(n_str); } }; ================================================ FILE: cpp/731-740/My Calendar II.cpp ================================================ class MyCalendarTwo { vector> once; vector> twice; public: MyCalendarTwo() { } bool book(int start, int end) { for (const pair& p : twice) if (max(p.first, start) < min(end, p.second)) return false; for (const pair& p : once) { if (max(p.first, start) < min(end, p.second)) { int duplicateStart = max(p.first, start); int duplicateEnd = min(end, p.second); twice.push_back({duplicateStart, duplicateEnd}); } } once.push_back({start, end}); return true; } }; /** * Your MyCalendarTwo object will be instantiated and called as such: * MyCalendarTwo obj = new MyCalendarTwo(); * bool param_1 = obj.book(start,end); */ ================================================ FILE: cpp/731-740/My Calendar III.cpp ================================================ class MyCalendarThree { map timeline; public: int book(int s, int e) { timeline[s]++; // 1 new event will be starting at [s] timeline[e]--; // 1 new event will be ending at [e]; int ongoing = 0, k = 0; for (const pair& t : timeline) k = max(k, ongoing += t.second); return k; } }; /** * Your MyCalendarThree object will be instantiated and called as such: * MyCalendarThree obj = new MyCalendarThree(); * int param_1 = obj.book(start,end); */ ================================================ FILE: cpp/731-740/Parse Lisp Expression.cpp ================================================ class Solution { public: int evaluate(string expression) { unordered_map myMap; return help(expression, myMap); } int help(string expression, unordered_map myMap) { if ((expression[0] == '-') || (isdigit(expression[0]))) return stoi(expression); else if (expression[0] != '(') return myMap[expression]; //to get rid of the first '(' and the last ')' string s = expression.substr(1, expression.size()-2); int start = 0; string word = parse(s, start); if (word == "let") { while (true) { string variable = parse(s, start); //if there is no more expression, simply evaluate the variable if (start >= s.size()) return help(variable, myMap); string temp = parse(s,start); myMap[variable] = help(temp, myMap); } } else if (word == "add") return help(parse(s,start), myMap) + help(parse(s,start), myMap); else if (word == "mult") return help(parse(s,start), myMap) * help(parse(s,start), myMap); } //function to seperate each expression string parse(string &s, int &start) { int end = start+1, temp = start; if (s[start] == '(') { int count = 1; while (count != 0) { if (s[end] == '(') count++; else if (s[end] == ')') count--; end++; } } else { while (end < s.size() && s[end] != ' ') end++; } start = end+1; return s.substr(temp, end-temp); } }; ================================================ FILE: cpp/731-740/Sentence Similarity II.cpp ================================================ class UF { private: vector parent; vector rank; int count; int N; public: UF(int N) : parent(N), rank(N, 0), N(N), count(N) { for (int i = 0; i < N; i++) { parent[i] = i; } } int find(int p) { while (p != parent[p]) { parent[p] = parent[parent[p]]; // path compression by halving p = parent[p]; } return p; } int getCount() const { return count; } bool connected(int p, int q) { return find(p) == find(q); } void Union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make root of smaller rank point to root of larger rank if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ; else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP; else { parent[rootQ] = rootP; rank[rootP]++; } count--; } }; class Solution { public: bool areSentencesSimilarTwo(vector& words1, vector& words2, vector> pairs) { if (words1.size() != words2.size()) return false; map mymap; int k = 0; for (const auto& pair : pairs) { if (mymap.count(pair.first) == 0) { mymap[pair.first] = k++; } if (mymap.count(pair.second) == 0) { mymap[pair.second] = k++; } } UF uf(k); for (const auto& pair : pairs) { uf.Union(mymap[pair.first], mymap[pair.second]); } for (int i = 0; i < words1.size(); i++) { if (words1[i] == words2[i]) continue; if (mymap.count(words1[i]) == 0 || mymap.count(words2[i]) == 0) return false; if (!uf.connected(mymap[words1[i]], mymap[words2[i]])) return false; } return true; } }; ================================================ FILE: cpp/731-740/Sentence Similarity.cpp ================================================ class Solution { public: bool areSentencesSimilar(vector& words1, vector& words2, vector> pairs) { if (words1.size() != words2.size()) return false; map> mymap; for (const auto& pair : pairs) { mymap[pair.first].insert(pair.second); mymap[pair.second].insert(pair.first); } for (int i = 0; i < words1.size(); i++) { if (words1[i] == words2[i]) continue; if (mymap[words1[i]].count(words2[i]) == 0) return false; } return true; } }; ================================================ FILE: cpp/741-750/Closest Leaf in a Binary Tree.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { vector nodes[1001]; void dfs(TreeNode* root, int k) { if (!root) return; if (root-> left) { nodes[root->val].push_back(root->left->val); nodes[root->left->val].push_back(root->val); dfs(root->left, k); } if (root->right) { nodes[root->val].push_back(root->right->val); nodes[root->right->val].push_back(root->val); dfs(root->right, k); } } public: int findClosestLeaf(TreeNode* root, int k) { if (!root->left && !root->right) return root->val; dfs (root, k); queue myqueue; set visited; visited.insert(k); myqueue.push(k); while (!myqueue.empty()) { int e = myqueue.front(); myqueue.pop(); if (nodes[e].size() == 1 && e != root->val) return e; for (int t : nodes[e]) { if (visited.count(t) == 0) { myqueue.push(t); visited.insert(t); } } } return -1; } }; ================================================ FILE: cpp/741-750/Find Smallest Letter Greater Than Target.cpp ================================================ class Solution { public: char nextGreatestLetter(vector& letters, char target) { vector::iterator it = upper_bound(letters.begin(), letters.end(), target); if (it == letters.end()) return letters.front(); return *it; } }; class Solution { public: char nextGreatestLetter(vector& letters, char target) { if (target >= letters.back()) { return letters.front(); } int i = 0; int j = letters.size() - 1; while (i < j) { int mid = (i + j) / 2; if (target < letters[mid]) { j = mid; } else if (target >= letters[mid]) { i = mid + 1; } } return letters[i]; } }; ================================================ FILE: cpp/741-750/Largest Number At Least Twice of Others.cpp ================================================ class Solution { public: int dominantIndex(vector& nums) { int maxOne = 0, maxTwo = 0, idx = 0; for (int i = 0; i < nums.size(); i++) { if (maxOne < nums[i]) { maxTwo = maxOne; maxOne = nums[i]; idx = i; } else if (maxTwo < nums[i]) { maxTwo = nums[i]; } } return maxOne >= maxTwo * 2 ? idx : -1; } }; ================================================ FILE: cpp/741-750/Min Cost Climbing Stairs.cpp ================================================ class Solution { public: int minCostClimbingStairs(vector& cost) { int n = cost.size(); vector dp (n+1, 0); dp[0] = cost[0]; dp[1] = cost[1]; for (int i = 2; i < n; i++) { dp[i] = cost[i] + min(dp[i-2], dp[i-1]); } return min(dp[n-1], dp[n-2]); } }; ================================================ FILE: cpp/741-750/Network Delay Time.cpp ================================================ class Solution { public: int networkDelayTime(vector>& times, int N, int K) { // Bellman-Ford vector dist(N + 1, INT_MAX); dist[K] = 0; for (int i = 0; i < N; i++) { for (const vector& e : times) { int u = e[0], v = e[1], w = e[2]; if (dist[u] != INT_MAX && dist[v] > dist[u] + w) { dist[v] = dist[u] + w; } } } int maxwait = 0; for (int i = 1; i <= N; i++) maxwait = max(maxwait, dist[i]); return maxwait == INT_MAX ? -1 : maxwait; } }; ================================================ FILE: cpp/741-750/Number Of Corner Rectangles.cpp ================================================ class Solution { public: int countCornerRectangles(vector>& grid) { int ans = 0; for (int i = 0; i < grid.size() - 1; i++) { for (int j = i + 1; j < grid.size(); j++) { int counter = 0; for (int k = 0; k < grid[0].size(); k++) { if (grid[i][k] == 1 && grid[j][k] == 1) counter++; } if (counter > 0) ans += counter * (counter - 1) / 2; } } return ans; } }; ================================================ FILE: cpp/741-750/Prefix and Suffix Search.cpp ================================================ struct TrieNode { TrieNode *nodes[26]; bool word; // Initialize your data structure here. TrieNode(): word(false) { memset(nodes, 0, sizeof(nodes)); } }; class Trie { void dfs(TrieNode *tmp, unordered_set& words, string prefix) { if (tmp->word) { words.insert(prefix); } for (int i = 0; i < 26; i++) { if (tmp->nodes[i]) { char t = 'a' + i; dfs(tmp->nodes[i], words, prefix + t); } } } public: Trie() { root = new TrieNode(); } // Inserts a word into the trie. void insert(const string& s) { TrieNode *tmp = root; for(char ch : s) { int index = ch - 'a'; if(tmp->nodes[index] == nullptr) { tmp->nodes[index] = new TrieNode(); } tmp = tmp->nodes[index]; } tmp->word = true; } // Returns if the word is in the trie. unordered_set search(const string& prefix) { unordered_set result; TrieNode *tmp = root; for(char ch : prefix) { int index = ch - 'a'; if(tmp->nodes[index] == nullptr) { return result; } tmp = tmp->nodes[index]; } dfs(tmp, result, prefix); return result; } private: TrieNode* root; }; class WordFilter { Trie T1, T2; unordered_map weights; public: WordFilter(vector words) { int i = 0; for (string word: words) { weights[word] = i++; T1.insert(word); reverse(word.begin(), word.end()); T2.insert(word); } } int f(string prefix, string suffix) { unordered_set set1 = T1.search(prefix); reverse(suffix.begin(), suffix.end()); unordered_set set2 = T2.search(suffix); if (set1.empty() || set2.empty()) return -1; string ans; for (string str : set2) { reverse(str.begin(), str.end()); if (set1.count(str) > 0) { if (ans.empty()) { ans = str; } else if (weights[ans] < weights[str]) { ans = str; } } } if (ans.empty()) return -1; return weights[ans]; } }; /** * Your WordFilter object will be instantiated and called as such: * WordFilter obj = new WordFilter(words); * int param_1 = obj.f(prefix,suffix); */ ================================================ FILE: cpp/741-750/Shortest Completing Word.cpp ================================================ class Solution { public: string shortestCompletingWord(string licensePlate, vector& words) { transform(licensePlate.begin(), licensePlate.end(), licensePlate.begin(), ::tolower); int counts[26] = {0}; string ans = ""; for (char ch : licensePlate) { if (isalpha(ch)) { counts[ch - 'a']++; } } for (const string& word : words) { int temp[26] = {0}; for (char ch : word) { temp[ch - 'a']++; } bool match = true; for (int i = 0; i < 26; i++) { if (counts[i] > temp[i]) { match = false; break; } } if (match && ( ans.empty() || ans.length() > word.length() )) { ans = word; } } return ans; } }; ================================================ FILE: cpp/751-760/Bold Words in String.cpp ================================================ class Solution { private: vector> findpairs(const string& s, const vector& dict) { vector> res; for (const string& w : dict) { int n = w.size(); for (int i = 0; (i = s.find(w, i)) != string::npos; i++) { res.emplace_back(make_pair(i, i + n)); } } return res; } vector> merge(vector>& a) { vector> r; auto cmp = [&](const pair& a, const pair& b) { return a.first < b.first || a.first == b.first && a.second < b.second; }; sort(a.begin(), a.end(), cmp); for (int i = 0, j = -1; i < a.size(); i++) { if (j < 0 || a[i].first > r[j].second) { r.push_back(a[i]); j++; } else { r[j].second = max(r[j].second, a[i].second); } } return r; } public: string boldWords(vector& words, string S) { vector> ranges = findpairs(S, words); ranges = merge(ranges); for (auto it = ranges.rbegin(); it != ranges.rend(); it++) { S.insert(it->second, ""); S.insert(it->first, ""); } return S; } }; ================================================ FILE: cpp/751-760/Cracking the Safe.cpp ================================================ class Solution { bool dfs(int total, string& ans, int n, int k, bool* nodes) { if (total == 0) return true; ans += '0'; for (int d = 0; d < k; d++) { ans.back() = d + '0'; int t = stoi(ans.substr(ans.size()-n, n)); if (!nodes[t]) { nodes[t] = true; bool OK = dfs (total-1, ans, n, k, nodes); if (OK) { return true; } nodes[t] = false; } } ans.pop_back(); return false; } public: string crackSafe(int n, int k) { bool nodes[10000] = {false}; string ans(n, '0'); int total = pow(k, n); nodes[0] = true; dfs(total - 1, ans, n, k, nodes); return ans; } }; ================================================ FILE: cpp/751-760/Employee Free Time.cpp ================================================ /* // Definition for an Interval. class Interval { public: int start; int end; Interval() {} Interval(int _start, int _end) { start = _start; end = _end; } }; */ class Solution { public: vector employeeFreeTime(vector> schedule) { map mymap; for (const vector& s : schedule) { for (const Interval& i : s) { mymap[i.start]++; mymap[i.end]--; } } int last = -1; int cnt = 0; vector ans; for (const auto& pair : mymap) { int pcnt = cnt; cnt += pair.second; if (pcnt == 0 && last != -1) { Interval in(last, pair.first); ans.push_back(in); } else if (cnt == 0) { last = pair.first; } } return ans; } }; ================================================ FILE: cpp/751-760/Find Anagram Mappings.cpp ================================================ class Solution { public: vector anagramMappings(vector& A, vector& B) { map mymap; for (int i = 0; i < B.size(); i++) { mymap[B[i]] = i; } vector result(A.size()); for (int i = 0; i < A.size(); i++) { result[i] = mymap[A[i]]; } return result; } }; ================================================ FILE: cpp/751-760/IP to CIDR.cpp ================================================ class Solution { vector split(const string &s, char delim) { vector elems; stringstream ss(s); string item; while (getline(ss, item, delim)) { if (item.length() > 0) { elems.push_back(item); } } return elems; } string construct(long x, long rightMost) { vector ans(4); ans[0] = to_string(x & 255); x >>= 8; ans[1] = to_string(x & 255); x >>= 8; ans[2] = to_string(x & 255); x >>= 8; ans[3] = to_string(x); int len = 33; while (rightMost > 0) { len --; rightMost /= 2; } return ans[3] + "." + ans[2] + "." + ans[1] + "." + ans[0] + "/" + to_string(len); } public: vector ipToCIDR(string ip, int n) { vector digits = split(ip, '.'); long start = stol(digits[0])*256*256*256 + stol(digits[1])*256*256 + stol(digits[2])*256 + stol(digits[3]); vector ans; while (n > 0) { long rightMost = start == 0 ? 1 << 30 : start & -start; while (rightMost > n) rightMost /= 2; ans.push_back(construct(start, rightMost)); n -= rightMost; start += rightMost; } return ans; } }; ================================================ FILE: cpp/751-760/Open the Lock.cpp ================================================ class Solution { string transform(string str, int index, int sign) { int i = str[index] - '0'; if (sign > 0) i = (i + 1)%10; else i = (i + 9)%10; char ch = i + '0'; str[index] = ch; return str; } public: int openLock(vector& deadends, string target) { queue> myqueue; set deadset(deadends.begin(), deadends.end()); set visited; if (deadset.count("0000") == 0) myqueue.push({"0000", 0}); while (!myqueue.empty()) { auto ele = myqueue.front(); myqueue.pop(); if (ele.first == target) { return ele.second; } visited.insert(ele.first); for (int i = 0; i < 4; i++) { for (int sign = 0; sign < 2; sign++) { string str = transform(ele.first, i, sign); if (deadset.count(str) == 0 && visited.count(str) == 0) { visited.insert(str); myqueue.push({str, ele.second + 1}); } } } } return -1; } }; ================================================ FILE: cpp/751-760/Pour Water.cpp ================================================ class Solution { public: vector pourWater(vector& heights, int V, int K) { for (int i = 0; i < V; i++) { // try left int candidateHeight = heights[K]; int candidateIndex = K; int j = K - 1; while(j >= 0 && heights[j] <= candidateHeight) { if (heights[j] < candidateHeight) { candidateHeight = heights[j]; candidateIndex = j; } j--; } // try right if (candidateIndex == K) { j = K + 1; while(j < heights.size() && heights[j] <= candidateHeight) { if (heights[j] < candidateHeight) { candidateHeight = heights[j]; candidateIndex = j; } j++; } } heights[candidateIndex]++; } return heights; } }; ================================================ FILE: cpp/751-760/Pyramid Transition Matrix.cpp ================================================ class Solution { bool dfs (vector>& pyramid, map, set>& allowed, int i, int j) { if (i < 0) return true; char ch1 = pyramid[i+1][j]; char ch2 = pyramid[i+1][j+1]; auto key = make_pair(ch1, ch2); if (allowed.count(key) == 0) return false; set chars = allowed[key]; for (char ch : chars) { pyramid[i][j] = ch; int nexti, nextj; if (i == j) { nexti = i - 1; nextj = 0; } else { nexti = i; nextj = j + 1; } if(dfs(pyramid, allowed, nexti, nextj)) return true; } return false; } public: bool pyramidTransition(string bottom, vector& allowed) { map, set> myallowed; for (string str : allowed) { myallowed[{str[0], str[1]}].insert(str[2]); } int n = bottom.length(); vector> pyramid(n, vector(n)); for (int i = 0; i < n; i++) { pyramid[n-1][i] = bottom[i]; } return dfs(pyramid, myallowed, n-2, 0); } }; ================================================ FILE: cpp/751-760/Reach a Number.cpp ================================================ class Solution { public: int reachNumber(int target) { target = abs(target); int n = 1; while (target > 0) { target -= n; n++; } if (target %2 == 0) return n - 1; if (n % 2 == 1) return n; return n + 1; } }; ================================================ FILE: cpp/751-760/Set Intersection Size At Least Two.cpp ================================================ class Solution { public: int intersectionSizeTwo(vector>& intervals) { auto comp = [](const vector& p1, const vector& p2) { return p1[1] < p2[1] || (p1[1] == p2[1] && p1[0] > p2[0]); }; sort(intervals.begin(), intervals.end(), comp); int n = intervals.size(); vector count(n, 2); int ans = 0; int end = -1; for (int i = 0; i < n; i++) { if (count[i] == 0) continue; ans += count[i]; for (int j = i+1; j < n; j++) { if (count[j] > 0) { if (count[i] == 2) { int overlap = intervals[i][1] - intervals[j][0] + 1; if (overlap > 0) { count[j] -= overlap; count[j] = max(0, count[j]); } } else if (count[i] == 1) { int overlap = intervals[i][1] >= intervals[j][0] ? 1 : 0; count[j] -= overlap; } } } } return ans; } }; ================================================ FILE: cpp/761-770/Couples Holding Hands.cpp ================================================ class Solution { int getMatch(int a) { if (a % 2 == 0) { return a + 1; } else { return a - 1; } } bool match(int a, int b) { return getMatch(a) == b; } public: int minSwapsCouples(vector& row) { int ans = 0; map mymap; for (int i = 0; i < row.size(); i ++) { mymap[row[i]] = i; } vector visited(row.size()/2, false); for (int i = 0; i < row.size(); i += 2) { if (match(row[i], row[i+1])) continue; int loop = 0; int copy_i = i; while (true) { int virtual_index = copy_i / 2; if (visited[virtual_index]) break; visited[virtual_index] = true; int mismatch = row[copy_i]; int match = getMatch(mismatch); int match_index = mymap[match]; loop++; copy_i = getMatch(match_index); } ans += loop > 0 ? (loop - 1) : 0; } return ans; } }; ================================================ FILE: cpp/761-770/Largest Plus Sign.cpp ================================================ class Solution { public: int orderOfLargestPlusSign(int N, vector>& mines) { set> myset; for (const auto& mine : mines) { myset.insert({mine[0], mine[1]}); } vector> left (N, vector(N, 0)); vector> right (N, vector(N, 0)); vector> up (N, vector(N, 0)); vector> down (N, vector(N, 0)); for (int i = 0; i < N; i++) { int temp = 0; for (int j = 0; j < N; j++) { if (myset.count({i, j}) > 0) { temp = 0; } else { temp++; } left[i][j] = temp; } } for (int i = 0; i < N; i++) { int temp = 0; for (int j = N-1; j >= 0; j--) { if (myset.count({i, j}) > 0) { temp = 0; } else { temp++; } right[i][j] = temp; } } for (int i = 0; i < N; i++) { int temp = 0; for (int j = 0; j < N; j++) { if (myset.count({j, i}) > 0) { temp = 0; } else { temp++; } up[j][i] = temp; } } for (int i = 0; i < N; i++) { int temp = 0; for (int j = N-1; j >= 0; j--) { if (myset.count({j, i}) > 0) { temp = 0; } else { temp++; } down[j][i] = temp; } } int ans = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { int current = min(left[i][j], right[i][j]); current = min(up[i][j], current); current = min(down[i][j], current); ans = max(ans, current); } } return ans; } }; ================================================ FILE: cpp/761-770/Max Chunks To Make Sorted II.cpp ================================================ class Solution { public: int maxChunksToSorted(vector& arr) { int n = arr.size(); vector leftMax(n, arr[0]); vector rightMin(n, arr[n-1]); for (int i = 1; i < n; i++) { leftMax[i] = max(leftMax[i-1], arr[i]); } for (int i = n - 2; i >= 0; i--) { rightMin[i] = min(rightMin[i+1], arr[i]); } int result = 0; for (int i = 0; i < n; i++) { if (i == n - 1) { result++; } else if (rightMin[i + 1] >= leftMax[i]) { result++; } } return result; } }; ================================================ FILE: cpp/761-770/Max Chunks To Make Sorted.cpp ================================================ class Solution { public: int maxChunksToSorted(vector& arr) { int result = 0; int temp_max = arr[0]; for (int i = 0; i < arr.size(); i++) { temp_max = max(temp_max, arr[i]); if (temp_max == i) { result++; } } return result; } }; ================================================ FILE: cpp/761-770/Partition Labels.cpp ================================================ class Solution { public: vector partitionLabels(string S) { map mymap; for (int i = 0; i < S.length(); i++) { mymap[S[i]] = i; } vector ans; int maximum_pos = 0; int last = -1; for (int i = 0; i < S.length(); i++) { char ch = S[i]; maximum_pos = max(maximum_pos, mymap[ch]); if (i == maximum_pos) { ans.push_back(i - last); last = i; } } return ans; } }; ================================================ FILE: cpp/761-770/Prime Number of Set Bits in Binary Representation.cpp ================================================ class Solution { public: int countPrimeSetBits(int L, int R) { set primes = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; int cnt = 0; for (int i = L; i <= R; i++) { int bits = 0; for (int n = i; n; n >>= 1) bits += n & 1; cnt += primes.count(bits); } return cnt; } }; ================================================ FILE: cpp/761-770/Reorganize String.cpp ================================================ class Solution { public: string reorganizeString(string S) { map mymap; for (char ch : S) { mymap[ch]++; if (mymap[ch] > (S.length() + 1) / 2) return ""; } auto cmp = [](const pair &a, const pair &b) { return a.first < b.first; }; priority_queue, vector>, decltype(cmp)> pq(cmp); for (const auto& e : mymap) { pq.push({e.second, e.first}); } string ans; while (!pq.empty()) { pair first = pq.top(); pq.pop(); ans += first.second; if (!pq.empty()) { pair second = pq.top(); pq.pop(); ans += second.second; if (first.first > 1) pq.push({first.first - 1, first.second}); if (second.first > 1) pq.push({second.first - 1, second.second}); } } return ans; } }; ================================================ FILE: cpp/761-770/Special Binary String.cpp ================================================ class Solution { static bool cmp(const string& a, const string& b) { return a > b; } public: string makeLargestSpecial(string S) { if (S.length() == 0) return ""; int cnt = 0; vector groups; int start = 0; for (int i = 0; i < S.length(); i++) { if (S[i] == '1') { cnt++; } else { cnt--; } if (cnt == 0) { groups.push_back("1" + makeLargestSpecial(S.substr(start + 1, i - start - 1)) + "0"); start = i + 1; } } sort(begin(groups), end(groups), cmp); string result; result = accumulate(begin(groups), end(groups), result); return result; } }; ================================================ FILE: cpp/761-770/Toeplitz Marix.cpp ================================================ class Solution { public: bool isToeplitzMatrix(vector>& matrix) { for (int r = 0; r < matrix.size(); r++) for (int c = 0; c < matrix[0].size(); c++) if (r > 0 && c > 0 && matrix[r-1][c-1] != matrix[r][c]) return false; return true; } }; ================================================ FILE: cpp/771-780/Basic Calculator III.cpp ================================================ class Solution { void apply(stack&s, char c) { int b = s.top();s.pop(); int a = s.top();s.pop(); if(c == '+') s.push(a+b); else if(c == '-') s.push(a-b); else if(c == '*') s.push(a*b); else s.push(a/b); } public: int calculate(string s) { stack symbol; stackss; int v = 0; bool number = false; for (char e : s) { if (number && !isdigit(e)) { ss.push(v); v = 0; number = false; } if (e == ' ') continue; else if (e == ')') { while (symbol.top() != '(') { char c = symbol.top(); apply(ss, c); symbol.pop(); } symbol.pop(); } else if (e == '(') { symbol.push('('); } else if (isdigit(e)) { v = 10*v + (e-'0'); number = true; } else if (e == '+' || e == '-') { while (!symbol.empty() && (symbol.top() == '*' || symbol.top() == '/' || symbol.top() == '+' || symbol.top() == '-')) { char c = symbol.top(); symbol.pop(); apply(ss, c); } symbol.push(e); } else if (e == '*' || e == '/') { while (!symbol.empty() && (symbol.top() == '*' || symbol.top() == '/') ) { char c = symbol.top(); symbol.pop(); apply(ss, c); } symbol.push(e); } } if (number) { ss.push(v); } while (!symbol.empty()) { char c = symbol.top(); apply(ss,c); symbol.pop(); } return ss.top(); } }; ================================================ FILE: cpp/771-780/Global and Local Inversions.cpp ================================================ class Solution { public: bool isIdealPermutation(vector& A) { vector dp(A.size(), 0); dp[0] = A[0]; for (int i = 1; i < A.size(); i++) { dp[i] = max(dp[i-1], A[i]); } for (int i = 2; i < A.size(); i++) { if (A[i] < dp[i-2]) { return false; } } return true; } }; ================================================ FILE: cpp/771-780/Jewels and Stones.cpp ================================================ class Solution { public: int numJewelsInStones(string J, string S) { set jewel; for (char ch : J) jewel.insert(ch); int ans = 0; for (char ch : S) { if (jewel.count(ch) > 0) { ans++; } } return ans; } }; ================================================ FILE: cpp/771-780/K-th Symbol in Grammar.cpp ================================================ class Solution { public: int kthGrammar(int N, int K) { if (N == 1) return 0; if (N == 2) { if (K == 1) return 0; return 1; } int temp = kthGrammar(N-1, (K+1)/2); if (K % 2 == 1) return temp; return (temp+1)%2; } }; ================================================ FILE: cpp/771-780/Minimize Max Distance to Gas Station.cpp ================================================ class Solution { public: double minmaxGasDist(vector& stations, int K) { int maxGap = 0; for (int i = 1; i < stations.size(); i++) { maxGap = max(maxGap, stations[i] - stations[i-1]); } double lower = 0, upper = maxGap; while (upper - lower >= 1e-6) { double mid = (lower + upper) / 2; int num = 0; for (int i = 1; i < stations.size(); i++) { num += ceil((stations[i] - stations[i-1]) / mid) - 1; } if (num > K) { lower = mid; } else { upper = mid; } } return upper; } }; ================================================ FILE: cpp/771-780/Sliding Puzzle.cpp ================================================ class Solution { int seralize(vector>& board) { int result = 0; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { result = result * 10 + board[i][j]; } } return result; } public: int slidingPuzzle(vector>& board) { int goal = 123450; int mi = 0, mj = 0; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { if (board[i][j] == 0) { mi = i; mj = j; } } } queue>>>myqueue; myqueue.push({0, board}); setvisited; while (!myqueue.empty()) { pair>> e = myqueue.front(); myqueue.pop(); int key = seralize(e.second); if (key == goal) { return e.first; } if (visited.count(key) > 0) continue; visited.insert(key); vector> myboard = e.second; int ii, jj; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { if (myboard[i][j] == 0) { ii = i; jj = j; } } } pair mypair[4] = {{1,0}, {-1, 0}, {0,-1}, {0,1}}; for (int i = 0; i < 4; i++) { int ni = ii + mypair[i].first; int nj = jj + mypair[i].second; if (ni < 0 || nj < 0 || ni >= 2 || nj >= 3) continue; vector> Tboard = myboard; Tboard[ii][jj] = Tboard[ni][nj]; Tboard[ni][nj] = 0; myqueue.push({e.first + 1, Tboard}); } } return -1; } }; ================================================ FILE: cpp/771-780/Split BST.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector splitBST(TreeNode* root, int V) { if (root == nullptr) { return vector {nullptr, nullptr}; } else if (root->val <= V) { vector result = splitBST(root->right, V); root->right = result[0]; result[0] = root; return result; } else { vector result = splitBST(root->left, V); root->left = result[1]; result[1] = root; return result; } } }; ================================================ FILE: cpp/771-780/Swap Adjacent in LR String.cpp ================================================ class Solution { public: bool canTransform(string start, string end) { string s, t; for (char ch : start) { if (ch != 'X') { s += ch; } } for (char ch : end) { if (ch != 'X') { t += ch; } } if (s != t) return false; int sR = 0, sL = 0, eR = 0, eL = 0; for (int i = 0; i < start.length(); i++) { if (start[i] == 'L') sL++; if (start[i] == 'R') sR++; if (end[i] == 'R') eR++; if (end[i] == 'L') eL++; if (eR > sR) return false; if (sL > eL) return false; } return true; } }; ================================================ FILE: cpp/771-780/Swim in Rising Water.cpp ================================================ class Solution { public: int swimInWater(vector>& grid) { int N = grid.size(); int ans = 0; auto cmp = [](const pair> &a, pair> &b) { return a.first > b.first; }; priority_queue>, vector>>, decltype(cmp)> pq(cmp); pair> start{grid[0][0], {0, 0}}; pq.push(start); set visited; while (!pq.empty()) { pair> current = pq.top(); pq.pop(); ans = max(ans, current.first); visited.insert(current.second.first * 10000 + current.second.second); if(current.second.first == N - 1 && current.second.second == N - 1) { break; } pair mypair[4] = {{1, 0}, {-1, 0}, {0,1}, {0,-1}}; for (pair pos : mypair) { int nexti = current.second.first + pos.first; int nextj = current.second.second + pos.second; if (nexti < 0 || nextj < 0 || nexti >= N || nextj >= N) continue; if (visited.count(nexti * 10000 + nextj) > 0) continue; pq.push({grid[nexti][nextj], {nexti, nextj}}); } } return ans; } }; ================================================ FILE: cpp/781-790/Cheapest Flights Within K Stops.cpp ================================================ class Solution { public: int findCheapestPrice(int n, vector>& flights, int src, int dst, int K) { vector dis(n, -1); dis[src] = 0; for (int i = 0; i <= K; i++) { vector copy(dis); for (const vector& flight : flights) { int u = flight[0]; int v = flight[1]; int cost = flight[2]; if (copy[u] < 0) continue; if (dis[v] < 0) dis[v] = copy[u] + cost; else dis[v] = min(dis[v], copy[u] + cost); } } return dis[dst]; } }; ================================================ FILE: cpp/781-790/Escape The Ghosts.cpp ================================================ class Solution { int dis(int x, int y) { return abs(x) + abs(y); } public: bool escapeGhosts(vector>& ghosts, vector& target) { int temp = dis(target[0], target[1]); for (const auto& ghost : ghosts) { if (dis(target[0] - ghost[0], target[1] - ghost[1]) <= temp) return false; } return true; } }; ================================================ FILE: cpp/781-790/Is Graph Bipartite?.cpp ================================================ class Solution { bool dfs(int node, vector& colors, const vector>& graph, int c) { colors[node] = c; for (int neighbor : graph[node]) { if (colors[neighbor] == c) { return false; } if (colors[neighbor] == 0 && !dfs(neighbor, colors, graph, 3 - c)) { return false; } } return true; } public: bool isBipartite(vector>& graph) { int n = graph.size(); vector colors(n, 0); for (int i = 0; i < n; i++) if (colors[i] == 0) if(!dfs(i, colors, graph, 1)) return false; return true; } }; ================================================ FILE: cpp/781-790/K-th Smallest Prime Fraction.cpp ================================================ class Solution { public: vector kthSmallestPrimeFraction(vector& A, int K) { auto cmp = [](const vector &a, const vector &b) { return a[0]*b[1] > b[0]*a[1]; }; priority_queue, vector>, decltype(cmp)> pq(cmp); for (int i = 1; i < A.size(); i++) { vector temp {1, A[i], 0}; pq.push(temp); } while (--K) { vector top = pq.top(); pq.pop(); int nindex = top[2] + 1; int next = A[nindex]; if (next >= top[1]) continue; vector temp {next, top[1], nindex}; pq.push(temp); } return vector {pq.top()[0], pq.top()[1]}; } }; ================================================ FILE: cpp/781-790/Letter Case Permutation.cpp ================================================ class Solution { void dfs(string S, int i, vector& result) { if (i == S.length()) { result.push_back(S); return; } if (isdigit(S[i])) { dfs(S, i+1, result); } else { S[i] = tolower(S[i]); dfs(S, i+1, result); S[i] = toupper(S[i]); dfs(S, i+1, result); } } public: vector letterCasePermutation(string S) { vector result; dfs(S, 0, result); return result; } }; ================================================ FILE: cpp/781-790/Minimum Distance Between BST Nodes.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { void dfs(TreeNode* root, int &pv, int& result) { if (!root) return; dfs(root->left, pv, result); if (pv != INT_MIN) result = min(result, abs(pv - root->val)); pv = root->val; dfs(root->right, pv, result); } public: int minDiffInBST(TreeNode* root) { int pv = INT_MIN; int result = INT_MAX; dfs(root, pv, result); return result; } }; ================================================ FILE: cpp/781-790/Rabbits in Forest.cpp ================================================ class Solution { public: int numRabbits(vector& answers) { unordered_map mymap; int ans = 0; for (int e : answers) { if (mymap[e] == 0) { ans += (e+1); mymap[e] = e; } else { mymap[e]--; } } return ans; } }; ================================================ FILE: cpp/781-790/Rotated Digits.cpp ================================================ class Solution { bool isValid(int N) { bool validFound = false; while (N > 0) { int lastDigit = N % 10; if (lastDigit == 2 || lastDigit == 5 || lastDigit == 6 || lastDigit == 9) validFound = true; if (lastDigit == 3 || lastDigit == 4 || lastDigit == 7) return false; N = N / 10; } return validFound; } public: int rotatedDigits(int N) { int count = 0; for (int i = 1; i <= N; i ++) { if (isValid(i)) count++; } return count; } }; ================================================ FILE: cpp/781-790/Transform to Chessboard.cpp ================================================ class Solution { unsigned int countSetBits(unsigned int n) { unsigned int count = 0; while (n) { count += n & 1; n >>= 1; } return count; } public: int movesToChessboard(vector>& board) { int n = board.size(); map mymap; for (const vector& row : board) { int num = 0; for (int e : row) { num = 2*num + e; } mymap[num]++; } int c1 = check(mymap, n); if (c1 < 0) return -1; map mymap2; for (int i = 0; i < n; i++) { int num = 0; for (int j = 0; j < n; j++) { num = 2*num + board[j][i]; } mymap2[num]++; } int c2 = check(mymap2, n); if (c2 < 0) return -1; return c1 + c2; } int check(map& mymap, int n) { if (mymap.size() != 2) return -1; int nOne = (1 << n) - 1; int key1 = -1, key2 = -1; // get the two key for (auto it : mymap) { if (key1 == -1) { key1 = it.first; } else { key2 = it.first; } } if ((key1 ^ key2) != nOne) return -1; if (abs(mymap[key1] - mymap[key2]) > 1) return -1; if (n%2 == 1) { int totalOne = countSetBits(key1); if (totalOne == n / 2) return countSetBits(key1 ^ (0xAAAAAAAA&nOne))/2; else return countSetBits(key1 ^ (0x55555555&nOne))/2; } return (min(countSetBits(key1 ^ (0xAAAAAAAA&nOne)), countSetBits(key1 ^ (0x55555555&nOne))) + 1)/2; } }; ================================================ FILE: cpp/791-800/All Paths From Source to Target.cpp ================================================ class Solution { void dfs(int current, int target, vector path, const vector>& graph, vector>& result) { if (current == target) { result.emplace_back(path); return; } for (int e : graph[current]) { vector pathCopy(path); pathCopy.push_back(e); dfs(e, target, pathCopy, graph, result); } } public: vector> allPathsSourceTarget(vector>& graph) { vector> result; int n = graph.size(); vector vec{0}; dfs(0, n-1, vec, graph, result); return result; } }; ================================================ FILE: cpp/791-800/Champagne Tower.cpp ================================================ class Solution { public: double champagneTower(int poured, int query_row, int query_glass) { vector> myvec (query_row+2, vector(query_row+3, 0)); myvec[0][0] = poured; for (int i = 0; i <= query_row; i++) { for (int j = 0; j <= i; j++) { double overflow = fmax(myvec[i][j] - 1, 0); myvec[i][j] -= overflow; myvec[i+1][j] += overflow/2; myvec[i+1][j+1] += overflow/2; } } return myvec[query_row][query_glass]; } }; ================================================ FILE: cpp/791-800/Custom Sort String.cpp ================================================ class Solution { public: string customSortString(string S, string T) { map mymap; for (char ch : T) mymap[ch]++; string result; for (char ch : S) { string temp(mymap[ch], ch); result += temp; mymap[ch] = 0; } for (const auto& it : mymap) { if (it.second > 0) { string temp(it.second, it.first); result += temp; } } return result; } }; ================================================ FILE: cpp/791-800/Number of Matching Subsequences.cpp ================================================ class Solution { public: int numMatchingSubseq(string S, vector& words) { vector waiting[128]; for (auto &w : words) waiting[w[0]].push_back(w.c_str()); for (char c : S) { vector advance = waiting[c]; waiting[c].clear(); for (const char* it : advance) waiting[*++it].push_back(it); } return waiting[0].size(); } }; ================================================ FILE: cpp/791-800/Number of Subarrays with Bounded Maximum.cpp ================================================ class Solution { public: int numSubarrayBoundedMax(vector& A, int L, int R) { int count = 0, ans = 0; int previous = 0; for (int i = 0; i < A.size(); i++) { if (A[i] >= L && A[i] <= R) { count = 1 + i - previous; ans += count; } else if (A[i] < L) { ans += count; } else { previous = i + 1; count = 0; } } return ans; } }; ================================================ FILE: cpp/791-800/Preimage Size of Factorial Zeroes Function.cpp ================================================ class Solution { public: int preimageSizeFZF(long K) { long a = 1; while (K >= 5*a + 1) a = 5*a + 1; cout << a << endl; while (K >= 6) { if (K % a == 0) { if (K == 5*a) { return 0; } else { return 5; } } K = K % a; a = (a-1)/5; } if (K == 5) return 0; return 5; } }; // 1 1 1 1 2 1 1 1 1 2 1 1 1 1 2 1 1 1 1 2 1 1 1 1 3 // 12 30 ================================================ FILE: cpp/791-800/Rotate String ================================================ class Solution { public: bool rotateString(string A, string B) { string AA = A + A; if (AA.find(B) != string::npos) return true; return false; } }; ================================================ FILE: cpp/791-800/Similar RGB Color.cpp ================================================ class Solution { string helper(string str) { string dec_to_hex = "0123456789abcdef"; int dec_num = stoi(str, nullptr, 16); int q = (dec_num+8) / 17; string res(2, dec_to_hex[q]); return res; } public: string similarRGB(string color) { return "#" + helper(color.substr(1, 2)) + helper(color.substr(3, 2)) + helper(color.substr(5, 2)); } }; ================================================ FILE: cpp/791-800/Valid Tic-Tac-Toe State.cpp ================================================ class Solution { public: bool validTicTacToe(vector& board) { vector rowSum(3, 0); vector colSum(3, 0); int dig1 = 0, dig2 = 0; int numX = 0, numO = 0; int winX = 0, winO = 0; for (int i = 0; i < 3; i++) { string str = board[i]; for (int j = 0; j < str.length(); j++) { if (str[j] == 'X') { numX++; rowSum[i]++; colSum[j]++; if (i == j) dig1++; if (i + j == 2) dig2++; } else if (str[j] == 'O') { numO++; rowSum[i]--; colSum[j]--; if (i == j) dig1--; if (i + j == 2) dig2--; } if (rowSum[i] == 3) winX++; if (colSum[j] == 3) winX++; if (dig1 == 3) winX++; if (dig2 == 3) winX++; if (rowSum[i] == -3) winO++; if (colSum[j] == -3) winO++; if (dig1 == -3) winO++; if (dig2 == -3) winO++; if (winX > 0 && winO > 0) return false; } } if (winX > 0) { if (numX != numO + 1) return false; } else if (winO > 0) { if (numX != numO) return false; } if (numO > numX || numX - numO >= 2) return false; return true; } }; ================================================ FILE: cpp/801-810/Bricks Falling When Hit.cpp ================================================ class UF { private: vector parent; vector rank; vector size; int N; public: UF(int N) : parent(N), rank(N, 0), size(N, 1), N(N) { for (int i = 0; i < N; i++) { parent[i] = i; } } int find(int p) { while (p != parent[p]) { parent[p] = parent[parent[p]]; // path compression by halving p = parent[p]; } return p; } bool connected(int p, int q) { return find(p) == find(q); } int getSize(int p) { return size[find(p)]; } void Union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make root of smaller rank point to root of larger rank if (rank[rootP] < rank[rootQ]) { parent[rootP] = rootQ; size[rootQ] += size[rootP]; } else if (rank[rootP] > rank[rootQ]) { parent[rootQ] = rootP; size[rootP] += size[rootQ]; } else { parent[rootQ] = rootP; size[rootP] += size[rootQ]; rank[rootP]++; } } }; class Solution { public: vector hitBricks(vector>& grid, vector>& hits) { int m = grid.size(); int n = grid.front().size(); int root = m * n; UF uf (m*n+1); vector> gridCopy(grid); for (const vector& hit : hits) { gridCopy[hit[0]][hit[1]] = 0; } pair pos[4] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; for (int i = 0; i < n; i++) { if (gridCopy[0][i] == 1) { uf.Union(root, i); } } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (gridCopy[i][j] == 0) continue; for (auto it : pos) { int ni = i + it.first; int nj = j + it.second; if (ni < 0 || ni >= m || nj < 0 || nj >= n || gridCopy[ni][nj] == 0) continue; uf.Union(i*n+j, ni*n+nj); } } } vector ans(hits.size(), 0); for (int k = hits.size() - 1; k >= 0; k--) { int x = hits[k][0]; int y = hits[k][1]; if (grid[x][y] == 0) continue; int count = uf.getSize(root); for (auto it : pos) { int nx = x + it.first; int ny = y + it.second; if (nx < 0 || nx >= m || ny < 0 || ny >= n || gridCopy[nx][ny] == 0) continue; uf.Union(x*n+y, nx*n+ny); } if (x == 0) uf.Union(root, y); gridCopy[x][y] = 1; ans[k] = max(0, uf.getSize(root) - count - 1); } return ans; } }; ================================================ FILE: cpp/801-810/Chalkboard XOR Game.cpp ================================================ class Solution { public: bool xorGame(vector& nums) { int x = 0; for (int v : nums) x ^= v; return x == 0 || nums.size() % 2 == 0; } }; ================================================ FILE: cpp/801-810/Expressive Words.cpp ================================================ class Solution { public: int expressiveWords(string S, vector& words) { int ans = 0; int ls = S.length(); for (const string& word : words) { int i(0), j(0); int lw = word.length(); bool ok = true; while (i < ls && j < lw) { if (S[i] != word[j]) { ok = false; break; } int numS = 1, numW = 1; while (i+1 < ls && S[i] == S[i+1]) { numS++; i++; } while (j+1 < lw && word[j] == word[j+1]) { numW++; j++; } if (numS < numW) { ok = false; break; } if (numS > numW && numS < 3) { ok = false; break; } i++; j++; } if (ok && i == ls && j == lw) ans++; } return ans; } }; ================================================ FILE: cpp/801-810/Find Eventual Safe States.cpp ================================================ class Solution { bool dfs(int i, const vector>& graph, vector& colors) { if (colors[i] == 2) return true; if (colors[i] == 1) return false; colors[i] = 1; for (int v : graph[i]) { if (!dfs(v, graph, colors)) { return false; } } colors[i] = 2; return true; } public: vector eventualSafeNodes(vector>& graph) { int n = graph.size(); vector colors(n, 0); vector ans; for (int i = 0; i < graph.size(); i++) { if (dfs(i, graph, colors)) { ans.push_back(i); } } return ans; } }; ================================================ FILE: cpp/801-810/Max Increase to Keep City Skyline.cpp ================================================ class Solution { public: int maxIncreaseKeepingSkyline(vector>& grid) { int n = grid.size(); vector col(n, 0), row(n, 0); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { row[i] = max(row[i], grid[i][j]); col[j] = max(col[j], grid[i][j]); } } int res = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) res += min(row[i], col[j]) - grid[i][j]; return res; } }; ================================================ FILE: cpp/801-810/Minimum Swaps To Make Sequences Increasing.cpp ================================================ class Solution { public: int minSwap(vector& A, vector& B) { // int nswap (no swap), swap // if size == 1, at the beginning, it must be true. int nswap = 0, swap = 1; for (int i = 1; i < A.size(); i++) { int temp_nswap = INT_MAX, temp_swap = INT_MAX; if (A[i] > A[i-1] && B[i] > B[i-1]) { temp_nswap = nswap; temp_swap = swap + 1; } if (A[i] > B[i-1] && B[i] > A[i-1]) { temp_nswap = min(temp_nswap, swap); temp_swap = min(temp_swap, nswap + 1); } nswap = temp_nswap; swap = temp_swap; } return min(nswap, swap); } }; ================================================ FILE: cpp/801-810/Number of Lines To Write String.cpp ================================================ class Solution { public: vector numberOfLines(vector& widths, string S) { int res = 1, cur = 0; for (char c : S) { int width = widths[c - 'a']; res = cur + width > 100 ? res + 1 : res; cur = cur + width > 100 ? width : cur + width; } return {res, cur}; } }; ================================================ FILE: cpp/801-810/Soup Servings.cpp ================================================ class Solution { double dfs(int A, int B, map, double>& mymap) { if (A <= 0 && B > 0) return 1; if (A <= 0 && B <= 0) return 0.5; if (B <= 0) return 0; pair mypair = make_pair(A, B); if (mymap.count(mypair)) { return mymap[mypair]; } double res = 0.25 * (dfs(A-4, B, mymap) + dfs(A-3, B-1, mymap) + dfs(A-2, B-2, mymap) + dfs(A-1, B-3, mymap)); return mymap[mypair] = res; } public: double soupServings(int N) { N = (N + 24)/25; if (N >= 200) return 1.0; map, double> mymap; return dfs(N, N, mymap); } }; ================================================ FILE: cpp/801-810/Unique Morse Code Words.cpp ================================================ class Solution { public: int uniqueMorseRepresentations(vector& words) { vector d = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."}; set s; for (const auto& word : words) { string code; for (auto c : word) code += d[c - 'a']; s.insert(code); } return s.size(); } }; ================================================ FILE: cpp/811-820/Ambiguous Coordinates.cpp ================================================ class Solution { // 1.0 -> false // 0001 -> false // 0.0 bool valid(const string& str) { string part1(str), part2; int idx = str.find('.'); if (idx >= 0) { part1 = str.substr(0, idx); part2 = str.substr(idx + 1); } if (part1.length() != to_string(stol(part1)).length()) return false; if (part2.length() > 0) { if (stol(part2) == 0) return false; reverse(part2.begin(), part2.end()); if (part2.length() != to_string(stol(part2)).length()) return false; } return true; } // Given a string, return all possible results // 123 -> [1.23, 12.3, 123] vector make(const string& str) { vector result; for (int i = 1; i < str.length(); i++) { string temp(str); temp.insert(i, 1, '.'); if (valid(temp)) result.push_back(temp); } if (valid(str)) result.push_back(str); return result; } public: vector ambiguousCoordinates(string S) { vector result; int len = S.length(); for (int i = 1; i < S.length() - 2; i++) { string leftStr = S.substr(1, i); string rightStr = S.substr(i+1, len - 2 - i); vector left = make(leftStr); vector right = make(rightStr); for (const string& ls : left) { for (const string& rs : right) { string ans = "(" + ls + ", " + rs + ")"; result.push_back(ans); } } } return result; } }; ================================================ FILE: cpp/811-820/Binary Tree Pruning.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* pruneTree(TreeNode* root) { if (!root) return nullptr; root->left = pruneTree(root->left); root->right = pruneTree(root->right); if(root->left || root->right || root->val == 1) return root; return nullptr; } }; ================================================ FILE: cpp/811-820/Bus Routes.cpp ================================================ class Solution { public: int numBusesToDestination(vector>& routes, int S, int T) { unordered_map> to_routes; for (int i = 0; i < routes.size(); ++i) for (auto& j : routes[i]) to_routes[j].insert(i); queue> bfs; bfs.push(make_pair(S, 0)); unordered_set seen = {S}; while (!bfs.empty()) { int stop = bfs.front().first; int bus = bfs.front().second; bfs.pop(); if (stop == T) return bus; for (const auto& route_i : to_routes[stop]) for (int next_stop : routes[route_i]) if (seen.find(next_stop) == seen.end()) { seen.insert(next_stop); bfs.push(make_pair(next_stop, bus + 1)); } } return -1; } }; ================================================ FILE: cpp/811-820/Largest Sum of Averages.cpp ================================================ class Solution { public: double largestSumOfAverages(vector& A, int K) { int n = A.size(); vector> dp(n+1, vector(K+1, 0)); for (int i = 1; i <= n; i++) { for (int j = 1; j <= K; j++) { int temp = 0; for (int v = i - 1; v >= 0; v--) { temp += A[v]; int numElement = i - v; if (i - numElement < j - 1 || (i - numElement > 0 && j - 1 <= 0)) continue; dp[i][j] = max(dp[i][j], dp[i - numElement][j-1] + 1.0*temp/numElement); } } } return dp[n][K]; } }; ================================================ FILE: cpp/811-820/Linked List Components.cpp ================================================ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: int numComponents(ListNode* head, vector& G) { set myset(G.begin(), G.end()); int ans = 0; bool flag = false; while (head) { int v = head->val; if (myset.count(v) > 0) { if (!flag) { flag = true; } } else { if (flag) { ans++; } flag = false; } head = head->next; } if (flag) ans++; return ans; } }; ================================================ FILE: cpp/811-820/Most Common Word.cpp ================================================ class Solution { public: string mostCommonWord(string paragraph, vector& banned) { unordered_set ban(banned.begin(), banned.end()); unordered_map count; for (auto & c: paragraph) c = isalpha(c) ? tolower(c) : ' '; istringstream iss(paragraph); string w, res; int c = 0; while (iss >> w) { if (ban.find(w) == ban.end() && ++count[w] > c) { res = w; c = count[w]; } } return res; } }; ================================================ FILE: cpp/811-820/Race Car.cpp ================================================ class Solution { int reverseSpeed(int speed) { return speed > 0 ? -1 : 1; } public: // (pos, speed) determines current state int racecar(int target) { // {pos, speed} unordered_set visited; queue> myqueue; myqueue.push({0, 1}); visited.insert("0.1"); int level = 0; while (!myqueue.empty()) { int mysize = myqueue.size(); for (int i = 0; i < mysize; i++) { pair cur = myqueue.front(); myqueue.pop(); if (cur.first == target) { return level; } pair first = make_pair(cur.first + cur.second, cur.second*2); pair second = make_pair(cur.first, reverseSpeed(cur.second)); string key1 = to_string(first.first) + "." + to_string(first.second); string key2 = to_string(second.first) + "." + to_string(second.second); if (first.first >= 0 && first.first <= 2*target && visited.count(key1) == 0) { visited.insert(key1); myqueue.emplace(first); } if (second.first >= 0 && second.first <= 2*target && visited.count(key2) == 0) { visited.insert(key2); myqueue.emplace(second); } } level++; } return -1; } }; ================================================ FILE: cpp/811-820/Short Encoding of Words.cpp ================================================ struct TrieNode { TrieNode *nodes[26]; // Initialize your data structure here. TrieNode() { memset(nodes, 0, sizeof(nodes)); } }; class Trie { public: Trie() { root = new TrieNode(); } // Inserts a word into the trie. void insert(const string& s) { TrieNode *tmp = root; for(char ch : s) { int index = ch - 'a'; if(tmp->nodes[index] == nullptr) { tmp->nodes[index] = new TrieNode(); } tmp = tmp->nodes[index]; } } int getWordLen() { return _getWordLen(root, 0); } private: TrieNode* root; int _getWordLen(TrieNode* root, int depth) { if (!root) return 0; int ans = 0; for (TrieNode* child : root->nodes) { ans += _getWordLen(child, depth+1); } if (ans == 0) return depth + 1; return ans; } }; class Solution { public: int minimumLengthEncoding(vector& words) { Trie trie; for (string str : words) { reverse(str.begin(), str.end()); trie.insert(str); } return trie.getWordLen(); } }; ================================================ FILE: cpp/811-820/Subdomain Visit Count.cpp ================================================ class Solution { public: vector subdomainVisits(vector& cpdomains) { unordered_map m; for (const auto& word : cpdomains) { int i = word.find (" "); int n = stoi(word.substr (0, i)); string s = word.substr (i+1, word.size ()-i-1); for (int i = s.size ()-1; i >= 0; i--) { if (s[i] == '.') m[s.substr (i+1, s.size ()-i-1)] += n; else if (i == 0) m[s.substr (i, s.size ()-i) ] += n; } } vector v; for (const auto& e : m) v.push_back (to_string (e.second) + " " + e.first); return v; } }; ================================================ FILE: cpp/821-830/Binary Trees With Factors.cpp ================================================ class Solution { public: int numFactoredBinaryTrees(vector& A) { map mymap; sort(A.begin(), A.end()); unordered_set myset(A.begin(), A.end()); int mod = 1000000007; long ans = 0; for (int i = 0; i < A.size(); i++) { long temp = 1; for (int j = 0; j < i; j++) { if (A[i] % A[j] == 0) { int divide = A[i] / A[j]; if (myset.count(divide) > 0) { long left = mymap[A[j]]; long right = mymap[divide]; temp += (left*right) % mod; temp = temp % mod; } } } mymap[A[i]] = temp; ans += mymap[A[i]]; ans %= mod; } return ans; } }; ================================================ FILE: cpp/821-830/Card Flipping Game.cpp ================================================ class Solution { public: int flipgame(vector& fronts, vector& backs) { unordered_set same; for (int i = 0; i < fronts.size(); ++i) if (fronts[i] == backs[i]) same.insert(fronts[i]); int ans = 2001; for (int x: fronts) if (same.count(x) == 0) ans = min(ans, x); for (int x: backs) if (same.count(x) == 0) ans = min(ans, x); return ans % 2001; } }; ================================================ FILE: cpp/821-830/Consecutive Numbers Sum.cpp ================================================ class Solution { public: int consecutiveNumbersSum(int N) { int ans = 1; for (int i = 2; i * (i + 1) / 2 <= N; ++i) { if ((N - i * (i + 1) / 2) % i == 0) ++ans; } return ans; } }; ================================================ FILE: cpp/821-830/Friends Of Appropriate Ages.cpp ================================================ class Solution { public: int numFriendRequests(vector& ages) { unordered_map count; for (int age : ages) count[age]++; int res = 0; for (const auto &a: count) { for (const auto &b: count) { if (request(a.first, b.first)) { res += a.second * (b.second - (a.first == b.first ? 1 : 0)); } } } return res; } bool request(int a, int b) { return !(b <= 0.5 * a + 7 || b > a || (b > 100 && a < 100)); } }; ================================================ FILE: cpp/821-830/Goat Latin.cpp ================================================ class Solution { public: string toGoatLatin(string S) { stringstream iss(S), oss; string vowels("aeiouAEIOU"), word, a; while (iss >> word) { a.push_back('a'); if (vowels.find(word[0]) != string::npos) // begin with a vowel oss << word; else // begin with a consonant oss << word.substr(1) << word[0]; oss << "ma" << a << ' '; } string res = oss.str(); res.pop_back(); return res; } }; ================================================ FILE: cpp/821-830/Making A Large Island.cpp ================================================ class Solution { int dfs(pair pos, const pair& root, const vector>& grid, map, pair>& roots) { roots[pos] = root; int m = grid.size(); int n = grid.front().size(); pair xys[4] = {{1,0}, {-1,0}, {0,1}, {0,-1}}; int area = 1; for (int i = 0; i < 4; i++) { int ni = pos.first + xys[i].first; int nj = pos.second + xys[i].second; if (ni < 0 || ni >= m || nj < 0 || nj >= n) continue; if (grid[ni][nj] == 0) continue; if (roots.find({ni, nj}) != roots.end()) continue; area += dfs(make_pair(ni, nj), root, grid, roots); } return area; } public: int largestIsland(vector>& grid) { map, int> areas; // coordinate -> area map, pair> roots; int m = grid.size(); int n = grid.front().size(); int ans = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (grid[i][j] == 0) continue; pair cur = make_pair(i, j); if (roots.find(cur) == roots.end()) { int area = dfs(cur, cur, grid, roots); areas[cur] = area; ans = max(ans, area); } } } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (grid[i][j] == 0) { set> used; pair xys[4] = {{1,0}, {-1,0}, {0,1}, {0,-1}}; int area = 1; for (int k = 0; k < 4; k++) { int ni = i + xys[k].first; int nj = j + xys[k].second; if (ni < 0 || ni >= m || nj < 0 || nj >= n) continue; if (grid[ni][nj] == 0) continue; pair curRoot = roots[make_pair(ni, nj)]; if (used.count(curRoot) == 0) { used.insert(curRoot); area += areas[curRoot]; } } ans = max(ans, area); } } } return ans; } }; ================================================ FILE: cpp/821-830/Most Profit Assigning Work.cpp ================================================ class Solution { public: int maxProfitAssignment(vector& difficulty, vector& profit, vector& worker) { vector> jobs; int N = profit.size(), res = 0, i = 0, maxp = 0; for (int j = 0; j < N; ++j) jobs.push_back(make_pair(difficulty[j], profit[j])); sort(jobs.begin(), jobs.end()); sort(worker.begin(), worker.end()); for (int ability : worker) { while (i < N && ability >= jobs[i].first) maxp = max(jobs[i++].second, maxp); res += maxp; } return res; } }; ================================================ FILE: cpp/821-830/Positions of Large Groups.cpp ================================================ class Solution { public: vector> largeGroupPositions(string S) { vector> ans; for (int i = 0; i < S.size(); ++i) { int begin = i; int count = 1; while (i + 1 < S.size() && S[i] == S[i + 1]) ++i, ++count; if (count >= 3) ans.push_back({begin, begin + count - 1}); } return ans; } }; ================================================ FILE: cpp/821-830/Shortest Distance to a Character.cpp ================================================ // Time Complexity: O(n) // Space COmplexity: O(n) class Solution { public: vector shortestToChar(string S, char C) { vector ans(S.length(), 0); int previous = -1; for (int i = 0; i < S.length(); i++) { if (S[i] == C) previous = i; ans[i] = previous < 0 ? INT_MAX : i - previous; } int next = INT_MAX; for (int i = S.length() - 1; i >= 0; i--) { if (S[i] == C) next = i; int temp = next == INT_MAX ? INT_MAX : next - i; ans[i] = min(ans[i], temp); } return ans; } }; ================================================ FILE: cpp/821-830/Unique Letter String.cpp ================================================ class Solution { public: int uniqueLetterString(string S) { int ans = 0; map lastPos, lastlastPos; for (int i = 0; i < 128; i++) { lastPos[i] = lastlastPos[i] = -1; } int tmp = 0; for (int i = 0; i < S.length(); i++) { char ch = S[i]; if (lastPos[ch] < 0) { // ....A we should add the previous tmp += (i - lastPos[ch]); } else { // A...A....A we should add the second half and remove the first half tmp += (i - lastPos[ch]); tmp -= (lastPos[ch] - lastlastPos[ch]); lastlastPos[ch] = lastPos[ch]; } ans += tmp; lastPos[ch] = i; } return ans; } }; ================================================ FILE: cpp/831-840/Find And Replace in String.cpp ================================================ class Solution { public: string findReplaceString(string S, vector& indexes, vector& sources, vector& targets) { if (indexes.empty() || S.empty()) return S; map> mymap; for (int i = 0; i < indexes.size(); i++) { mymap[indexes[i]] = make_pair(sources[i], targets[i]); } stringstream ss; for (int i = 0; i < S.length(); i++) { if (mymap.find(i) != mymap.end()) { string s = mymap[i].first; string t = mymap[i].second; if (i + s.length() > S.length()) { ss << S[i]; } else { string temp = S.substr(i, s.length()); if (temp == s) { ss << t; i += (s.length() - 1); } else { ss << S[i]; } } } else { ss << S[i]; } } return ss.str(); } }; ================================================ FILE: cpp/831-840/Flipping an Image.cpp ================================================ class Solution { public: vector> flipAndInvertImage(vector>& A) { if (A.empty() || A.front().empty()) return A; for (auto& v : A) reverse(v.begin(), v.end()); for (auto& v : A) { for (int& e : v) { e = 1 - e; } } return A; } }; ================================================ FILE: cpp/831-840/Image Overlap.cpp ================================================ class Solution { public: int largestOverlap(vector>& A, vector>& B) { if (A.empty() || A.front().empty()) { return 0; } int n = A.size(); int res = 0; for (int i = 1 - n; i <= n -1; i++) { for (int j = 1-n; j <= n-1; j++) { int cur = 0; for (int k = max(i, 0); k < min(i + n, n); k++) { for (int l = max(j, 0); l < min(j + n, n); l++) { if (A[k -i][l - j] == 1 && B[k][l] == 1) { cur ++; } } } res = max(res, cur); } } return res; } }; ================================================ FILE: cpp/831-840/Magic Squares In Grid.cpp ================================================ class Solution { bool validate(int i, int j, vector>& grid) { if (i + 2 >= grid.size() || j + 2 >= grid.front().size()) return false; int sum1 = grid[i][j] + grid[i][j+1] + grid[i][j+2]; int sum2 = grid[i+1][j] + grid[i+1][j+1] + grid[i+1][j+2]; int sum3 = grid[i+2][j] + grid[i+2][j+1] + grid[i+2][j+2]; int sum4 = grid[i][j] + grid[i+1][j] + grid[i+2][j]; int sum5 = grid[i][j+1] + grid[i+1][j+1] + grid[i+2][j+1]; int sum6 = grid[i][j+2] + grid[i+1][j+2] + grid[i+2][j+2]; int sum7 = grid[i][j] + grid[i+1][j+1] + grid[i+2][j+2]; int sum8 = grid[i][j+2] + grid[i+1][j+1] + grid[i+2][j]; set myset{grid[i][j], grid[i][j+1], grid[i][j+2], grid[i+1][j], grid[i+1][j+1], grid[i+1][j+2], grid[i+2][j], grid[i+2][j+1], grid[i+2][j+2]}; if (myset.size() != 9) return false; if (*myset.begin() != 1) return false; if (*myset.rbegin() != 9) return false; if (sum1 != sum2) return false; if (sum1 != sum3) return false; if (sum1 != sum4) return false; if (sum1 != sum5) return false; if (sum1 != sum6) return false; if (sum1 != sum7) return false; if (sum1 != sum8) return false; return true; } public: int numMagicSquaresInside(vector>& grid) { int ans = 0; if (grid.empty() || grid.front().empty()) return 0; int m = grid.size(); int n = grid.front().size(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (validate(i, j, grid)) { ans++; } } } return ans; } }; ================================================ FILE: cpp/831-840/Masking Personal Information.cpp ================================================ class Solution { string processEmail(string& S) { for (int i = 0; i < S.length(); i++) S[i] = tolower(S[i]); int index = S.find('@'); string ans; ans.push_back(S[0]); ans += "*****" + S.substr(index-1); return ans; } string processPhone(const string& S) { string filterS; for (char ch : S) if (isdigit(ch)) filterS += ch; string ans; int num = filterS.length() - 10; if (num > 0) { ans += '+'; ans += string(num, '*'); ans += '-'; } ans += "***-***-"; ans += filterS.substr(filterS.length() - 4); return ans; } public: string maskPII(string S) { if (S.find('@') != string::npos) { return processEmail(S); } else { return processPhone(S); } } }; ================================================ FILE: cpp/831-840/New 21 Game.cpp ================================================ class Solution { public: // dp[i]: probability of get points i // dp[i] = sum(last W dp values) / W double new21Game(int N, int K, int W) { if (K == 0 || N >= K + W) return 1.0; vector dp(N + 1); dp[0] = 1.0; double Wsum = 1.0, res = 0.0; for (int i = 1; i <= N; ++i) { dp[i] = Wsum / W; if (i < K) Wsum += dp[i]; else res += dp[i]; if (i - W >= 0) Wsum -= dp[i - W]; } return res; } }; ================================================ FILE: cpp/831-840/Push Dominoes.cpp ================================================ class Solution { public: // 'R......R' => 'RRRRRRRR' // 'R......L' => 'RRRRLLLL' or 'RRRR.LLLL' // 'L......R' => 'L......R' // 'L......L' => 'LLLLLLLL' string pushDominoes(string dominoes) { dominoes = 'L' + dominoes + 'R'; string res = ""; for (int i = 0, j = 1; j < dominoes.length(); ++j) { if (dominoes[j] == '.') continue; int middle = j - i - 1; if (i > 0) res += dominoes[i]; if (dominoes[i] == dominoes[j]) res += string(middle, dominoes[i]); else if (dominoes[i] == 'L' && dominoes[j] == 'R') res += string(middle, '.'); else res += string(middle / 2, 'R') + string(middle % 2,'.') + string(middle / 2, 'L'); i = j; } return res; } }; ================================================ FILE: cpp/831-840/Rectangle Overlap.cpp ================================================ class Solution { int overlapLen(int a1, int a2, int b1, int b2) { if (a1 > b1) return overlapLen(b1, b2, a1, a2); int left = b1; int right = min(a2, b2); if (right <= left) return 0; return right - left; } public: bool isRectangleOverlap(vector& rec1, vector& rec2) { return overlapLen(rec1[0], rec1[2], rec2[0], rec2[2]) > 0 && overlapLen(rec1[1], rec1[3], rec2[1], rec2[3]) > 0; } }; ================================================ FILE: cpp/831-840/Similar String Groups.cpp ================================================ class UF { private: vector parent; vector rank; int count; int N; public: UF(int N) : parent(N), rank(N, 0), N(N), count(N) { for (int i = 0; i < N; i++) { parent[i] = i; } } int find(int p) { while (p != parent[p]) { parent[p] = parent[parent[p]]; // path compression by halving p = parent[p]; } return p; } int getCount() const { return count; } bool connected(int p, int q) { return find(p) == find(q); } void Union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make root of smaller rank point to root of larger rank if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ; else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP; else { parent[rootQ] = rootP; rank[rootP]++; } count--; } }; class Solution { bool similar(const string &a, const string &b) { int n = 0; for (int i = 0; i < a.size(); i++) if (a[i] != b[i] && ++n > 2) return false; return true; } public: int numSimilarGroups(vector& A) { UF uf(A.size()); for (int i = 0; i < A.size(); i++) for (int j = i + 1; j < A.size(); j++) if (similar(A[i], A[j])) uf.Union(i, j); return uf.getCount(); } }; ================================================ FILE: cpp/831-840/Sum of Distances in Tree.cpp ================================================ class Solution { int dfs(int start, vector& myNodes, vector& visited, map>& graph, int level, int& res) { visited[start] = true; int nodeNum = 1; for (int neig : graph[start]) { if (visited[neig]) continue; nodeNum += dfs(neig, myNodes, visited, graph, level+1, res); } myNodes[start] = nodeNum; res += level; return nodeNum; } void dfs2(int start, vector& myNodes, map>& graph, vector& ans, int distanceOfStart) { if (ans[start] < 0) { int mine = myNodes[start] - 1; int other =myNodes.size() - mine - 2; ans[start] = distanceOfStart + (other - mine); } for (int neig : graph[start]) { if (ans[neig] > 0) continue; dfs2(neig, myNodes, graph, ans, ans[start]); } } public: vector sumOfDistancesInTree(int N, vector>& edges) { map> graph; for (auto& edge : edges) { int u = edge[0]; int v = edge[1]; graph[u].push_back(v); graph[v].push_back(u); } int distanceOfStart = 0; vector myNodes(N, 0); vector visited(N, false); dfs(0, myNodes, visited, graph, 0, distanceOfStart); vector ans(N, -1); ans[0] =distanceOfStart; dfs2(0, myNodes, graph, ans, distanceOfStart); return ans; } }; ================================================ FILE: cpp/841-850/Backspace String Compare.cpp ================================================ class Solution { string parse(const string& str) { stack mystack; int i = 0; while (i < str.length()) { if (str[i] != '#') { mystack.push(str[i]); } else if (!mystack.empty()){ mystack.pop(); } i++; } string ans; while (!mystack.empty()) { ans += mystack.top(); mystack.pop(); } return ans; } public: bool backspaceCompare(string S, string T) { return parse(S) == parse(T); } }; ================================================ FILE: cpp/841-850/Guess the Word.cpp ================================================ /** * // This is the Master's API interface. * // You should not implement it, or speculate about its implementation * class Master { * public: * int guess(string word); * }; */ class Solution { int similarity(string& s1, string& s2) { int n = s1.length(); int ans = 0; for (int i = 0; i < n; i++) { if (s1[i] == s2[i]) { ans++; } } return ans; } public: void findSecretWord(vector& wordlist, Master& master) { vector v(wordlist); for (int i = 0; i < 10; i++) { string candidate = v[v.size()/2]; int n = master.guess(candidate); if (n == 6) return; vector temp; for (int i = 0; i < v.size(); i++) { if (v[i] == candidate) continue; int similar = similarity(candidate, v[i]); if (similar == n) temp.push_back(v[i]); } v = temp; } } }; ================================================ FILE: cpp/841-850/Hand of Straights.cpp ================================================ class Solution { public: bool isNStraightHand(vector& hand, int W) { map mymap; for (int e : hand) mymap[e]++; while (!mymap.empty()) { int small = (mymap.begin())->first; for (int i = 0; i < W; i++) { if (mymap[small] > 0) { mymap[small]--; if (mymap[small] == 0) { mymap.erase(small); } } else { return false; } small++; } } return true; } }; ================================================ FILE: cpp/841-850/Keys and Rooms.cpp ================================================ class Solution { void dfs(int u, const vector>& rooms, vector& visited) { for (int v : rooms[u]) { if (!visited[v]) { visited[v] = true; dfs(v, rooms, visited); } } } public: bool canVisitAllRooms(vector>& rooms) { int n = rooms.size(); if (n < 2) return true; vector visited(n, false); visited[0] = true; dfs(0, rooms, visited); for (bool b : visited) { if (!b) return false; } return true; } }; ================================================ FILE: cpp/841-850/Longest Mountain in Array.cpp ================================================ class Solution { public: int longestMountain(vector& A) { int n = A.size(); vector dp1(n, 1); vector dp2(n, 1); for (int i = 1; i < n; i++) { if (A[i] > A[i-1]) { dp1[i] = dp1[i-1]+1; } else { dp1[i] = 1; } } for (int i = n-1; i >= 1; i--) { if (A[i-1] > A[i]) { dp2[i-1] = dp2[i]+1; } else { dp2[i-1] = 1; } } int ans = 1; for (int i = 0; i < n; i++) { if (dp1[i] > 1 && dp2[i] > 1) { ans = max(ans, dp1[i] + dp2[i] - 1); } } return ans >= 3 ? ans : 0; } }; ================================================ FILE: cpp/841-850/Maximize Distance to Closest Person.cpp ================================================ class Solution { public: int maxDistToClosest(vector& seats) { int last = -1; int ans = 0; for (int i = 0; i < seats.size(); i++) { if (seats[i] == 1) { if (last < 0) { ans = i; } else { ans = max(ans, (i - last)/2); } last = i; } } ans = max(ans, (int)seats.size() - last - 1); return ans; } }; ================================================ FILE: cpp/841-850/Shifting Letters.cpp ================================================ class Solution { char convert(char c, int x) { return (((c-'a')+x)%26) + 'a'; } public: string shiftingLetters(string S, vector& shifts) { for (int i = shifts.size() - 1; i >= 1; i--) { shifts[i-1] += (shifts[i]%26); } for (int i = 0; i < S.length(); i++) { S[i] = convert(S[i], shifts[i]); } return S; } }; ================================================ FILE: cpp/841-850/Shortest Path Visiting All Nodes.cpp ================================================ class Solution { int getKey(const pair>& e) { long key = e.first << 20;; for (int i = 0; i < 12; i++) { if (e.second.count(i) > 0) { key = key | (1 << i); } } return key; } public: int shortestPathLength(vector>& graph) { int n = graph.size(); int ans = INT_MAX; unordered_map cache; for (int i = 0; i < n; i++) { set unvisited; for (int k = 0; k < n; k++) { if (k != i) unvisited.insert(k); } queue>> myqueue; myqueue.push(make_pair(i, unvisited)); int key = getKey(make_pair(i, unvisited)); cache[key] = 0; while (!myqueue.empty()) { pair> cur = myqueue.front(); myqueue.pop(); int key = getKey(cur); if (cur.second.empty()) { ans = min(ans, cache[key]); break; } int step = cache[key]; for (int v : graph[cur.first]) { set newUnvisited = (cur.second); newUnvisited.erase(v); pair> newPair = make_pair(v, newUnvisited); int nkey = getKey(newPair); if (cache.count(nkey) > 0 && (cache[nkey] <= step + 1)) continue; cache[nkey] = step+1; myqueue.emplace(newPair); } } } return ans; } }; ================================================ FILE: cpp/841-850/Split Array into Fibonacci Sequence.cpp ================================================ class Solution { bool dfs(long n1, long n2, string& S, int pos, int l, vector& ans) { if (pos >= S.length()) { return l >= 3; } long n3 = n1 + n2; if (n1 > INT_MAX || n2 > INT_MAX || n3 > INT_MAX) return false; string s = to_string(n3); int len = s.length(); if (S.length() - pos < len) return false; if (S.substr(pos, len) != s) return false; ans.push_back(n3); bool f = dfs(n2, n3, S, pos + len, l+1, ans); if (f) return true; ans.pop_back(); return false; } public: vector splitIntoFibonacci(string S) { vector ans; if (S.size() < 3) return ans; int n = S.length(); for (int len1 = 1; len1 <= min(10, n/2+1); len1++) { string str1 = S.substr(0, len1); if (str1[0] == '0' && len1 > 1) continue; long num1 = stol(str1); ans.push_back(num1); for (int len2 = 1; len2 <= min(10, n/2+1); len2++) { string str2 = S.substr(len1, len2); if (str2[0] == '0' && len2 > 1) break; long num2 = stol(str2); ans.push_back(num2); if (dfs(num1, num2, S, len1+len2, 2, ans)) return ans; ans.pop_back(); } ans.pop_back(); } return ans; } }; ================================================ FILE: cpp/851-860/Buddy Strings.cpp ================================================ class Solution { public: bool buddyStrings(string A, string B) { if (A.length() != B.length()) return false; if (A == B && set(A.begin(), A.end()).size() < A.size()) return true; vector dif; for (int i = 0; i < A.length(); ++i) if (A[i] != B[i]) dif.push_back(i); return dif.size() == 2 && A[dif[0]] == B[dif[1]] && A[dif[1]] == B[dif[0]]; } }; ================================================ FILE: cpp/851-860/Car Fleet.cpp ================================================ class Solution { public: int carFleet(int target, vector& position, vector& speed) { int n = position.size(); vector> arrays(n); for (int i = 0; i < n; ++i) arrays[i] = make_pair(position[i], (target - position[i])*1.0 / speed[i]); auto cmp = [](const pair& p1, const pair& p2) { return p1.first > p2.first; }; sort(arrays.begin(), arrays.end(), cmp); int ans = 0, t = 0; while (t < n-1) { if (arrays[t].second < arrays[t+1].second) ans++; else arrays[t+1] = arrays[t]; t++; } return ans + (t == n-1 ? 1 : 0); } }; ================================================ FILE: cpp/851-860/Exam Room.cpp ================================================ class ExamRoom { set taken; int n; public: ExamRoom(int N) { n = N; } int seat() { if (taken.empty()) { taken.insert(0); return 0; } int ans = 0; int len = -1; if (taken.count(0) == 0) { len = max(len, *taken.begin()); ans = 0; } int prevSeat = -1; for (int currentSeat : taken) { if (prevSeat < 0) { prevSeat = currentSeat; } else { // 6, 9 candidatelen = (6+9)/2 = 7 candidatelen = min(7-6, 9-7) int candidatePos = (currentSeat + prevSeat) / 2; int candidateLen = min(candidatePos - prevSeat, currentSeat - candidatePos); if (candidateLen > len) { len = candidateLen; ans = candidatePos; } prevSeat = currentSeat; } } if (taken.count(n-1) == 0) { int candidateLen = n - 1 - *taken.rbegin(); if (candidateLen > len) { ans = n - 1; } } taken.insert(ans); return ans; } void leave(int p) { if (taken.count(p) > 0) { taken.erase(p); } } }; /** * Your ExamRoom object will be instantiated and called as such: * ExamRoom obj = new ExamRoom(N); * int param_1 = obj.seat(); * obj.leave(p); */ ================================================ FILE: cpp/851-860/K-Similar Strings.cpp ================================================ class Solution { public: int kSimilarity(string A, string B) { if(A == B) return 0; unordered_set visit; queue> q; int n = A.size(); int step = 0; int i = 0; for(; i < n; ++i) { if(A[i] != B[i]) break; } q.push({A, i}); visit.insert(A); while (!q.empty()) { int size = q.size(); for (int i = 0; i < size; ++i) { string t = move(q.front().first); int index = q.front().second; q.pop(); if(t == B) return step; while(t[index] == B[index]) ++index; for(int i = index +1; i < n; ++i) { if(t[i] == B[index] && t[i] != B[i]) { swap(t[index], t[i]); if(visit.count(t) == 0) { q.push({t, index+1}); visit.insert(t); } swap(t[index], t[i]); } } } ++step; } return step; } }; ================================================ FILE: cpp/851-860/Lemonade Change.cpp ================================================ class Solution { public: bool lemonadeChange(vector& bills) { map mymap; for (int e : bills) { if (e == 5) { mymap[5]++; } else if (e == 10) { mymap[10]++; if (mymap[5] == 0) return false; mymap[5]--; } else { mymap[20]++; int remain = 15; if (mymap[10] > 0) { remain = 5; mymap[10]--; } while (remain > 0) { if (mymap[5] > 0) { mymap[5]--; remain -= 5; } else { return false; } } } } return true; } }; ================================================ FILE: cpp/851-860/Loud and Rich.cpp ================================================ class Solution { public: vector loudAndRich(vector>& richer, vector& quiet) { unordered_map> richer2; for (const auto& v : richer) richer2[v[1]].push_back(v[0]); vector ans(quiet.size(), -1); for (int i = 0; i < quiet.size(); i++) dfs(i, quiet, ans, richer2); return ans; } int dfs(int i, const vector& quiet, vector& ans, unordered_map>& richer2) { if (ans[i] >= 0) return ans[i]; ans[i] = i; for (int j : richer2[i]) if (quiet[ans[i]] > quiet[dfs(j, quiet, ans, richer2)]) ans[i] = ans[j]; return ans[i]; } }; ================================================ FILE: cpp/851-860/Peak Index in a Mountain Array.cpp ================================================ class Solution { public: int peakIndexInMountainArray(vector& A) { for (int i = 0; i < A.size(); i++) { if (A[i] > A[i+1]) { return i; } } } }; ================================================ FILE: cpp/851-860/Score of Parentheses.cpp ================================================ class Solution { int dfs(const string& S, int& i) { int sum = 0; for (i; i < S.length(); i++) { if (S[i] == '(') { i++; sum += dfs(S, i); } else if (S[i] == ')') { if (sum == 0) return 1; return 2*sum; } } return sum; } public: int scoreOfParentheses(string S) { int i = 0; return dfs(S, i); } }; ================================================ FILE: cpp/861-870/Advantage Shuffle.cpp ================================================ class Solution { public: vector advantageCount(vector& A, vector& B) { multiset s(begin(A), end(A)); for (int i = 0; i < B.size(); ++i) { auto p = *s.rbegin() <= B[i] ? s.begin() : s.upper_bound(B[i]); A[i] = *p; s.erase(p); } return A; } }; ================================================ FILE: cpp/861-870/All Nodes Distance K in Binary Tree.cpp ================================================ // Solution 1: O(n) Time, O(n) Space /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector ans; unordered_map parent; // son=>parent unordered_set visit; //record visied node void findParent(TreeNode* node) { if (node == nullptr) return; if (node->left != nullptr) { parent[node->left] = node; findParent(node->left); } if (node->right != nullptr){ parent[node->right] = node; findParent(node->right); } } void dfs(TreeNode* node, int K){ if (node == nullptr || visit.count(node) > 0) { return; } visit.insert(node); if (K == 0) { ans.push_back(node->val); return; } dfs(node->left, K-1); dfs(node->right, K-1); dfs(parent[node], K-1); } vector distanceK(TreeNode* root, TreeNode* target, int K) { findParent(root); dfs(target, K); return ans; } }; // Solution 2: O(n) Time, O(lgn) Space /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { bool FindPath(TreeNode* root, TreeNode* target, vector& paths) { if (root == nullptr) { return false; } if (target == root) { return true; } bool l = FindPath(root->left, target, paths); if (l) { paths.push_back(false); return true; } bool r = FindPath(root->right, target, paths); if (r) { paths.push_back(true); return true; } return false; } void FindAnswer(TreeNode* root, vector& ans, int dis, int K) { if (root == nullptr || dis > K) { return; } if (dis == K) { ans.push_back(root->val); return; } FindAnswer(root->left, ans, dis + 1, K); FindAnswer(root->right, ans, dis + 1, K); } public: vector distanceK(TreeNode* root, TreeNode* target, int K) { vector paths; FindPath(root, target, paths); reverse(paths.begin(), paths.end()); vector ans; for (int i = 0; i < paths.size(); i++) { if (paths.size() - i == K) { ans.push_back(root->val); } bool path = paths[i]; if (path == false) { FindAnswer(root->right, ans, paths.size() + 1 - i, K); root = root->left; } else { FindAnswer(root->left, ans, paths.size() + 1 - i, K); root = root->right; } } FindAnswer(root, ans, 0, K); return ans; } }; ================================================ FILE: cpp/861-870/Binary Gap.cpp ================================================ class Solution { public: int binaryGap(int N) { int last = -1, ans = 0; for (int i = 0; i < 32; ++i) if (((N >> i) & 1) > 0) { if (last >= 0) ans = max(ans, i - last); last = i; } return ans; } }; ================================================ FILE: cpp/861-870/Prime Palindrome.cpp ================================================ class Solution { public: int primePalindrome(int N) { if (N == 1 || N == 2) return 2; if (N % 2 == 0) N++; long t, r = 0, d; while (true) { t = N; while(t) { r = r * 10; r = r + t % 10; t = t / 10; } if (r == N) { d = (int)sqrt(N); long c = 2; for (; c <= d; c++) { if (N % c == 0) break; } if (c == d + 1) break; } r = 0; N += 2; } return N; } }; ================================================ FILE: cpp/861-870/Reordered Power of 2.cpp ================================================ class Solution { public: bool reorderedPowerOf2(int N) { long c = counter(N); for (int i = 0; i < 32; i++) if (counter(1 << i) == c) return true; return false; } long counter(int N) { long res = 0; for (; N; N /= 10) res += pow(10, N % 10); return res; } }; ================================================ FILE: cpp/861-870/Score After Flipping Matrix.cpp ================================================ class Solution { public: int matrixScore(vector> A) { int M = A.size(), N = A[0].size(), res = (1 << (N - 1)) * M; for (int j = 1; j < N; j++) { int cur = 0; for (int i = 0; i < M; i++) cur += A[i][j] == A[i][0]; res += max(cur, M - cur) * (1 << (N - j - 1)); } return res; } }; ================================================ FILE: cpp/861-870/Smallest Subtree with all the Deepest Nodes.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { int maxDeep; int maxDepth(TreeNode* root) { if(!root) return 0; return 1 + max(maxDepth(root->left), maxDepth(root->right)); } TreeNode* dfs(TreeNode* root, int deep) { if (!root) return nullptr; if (deep == maxDeep) return root; TreeNode* l = dfs(root->left, deep+1); TreeNode* r = dfs(root->right, deep+1); if (l && r) return root; if (l && !r) return l; if (r && !l) return r; return nullptr; } public: TreeNode* subtreeWithAllDeepest(TreeNode* root) { if (root == nullptr) return nullptr; maxDeep = maxDepth(root); return dfs(root, 1); } }; ================================================ FILE: cpp/861-870/Transpose Matrix.cpp ================================================ class Solution { public: vector> transpose(vector>& A) { if (A.empty()) return vector>(); int m = A.size(); int n = A[0].size(); vector> ans (n, vector(m, 0)); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { ans[j][i] = A[i][j]; } } return ans; } }; ================================================ FILE: cpp/871-880/Implement Rand10() Using Rand7().cpp ================================================ // The rand7() API is already defined for you. // int rand7(); // @return a random integer in the range 1 to 7 class Solution { public: int rand10() { while (true) { int n = 7 * rand7() + rand7() - 8; if (n < 40) return n % 10 + 1; } } }; ================================================ FILE: cpp/871-880/Koko Eating Bananas.cpp ================================================ class Solution { public: int minEatingSpeed(vector& piles, int H) { int l = 1, r = 1e9; while (l < r) { int m = (l + r) / 2, total = 0; for (int p : piles) total += ceil(p*1.0 / m); if (total > H) l = m + 1; else r = m; } return l; } }; ================================================ FILE: cpp/871-880/Leaf-Similar Trees.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { int next(stack& mystack) { while (true) { TreeNode* cur = mystack.top(); mystack.pop(); if (cur->right) { mystack.push(cur->right); } if (cur->left) { mystack.push(cur->left); } if (!cur->left && !cur->right) { return cur->val; } } } public: bool leafSimilar(TreeNode* root1, TreeNode* root2) { stack stackOne; stackOne.push(root1); stack stackTwo; stackTwo.push(root2); while (true) { if (stackOne.empty() && stackTwo.empty()) { return true; } if (!stackOne.empty() && !stackTwo.empty()) { int v1 = next(stackOne); int v2 = next(stackTwo); if (v1 != v2) return false; } else { return false; } } } }; ================================================ FILE: cpp/871-880/Length of Longest Fibonacci Subsequence.cpp ================================================ class Solution { public: int lenLongestFibSubseq(vector& A) { unordered_map m; int N = A.size(), res = 0; int dp[N][N]; for (int j = 0; j < N; ++j) { m[A[j]] = j; for (int i = 0; i < j; ++i) { int k = m.find(A[j] - A[i]) == m.end() ? -1 : m[A[j] - A[i]]; dp[i][j] = (A[j] - A[i] < A[i] && k >= 0) ? dp[k][i] + 1 : 2; res = max(res, dp[i][j]); } } return res > 2 ? res : 0; } }; ================================================ FILE: cpp/871-880/Middle of the Linked List.cpp ================================================ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* middleNode(ListNode* head) { ListNode *slow(head), *fast(head->next); while (fast) { slow = slow->next; fast = fast->next; if (fast) fast = fast->next; } return slow; } }; ================================================ FILE: cpp/871-880/Stone Game.cpp ================================================ class Solution { public: bool stoneGame(vector& piles) { return true; } }; ================================================ FILE: cpp/881-890/Boats to Save People.cpp ================================================ class Solution { public: int numRescueBoats(vector& people, int limit) { sort(people.begin(), people.end()); int i = 0, j = people.size() - 1; int ans = 0; while (i <= j) { if (people[i] + people[j] <= limit) { i++; } j--; ans++; } return ans; } }; ================================================ FILE: cpp/881-890/Possible Bipartition.cpp ================================================ class Solution { public: bool possibleBipartition(int N, vector>& dislikes) { vector color(N+1, 0); map> al; for (auto& d: dislikes) { al[d[0]].push_back(d[1]); al[d[1]].push_back(d[0]); } queue q; for (auto e : al) { if (color[e.first] == 0) { // untouched person color[e.first] = 1; q.push(e.first); while (!q.empty()) { int s = q.front(); q.pop(); for (int x : al[s]) { // all neighbors of s if (color[x] == 0) { color[x] = 3 - color[s]; q.push(x); } else if (color[x] != 3 - color[s]) return false; } } } } return true; } }; ================================================ FILE: cpp/881-890/Projection Area of 3D Shapes.cpp ================================================ class Solution { public: int projectionArea(vector>& grid) { int ans = 0; int n = grid.size(); for (auto& v : grid) { for (int v : v) { ans += (v > 0); } ans += *(max_element(v.begin(), v.end())); } for (int i = 0; i < n; i++) { int temp = 0; for (int j = 0; j < n; j++) { temp = max(temp, grid[j][i]); } ans += temp; } return ans; } }; ================================================ FILE: cpp/881-890/Uncommon Words from Two Sentences.cpp ================================================ class Solution { public: vector uncommonFromSentences(string A, string B) { unordered_map count; istringstream iss(A + " " + B); while (iss >> A) count[A]++; vector res; for (auto& w: count) if (w.second == 1) res.emplace_back(move(w.first)); return res; } }; ================================================ FILE: cpp/891-900/Maximum Frequency Stack.cpp ================================================ class FreqStack { map freq; map> mystack; int maxFreq; public: FreqStack() { maxFreq = 0; } void push(int x) { freq[x]++; mystack[freq[x]].push(x); maxFreq = max(freq[x], maxFreq); } int pop() { int retVal = mystack[maxFreq].top(); mystack[maxFreq].pop(); freq[retVal]--; if (mystack[maxFreq].empty()) { maxFreq--; } return retVal; } }; /** * Your FreqStack object will be instantiated and called as such: * FreqStack obj = new FreqStack(); * obj.push(x); * int param_2 = obj.pop(); */ ================================================ FILE: cpp/911-920/Complete Binary Tree Inserter.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class CBTInserter { TreeNode* myroot; queue myqueue; public: CBTInserter(TreeNode* root) { myroot = root; myqueue.push(root); while (true) { if (myqueue.front()->left && myqueue.front()->right) { myqueue.push(myqueue.front()->left); myqueue.push(myqueue.front()->right); myqueue.pop(); } else { break; } } } int insert(int v) { TreeNode* cur = new TreeNode(v); int retVal = myqueue.front()->val; if (myqueue.front()->left == nullptr) { myqueue.front()->left = cur; } else { myqueue.front()->right = cur; myqueue.push(myqueue.front()->left); myqueue.push(cur); myqueue.pop(); } return retVal; } TreeNode* get_root() { return myroot; } }; /** * Your CBTInserter object will be instantiated and called as such: * CBTInserter obj = new CBTInserter(root); * int param_1 = obj.insert(v); * TreeNode* param_2 = obj.get_root(); */ ================================================ FILE: cpp/911-920/Maximum Sum Circular Subarray.cpp ================================================ class Solution { public: int maxSubarraySumCircular(vector& A) { int sum = 0; int cur_max = 0; int max_so_far = INT_MIN; int cur_min = 0; int min_so_far = INT_MAX; for (int v : A) { cur_max = max(cur_max + v, v); max_so_far = max(max_so_far, cur_max); cur_min = min(cur_min + v, v); min_so_far = min(min_so_far, cur_min); sum += v; } if (max_so_far <= 0) return max_so_far; return max(max_so_far, sum - min_so_far); } }; ================================================ FILE: cpp/911-920/Number of Music Playlists.cpp ================================================ class Solution { public: int numMusicPlaylists(int N, int L, int K) { int MOD = 1000000007; vector> dp (L+1, vector(N+1, 0)); dp[0][0] = 1; for (int i = 1; i <= L; ++i) for (int j = 1; j <= N; ++j) { dp[i][j] += dp[i-1][j-1] * (N-j+1); dp[i][j] += dp[i-1][j] * max(j-K, 0); dp[i][j] %= MOD; } return dp[L][N]; } }; ================================================ FILE: cpp/911-920/Online Election.cpp ================================================ class TopVotedCandidate { public: map m; TopVotedCandidate(vector persons, vector times) { int n = persons.size(), lead = -1; unordered_map count; for (int i = 0; i < n; ++i) m[times[i]] = persons[i]; for (auto it : m) { if (++count[it.second] >= count[lead])lead = it.second; m[it.first] = lead; } } int q(int t) { return (--m.upper_bound(t))-> second; } }; /** * Your TopVotedCandidate object will be instantiated and called as such: * TopVotedCandidate obj = new TopVotedCandidate(persons, times); * int param_1 = obj.q(t); */ ================================================ FILE: cpp/911-920/Partition Array into Disjoint Intervals.cpp ================================================ class Solution { public: int partitionDisjoint(vector& A) { int n = A.size(), pmax = 0; vector B(n); B[n - 1] = A[n - 1]; for (int i = n - 2; i > 0; --i) B[i] = min(A[i], B[i + 1]); for (int i = 1; i < n; ++i) { pmax = max(pmax, A[i - 1]); if (pmax <= B[i]) return i; } } }; ================================================ FILE: cpp/911-920/Reverse Only Letters.cpp ================================================ class Solution { public: string reverseOnlyLetters(string S) { int i = 0, j = S.length() - 1; while (i < j) { while (!isalpha(S[i])) i++; while (!isalpha(S[j])) j--; if (i < j) swap(S[i], S[j]); i++; j--; } return S; } }; ================================================ FILE: cpp/911-920/Word Subsets.cpp ================================================ class Solution { public: vector wordSubsets(vector& A, vector& B) { vector uni(26), tmp(26); int i; for (const string& b : B) { tmp = counter(b); for (i = 0; i < 26; ++i) uni[i] = max(uni[i], tmp[i]); } vector res; for (const string& a : A) { tmp = counter(a); for (i = 0; i < 26; ++i) if (tmp[i] < uni[i]) break; if (i == 26) res.push_back(a); } return res; } vector counter(const string& word) { vector count(26); for (char c : word) count[c - 'a']++; return count; } }; ================================================ FILE: cpp/911-920/X of a Kind in a Deck of Cards.cpp ================================================ class Solution { public: bool hasGroupsSizeX(vector& deck) { map mymap; for (int e : deck) mymap[e]++; int gcd = mymap[deck[0]]; for (const auto& e : mymap) gcd = __gcd(gcd, e.second); return gcd >= 2; } };w ================================================ FILE: cpp/921-930/3Sum With Multiplicity.cpp ================================================ class Solution { long MOD = 1000000007; long getCount(int a, int b, int c, unordered_map& mymap) { long v = 0; long ta = mymap[a]; long tb = mymap[b]; long tc = mymap[c]; if (a == b && b == c) { v = ta*(ta-1)*(ta-2)/6; } else if (a == b) { v = tc*tb*(tb-1)/2; } else if (b == c) { v = ta*tb*(tb-1)/2; } else { v = ta*tb*tc; } return v%MOD; } public: int threeSumMulti(vector& A, int target) { sort(A.begin(), A.end()); unordered_map mymap; for (int e : A) mymap[e]++; long ans = 0; for (int i = 0; i < A.size(); i++) { if (3*A[i] > target) break; while (i > 0 && i < A.size() && A[i] == A[i-1]) i++; for (int j = i + 1; j < A.size(); j++) { while (j < A.size() && A[j] != A[i] && A[j] == A[j-1]) j++; while (j > 1 && j < A.size() && A[j] == A[j-2]) j++; if (j >= A.size()-1) break; if (2*A[j] > target - A[i]) break; int v = target - A[i] - A[j]; if (mymap.count(v) > 0) { ans = (ans + getCount(A[i], A[j], v, mymap)) % MOD; } } } return ans; } }; ================================================ FILE: cpp/921-930/Binary Subarrays With Sum.cpp ================================================ class Solution { public: int numSubarraysWithSum(vector& A, int S) { unordered_map mymap; int sum = 0; int ans = 0; mymap[0] = -1; for (int i = 0; i < A.size(); i++) { sum += A[i]; if (A[i] == 1) mymap[sum] = i; if (sum >= S) { int needed = sum - S; int idx2 = mymap.count(needed+1) == 0 ? i : mymap[needed+1]; int idx1 = mymap[needed]; ans += (idx2 - idx1); } } return ans; } }; ================================================ FILE: cpp/921-930/Flip String to Monotone Increasing.cpp ================================================ class Solution { public: int minFlipsMonoIncr(string S) { int rightZero = 0; for (char ch : S) if (ch == '0') rightZero++; int ans = min(rightZero, (int)S.size() - rightZero); int leftOne = 0; for (int i = 0; i < S.size(); i++) { ans = min(ans, rightZero + leftOne); if (S[i] == '1') leftOne++; else rightZero--; } return ans; } }; ================================================ FILE: cpp/921-930/Long Pressed Name.cpp ================================================ class Solution { public: bool isLongPressedName(string name, string typed) { int i = 0; for (char ch : name) { if (typed[i] == ch) { i++; continue; } while (i > 0 && i < typed.size() && typed[i] == typed[i-1]) i++; if (typed[i] == ch) { i++; continue; } else return false; } return true; } }; ================================================ FILE: cpp/921-930/Minimize Malware Spread.cpp ================================================ class Solution { vector parents; public: int minMalwareSpread(vector>& graph, vector& initial) { int n = graph.size(); for (int i = 0; i < n; ++i) parents.push_back(i); for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) if (graph[i][j]) uni(i, j); vector area(n, 0), malware(n, 0); for (int i = 0; i < n; ++i) area[find(i)]++; for (int i : initial) malware[find(i)]++; int maxarea = 1, idx = initial[0]; for (int i : initial) { if (malware[find(i)] == 1 && area[find(i)] > maxarea) { maxarea = area[find(i)]; idx = i; } if (maxarea == 1) { idx = min(idx, i); } } return idx; } int find(int x) { if (x != parents[x]) parents[x] = find(parents[x]); return parents[x]; } void uni(int x, int y) { parents[find(x)] = find(y); } }; ================================================ FILE: cpp/921-930/Minimum Add to Make Parentheses Valid.cpp ================================================ class Solution { public: int minAddToMakeValid(string S) { int left = 0, ans = 0; for (char ch : S) { if (ch == '(') { left++; } else { if (left > 0) left--; else ans++; } } return ans + left; } }; ================================================ FILE: cpp/921-930/Sort Array By Parity II.cpp ================================================ class Solution { public: vector sortArrayByParityII(vector& A) { int i = 0, j = 1; for (int k = 0; k < A.size(); k++) { if (A[k] % 2 == 0) { if (k % 2 == 0) continue; swap(A[i], A[k]); i += 2; } else { if (k % 2 == 1) continue; swap(A[j], A[k]); j += 2; } k--; } return A; } }; ================================================ FILE: cpp/921-930/Three Equal Parts.cpp ================================================ class Solution { public: vector threeEqualParts(vector& A) { int numOfOne = 0; for (int e : A) numOfOne += e; if (numOfOne == 0) return { 0, A.size()-1 }; if (numOfOne % 3 != 0) return { -1, -1 }; int expectedOne = numOfOne / 3; int paddingZero = 0; int currentOne = 0; int pos = A.size() - 1; while (currentOne < expectedOne) { if(A[pos] == 1) { currentOne++; } else { if (currentOne == 0) { paddingZero++; } } pos--; } int currentPaddingZero = 0; while (A[pos] == 0) { currentPaddingZero++; pos--; } if (currentPaddingZero < paddingZero) return { -1, -1 }; int pos2 = pos + 1 + paddingZero; currentOne = 0; while (currentOne < expectedOne) { if(A[pos] == 1) { currentOne++; } pos--; } currentPaddingZero = 0; while (pos >=0 && A[pos] == 0) { currentPaddingZero++; pos--; } if (currentPaddingZero < paddingZero) return { -1, -1 }; int i = pos + paddingZero, j = pos2-1; while (i >= 0 && j > pos) { if (A[i] != A[j]) return { -1, -1 }; i--; j--; } return { pos + paddingZero, pos2 }; } }; ================================================ FILE: cpp/921-930/Unique Email Addresses.cpp ================================================ class Solution { public: int numUniqueEmails(vector& emails) { set uniqueEmails; for (string email : emails) { string ans; int idx = email.find('@'); for (char ch : email) { if (ch == '.') continue; if (ch == '+' || ch == '@') break; } ans = ans + email.substr(idx, email.size() - idx); uniqueEmails.insert(ans); } return uniqueEmails.size(); } }; ================================================ FILE: cpp/931-940/Beautiful Array.cpp ================================================ class Solution { public: vector beautifulArray(int N) { vector res = {1}; while (res.size() < N) { vector tmp; for (int i : res) if (i * 2 - 1 <= N) tmp.push_back(i * 2 - 1); for (int i : res) if (i * 2 <= N) tmp.push_back(i * 2); res = tmp; } return res; } }; ================================================ FILE: cpp/931-940/Distinct Subsequences II.cpp ================================================ class Solution { public: int distinctSubseqII(string S) { // Create an array to store index of last vector last(256, -1); int n = S.length(); long dp[n+1]; long MOD = 1000000007; // Empty substring has only one subsequence dp[0] = 1; for (int i = 1; i <= n; i++) { dp[i] = (2*dp[i-1]) % MOD; // If current character has appeared before, then remove all subsequences // ending with previous occurrence. if (last[S[i-1]] != -1) dp[i] = (dp[i] + MOD - dp[last[S[i-1]]]) % MOD; last[S[i-1]] = (i-1); } // Remove the empty string. return dp[n] - 1; } }; ================================================ FILE: cpp/931-940/Knight Dialer.cpp ================================================ class Solution { public: int knightDialer(int N) { vector> dp(2, vector(10, 1)); long MOD = 1000000007; for (int i = 1; i < N; i++) { dp[1][0] = (dp[0][4] + dp[0][6]) % MOD; dp[1][1] = (dp[0][6] + dp[0][8]) % MOD; dp[1][2] = (dp[0][7] + dp[0][9]) % MOD; dp[1][3] = (dp[0][4] + dp[0][8]) % MOD; dp[1][4] = (dp[0][0] + dp[0][3] + dp[0][9]) % MOD; dp[1][5] = 0; dp[1][6] = (dp[0][0] + dp[0][1] + dp[0][7]) % MOD; dp[1][7] = (dp[0][2] + dp[0][6]) % MOD; dp[1][8] = (dp[0][1] + dp[0][3]) % MOD; dp[1][9] = (dp[0][2] + dp[0][4]) % MOD; dp[0] = dp[1]; } return accumulate(dp.front().begin(), dp.front().end(), 0l) % MOD; } }; ================================================ FILE: cpp/931-940/Minimum Area Rectangle.cpp ================================================ class Solution { public: int minAreaRect(vector>& points) { set> myset; for (const vector& point : points) { myset.insert({point[0], point[1]}); } int ans = INT_MAX; for (int i = 0; i < points.size(); i++) { for (int j = i + 1; j < points.size(); j++) { pair a{points[i][0], points[j][1]}; pair b{points[j][0], points[i][1]}; if (a.first != b.first && a.second != b.second && myset.count(a) > 0 && myset.count(b) > 0) { int w = abs(a.first - b.first); int h = abs(a.second - b.second); ans = min(ans, w * h); } } } return ans == INT_MAX ? 0 : ans; } }; ================================================ FILE: cpp/931-940/Minimum Falling Path Sum.cpp ================================================ class Solution { public: int minFallingPathSum(vector>& A) { for (int i = 1; i < A.size(); ++i) for (int j = 0; j < A.size(); ++j) A[i][j] += min(A[i-1][j], min(A[i-1][max(0,j-1)], A[i-1][min((int)A.size()-1,j+1)])); return *min_element(begin(A.back()), end(A.back())); } }; ================================================ FILE: cpp/931-940/Number of Recent Calls.cpp ================================================ class RecentCounter { public: queue q; RecentCounter() { } int ping(int t) { while (!q.empty() && q.front() < t-3000) q.pop(); q.push(t); return q.size(); } }; /** * Your RecentCounter object will be instantiated and called as such: * RecentCounter* obj = new RecentCounter(); * int param_1 = obj->ping(t); */ ================================================ FILE: cpp/931-940/Range Sum of BST.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { int dfs(TreeNode* root, int L, int R) { if (root == nullptr) return 0; int v = dfs(root->left, L, R) + dfs(root->right, L, R); if (root->val >= L && root->val <= R) return v + root->val; else return v; } public: int rangeSumBST(TreeNode* root, int L, int R) { return dfs(root, L, R); } }; ================================================ FILE: cpp/931-940/Reorder Log Files.cpp ================================================ class Solution { public: vector reorderLogFiles(vector& logs) { auto cmp = [](const string& l, const string& r) { int lp = l.find(" "); int rp = r.find(" "); return l.substr(lp) < r.substr(rp); }; // In-place partition int left = logs.size() - 1; int right = logs.size() - 1; while (left > -1) { if (isdigit(logs[left].back())) { swap(logs[left], logs[right]); --right; } --left; } // lexicographic order sort sort(logs.begin(), logs.begin() + right + 1, cmp); return logs; } }; ================================================ FILE: cpp/931-940/Shortest Bridge.cpp ================================================ class Solution { public: int shortestBridge(vector>& A) { int row = A.size(); int col = A[0].size(); int c, r; // find the first '1' (i.e. the first island) by scaning the matrix for (int i = 0; i < row * col; i++) { c = i % col; r = i / col; if (A[r][c] == 1) break; } queue> q1,q2; q1.push({r,c}); A[r][c] = -1; int d[][2] = {{-1,0}, {0,1}, {1,0}, {0, -1}}; while (!q1.empty()) { auto cur = q1.front(); q1.pop(); for (int i = 0; i < 4; i++) { int newr = cur.first + d[i][0]; int newc = cur.second + d[i][1]; if (newr < 0 || newc < 0 || newr >= row || newc >= col) continue; if (A[newr][newc] == 1) { A[newr][newc] = -1; q1.push({newr, newc}); } else if (A[newr][newc] == 0) { A[newr][newc] = -1; q2.push({newr, newc}); } } } int step = 0; while (!q2.empty()) { auto size = q2.size(); step++; for (int j = 0; j < size; j++) { auto cur = q2.front(); q2.pop(); for (int i = 0; i < 4; i++) { int newr = cur.first + d[i][0]; int newc = cur.second + d[i][1]; if (newr < 0 || newc < 0 || newr >= row || newc >= col) continue; if (A[newr][newc] == -1) continue; if (A[newr][newc] == 1) return step; q2.push({newr, newc}); A[newr][newc] = -1; } } } } }; ================================================ FILE: cpp/931-940/Stamping The Sequence.cpp ================================================ class Solution { public: vector movesToStamp(string stamp, string target) { vector res; int total_stamp = 0, turn_stamp = -1; while (turn_stamp != 0) { turn_stamp = 0; for (int sz = stamp.size(); sz > 0; --sz) for (int i = 0; i <= stamp.size() - sz; ++i) { string new_stamp = string(i, '*') + stamp.substr(i, sz) + string(stamp.size() - sz - i, '*'); size_t pos = target.find(new_stamp); while (pos != string::npos) { res.push_back(pos); turn_stamp += sz; fill(begin(target) + pos, begin(target) + pos + stamp.size(), '*'); pos = target.find(new_stamp); } } total_stamp += turn_stamp; } reverse(begin(res), end(res)); return total_stamp == target.size() ? res : vector(); } }; ================================================ FILE: cpp/941-950/Bag of Tokens.cpp ================================================ class Solution { public: int bagOfTokensScore(vector& tokens, int P) { sort(tokens.begin(), tokens.end()); int i = 0, j = tokens.size() - 1; int points = 0; while (true) { while (i <= j && P >= tokens[i]) { points++; P -= tokens[i]; i++; } if (i >= j || points <= 0) break; P += tokens[j]; j--; points--; } return points; } }; ================================================ FILE: cpp/941-950/DI String Match.cpp ================================================ class Solution { public: vector diStringMatch(string S) { vector ans(S.size() + 1); int low = 0; int high = S.size(); for (int i = 0; i < S.size(); i++) { if (S[i] == 'I') { ans[i] = low; low++; } else { ans[i] = high; high--; } } ans[S.size()] = low; return ans; } }; ================================================ FILE: cpp/941-950/Delete Columns to Make Sorted.cpp ================================================ class Solution { public: int minDeletionSize(vector& A) { int res = 0; if (A.empty()) return res; for (int c = 0; c < A[0].size(); ++c) for (int i = 1; i < A.size(); ++i) { if (A[i - 1][c] > A[i][c]) { ++res; break; } } return res; } }; ================================================ FILE: cpp/941-950/Minimum Increment to Make Array Unique.cpp ================================================ class Solution { public: int minIncrementForUnique(vector& A) { sort(A.begin(), A.end()); int res = 0, need = 0; for (int a: A) { res += max(need - a, 0); need = max(a, need) + 1; } return res; } }; ================================================ FILE: cpp/941-950/Most Stones Removed with Same Row or Column.cpp ================================================ class UF { private: vector parent; vector rank; int count; int N; bool validate(int p) { return (p >= 0 && p < N); } public: UF(int N) : parent(N), rank(N, 0), N(N), count(N) { for (int i = 0; i < N; i++) { parent[i] = i; } } int find(int p) { if (!validate(p)) return -1; while (p != parent[p]) { parent[p] = parent[parent[p]]; // path compression by halving p = parent[p]; } return p; } int getCount() const { return count; } bool connected(int p, int q) { return find(p) == find(q); } void Union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make root of smaller rank point to root of larger rank if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ; else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP; else { parent[rootQ] = rootP; rank[rootP]++; } count--; } }; class Solution { public: int removeStones(vector>& stones) { UF uf(20000); for (const vector& stone: stones) { uf.Union(stone[0], stone[1]+10000); } set myset; for (const vector& stone: stones) { myset.insert(uf.find(stone[0])); } return stones.size() - myset.size(); } }; ================================================ FILE: cpp/941-950/Valid Mountain Array.cpp ================================================ class Solution { public: bool validMountainArray(vector& A) { if (A.size() < 3) return false; if (A[1] <= A[0]) return false; if (A[A.size()-2] <= A[A.size()-1]) return false; int i = 0, j = A.size()-1; while (A[i] < A[i+1]) i++; while (A[j] < A[j-1]) j--; return i == j; } }; ================================================ FILE: cpp/941-950/Validate Stack Sequences.cpp ================================================ class Solution { public: bool validateStackSequences(vector& pushed, vector& popped) { stack mystack; int i = 0; for (int e : pushed) { if (e == popped[i]) { // check if we should pop more elements. i++; while (!mystack.empty() && mystack.top() == popped[i]) { mystack.pop(); i++; } } else { mystack.push(e); } } return mystack.empty(); } }; ================================================ FILE: cpp/951-960/Check Completeness of a Binary Tree.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isCompleteTree(TreeNode* root) { if (root == nullptr) return true; queue myqueue; myqueue.push(root); bool flag = false; while (!myqueue.empty()) { TreeNode* node = myqueue.front(); myqueue.pop(); if (node->left) { if (flag) return false; myqueue.push(node->left); } else { flag = true; } if (node->right) { if (flag) return false; myqueue.push(node->right); } else { flag = true; } } return true; } }; ================================================ FILE: cpp/951-960/Prison Cells After N Days.cpp ================================================ class Solution { vector int2vec(int n) { vector result(8, 0); for (int i = 0; i < 8; i++) { int v = n & 1; result[7 - i] = v; n /= 2; } return result; } int ith(int a, int i) { return (a >> i) & 1; } int transform(int num) { int result = 0; for (int i = 1; i <= 6; i++) { int tmp = (ith(num, i-1) == ith(num, i+1)); result |= (tmp << i); } result &= 126; return result; } public: vector prisonAfterNDays(vector& cells, int N) { int start = 0; for (auto p = cells.begin(); p != cells.end(); p++) { start *= 2; start |= *p; } map mymap; map step2v; mymap[start] = 0; step2v[0] = start; int i = 0; while (i < N) { start = transform(start); i++; if (mymap.count(start) == 1) { int coef = i - mymap[start]; int mystep = ((N - i) % coef) + mymap[start]; return int2vec(step2v[mystep]); } mymap[start] = i; step2v[i] = start; } return int2vec(start); } }; ================================================ FILE: cpp/951-960/Regions Cut By Slashes.cpp ================================================ class UF { private: vector parent; vector rank; int count; int N; public: UF(int N) : parent(N), rank(N, 0), N(N), count(N) { for (int i = 0; i < N; i++) { parent[i] = i; } } int find(int p) { while (p != parent[p]) { parent[p] = parent[parent[p]]; // path compression by halving p = parent[p]; } return p; } int getCount() const { return count; } bool connected(int p, int q) { return find(p) == find(q); } void Union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make root of smaller rank point to root of larger rank if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ; else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP; else { parent[rootQ] = rootP; rank[rootP]++; } count--; } }; class Solution { public: int regionsBySlashes(vector& grid) { int n = grid.size(); UF uf(4*n*n); for (int r = 0; r < n; ++r) { for (int c = 0; c < n; ++c) { int root = 4 * (r * n + c); char val = grid[r][c]; if (val != '\\') { uf.Union(root + 0, root + 1); uf.Union(root + 2, root + 3); } if (val != '/') { uf.Union(root + 0, root + 2); uf.Union(root + 1, root + 3); } // north south if (r + 1 < n) uf.Union(root + 3, (root + 4 * n) + 0); if (r - 1 >= 0) uf.Union(root + 0, (root - 4 * n) + 3); // east west if (c + 1 < n) uf.Union(root + 2, (root + 4) + 1); if (c - 1 >= 0) uf.Union(root + 1, (root - 4) + 2); } } return uf.getCount(); } }; ================================================ FILE: cpp/951-960/Verifying an Alien Dictionary.cpp ================================================ class Solution { bool check(const string& previous_word, const string& current_word, char* orders) { int len = min(previous_word.length(), current_word.length()); for (int i = 0; i < len; i++) { char p_ch = previous_word[i]; char c_ch = current_word[i]; if (orders[p_ch - 'a'] < orders[c_ch - 'a']) return true; if (orders[p_ch - 'a'] > orders[c_ch - 'a']) return false; } return previous_word <= current_word; } public: bool isAlienSorted(vector& words, string order) { char orders[26]; for (int i = 0; i < order.length(); i++) { orders[order[i] - 'a'] = i; } for (int i = 1; i < words.size(); i++) { const string& previous_word = words[i - 1]; const string& current_word = words[i]; if (!check(previous_word, current_word, orders)) { return false; } } return true; } }; ================================================ FILE: cpp/961-970/N-Repeated Element in Size 2N Array.cpp ================================================ class Solution { public: int repeatedNTimes(vector& A) { for (auto i = 0; i < A.size() - 2; ++i) { if (A[i] == A[i + 1] || A[i] == A[i + 2]) { return A[i]; } } return A[A.size() - 1]; } }; ================================================ FILE: cpp/961-970/Pancake Sorting.cpp ================================================ class Solution { public: vector pancakeSort(vector& A) { vector res; int x,i; for (x = A.size(); x > 0; --x) { for (i = 0; A[i] != x; ++i); reverse(A.begin(), A.begin() + i + 1); res.push_back(i + 1); reverse(A.begin(), A.begin() + x); res.push_back(x); } return res; } }; ================================================ FILE: cpp/971-980/Distribute Coins in Binary Tree.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { int ans; // {num of nodes, num of coins} pair dfs(TreeNode* root) { if (root == nullptr) return {0, 0}; auto leftRes = dfs(root->left); auto rightRes = dfs(root->right); if (leftRes.first > leftRes.second) { ans += (leftRes.first - leftRes.second); } if (rightRes.first > rightRes.second) { ans += (rightRes.first - rightRes.second); } int node = leftRes.first + rightRes.first + 1; int coin = leftRes.second + rightRes.second + root->val; if (coin > node) ans += (coin - node); return {node, coin}; } public: int distributeCoins(TreeNode* root) { ans = 0; dfs(root); return ans; } }; ================================================ FILE: cpp/971-980/K Closest Points to Origin.cpp ================================================ class Solution { public: vector> kClosest(vector>& points, int K) { auto cmp = [&](const vector& a, const vector& b) { return a[0] * a[0] + a[1] * a[1] < b[0] * b[0] + b[1] * b[1]; }; nth_element(points.begin(), points.begin() + K, points.end(), cmp); // sort(points.begin(), points.end(), cmp); vector> ans(points.begin(), points.begin() + K); return ans; } }; ================================================ FILE: cpp/971-980/Largest Perimeter Triangle.cpp ================================================ class Solution { public: int largestPerimeter(vector& A) { sort(A.begin(), A.end()); for (int i = A.size() - 1; i >= 2; i--) { if (A[i-2] + A[i-1] > A[i]) { return A[i] + A[i-1] + A[i-2]; } } return 0; } }; ================================================ FILE: cpp/971-980/Longest Turbulent Subarray.cpp ================================================ class Solution { public: int maxTurbulenceSize(vector& A) { int ans = 0; int i = 0; int currentFlag = 0; int currentLen = 1; while (i + 1 < A.size()) { if (A[i] < A[i+1]) { if (currentFlag == -1) { currentLen++; } else if (currentFlag == 1) { currentLen = 2; } else { currentLen = 2; } currentFlag = 1; } else if (A[i] > A[i+1]) { if (currentFlag == -1) { currentLen = 2; } else if (currentFlag == 1) { currentLen++; } else { currentLen = 2; } currentFlag = -1; } else { currentFlag = 0; currentLen = 1; } i++; ans = max(currentLen, ans); } return max(currentLen, ans); } }; ================================================ FILE: cpp/971-980/Squares of a Sorted Array.cpp ================================================ class Solution { public: vector sortedSquares(vector& A) { vector ans(A.size()); int i = 0, j = A.size() - 1; int k = 0; while (i <= j) { if (abs(A[i]) >= abs(A[j])) { ans[k] = A[i]*A[i]; i++; } else { ans[k] = A[j]*A[j]; j--; } k++; } reverse(ans.begin(), ans.end()); return ans; } }; ================================================ FILE: cpp/971-980/Subarray Sums Divisible by K.cpp ================================================ class Solution { public: int subarraysDivByK(vector& A, int K) { vector record(K+1, 0); record[0] = 1; int sum = 0; int ans = 0; for (int e : A) { sum += e; // Make it a positive number to avoid bad mod. if (sum < 0) sum += (-1*sum / K) * K + K; int target = sum % K; // You can also remove following line. sum = target; ans += record[target]; record[target]++; } return ans; } }; ================================================ FILE: cpp/971-980/Unique Paths III.cpp ================================================ class Solution { int dfs(vector>& grid, int i, int j, int w, int h, int n) { if (i < 0 || i >= w || j < 0 || j >= h) return 0; if (grid[i][j] == -1) return 0; if (grid[i][j] == 999) return 0; if (grid[i][j] == 2) { if (n == -1) return 1; else return 0; } grid[i][j] = 999; int ans = 0; ans += dfs(grid, i-1, j, w, h, n-1); ans += dfs(grid, i+1, j, w, h, n-1); ans += dfs(grid, i, j-1, w, h, n-1); ans += dfs(grid, i, j+1, w, h, n-1); grid[i][j] = 0; return ans; } public: int uniquePathsIII(vector>& grid) { int w = grid.size(); int h = grid.front().size(); int n = 0; int ii, jj; for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { if (grid[i][j] == 0) { n++; } if (grid[i][j] == 1) { ii = i; jj = j; } } } return dfs(grid, ii, jj, w, h, n); } }; ================================================ FILE: cpp/981-990/Add to Array-Form of Integer.cpp ================================================ class Solution { public: vector addToArrayForm(vector& A, int K) { reverse(A.begin(), A.end()); vector B; while (K > 0) { int v = K % 10; B.push_back(v); K = K / 10; } int carry = 0; B.resize(max(A.size(), B.size())); for (int i = 0; i < max(A.size(), B.size()); i++) { int a = i < A.size() ? A[i] : 0; int b = i < B.size() ? B[i] : 0; int v = a + b + carry; B[i] = v % 10; carry = v / 10; } if (carry) { B.push_back(1); } reverse(B.begin(), B.end()); return B; } }; ================================================ FILE: cpp/981-990/Interval List Intersections.cpp ================================================ class Solution { vector getInterval(const vector& a, const vector& b) { vector ans(2, 0); ans[0] = max(a[0], b[0]); ans[1] = min(a[1], b[1]); return ans; } public: vector> intervalIntersection(vector>& A, vector>& B) { int i = 0, j = 0; vector> ans; while (i < A.size() && j < B.size()) { const vector& first = A[i]; const vector& second = B[j]; if (first[1] < second[0]) { i++; } else if (second[1] < first[0]) { j++; } else { ans.emplace_back(getInterval(first, second)); if (first[1] < second[1]) { i++; } else if (first[1] > second[1]) { j++; } else { i++; j++; } } } return ans; } }; ================================================ FILE: cpp/981-990/Satisfiability of Equality Equations.cpp ================================================ class UF { private: vector parent; vector rank; int count; int N; bool validate(int p) { return (p >= 0 && p < N); } public: UF(int N) : parent(N), rank(N, 0), N(N), count(N) { for (int i = 0; i < N; i++) { parent[i] = i; } } int find(int p) { if (!validate(p)) return -1; while (p != parent[p]) { parent[p] = parent[parent[p]]; // path compression by halving p = parent[p]; } return p; } int getCount() const { return count; } bool connected(int p, int q) { return find(p) == find(q); } void Union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make root of smaller rank point to root of larger rank if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ; else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP; else { parent[rootQ] = rootP; rank[rootP]++; } count--; } ~UF() {} }; class Solution { public: bool equationsPossible(vector& equations) { UF uf(256); // go through == first for (const string& str : equations) { if (str[1] == '=') { uf.Union(str[0], str[3]); } } // then go through != for (const string& str : equations) { if (str[1] == '!') { if (uf.connected(str[0], str[3])) { return false; } } } return true; } }; ================================================ FILE: cpp/981-990/String Without AAA or BBB.cpp ================================================ class Solution { public: string strWithout3a3b(int A, int B) { string ans = " "; while (A > 0 || B > 0) { if (A == B) { A--; B--; ans = ans + (ans.back() == 'a' ? "ba" : "ab"); } else if (A > B) { if (ans.back() == 'a') { ans = ans + 'b'; B--; } else { ans = ans + 'a'; A--; if (A > 0) { ans = ans + 'a'; A--; } } } else { if (ans.back() == 'b') { ans = ans + 'a'; A--; } else { ans = ans + 'b'; B--; if (B > 0) { ans = ans + 'b'; B--; } } } } return ans.substr(1); } }; ================================================ FILE: cpp/981-990/Time Based Key-Value Store.cpp ================================================ class TimeMap { unordered_map>> db; public: TimeMap() { } void set(string key, string value, int timestamp) { db[key].push_back({timestamp, value}); } string get(string key, int timestamp) { auto cmp = [](const pair& lhs, const pair& rhs) { return lhs.first < rhs.first; }; auto it = upper_bound(db[key].begin(), db[key].end(), make_pair(timestamp, ""), cmp); if (it == db[key].begin()) { return ""; } else { it--; return it->second; } } }; /** * Your TimeMap object will be instantiated and called as such: * TimeMap* obj = new TimeMap(); * obj->set(key,value,timestamp); * string param_2 = obj->get(key,timestamp); */ ================================================ FILE: cpp/991-1000/Broken Calculator.cpp ================================================ class Solution { map cache; public: int brokenCalc(int X, int Y) { int ans = 0; while (Y > X) { ans++; if (Y % 2 == 1) Y++; else Y /= 2; } return ans + X - Y; } }; ================================================ FILE: cpp/991-1000/Cousins in Binary Tree.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { // {parent, depth} bool getPD(TreeNode* root, int v, pair* res, int depth, TreeNode* parent) { if (root == nullptr) return false; if (root->val == v) { res->first = parent; res->second = depth; return true; } bool flag = getPD(root->left, v, res, depth+1, root); if (flag) return true; flag = getPD(root->right, v, res, depth+1, root); return flag; } public: bool isCousins(TreeNode* root, int x, int y) { pair left, right; getPD(root, x, &left, 0, nullptr); getPD(root, y, &right, 0, nullptr); if (left.second != right.second) return false; if (left.first == right.first) return false; return true; } }; ================================================ FILE: cpp/991-1000/Find the Town Judge.cpp ================================================ class Solution { public: int findJudge(int N, vector>& trust) { map mymap; for (int i = 1; i <= N; i++) mymap[i] = 0; for (const auto& e : trust) { mymap[e[0]]--; mymap[e[1]]++; } for (const auto& iter : mymap) { if (iter.second == N - 1) return iter.first; } return -1; } }; ================================================ FILE: cpp/991-1000/Maximum Binary Tree II.cpp ================================================ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* insertIntoMaxTree(TreeNode* root, int val) { if (root != nullptr && root->val > val) { root->right = insertIntoMaxTree(root->right, val); return root; } TreeNode* node = new TreeNode(val); node->left = root; return node; } }; ================================================ FILE: cpp/991-1000/Minimum Number of K Consecutive Bit Flips.cpp ================================================ class Solution { public: int minKBitFlips(vector& A, int K) { int ans = 0; int flag = 0; map mymap; for (int i = 0; i < A.size(); i++) { flag ^= mymap[i]; if (A[i] + flag == 1) continue; // flip ans++; flag = 1 - flag; if (i + K > A.size()) return -1; mymap[i+K] = 1 - mymap[i+K]; } return ans; } }; ================================================ FILE: cpp/991-1000/Number of Squareful Arrays.cpp ================================================ class Solution { int ans; set ans_set; void dfs(int i, const vector>& graph, const vector& A, bool* visited, string temp, int count) { visited[i] = true; temp += to_string(A[i]); if (count == graph.size()) { if (ans_set.count(temp) == 0) { ans++; ans_set.insert(temp); } } else { set performance; for (int k = 0; k < graph[i].size(); k++) { int index = graph[i][k]; if (performance.count(A[index]) == 1) continue; if (visited[index] == false) { performance.insert(A[index]); dfs(index, graph, A, visited, temp, count+1); } } } visited[i] = false; } public: int numSquarefulPerms(vector& A) { vector> graph(A.size(), vector()); for (int i = 0; i < A.size(); i++) { for (int j = 0; j < A.size(); j++) { if (i == j) continue; int val = A[i] + A[j]; int root = sqrt(val); if (root*root == val) { graph[i].push_back(j); graph[j].push_back(i); } } } bool visited[12] = {false}; set performance; for (int i = 0; i < A.size(); i++) { if (performance.count(A[i]) == 1) continue; performance.insert(A[i]); dfs(i, graph, A, visited, "", 1); } return ans; } }; ================================================ FILE: cpp/991-1000/Rotting Oranges.cpp ================================================ class Solution { public: int orangesRotting(vector>& grid) { // BFS queue> rot; int previous_fresh = -1; int fresh = 0; int h = grid.size(); int w = grid.front().size(); for (int i = 0; i < grid.size(); i++) { for (int j = 0; j < grid[i].size(); j++) { if (grid[i][j] == 1) { fresh++; } else if (grid[i][j] == 2) { rot.push({i, j}); } } } int day = 0; while (!rot.empty() && fresh > 0) { previous_fresh = fresh; int n = rot.size(); for (int i = 0; i < n; i++) { auto e = rot.front(); rot.pop(); pair directions[4] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; for (int j = 0; j < 4; j++) { int newi = e.first + directions[j].first; int newj = e.second + directions[j].second; if (newi < 0 || newj < 0 || newi >= h || newj >= w) continue; if (grid[newi][newj] == 1) { fresh--; rot.push({newi, newj}); grid[newi][newj] = 2; } } } day++; } return fresh == 0 ? day : -1; } }; ================================================ FILE: golang/001-010/Add Two Numbers.go ================================================ /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { carry := 0 var virtual_head *ListNode = new(ListNode) copy_virtual_head := virtual_head for l1 != nil || l2 != nil || carry > 0 { v1 := 0 v2 := 0 if l1 != nil { v1 = l1.Val l1 = l1.Next } if l2 != nil { v2 = l2.Val l2 = l2.Next } tmp := v1 + v2 + carry carry = tmp/10 var new_node *ListNode = new(ListNode) new_node.Val = tmp%10; virtual_head.Next = new_node virtual_head = new_node } return copy_virtual_head.Next } ================================================ FILE: golang/001-010/Longest Substring Without Repeating Characters.go ================================================ func lengthOfLongestSubstring(s string) int { var i, maximum_len int = 0, 0 mymap := make(map[byte]int) for j := 0; j < len(s); j++ { mymap[s[j]]++ for mymap[s[j]] == 2 && i < j { mymap[s[i]]-- i++ } if maximum_len < j - i + 1 { maximum_len = j - i + 1 } } return maximum_len } ================================================ FILE: golang/001-010/Two Sum.go ================================================ func twoSum(nums []int, target int) []int { mymap := make(map[int]int) for i := 0; i < len(nums); i++ { j, ok := mymap[target-nums[i]] if ok { result := []int{j, i} return result } mymap[nums[i]] = i } result := []int{-1, -1} return result } ================================================ FILE: java/201-210/Happy Number.java ================================================ public class Solution { public int convert(String str) { int val = 0; for (int i = 0, n = str.length(); i < n; i++) { int c = str.charAt(i) - '0'; val += c*c; } return val; } public boolean isHappy(int n) { Map m1 = new HashMap(); while(n != 1) { m1.put(n, true); n = convert(Integer.toString(n)); if(m1.containsKey(n)) return false; } return true; } } ================================================ FILE: java/291-300/Nim Game.java ================================================ public class Solution { public boolean canWinNim(int n) { return n%4 != 0; } } ================================================ FILE: java/331-340/Counting Bits.java ================================================ /* * 0000 0001 0010 0011 0100 0101 0110 0111 1000 * 0 1 1 2 1 2 2 3 1 */ public class Solution { public int[] countBits(int num) { int[] result = new int[num+1]; if(num == 0) return result; int loops = 1; while(true) { for(int k = 0;k < loops;k++) { int index = k+loops; if(index > num) return result; result[index] = result[k]+1; } loops *= 2; } } } ================================================ FILE: java/331-340/Nested List Weight Sum.java ================================================ /** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * public interface NestedInteger { * * // @return true if this NestedInteger holds a single integer, rather than a nested list. * public boolean isInteger(); * * // @return the single integer that this NestedInteger holds, if it holds a single integer * // Return null if this NestedInteger holds a nested list * public Integer getInteger(); * * // @return the nested list that this NestedInteger holds, if it holds a nested list * // Return null if this NestedInteger holds a single integer * public List getList(); * } */ public class Solution { public int helper(List nestedList, int depth) { int sum = 0; for (int i = 0; i < nestedList.size(); i++) { if(nestedList.get(i).isInteger()) sum += nestedList.get(i).getInteger() * depth; else sum += helper(nestedList.get(i).getList(), depth+1); } return sum; } public int depthSum(List nestedList) { return helper(nestedList, 1); } } ================================================ FILE: python/001-010/Median of Two Sorted Arrays.py ================================================ def findMedianSortedArrays(self, A, B): l = len(A) + len(B) if l % 2 == 1: return self.kth(A, B, l // 2) else: return (self.kth(A, B, l // 2) + self.kth(A, B, l // 2 - 1)) / 2. def kth(self, a, b, k): if not a: return b[k] if not b: return a[k] ia, ib = len(a) // 2 , len(b) // 2 ma, mb = a[ia], b[ib] # when k is bigger than the sum of a and b's median indices if ia + ib < k: # if a's median is bigger than b's, b's first half doesn't include k if ma > mb: return self.kth(a, b[ib + 1:], k - ib - 1) else: return self.kth(a[ia + 1:], b, k - ia - 1) # when k is smaller than the sum of a and b's indices else: # if a's median is bigger than b's, a's second half doesn't include k if ma > mb: return self.kth(a[:ia], b, k) else: return self.kth(a, b[:ib], k) ================================================ FILE: python/011-020/Valid Parentheses.py ================================================ class Solution: # @param {string} s # @return {boolean} def isValid(self, s): stack = [] dict = {"]":"[", "}":"{", ")":"("} for char in s: if char in dict.values(): stack.append(char) elif char in dict.keys(): if stack == [] or dict[char] != stack.pop(): return False else: return False return not stack ================================================ FILE: python/021-030/Reverse Nodes in k-Group.py ================================================ #!/usr/bin/env python # coding=utf-8 # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param {ListNode} head # @param {integer} k # @return {ListNode} def reverseKGroup(self, head, k): if not head or k < 2: return head ret = head for i in range(k-1): ret = ret.next if not ret: return head prev,cur = None,head for i in range(k): tmp = cur.next cur.next = prev prev = cur cur = tmp head.next = self.reverseKGroup(cur, k) return ret ================================================ FILE: python/031-040/Combination Sum II.py ================================================ class Solution: # @param {integer[]} candidates # @param {integer} target # @return {integer[][]} def combinationSum2(self, candidates, target): candidates.sort() result = [] tmp = [] self.help(tmp, candidates, 0, target, result) return result def help(self, now, candidates, index, target, result): i = index while i < len(candidates): if candidates[i] < target: now.append(candidates[i]); self.help(now, candidates, i+1, target-candidates[i], result) del now[-1] while i < len(candidates)-1 and candidates[i] == candidates[i+1]: i += 1 elif candidates[i] == target: temp = now[:] temp.append(candidates[i]) result.append(temp) return i += 1 ================================================ FILE: python/031-040/Combination Sum.py ================================================ #!/usr/bin/env python # coding=utf-8 class Solution: # @param {integer[]} candidates # @param {integer} target # @return {integer[][]} def combinationSum(self, candidates, target): candidates.sort() result = [] tmp = [] self.help(tmp, candidates, 0, target, result) return result def help(self, now, candidates, index, target, result): for i in range(index, len(candidates)): if candidates[i] < target: now.append(candidates[i]); self.help(now, candidates, i, target-candidates[i], result) del now[-1] elif candidates[i] == target: now.append(candidates[i]) temp = now[:] result.append(temp) del now[-1] ================================================ FILE: python/031-040/Next Permutation.py ================================================ class Solution(object): def nextPermutation(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ i = len(nums) - 2 while i >= 0 and nums[i] >= nums[i+1]: i -= 1 left = i+1 right = len(nums)-1; while left < right: nums[left], nums[right] = nums[right], nums[left] left += 1 right -= 1 if i == -1: return j = 0 v = 100000000 for k in range(i+1, len(nums)): if nums[k] > nums[i] and nums[k] < v: j = k v = nums[k] nums[i], nums[j] = nums[j], nums[i] ================================================ FILE: python/031-040/Search Insert Position.py ================================================ class Solution: # @param {integer[]} nums # @param {integer} target # @return {integer} def searchInsert(self, nums, target): lo = 0 hi = len(nums) - 1 while lo <= hi: mid = lo + (hi - lo) / 2 if target < nums[mid]: hi = mid - 1 elif target > nums[mid]: lo = mid + 1 else: return mid return lo; ================================================ FILE: python/031-040/Search for a Range.py ================================================ class Solution: # @param {integer[]} nums # @param {integer} target # @return {integer[]} def searchRange(self, nums, target): low = 0 high = len(nums)-1 res = [] while low <= high: mid = (low+high)/2 if(nums[mid] < target): low = mid+1 elif(nums[mid] > target): high = mid-1 else: bound1 = bound2 = mid while bound1 >= 0 and nums[bound1] == nums[mid]: bound1 -= 1 while bound2 < len(nums) and nums[bound2] == nums[mid]: bound2 += 1 res.append(bound1+1) res.append(bound2-1) break if(len(res) == 0): res.append(-1) res.append(-1) return res ================================================ FILE: python/031-040/Sudoku Solver.py ================================================ class Solution: def help(self, board, i, j, rows, cols, rec): if i == 9: return True nexti = nextj = 0 if j != 8: nexti = i nextj = j + 1 else: nexti = i + 1 if board[i][j] != '.': return self.help(board, nexti, nextj, rows, cols, rec) else: t = (i/3)*3+j/3 for k in range(9): if rows[i][k] == False and cols[k][j] == False and rec[t][k] == False: rows[i][k] = cols[k][j] = rec[t][k] = True board[i][j] = chr(49+k) check = self.help(board, nexti, nextj, rows, cols, rec) if check: return True rows[i][k] = cols[k][j] = rec[t][k] = False board[i][j] = '.' return False # @param {character[][]} board # @return {void} Do not return anything, modify board in-place instead. def solveSudoku(self, board): rows, cols, rec = [[False] * 9 for i in range(9)], [[False] * 9 for i in range(9)], [[False] * 9 for i in range(9)] for i in range(9): for j in range(9): if board[i][j] != '.': index = int(board[i][j]) - 1 k = (i/3)*3 + j/3 rows[i][index] = cols[index][j] = rec[k][index] = True self.help(board, 0, 0, rows, cols, rec) ================================================ FILE: python/031-040/Valid Sudoku.py ================================================ class Solution: # @param {character[][]} board # @return {boolean} def isValidSudoku(self, board): if not board: return False row, col, box = [[False] * 9 for i in range(9)], [[False] * 9 for i in range(9)], [[False] * 9 for i in range(9)] for i in range(9): for j in range(9): num = board[i][j] if num != '.': index = int(num) - 1 k = i / 3 * 3 + j / 3 if row[i][index] or col[j][index] or box[k][index]: return False row[i][index] = col[j][index] = box[k][index] = True return True ================================================ FILE: python/041-050/Jump Game II.py ================================================ class Solution: # @param {integer[]} nums # @return {integer} def jump(self, nums): step = 0 nextstep = 0 count = 0 for i in range(len(nums)): if i+nums[i] > nextstep: nextstep = i + nums[i] if i == step and i != len(nums)-1: count += 1 step = nextstep return count ================================================ FILE: python/041-050/Rotate Image.py ================================================ class Solution: # @param {integer[][]} matrix # @return {void} Do not return anything, modify matrix in-place instead. def rotate(self, matrix): n = len(matrix)-1 i = 0 while i <= n -i: j = i while j <= n - i - 1: tmp = matrix[j][n-i] matrix[j][n-i] = matrix[i][j] matrix[i][j] = matrix[n-j][i] matrix[n-j][i] = matrix[n-i][n-j] matrix[n-i][n-j] = tmp j += 1 i += 1 ================================================ FILE: python/051-060/Jump Game.py ================================================ class Solution: # @param {integer[]} nums # @return {boolean} def canJump(self, nums): l = len(nums) res = 0 for i in range(l): if i <= res: res = max(res, i+nums[i]); if res >= l-1: return True return False ================================================ FILE: python/051-060/Permutation Sequence.py ================================================ class Solution(object): def getPermutation(self, n, k): """ :type n: int :type k: int :rtype: str """ numset = ['1','2','3','4','5','6','7','8','9'] pTable = [1]*10 for i in range(1,10): pTable[i] = i * pTable[i-1] res = '' while n > 0: temp = (k-1)/pTable[n-1] res += numset[temp] del numset[temp] k -= temp * pTable[n-1] n -= 1 return res ================================================ FILE: python/061-070/Minimum Path Sum.py ================================================ class Solution: # @param {integer[][]} grid # @return {integer} def minPathSum(self, grid): n = len(grid); m = len(grid[0]); p = [([0] * m) for i in range(n)] p[0][0] = grid[0][0]; for k in range (1, n): p[k][0] = p[k-1][0]+grid[k][0]; for k in range (1, m): p[0][k] = p[0][k-1]+grid[0][k]; for i in range (1, n): for j in range (1, m): p[i][j] = min(p[i-1][j], p[i][j-1]) + grid[i][j]; return p[n-1][m-1]; ================================================ FILE: python/061-070/Sqrt(x).py ================================================ class Solution: # @param {integer} x # @return {integer} def mySqrt(self, x): if x == 0: return 0 k = 1.0 while abs(k*k-x) >= 1: k = (k+x/k)/2 return int(k) ================================================ FILE: python/061-070/Unique Paths II.py ================================================ class Solution: # @param {integer[][]} obstacleGrid # @return {integer} def uniquePathsWithObstacles(self, obstacleGrid): m = len(obstacleGrid) n = len(obstacleGrid[0]) if obstacleGrid[0][0] == 1 or obstacleGrid[m-1][n-1] == 1: return 0 table = [([0] * (n+1)) for i in range(m+1)] table[1][1] = 1 for i in range(1,m+1): for j in range(1,n+1): if i == 1 and j == 1: continue if obstacleGrid[i-1][j-1] == 1: table[i][j] = 0 else: table[i][j] = table[i-1][j] + table[i][j-1] return table[m][n] ================================================ FILE: python/061-070/Unique Paths.py ================================================ class Solution: # @param {integer} m # @param {integer} n # @return {integer} def uniquePaths(self, m, n): table = [([0] * (n+1)) for i in range(m+1)] table[1][1] = 1 for i in range(1,m+1): for j in range(1,n+1): if i == 1 and j == 1: continue table[i][j] = table[i-1][j] + table[i][j-1] return table[m][n] ================================================ FILE: python/061-070/Valid Number.py ================================================ class Solution: # @param {string} s # @return {boolean} def isNumber(self, s): try: num = float(s.strip()) return True except: return False ================================================ FILE: python/071-080/Edit Distance.py ================================================ class Solution: # @param {string} word1 # @param {string} word2 # @return {integer} def minDistance(self, word1, word2): n,m = len(word1), len(word2) p = [[0]*(m+1) for _ in range(n+1)] for i in range(1, n+1): p[i][0] = i for i in range(1, m+1): p[0][i] = i for i in range(1, n+1): for j in range(1, m+1): f = 1 if word1[i-1] != word2[j-1] else 0 p[i][j] = min(p[i-1][j]+1, p[i][j-1]+1, p[i-1][j-1]+f); return p[n][m] ================================================ FILE: python/081-090/Largest Rectangle in Histogram.py ================================================ class Solution: # @param {integer[]} height # @return {integer} def largestRectangleArea(self, height): res = 0 height.append(0) mystack = [] for i in range(len(height)): if len(mystack) == 0 or height[i] >= height[mystack[-1]]: mystack.append(i) else: while len(mystack) > 0 and height[i] < height[mystack[-1]]: h = height[mystack[-1]] del mystack[-1] width = i if len(mystack) == 0 else i - 1 - mystack[-1] res = max(res, width*h) mystack.append(i) return res ================================================ FILE: python/081-090/Maximal Rectangle.py ================================================ class Solution: # @param {character[][]} matrix # @return {integer} def maximalRectangle(self, matrix): if len(matrix) == 0: return 0 h = [0] * (len(matrix[0])+1) res = 0 for i in range(len(matrix)): matrix[i].append('0') mystack = [] for j in range(len(matrix[i])): if matrix[i][j] == '1': h[j] += 1 else: h[j] = 0 if len(mystack) == 0 or h[j] >= h[mystack[-1]]: mystack.append(j) else: while len(mystack) > 0 and h[j] < h[mystack[-1]]: height = h[mystack[-1]] del mystack[-1] width = j if len(mystack) == 0 else j - 1 - mystack[-1] res = max(res, width*height) mystack.append(j) return res ================================================ FILE: python/081-090/Remove Duplicates from Sorted List II.py ================================================ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param {ListNode} head # @return {ListNode} def deleteDuplicates(self, head): nhead = ListNode(0) prev = -2**31 res = nhead while head: if head.val != prev and (not head.next or head.val != head.next.val) : nhead.next = head nhead = head prev = head.val head = head.next nhead.next = None return res.next ================================================ FILE: python/081-090/Remove Duplicates from Sorted List.py ================================================ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param {ListNode} head # @return {ListNode} def deleteDuplicates(self, head): node = head while node and node.next: if node.val == node.next.val: node.next = node.next.next else: node = node.next return head ================================================ FILE: python/091-100/Decode Ways.py ================================================ #!/usr/bin/env python # coding=utf-8 class Solution: # @param {string} s # @return {integer} def numDecodings(self, s): if not s: return 0 dp = [0]*(len(s)+1) dp[0] = 1 for i in xrange(len(s)): if self.isValid(s[i]): dp[i+1] = dp[i] if i>0 and self.isValid(s[i-1:i+1]): dp[i+1] += dp[i-1] return dp[-1] def isValid(self,s): if len(s) == 1 and 0} wordDict # @return {integer} def ladderLength(self, beginWord, endWord, wordDict): dis = {} dis[beginWord] = 1 chars = string.ascii_lowercase myqueue = [beginWord] while len(myqueue) > 0: word = myqueue[0] del myqueue[0] if word == endWord: break for i in range(len(word)): for c in chars: newWord = word[:i] + c + word[i+1:] if newWord in wordDict and newWord not in dis: dis[newWord] = dis[word]+1 myqueue.append(newWord) if endWord not in dis: return 0 return dis[endWord] ================================================ FILE: python/131-140/Candy.py ================================================ class Solution: # @param {integer[]} ratings # @return {integer} def candy(self, ratings): l = len(ratings) p = [1]*l for i in range(l-1): if ratings[i+1] > ratings[i]: p[i+1] = p[i]+1 for i in range(l-1, 0, -1): if ratings[i-1] > ratings[i]: p[i-1] = max(p[i-1], p[i]+1) return sum(p) ================================================ FILE: python/131-140/Clone Graph.py ================================================ # Definition for a undirected graph node # class UndirectedGraphNode: # def __init__(self, x): # self.label = x # self.neighbors = [] class Solution: dict = {} # @param node, a undirected graph node # @return a undirected graph node def cloneGraph(self, node): if not node: return None if node not in self.dict: self.dict[node] = UndirectedGraphNode(node.label) for e in node.neighbors: self.dict[node].neighbors.append(self.cloneGraph(e)) return self.dict[node] ================================================ FILE: python/131-140/Single Number II.py ================================================ class Solution: # @param {integer[]} nums # @return {integer} def singleNumber(self, nums): tmp = set(nums) v = sum(tmp)*3 -sum(nums) return v/2 s = Solution() items = [2,2,3,2] print s.singleNumber(items) ================================================ FILE: python/141-150/Binary Tree Postorder Traversal.py ================================================ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param {TreeNode} root # @return {integer[]} def postorderTraversal(self, root): v = [] if not root: return v stacks = [] stacks.append(root) while len(stacks) > 0: root = stacks[-1] del stacks[-1] v.append(root.val) if root.left: stacks.append(root.left) if root.right: stacks.append(root.right) v.reverse() return v ================================================ FILE: python/141-150/LRU Cache.py ================================================ class LRUCache: # @param capacity, an integer def __init__(self, capacity): self.capacity = capacity self.cache = collections.OrderedDict() # @return an integer def get(self, key): if not key in self.cache: return -1 value = self.cache.pop(key) self.cache[key] = value return value # @param key, an integer # @param value, an integer # @return nothing def set(self, key, value): if key in self.cache: self.cache.pop(key) elif len(self.cache) == self.capacity: self.cache.popitem(last=False) self.cache[key] = value ================================================ FILE: python/151-160/Find Minimum in Rotated Sorted Array II.py ================================================ class Solution: # @param {integer[]} nums # @return {integer} def findMin(self, nums): start = 0 end = len(nums)-1 while start < end: if nums[start] < nums[end]: return nums[start] mid = (start+end)/2 if(nums[mid] > nums[start]): start = mid+1 elif(nums[mid] < nums[start]): end = mid else: start += 1 return nums[start] ================================================ FILE: python/151-160/Find Minimum in Rotated Sorted Array.py ================================================ class Solution: # @param {integer[]} nums # @return {integer} def findMin(self, nums): start = 0 end = len(nums)-1 while start < end: if nums[start] < nums[end]: return nums[start] mid = (start+end)/2 if(nums[mid] >= nums[start]): start = mid+1 else: end = mid return nums[start] ================================================ FILE: python/161-170/Majority Element.py ================================================ class Solution: # @param {integer[]} nums # @return {integer} def majorityElement(self, nums): stack = [] for e in nums: if len(stack) == 0: stack.append(e) else: if stack[-1] == e: stack.append(e) else: del stack[-1] return stack[0] ================================================ FILE: python/161-170/Maximum Gap.py ================================================ import math class Solution: # @param num, a list of integer # @return an integer def maximumGap(self, num): if len(num) < 2 or min(num) == max(num): return 0 a, b = min(num), max(num) gap = int(math.ceil((b-a)*1.0/(len(num)-1))) bucket = [[None, None] for _ in range((b-a)/gap+1)] for n in num: b = bucket[int((n-a)/gap)] b[0] = n if b[0] is None else min(b[0], n) b[1] = n if b[1] is None else max(b[1], n) bucket = [b for b in bucket if b[0] is not None] return max(bucket[i][0]-bucket[i-1][1] for i in range(1, len(bucket))) items = [1,1,1,1,1,5,5,5,5,5] s = Solution() print s.maximumGap(items) ================================================ FILE: python/171-180/Largest Number.py ================================================ class Solution: # @param {integer[]} nums # @return {string} def largestNumber(self, nums): num = [str(x) for x in nums] num.sort(cmp = lambda x,y : cmp(y+x, x+y)) return "".join(num).lstrip('0') or '0' ================================================ FILE: python/181-190/Best Time to Buy and Sell Stock IV.py ================================================ #!/usr/bin/env python # coding=utf-8 class Solution: # @param {integer} k # @param {integer[]} prices # @return {integer} def maxProfit(self, k, prices): l = len(prices) if l < 2: return 0 if k >= l/2: res = 0 for i in range(l-1): if prices[i+1] > prices[i]: res = res + prices[i+1] - prices[i] return res p = [[0]*(l+1) for _ in range(k+1)] for i in range(1,k+1): temp = -prices[0] for j in range(1,l+1): p[i][j] = max(p[i][j-1], temp+prices[j-1]) temp = max(temp, p[i-1][j-1]-prices[j-1]) return p[k][l] ================================================ FILE: python/181-190/Repeated DNA Sequences.py ================================================ class Solution: # @param {string} s # @return {string[]} def findRepeatedDnaSequences(self, s): result = [] t = i = 0 ss = len(s) if ss < 10: return result dic = {} while i < 9: t = t << 3 | ord(s[i]) & 7 i = i + 1 while i < ss: t = t << 3 & 0x3FFFFFFF | ord(s[i]) & 7 i = i + 1 if t in dic: dic[t] = dic[t]+1 else: dic[t] = 1 if dic[t] == 2: result.append(s[i-10:i]); return result s = Solution() st = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" print s.findRepeatedDnaSequences(st) ================================================ FILE: python/191-200/Binary Tree Right Side View.py ================================================ #!/usr/bin/env python # coding=utf-8 class Solution: # @param {TreeNode} root # @return {integer[]} def rightSideView(self, root): items = [] self.help(root, items, 0) return items def help(self, root, items, height): if not root: return if(height == len(items)): items.append(root.val) self.help(root.right, items, height+1) self.help(root.left, items, height+1) ================================================ FILE: python/191-200/House Robber.py ================================================ class Solution: # @param {integer[]} nums # @return {integer} def rob(self, nums): if not nums: return 0 if(len(nums) == 1): return nums[0] p = [0]*len(nums) p[0] = nums[0] p[1] = max(nums[0], nums[1]) for i in range(2, len(nums)): p[i] = max(p[i-2] + nums[i], p[i-1]) return p[-1] ================================================ FILE: python/201-210/Count Primes.py ================================================ import math class Solution: # @param {integer} n # @return {integer} def countPrimes(self, n): if n <= 2: return 0 c = int(math.sqrt(n)) b = [False] * n; for i in range(3, c+1): if not b[i]: j = i*i k = i << 1 while j < n: b[j] = True j += k res = 1 for i in range(3, n, 2): if not b[i]: res += 1 return res ================================================ FILE: python/201-210/Implement Trie (Prefix Tree).py ================================================ class TrieNode: # Initialize your data structure here. def __init__(self): self.children = collections.defaultdict(TrieNode) self.isWord = False class Trie: def __init__(self): self.root = TrieNode() # @param {string} word # @return {void} # Inserts a word into the trie. def insert(self, word): cur = self.root for e in word: cur = cur.children[e] cur.isWord = True # @param {string} word # @return {boolean} # Returns if the word is in the trie. def search(self, word): cur = self.root for e in word: cur = cur.children.get(e) if not cur: return False return cur.isWord # @param {string} prefix # @return {boolean} # Returns if there is any word in the trie # that starts with the given prefix. def startsWith(self, prefix): cur = self.root for e in prefix: cur = cur.children.get(e) if not cur: return False return True # Your Trie object will be instantiated and called as such: # trie = Trie() # trie.insert("somestring") # trie.search("key") ================================================ FILE: python/211-220/House Robber II.py ================================================ class Solution: # @param {integer[]} nums # @return {integer} def rob(self, nums): if not nums: return 0 if len(nums) == 1: return nums[0] pre1 = cur1 = 0 for i in range(len(nums)-1): temp = pre1 pre1 = cur1 cur1 = max(temp+nums[i], pre1) pre2 = cur2 = 0 for i in range(1, len(nums)): temp = pre2 pre2 = cur2 cur2 = max(temp+nums[i], pre2) return max(cur1, cur2) ================================================ FILE: python/221-230/Maximal Square.py ================================================ class Solution: # @param {character[][]} matrix # @return {integer} def maximalSquare(self, matrix): if len(matrix) == 0: return 0 h = [0] * (len(matrix[0])+1) res = 0 for i in range(len(matrix)): matrix[i].append('0') mystack = [] for j in range(len(matrix[i])): if matrix[i][j] == '1': h[j] += 1 else: h[j] = 0 if len(mystack) == 0 or h[j] >= h[mystack[-1]]: mystack.append(j) else: while len(mystack) > 0 and h[j] < h[mystack[-1]]: height = h[mystack[-1]] del mystack[-1] width = j if len(mystack) == 0 else j - 1 - mystack[-1] side = min(height, width) res = max(res, side*side) mystack.append(j) return res ================================================ FILE: python/231-240/Palindrome Linked List.py ================================================ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param {ListNode} head # @return {boolean} def isPalindrome(self, head): if not head or not head.next: return True slow = fast = head while fast.next and fast.next.next: slow = slow.next fast = fast.next.next fast = self.reverse(slow.next) while fast: if head.val != fast.val: return False fast = fast.next head = head.next return True def reverse(self, head): prev = tmp = None while head: tmp = head.next head.next = prev prev = head head = tmp return prev ================================================ FILE: python/231-240/Product of Array Except Self.py ================================================ class Solution: # @param {integer[]} nums # @return {integer[]} def productExceptSelf(self, nums): ls = len(nums) result = [0]*ls result[0] = 1 tmp = 1 for i in range(1,ls): result[i] = result[i-1]*nums[i-1] for i in range(ls-2, -1, -1): tmp = tmp * nums[i+1] result[i] = result[i]*tmp return result items = [0,1] s = Solution() print s.productExceptSelf(items) ================================================ FILE: python/231-240/a.py ================================================ class Solution: # @param {integer[]} nums # @param {integer} k # @return {integer[]} def maxSlidingWindow(self, nums, k): myqueue,res = [],[] for i in range(len(nums)): if len(myqueue) > 0 and myqueue[0] == i - k: del myqueue[0] while len(myqueue) > 0 and nums[myqueue[-1]] < nums[i]: del myqueue[-1] myqueue.append(i) if i >= k - 1: res.append(nums[myqueue[0]]) return res ================================================ FILE: scala/0001-0010/Add Two Numbers.scala ================================================ /** * Definition for singly-linked list. * class ListNode(_x: Int = 0, _next: ListNode = null) { * var next: ListNode = _next * var x: Int = _x * } */ object Solution { def addTwoNumbers(l1: ListNode, l2: ListNode): ListNode = { def addTwoNumbersHelper(l1: ListNode, l2: ListNode, carry: Int): ListNode = { if (l1 == null && l2 == null) if (carry == 0) null else ListNode(carry) else if (l1 == null) addTwoNumbersHelper(ListNode(0), l2, carry) else if (l2 == null) addTwoNumbersHelper(l1, ListNode(0), carry) else ListNode((l1.x + l2.x + carry) % 10, addTwoNumbersHelper(l1.next, l2.next, (l1.x + l2.x + carry) / 10 )) } addTwoNumbersHelper(l1, l2, 0) } } ================================================ FILE: scala/0001-0010/Longest Substring Without Repeating Characters.scala ================================================ import scala.collection._ object Solution { def lengthOfLongestSubstring(s: String): Int = { val mymap = mutable.Map[Int, Int]() var start = 0 var ans = 0 for (i <- 0 until s.length()) { val ch = s(i) if (mymap.contains(ch)) { start = Math.max(start, mymap(ch) + 1) } mymap(ch) = i ans = Math.max(ans, i - start + 1) } ans } } ================================================ FILE: scala/0001-0010/Palindrome Number.scala ================================================ object Solution { def isPalindrome(x: Int): Boolean = { if (x < 0) return false val s = x.toString for( i <- 0 to s.length()/2 ) { if (s(i) != s(s.length() - i - 1)) return false } true } } ================================================ FILE: scala/0001-0010/Two Sum.scala ================================================ import scala.collection._ object Solution { def twoSum(nums: Array[Int], target: Int): Array[Int] = { val map = mutable.Map[Int, Int]() for (i <- 0 until nums.length) { val num = target - nums(i) if (map.contains(num)) { return Array(map(num), i) } map.put(nums(i), i) } return Array(0, 0) } } ================================================ FILE: scala/0011-0020/Longest Common Prefix.scala ================================================ import scala.util.control.Breaks._ object Solution { def longestCommonPrefix(strs: Array[String]): String = { if (strs.isEmpty) { return "" } var prefix = strs(0) for (i <- 1 until strs.length) { val str = strs(i) var k = 0; breakable { while (k < math.min(prefix.length, str.length)) { if (prefix(k) != str(k)) { break } k += 1 } } prefix = prefix.substring(0, k) } return prefix; } } ================================================ FILE: scala/0011-0020/Roman to Integer.scala ================================================ object Solution { def romanToInt(s: String): Int = { val table = Map( 'I' -> 1, 'V' -> 5, 'X' -> 10, 'L' -> 50, 'C' -> 100, 'D' -> 500, 'M' -> 1000 ) var result = 0 for (i <- 0 until s.length()) { if (i < s.length()-1 && table(s(i)) < table(s(i+1)) ) { result -= table(s(i)) } else { result += table(s(i)) } } result } }