├── Array ├── 1. Two Sum.java ├── 1007. Minimum Domino Rotations For Equal Row.java ├── 1010. Pairs of Songs With Total Durations Divisible by 60.java ├── 1013. Partition Array Into Three Parts With Equal Sum.java ├── 1014. Best Sightseeing Pair.java ├── 1018. Binary Prefix Divisible By 5.java ├── 1031. Maximum Sum of Two Non-Overlapping Subarrays.java ├── 1040. Moving Stones Until Consecutive II.java ├── 105. Construct Binary Tree from Preorder and Inorder Traversal.java ├── 1051. Height Checker.java ├── 1053. Previous Permutation With One Swap.java ├── 106. Construct Binary Tree from Inorder and Postorder Traversal.java ├── 1085. Sum of Digits in the Minimum Number.java ├── 1089. Duplicate Zeros.java ├── 1099. Two Sum Less Than K.java ├── 11. Container With Most Water.java ├── 1100. Find K-Length Substrings With No Repeated Characters.java ├── 1109. Corporate Flight Bookings.java ├── 1122. Relative Sort Array.java ├── 1124. Longest Well-Performing Interval.java ├── 1133. Largest Unique Number.java ├── 1137. N-th Tribonacci Number.java ├── 1144. Decrease Elements To Make Array Zigzag.java ├── 1150. Check If a Number Is Majority Element in a Sorted Array.java ├── 1151. Minimum Swaps to Group All 1's Together.java ├── 118. Pascal's Triangle.java ├── 119. Pascal's Triangle II.java ├── 120. Triangle.java ├── 126. Word Ladder II.java ├── 128. Longest Consecutive Sequence.java ├── 15. 3Sum.java ├── 152. Maximum Product Subarray.java ├── 153. Find Minimum in Rotated Sorted Array.java ├── 154. Find Minimum in Rotated Sorted Array II.java ├── 16. 3Sum Closest.java ├── 162. Find Peak Element.java ├── 163. Missing Ranges.java ├── 167. Two Sum II - Input array is sorted.java ├── 169. Majority Element.java ├── 18. 4Sum.java ├── 189. Rotate Array.java ├── 209. Minimum Size Subarray Sum.java ├── 216. Combination Sum III.java ├── 217. Contains Duplicate.java ├── 219. Contains Duplicate II.java ├── 228. Summary Ranges.java ├── 229. Majority Element II.java ├── 238. Product of Array Except Self.java ├── 243. Shortest Word Distance.java ├── 245. Shortest Word Distance III.java ├── 259. 3Sum Smaller.java ├── 26. Remove Duplicates from Sorted Array.java ├── 268. Missing Number.java ├── 27. Remove Elements.java ├── 277. Find the Celebrity.java ├── 280. Wiggle Sort.java ├── 283. Move Zeroes.java ├── 287. Find the Duplicate Number.java ├── 289. Game of Life.java ├── 31. Next Permutation.java ├── 33. Search in Rotated Sorted Array.java ├── 334. Increasing Triplet Subsequence.java ├── 34. Find First and Last Position of Element in Sorted Array.java ├── 35. Search Insert Position.java ├── 361. Bomb Enemy.java ├── 370. Range Addition.java ├── 380. Insert Delete GetRandom O(1).java ├── 381. Insert Delete GetRandom O(1) - Duplicates allowed.java ├── 39. Combination Sum.java ├── 4. Median of Two Sorted Arrays.java ├── 40. Combination Sum II.java ├── 41. First Missing Positive.java ├── 412. Fizz Buzz.java ├── 414. Third Maximum Number.java ├── 42. Trapping Rain Water.java ├── 442. Find All Duplicates in an Array.java ├── 448. Find All Numbers Disappeared in an Array.java ├── 45. Jump Game II.java ├── 457. Circular Array Loop.java ├── 48. Rotate Image.java ├── 485. Max Consecutive Ones.java ├── 495. Teemo Attacking.java ├── 509. Fibonacci Number.java ├── 53. Maximum Subarray.java ├── 531. Lonely Pixel I.java ├── 532. K-diff Pairs in an Array.java ├── 533. Lonely Pixel II.java ├── 54. Spiral Matrix.java ├── 548. Split Array with Equal Sum.java ├── 55. Jump Game.java ├── 56. Merge Intervals.java ├── 560. Subarray Sum Equals K.java ├── 561. Array Partition I.java ├── 562. Longest Line of Consecutive One in Matrix.java ├── 565. Array Nesting.java ├── 566. Reshape the Matrix.java ├── 57. Insert Interval.java ├── 581. Shortest Unsorted Continuous Subarray.java ├── 59. Spiral Matrix II.java ├── 605. Can Place Flowers.java ├── 611. Valid Triangle Number.java ├── 62. Unique Path.java ├── 621. Task Scheduler.java ├── 624. Maximum Distance in Arrays.java ├── 63. Unique Paths II.java ├── 64. Minimum Path Sum.java ├── 643. Maximum Average Subarray I.java ├── 644. Maximum Average Subarray II.java ├── 645. Set Mismatch.java ├── 66. Plus One.java ├── 661. Image Smoother.java ├── 665. Non-decreasing Array.java ├── 667. Beautiful Arrangement II.java ├── 674. Longest Continuous Increasing Subsequence.java ├── 713. Subarray Product Less Than K.java ├── 717. 1-bit and 2-bit Characters.java ├── 723. Candy Crush.java ├── 724. Find Pivot Index.java ├── 729. My Calendar I.java ├── 73. Set Matrix Zeroes.java ├── 74. Search a 2D Matrix.java ├── 75. Sort Colors.java ├── 78. Subsets.java ├── 79. Word Search.java ├── 80. Remove Duplicates from Sorted Array II.java ├── 81. Search in Rotated Sorted Array II.java ├── 84. Largest Rectangle in Histogram.java ├── 85. Maximal Rectangle.java ├── 88. Merge Sorted Array.java ├── 891. Sum of Subsequence Widths.java ├── 90. Subsets II.java ├── 926. Flip String to Monotone Increasing.java ├── 941. Valid Mountain Array.java ├── 945. Minimum Increment to Make Array Unique.java ├── 950. Reveal Cards In Increasing Order.java ├── 954. Array of Doubled Pairs.java ├── 961. N-Repeated Element in Size 2N Array.java ├── 962. Maximum Width Ramp.java ├── 969. Pancake Sorting.java ├── 974. Subarray Sums Divisible by K.java ├── 977. Squares of a Sorted Array.java ├── 985. Sum of Even Numbers After Queries.java ├── 989. Add to Array-Form of Integer.java └── 999. Available Captures for Rook.java ├── Backtracking ├── 1066. Campus Bikes II.java ├── 1079. Letter Tile Possibilities.java ├── 1087. Brace Expansion.java ├── 1088. Confusing Number II.java ├── 1125. Smallest Sufficient Team.java ├── 126. Word Ladder II.java ├── 131. Palindrome Partitioning.java ├── 140. Word Break II.java ├── 17. Letter Combinations of a Phone Number.java ├── 211. Add and Search Word - Data structure design.java ├── 212. Word Search II.java ├── 216. Combination Sum III.java ├── 22. Generate Parentheses.java ├── 254. Factor Combinations.java ├── 267. Palindrome Permutation II.java ├── 282. Expression Add Operators.java ├── 291. Word Pattern II.java ├── 294. Flip Game II.java ├── 306. Additive Number.java ├── 320. Generalized Abbreviation.java ├── 351. Android Unlock Patterns.java ├── 357. Count Numbers with Unique Digits.java ├── 37. Sudoku Solver.java ├── 39. Combination Sum.java ├── 40. Combination Sum II.java ├── 401. Binary Watch.java ├── 411. Minimum Unique Word Abbreviation.java ├── 425. Word Squares.java ├── 44. Wildcard Matching.java ├── 46. Permutations.java ├── 47. Permutations II.java ├── 491. Increasing Subsequences.java ├── 51. N-Queens.java ├── 52. N-Queens II.java ├── 526. Beautiful Arrangement.java ├── 691. Stickers to Spell Word.java ├── 77. Combinations.java ├── 78. Subsets.java ├── 79. Word Search.java ├── 80. Subsets II.java ├── 93. Restore IP Addresses.java ├── 980. Unique Paths III.java └── 996. Number of Squareful Arrays.java ├── Bash ├── 192. Word Frequency.sh ├── 193. Valid Phone Numbers.sh ├── 194. Transpose File.sh └── 195. Tenth Line.sh ├── Binary Indexed Tree ├── 307. Range Sum Query - Mutable.java └── 308. Range Sum Query 2D - Mutable.java ├── Binary Search ├── 1011. Capacity To Ship Packages Within D Days.java ├── 1060. Missing Element in Sorted Array.java ├── 1064. Fixed Point.java ├── 1095. Find in Mountain Array.java ├── 1150. Check If a Number Is Majority Element in a Sorted Array.java ├── 153. Find Minimum in Rotated Sorted Array.java ├── 154. Find Minimum in Rotated Sorted Array II.java ├── 162. Find Peak Element.java ├── 209. Minimum Size Subarray Sum.java ├── 222. Count Complete Tree Nodes.java ├── 230. Kth Smallest Element in a BST.java ├── 240. Search a 2D Matrix II.java ├── 270. Closest Binary Search Tree Value.java ├── 275. H-Index II.java ├── 278. First Bad Version.java ├── 287. Find the Duplicate Number.java ├── 29. Divide Two Integers.java ├── 300. Longest Increasing Subsequence.java ├── 302. Smallest Rectangle Enclosing Black Pixels.java ├── 33. Search in Rotated Sorted Array.java ├── 34. Find First and Last Position of Element in Sorted Array.java ├── 349. Intersection of Two Arrays.java ├── 35. Search Insert Position.java ├── 354. Russian Doll Envelopes.java ├── 363. Max Sum of Rectangle No Larger Than K.java ├── 367. Valid Perfect Square.java ├── 374. Guess Number Higher or Lower.java ├── 378. Kth Smallest Element in a Sorted Matrix.java ├── 392. Is Subsequence.java ├── 4. Median of Two Sorted Arrays.java ├── 410. Split Array Largest Sum.java ├── 436. Find Right Interval.java ├── 441. Arranging Coins.java ├── 475. Heaters.java ├── 50. Pow(x, n).java ├── 528. Random Pick with Weight.java ├── 540. Single Element in a Sorted Array.java ├── 644. Maximum Average Subarray II.java ├── 658. Find K Closest Elements.java ├── 668. Kth Smallest Number in Multiplication Table.java ├── 69. Sqrt(x).java ├── 702. Search in a Sorted Array of Unknown Size.java ├── 704. Binary Search.java ├── 719. Find K-th Smallest Pair Distance.java ├── 74. Search a 2D Matrix.java ├── 774. Minimize Max Distance to Gas Station.java └── 81. Search in Rotated Sorted Array II.java ├── Bit Manipulation ├── 1009. Complement to Base 10 Integer.java ├── 136. Single Number.java ├── 137. Single Number II.java ├── 169. Majority Element.java ├── 187. Repeated DNA Sequences.java ├── 190. Reverse Bits.java ├── 191. Number of 1 Bits.java ├── 201. Bitwise AND of Numbers Range.java ├── 231. Power of Two.java ├── 260. Single Number III.java ├── 268. Missing Number.java ├── 318. Maximum Product of Word Lengths.java ├── 338. Counting Bits.java ├── 342. Power of Four.java ├── 371. Sum of Two Integers.java ├── 389. Find the Difference.java ├── 393. UTF-8 Validation.java ├── 405. Convert a Number to Hexadecimal.java ├── 421. Maximum XOR of Two Numbers in an Array.java ├── 461. Hamming Distance.java ├── 476. Number Complement.java ├── 477. Total Hamming Distance.java ├── 693. Binary Number with Alternating Bits.java ├── 78. Subsets.java └── 89. Grey Code.java ├── Brainteaser ├── 1033. Moving Stones Until Consecutive.java ├── 292. Nim Game.java └── 319. Bulb Switcher.java ├── Breadth-first Search ├── 101. Symmetric Tree.java ├── 102. Binary Tree Level Order Traversal.java ├── 103. Binary Tree Zigzag Level Order Traversal.java ├── 1030. Matrix Cells in Distance Order.java ├── 1036. Escape a Large Maze.java ├── 107. Binary Tree Level Order Traversal II.java ├── 1091. Shortest Path in Binary Matrix.java ├── 111. Minimum Depth of Binary Tree.java ├── 112. Path Sum.java ├── 1129. Shortest Path with Alternating Colors.java ├── 126. Word Ladder II.java ├── 127. Word Ladder.java ├── 133. Clone Graph.java ├── 199. Binary Tree Right Side View.java ├── 200. Number of Islands.java ├── 207. Course Schedule.java ├── 210. Course Schedule II.java ├── 261. Graph Valid Tree.java ├── 286. Walls and Gates.java ├── 310. Minimum Height Trees.java ├── 317. Shortest Distance from All Buildings.java ├── 323. Number of Connected Components in an Undirected Graph.java ├── 364. Nested List Weight Sum II.java ├── 407. Trapping Rain Water II.java ├── 417. Pacific Atlantic Water Flow.java ├── 429. N-ary Tree Level Order Traversal.java ├── 433. Minimum Genetic Mutation.java ├── 490. The Maze.java ├── 499. The Maze III.java ├── 505. The Maze II.java ├── 513. Find Bottom Left Tree Value.java ├── 529. Minesweeper.java ├── 542. 01 Matrix.java ├── 582. Kill Process.java ├── 675. Cut Off Trees for Golf Event.java ├── 695. Max Area of Island.java ├── 854. K-Similar Strings.java ├── 864. Shortest Path to Get All Keys.java ├── 934. Shortest Bridge.java ├── 993. Cousins in Binary Tree.java └── 994. Rotting Oranges.java ├── Concurrency ├── 1114. Print in Order.java ├── 1115. Print FooBar Alternately.java ├── 1116. Print Zero Even Odd.java └── 1117. Building H2O.java ├── Depth-first Search ├── 100. Same Tree.java ├── 101. Depth-first Search.java ├── 1020. Number of Enclaves.java ├── 1034. Coloring A Border.java ├── 104. Maximum Depth of Binary Tree.java ├── 105. Construct Binary Tree from Preorder and Inorder Traversal.java ├── 1059. All Paths from Source Lead to Destination.java ├── 106. Construct Binary Tree from Inorder and Postorder Traversal.java ├── 108. Convert Sorted Array to BST.java ├── 1080. Insufficient Nodes in Root to Leaf Paths.java ├── 109. Convert Sorted List to BST.java ├── 110. Balanced Binary Tree.java ├── 1102. Path With Maximum Minimum Value.java ├── 111. Minimum Depth of Binary Tree.java ├── 1110. Delete Nodes And Return Forest.java ├── 112. Path Sum.java ├── 1123. Lowest Common Ancestor of Deepest Leaves.java ├── 113. Path Sum II.java ├── 114. Flatten Binary Tree to Linked List.java ├── 1140. Stone Game II.java ├── 1145. Binary Tree Coloring Game.java ├── 124. Binary Tree Maximum Path Sum.java ├── 129. Sum Root to Leaf Numbers.java ├── 130. Surrounded Regions.java ├── 133. Clone Graph.java ├── 199. Binary Tree Right Side View.java ├── 200. Number of Islands.java ├── 207. Course Schedule.java ├── 210. Course Schedule II.java ├── 257. Binary Tree Paths.java ├── 261. Graph Valid Tree.java ├── 301. Remove Invalid Parentheses.java ├── 302. Smallest Rectangle Enclosing Black Pixels.java ├── 323. Number of Connected Components in an Undirected Graph.java ├── 329. Longest Increasing Path in a Matrix.java ├── 332. Reconstruct Itinerary.java ├── 337. House Robber III.java ├── 339. Nested List Weight Sum.java ├── 366. Find Leaves of Binary Tree.java ├── 439. Ternary Expression Parser.java ├── 472. Concatenated Words.java ├── 473. Matchsticks to Square.java ├── 488. Zuma Game.java ├── 489. Robot Room Cleaner.java ├── 491. Increasing Subsequences.java ├── 494. Target Sum.java ├── 513. Find Bottom Left Tree Value.java ├── 547. Friend Circles.java ├── 568. Maximum Vacation Days.java ├── 576. Out of Boundary Paths.java ├── 638. Shopping Offers.java ├── 679. 24 Game.java ├── 690. Employee Importance.java ├── 691. Stickers to Spell Word.java ├── 694. Number of Distinct Islands.java ├── 695. Max Area of Island.java ├── 698. Partition to K Equal Sum Subsets.java ├── 711. Number of Distinct Islands II.java ├── 721. Accounts Merge.java ├── 733. Flood Fill.java ├── 737. Sentence Similarity II.java ├── 778. Swim in Rising Water.java ├── 851. Loud and Rich.java ├── 928. Minimize Malware Spread II.java ├── 934. Shortest Bridge.java ├── 959. Regions Cut By Slashes.java ├── 964. Least Operators to Express Number.java ├── 967. Numbers With Same Consecutive Differences.java ├── 968. Binary Tree Cameras.java ├── 971. Flip Binary Tree To Match Preorder Traversal.java ├── 979. Distribute Coins in Binary Tree.java ├── 98. Validate Binary Search Tree.java ├── 980. Unique Paths III.java ├── 988. Smallest String Starting From Leaf.java └── 99. Recover Binary Search Tree.java ├── Design ├── 1146. Snapshot Array.java ├── 146. LRU Cache.java ├── 155. Min Stack.java ├── 170. Two Sum III - Data structure design.java ├── 173. Binary Search Tree Iterator.java ├── 208. Implement Trie (Prefix Tree).java ├── 211. Add and Search Word - Data structure design.java ├── 225. Implement Stack using Queues.java ├── 232. Implement Queue using Stacks.java ├── 244. Shortest Word Distance II.java ├── 251. Flatten 2D Vector.java ├── 281. Zigzag Iterator.java ├── 284. Peeking Iterator.java ├── 288. Unique Word Abbreviation.java ├── 295. Find Median from Data Stream.java ├── 297. Serialize and Deserialize Binary Tree.java ├── 341. Flatten Nested List Iterator.java ├── 346. Moving Average from Data Stream.java ├── 348. Design Tic-Tac-Toe.java ├── 353. Design Snake Game.java ├── 355. Design Twitter.java ├── 359. Logger Rate Limiter.java ├── 362. Design Hit Counter.java ├── 379. Design Phone Directory.java ├── 380. Insert Delete GetRandom O(1).java ├── 381. Insert Delete GetRandom O(1) - Duplicates allowed.java ├── 384. Shuffle an Array.java ├── 432. All O`one Data Structure.java ├── 460. LFU Cache.java ├── 588. Design In-Memory File System.java ├── 604. Design Compressed String Iterator.java ├── 622. Design Circular Queue.java ├── 635. Design Log Storage System.java ├── 641. Design Circular Deque.java ├── 642. Design Search Autocomplete System.java ├── 705. Design HashSet.java ├── 706. Design HashMap.java ├── 707. Design Linked List.java ├── 710. Random Pick with Blacklist.java ├── 716. Max Stack.java └── 745. Prefix and Suffix Search.java ├── Divide and Conquer ├── 215. Kth Largest Element in an Array.java ├── 23. Merge K Sorted Lists.java ├── 241. Different Ways to Add Parentheses.java ├── 282. Expression Add Operators.java ├── 312. Burst Balloons.java ├── 4. Median of Two Sorted Arrays.java ├── 932. Beautiful Array.java └── 973. K Closest Points to Origin.java ├── Dynamic Programming ├── 10. Regular Expression Matching.java ├── 1024. Video Stitching.java ├── 1027. Longest Arithmetic Sequence.java ├── 1031. Maximum Sum of Two Non-Overlapping Subarrays.java ├── 1035. Uncrossed Lines.java ├── 1039. Minimum Score Triangulation of Polygon.java ├── 1043. Partition Array for Maximum Sum.java ├── 1048. Longest String Chain.java ├── 1049. Last Stone Weight II.java ├── 1058. Minimize Rounding Error to Meet Target.java ├── 1074. Number of Submatrices That Sum to Target.java ├── 1092. Shortest Common Supersequence.java ├── 1105. Filling Bookcase Shelves.java ├── 1130. Minimum Cost Tree From Leaf Values.java ├── 1139. Largest 1-Bordered Square.java ├── 1143. Longest Common Subsequence.java ├── 1147. Longest Chunked Palindrome Decomposition.java ├── 115. Distinct Subsequences.java ├── 1155. Number of Dice Rolls With Target Sum.java ├── 120. Triangle.java ├── 121. Best Time to Buy and Sell Stock.java ├── 122. Best Time to Buy and Sell Stock II.java ├── 123. Best Time to Buy and Sell Stock III.java ├── 132. Palindrome Partitioning II.java ├── 139. Word Break.java ├── 140. Word Break II.java ├── 152. Maximum Product Subarray.java ├── 174. Dungeon Game.java ├── 188. Best Time to Buy and Sell Stock IV.java ├── 198. House Robber.java ├── 213. House Robber II.java ├── 221. Maximal Square.java ├── 256. Paint House.java ├── 265. Paint House II.java ├── 276. Paint Fence.java ├── 279. Perfect Squares.java ├── 300. Longest Increasing Subsequence.java ├── 303. Range Sum Query - Immutable.java ├── 304. Range Sum Query 2D - Immutable.java ├── 309. Best Time to Buy and Sell Stock with Cooldown.java ├── 312. Burst Balloons.java ├── 32. Longest Valid Parentheses.java ├── 322. Coin Change.java ├── 338. Counting Bits.java ├── 343. Integer Break.java ├── 354. Russian Doll Envelopes.java ├── 357. Count Numbers with Unique Digits.java ├── 363. Max Sum of Rectangle No Larger Than K.java ├── 368. Largest Divisible Subset.java ├── 375. Guess Number Higher or Lower II.java ├── 376. Wiggle Subsequence.java ├── 377. Combination Sum IV.java ├── 403. Frog Jump.java ├── 410. Split Array Largest Sum.java ├── 416. Partition Equal Subset Sum.java ├── 44. Wildcard Matching.java ├── 446. Arithmetic Slices II.java ├── 464. Can I Win.java ├── 466. Count The Repetitions.java ├── 467. Unique Substrings in Wraparound String.java ├── 471. Encode String with Shortest Length.java ├── 474. Ones and Zeroes.java ├── 486. Predict the Winner.java ├── 494. Target Sum.java ├── 5. Longest Palindromic Substring.java ├── 516. Longest Palindromic Subsequence.java ├── 518. Coin Change 2.java ├── 523. Continuous Subarray Sum.java ├── 53. Maximum Subarray.java ├── 542. 01 Matrix.java ├── 552. Student Attendance Record II.java ├── 562. Longest Line of Consecutive One in Matrix.java ├── 568. Maximum Vacation Days.java ├── 576. Out of Boundary Paths.java ├── 583. Delete Operation for Two Strings.java ├── 600. Non-negative Integers without Consecutive Ones.java ├── 62. Unique Paths.java ├── 629. K Inverse Pairs Array.java ├── 63. Unique Paths II.java ├── 634. Find the Derangement of an Array.java ├── 639. Decode Ways II.java ├── 64. Minimum Path Sum.java ├── 646. Maximum Length of Pair Chain.java ├── 647. Palindromic Substrings.java ├── 650. 2 Keys Keyboard.java ├── 651. 4 Keys Keyboard.java ├── 656. Coin Path.java ├── 673. Number of Longest Increasing Subsequence.java ├── 688. Knight Probability in Chessboard.java ├── 689. Maximum Sum of 3 Non-Overlapping Subarrays.java ├── 70. Climbing Stairs.java ├── 712. Minimum ASCII Delete Sum for Two Strings.java ├── 714. Best Time to Buy and Sell Stock with Transaction Fee.java ├── 718. Maximum Length of Repeated Subarray.java ├── 72. Edit Distance.java ├── 741. Cherry Pickup.java ├── 750. Number Of Corner Rectangles.java ├── 87. Scramble String.java ├── 91. Decode Ways.java ├── 935. Knight Dialer.java ├── 943. Find the Shortest Superstring.java ├── 95. Unique Binary Search Trees II.java ├── 956. Tallest Billboard.java ├── 96. Unique Binary Search Trees.java ├── 960. Delete Columns to Make Sorted III.java ├── 97. Interleaving String.java ├── 975. Odd Even Jump.java ├── 978. Longest Turbulent Subarray.java ├── 982. Triples with Bitwise AND Equal To Zero.java └── 983. Minimum Cost For Tickets.java ├── Graph ├── 1042. Flower Planting With No Adjacent.java ├── 1059. All Paths from Source Lead to Destination.java ├── 1102. Path With Maximum Minimum Value.java ├── 1129. Shortest Path with Alternating Colors.java ├── 1135. Connecting Cities With Minimum Cost.java ├── 1136. Parallel Courses.java ├── 133. Clone Graph.java ├── 207. Course Schedule.java ├── 210. Course Schedule II.java ├── 261. Graph Valid Tree.java ├── 269. Alien Dictionary.java ├── 310. Minimum Height Trees.java ├── 323. Number of Connected Components in an Undirected Graph.java ├── 332. Reconstruct Itinerary.java ├── 399. Evaluate Division.java ├── 444. Sequence Reconstruction.java ├── 582. Kill Process.java ├── 684. Redundant Connection.java ├── 685. Redundant Connection II.java ├── 928. Minimize Malware Spread II.java ├── 943. Find the Shortest Superstring.java ├── 959. Regions Cut By Slashes.java └── 997. Find the Town Judge.java ├── Greedy ├── 1005. Maximize Sum Of Array After K Negations.java ├── 1024. Video Stitching.java ├── 1029. Two City Scheduling.java ├── 1094. Car Pooling.java ├── 1111. Maximum Nesting Depth of Two Valid Parentheses Strings.java ├── 1130. Minimum Cost Tree From Leaf Values.java ├── 1147. Longest Chunked Palindrome Decomposition.java ├── 134. Gas Station.java ├── 135. Candy.java ├── 253. Meeting Rooms II.java ├── 330. Patching Array.java ├── 358. Rearrange String k Distance Apart.java ├── 392. Is Subsequence.java ├── 402. Remove K Digits.java ├── 406. Queue Reconstruction by Height.java ├── 435. Non-overlapping Intervals.java ├── 45. Jump Game II.java ├── 452. Minimum Number of Arrows to Burst Balloons.java ├── 455. Assign Cookies.java ├── 484. Find Permutation.java ├── 502. IPO.java ├── 55. Jump Game.java ├── 621. Task Scheduler.java ├── 630. Course Schedule III.java ├── 646. Maximum Length of Pair Chain.java ├── 649. Dota2 Senate.java ├── 650. 2 Keys Keyboard.java ├── 659. Split Array into Consecutive Subsequences.java ├── 738. Monotone Increasing Digits.java ├── 861. Score After Flipping Matrix.java ├── 870. Advantage Shuffle.java ├── 948. Bag of Tokens.java ├── 955. Delete Columns to Make Sorted II.java ├── 984. String Without AAA or BBB.java └── 995. Minimum Number of K Consecutive Bit Flips.java ├── Hash Table ├── 1. Two Sum.java ├── 1001. Grid Illumination.java ├── 1002. Find Common Characters.java ├── 1072. Flip Columns For Maximum Number of Equal Rows.java ├── 1086. High Five.java ├── 1090. Largest Values From Labels.java ├── 1128. Number of Equivalent Domino Pairs.java ├── 1133. Largest Unique Number.java ├── 1152. Analyze User Website Visit Pattern.java ├── 138. Copy List with Random Pointer.java ├── 149. Max Points on a Line.java ├── 159. Longest Substring with At Most Two Distinct Characters.java ├── 166. Fraction to Recurring Decimal.java ├── 170. Two Sum III - Date structure design.java ├── 187. Repeated DNA Sequences.java ├── 202. Happy Number.java ├── 204. Count Primes.java ├── 205. Isomorphic Strings.java ├── 217. Contains Duplicate.java ├── 219. Contains Duplicate II.java ├── 220. Contains Duplicate III.java ├── 242. Valid Anagram.java ├── 244. Shortest Word Distance II.java ├── 246. Strobogrammatic Number.java ├── 249. Group Shifted Strings.java ├── 266. Palindrome Permutation.java ├── 274. H-Index.java ├── 288. Unique Word Abbreviation.java ├── 290. Word Pattern.java ├── 299. Bulls and Cows.java ├── 3. Longest Substring Without Repeating Characters.java ├── 30. Substring with Concatenation of All Words.java ├── 314. Binary Tree Vertical Order Traversal.java ├── 325. Maximum Size Subarray Sum Equals k.java ├── 336. Palindrome Pairs.java ├── 340. Longest Substring with At Most K Distinct Characters.java ├── 347. Top K Frequent Elements.java ├── 349. Intersection of Two Arrays.java ├── 350. Intersection of Two Arrays II.java ├── 352. Data Stream as Disjoint Intervals.java ├── 355. Design Twitter.java ├── 356. Line Reflection.java ├── 358. Rearrange String k Distance Apart.java ├── 359. Logger Rate Limiter.java ├── 36. Valid Sudoku.java ├── 37. Sudoku Solver.java ├── 380. Insert Delete GetRandom O(1).java ├── 381. Insert Delete GetRandom O(1) - Duplicates allowed.java ├── 387. First Unique Character in a String.java ├── 409. Longest Palindrome.java ├── 438. Find All Anagrams in a String.java ├── 447. Number of Boomerangs.java ├── 451. Sort Characters By Frequency.java ├── 454. 4Sum II.java ├── 463. Island Perimeter.java ├── 49. Group Anagrams.java ├── 500. Keyboard Row.java ├── 508. Most Frequent Subtree Sum.java ├── 525. Contiguous Array.java ├── 535. Encode and Decode TinyURL.java ├── 554. Brick Wall.java ├── 560. Subarray Sum Equals K.java ├── 575. Distribute Candies.java ├── 594. Longest Harmonious Subsequence.java ├── 599. Minimum Index Sum of Two Lists.java ├── 609. Find Duplicate File in System.java ├── 676. Implement Magic Dictionary.java ├── 683. K Empty Slots.java ├── 690. Employee Importance.java ├── 692. Top K Frequent Words.java ├── 697. Degree of an Array.java ├── 706. Design HashMap.java ├── 710. Random Pick with Blacklist.java ├── 711. Number of Distinct Islands II.java ├── 726. Number of Atoms.java ├── 731. My Calendar II.java ├── 732. My Calendar III.java ├── 734. Sentence Similarity.java ├── 76. Minimum Window Substring.java ├── 953. Verifying an Alien Dictionary.java ├── 954. Array of Doubled Pairs.java ├── 957. Prison Cells After N Days.java ├── 966. Vowel Spellchecker.java ├── 974. Subarray Sums Divisible by K.java ├── 981. Time Based Key.java ├── 987. Vertical Order Traversal of a Binary Tree.java └── 992. Subarrays with K Different Integers.java ├── Heap ├── 1046. Last Stone Weight.java ├── 1054. Distant Barcodes.java ├── 1057. Campus Bikes.java ├── 215. Kth Largest Element in an Array.java ├── 218. The Skyline Problem.java ├── 23. Merge K Sorted Lists.java ├── 239. Sliding Window Maximum.java ├── 253. Meeting Rooms II.java ├── 295. Find Median from Data Stream.java ├── 355. Design Twitter.java ├── 358. Rearrange String k Distance Apart.java ├── 373. Find K Pairs with Smallest Sums.java ├── 378. Kth Smallest Element in a Sorted Matrix.java ├── 407. Trapping Rain Water II.java ├── 502. IPO.java ├── 630. Course Schedule III.java ├── 632. Smallest Range.java ├── 692. Top K Frequent Words.java ├── 703. Kth Largest Element in a Stream.java ├── 759. Employee Free Time.java ├── 778. Swim in Rising Water.java ├── 786. K-th Smallest Prime Fraction.java ├── 857. Minimum Cost to Hire K Workers.java └── 973. K Closest Points to Origin.java ├── Linked List ├── 1019. Next Greater Node In Linked List.java ├── 109. Convert Sorted List to BST.java ├── 138. Copy List with Random Pointer.java ├── 141. Linked List Cycle.java ├── 142. Linked List Cycle II.java ├── 143. Reorder List.java ├── 147. Insertion Sort List.java ├── 148. Sort List.java ├── 160. Intersection of Two Linked Lists.java ├── 19. Remove Nth Node From End of List.java ├── 2. Add Two Numbers.java ├── 203. Remove Linked List Elements.java ├── 206. Reverse Linked List.java ├── 21. Merge Two Sorted Lists.java ├── 23. Merge K Sorted Lists.java ├── 234. Palindrome Linked List.java ├── 237. Delete Node in a Linked List.java ├── 24. Swap Nodes in Pairs.java ├── 25. Reverse Nodes in K-Group.java ├── 328. Odd Even Linked List.java ├── 369. Plus One Linked List.java ├── 379. Design Phone Directory.java ├── 426. Convert Binary Search Tree to Sorted Doubly Linked List.java ├── 430. Flatten a Multilevel Doubly Linked List.java ├── 445. Add Two Numbers II.java ├── 61. Rotate List.java ├── 707. Design Linked List.java ├── 708. Insert into a Cyclic Sorted List.java ├── 725. Split Linked List in Parts.java ├── 82. Remove Duplicates from Sorted List II.java ├── 83. Remove Duplicates from Sorted List.java ├── 86. Partition List.java └── 92. Reverse Linked List II.java ├── Math ├── 1006. Clumsy Factorial.java ├── 1012. Numbers With Repeated Digits.java ├── 1015. Smallest Integer Divisible by K.java ├── 1017. Convert to Base -2.java ├── 1025. Divisor Game.java ├── 1037. Valid Boomerang.java ├── 1041. Robot Bounded In Circle.java ├── 1056. Confusing Number.java ├── 1067. Digit Count in Range.java ├── 1073. Adding Two Negabinary Numbers.java ├── 1088. Confusing Number II.java ├── 1093. Statistics from a Large Sample.java ├── 1103. Distribute Candies to People.java ├── 1104. Path In Zigzag Labelled Binary Tree.java ├── 1118. Number of Days in a Month.java ├── 1121. Divide Array Into Increasing Sequences.java ├── 1131. Maximum of Absolute Value Expression.java ├── 1134. Armstrong Number.java ├── 1138. Alphabet Board Path.java ├── 1153. String Transforms Into Another String.java ├── 12. Integer to Roman.java ├── 13. Roman to Integer.java ├── 149. Max Points on a Line.java ├── 166. Fraction to Recurring Decimal.java ├── 168. Excel Sheet Column Title.java ├── 171. Excel Sheet Column Number.java ├── 172. Factorial Trailing Zeroes.java ├── 2. Add Two Numbers.java ├── 202. Happy Number.java ├── 204. Count Primes.java ├── 223. Rectangle Area.java ├── 224. Basic Calculator.java ├── 231. Power of Two.java ├── 233. Number of Digit One.java ├── 246. Strobogrammatic Number.java ├── 247. Strobogrammatic Number II.java ├── 248. Strobogrammatic Number III.java ├── 258. Add Digits.java ├── 263. Ugly Number.java ├── 264. Ugly Number II.java ├── 268. Missing Number.java ├── 273. Integer to English Words.java ├── 279. Perfect Squares.java ├── 29. Divide Two Integers.java ├── 296. Best Meeting Point.java ├── 311. Sparse Matrix Multiplication.java ├── 313. Super Ugly Number.java ├── 319. Bulb Switcher.java ├── 326. Power of Three.java ├── 335. Self Crossing.java ├── 343. Integer Break.java ├── 356. Line Reflection.java ├── 357. Count Numbers with Unique Digits.java ├── 360. Sort Transformed Array.java ├── 365. Water and Jug Problem.java ├── 367. Valid Perfect Square.java ├── 368. Largest Divisible Subset.java ├── 372. Super Pow.java ├── 390. Elimination Game.java ├── 391. Perfect Rectangle.java ├── 396. Rotate Function.java ├── 397. Integer Replacement.java ├── 400. Nth Digit.java ├── 413. Arithmetic Slices.java ├── 423. Reconstruct Original Digits from English.java ├── 43. Multiply Strings.java ├── 440. K-th Smallest in Lexicographical Order.java ├── 441. Arranging Coins.java ├── 453. Minimum Moves to Equal Array Elements.java ├── 458. Poor Pigs.java ├── 462. Minimum Moves to Equal Array Elements II.java ├── 469. Convex Polygon.java ├── 478. Generate Random Point in a Circle.java ├── 492. Construct the Rectangle.java ├── 50. Pow(x, n).java ├── 507. Perfect Number.java ├── 517. Super Washing Machine.java ├── 523. Continuous Subarray Sum.java ├── 537. Complex Number Multiplication.java ├── 553. Optimal Division.java ├── 573. Squirrel Simulation.java ├── 592. Fraction Addition and Subtraction.java ├── 593. Valid Square.java ├── 598. Range Addition II.java ├── 60. Permutation Sequence.java ├── 625. Minimum Factorization.java ├── 628. Maximum Product of Three Numbers.java ├── 633. Sum of Square Numbers.java ├── 645. Set Mismatch.java ├── 65. Valid Number.java ├── 66. Plus One.java ├── 660. Remove 9.java ├── 67. Add Binary.java ├── 670. Maximum Swap.java ├── 672. Bulb Switcher II.java ├── 69. Sqrt(x).java ├── 7. Reverse Integer.java ├── 728. Self Dividing Numbers.java ├── 8. String to Integer (atoi).java ├── 866. Prime Palindrome.java ├── 891. Sum of Subsequence Widths.java ├── 9. Palindrome Number.java ├── 942. DI String Match.java ├── 949. Largest Time for Given Digits.java ├── 952. Largest Component Size by Common Factor.java ├── 963. Minimum Area Rectangle II.java ├── 970. Powerful Integers.java ├── 972. Equal Rational Numbers.java ├── 976. Largest Perimeter Triangle.java └── 991. Broken Calculator.java ├── MySQL ├── 1045. Customers Who Bought All Products.sql ├── 1050. Actors and Directors Who Cooperated At Least Three Times.sql ├── 1068. Product Sales Analysis I.sql ├── 1069. Product Sales Analysis II.sql ├── 1070. Product Sales Analysis III.sql ├── 1075. Project Employees I.sql ├── 1076. Project Employees II.sql ├── 1077. Project Employees III.sql ├── 1082. Sales Analysis I.sql ├── 1083. Sales Analysis II.sql ├── 1084. Sales Analysis III.sql ├── 1097. Game Play Analysis V.sql ├── 1098. Unpopular Books.sql ├── 1107. New Users Daily Count.sql ├── 1112. Highest Grade For Each Student.sql ├── 1113. Reported Posts.sql ├── 1126. Active Businesses.sql ├── 1127. User Purchase Platform.sql ├── 1132. Reported Posts II.sql ├── 1141. User Activity for the Past 30 Days I.sql ├── 1142. User Activity for the Past 30 Days II.sql ├── 1148. Article Views I.sql ├── 1149. Article Views II.sql ├── 175. Combine Two Tables.sql ├── 176. Second Highest Salary.sql ├── 177. Nth Highest Salary.sql ├── 178. Rank Scores.sql ├── 180. Consecutive Numbers.sql ├── 181. Employee Earning More Than Their Manager.sql ├── 182. Duplicate Emails.sql ├── 183. Customers Who Never Order.sql ├── 184. Department Highest Salary.sql ├── 185. Department Top Three Salaries.sql ├── 196. Delete Duplicate Emails.sql ├── 197. Rising Temperature.sql ├── 262. Trips and Users.sql ├── 511. Game Play Analysis I.sql ├── 512. Game Play Analysis II.sql ├── 534. Game Play Analysis III.sql ├── 550. Game Play Analysis IV.sql ├── 569. Median Employee Salary.sql ├── 570. Managers with at Least 5 Direct Reports.sql ├── 571. Find Median Given Frequency of Numbers.sql ├── 574. Winning Candidate.sql ├── 577. Employee Bonus.sql ├── 578. Get Highest Answer Rate Question.sql ├── 579. Find Cumulative Salary of an Employee.sql ├── 580. Count Student Number in Departments.sql ├── 584. Find Customer Referee.sql ├── 585. Investments in 2016.sql ├── 586. Customer Placing the Largest Number of Orders.sql ├── 595. Big Countries.sql ├── 596. Classes More Than 5 Students.sql ├── 597. Friend Requests I: Overall Acceptance Rate.sql ├── 601. Human Traffic of Stadium.sql ├── 602. Friend Requests II: Who Has the Most Friends.sql ├── 603. Consecutive Available Seats.sql ├── 607. Sales Person.sql ├── 608. Tree Node.sql ├── 610. Triangle Judgement.sql ├── 612. Shortest Distance in a Plane.sql ├── 613. Shortest Distance in a Line.sql ├── 614. Second Degree Follower.sql ├── 615. Average Salary: Department VS Company.sql ├── 618. Students Report By Geography.sql ├── 619. Biggest Single Number.sql ├── 620. Not Boring Movies.sql ├── 626. Exchange Seats.sql └── 627. Swap Salary.sql ├── Other ├── 386. Lexicographical Numbers.java ├── 388. Longest Absolute File Path.java ├── 419. Battleships in a Board.java ├── 420. Strong Password Checker.java ├── 427. Construct Quad Tree.java ├── 470. Implement Rand10() Using Rand7().java ├── 479. Largest Palindrome Product.java ├── 481. Magical String.java ├── 482. License Key Formatting.java ├── 497. Random Point in Non-overlapping Rectangles.java ├── 498. Diagonal Traverse.java ├── 504. Base 7.java ├── 506. Relative Ranks.java ├── 519. Random Flip Matrix.java └── 558. Quad Tree Intersection.java ├── Queue ├── 346. Moving Average from Data Stream.java └── 353. Design Snake Game.java ├── README.md ├── Recursion ├── 247. Strobogrammatic Number II.java ├── 248. Strobogrammatic Number III.java ├── 698. Partition to K Equal Sum Subsets.java ├── 726. Number of Atoms.java └── 776. Split BST.java ├── Reservoir Sampling ├── 382. Linked List Random Node.java └── 398. Random Pick Index.java ├── Segment Tree ├── 307. Range Sum Query - Mutable.java ├── 315. Count of Smaller Numbers After Self.java └── 493. Reverse Pairs.java ├── Sliding Window ├── 1004. Max Consecutive Ones III.java ├── 1052. Grumpy Bookstore Owner.java ├── 1100. Find K-Length Substrings With No Repeated Characters.java ├── 1151. Minimum Swaps to Group All 1's Together.java ├── 159. Longest Substring with At Most Two Distinct Characters.java ├── 239. Sliding Window Maximum.java ├── 3. Longest Substring Without Repeating Characters.java ├── 340. Longest Substring with At Most K Distinct Characters.java ├── 424. Longest Repeating Character Replacement.java ├── 438. Find All Anagrams in a String.java ├── 480. Sliding Window Median.java ├── 567. Permutation in String.java ├── 727. Minimum Window Subsequence.java ├── 76. Minimum Window Substring.java ├── 992. Subarrays with K Different Integers.java └── 995. Minimum Number of K Consecutive Bit Flips.java ├── Sort ├── 1057. Campus Bikes.java ├── 1086. High Five.java ├── 147. Insertion Sort List.java ├── 148. Sort List.java ├── 164. Maximum Gap.java ├── 179. Largest Number.java ├── 252. Meeting Rooms.java ├── 253. Meeting Rooms II.java ├── 280. Wiggle Sort.java ├── 296. Best Meeting Point.java ├── 324. Wiggle Sort II.java ├── 349. Intersection of Two Arrays.java ├── 350. Intersection of Two Arrays II.java ├── 56. Merge Intervals.java ├── 57. Insert Interval.java ├── 75. Sort Colors.java ├── 759. Employee Free Time.java ├── 853. Car Fleet.java ├── 912. Sort an Array.java ├── 969. Pancake Sorting.java └── 973. K Closest Points to Origin.java ├── Stack ├── 1003. Check If Word Is Valid After Substitutions.java ├── 1019. Next Greater Node In Linked List.java ├── 1028. Recover a Tree From Preorder Traversal.java ├── 1047. Remove All Adjacent Duplicates In String.java ├── 1063. Number of Valid Subarrays.java ├── 1081. Smallest Subsequence of Distinct Characters.java ├── 1106. Parsing A Boolean Expression.java ├── 144. Binary Tree Preorder Traversal.java ├── 145. Binary Tree Postorder Traversal.java ├── 150. Evaluate Reverse Polish Notation.java ├── 155. Min Stack.java ├── 173. Binary Search Tree Iterator.java ├── 20. Valid Parentheses.java ├── 224. Basic Calculator.java ├── 225. Implement Stack using Queues.java ├── 232. Implement Queue using Stacks.java ├── 255. Verify Preorder Sequence in Binary Search Tree.java ├── 316. Remove Duplicate Letters.java ├── 331. Verify Preorder Serialization of a Binary Tree.java ├── 341. Flatten Nested List Iterator.java ├── 385. Mini Parser.java ├── 394. Decode String.java ├── 402. Remove K Digits.java ├── 439. Ternary Expression Parser.java ├── 456. 132 Pattern.java ├── 496. Next Greater Element I.java ├── 503. Next Greater Element II.java ├── 591. Tag Validator.java ├── 636. Exclusive Time of Functions.java ├── 682. Baseball Game.java ├── 71. Simplify Path.java ├── 716. Max Stack.java ├── 735. Asteroid Collision.java ├── 739. Daily Temperatures.java ├── 84. Largest Rectangle in Histogram.java ├── 856. Score of Parentheses.java ├── 94. Binary Tree Inorder Traversal.java └── 946. Validate Stack Sequences.java ├── String ├── 10. Regular Expression Matching.java ├── 1016. Binary String With Substrings Representing 1 To N.java ├── 1023. Camelcase Matching.java ├── 1065. Index Pairs of a String.java ├── 1071. Greatest Common Divisor of Strings.java ├── 1078. Occurrences After Bigram.java ├── 1096. Brace Expansion II.java ├── 1106. Parsing A Boolean Expression.java ├── 1108. Defanging an IP Address.java ├── 1119. Remove Vowels from a String.java ├── 115. Distinct Subsequences.java ├── 12. Integer to Roman.java ├── 125. Valid Palindrome.java ├── 126. Word Ladder II.java ├── 13. Roman to Integer.java ├── 14. Longest Common Prefix.java ├── 151. Reverse Words in a String.java ├── 157. Read N Characters Given Read4.java ├── 158. Read N Characters Given Read4 II - Call multiple times.java ├── 159. Longest Substring with At Most Two Distinct Characters.java ├── 161. One Edit Distance.java ├── 165. Compare Version Numbers.java ├── 17. Letter Combinations of a Phone Number.java ├── 186. Reverse Words in a String II.java ├── 20. Valid Parentheses.java ├── 22. Generate Parentheses.java ├── 227. Basic Calculator II.java ├── 249. Group Shifted Strings.java ├── 271. Encode and Decode Strings.java ├── 273. Integer to English Words.java ├── 28. Implement strStr().java ├── 293. Flip Game.java ├── 3. Longest Substring Without Repeating Characters.java ├── 30. Substring with Concatenation of All Words.java ├── 32. Longest Valid Parentheses.java ├── 340. Longest Substring with At Most K Distinct Characters.java ├── 344. Reverse String.java ├── 345. Reverse Vowels of a String.java ├── 38. Count and Say.java ├── 383. Ransom Note.java ├── 385. Mini Parser.java ├── 387. First Unique Character in a String.java ├── 408. Valid Word Abbreviation.java ├── 415. Add Strings.java ├── 418. Sentence Screen Fitting.java ├── 422. Valid Word Square.java ├── 43. Multiply Strings.java ├── 434. Number of Segments in a String.java ├── 44. Wildcard Matching.java ├── 443. String Compression.java ├── 459. Repeated Substring Pattern.java ├── 468. Validate IP Address.java ├── 49. Group Anagrams.java ├── 5. Longest Palindromic Substring.java ├── 520. Detect Capital.java ├── 521. Longest Uncommon Subsequence I.java ├── 522. Longest Uncommon Subsequence II.java ├── 527. Word Abbreviation.java ├── 539. Minimum Time Difference.java ├── 541. Reverse String II.java ├── 544. Output Contest Matches.java ├── 551. Student Attendance Record I.java ├── 555. Split Concatenated Strings.java ├── 556. Next Greater Element III.java ├── 557. Reverse Words in a String III.java ├── 564. Find the Closest Palindrome.java ├── 58. Length of Last Word.java ├── 591. Tag Validator.java ├── 6. ZigZag Conversion.java ├── 616. Add Bold Tag in String.java ├── 640. Solve the Equation.java ├── 65. Valid Number.java ├── 657. Robot Return to Origin.java ├── 67. Add Binary.java ├── 68. Text Justification.java ├── 680. Valid Palindrome II.java ├── 681. Next Closest Time.java ├── 686. Repeated String Match.java ├── 696. Count Binary Substrings.java ├── 709. To Lower Case.java ├── 71. Simplify Path.java ├── 72. Edit Distance.java ├── 722. Remove Comments.java ├── 758. Bold Words in String.java ├── 76. Minimum Window Substring.java ├── 8. String to Integer (atoi).java ├── 87. Scramble String.java ├── 91. Decode Ways.java ├── 93. Restore IP Addresses.java ├── 944. Delete Columns to Make Sorted.java ├── 966. Vowel Spellchecker.java └── 97. Interleaving String.java ├── Topological Sort ├── 1136. Parallel Courses.java ├── 207. Course Schedule.java ├── 210. Course Schedule II.java ├── 269. Alien Dictionary.java └── 444. Sequence Reconstruction.java ├── Tree ├── 100. Same Tree.java ├── 1008. Construct Binary Search Tree from Preorder Traversal.java ├── 101. Symmetric Tree.java ├── 102. Binary Tree Level Order Traversal.java ├── 1022. Sum of Root To Leaf Binary Numbers.java ├── 1026. Maximum Difference Between Node and Ancestor.java ├── 1028. Recover a Tree From Preorder Traversal.java ├── 103. Binary Tree Zigzag Level Order Traversal.java ├── 1038. Binary Search Tree to Greater Sum Tree.java ├── 104. Maximum Depth of Binary Tree.java ├── 105. Construct Binary Tree from Preorder and Inorder Traversal.java ├── 106. Construct Binary Tree from Inorder and Postorder Traversal.java ├── 107. Binary Tree Level Order Traversal II.java ├── 108. Convert Sorted Array to BST.java ├── 1080. Insufficient Nodes in Root to Leaf Paths.java ├── 110. Balanced Binary Tree.java ├── 111. Minimum Depth of Binary Tree.java ├── 1110. Delete Nodes And Return Forest.java ├── 112. Path Sum.java ├── 1120. Maximum Average Subtree.java ├── 1123. Lowest Common Ancestor of Deepest Leaves.java ├── 113. Path Sum II.java ├── 114. Flatten Binary Tree to Linked List.java ├── 1145. Binary Tree Coloring Game.java ├── 116. Populating Next Right Pointers in Each Node.java ├── 117. Populating Next Right Pointers in Each Node II.java ├── 124. Binary Tree Maximum Path Sum.java ├── 129. Sum Root to Leaf Numbers.java ├── 144. Binary Tree Preorder Traversal.java ├── 145. Binary Tree Postorder Traversal.java ├── 156. Binary Tree Upside Down.java ├── 173. Binary Search Tree Iterator.java ├── 199. Binary Tree Right Side View.java ├── 222. Count Complete Tree Nodes.java ├── 226. Invert Binary Tree.java ├── 230. Kth Smallest Element in a BST.java ├── 235. Lowest Common Ancestor of a Binary Search Tree.java ├── 236. Lowest Common Ancestor of a Binary Tree.java ├── 250. Count Univalue Subtrees.java ├── 255. Verify Preorder Sequence in Binary Search Tree.java ├── 257. Binary Tree Paths.java ├── 270. Closest Binary Search Tree Value.java ├── 285. Inorder Successor in BST.java ├── 297. Serialize and Deserialize Binary Tree.java ├── 298. Binary Tree Longest Consecutive Sequence.java ├── 333. Largest BST Subtree.java ├── 337. House Robber III.java ├── 366. Find Leaves of Binary Tree.java ├── 404. Sum of Left Leaves.java ├── 426. Convert Binary Search Tree to Sorted Doubly Linked List.java ├── 428. Serialize and Deserialize N-ary Tree.java ├── 429. N-ary Tree Level Order Traversal.java ├── 431. Encode N-ary Tree to Binary Tree.java ├── 437. Path Sum III.java ├── 449. Serialize and Deserialize BST.java ├── 450. Delete Node in a BST.java ├── 501. Find Mode in Binary Search Tree.java ├── 508. Most Frequent Subtree Sum.java ├── 510. Inorder Successor in BST II.java ├── 513. Find Bottom Left Tree Value.java ├── 515. Find Largest Value in Each Tree Row.java ├── 530. Minimum Absolute Difference in BST.java ├── 536. Construct Binary Tree from String.java ├── 538. Convert BST to Greater Tree.java ├── 543. Diameter of Binary Tree.java ├── 545. Boundary of Binary Tree.java ├── 549. Binary Tree Longest Consecutive Sequence II.java ├── 559. Maximum Depth of N-ary Tree.java ├── 563. Binary Tree Tilt.java ├── 572. Subtree of Another Tree.java ├── 589. N-ary Tree Preorder Traversal.java ├── 590. N-ary Tree Postorder Traversal.java ├── 606. Construct String from Binary Tree.java ├── 617. Merge Two Binary Trees.java ├── 623. Add One Row to Tree.java ├── 637. Average of Levels in Binary Tree.java ├── 652. Find Duplicate Subtrees.java ├── 653. Two Sum IV - Input is a BST.java ├── 654. Maximum Binary Tree.java ├── 655. Print Binary Tree.java ├── 662. Maximum Width of Binary Tree.java ├── 663. Equal Tree Partition.java ├── 666. Path Sum IV.java ├── 669. Trim a Binary Search Tree.java ├── 671. Second Minimum Node In a Binary Tree.java ├── 687. Longest Univalue Path.java ├── 700. Search in a Binary Search Tree.java ├── 701. Insert into a Binary Search Tree.java ├── 742. Closest Leaf in a Binary Tree.java ├── 776. Split BST.java ├── 94. Binary Tree Inorder Traversal.java ├── 95. Unique Binary Search Trees II.java ├── 951. Flip Equivalent Binary Trees.java ├── 958. Check Completeness of a Binary Tree.java ├── 96. Unique Binary Search Trees.java ├── 965. Univalued Binary Tree.java ├── 968. Binary Tree Cameras.java ├── 971. Flip Binary Tree To Match Preorder Traversal.java ├── 979. Distribute Coins in Binary Tree.java ├── 98. Validate Binary Search Tree.java ├── 987. Vertical Order Traversal of a Binary Tree.java ├── 988. Smallest String Starting From Leaf.java ├── 99. Recover Binary Search Tree.java ├── 993. Cousins in Binary Tree.java └── 998. Maximum Binary Tree II.java ├── Trie ├── 1032. Stream of Characters.java ├── 1065. Index Pairs of a String.java ├── 208. Implement Trie (Prefix Tree).java ├── 211. Add and Search Word - Data structure design.java ├── 212. Word Search II.java ├── 411. Minimum Unique Word Abbreviation.java ├── 421. Maximum XOR of Two Numbers in an Array.java ├── 425. Word Squares.java ├── 472. Concatenated Words.java ├── 527. Word Abbreviation.java ├── 588. Design In-Memory File System.java ├── 642. Design Search Autocomplete System.java ├── 648. Replace Words.java ├── 676. Implement Magic Dictionary.java ├── 677. Map Sum Pairs.java ├── 720. Longest Word in Dictionary.java └── 745. Prefix and Suffix Search.java ├── Two Pointers ├── 1021. Remove Outermost Parentheses.java ├── 1055. Shortest Way to Form String.java ├── 11. Container With Most Water.java ├── 125. Valid Palindrome.java ├── 141. Linked List Cycle.java ├── 142. Linked List Cycle II.java ├── 15. 3Sum.java ├── 159. Longest Substring with At Most Two Distinct Characters.java ├── 16. 3Sum Closest.java ├── 167. Two Sum II - Input array is sorted.java ├── 18. 4Sum.java ├── 19. Remove Nth Node From End of List.java ├── 209. Minimum Size Subarray Sum.java ├── 234. Palindrome Linked List.java ├── 259. 3Sum Smaller.java ├── 26. Remove Duplicates from Sorted Array.java ├── 27. Remove Elements.java ├── 28. Implement strStr().java ├── 283. Move Zeroes.java ├── 287. Find the Duplicate Number.java ├── 3. Longest Substring Without Repeating Characters.java ├── 30. Substring with Concatenation of All Words.java ├── 344. Reverse String.java ├── 345. Reverse Vowels of a String.java ├── 349. Intersection of Two Arrays.java ├── 350. Intersection of Two Arrays II.java ├── 360. Sort Transformed Array.java ├── 42. Trapping Rain Water.java ├── 424. Longest Repeating Character Replacement.java ├── 457. Circular Array Loop.java ├── 487. Max Consecutive Ones II.java ├── 524. Longest Word in Dictionary through Deleting.java ├── 567. Permutation in String.java ├── 61. Rotate List.java ├── 632. Smallest Range.java ├── 633. Sum of Square Numbers.java ├── 713. Subarray Product Less Than K.java ├── 75. Sort Colors.java ├── 76. Minimum Window Substring.java ├── 80. Remove Duplicates from Sorted Array II.java ├── 86. Partition List.java ├── 88. Merge Sorted Array.java ├── 977. Squares of a Sorted Array.java ├── 986. Interval List Intersections.java └── 992. Subarrays with K Different Integers.java └── Union Find ├── 1061. Lexicographically Smallest Equivalent String.java ├── 1101. The Earliest Moment When Everyone Become Friends.java ├── 1135. Connecting Cities With Minimum Cost.java ├── 200. Number of Islands.java ├── 261. Graph Valid Tree.java ├── 305. Number of Islands II.java ├── 323. Number of Connected Components in an Undirected Graph.java ├── 684. Redundant Connection.java ├── 685. Redundant Connection II.java ├── 737. Sentence Similarity II.java ├── 928. Minimize Malware Spread II.java ├── 947. Most Stones Removed with Same Row or Column.java ├── 952. Largest Component Size by Common Factor.java └── 990. Satisfiability of Equality Equations.java /Array/1014. Best Sightseeing Pair.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array A of positive integers, A[i] represents the value of the i-th sightseeing spot, 5 | and two sightseeing spots i and j have distance j - i between them. 6 | The score of a pair (i < j) of sightseeing spots is (A[i] + A[j] + i - j) : 7 | the sum of the values of the sightseeing spots, minus the distance between them. 8 | Return the maximum score of a pair of sightseeing spots. 9 | 10 | Example 1: 11 | Input: [8,1,5,2,6] 12 | Output: 11 13 | Explanation: i = 0, j = 2, A[i] + A[j] + i - j = 8 + 5 + 0 - 2 = 11 14 | 15 | */ 16 | 17 | /* 18 | 19 | Solution: use max to track the current max number in A[0...i] 20 | ans=max(ans,max+A[i]) if we don't consider j-i, with j-i which means max should decrease by 1 for each step 21 | O(n),O(1) 22 | 23 | */ 24 | 25 | public int maxScoreSightseeingPair(int[] A) { 26 | int ans = 0, max = 0; 27 | for (int a : A) { 28 | ans = Math.max(ans, max + a); 29 | max = Math.max(max, a) - 1; 30 | } 31 | return ans; 32 | } 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /Array/1051. Height Checker.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Students are asked to stand in non-decreasing order of heights for an annual photo. 5 | Return the minimum number of students not standing in the right positions. 6 | (This is the number of students that must move in order for all students to be standing in non-decreasing order of height.) 7 | 8 | Example 1: 9 | Input: [1,1,4,2,1,3] 10 | Output: 3 11 | Explanation: 12 | Students with heights 4, 3 and the last 1 are not standing in the right positions. 13 | 14 | */ 15 | 16 | /* 17 | 18 | O(nlogn),O(n) 19 | 20 | */ 21 | 22 | public int heightChecker(int[] heights) { 23 | int n = heights.length, ans = 0; 24 | int[] sorted = Arrays.copyOf(heights, n); 25 | Arrays.sort(sorted); 26 | for (int i = 0; i < n; ++i) { 27 | if (heights[i] != sorted[i]) { 28 | ans++; 29 | } 30 | } 31 | return ans; 32 | } 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Array/1085. Sum of Digits in the Minimum Number.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array A of positive integers, let S be the sum of the digits of the minimal element of A. 5 | Return 0 if S is odd, otherwise return 1. 6 | 7 | Example 1: 8 | Input: [34,23,1,24,75,33,54,8] 9 | Output: 0 10 | Explanation: 11 | The minimal element is 1, and the sum of those digits is S = 1 which is odd, so the answer is 0. 12 | 13 | Example 2: 14 | Input: [99,77,33,66,55] 15 | Output: 1 16 | Explanation: 17 | The minimal element is 33, and the sum of those digits is S = 3 + 3 = 6 which is even, so the answer is 1. 18 | 19 | */ 20 | 21 | /* 22 | 23 | O(n),O(1) 24 | 25 | */ 26 | 27 | public int sumOfDigits(int[] A) { 28 | int ans = 0, min = Integer.MAX_VALUE; 29 | for (int a : A) { 30 | min = Math.min(min, a); 31 | } 32 | while (min != 0) { 33 | ans += min % 10; 34 | min /= 10; 35 | } 36 | return ans % 2 == 0 ? 1 : 0; 37 | } 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /Array/1099. Two Sum Less Than K.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array A of integers and integer K, return the maximum S such that there exists i < j with A[i] + A[j] = S and S < K. 5 | If no i, j exist satisfying this equation, return -1. 6 | 7 | Example 1: 8 | Input: A = [34,23,1,24,75,33,54,8], K = 60 9 | Output: 58 10 | Explanation: 11 | We can use 34 and 24 to sum 58 which is less than 60. 12 | 13 | Example 2: 14 | Input: A = [10,20,30], K = 15 15 | Output: -1 16 | Explanation: 17 | In this case it's not possible to get a pair sum less that 15. 18 | 19 | */ 20 | 21 | /* 22 | 23 | O(nlogn),O(1) 24 | 25 | */ 26 | 27 | public int twoSumLessThanK(int[] A, int K) { 28 | Arrays.sort(A); 29 | int ans = -1, i = 0, j = A.length - 1; 30 | while (i < j) { 31 | int sum = A[i] + A[j]; 32 | if (sum < K) { 33 | ans = Math.max(ans, sum); 34 | i++; 35 | } else { 36 | j--; 37 | } 38 | } 39 | return ans; 40 | } 41 | 42 | 43 | -------------------------------------------------------------------------------- /Array/11. Container With Most Water.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn 5 | such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, 6 | such that the container contains the most water. 7 | 8 | Note: You may not slant the container and n is at least 2. 9 | 10 | */ 11 | 12 | /* 13 | 14 | O(n),O(1) 15 | 16 | */ 17 | 18 | public int maxArea(int[] height) { 19 | int l = 0, r = height.length - 1, ans = 0; 20 | while (l < r) { 21 | ans = Math.max(ans, (r - l) * Math.min(height[l], height[r])); 22 | if (height[l] < height[r]) l++; 23 | else r--; 24 | } 25 | return ans; 26 | } 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /Array/1100. Find K-Length Substrings With No Repeated Characters.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a string S, return the number of substrings of length K with no repeated characters. 5 | 6 | Example 1: 7 | Input: S = "havefunonleetcode", K = 5 8 | Output: 6 9 | Explanation: 10 | There are 6 substrings they are : 'havef','avefu','vefun','efuno','etcod','tcode'. 11 | 12 | Example 2: 13 | Input: S = "home", K = 5 14 | Output: 0 15 | Explanation: 16 | Notice K can be larger than the length of S. In this case is not possible to find any substring. 17 | 18 | */ 19 | 20 | /* 21 | 22 | O(n),O(1) 23 | 24 | */ 25 | 26 | public int numKLenSubstrNoRepeats(String S, int K) { 27 | int[] buckets = new int[26]; 28 | int ans = 0; 29 | for (int i = 0, j = 0; j < S.length(); ++j) { 30 | buckets[S.charAt(j) - 'a']++; 31 | while (buckets[S.charAt(j) - 'a'] > 1) { 32 | buckets[S.charAt(i) - 'a']--; 33 | i++; 34 | } 35 | if (j - i + 1 >= K) { 36 | ans++; 37 | } 38 | } 39 | return ans; 40 | } 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Array/1109. Corporate Flight Bookings.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | There are n flights, and they are labeled from 1 to n. 5 | We have a list of flight bookings. 6 | The i-th booking bookings[i] = [i, j, k] means that we booked k seats from flights labeled i to j inclusive. 7 | Return an array answer of length n, representing the number of seats booked on each flight in order of their label. 8 | 9 | Example 1: 10 | Input: bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5 11 | Output: [10,55,45,25,25] 12 | 13 | */ 14 | 15 | /* 16 | 17 | O(n),O(n) 18 | 19 | */ 20 | 21 | public int[] corpFlightBookings(int[][] bookings, int n) { 22 | int[] ans = new int[n]; 23 | for (int[] booking : bookings) { 24 | int l = booking[0], r = booking[1], cnt = booking[2]; 25 | ans[l - 1] += cnt; 26 | if (r < n) { 27 | ans[r] -= cnt; 28 | } 29 | } 30 | for (int i = 1; i < n; ++i) { 31 | ans[i] += ans[i - 1]; 32 | } 33 | return ans; 34 | } 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /Array/1133. Largest Unique Number.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array of integers A, return the largest integer that only occurs once. 5 | If no integer occurs once, return -1. 6 | 7 | Example 1: 8 | Input: [5,7,3,9,4,9,8,3,1] 9 | Output: 8 10 | Explanation: 11 | The maximum integer in the array is 9 but it is repeated. The number 8 occurs only once, so it's the answer. 12 | 13 | Example 2: 14 | Input: [9,9,8,8] 15 | Output: -1 16 | Explanation: 17 | There is no number that occurs only once. 18 | 19 | */ 20 | 21 | /* 22 | 23 | O(n),O(n) 24 | 25 | */ 26 | 27 | public int largestUniqueNumber(int[] A) { 28 | int max = 0, ans = 0; 29 | for (int a : A) { 30 | max = Math.max(max, a); 31 | } 32 | int[] buckets = new int[max + 1]; 33 | for (int a : A) { 34 | buckets[a]++; 35 | } 36 | for (int i = max; i >= 0; --i) { 37 | if (buckets[i] == 1) { 38 | return i; 39 | } 40 | } 41 | return -1; 42 | } 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /Array/1137. N-th Tribonacci Number.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | The Tribonacci sequence Tn is defined as follows: 5 | T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0. 6 | Given n, return the value of Tn. 7 | 8 | Example 1: 9 | Input: n = 4 10 | Output: 4 11 | Explanation: 12 | T_3 = 0 + 1 + 1 = 2 13 | T_4 = 1 + 1 + 2 = 4 14 | 15 | Example 2: 16 | Input: n = 25 17 | Output: 1389537 18 | 19 | */ 20 | 21 | /* 22 | 23 | O(n),O(1) 24 | 25 | */ 26 | 27 | public int tribonacci(int n) { 28 | if (n < 2) { 29 | return n; 30 | } 31 | int first = 1, second = 1, third = 0; 32 | while (n > 2) { 33 | int cur = first + second + third; 34 | third = second; 35 | second = first; 36 | first = cur; 37 | n--; 38 | } 39 | return first; 40 | } 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Array/118. Pascal's Triangle.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. 5 | In Pascal's triangle, each number is the sum of the two numbers directly above it. 6 | 7 | Example: 8 | Input: 5 9 | Output: 10 | [ 11 | [1], 12 | [1,1], 13 | [1,2,1], 14 | [1,3,3,1], 15 | [1,4,6,4,1] 16 | ] 17 | 18 | */ 19 | 20 | /* 21 | 22 | O(n^2),O(n) 23 | 24 | */ 25 | 26 | public List> generate(int numRows) { 27 | List> ans = new ArrayList<>(); 28 | for (int i = 0; i < numRows; ++i) { 29 | List tmp = new ArrayList<>(); 30 | for (int j = 0; j <= i; ++j) { 31 | if (j == 0 || j == i) tmp.add(1); 32 | else tmp.add(ans.get(i - 1).get(j - 1) + ans.get(i - 1).get(j)); 33 | } 34 | ans.add(tmp); 35 | } 36 | return ans; 37 | } 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /Array/119. Pascal's Triangle II.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle. 5 | Note that the row index starts from 0. 6 | In Pascal's triangle, each number is the sum of the two numbers directly above it. 7 | 8 | Example: 9 | Input: 3 10 | Output: [1,3,3,1] 11 | 12 | */ 13 | 14 | /* 15 | 16 | Solution: add 1 to the list in each level, and simulate the pascal's triangle adding process 17 | 1 18 | 11 19 | 111 -> 121 20 | 1211 -> 1331 21 | 13311 -> 14641 22 | O(n^2),O(n) 23 | 24 | */ 25 | 26 | public List getRow(int rowIndex) { 27 | List ans = new ArrayList<>(); 28 | for (int i = 0; i <= rowIndex; ++i) { 29 | ans.add(1); 30 | for (int j = i - 1; j >= 1; --j) { 31 | ans.set(j, ans.get(j - 1) + ans.get(j)); 32 | } 33 | } 34 | return ans; 35 | } 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Array/153. Find Minimum in Rotated Sorted Array.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 5 | (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). 6 | Find the minimum element. 7 | You may assume no duplicate exists in the array. 8 | 9 | Example 1: 10 | Input: [3,4,5,1,2] 11 | Output: 1 12 | 13 | Example 2: 14 | Input: [4,5,6,7,0,1,2] 15 | Output: 0 16 | 17 | */ 18 | 19 | /* 20 | 21 | O(logn),O(1) 22 | 23 | */ 24 | 25 | public int findMin(int[] nums) { 26 | int l = 0, r = nums.length - 1; 27 | while (l < r) { 28 | int mid = (l + r) / 2; 29 | if (nums[r] < nums[mid]) l = mid + 1; 30 | else r = mid; 31 | } 32 | return nums[l]; 33 | } 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /Array/154. Find Minimum in Rotated Sorted Array II.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 5 | (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). 6 | Find the minimum element. 7 | The array may contain duplicates. 8 | 9 | Example 1: 10 | Input: [1,3,5] 11 | Output: 1 12 | 13 | Example 2: 14 | Input: [2,2,2,0,1] 15 | Output: 0 16 | 17 | */ 18 | 19 | /* 20 | 21 | O(logn),O(1) 22 | 23 | */ 24 | 25 | public int findMin(int[] nums) { 26 | int l = 0, r = nums.length - 1; 27 | while (l < r) { 28 | int mid = (l + r) / 2; 29 | if (nums[mid] > nums[r]) l = mid + 1; 30 | else if (nums[mid] < nums[r]) r = mid; 31 | else r--; 32 | } 33 | return nums[l]; 34 | } 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /Array/219. Contains Duplicate II.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array 5 | such that nums[i] = nums[j] and the absolute difference between i and j is at most k. 6 | 7 | Example 1: 8 | Input: nums = [1,2,3,1], k = 3 9 | Output: true 10 | 11 | Example 2: 12 | Input: nums = [1,0,1,1], k = 1 13 | Output: true 14 | 15 | Example 3: 16 | Input: nums = [1,2,3,1,2,3], k = 2 17 | Output: false 18 | 19 | */ 20 | 21 | /* 22 | 23 | O(n),O(k) 24 | 25 | */ 26 | 27 | public boolean containsNearbyDuplicate(int[] nums, int k) { 28 | Set set = new HashSet<>(); 29 | for (int i = 0; i < nums.length; ++i) { 30 | if (i > k) set.remove(nums[i - k - 1]); 31 | if (!set.add(nums[i])) return true; 32 | } 33 | return false; 34 | } 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /Array/228. Summary Ranges.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a sorted integer array without duplicates, return the summary of its ranges. 5 | 6 | Example 1: 7 | Input: [0,1,2,4,5,7] 8 | Output: ["0->2","4->5","7"] 9 | Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range. 10 | 11 | Example 2: 12 | Input: [0,2,3,4,6,8,9] 13 | Output: ["0","2->4","6","8->9"] 14 | Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range. 15 | 16 | */ 17 | 18 | /* 19 | 20 | O(n),O(1) 21 | 22 | */ 23 | 24 | public List summaryRanges(int[] nums) { 25 | List ans = new ArrayList<>(); 26 | for (int i = 0; i < nums.length; ++i) { 27 | int start = nums[i]; 28 | while (i < nums.length - 1 && nums[i + 1] == nums[i] + 1) ++i; 29 | int end = nums[i]; 30 | if (start == end) ans.add(String.valueOf(start)); 31 | else ans.add(start + "->" + end); 32 | } 33 | return ans; 34 | } 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /Array/238. Product of Array Except Self.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array nums of n integers where n > 1, 5 | return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. 6 | 7 | Example: 8 | Input: [1,2,3,4] 9 | Output: [24,12,8,6] 10 | 11 | */ 12 | 13 | /* 14 | 15 | O(n),O(1) 16 | 17 | */ 18 | 19 | public int[] productExceptSelf(int[] nums) { 20 | int n = nums.length; 21 | int[] ans = new int[n]; 22 | for (int i = 0, tmp = 1; i < n; ++i) { 23 | ans[i] = tmp; 24 | tmp *= nums[i]; 25 | } 26 | for (int i = n - 1, tmp = 1; i >= 0; --i) { 27 | ans[i] *= tmp; 28 | tmp *= nums[i]; 29 | } 30 | return ans; 31 | } 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /Array/243. Shortest Word Distance.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list. 5 | 6 | Example: 7 | Assume that words = ["practice", "makes", "perfect", "coding", "makes"]. 8 | 9 | Input: word1 = “coding”, word2 = “practice” 10 | Output: 3 11 | 12 | Input: word1 = "makes", word2 = "coding" 13 | Output: 1 14 | 15 | */ 16 | 17 | /* 18 | 19 | O(n),O(1) 20 | 21 | */ 22 | 23 | public int shortestDistance(String[] words, String word1, String word2) { 24 | int idx1 = -1, idx2 = -1, ans = Integer.MAX_VALUE; 25 | for (int i = 0; i < words.length; ++i) { 26 | if (words[i].equals(word1)) idx1 = i; 27 | else if (words[i].equals(word2)) idx2 = i; 28 | if (idx1 != -1 && idx2 != -1) ans = Math.min(ans, Math.abs(idx1 - idx2)); 29 | } 30 | return ans; 31 | } 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Array/259. 3Sum Smaller.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n 5 | that satisfy the condition nums[i] + nums[j] + nums[k] < target. 6 | 7 | Example: 8 | Input: nums = [-2,0,1,3], and target = 2 9 | Output: 2 10 | Explanation: Because there are two triplets which sums are less than 2: 11 | [-2,0,1] 12 | [-2,0,3] 13 | 14 | */ 15 | 16 | /* 17 | 18 | O(n^2),O(1) 19 | 20 | */ 21 | 22 | public int threeSumSmaller(int[] nums, int target) { 23 | int ans = 0; 24 | Arrays.sort(nums); 25 | for (int i = 0; i < nums.length; ++i) { 26 | int j = i + 1, k = nums.length - 1; 27 | while (j < k) { 28 | int sum = nums[i] + nums[j] + nums[k]; 29 | if (sum < target) { 30 | ans += k - j; 31 | j++; 32 | } else k--; 33 | } 34 | } 35 | return ans; 36 | } 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /Array/26. Remove Duplicates from Sorted Array.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. 5 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 6 | 7 | Example 1: 8 | Given nums = [1,1,2], 9 | Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. 10 | It doesn't matter what you leave beyond the returned length. 11 | 12 | Example 2: 13 | Given nums = [0,0,1,1,1,2,2,3,3,4], 14 | Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. 15 | It doesn't matter what values are set beyond the returned length. 16 | 17 | */ 18 | 19 | /* 20 | 21 | O(n),O(1) 22 | 23 | */ 24 | 25 | public int removeDuplicates(int[] nums) { 26 | int i = 0; 27 | for (int num : nums) { 28 | if (i < 1 || num != nums[i - 1]) nums[i++] = num; 29 | } 30 | return i; 31 | } 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Array/268. Missing Number.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. 5 | 6 | Example 1: 7 | Input: [3,0,1] 8 | Output: 2 9 | 10 | Example 2: 11 | Input: [9,6,4,2,3,5,7,0,1] 12 | Output: 8 13 | 14 | */ 15 | 16 | /* 17 | 18 | Solution: since num is 0,1,2,...,n, num^index=0 if this num is not missing 19 | O(n),O(1) 20 | 21 | */ 22 | 23 | public int missingNumber(int[] nums) { 24 | int ans = nums.length; 25 | for (int i = 0; i < nums.length; ++i) ans = ans ^ i ^ nums[i]; 26 | return ans; 27 | } 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /Array/283. Move Zeroes.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array nums, write a function to move all 0's to the end of it while maintaining the order of the other elements. 5 | 6 | Example: 7 | Input: [0,1,0,3,12] 8 | Output: [1,3,12,0,0] 9 | 10 | */ 11 | 12 | /* 13 | 14 | O(n),O(1) 15 | 16 | */ 17 | 18 | public void moveZeroes(int[] nums) { 19 | int i = 0; 20 | for (int num : nums) { 21 | if (num != 0) nums[i++] = num; 22 | } 23 | while (i < nums.length) nums[i++] = 0; 24 | } 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /Array/334. Increasing Triplet Subsequence.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array. 5 | Formally the function should: 6 | Return true if there exists i, j, k 7 | such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false. 8 | Note: Your algorithm should run in O(n) time complexity and O(1) space complexity. 9 | 10 | Example 1: 11 | Input: [1,2,3,4,5] 12 | Output: true 13 | 14 | Example 2: 15 | Input: [5,4,3,2,1] 16 | Output: false 17 | 18 | */ 19 | 20 | /* 21 | 22 | O(n),O(1) 23 | 24 | */ 25 | 26 | public boolean increasingTriplet(int[] nums) { 27 | int first = Integer.MAX_VALUE, second = Integer.MIN_VALUE; 28 | for (int i = 0; i < nums.length; ++i) { 29 | if (first != Integer.MAX_VALUE && second != Integer.MIN_VALUE && nums[i] > second) return true; 30 | if (nums[i] <= first) first = nums[i]; 31 | else second = nums[i]; 32 | } 33 | return false; 34 | } 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Array/35. Search Insert Position.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a sorted array and a target value, return the index if the target is found. 5 | If not, return the index where it would be if it were inserted in order. 6 | You may assume no duplicates in the array. 7 | 8 | Example 1: 9 | Input: [1,3,5,6], 5 10 | Output: 2 11 | 12 | Example 2: 13 | Input: [1,3,5,6], 2 14 | Output: 1 15 | 16 | Example 3: 17 | Input: [1,3,5,6], 7 18 | Output: 4 19 | 20 | Example 4: 21 | Input: [1,3,5,6], 0 22 | Output: 0 23 | 24 | */ 25 | 26 | /* 27 | 28 | O(logn),O(1) 29 | 30 | */ 31 | 32 | public int searchInsert(int[] nums, int target) { 33 | int l = 0, r = nums.length - 1; 34 | while (l <= r) { 35 | int m = (l + r) / 2; 36 | if (nums[m] == target) return m; 37 | if (nums[m] < target) l = m + 1; 38 | else r = m - 1; 39 | } 40 | return l; 41 | } 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /Array/41. First Missing Positive.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an unsorted integer array, find the smallest missing positive integer. 5 | 6 | Example 1: 7 | Input: [1,2,0] 8 | Output: 3 9 | 10 | Example 2: 11 | Input: [3,4,-1,1] 12 | Output: 2 13 | 14 | Example 3: 15 | Input: [7,8,9,11,12] 16 | Output: 1 17 | 18 | */ 19 | 20 | /* 21 | 22 | O(n),O(1) 23 | 24 | */ 25 | 26 | public int firstMissingPositive(int[] nums) { 27 | int i = 0, n = nums.length; 28 | if (n == 0) 29 | return 1; 30 | while (i < nums.length) { 31 | if (0 <= nums[i] && nums[i] < n && nums[i] != nums[nums[i]]) swap(nums, i, nums[i]); 32 | else i++; 33 | } 34 | int ans = 1; 35 | while (ans < n && nums[ans] == ans) ans++; 36 | return nums[0] == ans ? ans + 1 : ans; 37 | } 38 | 39 | private void swap(int[] nums, int i, int j) { 40 | int tmp = nums[i]; 41 | nums[i] = nums[j]; 42 | nums[j] = tmp; 43 | } 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /Array/442. Find All Duplicates in an Array.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. 5 | Find all the elements that appear twice in this array. 6 | 7 | Example: 8 | Input: 9 | [4,3,2,7,8,2,3,1] 10 | Output: 11 | [2,3] 12 | 13 | */ 14 | 15 | /* 16 | 17 | Solution: use number as index, mark the number of that index negative, whenever we meet a negative number again, it's duplicate 18 | O(n),O(1) 19 | 20 | */ 21 | 22 | public List findDuplicates(int[] nums) { 23 | List ans = new ArrayList<>(); 24 | for (int i = 0; i < nums.length; ++i) { 25 | int idx = Math.abs(nums[i]) - 1; 26 | if (nums[idx] < 0) ans.add(idx + 1); 27 | nums[idx] = -nums[idx]; 28 | } 29 | return ans; 30 | } 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /Array/448. Find All Numbers Disappeared in an Array.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. 5 | Find all the elements of [1, n] inclusive that do not appear in this array. 6 | 7 | Example: 8 | Input: 9 | [4,3,2,7,8,2,3,1] 10 | Output: 11 | [5,6] 12 | 13 | */ 14 | 15 | /* 16 | 17 | O(n),O(1) 18 | 19 | */ 20 | 21 | public List findDisappearedNumbers(int[] nums) { 22 | int n = nums.length; 23 | List ans = new ArrayList<>(); 24 | for (int i = 0; i < n; ++i) { 25 | int idx = Math.abs(nums[i]) - 1; 26 | if (nums[idx] > 0) nums[idx] = -nums[idx]; 27 | } 28 | for (int i = 0; i < n; ++i) { 29 | if (nums[i] > 0) ans.add(i + 1); 30 | } 31 | return ans; 32 | } 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /Array/485. Max Consecutive Ones.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a binary array, find the maximum number of consecutive 1s in this array. 5 | 6 | Example 1: 7 | Input: [1,1,0,1,1,1] 8 | Output: 3 9 | Explanation: The first two digits or the last three digits are consecutive 1s. 10 | The maximum number of consecutive 1s is 3. 11 | 12 | */ 13 | 14 | /* 15 | 16 | O(n),O(1) 17 | 18 | */ 19 | 20 | public int findMaxConsecutiveOnes(int[] nums) { 21 | int ans = 0, cnt = 0; 22 | for (int num : nums) { 23 | if (num == 1) { 24 | cnt++; 25 | } else { 26 | cnt = 0; 27 | } 28 | ans = Math.max(ans, cnt); 29 | } 30 | return ans; 31 | } 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Array/509. Fibonacci Number.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, 5 | such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, 6 | F(0) = 0, F(1) = 1 7 | F(N) = F(N - 1) + F(N - 2), for N > 1. 8 | Given N, calculate F(N). 9 | 10 | Example 1: 11 | Input: 2 12 | Output: 1 13 | Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. 14 | 15 | Example 2: 16 | Input: 3 17 | Output: 2 18 | Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. 19 | 20 | Example 3: 21 | Input: 4 22 | Output: 3 23 | Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. 24 | 25 | */ 26 | 27 | /* 28 | 29 | O(n),O(n) 30 | 31 | */ 32 | 33 | public int fib(int N) { 34 | if (N == 0) { 35 | return 0; 36 | } 37 | if (N == 1) { 38 | return 1; 39 | } 40 | return fib(N - 1) + fib(N - 2); 41 | } 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /Array/53. Maximum Subarray.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum 5 | and return its sum. 6 | 7 | Example: 8 | Input: [-2,1,-3,4,-1,2,1,-5,4], 9 | Output: 6 10 | Explanation: [4,-1,2,1] has the largest sum = 6. 11 | 12 | */ 13 | 14 | /* 15 | 16 | O(n),O(n) 17 | 18 | */ 19 | 20 | public int maxSubArray(int[] nums) { 21 | int n = nums.length; 22 | int[] dp = new int[n]; 23 | dp[0] = nums[0]; 24 | int ans = nums[0]; 25 | for (int i = 1; i < n; ++i) { 26 | dp[i] = dp[i - 1] > 0 ? dp[i - 1] + nums[i] : nums[i]; 27 | ans = Math.max(ans, dp[i]); 28 | } 29 | return ans; 30 | } 31 | 32 | 33 | public int maxSubArray(int[] nums) { 34 | int prev = nums[0], ans = nums[0]; 35 | for (int i = 1; i < nums.length; ++i) { 36 | prev = prev > 0 ? prev + nums[i] : nums[i]; 37 | ans = Math.max(ans, prev); 38 | } 39 | return ans; 40 | } 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /Array/55. Jump Game.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 5 | Each element in the array represents your maximum jump length at that position. 6 | Determine if you are able to reach the last index. 7 | 8 | Example 1: 9 | Input: [2,3,1,1,4] 10 | Output: true 11 | Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. 12 | 13 | Example 2: 14 | Input: [3,2,1,0,4] 15 | Output: false 16 | Explanation: You will always arrive at index 3 no matter what. Its maximum 17 | jump length is 0, which makes it impossible to reach the last index. 18 | 19 | */ 20 | 21 | /* 22 | 23 | O(n),O(1) 24 | 25 | */ 26 | 27 | public boolean canJump(int[] nums) { 28 | int curEnd = 0, curMax = 0; 29 | for (int i = 0; i < nums.length; ++i) { 30 | curMax = Math.max(curMax, i + nums[i]); 31 | if (i > curEnd) return false; 32 | if (i == curEnd) curEnd = curMax; 33 | } 34 | return true; 35 | } 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Array/560. Subarray Sum Equals K.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. 5 | 6 | Example 1: 7 | Input:nums = [1,1,1], k = 2 8 | Output: 2 9 | 10 | */ 11 | 12 | /* 13 | 14 | Solution: use prefix sum, when we have a sum for nums[j] and sum-k for nums[i] which means nums[i...j] is k 15 | O(n),O(n) 16 | 17 | */ 18 | 19 | public int subarraySum(int[] nums, int k) { 20 | int ans = 0, sum = 0; 21 | Map map = new HashMap<>(); 22 | map.put(0, 1); 23 | for (int num : nums) { 24 | sum += num; 25 | if (map.containsKey(sum - k)) { 26 | ans += map.get(sum - k); 27 | } 28 | map.put(sum, map.getOrDefault(sum, 0) + 1); 29 | } 30 | return ans; 31 | } 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Array/561. Array Partition I.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array of 2n integers, your task is to group these integers into n pairs of integer, 5 | say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. 6 | 7 | Example 1: 8 | Input: [1,4,3,2] 9 | Output: 4 10 | Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4). 11 | 12 | */ 13 | 14 | /* 15 | 16 | O(nlogn),O(1) 17 | 18 | */ 19 | 20 | public int arrayPairSum(int[] nums) { 21 | Arrays.sort(nums); 22 | int ans = 0; 23 | for (int i = 0; i < nums.length; i += 2) { 24 | ans += nums[i]; 25 | } 26 | return ans; 27 | } 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /Array/59. Spiral Matrix II.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. 5 | 6 | Example: 7 | Input: 3 8 | Output: 9 | [ 10 | [ 1, 2, 3 ], 11 | [ 8, 9, 4 ], 12 | [ 7, 6, 5 ] 13 | ] 14 | 15 | */ 16 | 17 | /* 18 | 19 | O(n*n),O(1) 20 | 21 | */ 22 | 23 | public int[][] generateMatrix(int n) { 24 | int[][] ans = new int[n][n]; 25 | int minRow = 0, maxRow = n - 1, minCol = 0, maxCol = n - 1, cur = 1; 26 | while (cur <= n * n) { 27 | for (int i = minCol; i <= maxCol; ++i) ans[minRow][i] = cur++; 28 | minRow++; 29 | for (int i = minRow; i <= maxRow; ++i) ans[i][maxCol] = cur++; 30 | maxCol--; 31 | for (int i = maxCol; i >= minCol; --i) ans[maxRow][i] = cur++; 32 | maxRow--; 33 | for (int i = maxRow; i >= minRow; --i) ans[i][minCol] = cur++; 34 | minCol++; 35 | } 36 | return ans; 37 | } 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /Array/611. Valid Triangle Number.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array consists of non-negative integers, your task is to count the number of triplets chosen from the array 5 | that can make triangles if we take them as side lengths of a triangle. 6 | 7 | Example 1: 8 | Input: [2,2,3,4] 9 | Output: 3 10 | Explanation: 11 | Valid combinations are: 12 | 2,3,4 (using the first 2) 13 | 2,3,4 (using the second 2) 14 | 2,2,3 15 | 16 | */ 17 | 18 | /* 19 | 20 | O(nlogn+n^2),O(1) 21 | 22 | */ 23 | 24 | public int triangleNumber(int[] nums) { 25 | int ans = 0; 26 | Arrays.sort(nums); 27 | for (int i = 2; i < nums.length; ++i) { 28 | int l = 0, r = i - 1; 29 | while (l < r) { 30 | if (nums[l] + nums[r] > nums[i]) { 31 | ans += (r - l); 32 | r--; 33 | } else { 34 | l++; 35 | } 36 | } 37 | } 38 | return ans; 39 | } 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Array/64. Minimum Path Sum.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right 5 | which minimizes the sum of all numbers along its path. 6 | Note: You can only move either down or right at any point in time. 7 | 8 | Example: 9 | Input: 10 | [ 11 | [1,3,1], 12 | [1,5,1], 13 | [4,2,1] 14 | ] 15 | Output: 7 16 | Explanation: Because the path 1→3→1→1→1 minimizes the sum. 17 | 18 | */ 19 | 20 | /* 21 | 22 | O(nm),O(nm) 23 | 24 | */ 25 | 26 | public int minPathSum(int[][] grid) { 27 | int n = grid.length, m = grid[0].length; 28 | int[][] dp = new int[n][m]; 29 | dp[0][0] = grid[0][0]; 30 | for (int i = 1; i < n; ++i) dp[i][0] = dp[i - 1][0] + grid[i][0]; 31 | for (int j = 1; j < m; ++j) dp[0][j] = dp[0][j - 1] + grid[0][j]; 32 | for (int i = 1; i < n; ++i) { 33 | for (int j = 1; j < m; ++j) 34 | dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]; 35 | } 36 | return dp[n - 1][m - 1]; 37 | } 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /Array/643. Maximum Average Subarray I.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. 5 | And you need to output the maximum average value. 6 | 7 | Example 1: 8 | Input: [1,12,-5,-6,50,3], k = 4 9 | Output: 12.75 10 | Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75 11 | 12 | */ 13 | 14 | /* 15 | 16 | O(n),O(1) 17 | 18 | */ 19 | 20 | public double findMaxAverage(int[] nums, int k) { 21 | int n = nums.length; 22 | double ans = 0, sum = 0; 23 | for (int i = 0; i < k; ++i) { 24 | sum += nums[i]; 25 | } 26 | ans = sum / k; 27 | for (int i = 0, j = k; j < n; ++i, ++j) { 28 | sum += nums[j]; 29 | sum -= nums[i]; 30 | ans = Math.max(ans, sum / k); 31 | } 32 | return ans; 33 | } 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /Array/66. Plus One.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a non-empty array of digits representing a non-negative integer, plus one to the integer. 5 | The digits are stored such that the most significant digit is at the head of the list, 6 | and each element in the array contain a single digit. 7 | You may assume the integer does not contain any leading zero, except the number 0 itself. 8 | 9 | Example 1: 10 | Input: [1,2,3] 11 | Output: [1,2,4] 12 | Explanation: The array represents the integer 123. 13 | 14 | Example 2: 15 | Input: [4,3,2,1] 16 | Output: [4,3,2,2] 17 | Explanation: The array represents the integer 4321. 18 | 19 | */ 20 | 21 | /* 22 | 23 | O(n),O(n) 24 | 25 | */ 26 | 27 | public int[] plusOne(int[] digits) { 28 | int n = digits.length; 29 | for (int i = n - 1; i >= 0; --i) { 30 | if (digits[i] != 9) { 31 | digits[i]++; 32 | return digits; 33 | } else digits[i] = 0; 34 | } 35 | int[] ans = new int[n + 1]; 36 | ans[0] = 1; 37 | return ans; 38 | } 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /Array/665. Non-decreasing Array.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element. 5 | We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n). 6 | 7 | Example 1: 8 | Input: [4,2,3] 9 | Output: True 10 | Explanation: You could modify the first 4 to 1 to get a non-decreasing array. 11 | 12 | Example 2: 13 | Input: [4,2,1] 14 | Output: False 15 | Explanation: You can't get a non-decreasing array by modify at most one element. 16 | 17 | */ 18 | 19 | /* 20 | 21 | O(n),O(1) 22 | 23 | */ 24 | 25 | public boolean checkPossibility(int[] nums) { 26 | int n = nums.length, cnt = 0; 27 | for (int i = 0; i < n - 1; ++i) { 28 | if (nums[i] > nums[i + 1]) { 29 | cnt++; 30 | if (i > 0 && nums[i - 1] > nums[i + 1]) { 31 | nums[i + 1] = nums[i]; 32 | } 33 | } 34 | if (cnt == 2) { 35 | return false; 36 | } 37 | } 38 | return true; 39 | } 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Array/674. Longest Continuous Increasing Subsequence.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray). 5 | 6 | Example 1: 7 | Input: [1,3,5,4,7] 8 | Output: 3 9 | Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3. 10 | Even though [1,3,5,7] is also an increasing subsequence, it's not a continuous one where 5 and 7 are separated by 4. 11 | 12 | Example 2: 13 | Input: [2,2,2,2,2] 14 | Output: 1 15 | Explanation: The longest continuous increasing subsequence is [2], its length is 1. 16 | 17 | */ 18 | 19 | /* 20 | 21 | O(n),O(1) 22 | 23 | */ 24 | 25 | public int findLengthOfLCIS(int[] nums) { 26 | int n = nums.length, ans = 0, cnt = 1; 27 | if (n == 1) { 28 | return 1; 29 | } 30 | for (int i = 1; i < n; ++i) { 31 | if (nums[i] > nums[i - 1]) { 32 | cnt++; 33 | } else { 34 | cnt = 1; 35 | } 36 | ans = Math.max(ans, cnt); 37 | } 38 | return ans; 39 | } 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Array/88. Merge Sorted Array.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 5 | 6 | Note: 7 | The number of elements initialized in nums1 and nums2 are m and n respectively. 8 | You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. 9 | 10 | Example: 11 | Input: 12 | nums1 = [1,2,3,0,0,0], m = 3 13 | nums2 = [2,5,6], n = 3 14 | Output: [1,2,2,3,5,6] 15 | 16 | */ 17 | 18 | /* 19 | 20 | O(n+m),O(1) 21 | 22 | */ 23 | 24 | public void merge(int[] nums1, int m, int[] nums2, int n) { 25 | int i = m - 1, j = n - 1, k = m + n - 1; 26 | while (i >= 0 && j >= 0) { 27 | if (nums1[i] > nums2[j]) nums1[k--] = nums1[i--]; 28 | else nums1[k--] = nums2[j--]; 29 | } 30 | while (j >= 0) nums1[k--] = nums2[j--]; 31 | } 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Array/90. Subsets II.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set). 5 | Note: The solution set must not contain duplicate subsets. 6 | 7 | Example: 8 | Input: [1,2,2] 9 | Output: 10 | [ 11 | [2], 12 | [1], 13 | [1,2,2], 14 | [2,2], 15 | [1,2], 16 | [] 17 | ] 18 | 19 | */ 20 | 21 | /* 22 | 23 | O(2^n),O(n) 24 | 25 | */ 26 | 27 | public List> subsetsWithDup(int[] nums) { 28 | List> ans = new ArrayList<>(); 29 | Arrays.sort(nums); 30 | dfs(ans, new ArrayList<>(), nums, 0); 31 | return ans; 32 | } 33 | 34 | private void dfs(List> ans, List tmp, int[] nums, int idx) { 35 | ans.add(new ArrayList<>(tmp)); 36 | for (int i = idx; i < nums.length; ++i) { 37 | if (i > idx && nums[i] == nums[i - 1]) continue; 38 | tmp.add(nums[i]); 39 | dfs(ans, tmp, nums, i + 1); 40 | tmp.remove(tmp.size() - 1); 41 | } 42 | } 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /Array/941. Valid Mountain Array.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array A of integers, return true if and only if it is a valid mountain array. 5 | Recall that A is a mountain array if and only if: 6 | A.length >= 3 7 | There exists some i with 0 < i < A.length - 1 such that: 8 | A[0] < A[1] < ... A[i-1] < A[i] 9 | A[i] > A[i+1] > ... > A[B.length - 1] 10 | 11 | Example 1: 12 | Input: [2,1] 13 | Output: false 14 | 15 | Example 2: 16 | Input: [3,5,5] 17 | Output: false 18 | 19 | Example 3: 20 | Input: [0,3,2,1] 21 | Output: true 22 | 23 | */ 24 | 25 | /* 26 | 27 | O(n),O(1) 28 | 29 | */ 30 | 31 | public boolean validMountainArray(int[] A) { 32 | int n = A.length; 33 | if (n <= 2 || A[0] >= A[1]) return false; 34 | boolean up = true; 35 | for (int i = 2; i < n; ++i) { 36 | if (A[i] < A[i - 1]) up = false; 37 | else if (A[i] == A[i - 1] || !up) return false; 38 | } 39 | return !up; 40 | } 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /Array/945. Minimum Increment to Make Array Unique.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array of integers A, a move consists of choosing any A[i], and incrementing it by 1. 5 | Return the least number of moves to make every value in A unique. 6 | 7 | Example 1: 8 | Input: [1,2,2] 9 | Output: 1 10 | Explanation: After 1 move, the array could be [1, 2, 3]. 11 | 12 | Example 2: 13 | Input: [3,2,1,2,1,7] 14 | Output: 6 15 | Explanation: After 6 moves, the array could be [3, 4, 1, 2, 5, 7]. 16 | It can be shown with 5 or less moves that it is impossible for the array to have all unique values. 17 | 18 | */ 19 | 20 | /* 21 | 22 | O(nlogn),O(1) 23 | 24 | */ 25 | 26 | public int minIncrementForUnique(int[] A) { 27 | Arrays.sort(A); 28 | int ans = 0, cur = 0; 29 | for (int num : A) { 30 | ans += Math.max(cur - num, 0); 31 | cur = Math.max(cur, num) + 1; 32 | } 33 | return ans; 34 | } 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Array/961. N-Repeated Element in Size 2N Array.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times. 5 | Return the element repeated N times. 6 | 7 | Example 1: 8 | Input: [1,2,3,3] 9 | Output: 3 10 | 11 | Example 2: 12 | Input: [2,1,2,5,3,2] 13 | Output: 2 14 | 15 | Example 3: 16 | Input: [5,1,5,2,5,3,5,4] 17 | Output: 5 18 | 19 | */ 20 | 21 | /* 22 | 23 | O(n),O(1) 24 | 25 | */ 26 | 27 | public int repeatedNTimes(int[] A) { 28 | for (int i = 2; i < A.length; ++i) { 29 | if (A[i] == A[i - 1] || A[i] == A[i - 2]) { 30 | return A[i]; 31 | } 32 | } 33 | return A[0]; 34 | } 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Array/974. Subarray Sums Divisible by K.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by K. 5 | 6 | Example 1: 7 | Input: A = [4,5,0,-2,-3,1], K = 5 8 | Output: 7 9 | Explanation: There are 7 subarrays with a sum divisible by K = 5: 10 | [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3] 11 | 12 | */ 13 | 14 | /* 15 | 16 | O(n),O(n) 17 | 18 | */ 19 | 20 | public int subarraysDivByK(int[] A, int K) { 21 | Map map = new HashMap<>(); 22 | map.put(0, 1); 23 | int ans = 0, sum = 0; 24 | for (int a : A) { 25 | sum = (sum + a) % K; 26 | if (sum < 0) { 27 | sum += K; 28 | } 29 | ans += map.getOrDefault(sum, 0); 30 | map.put(sum, map.getOrDefault(sum, 0) + 1); 31 | } 32 | return ans; 33 | } 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /Array/977. Squares of a Sorted Array.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array of integers A sorted in non-decreasing order, 5 | return an array of the squares of each number, also in sorted non-decreasing order. 6 | 7 | Example 1: 8 | Input: [-4,-1,0,3,10] 9 | Output: [0,1,9,16,100] 10 | 11 | Example 2: 12 | Input: [-7,-3,2,3,11] 13 | Output: [4,9,9,49,121] 14 | 15 | */ 16 | 17 | /* 18 | 19 | O(n),O(n) 20 | 21 | */ 22 | 23 | public int[] sortedSquares(int[] A) { 24 | int n = A.length, i = 0, j = n - 1; 25 | int[] ans = new int[n]; 26 | for (int k = n - 1; k >= 0; --k) { 27 | if (Math.abs(A[i]) < Math.abs(A[j])) { 28 | ans[k] = A[j] * A[j]; 29 | j--; 30 | } else { 31 | ans[k] = A[i] * A[i]; 32 | i++; 33 | } 34 | } 35 | return ans; 36 | } 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /Backtracking/1079. Letter Tile Possibilities.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | You have a set of tiles, where each tile has one letter tiles[i] printed on it. 5 | Return the number of possible non-empty sequences of letters you can make. 6 | 7 | Example 1: 8 | Input: "AAB" 9 | Output: 8 10 | Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". 11 | 12 | Example 2: 13 | Input: "AAABBC" 14 | Output: 188 15 | 16 | */ 17 | 18 | /* 19 | 20 | O(26^n),O(n) 21 | 22 | */ 23 | 24 | public int numTilePossibilities(String tiles) { 25 | int[] buckets = new int[26]; 26 | for (char c : tiles.toCharArray()) { 27 | buckets[c - 'A']++; 28 | } 29 | return dfs(buckets); 30 | } 31 | 32 | private int dfs(int[] buckets) { 33 | int ans = 0; 34 | for (int i = 0; i < 26; ++i) { 35 | if (buckets[i] != 0) { 36 | buckets[i]--; 37 | ans++; 38 | ans += dfs(buckets); 39 | buckets[i]++; 40 | } 41 | } 42 | return ans; 43 | } 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /Backtracking/77. Combinations.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. 5 | 6 | Example: 7 | Input: n = 4, k = 2 8 | Output: 9 | [ 10 | [2,4], 11 | [3,4], 12 | [2,3], 13 | [1,2], 14 | [1,3], 15 | [1,4], 16 | ] 17 | 18 | */ 19 | 20 | /* 21 | 22 | O(n^k),O(k) 23 | 24 | */ 25 | 26 | public List> combine(int n, int k) { 27 | List> ans = new ArrayList<>(); 28 | dfs(ans, new ArrayList<>(), n, k, 1); 29 | return ans; 30 | } 31 | 32 | private void dfs(List> ans, List tmp, int n, int k, int idx) { 33 | if (tmp.size() == k) { 34 | ans.add(new ArrayList<>(tmp)); 35 | return; 36 | } 37 | for (int i = idx; i <= n; ++i) { 38 | tmp.add(i); 39 | dfs(ans, tmp, n, k, i + 1); 40 | tmp.remove(tmp.size() - 1); 41 | } 42 | } 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /Backtracking/80. Subsets II.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set). 5 | Note: The solution set must not contain duplicate subsets. 6 | 7 | Example: 8 | Input: [1,2,2] 9 | Output: 10 | [ 11 | [2], 12 | [1], 13 | [1,2,2], 14 | [2,2], 15 | [1,2], 16 | [] 17 | ] 18 | 19 | */ 20 | 21 | /* 22 | 23 | O(2^n),O(n) 24 | 25 | */ 26 | 27 | public List> subsetsWithDup(int[] nums) { 28 | List> ans = new ArrayList<>(); 29 | Arrays.sort(nums); 30 | dfs(ans, new ArrayList<>(), nums, 0); 31 | return ans; 32 | } 33 | 34 | private void dfs(List> ans, List tmp, int[] nums, int idx) { 35 | ans.add(new ArrayList<>(tmp)); 36 | for (int i = idx; i < nums.length; ++i) { 37 | if (i > idx && nums[i] == nums[i - 1]) continue; 38 | tmp.add(nums[i]); 39 | dfs(ans, tmp, nums, i + 1); 40 | tmp.remove(tmp.size() - 1); 41 | } 42 | } 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /Bash/193. Valid Phone Numbers.sh: -------------------------------------------------------------------------------- 1 | 2 | : ' 3 | 4 | Given a text file file.txt that contains list of phone numbers (one per line), 5 | write a one liner bash script to print all valid phone numbers. 6 | 7 | You may assume that a valid phone number must appear in one of the following two formats: 8 | (xxx) xxx-xxxx or xxx-xxx-xxxx. (x means a digit) 9 | You may also assume each line in the text file must not contain leading or trailing white spaces. 10 | 11 | Example: 12 | Assume that file.txt has the following content: 13 | 987-123-4567 14 | 123 456 7890 15 | (123) 456-7890 16 | Your script should output the following valid phone numbers: 17 | 987-123-4567 18 | (123) 456-7890 19 | 20 | ' 21 | 22 | awk '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/' file.txt 23 | 24 | 25 | -------------------------------------------------------------------------------- /Bash/194. Transpose File.sh: -------------------------------------------------------------------------------- 1 | 2 | : ' 3 | 4 | Given a text file file.txt, transpose its content. 5 | You may assume that each row has the same number of columns and each field is separated by the ' ' character. 6 | 7 | Example: 8 | If file.txt has the following content: 9 | name age 10 | alice 21 11 | ryan 30 12 | Output the following: 13 | name alice ryan 14 | age 21 30 15 | 16 | ' 17 | 18 | : ' 19 | 20 | NF: a variable indicating the number of fields (i.e. number of "columns") on an input line 21 | NR: a variable indicating the number of records (i.e. current line number) that's accumulated across multiple files read 22 | $i: the i-th field of the input line 23 | 24 | ' 25 | 26 | awk ' 27 | { 28 | for (i = 1; i <= NF; i++) { 29 | if(NR == 1) { 30 | s[i] = $i; 31 | } else { 32 | s[i] = s[i] " " $i; 33 | } 34 | } 35 | } 36 | END { 37 | for (i = 1; s[i] != ""; i++) { 38 | print s[i]; 39 | } 40 | }' file.txt 41 | 42 | 43 | -------------------------------------------------------------------------------- /Bash/195. Tenth Line.sh: -------------------------------------------------------------------------------- 1 | 2 | : ' 3 | 4 | Given a text file file.txt, print just the 10th line of the file. 5 | 6 | Example: 7 | Assume that file.txt has the following content: 8 | Line 1 9 | Line 2 10 | Line 3 11 | Line 4 12 | Line 5 13 | Line 6 14 | Line 7 15 | Line 8 16 | Line 9 17 | Line 10 18 | Your script should output the tenth line, which is: 19 | Line 10 20 | 21 | ' 22 | 23 | awk 'NR==10{print;exit}' file.txt 24 | 25 | 26 | -------------------------------------------------------------------------------- /Binary Search/153. Find Minimum in Rotated Sorted Array.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 5 | (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). 6 | Find the minimum element. 7 | You may assume no duplicate exists in the array. 8 | 9 | Example 1: 10 | Input: [3,4,5,1,2] 11 | Output: 1 12 | 13 | Example 2: 14 | Input: [4,5,6,7,0,1,2] 15 | Output: 0 16 | 17 | */ 18 | 19 | /* 20 | 21 | O(logn),O(1) 22 | 23 | */ 24 | 25 | public int findMin(int[] nums) { 26 | int l = 0, r = nums.length - 1; 27 | while (l < r) { 28 | int mid = (l + r) / 2; 29 | if (nums[r] < nums[mid]) l = mid + 1; 30 | else r = mid; 31 | } 32 | return nums[l]; 33 | } 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /Binary Search/154. Find Minimum in Rotated Sorted Array II.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 5 | (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). 6 | Find the minimum element. 7 | The array may contain duplicates. 8 | 9 | Example 1: 10 | Input: [1,3,5] 11 | Output: 1 12 | 13 | Example 2: 14 | Input: [2,2,2,0,1] 15 | Output: 0 16 | 17 | */ 18 | 19 | /* 20 | 21 | O(logn),O(1) 22 | 23 | */ 24 | 25 | public int findMin(int[] nums) { 26 | int l = 0, r = nums.length - 1; 27 | while (l < r) { 28 | int mid = (l + r) / 2; 29 | if (nums[mid] > nums[r]) l = mid + 1; 30 | else if (nums[mid] < nums[r]) r = mid; 31 | else r--; 32 | } 33 | return nums[l]; 34 | } 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /Binary Search/240. Search a 2D Matrix II.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: 5 | Integers in each row are sorted in ascending from left to right. 6 | Integers in each column are sorted in ascending from top to bottom. 7 | 8 | Example: 9 | Consider the following matrix: 10 | [ 11 | [1, 4, 7, 11, 15], 12 | [2, 5, 8, 12, 19], 13 | [3, 6, 9, 16, 22], 14 | [10, 13, 14, 17, 24], 15 | [18, 21, 23, 26, 30] 16 | ] 17 | Given target = 5, return true. 18 | Given target = 20, return false. 19 | 20 | */ 21 | 22 | /* 23 | 24 | O(n+m),O(1) 25 | 26 | */ 27 | 28 | public boolean searchMatrix(int[][] matrix, int target) { 29 | if (matrix.length == 0) return false; 30 | int n = matrix.length, m = matrix[0].length; 31 | int i = 0, j = m - 1; 32 | while (i < n && j >= 0) { 33 | if (matrix[i][j] == target) return true; 34 | if (matrix[i][j] > target) --j; 35 | else ++i; 36 | } 37 | return false; 38 | } 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /Binary Search/35. Search Insert Position.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a sorted array and a target value, return the index if the target is found. 5 | If not, return the index where it would be if it were inserted in order. 6 | You may assume no duplicates in the array. 7 | 8 | Example 1: 9 | Input: [1,3,5,6], 5 10 | Output: 2 11 | 12 | Example 2: 13 | Input: [1,3,5,6], 2 14 | Output: 1 15 | 16 | Example 3: 17 | Input: [1,3,5,6], 7 18 | Output: 4 19 | 20 | Example 4: 21 | Input: [1,3,5,6], 0 22 | Output: 0 23 | 24 | */ 25 | 26 | /* 27 | 28 | O(logn),O(1) 29 | 30 | */ 31 | 32 | public int searchInsert(int[] nums, int target) { 33 | int l = 0, r = nums.length - 1; 34 | while (l <= r) { 35 | int m = (l + r) / 2; 36 | if (nums[m] == target) return m; 37 | if (nums[m] < target) l = m + 1; 38 | else r = m - 1; 39 | } 40 | return l; 41 | } 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /Binary Search/367. Valid Perfect Square.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a positive integer num, write a function which returns True if num is a perfect square else False. 5 | Note: Do not use any built-in library function such as sqrt. 6 | 7 | Example 1: 8 | Input: 16 9 | Output: true 10 | 11 | Example 2: 12 | Input: 14 13 | Output: false 14 | 15 | */ 16 | 17 | /* 18 | 19 | O(logn),O(1) 20 | 21 | */ 22 | 23 | public boolean isPerfectSquare(int num) { 24 | if (num <= 0) return false; 25 | int l = 1, r = num; 26 | while (l <= r) { 27 | int mid = (l + r) / 2; 28 | if (mid == num / mid) return num % mid == 0; 29 | else if (mid < num / mid) l = mid + 1; 30 | else r = mid - 1; 31 | } 32 | return false; 33 | } 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /Binary Search/374. Guess Number Higher or Lower.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | We are playing the Guess Game. The game is as follows: 5 | I pick a number from 1 to n. You have to guess which number I picked. 6 | Every time you guess wrong, I'll tell you whether the number is higher or lower. 7 | You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0): 8 | -1 : My number is lower 9 | 1 : My number is higher 10 | 0 : Congrats! You got it! 11 | 12 | Example : 13 | Input: n = 10, pick = 6 14 | Output: 6 15 | 16 | */ 17 | 18 | /* 19 | 20 | O(logn),O(1) 21 | 22 | */ 23 | 24 | public class Solution extends GuessGame { 25 | public int guessNumber(int n) { 26 | int l = 1, r = n; 27 | while (l <= r) { 28 | int mid = l + (r - l) / 2; 29 | if (guess(mid) == 0) return mid; 30 | else if (guess(mid) == 1) l = mid + 1; 31 | else r = mid - 1; 32 | } 33 | return 0; 34 | } 35 | } 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /Binary Search/69. Sqrt(x).java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Implement int sqrt(int x). 5 | Compute and return the square root of x, where x is guaranteed to be a non-negative integer. 6 | Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. 7 | 8 | Example 1: 9 | Input: 4 10 | Output: 2 11 | 12 | Example 2: 13 | Input: 8 14 | Output: 2 15 | Explanation: The square root of 8 is 2.82842..., and since 16 | the decimal part is truncated, 2 is returned. 17 | 18 | */ 19 | 20 | /* 21 | 22 | O(logn),O(1) 23 | 24 | */ 25 | 26 | public int mySqrt(int x) { 27 | int l = 1, r = x; 28 | while (l <= r) { 29 | int mid = (l + r) / 2; 30 | if (x / mid == mid) return mid; 31 | if (x / mid > mid) l = mid + 1; 32 | else r = mid - 1; 33 | } 34 | return r; 35 | } 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Binary Search/704. Binary Search.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a sorted (in ascending order) integer array nums of n elements and a target value, 5 | write a function to search target in nums. If target exists, then return its index, otherwise return -1. 6 | 7 | Example 1: 8 | Input: nums = [-1,0,3,5,9,12], target = 9 9 | Output: 4 10 | Explanation: 9 exists in nums and its index is 4 11 | 12 | Example 2: 13 | Input: nums = [-1,0,3,5,9,12], target = 2 14 | Output: -1 15 | Explanation: 2 does not exist in nums so return -1 16 | 17 | */ 18 | 19 | /* 20 | 21 | O(logn),O(1) 22 | 23 | */ 24 | 25 | public int search(int[] nums, int target) { 26 | int l = 0, r = nums.length - 1; 27 | while (l < r) { 28 | int mid = (l + r) / 2; 29 | if (nums[mid] == target) { 30 | return mid; 31 | } else if (nums[mid] < target) { 32 | l = mid + 1; 33 | } else { 34 | r = mid - 1; 35 | } 36 | } 37 | return nums[l] == target ? l : -1; 38 | } 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /Bit Manipulation/136. Single Number.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a non-empty array of integers, every element appears twice except for one. Find that single one. 5 | 6 | Note: 7 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 8 | 9 | Example 1: 10 | Input: [2,2,1] 11 | Output: 1 12 | 13 | Example 2: 14 | Input: [4,1,2,1,2] 15 | Output: 4 16 | 17 | */ 18 | 19 | /* 20 | 21 | O(n),O(1) 22 | 23 | */ 24 | 25 | public int singleNumber(int[] nums) { 26 | int ans = 0; 27 | for (int num : nums) ans ^= num; 28 | return ans; 29 | } 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /Bit Manipulation/137. Single Number II.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. 5 | Find that single one. 6 | 7 | Note: 8 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 9 | 10 | Example 1: 11 | Input: [2,2,3,2] 12 | Output: 3 13 | 14 | Example 2: 15 | Input: [0,1,0,1,0,1,99] 16 | Output: 99 17 | 18 | */ 19 | 20 | /* 21 | 22 | Solution: first to track the number appeared once, second to track the number appeared twice 23 | first^num means first is the number at its once, &(~second) means the number only equal to first when second is 0 24 | O(n),O(1) 25 | 26 | */ 27 | 28 | public int singleNumber(int[] nums) { 29 | int first = 0, second = 0; 30 | for (int num : nums) { 31 | first = (first ^ num) & (~second); 32 | second = (second ^ num) & (~first); 33 | } 34 | return first; 35 | } 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Bit Manipulation/190. Reverse Bits.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Reverse bits of a given 32 bits unsigned integer. 5 | 6 | Example 1: 7 | Input: 00000010100101000001111010011100 8 | Output: 00111001011110000010100101000000 9 | Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, 10 | so return 964176192 which its binary representation is 00111001011110000010100101000000. 11 | 12 | Example 2: 13 | Input: 11111111111111111111111111111101 14 | Output: 10111111111111111111111111111111 15 | Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, 16 | so return 3221225471 which its binary representation is 10101111110010110010011101101001. 17 | 18 | */ 19 | 20 | /* 21 | 22 | O(32),O(1) 23 | 24 | */ 25 | 26 | public int reverseBits(int n) { 27 | int ans = 0; 28 | for (int i = 0; i < 32; ++i) { 29 | ans <<= 1; 30 | ans |= n & 1; 31 | n >>= 1; 32 | } 33 | return ans; 34 | } 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Bit Manipulation/201. Bitwise AND of Numbers Range.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. 5 | 6 | Example 1: 7 | Input: [5,7] 8 | Output: 4 9 | 10 | Example 2: 11 | Input: [0,1] 12 | Output: 0 13 | 14 | */ 15 | 16 | /* 17 | 18 | Solution: if m!=n, the last bit AND always has 0&1=0 19 | m>>1 and n>>1 to check the next bit until m=n 20 | O(32),O(1) 21 | 22 | */ 23 | 24 | public int rangeBitwiseAnd(int m, int n) { 25 | int i = 0; 26 | while (m != n) { 27 | m >>= 1; 28 | n >>= 1; 29 | i++; 30 | } 31 | return m << i; 32 | } 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /Bit Manipulation/231. Power of Two.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an integer, write a function to determine if it is a power of two. 5 | 6 | Example 1: 7 | Input: 1 8 | Output: true 9 | Explanation: 20 = 1 10 | 11 | Example 2: 12 | Input: 16 13 | Output: true 14 | Explanation: 24 = 16 15 | 16 | Example 3: 17 | Input: 218 18 | Output: false 19 | 20 | */ 21 | 22 | /* 23 | 24 | O(n),O(1) 25 | 26 | */ 27 | 28 | public boolean isPowerOfTwo(int n) { 29 | if (n <= 0) return false; 30 | while (n % 2 == 0) n /= 2; 31 | return n == 1; 32 | } 33 | 34 | 35 | /* 36 | 37 | Solution 2: n&(n-1) to remove the last set bit, and if it's power of two, there is only one '1' bit, so the remain should be 0 38 | O(1),O(1) 39 | 40 | */ 41 | 42 | public boolean isPowerOfTwo(int n) { 43 | if (n <= 0) return false; 44 | return (n & (n - 1)) == 0; 45 | } 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /Bit Manipulation/260. Single Number III.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. 5 | Find the two elements that appear only once. 6 | 7 | Example: 8 | Input: [1,2,1,3,2,5] 9 | Output: [3,5] 10 | 11 | */ 12 | 13 | /* 14 | 15 | Solution: 1. diff^=num to get the XOR two single numbers 16 | 2. diff&=(~(diff-1)) to get the last set bit, for 010100, (diff-1) gets 010011, ~(diff-1) gets 101100, & gets 000100 17 | 3. by diff, group all the numbers into two groups, the two single numbers are in each group 18 | O(n),O(1) 19 | 20 | */ 21 | 22 | public int[] singleNumber(int[] nums) { 23 | int[] ans = new int[2]; 24 | int diff = 0; 25 | for (int num : nums) diff ^= num; 26 | diff &= ~(diff - 1); 27 | for (int num : nums) { 28 | if ((num & diff) == 0) ans[0] ^= num; 29 | else ans[1] ^= num; 30 | } 31 | return ans; 32 | } 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /Bit Manipulation/268. Missing Number.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. 5 | 6 | Example 1: 7 | Input: [3,0,1] 8 | Output: 2 9 | 10 | Example 2: 11 | Input: [9,6,4,2,3,5,7,0,1] 12 | Output: 8 13 | 14 | */ 15 | 16 | /* 17 | 18 | Solution: since num is 0,1,2,...,n, num^index=0 if this num is not missing 19 | O(n),O(1) 20 | 21 | */ 22 | 23 | public int missingNumber(int[] nums) { 24 | int ans = nums.length; 25 | for (int i = 0; i < nums.length; ++i) ans = ans ^ i ^ nums[i]; 26 | return ans; 27 | } 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /Bit Manipulation/342. Power of Four.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an integer (signed 32 bits), write a function to check whether it is a power of 4. 5 | 6 | Example 1: 7 | Input: 16 8 | Output: true 9 | 10 | Example 2: 11 | Input: 5 12 | Output: false 13 | 14 | */ 15 | 16 | /* 17 | 18 | Solution: 4^n must be larger than 0, it's also 2^2n which means there is only one '1' bit, and the bit should be in odd place 19 | O(1),O(1) 20 | 21 | */ 22 | 23 | public boolean isPowerOfFour(int num) { 24 | return num > 0 && (num & (num - 1)) == 0 && (num & 0x55555555) != 0; 25 | } 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /Bit Manipulation/371. Sum of Two Integers.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. 5 | 6 | Example 1: 7 | Input: a = 1, b = 2 8 | Output: 3 9 | 10 | Example 2: 11 | Input: a = -2, b = 3 12 | Output: 1 13 | 14 | */ 15 | 16 | /* 17 | 18 | Solution: a^b to sum up the different bits, (a&b)<<1 to get the bits which are carry bits and add them together recursively 19 | O(1),O(1) 20 | 21 | */ 22 | 23 | public int getSum(int a, int b) { 24 | return b == 0 ? a : getSum(a ^ b, (a & b) << 1); 25 | } 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /Bit Manipulation/389. Find the Difference.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given two strings s and t which consist of only lowercase letters. 5 | String t is generated by random shuffling string s and then add one more letter at a random position. 6 | Find the letter that was added in t. 7 | 8 | Example: 9 | Input: 10 | s = "abcd" 11 | t = "abcde" 12 | Output: 13 | e 14 | Explanation: 15 | 'e' is the letter that was added. 16 | 17 | */ 18 | 19 | /* 20 | 21 | O(n),O(1) 22 | 23 | */ 24 | 25 | public char findTheDifference(String s, String t) { 26 | char ans = 0; 27 | for (int i = 0; i < s.length(); ++i) ans ^= (s.charAt(i) ^ t.charAt(i)); 28 | ans ^= t.charAt(t.length() - 1); 29 | return ans; 30 | } 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /Bit Manipulation/461. Hamming Distance.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 5 | Given two integers x and y, calculate the Hamming distance. 6 | Note: 7 | 0 ≤ x, y < 231. 8 | 9 | Example: 10 | Input: x = 1, y = 4 11 | Output: 2 12 | Explanation: 13 | 1 (0 0 0 1) 14 | 4 (0 1 0 0) 15 | ↑ ↑ 16 | The above arrows point to positions where the corresponding bits are different. 17 | 18 | */ 19 | 20 | /* 21 | 22 | O(1),O(1) 23 | 24 | */ 25 | 26 | public int hammingDistance(int x, int y) { 27 | int xor = x ^ y, ans = 0; 28 | while (xor > 0) { 29 | ans++; 30 | xor &= (xor - 1); 31 | } 32 | return ans; 33 | } 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /Bit Manipulation/477. Total Hamming Distance.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 5 | Now your job is to find the total Hamming distance between all pairs of the given numbers. 6 | 7 | Example: 8 | Input: 4, 14, 2 9 | Output: 6 10 | Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just 11 | showing the four bits relevant in this case). So the answer will be: 12 | HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. 13 | 14 | */ 15 | 16 | /* 17 | 18 | O(31n),O(1) 19 | 20 | */ 21 | 22 | public int totalHammingDistance(int[] nums) { 23 | int ans = 0, n = nums.length; 24 | for (int i = 0; i < 31; ++i) { 25 | int cnt = 0; 26 | for (int j = 0; j < n; ++j) { 27 | cnt += nums[j] & 1; 28 | nums[j] >>= 1; 29 | } 30 | ans += cnt * (n - cnt); 31 | } 32 | return ans; 33 | } 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /Bit Manipulation/693. Binary Number with Alternating Bits.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a positive integer, check whether it has alternating bits: 5 | namely, if two adjacent bits will always have different values. 6 | 7 | Example 1: 8 | Input: 5 9 | Output: True 10 | Explanation: 11 | The binary representation of 5 is: 101 12 | 13 | Example 2: 14 | Input: 7 15 | Output: False 16 | Explanation: 17 | The binary representation of 7 is: 111. 18 | 19 | Example 3: 20 | Input: 11 21 | Output: False 22 | Explanation: 23 | The binary representation of 11 is: 1011. 24 | 25 | Example 4: 26 | Input: 10 27 | Output: True 28 | Explanation: 29 | The binary representation of 10 is: 1010. 30 | 31 | */ 32 | 33 | /* 34 | 35 | O(logn),O(1) 36 | 37 | */ 38 | 39 | public boolean hasAlternatingBits(int n) { 40 | int cur = n & 1; 41 | while (n > 0) { 42 | n >>= 1; 43 | if ((n & 1) == cur) { 44 | return false; 45 | } 46 | cur = n & 1; 47 | } 48 | return true; 49 | } 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /Brainteaser/292. Nim Game.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | You are playing the following Nim Game with your friend: 5 | There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. 6 | The one who removes the last stone will be the winner. You will take the first turn to remove the stones. 7 | Both of you are very clever and have optimal strategies for the game. 8 | Write a function to determine whether you can win the game given the number of stones in the heap. 9 | 10 | Example: 11 | Input: 4 12 | Output: false 13 | Explanation: If there are 4 stones in the heap, then you will never win the game; 14 | No matter 1, 2, or 3 stones you remove, the last stone will always be 15 | removed by your friend. 16 | 17 | */ 18 | 19 | /* 20 | 21 | O(1),O(1) 22 | 23 | */ 24 | 25 | public boolean canWinNim(int n) { 26 | return n % 4 != 0; 27 | } 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /Depth-first Search/104. Maximum Depth of Binary Tree.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a binary tree, find its maximum depth. 5 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 6 | Note: A leaf is a node with no children. 7 | 8 | Example: 9 | Given binary tree [3,9,20,null,null,15,7], 10 | 11 | 3 12 | / \ 13 | 9 20 14 | / \ 15 | 15 7 16 | return its depth = 3. 17 | 18 | */ 19 | 20 | /* 21 | 22 | O(n),O(logn) 23 | 24 | */ 25 | 26 | public int maxDepth(TreeNode root) { 27 | if (root == null) return 0; 28 | int left = maxDepth(root.left); 29 | int right = maxDepth(root.right); 30 | return 1 + Math.max(left, right); 31 | } 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Depth-first Search/257. Binary Tree Paths.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a binary tree, return all root-to-leaf paths. 5 | Note: A leaf is a node with no children. 6 | 7 | Example: 8 | Input: 9 | 1 10 | / \ 11 | 2 3 12 | \ 13 | 5 14 | Output: ["1->2->5", "1->3"] 15 | Explanation: All root-to-leaf paths are: 1->2->5, 1->3 16 | 17 | */ 18 | 19 | /* 20 | 21 | O(nlogn),O(logn) 22 | 23 | */ 24 | 25 | public List binaryTreePaths(TreeNode root) { 26 | List ans = new ArrayList<>(); 27 | dfs(ans, new StringBuilder(), root); 28 | return ans; 29 | } 30 | 31 | private void dfs(List ans, StringBuilder tmp, TreeNode root) { 32 | if (root == null) return; 33 | tmp.append(tmp.length() == 0 ? "" : "->").append(root.val); 34 | if (root.left == null && root.right == null) { 35 | ans.add(tmp.toString()); 36 | return; 37 | } 38 | int len = tmp.length(); 39 | dfs(ans, tmp, root.left); 40 | tmp.setLength(len); 41 | dfs(ans, tmp, root.right); 42 | tmp.setLength(len); 43 | } 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /Depth-first Search/366. Find Leaves of Binary Tree.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a binary tree, collect a tree's nodes as if you were doing this: 5 | Collect and remove all leaves, repeat until the tree is empty. 6 | 7 | Example: 8 | Input: [1,2,3,4,5] 9 | 1 10 | / \ 11 | 2 3 12 | / \ 13 | 4 5 14 | Output: [[4,5,3],[2],[1]] 15 | 16 | */ 17 | 18 | /* 19 | 20 | O(n),O(logn) 21 | 22 | */ 23 | 24 | public List> findLeaves(TreeNode root) { 25 | List> ans = new ArrayList<>(); 26 | dfs(ans, root); 27 | return ans; 28 | } 29 | 30 | private int dfs(List> ans, TreeNode root) { 31 | if (root == null) return -1; 32 | int level = 1 + Math.max(dfs(ans, root.left), dfs(ans, root.right)); 33 | if (ans.size() == level) ans.add(new ArrayList<>()); 34 | ans.get(level).add(root.val); 35 | return level; 36 | } 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /Design/346. Moving Average from Data Stream.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. 5 | 6 | Example: 7 | MovingAverage m = new MovingAverage(3); 8 | m.next(1) = 1 9 | m.next(10) = (1 + 10) / 2 10 | m.next(3) = (1 + 10 + 3) / 3 11 | m.next(5) = (10 + 3 + 5) / 3 12 | 13 | */ 14 | 15 | /* 16 | 17 | O(1),O(n) 18 | 19 | */ 20 | 21 | class MovingAverage { 22 | 23 | private Deque deque; 24 | private int size; 25 | private int sum; 26 | 27 | /** Initialize your data structure here. */ 28 | public MovingAverage(int size) { 29 | this.deque = new LinkedList<>(); 30 | this.size = size; 31 | this.sum = 0; 32 | } 33 | 34 | public double next(int val) { 35 | deque.offerLast(val); 36 | sum += val; 37 | if (deque.size() > size) sum -= deque.pollFirst(); 38 | return sum * 1.0 / deque.size(); 39 | } 40 | } 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /Dynamic Programming/303. Range Sum Query - Immutable.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. 5 | 6 | Example: 7 | Given nums = [-2, 0, 3, -5, 2, -1] 8 | sumRange(0, 2) -> 1 9 | sumRange(2, 5) -> -1 10 | sumRange(0, 5) -> -3 11 | 12 | */ 13 | 14 | /* 15 | 16 | O(n),O(n) 17 | 18 | */ 19 | 20 | class NumArray { 21 | 22 | private int[] sums; 23 | 24 | public NumArray(int[] nums) { 25 | int n = nums.length; 26 | this.sums = new int[n + 1]; 27 | for (int i = 1; i <= n; ++i) this.sums[i] = this.sums[i - 1] + nums[i - 1]; 28 | } 29 | 30 | public int sumRange(int i, int j) { 31 | return sums[j + 1] - sums[i]; 32 | } 33 | } 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /Dynamic Programming/5. Longest Palindromic Substring.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. 5 | 6 | Example 1: 7 | Input: "babad" 8 | Output: "bab" 9 | Note: "aba" is also a valid answer. 10 | 11 | Example 2: 12 | Input: "cbbd" 13 | Output: "bb" 14 | 15 | */ 16 | 17 | /* 18 | 19 | Solution: dp[i][j]=true, if s[i]=s[j] and dp[i+1][j-1]=true which means s[i+1...j-1] is palindromic 20 | O(n^2),O(n^2) 21 | 22 | */ 23 | 24 | public String longestPalindrome(String s) { 25 | int n = s.length(); 26 | String ans = ""; 27 | boolean[][] dp = new boolean[n][n]; 28 | for (int j = 0; j < n; ++j) { 29 | for (int i = j; i >= 0; --i) { 30 | if (s.charAt(i) == s.charAt(j) && (j - i < 2 || dp[i + 1][j - 1])) 31 | dp[i][j] = true; 32 | if (dp[i][j] && ans.length() < j - i + 1) 33 | ans = s.substring(i, j + 1); 34 | } 35 | } 36 | return ans; 37 | } 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /Dynamic Programming/53. Maximum Subarray.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum 5 | and return its sum. 6 | 7 | Example: 8 | Input: [-2,1,-3,4,-1,2,1,-5,4], 9 | Output: 6 10 | Explanation: [4,-1,2,1] has the largest sum = 6. 11 | 12 | */ 13 | 14 | /* 15 | 16 | O(n),O(n) 17 | 18 | */ 19 | 20 | public int maxSubArray(int[] nums) { 21 | int n = nums.length; 22 | int[] dp = new int[n]; 23 | dp[0] = nums[0]; 24 | int ans = nums[0]; 25 | for (int i = 1; i < n; ++i) { 26 | dp[i] = dp[i - 1] > 0 ? dp[i - 1] + nums[i] : nums[i]; 27 | ans = Math.max(ans, dp[i]); 28 | } 29 | return ans; 30 | } 31 | 32 | 33 | public int maxSubArray(int[] nums) { 34 | int prev = nums[0], ans = nums[0]; 35 | for (int i = 1; i < nums.length; ++i) { 36 | prev = prev > 0 ? prev + nums[i] : nums[i]; 37 | ans = Math.max(ans, prev); 38 | } 39 | return ans; 40 | } 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /Dynamic Programming/64. Minimum Path Sum.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right 5 | which minimizes the sum of all numbers along its path. 6 | Note: You can only move either down or right at any point in time. 7 | 8 | Example: 9 | Input: 10 | [ 11 | [1,3,1], 12 | [1,5,1], 13 | [4,2,1] 14 | ] 15 | Output: 7 16 | Explanation: Because the path 1→3→1→1→1 minimizes the sum. 17 | 18 | */ 19 | 20 | /* 21 | 22 | O(nm),O(nm) 23 | 24 | */ 25 | 26 | public int minPathSum(int[][] grid) { 27 | int n = grid.length, m = grid[0].length; 28 | int[][] dp = new int[n][m]; 29 | dp[0][0] = grid[0][0]; 30 | for (int i = 1; i < n; ++i) dp[i][0] = dp[i - 1][0] + grid[i][0]; 31 | for (int j = 1; j < m; ++j) dp[0][j] = dp[0][j - 1] + grid[0][j]; 32 | for (int i = 1; i < n; ++i) { 33 | for (int j = 1; j < m; ++j) 34 | dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]; 35 | } 36 | return dp[n - 1][m - 1]; 37 | } 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /Greedy/406. Queue Reconstruction by Height.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Suppose you have a random list of people standing in a queue. 5 | Each person is described by a pair of integers (h, k), where h is the height of the person and 6 | k is the number of people in front of this person who have a height greater than or equal to h. 7 | Write an algorithm to reconstruct the queue. 8 | 9 | Example 10 | Input: 11 | [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] 12 | Output: 13 | [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]] 14 | 15 | */ 16 | 17 | /* 18 | 19 | O(nlogn),O(n) 20 | 21 | */ 22 | 23 | public int[][] reconstructQueue(int[][] people) { 24 | Arrays.sort(people, new Comparator() { 25 | @Override 26 | public int compare(int[] a, int[] b) { 27 | return a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]; 28 | } 29 | }); 30 | List ans = new LinkedList<>(); 31 | for (int[] p : people) ans.add(p[1], p); 32 | return ans.toArray(people); 33 | } 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /Greedy/55. Jump Game.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 5 | Each element in the array represents your maximum jump length at that position. 6 | Determine if you are able to reach the last index. 7 | 8 | Example 1: 9 | Input: [2,3,1,1,4] 10 | Output: true 11 | Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. 12 | 13 | Example 2: 14 | Input: [3,2,1,0,4] 15 | Output: false 16 | Explanation: You will always arrive at index 3 no matter what. Its maximum 17 | jump length is 0, which makes it impossible to reach the last index. 18 | 19 | */ 20 | 21 | /* 22 | 23 | O(n),O(1) 24 | 25 | */ 26 | 27 | public boolean canJump(int[] nums) { 28 | int curEnd = 0, curMax = 0; 29 | for (int i = 0; i < nums.length; ++i) { 30 | curMax = Math.max(curMax, i + nums[i]); 31 | if (i > curEnd) return false; 32 | if (i == curEnd) curEnd = curMax; 33 | } 34 | return true; 35 | } 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Hash Table/1133. Largest Unique Number.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array of integers A, return the largest integer that only occurs once. 5 | If no integer occurs once, return -1. 6 | 7 | Example 1: 8 | Input: [5,7,3,9,4,9,8,3,1] 9 | Output: 8 10 | Explanation: 11 | The maximum integer in the array is 9 but it is repeated. The number 8 occurs only once, so it's the answer. 12 | 13 | Example 2: 14 | Input: [9,9,8,8] 15 | Output: -1 16 | Explanation: 17 | There is no number that occurs only once. 18 | 19 | */ 20 | 21 | /* 22 | 23 | O(n),O(n) 24 | 25 | */ 26 | 27 | public int largestUniqueNumber(int[] A) { 28 | int max = 0, ans = 0; 29 | for (int a : A) { 30 | max = Math.max(max, a); 31 | } 32 | int[] buckets = new int[max + 1]; 33 | for (int a : A) { 34 | buckets[a]++; 35 | } 36 | for (int i = max; i >= 0; --i) { 37 | if (buckets[i] == 1) { 38 | return i; 39 | } 40 | } 41 | return -1; 42 | } 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /Hash Table/159. Longest Substring with At Most Two Distinct Characters.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a string s , find the length of the longest substring t that contains at most 2 distinct characters. 5 | 6 | Example 1: 7 | Input: "eceba" 8 | Output: 3 9 | Explanation: t is "ece" which its length is 3. 10 | 11 | Example 2: 12 | Input: "ccaabbb" 13 | Output: 5 14 | Explanation: t is "aabbb" which its length is 5. 15 | 16 | */ 17 | 18 | /* 19 | 20 | O(n),O(1) 21 | 22 | */ 23 | 24 | public int lengthOfLongestSubstringTwoDistinct(String s) { 25 | int[] buckets = new int[128]; 26 | int ans = 0, cnt = 0; 27 | for (int i = 0, j = 0; j < s.length(); ++j) { 28 | char right = s.charAt(j); 29 | if (buckets[right] == 0) cnt++; 30 | buckets[right]++; 31 | while (cnt > 2) { 32 | char left = s.charAt(i); 33 | buckets[left]--; 34 | if (buckets[left] == 0) cnt--; 35 | i++; 36 | } 37 | ans = Math.max(ans, j - i + 1); 38 | } 39 | return ans; 40 | } 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /Hash Table/204. Count Primes.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Count the number of prime numbers less than a non-negative number, n. 5 | 6 | Example: 7 | Input: 10 8 | Output: 4 9 | Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. 10 | 11 | */ 12 | 13 | /* 14 | 15 | O(nlog(logn)),O(n) 16 | 17 | */ 18 | 19 | public int countPrimes(int n) { 20 | int ans = 0; 21 | boolean[] notPrimes = new boolean[n]; 22 | for (int i = 2; i < n; ++i) { 23 | if (!notPrimes[i]) { 24 | ans++; 25 | if (i * i < n) { 26 | for (int j = 2; i * j < n; ++j) notPrimes[i * j] = true; 27 | } 28 | } 29 | } 30 | return ans; 31 | } 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /Hash Table/219. Contains Duplicate II.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array 5 | such that nums[i] = nums[j] and the absolute difference between i and j is at most k. 6 | 7 | Example 1: 8 | Input: nums = [1,2,3,1], k = 3 9 | Output: true 10 | 11 | Example 2: 12 | Input: nums = [1,0,1,1], k = 1 13 | Output: true 14 | 15 | Example 3: 16 | Input: nums = [1,2,3,1,2,3], k = 2 17 | Output: false 18 | 19 | */ 20 | 21 | /* 22 | 23 | O(n),O(k) 24 | 25 | */ 26 | 27 | public boolean containsNearbyDuplicate(int[] nums, int k) { 28 | Set set = new HashSet<>(); 29 | for (int i = 0; i < nums.length; ++i) { 30 | if (i > k) set.remove(nums[i - k - 1]); 31 | if (!set.add(nums[i])) return true; 32 | } 33 | return false; 34 | } 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /Hash Table/242. Valid Anagram.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given two strings s and t , write a function to determine if t is an anagram of s. 5 | 6 | Example 1: 7 | Input: s = "anagram", t = "nagaram" 8 | Output: true 9 | 10 | Example 2: 11 | Input: s = "rat", t = "car" 12 | Output: false 13 | 14 | */ 15 | 16 | /* 17 | 18 | O(n),O(n) 19 | 20 | */ 21 | 22 | public boolean isAnagram(String s, String t) { 23 | if (s.length() != t.length()) return false; 24 | int[] buckets = new int[128]; 25 | for (int i = 0; i < s.length(); ++i) buckets[s.charAt(i)]++; 26 | for (int i = 0; i < t.length(); ++i) { 27 | if (buckets[t.charAt(i)] == 0) return false; 28 | buckets[t.charAt(i)]--; 29 | } 30 | return true; 31 | } 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Hash Table/246. Strobogrammatic Number.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). 5 | Write a function to determine if a number is strobogrammatic. The number is represented as a string. 6 | 7 | Example 1: 8 | Input: "69" 9 | Output: true 10 | 11 | Example 2: 12 | Input: "88" 13 | Output: true 14 | 15 | Example 3: 16 | Input: "962" 17 | Output: false 18 | 19 | */ 20 | 21 | /* 22 | 23 | O(n),O(1) 24 | 25 | */ 26 | 27 | public boolean isStrobogrammatic(String num) { 28 | Map map = new HashMap<>(); 29 | map.put('0', '0'); 30 | map.put('1', '1'); 31 | map.put('6', '9'); 32 | map.put('8', '8'); 33 | map.put('9', '6'); 34 | int l = 0, r = num.length() - 1; 35 | while (l <= r) { 36 | if (!map.containsKey(num.charAt(l))) return false; 37 | else if (map.get(num.charAt(l)) != num.charAt(r)) return false; 38 | l++; 39 | r--; 40 | } 41 | return true; 42 | } 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /Hash Table/266. Palindrome Permutation.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a string, determine if a permutation of the string could form a palindrome. 5 | 6 | Example 1: 7 | Input: "code" 8 | Output: false 9 | 10 | Example 2: 11 | Input: "aab" 12 | Output: true 13 | 14 | Example 3: 15 | Input: "carerac" 16 | Output: true 17 | 18 | */ 19 | 20 | /* 21 | 22 | O(n),O(1) 23 | 24 | */ 25 | 26 | public boolean canPermutePalindrome(String s) { 27 | int[] buckets = new int[128]; 28 | int cnt = 0; 29 | for (int i = 0; i < s.length(); ++i) buckets[s.charAt(i)]++; 30 | for (int i = 0; i < buckets.length; ++i) { 31 | if (buckets[i] % 2 == 1) cnt++; 32 | if (cnt > 1) return false; 33 | } 34 | return true; 35 | } 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Hash Table/356. Line Reflection.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given n points on a 2D plane, find if there is such a line parallel to y-axis that reflect the given points. 5 | 6 | Example 1: 7 | Input: [[1,1],[-1,1]] 8 | Output: true 9 | 10 | Example 2: 11 | Input: [[1,1],[-1,-1]] 12 | Output: false 13 | 14 | */ 15 | 16 | /* 17 | 18 | O(n),O(n) 19 | 20 | */ 21 | 22 | public boolean isReflected(int[][] points) { 23 | Set set = new HashSet<>(); 24 | int left = Integer.MAX_VALUE, right = Integer.MIN_VALUE; 25 | for (int[] point : points) { 26 | set.add(point[0] + "," + point[1]); 27 | left = Math.min(left, point[0]); 28 | right = Math.max(right, point[0]); 29 | } 30 | int mid = left + right; 31 | for (int[] point : points) { 32 | if (!set.contains((mid - point[0]) + "," + point[1])) return false; 33 | } 34 | return true; 35 | } 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /Hash Table/387. First Unique Character in a String.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. 5 | 6 | Examples: 7 | s = "leetcode" 8 | return 0. 9 | 10 | s = "loveleetcode", 11 | return 2. 12 | 13 | */ 14 | 15 | /* 16 | 17 | O(n),O(1) 18 | 19 | */ 20 | 21 | public int firstUniqChar(String s) { 22 | int[] buckets = new int[26]; 23 | for (char c : s.toCharArray()) buckets[c - 'a']++; 24 | for (int i = 0; i < s.length(); ++i) { 25 | if (buckets[s.charAt(i) - 'a'] == 1) return i; 26 | } 27 | return -1; 28 | } 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /Hash Table/409. Longest Palindrome.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a string which consists of lowercase or uppercase letters, 5 | find the length of the longest palindromes that can be built with those letters. 6 | This is case sensitive, for example "Aa" is not considered a palindrome here. 7 | 8 | Example: 9 | Input: 10 | "abccccdd" 11 | Output: 12 | 7 13 | Explanation: 14 | One longest palindrome that can be built is "dccaccd", whose length is 7. 15 | 16 | */ 17 | 18 | /* 19 | 20 | O(n),O(1) 21 | 22 | */ 23 | 24 | public int longestPalindrome(String s) { 25 | int[] buckets = new int[128]; 26 | int ans = 0, mid = 0; 27 | for (char c : s.toCharArray()) buckets[c]++; 28 | for (int cnt : buckets) { 29 | if (cnt % 2 == 1) mid = 1; 30 | ans += cnt / 2 * 2; 31 | } 32 | return ans + mid; 33 | } 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /Hash Table/49. Group Anagrams.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array of strings, group anagrams together. 5 | 6 | Example: 7 | Input: ["eat", "tea", "tan", "ate", "nat", "bat"], 8 | Output: 9 | [ 10 | ["ate","eat","tea"], 11 | ["nat","tan"], 12 | ["bat"] 13 | ] 14 | 15 | */ 16 | 17 | /* 18 | 19 | O(nmlogm),O(nm), where m is the average length of the strings 20 | 21 | */ 22 | 23 | public List> groupAnagrams(String[] strs) { 24 | List> ans = new ArrayList<>(); 25 | Map> map = new HashMap<>(); 26 | for (String s : strs) { 27 | char[] ch = s.toCharArray(); 28 | Arrays.sort(ch); 29 | String key = new String(ch); 30 | List values = map.getOrDefault(key, new ArrayList<>()); 31 | values.add(s); 32 | map.put(key, values); 33 | } 34 | for (String key : map.keySet()) ans.add(map.get(key)); 35 | return ans; 36 | } 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /Hash Table/560. Subarray Sum Equals K.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. 5 | 6 | Example 1: 7 | Input:nums = [1,1,1], k = 2 8 | Output: 2 9 | 10 | */ 11 | 12 | /* 13 | 14 | Solution: use prefix sum, when we have a sum for nums[j] and sum-k for nums[i] which means nums[i...j] is k 15 | O(n),O(n) 16 | 17 | */ 18 | 19 | public int subarraySum(int[] nums, int k) { 20 | int ans = 0, sum = 0; 21 | Map map = new HashMap<>(); 22 | map.put(0, 1); 23 | for (int num : nums) { 24 | sum += num; 25 | if (map.containsKey(sum - k)) { 26 | ans += map.get(sum - k); 27 | } 28 | map.put(sum, map.getOrDefault(sum, 0) + 1); 29 | } 30 | return ans; 31 | } 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Hash Table/594. Longest Harmonious Subsequence.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1. 5 | Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences. 6 | 7 | Example 1: 8 | Input: [1,3,2,2,5,2,3,7] 9 | Output: 5 10 | Explanation: The longest harmonious subsequence is [3,2,2,2,3]. 11 | 12 | */ 13 | 14 | /* 15 | 16 | O(n),O(n) 17 | 18 | */ 19 | 20 | public int findLHS(int[] nums) { 21 | int ans = 0; 22 | Map map = new HashMap<>(); 23 | for (int num : nums) { 24 | map.put(num, map.getOrDefault(num, 0) + 1); 25 | } 26 | for (int num : map.keySet()) { 27 | if (map.containsKey(num + 1)) { 28 | ans = Math.max(ans, map.get(num) + map.get(num + 1)); 29 | } 30 | } 31 | return ans; 32 | } 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /Hash Table/974. Subarray Sums Divisible by K.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by K. 5 | 6 | Example 1: 7 | Input: A = [4,5,0,-2,-3,1], K = 5 8 | Output: 7 9 | Explanation: There are 7 subarrays with a sum divisible by K = 5: 10 | [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3] 11 | 12 | */ 13 | 14 | /* 15 | 16 | O(n),O(n) 17 | 18 | */ 19 | 20 | public int subarraysDivByK(int[] A, int K) { 21 | Map map = new HashMap<>(); 22 | map.put(0, 1); 23 | int ans = 0, sum = 0; 24 | for (int a : A) { 25 | sum = (sum + a) % K; 26 | if (sum < 0) { 27 | sum += K; 28 | } 29 | ans += map.getOrDefault(sum, 0); 30 | map.put(sum, map.getOrDefault(sum, 0) + 1); 31 | } 32 | return ans; 33 | } 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /Linked List/19. Remove Nth Node From End of List.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a linked list, remove the n-th node from the end of list and return its head. 5 | 6 | Example: 7 | Given linked list: 1->2->3->4->5, and n = 2. 8 | After removing the second node from the end, the linked list becomes 1->2->3->5. 9 | 10 | Note: 11 | Given n will always be valid. 12 | 13 | */ 14 | 15 | /* 16 | 17 | O(n),O(1) 18 | 19 | */ 20 | 21 | public ListNode removeNthFromEnd(ListNode head, int n) { 22 | ListNode dummy = new ListNode(0); 23 | dummy.next = head; 24 | ListNode fast = dummy, slow = dummy; 25 | while (n > 0) { 26 | fast = fast.next; 27 | n--; 28 | } 29 | while (fast.next != null) { 30 | fast = fast.next; 31 | slow = slow.next; 32 | } 33 | slow.next = slow.next.next; 34 | return dummy.next; 35 | } 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /Linked List/203. Remove Linked List Elements.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Remove all elements from a linked list of integers that have value val. 5 | 6 | Example: 7 | Input: 1->2->6->3->4->5->6, val = 6 8 | Output: 1->2->3->4->5 9 | 10 | */ 11 | 12 | /* 13 | 14 | O(n),O(1) 15 | 16 | */ 17 | 18 | public ListNode removeElements(ListNode head, int val) { 19 | if (head == null) return head; 20 | ListNode dummy = new ListNode(0); 21 | dummy.next = head; 22 | ListNode prev = dummy; 23 | while (prev != null) { 24 | while (prev.next != null && prev.next.val == val) prev.next = prev.next.next; 25 | prev = prev.next; 26 | } 27 | return dummy.next; 28 | } 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /Linked List/206. Reverse Linked List.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Reverse a singly linked list. 5 | 6 | Example: 7 | Input: 1->2->3->4->5->NULL 8 | Output: 5->4->3->2->1->NULL 9 | 10 | */ 11 | 12 | /* 13 | 14 | Solution 1: iterative way 15 | O(n),O(1) 16 | 17 | */ 18 | 19 | public ListNode reverseList(ListNode head) { 20 | ListNode newHead = null; 21 | while (head != null) { 22 | ListNode tmp = head.next; 23 | head.next = newHead; 24 | newHead = head; 25 | head = tmp; 26 | } 27 | return newHead; 28 | } 29 | 30 | 31 | /* 32 | 33 | Solution 2: recursive way 34 | O(n),O(n) 35 | 36 | */ 37 | 38 | public ListNode reverseList(ListNode head) { 39 | if (head == null || head.next == null) return head; 40 | ListNode newHead = reverseList(head.next); 41 | head.next.next = head; 42 | head.next = null; 43 | return newHead; 44 | } 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /Linked List/21. Merge Two Sorted Lists.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Merge two sorted linked lists and return it as a new list. 5 | The new list should be made by splicing together the nodes of the first two lists. 6 | 7 | Example: 8 | Input: 1->2->4, 1->3->4 9 | Output: 1->1->2->3->4->4 10 | 11 | */ 12 | 13 | /* 14 | 15 | O(n+m),O(1) 16 | 17 | */ 18 | 19 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 20 | if (l1 == null) return l2; 21 | if (l2 == null) return l1; 22 | if (l1.val < l2.val) { 23 | l1.next = mergeTwoLists(l1.next, l2); 24 | return l1; 25 | } else { 26 | l2.next = mergeTwoLists(l1, l2.next); 27 | return l2; 28 | } 29 | } 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /Linked List/234. Palindrome Linked List.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a singly linked list, determine if it is a palindrome. 5 | 6 | Example 1: 7 | Input: 1->2 8 | Output: false 9 | 10 | Example 2: 11 | Input: 1->2->2->1 12 | Output: true 13 | 14 | */ 15 | 16 | /* 17 | 18 | O(n),O(1) 19 | 20 | */ 21 | 22 | public boolean isPalindrome(ListNode head) { 23 | ListNode fast = head, slow = head; 24 | while (fast != null && fast.next != null) { 25 | fast = fast.next.next; 26 | slow = slow.next; 27 | } 28 | slow = reverse(slow); 29 | fast = head; 30 | while (slow != null) { 31 | if (fast.val != slow.val) return false; 32 | fast = fast.next; 33 | slow = slow.next; 34 | } 35 | return true; 36 | } 37 | 38 | private ListNode reverse(ListNode head) { 39 | if (head == null || head.next == null) return head; 40 | ListNode newHead = reverse(head.next); 41 | head.next.next = head; 42 | head.next = null; 43 | return newHead; 44 | } 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /Linked List/237. Delete Node in a Linked List.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. 5 | 6 | Example 1: 7 | Input: head = [4,5,1,9], node = 5 8 | Output: [4,1,9] 9 | Explanation: You are given the second node with value 5, the linked list should become 4->1->9 after calling your function. 10 | 11 | Example 2: 12 | Input: head = [4,5,1,9], node = 1 13 | Output: [4,5,9] 14 | Explanation: You are given the third node with value 1, the linked list should become 4->5->9 after calling your function. 15 | 16 | */ 17 | 18 | /* 19 | 20 | O(1),O(1) 21 | 22 | */ 23 | 24 | public void deleteNode(ListNode node) { 25 | node.val = node.next.val; 26 | node.next = node.next.next; 27 | } 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /Linked List/24. Swap Nodes in Pairs.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a linked list, swap every two adjacent nodes and return its head. 5 | 6 | Example: 7 | Given 1->2->3->4, you should return the list as 2->1->4->3. 8 | 9 | */ 10 | 11 | /* 12 | 13 | O(n),O(1) 14 | 15 | */ 16 | 17 | public ListNode swapPairs(ListNode head) { 18 | ListNode dummy = new ListNode(0); 19 | dummy.next = head; 20 | ListNode prev = dummy; 21 | while (prev.next != null && prev.next.next != null) { 22 | ListNode l1 = prev.next, l2 = prev.next.next; 23 | l1.next = l2.next; 24 | l2.next = l1; 25 | prev.next = l2; 26 | prev = l1; 27 | } 28 | return dummy.next; 29 | } 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /Linked List/328. Odd Even Linked List.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a singly linked list, group all odd nodes together followed by the even nodes. 5 | Please note here we are talking about the node number and not the value in the nodes. 6 | You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity. 7 | 8 | Example 1: 9 | Input: 1->2->3->4->5->NULL 10 | Output: 1->3->5->2->4->NULL 11 | 12 | Example 2: 13 | Input: 2->1->3->5->6->4->7->NULL 14 | Output: 2->3->6->7->1->5->4->NULL 15 | 16 | */ 17 | 18 | /* 19 | 20 | O(n),O(1) 21 | 22 | */ 23 | 24 | public ListNode oddEvenList(ListNode head) { 25 | if (head == null || head.next == null) return head; 26 | ListNode odd = head, even = head.next, evenHead = head.next; 27 | while (even != null && even.next != null) { 28 | odd.next = odd.next.next; 29 | odd = odd.next; 30 | even.next = even.next.next; 31 | even = even.next; 32 | } 33 | odd.next = evenHead; 34 | return head; 35 | } 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /Linked List/82. Remove Duplicates from Sorted List II.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. 5 | 6 | Example 1: 7 | Input: 1->2->3->3->4->4->5 8 | Output: 1->2->5 9 | 10 | Example 2: 11 | Input: 1->1->1->2->3 12 | Output: 2->3 13 | 14 | */ 15 | 16 | /* 17 | 18 | O(n),O(1) 19 | 20 | */ 21 | 22 | public ListNode deleteDuplicates(ListNode head) { 23 | ListNode dummy = new ListNode(0); 24 | dummy.next = head; 25 | ListNode fast = head, slow = dummy; 26 | while (fast != null && fast.next != null) { 27 | while (fast != null && fast.next != null && fast.val == fast.next.val) fast = fast.next; 28 | if (slow.next == fast) slow = slow.next; 29 | else slow.next = fast.next; 30 | fast = fast.next; 31 | } 32 | return dummy.next; 33 | } 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Linked List/86. Partition List.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. 5 | You should preserve the original relative order of the nodes in each of the two partitions. 6 | 7 | Example: 8 | Input: head = 1->4->3->2->5->2, x = 3 9 | Output: 1->2->2->4->3->5 10 | 11 | */ 12 | 13 | /* 14 | 15 | O(n),O(1) 16 | 17 | */ 18 | 19 | public ListNode partition(ListNode head, int x) { 20 | ListNode dummy1 = new ListNode(0), prev1 = dummy1; 21 | ListNode dummy2 = new ListNode(0), prev2 = dummy2; 22 | ListNode cur = head; 23 | while (cur != null) { 24 | if (cur.val < x) { 25 | prev1.next = cur; 26 | prev1 = prev1.next; 27 | } else { 28 | prev2.next = cur; 29 | prev2 = prev2.next; 30 | } 31 | cur = cur.next; 32 | } 33 | prev1.next = dummy2.next; 34 | prev2.next = null; 35 | return dummy1.next; 36 | } 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /Linked List/92. Reverse Linked List II.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Reverse a linked list from position m to n. Do it in one-pass. 5 | Note: 1 ≤ m ≤ n ≤ length of list. 6 | 7 | Example: 8 | Input: 1->2->3->4->5->NULL, m = 2, n = 4 9 | Output: 1->4->3->2->5->NULL 10 | 11 | */ 12 | 13 | /* 14 | 15 | O(n),O(1) 16 | 17 | */ 18 | 19 | public ListNode reverseBetween(ListNode head, int m, int n) { 20 | ListNode dummy = new ListNode(0); 21 | dummy.next = head; 22 | ListNode prev = dummy; 23 | for (int i = 0; i < m - 1; ++i) prev = prev.next; 24 | ListNode cur = prev.next, nxt = cur.next; 25 | for (int i = 0; i < n - m; ++i) { 26 | cur.next = nxt.next; 27 | nxt.next = prev.next; 28 | prev.next = nxt; 29 | nxt = cur.next; 30 | } 31 | return dummy.next; 32 | } 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Math/1015. Smallest Integer Divisible by K.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a positive integer K, you need find the smallest positive integer N such that N is divisible by K, 5 | and N only contains the digit 1. 6 | Return the length of N. If there is no such N, return -1. 7 | 8 | Example 1: 9 | Input: 1 10 | Output: 1 11 | Explanation: The smallest answer is N = 1, which has length 1. 12 | 13 | Example 2: 14 | Input: 2 15 | Output: -1 16 | Explanation: There is no such positive integer N divisible by 2. 17 | 18 | Example 3: 19 | Input: 3 20 | Output: 3 21 | Explanation: The smallest answer is N = 111, which has length 3. 22 | 23 | */ 24 | 25 | /* 26 | 27 | Solution: 28 | 29 | */ 30 | 31 | public int smallestRepunitDivByK(int K) { 32 | if (K == 1) { 33 | return 1; 34 | } 35 | if (K % 2 == 0 || K % 5 == 0) { 36 | return -1; 37 | } 38 | int cur = 1, ans = 1;; 39 | while (true) { 40 | if (cur == 0) { 41 | return ans; 42 | } 43 | cur = (cur * 10 + 1) % K; 44 | ans++; 45 | } 46 | } 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /Math/1017. Convert to Base -2.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a number N, return a string consisting of "0"s and "1"s that represents its value in base -2 (negative two). 5 | The returned string must have no leading zeroes, unless the string is "0". 6 | 7 | Example 1: 8 | Input: 2 9 | Output: "110" 10 | Explantion: (-2) ^ 2 + (-2) ^ 1 = 2 11 | 12 | Example 2: 13 | Input: 3 14 | Output: "111" 15 | Explantion: (-2) ^ 2 + (-2) ^ 1 + (-2) ^ 0 = 3 16 | 17 | Example 3: 18 | Input: 4 19 | Output: "100" 20 | Explantion: (-2) ^ 2 = 4 21 | 22 | */ 23 | 24 | /* 25 | 26 | O(logn),O(1) 27 | 28 | */ 29 | 30 | public String baseNeg2(int N) { 31 | StringBuilder ans = new StringBuilder(); 32 | while (N != 0) { 33 | ans.append(N & 1); 34 | N = -(N >> 1); 35 | } 36 | return ans.length() > 0 ? ans.reverse().toString() : "0"; 37 | } 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /Math/1025. Divisor Game.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Alice and Bob take turns playing a game, with Alice starting first. 5 | Initially, there is a number N on the chalkboard. On each player's turn, that player makes a move consisting of: 6 | Choosing any x with 0 < x < N and N % x == 0. 7 | Replacing the number N on the chalkboard with N - x. 8 | Also, if a player cannot make a move, they lose the game. 9 | Return True if and only if Alice wins the game, assuming both players play optimally. 10 | 11 | Example 1: 12 | Input: 2 13 | Output: true 14 | Explanation: Alice chooses 1, and Bob has no more moves. 15 | 16 | Example 2: 17 | Input: 3 18 | Output: false 19 | Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves. 20 | 21 | */ 22 | 23 | /* 24 | 25 | O(1),O(1) 26 | 27 | */ 28 | 29 | public boolean divisorGame(int N) { 30 | return N % 2 == 0; 31 | } 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /Math/1037. Valid Boomerang.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | A boomerang is a set of 3 points that are all distinct and not in a straight line. 5 | Given a list of three points in the plane, return whether these points are a boomerang. 6 | 7 | Example 1: 8 | Input: [[1,1],[2,3],[3,2]] 9 | Output: true 10 | 11 | Example 2: 12 | Input: [[1,1],[2,2],[3,3]] 13 | Output: false 14 | 15 | */ 16 | 17 | /* 18 | 19 | O(1),O(1) 20 | 21 | */ 22 | 23 | public boolean isBoomerang(int[][] points) { 24 | return (points[0][0] - points[1][0]) * (points[0][1] - points[2][1]) != 25 | (points[0][0] - points[2][0]) * (points[0][1] - points[1][1]); 26 | } 27 | 28 | 29 | -------------------------------------------------------------------------------- /Math/1118. Number of Days in a Month.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a year Y and a month M, return how many days there are in that month. 5 | 6 | Example 1: 7 | Input: Y = 1992, M = 7 8 | Output: 31 9 | 10 | Example 2: 11 | Input: Y = 2000, M = 2 12 | Output: 29 13 | 14 | Example 3: 15 | Input: Y = 1900, M = 2 16 | Output: 28 17 | 18 | */ 19 | 20 | /* 21 | 22 | O(1),O(1) 23 | 24 | */ 25 | 26 | private int[] days = new int[] {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; 27 | 28 | public int numberOfDays(int Y, int M) { 29 | return M == 2 && isLeapYear(Y) ? 29 : days[M]; 30 | } 31 | 32 | private boolean isLeapYear(int Y) { 33 | return (Y % 4 == 0 && Y % 100 != 0) || Y % 400 == 0; 34 | } 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /Math/1134. Armstrong Number.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | The k-digit number N is an Armstrong number if and only if the k-th power of each digit sums to N. 5 | Given a positive integer N, return true if and only if it is an Armstrong number. 6 | 7 | Example 1: 8 | Input: 153 9 | Output: true 10 | Explanation: 11 | 153 is a 3-digit number, and 153 = 1^3 + 5^3 + 3^3. 12 | 13 | Example 2: 14 | Input: 123 15 | Output: false 16 | Explanation: 17 | 123 is a 3-digit number, and 123 != 1^3 + 2^3 + 3^3 = 36. 18 | 19 | */ 20 | 21 | /* 22 | 23 | O(logn),O(1) 24 | 25 | */ 26 | 27 | public boolean isArmstrong(int N) { 28 | int k = 0, num = N, ans = 0; 29 | while (num > 0) { 30 | num /= 10; 31 | k++; 32 | } 33 | num = N; 34 | while (num > 0) { 35 | int digit = num % 10; 36 | ans += Math.pow(digit, k); 37 | num /= 10; 38 | } 39 | return ans == N; 40 | } 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Math/168. Excel Sheet Column Title.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a positive integer, return its corresponding column title as appear in an Excel sheet. 5 | For example: 6 | 1 -> A 7 | 2 -> B 8 | 3 -> C 9 | ... 10 | 26 -> Z 11 | 27 -> AA 12 | 28 -> AB 13 | ... 14 | 15 | Example 1: 16 | Input: 1 17 | Output: "A" 18 | 19 | Example 2: 20 | Input: 28 21 | Output: "AB" 22 | 23 | Example 3: 24 | Input: 701 25 | Output: "ZY" 26 | 27 | */ 28 | 29 | /* 30 | 31 | O(n),O(1) 32 | 33 | */ 34 | 35 | public String convertToTitle(int n) { 36 | StringBuilder ans = new StringBuilder(); 37 | while (n > 0) { 38 | n--; 39 | ans.append((char)('A' + n % 26)); 40 | n /= 26; 41 | } 42 | ans.reverse(); 43 | return ans.toString(); 44 | } 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /Math/171. Excel Sheet Column Number.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a column title as appear in an Excel sheet, return its corresponding column number. 5 | For example: 6 | A -> 1 7 | B -> 2 8 | C -> 3 9 | ... 10 | Z -> 26 11 | AA -> 27 12 | AB -> 28 13 | ... 14 | 15 | Example 1: 16 | Input: "A" 17 | Output: 1 18 | 19 | Example 2: 20 | Input: "AB" 21 | Output: 28 22 | 23 | Example 3: 24 | Input: "ZY" 25 | Output: 701 26 | 27 | */ 28 | 29 | /* 30 | 31 | O(n),O(1) 32 | 33 | */ 34 | 35 | public int titleToNumber(String s) { 36 | int ans = 0, tmp = 1; 37 | for (int i = s.length() - 1; i >= 0; --i) { 38 | ans += (s.charAt(i) - 'A' + 1) * tmp; 39 | tmp *= 26; 40 | } 41 | return ans; 42 | } 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /Math/172. Factorial Trailing Zeroes.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an integer n, return the number of trailing zeroes in n!. 5 | 6 | Example 1: 7 | Input: 3 8 | Output: 0 9 | Explanation: 3! = 6, no trailing zero. 10 | 11 | Example 2: 12 | Input: 5 13 | Output: 1 14 | Explanation: 5! = 120, one trailing zero. 15 | 16 | */ 17 | 18 | /* 19 | 20 | O(logn),O(1) 21 | 22 | */ 23 | 24 | public int trailingZeroes(int n) { 25 | int ans = 0; 26 | while (n > 0) { 27 | n /= 5; 28 | ans += n; 29 | } 30 | return ans; 31 | } 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Math/204. Count Primes.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Count the number of prime numbers less than a non-negative number, n. 5 | 6 | Example: 7 | Input: 10 8 | Output: 4 9 | Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. 10 | 11 | */ 12 | 13 | /* 14 | 15 | O(nlog(logn)),O(n) 16 | 17 | */ 18 | 19 | public int countPrimes(int n) { 20 | int ans = 0; 21 | boolean[] notPrimes = new boolean[n]; 22 | for (int i = 2; i < n; ++i) { 23 | if (!notPrimes[i]) { 24 | ans++; 25 | if (i * i < n) { 26 | for (int j = 2; i * j < n; ++j) notPrimes[i * j] = true; 27 | } 28 | } 29 | } 30 | return ans; 31 | } 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /Math/223. Rectangle Area.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Find the total area covered by two rectilinear rectangles in a 2D plane. 5 | Each rectangle is defined by its bottom left corner and top right corner as shown in the figure. 6 | 7 | Example: 8 | Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2 9 | Output: 45 10 | 11 | */ 12 | 13 | /* 14 | 15 | O(1),O(1) 16 | 17 | */ 18 | 19 | public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { 20 | int area1 = (C - A) * (D - B), area2 = (G - E) * (H - F); 21 | int l = Math.max(A, E), r = Math.min(C, G), t = Math.min(D, H), b = Math.max(B, F); 22 | int overlap = 0; 23 | if (r > l && t > b) overlap = (r - l) * (t - b); 24 | return area1 + area2 - overlap; 25 | } 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /Math/231. Power of Two.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an integer, write a function to determine if it is a power of two. 5 | 6 | Example 1: 7 | Input: 1 8 | Output: true 9 | Explanation: 20 = 1 10 | 11 | Example 2: 12 | Input: 16 13 | Output: true 14 | Explanation: 24 = 16 15 | 16 | Example 3: 17 | Input: 218 18 | Output: false 19 | 20 | */ 21 | 22 | /* 23 | 24 | O(n),O(1) 25 | 26 | */ 27 | 28 | public boolean isPowerOfTwo(int n) { 29 | if (n <= 0) return false; 30 | while (n % 2 == 0) n /= 2; 31 | return n == 1; 32 | } 33 | 34 | 35 | /* 36 | 37 | Solution 2: n&(n-1) to remove the last set bit, and if it's power of two, there is only one '1' bit, so the remain should be 0 38 | O(1),O(1) 39 | 40 | */ 41 | 42 | public boolean isPowerOfTwo(int n) { 43 | if (n <= 0) return false; 44 | return (n & (n - 1)) == 0; 45 | } 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /Math/233. Number of Digit One.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n. 5 | 6 | Example: 7 | Input: 13 8 | Output: 6 9 | Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13. 10 | 11 | */ 12 | 13 | /* 14 | 15 | Solution: 16 | O(k),O(1), where k is the number of digits 17 | 18 | */ 19 | 20 | public int countDigitOne(int n) { 21 | int x = n, y = 1, ans = 0; 22 | while (x > 0) { 23 | int digit = x % 10; 24 | x /= 10; 25 | ans += x * y; 26 | if (digit == 1) ans += n % y + 1; 27 | else if (digit > 1) ans += y; 28 | y *= 10; 29 | } 30 | return ans; 31 | } 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /Math/246. Strobogrammatic Number.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). 5 | Write a function to determine if a number is strobogrammatic. The number is represented as a string. 6 | 7 | Example 1: 8 | Input: "69" 9 | Output: true 10 | 11 | Example 2: 12 | Input: "88" 13 | Output: true 14 | 15 | Example 3: 16 | Input: "962" 17 | Output: false 18 | 19 | */ 20 | 21 | /* 22 | 23 | O(n),O(1) 24 | 25 | */ 26 | 27 | public boolean isStrobogrammatic(String num) { 28 | Map map = new HashMap<>(); 29 | map.put('0', '0'); 30 | map.put('1', '1'); 31 | map.put('6', '9'); 32 | map.put('8', '8'); 33 | map.put('9', '6'); 34 | int l = 0, r = num.length() - 1; 35 | while (l <= r) { 36 | if (!map.containsKey(num.charAt(l))) return false; 37 | else if (map.get(num.charAt(l)) != num.charAt(r)) return false; 38 | l++; 39 | r--; 40 | } 41 | return true; 42 | } 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /Math/263. Ugly Number.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Write a program to check whether a given number is an ugly number. 5 | Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. 6 | 7 | Example 1: 8 | Input: 6 9 | Output: true 10 | Explanation: 6 = 2 × 3 11 | 12 | Example 2: 13 | Input: 8 14 | Output: true 15 | Explanation: 8 = 2 × 2 × 2 16 | 17 | Example 3: 18 | Input: 14 19 | Output: false 20 | Explanation: 14 is not ugly since it includes another prime factor 7. 21 | 22 | */ 23 | 24 | /* 25 | 26 | O(n),O(1) 27 | 28 | */ 29 | 30 | public boolean isUgly(int num) { 31 | if (num == 0) return false; 32 | if (num == 1) return true; 33 | while (num % 2 == 0) num /= 2; 34 | while (num % 3 == 0) num /= 3; 35 | while (num % 5 == 0) num /= 5; 36 | return num == 1; 37 | } 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /Math/264. Ugly Number II.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Write a program to find the n-th ugly number. 5 | Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. 6 | 7 | Example: 8 | Input: n = 10 9 | Output: 12 10 | Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers. 11 | 12 | */ 13 | 14 | /* 15 | 16 | Solution: num2,num3,num5 means the index of next element can be multiplied with 2,3,5 17 | ans[i]=min(ans[num2]*2,ans[num3]*3,ans[num5]*5), and move the corresponding index if 2,3,5 is multiplied 18 | O(n),O(n) 19 | 20 | */ 21 | 22 | public int nthUglyNumber(int n) { 23 | int[] ans = new int[n]; 24 | ans[0] = 1; 25 | int num2 = 0, num3 = 0, num5 = 0; 26 | for (int i = 1; i < n; ++i) { 27 | ans[i] = Math.min(ans[num2] * 2, Math.min(ans[num3] * 3, ans[num5] * 5)); 28 | if (ans[i] == ans[num2] * 2) num2++; 29 | if (ans[i] == ans[num3] * 3) num3++; 30 | if (ans[i] == ans[num5] * 5) num5++; 31 | } 32 | return ans[n - 1]; 33 | } 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /Math/268. Missing Number.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. 5 | 6 | Example 1: 7 | Input: [3,0,1] 8 | Output: 2 9 | 10 | Example 2: 11 | Input: [9,6,4,2,3,5,7,0,1] 12 | Output: 8 13 | 14 | */ 15 | 16 | /* 17 | 18 | Solution: since num is 0,1,2,...,n, num^index=0 if this num is not missing 19 | O(n),O(1) 20 | 21 | */ 22 | 23 | public int missingNumber(int[] nums) { 24 | int ans = nums.length; 25 | for (int i = 0; i < nums.length; ++i) ans = ans ^ i ^ nums[i]; 26 | return ans; 27 | } 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /Math/326. Power of Three.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an integer, write a function to determine if it is a power of three. 5 | 6 | Example 1: 7 | Input: 27 8 | Output: true 9 | 10 | Example 2: 11 | Input: 0 12 | Output: false 13 | 14 | Example 3: 15 | Input: 9 16 | Output: true 17 | 18 | Example 4: 19 | Input: 45 20 | Output: false 21 | 22 | */ 23 | 24 | /* 25 | 26 | Solution 1: use loop 27 | O(n),O(1) 28 | 29 | */ 30 | 31 | public boolean isPowerOfThree(int n) { 32 | if (n == 0) return false; 33 | while (n % 3 == 0) n /= 3; 34 | return n == 1; 35 | } 36 | 37 | 38 | /* 39 | 40 | Solution 2: 3^x=n,x=log3(n)=log10(n)/log10(3) which should be an integer 41 | O(1),O(1) 42 | 43 | */ 44 | 45 | public boolean isPowerOfThree(int n) { 46 | return (Math.log10(n) / Math.log10(3)) % 1 == 0; 47 | } 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /Math/356. Line Reflection.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given n points on a 2D plane, find if there is such a line parallel to y-axis that reflect the given points. 5 | 6 | Example 1: 7 | Input: [[1,1],[-1,1]] 8 | Output: true 9 | 10 | Example 2: 11 | Input: [[1,1],[-1,-1]] 12 | Output: false 13 | 14 | */ 15 | 16 | /* 17 | 18 | O(n),O(n) 19 | 20 | */ 21 | 22 | public boolean isReflected(int[][] points) { 23 | Set set = new HashSet<>(); 24 | int left = Integer.MAX_VALUE, right = Integer.MIN_VALUE; 25 | for (int[] point : points) { 26 | set.add(point[0] + "," + point[1]); 27 | left = Math.min(left, point[0]); 28 | right = Math.max(right, point[0]); 29 | } 30 | int mid = left + right; 31 | for (int[] point : points) { 32 | if (!set.contains((mid - point[0]) + "," + point[1])) return false; 33 | } 34 | return true; 35 | } 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /Math/367. Valid Perfect Square.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a positive integer num, write a function which returns True if num is a perfect square else False. 5 | Note: Do not use any built-in library function such as sqrt. 6 | 7 | Example 1: 8 | Input: 16 9 | Output: true 10 | 11 | Example 2: 12 | Input: 14 13 | Output: false 14 | 15 | */ 16 | 17 | /* 18 | 19 | O(logn),O(1) 20 | 21 | */ 22 | 23 | public boolean isPerfectSquare(int num) { 24 | if (num <= 0) return false; 25 | int l = 1, r = num; 26 | while (l <= r) { 27 | int mid = (l + r) / 2; 28 | if (mid == num / mid) return num % mid == 0; 29 | else if (mid < num / mid) l = mid + 1; 30 | else r = mid - 1; 31 | } 32 | return false; 33 | } 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /Math/372. Super Pow.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer 5 | given in the form of an array. 6 | 7 | Example 1: 8 | Input: a = 2, b = [3] 9 | Output: 8 10 | 11 | Example 2: 12 | Input: a = 2, b = [1,0] 13 | Output: 1024 14 | 15 | */ 16 | 17 | /* 18 | 19 | Solution: a^(b[0...n])=a^(b[0]*10^n)*a^(b[1]*10^(n-1))*...*a^(b[n-2]*10)*a^(b[n-1]*1) 20 | O(n),O(1) 21 | 22 | */ 23 | 24 | private final int MOD = 1337; 25 | 26 | public int superPow(int a, int[] b) { 27 | if (b.length == 0) return 1; 28 | return superPow(a, b, b.length - 1); 29 | } 30 | 31 | private int superPow(int a, int[] b, int idx) { 32 | if (idx == 0) return pow(a, b[0]); 33 | int cur = b[idx]; 34 | return pow(superPow(a, b, idx - 1), 10) * pow(a, cur) % MOD; 35 | } 36 | 37 | private int pow(int a, int b) { 38 | a %= MOD; 39 | int ans = 1; 40 | for (int i = 0; i < b; ++i) { 41 | ans = (ans * a) % MOD; 42 | } 43 | return ans; 44 | } 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /Math/397. Integer Replacement.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a positive integer n and you can do operations as follow: 5 | If n is even, replace n with n/2. 6 | If n is odd, you can replace n with either n + 1 or n - 1. 7 | What is the minimum number of replacements needed for n to become 1? 8 | 9 | Example 1: 10 | Input: 11 | 8 12 | Output: 13 | 3 14 | Explanation: 15 | 8 -> 4 -> 2 -> 1 16 | 17 | Example 2: 18 | Input: 19 | 7 20 | Output: 21 | 4 22 | Explanation: 23 | 7 -> 8 -> 4 -> 2 -> 1 24 | or 25 | 7 -> 6 -> 3 -> 2 -> 1 26 | 27 | */ 28 | 29 | /* 30 | 31 | O(logn),O(logn) 32 | 33 | */ 34 | 35 | public int integerReplacement(int n) { 36 | if (n == 1) return 0; 37 | else if (n % 2 == 0) return 1 + integerReplacement(n / 2); 38 | else return 2 + Math.min(integerReplacement(n / 2 + 1), integerReplacement(n / 2)); 39 | } 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Math/413. Arithmetic Slices.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | A sequence of number is called arithmetic if it consists of at least three elements and 5 | if the difference between any two consecutive elements is the same. 6 | 7 | For example, these are arithmetic sequence: 8 | 1, 3, 5, 7, 9 9 | 7, 7, 7, 7 10 | 3, -1, -5, -9 11 | The following sequence is not arithmetic. 12 | 1, 1, 2, 5, 7 13 | 14 | Example: 15 | A = [1, 2, 3, 4] 16 | return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself. 17 | 18 | */ 19 | 20 | /* 21 | 22 | O(n),O(1) 23 | 24 | */ 25 | 26 | public int numberOfArithmeticSlices(int[] A) { 27 | int n = A.length, ans = 0, cnt = 0; 28 | if (n <= 2) return 0; 29 | for (int i = 2; i < n; ++i) { 30 | if (A[i] - A[i - 1] == A[i - 1] - A[i - 2]) cnt++; 31 | else cnt = 0; 32 | ans += cnt; 33 | } 34 | return ans; 35 | } 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /Math/453. Minimum Moves to Equal Array Elements.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, 5 | where a move is incrementing n - 1 elements by 1. 6 | 7 | Example: 8 | Input: 9 | [1,2,3] 10 | Output: 11 | 3 12 | Explanation: 13 | Only three moves are needed (remember each move increments two elements): 14 | [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4] 15 | 16 | */ 17 | 18 | /* 19 | 20 | Solution: assume use k moves to get the array element equals to x, which is sum+(n-1)*k=n*x 21 | and the minimum element needs to be incremented in each move, which is x=k+min 22 | then sum+(n-1)*k=n*(k+min), which is k=sum-n*min 23 | O(n),O(1) 24 | 25 | */ 26 | 27 | public int minMoves(int[] nums) { 28 | int sum = 0, min = Integer.MAX_VALUE, n = nums.length; 29 | for (int i = 0; i < n; ++i) { 30 | min = Math.min(min, nums[i]); 31 | sum += nums[i]; 32 | } 33 | return sum - n * min; 34 | } 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /Math/458. Poor Pigs.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | There are 1000 buckets, one and only one of them is poisonous, while the rest are filled with water. 5 | They all look identical. If a pig drinks the poison it will die within 15 minutes. 6 | What is the minimum amount of pigs you need to figure out which bucket is poisonous within one hour? 7 | Answer this question, and write an algorithm for the general case. 8 | 9 | General case: 10 | If there are n buckets and a pig drinking poison will die within m minutes, 11 | how many pigs (x) you need to figure out the poisonous bucket within p minutes? There is exactly one bucket with poison. 12 | 13 | */ 14 | 15 | /* 16 | 17 | O(1),O(1) 18 | 19 | */ 20 | 21 | public int poorPigs(int buckets, int minutesToDie, int minutesToTest) { 22 | int attemps = minutesToTest / minutesToDie + 1; 23 | int ans = 0; 24 | while (Math.pow(attemps, ans) < buckets) ans++; 25 | return ans; 26 | } 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /Math/462. Minimum Moves to Equal Array Elements II.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, 5 | where a move is incrementing a selected element by 1 or decrementing a selected element by 1. 6 | You may assume the array's length is at most 10,000. 7 | 8 | Example: 9 | Input: 10 | [1,2,3] 11 | Output: 12 | 2 13 | Explanation: 14 | Only two moves are needed (remember each move increments or decrements one element): 15 | [1,2,3] => [2,2,3] => [2,2,2] 16 | 17 | */ 18 | 19 | /* 20 | 21 | O(nlogn),O(1) 22 | 23 | */ 24 | 25 | public int minMoves2(int[] nums) { 26 | Arrays.sort(nums); 27 | int ans = 0, i = 0, j = nums.length - 1; 28 | while (i < j) { 29 | ans += nums[j] - nums[i]; 30 | i++; 31 | j--; 32 | } 33 | return ans; 34 | } 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /Math/507. Perfect Number.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself. 5 | Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not. 6 | 7 | Example: 8 | Input: 28 9 | Output: True 10 | Explanation: 28 = 1 + 2 + 4 + 7 + 14 11 | 12 | */ 13 | 14 | /* 15 | 16 | O(sqrt(n)),O(1) 17 | 18 | */ 19 | 20 | public boolean checkPerfectNumber(int num) { 21 | if (num == 1) { 22 | return false; 23 | } 24 | int sum = 1; 25 | for (int i = 2; i <= Math.sqrt(num); ++i) { 26 | if (num % i == 0) { 27 | sum += i + num / i; 28 | } 29 | } 30 | return sum == num; 31 | } 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Math/537. Complex Number Multiplication.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given two strings representing two complex numbers. 5 | You need to return a string representing their multiplication. Note i2 = -1 according to the definition. 6 | 7 | Example 1: 8 | Input: "1+1i", "1+1i" 9 | Output: "0+2i" 10 | Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i. 11 | 12 | Example 2: 13 | Input: "1+-1i", "1+-1i" 14 | Output: "0+-2i" 15 | Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i. 16 | 17 | */ 18 | 19 | /* 20 | 21 | O(1),O(1) 22 | 23 | */ 24 | 25 | public String complexNumberMultiply(String a, String b) { 26 | String[] A = a.split("\\+|i"); 27 | String[] B = b.split("\\+|i"); 28 | int realA = Integer.valueOf(A[0]); 29 | int imgA = Integer.valueOf(A[1]); 30 | int realB = Integer.valueOf(B[0]); 31 | int imgB = Integer.valueOf(B[1]); 32 | return (realA * realB - imgA * imgB) + "+" + (realA * imgB + realB * imgA) + "i"; 33 | } 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /Math/593. Valid Square.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given the coordinates of four points in 2D space, return whether the four points could construct a square. 5 | The coordinate (x,y) of a point is represented by an integer array with two integers. 6 | 7 | Example: 8 | Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1] 9 | Output: True 10 | 11 | */ 12 | 13 | /* 14 | 15 | O(1),O(1) 16 | 17 | */ 18 | 19 | public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) { 20 | return check(p1, p2, p3, p4) || check(p1, p3, p2, p4) || check(p1, p2, p4, p3); 21 | } 22 | 23 | private boolean check(int[] tl, int[] tr, int[] br, int[] bl) { 24 | int d1 = dist(tl, tr), d2 = dist(tr, br), d3 = dist(br, bl), d4 = dist(bl, tl); 25 | return d1 > 0 && d1 == d2 && d2 == d3 && d3 == d4 && dist(tl, br) == dist(tr, bl); 26 | } 27 | 28 | private int dist(int[] a, int[] b) { 29 | return (b[0] - a[0]) * (b[0] - a[0]) + (b[1] - a[1]) * (b[1] - a[1]); 30 | } 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /Math/625. Minimum Factorization.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a positive integer a, find the smallest positive integer b whose multiplication of each digit equals to a. 5 | If there is no answer or the answer is not fit in 32-bit signed integer, then return 0. 6 | 7 | Example 1 8 | Input: 9 | 48 10 | Output: 11 | 68 12 | 13 | Example 2 14 | Input: 15 | 15 16 | Output: 17 | 35 18 | 19 | */ 20 | 21 | /* 22 | 23 | O(logn),O(1) 24 | 25 | */ 26 | 27 | public int smallestFactorization(int a) { 28 | if (a < 10) { 29 | return a; 30 | } 31 | long ans = 0; 32 | for (long i = 9, cur = 1; i > 1; --i) { 33 | while (a % i == 0) { 34 | ans += cur * i; 35 | if (ans > Integer.MAX_VALUE) { 36 | return 0; 37 | } 38 | a /= i; 39 | cur *= 10; 40 | } 41 | } 42 | return a == 1 ? (int)ans : 0; 43 | } 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /Math/633. Sum of Square Numbers.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c. 5 | 6 | Example 1: 7 | Input: 5 8 | Output: True 9 | Explanation: 1 * 1 + 2 * 2 = 5 10 | 11 | Example 2: 12 | Input: 3 13 | Output: False 14 | 15 | */ 16 | 17 | /* 18 | 19 | O(sqrt(n)),O(1) 20 | 21 | */ 22 | 23 | public boolean judgeSquareSum(int c) { 24 | int l = 0, r = (int)Math.sqrt(c); 25 | while (l <= r) { 26 | int n = l * l + r * r; 27 | if (n == c) { 28 | return true; 29 | } else if (n > c) { 30 | r--; 31 | } else { 32 | l++; 33 | } 34 | } 35 | return false; 36 | } 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /Math/66. Plus One.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a non-empty array of digits representing a non-negative integer, plus one to the integer. 5 | The digits are stored such that the most significant digit is at the head of the list, 6 | and each element in the array contain a single digit. 7 | You may assume the integer does not contain any leading zero, except the number 0 itself. 8 | 9 | Example 1: 10 | Input: [1,2,3] 11 | Output: [1,2,4] 12 | Explanation: The array represents the integer 123. 13 | 14 | Example 2: 15 | Input: [4,3,2,1] 16 | Output: [4,3,2,2] 17 | Explanation: The array represents the integer 4321. 18 | 19 | */ 20 | 21 | /* 22 | 23 | O(n),O(n) 24 | 25 | */ 26 | 27 | public int[] plusOne(int[] digits) { 28 | int n = digits.length; 29 | for (int i = n - 1; i >= 0; --i) { 30 | if (digits[i] != 9) { 31 | digits[i]++; 32 | return digits; 33 | } else digits[i] = 0; 34 | } 35 | int[] ans = new int[n + 1]; 36 | ans[0] = 1; 37 | return ans; 38 | } 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /Math/660. Remove 9.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Start from integer 1, remove any integer that contains 9 such as 9, 19, 29... 5 | So now, you will have a new integer sequence: 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, ... 6 | Given a positive integer n, you need to return the n-th integer after removing. Note that 1 will be the first integer. 7 | 8 | Example 1: 9 | Input: 9 10 | Output: 10 11 | 12 | */ 13 | 14 | /* 15 | 16 | Solution: 17 | O(logn),O(1) 18 | 19 | */ 20 | 21 | public int newInteger(int n) { 22 | int ans = 0, base = 1; 23 | while (n > 0) { 24 | ans += (n % 9) * base; 25 | base *= 10; 26 | n /= 9; 27 | } 28 | return ans; 29 | } 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /Math/67. Add Binary.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given two binary strings, return their sum (also a binary string). 5 | The input strings are both non-empty and contains only characters 1 or 0. 6 | 7 | Example 1: 8 | Input: a = "11", b = "1" 9 | Output: "100" 10 | 11 | Example 2: 12 | Input: a = "1010", b = "1011" 13 | Output: "10101" 14 | 15 | */ 16 | 17 | /* 18 | 19 | O(n+m),O(1) 20 | 21 | */ 22 | 23 | public String addBinary(String a, String b) { 24 | StringBuilder ans = new StringBuilder(); 25 | int n = a.length(), m = b.length(), sum = 0; 26 | while (n > 0 || m > 0) { 27 | sum /= 2; 28 | if (n > 0) { 29 | sum += a.charAt(n - 1) - '0'; 30 | n--; 31 | } 32 | if (m > 0) { 33 | sum += b.charAt(m - 1) - '0'; 34 | m--; 35 | } 36 | ans.append(sum % 2); 37 | } 38 | if (sum >= 2) ans.append("1"); 39 | return ans.reverse().toString(); 40 | } 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /Math/69. Sqrt(x).java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Implement int sqrt(int x). 5 | Compute and return the square root of x, where x is guaranteed to be a non-negative integer. 6 | Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. 7 | 8 | Example 1: 9 | Input: 4 10 | Output: 2 11 | 12 | Example 2: 13 | Input: 8 14 | Output: 2 15 | Explanation: The square root of 8 is 2.82842..., and since 16 | the decimal part is truncated, 2 is returned. 17 | 18 | */ 19 | 20 | /* 21 | 22 | O(logn),O(1) 23 | 24 | */ 25 | 26 | public int mySqrt(int x) { 27 | int l = 1, r = x; 28 | while (l <= r) { 29 | int mid = (l + r) / 2; 30 | if (x / mid == mid) return mid; 31 | if (x / mid > mid) l = mid + 1; 32 | else r = mid - 1; 33 | } 34 | return r; 35 | } 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Math/7. Reverse Integer.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a 32-bit signed integer, reverse digits of an integer. 5 | 6 | Example 1: 7 | Input: 123 8 | Output: 321 9 | 10 | Example 2: 11 | Input: -123 12 | Output: -321 13 | 14 | Example 3: 15 | Input: 120 16 | Output: 21 17 | 18 | Note: 19 | Assume we are dealing with an environment which could only store integers within the 32-bit signed integer: [−2^31, 2^31 − 1]. 20 | For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. 21 | 22 | */ 23 | 24 | /* 25 | 26 | O(1),O(1) 27 | 28 | */ 29 | 30 | public int reverse(int x) { 31 | int ans = 0; 32 | while (x != 0) { 33 | int mod = x % 10, tmp = ans * 10 + mod; 34 | if ((tmp - mod) / 10 != ans) 35 | return 0; 36 | ans = tmp; 37 | x /= 10; 38 | } 39 | return ans; 40 | } 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /Math/9. Palindrome Number.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. 5 | 6 | Example 1: 7 | Input: 121 8 | Output: true 9 | 10 | Example 2: 11 | Input: -121 12 | Output: false 13 | Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. 14 | 15 | Example 3: 16 | Input: 10 17 | Output: false 18 | Explanation: Reads 01 from right to left. Therefore it is not a palindrome. 19 | 20 | */ 21 | 22 | /* 23 | 24 | O(1),O(1) 25 | 26 | */ 27 | 28 | public boolean isPalindrome(int x) { 29 | if (x != 0 && x % 10 == 0) 30 | return false; 31 | int ans = 0; 32 | while (x > ans) { 33 | ans = ans * 10 + x % 10; 34 | x /= 10; 35 | } 36 | return ans == x || ans / 10 == x; 37 | } 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /Math/942. DI String Match.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a string S that only contains "I" (increase) or "D" (decrease), let N = S.length. 5 | Return any permutation A of [0, 1, ..., N] such that for all i = 0, ..., N-1: 6 | If S[i] == "I", then A[i] < A[i+1] 7 | If S[i] == "D", then A[i] > A[i+1] 8 | 9 | Example 1: 10 | Input: "IDID" 11 | Output: [0,4,1,3,2] 12 | 13 | Example 2: 14 | Input: "III" 15 | Output: [0,1,2,3] 16 | 17 | Example 3: 18 | Input: "DDI" 19 | Output: [3,2,0,1] 20 | 21 | */ 22 | 23 | /* 24 | 25 | O(n),O(n) 26 | 27 | */ 28 | 29 | public int[] diStringMatch(String S) { 30 | int n = S.length(), l = 0, r = n; 31 | int[] ans = new int[n + 1]; 32 | for (int i = 0; i < n; ++i) { 33 | ans[i] = S.charAt(i) == 'I' ? l++ : r--; 34 | } 35 | ans[n] = l; 36 | return ans; 37 | } 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /Math/976. Largest Perimeter Triangle.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array A of positive lengths, return the largest perimeter of a triangle with non-zero area, 5 | formed from 3 of these lengths. 6 | If it is impossible to form any triangle of non-zero area, return 0. 7 | 8 | Example 1: 9 | Input: [2,1,2] 10 | Output: 5 11 | 12 | Example 2: 13 | Input: [1,2,1] 14 | Output: 0 15 | 16 | Example 3: 17 | Input: [3,2,3,4] 18 | Output: 10 19 | 20 | Example 4: 21 | Input: [3,6,2,3] 22 | Output: 8 23 | 24 | */ 25 | 26 | /* 27 | 28 | O(nlogn),O(1) 29 | 30 | */ 31 | 32 | public int largestPerimeter(int[] A) { 33 | Arrays.sort(A); 34 | for (int i = A.length - 1; i >= 2; --i) { 35 | if (A[i] < A[i - 1] + A[i - 2]) { 36 | return A[i] + A[i - 1] + A[i - 2]; 37 | } 38 | } 39 | return 0; 40 | } 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /MySQL/175. Combine Two Tables.sql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Table: Person 5 | +-------------+---------+ 6 | | Column Name | Type | 7 | +-------------+---------+ 8 | | PersonId | int | 9 | | FirstName | varchar | 10 | | LastName | varchar | 11 | +-------------+---------+ 12 | PersonId is the primary key column for this table. 13 | Table: Address 14 | +-------------+---------+ 15 | | Column Name | Type | 16 | +-------------+---------+ 17 | | AddressId | int | 18 | | PersonId | int | 19 | | City | varchar | 20 | | State | varchar | 21 | +-------------+---------+ 22 | AddressId is the primary key column for this table. 23 | 24 | Write a SQL query for a report that provides the following information for each person in the Person table, 25 | regardless if there is an address for each of those people: 26 | FirstName, LastName, City, State 27 | 28 | */ 29 | 30 | SELECT p.FirstName, p.LastName, a.City, a.State 31 | FROM Person as p 32 | LEFT JOIN Address as a 33 | ON p.PersonId=a.PersonId 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /MySQL/176. Second Highest Salary.sql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Write a SQL query to get the second highest salary from the Employee table. 5 | +----+--------+ 6 | | Id | Salary | 7 | +----+--------+ 8 | | 1 | 100 | 9 | | 2 | 200 | 10 | | 3 | 300 | 11 | +----+--------+ 12 | For example, given the above Employee table, the query should return 200 as the second highest salary. 13 | If there is no second highest salary, then the query should return null. 14 | +---------------------+ 15 | | SecondHighestSalary | 16 | +---------------------+ 17 | | 200 | 18 | +---------------------+ 19 | 20 | */ 21 | 22 | /* 23 | 24 | LIMIT a OFFSET b = LIMIT b, a, which means fetch a records and begin with (b+1)th record 25 | 26 | */ 27 | 28 | SELECT IFNULL( 29 | (SELECT DISTINCT Salary FROM Employee 30 | ORDER BY Salary DESC LIMIT 1, 1), NULL) 31 | AS SecondHighestSalary 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /MySQL/177. Nth Highest Salary.sql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Write a SQL query to get the nth highest salary from the Employee table. 5 | +----+--------+ 6 | | Id | Salary | 7 | +----+--------+ 8 | | 1 | 100 | 9 | | 2 | 200 | 10 | | 3 | 300 | 11 | +----+--------+ 12 | For example, given the above Employee table, the nth highest salary where n = 2 is 200. 13 | If there is no nth highest salary, then the query should return null. 14 | +------------------------+ 15 | | getNthHighestSalary(2) | 16 | +------------------------+ 17 | | 200 | 18 | +------------------------+ 19 | 20 | */ 21 | 22 | CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT 23 | BEGIN 24 | SET N = N - 1; 25 | RETURN ( 26 | # Write your MySQL query statement below. 27 | SELECT IFNULL( 28 | (SELECT DISTINCT Salary FROM Employee 29 | ORDER BY Salary DESC LIMIT N, 1), NULL) 30 | ); 31 | END 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /MySQL/180. Consecutive Numbers.sql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Write a SQL query to find all numbers that appear at least three times consecutively. 5 | +----+-----+ 6 | | Id | Num | 7 | +----+-----+ 8 | | 1 | 1 | 9 | | 2 | 1 | 10 | | 3 | 1 | 11 | | 4 | 2 | 12 | | 5 | 1 | 13 | | 6 | 2 | 14 | | 7 | 2 | 15 | +----+-----+ 16 | For example, given the above Logs table, 1 is the only number that appears consecutively for at least three times. 17 | +-----------------+ 18 | | ConsecutiveNums | 19 | +-----------------+ 20 | | 1 | 21 | +-----------------+ 22 | 23 | */ 24 | 25 | SELECT DISTINCT l1.Num AS ConsecutiveNums 26 | FROM Logs l1, Logs l2, Logs l3 27 | WHERE l1.Id = l2.Id - 1 AND l2.Id = l3.Id - 1 28 | AND l1.Num = l2.Num AND l2.Num = l3.Num 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /MySQL/181. Employee Earning More Than Their Manager.sql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | The Employee table holds all employees including their managers. 5 | Every employee has an Id, and there is also a column for the manager Id. 6 | +----+-------+--------+-----------+ 7 | | Id | Name | Salary | ManagerId | 8 | +----+-------+--------+-----------+ 9 | | 1 | Joe | 70000 | 3 | 10 | | 2 | Henry | 80000 | 4 | 11 | | 3 | Sam | 60000 | NULL | 12 | | 4 | Max | 90000 | NULL | 13 | +----+-------+--------+-----------+ 14 | Given the Employee table, write a SQL query that finds out employees who earn more than their managers. 15 | For the above table, Joe is the only employee who earns more than his manager. 16 | +----------+ 17 | | Employee | 18 | +----------+ 19 | | Joe | 20 | +----------+ 21 | 22 | */ 23 | 24 | SELECT E1.Name AS Employee 25 | FROM Employee E1, Employee E2 26 | WHERE E1.ManagerId = E2.Id AND E1.Salary > E2.Salary 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /MySQL/182. Duplicate Emails.sql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Write a SQL query to find all duplicate emails in a table named Person. 5 | +----+---------+ 6 | | Id | Email | 7 | +----+---------+ 8 | | 1 | a@b.com | 9 | | 2 | c@d.com | 10 | | 3 | a@b.com | 11 | +----+---------+ 12 | For example, your query should return the following for the above table: 13 | +---------+ 14 | | Email | 15 | +---------+ 16 | | a@b.com | 17 | +---------+ 18 | 19 | */ 20 | 21 | /* 22 | 23 | HAVING clause must follow GROUP BY clause as a condition check 24 | 25 | */ 26 | 27 | SELECT Email FROM Person 28 | GROUP BY Email 29 | HAVING COUNT(id) > 1 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /MySQL/183. Customers Who Never Order.sql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Suppose that a website contains two tables, the Customers table and the Orders table. 5 | Write a SQL query to find all customers who never order anything. 6 | 7 | Table: Customers. 8 | +----+-------+ 9 | | Id | Name | 10 | +----+-------+ 11 | | 1 | Joe | 12 | | 2 | Henry | 13 | | 3 | Sam | 14 | | 4 | Max | 15 | +----+-------+ 16 | Table: Orders. 17 | +----+------------+ 18 | | Id | CustomerId | 19 | +----+------------+ 20 | | 1 | 3 | 21 | | 2 | 1 | 22 | +----+------------+ 23 | Using the above tables as example, return the following: 24 | +-----------+ 25 | | Customers | 26 | +-----------+ 27 | | Henry | 28 | | Max | 29 | +-----------+ 30 | 31 | */ 32 | 33 | SELECT c.Name AS Customers 34 | FROM Customers AS c 35 | WHERE c.Id NOT IN 36 | (SELECT o.CustomerId 37 | FROM Orders AS o) 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /MySQL/196. Delete Duplicate Emails.sql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Write a SQL query to delete all duplicate email entries in a table named Person, 5 | keeping only unique emails based on its smallest Id. 6 | +----+------------------+ 7 | | Id | Email | 8 | +----+------------------+ 9 | | 1 | john@example.com | 10 | | 2 | bob@example.com | 11 | | 3 | john@example.com | 12 | +----+------------------+ 13 | Id is the primary key column for this table. 14 | For example, after running your query, the above Person table should have the following rows: 15 | +----+------------------+ 16 | | Id | Email | 17 | +----+------------------+ 18 | | 1 | john@example.com | 19 | | 2 | bob@example.com | 20 | +----+------------------+ 21 | 22 | Note: 23 | Your output is the whole Person table after executing your sql. Use delete statement. 24 | 25 | */ 26 | 27 | DELETE P2 28 | FROM Person P1, Person P2 29 | WHERE P1.Email = P2.Email 30 | AND P1.Id < P2.Id 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /MySQL/197. Rising Temperature.sql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a Weather table, write a SQL query to find all dates' Ids with higher temperature 5 | compared to its previous (yesterday's) dates. 6 | +---------+------------------+------------------+ 7 | | Id(INT) | RecordDate(DATE) | Temperature(INT) | 8 | +---------+------------------+------------------+ 9 | | 1 | 2015-01-01 | 10 | 10 | | 2 | 2015-01-02 | 25 | 11 | | 3 | 2015-01-03 | 20 | 12 | | 4 | 2015-01-04 | 30 | 13 | +---------+------------------+------------------+ 14 | For example, return the following Ids for the above Weather table: 15 | +----+ 16 | | Id | 17 | +----+ 18 | | 2 | 19 | | 4 | 20 | +----+ 21 | 22 | */ 23 | 24 | /* 25 | 26 | TO_DAYS(x.DATE): return the number of days between from year 0 to date DATE 27 | 28 | */ 29 | 30 | SELECT W2.Id 31 | FROM Weather W1, Weather W2 32 | WHERE W1.Temperature < W2.Temperature 33 | AND TO_DAYS(W1.RecordDate) = TO_DAYS(W2.RecordDate) - 1 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /MySQL/570. Managers with at Least 5 Direct Reports.sql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | The Employee table holds all employees including their managers. 5 | Every employee has an Id, and there is also a column for the manager Id. 6 | +------+----------+-----------+----------+ 7 | |Id |Name |Department |ManagerId | 8 | +------+----------+-----------+----------+ 9 | |101 |John |A |null | 10 | |102 |Dan |A |101 | 11 | |103 |James |A |101 | 12 | |104 |Amy |A |101 | 13 | |105 |Anne |A |101 | 14 | |106 |Ron |B |101 | 15 | +------+----------+-----------+----------+ 16 | 17 | Given the Employee table, write a SQL query that finds out managers with at least 5 direct report. 18 | For the above table, your SQL query should return: 19 | +-------+ 20 | | Name | 21 | +-------+ 22 | | John | 23 | +-------+ 24 | 25 | */ 26 | 27 | SELECT Name FROM Employee 28 | WHERE id IN 29 | (SELECT ManagerId FROM Employee 30 | GROUP BY ManagerId 31 | HAVING COUNT(ManagerId) >= 5) 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /MySQL/571. Find Median Given Frequency of Numbers.sql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | The Numbers table keeps the value of number and its frequency. 5 | +----------+-------------+ 6 | | Number | Frequency | 7 | +----------+-------------| 8 | | 0 | 7 | 9 | | 1 | 1 | 10 | | 2 | 3 | 11 | | 3 | 1 | 12 | +----------+-------------+ 13 | In this table, the numbers are 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 3, so the median is (0 + 0) / 2 = 0. 14 | +--------+ 15 | | median | 16 | +--------| 17 | | 0.0000 | 18 | +--------+ 19 | Write a query to find the median of all numbers and name the result as median. 20 | 21 | */ 22 | 23 | SELECT AVG(n.Number) AS median 24 | FROM Numbers n 25 | WHERE n.Frequency >= ABS((SELECT SUM(Frequency) FROM Numbers WHERE Number <= n.Number) - 26 | (SELECT SUM(Frequency) FROM Numbers WHERE Number >= n.Number)) 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /MySQL/574. Winning Candidate.sql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Table: Candidate 5 | +-----+---------+ 6 | | id | Name | 7 | +-----+---------+ 8 | | 1 | A | 9 | | 2 | B | 10 | | 3 | C | 11 | | 4 | D | 12 | | 5 | E | 13 | +-----+---------+ 14 | Table: Vote 15 | +-----+--------------+ 16 | | id | CandidateId | 17 | +-----+--------------+ 18 | | 1 | 2 | 19 | | 2 | 4 | 20 | | 3 | 3 | 21 | | 4 | 2 | 22 | | 5 | 5 | 23 | +-----+--------------+ 24 | id is the auto-increment primary key, 25 | CandidateId is the id appeared in Candidate table. 26 | Write a sql to find the name of the winning candidate, the above example will return the winner B. 27 | +------+ 28 | | Name | 29 | +------+ 30 | | B | 31 | +------+ 32 | 33 | */ 34 | 35 | SELECT C.Name FROM Candidate C 36 | WHERE id = (SELECT CandidateId FROM Vote GROUP BY CandidateId ORDER BY COUNT(id) DESC LIMIT 1) 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /MySQL/584. Find Customer Referee.sql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a table customer holding customers information and the referee. 5 | +------+------+-----------+ 6 | | id | name | referee_id| 7 | +------+------+-----------+ 8 | | 1 | Will | NULL | 9 | | 2 | Jane | NULL | 10 | | 3 | Alex | 2 | 11 | | 4 | Bill | NULL | 12 | | 5 | Zack | 1 | 13 | | 6 | Mark | 2 | 14 | +------+------+-----------+ 15 | 16 | Write a query to return the list of customers NOT referred by the person with id '2'. 17 | For the sample data above, the result is: 18 | +------+ 19 | | name | 20 | +------+ 21 | | Will | 22 | | Jane | 23 | | Bill | 24 | | Zack | 25 | +------+ 26 | 27 | */ 28 | 29 | SELECT name FROM customer 30 | WHERE referee_id <> 2 OR referee_id IS NULL 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /MySQL/596. Classes More Than 5 Students.sql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | There is a table courses with columns: student and class 5 | Please list out all classes which have more than or equal to 5 students. 6 | 7 | For example, the table: 8 | +---------+------------+ 9 | | student | class | 10 | +---------+------------+ 11 | | A | Math | 12 | | B | English | 13 | | C | Math | 14 | | D | Biology | 15 | | E | Math | 16 | | F | Computer | 17 | | G | Math | 18 | | H | Math | 19 | | I | Math | 20 | +---------+------------+ 21 | Should output: 22 | +---------+ 23 | | class | 24 | +---------+ 25 | | Math | 26 | +---------+ 27 | 28 | */ 29 | 30 | SELECT class FROM courses 31 | GROUP BY class 32 | HAVING COUNT(DISTINCT student) >= 5 33 | 34 | 35 | -------------------------------------------------------------------------------- /MySQL/603. Consecutive Available Seats.sql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Several friends at a cinema ticket office would like to reserve consecutive available seats. 5 | Can you help to query all the consecutive available seats order by the seat_id using the following cinema table? 6 | | seat_id | free | 7 | |---------|------| 8 | | 1 | 1 | 9 | | 2 | 0 | 10 | | 3 | 1 | 11 | | 4 | 1 | 12 | | 5 | 1 | 13 | Your query should return the following result for the sample case above. 14 | | seat_id | 15 | |---------| 16 | | 3 | 17 | | 4 | 18 | | 5 | 19 | 20 | */ 21 | 22 | SELECT DISTINCT c1.seat_id FROM cinema c1, cinema c2 23 | WHERE c1.free = 1 AND c2.free = 1 AND ABS(c1.seat_id - c2.seat_id) = 1 24 | ORDER BY c1.seat_id 25 | 26 | 27 | -------------------------------------------------------------------------------- /MySQL/608. Tree Node.sql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a table tree, id is identifier of the tree node and p_id is its parent node's id. 5 | +----+------+ 6 | | id | p_id | 7 | +----+------+ 8 | | 1 | null | 9 | | 2 | 1 | 10 | | 3 | 1 | 11 | | 4 | 2 | 12 | | 5 | 2 | 13 | +----+------+ 14 | Each node in the tree can be one of three types: 15 | Leaf: if the node is a leaf node. 16 | Root: if the node is the root of the tree. 17 | Inner: If the node is neither a leaf node nor a root node. 18 | Write a query to print the node id and the type of the node. Sort your output by the node id. 19 | 20 | The result for the above sample is: 21 | +----+------+ 22 | | id | Type | 23 | +----+------+ 24 | | 1 | Root | 25 | | 2 | Inner| 26 | | 3 | Leaf | 27 | | 4 | Leaf | 28 | | 5 | Leaf | 29 | +----+------+ 30 | 31 | */ 32 | 33 | SELECT t.id, 34 | IF(ISNULL(t.p_id), 'Root', IF(t.id IN (SELECT p_id FROM tree), 'Inner', 'Leaf')) AS Type 35 | FROM tree t 36 | 37 | 38 | -------------------------------------------------------------------------------- /MySQL/610. Triangle Judgement.sql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | A pupil Tim gets homework to identify whether three line segments could possibly form a triangle. 5 | However, this assignment is very heavy because there are hundreds of records to calculate. 6 | Could you help Tim by writing a query to judge whether these three sides can form a triangle, 7 | assuming table triangle holds the length of the three sides x, y and z. 8 | | x | y | z | 9 | |----|----|----| 10 | | 13 | 15 | 30 | 11 | | 10 | 20 | 15 | 12 | 13 | For the sample data above, your query should return the follow result: 14 | | x | y | z | triangle | 15 | |----|----|----|----------| 16 | | 13 | 15 | 30 | No | 17 | | 10 | 20 | 15 | Yes | 18 | 19 | */ 20 | 21 | SELECT *, IF(x + y > z AND x + z > y AND y + z > x, 'Yes', 'No') AS triangle FROM triangle 22 | 23 | 24 | -------------------------------------------------------------------------------- /MySQL/612. Shortest Distance in a Plane.sql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Table point_2d holds the coordinates (x,y) of some unique points (more than two) in a plane. 5 | Write a query to find the shortest distance between these points rounded to 2 decimals. 6 | 7 | | x | y | 8 | |----|----| 9 | | -1 | -1 | 10 | | 0 | 0 | 11 | | -1 | -2 | 12 | The shortest distance is 1.00 from point (-1,-1) to (-1,2). So the output should be: 13 | | shortest | 14 | |----------| 15 | | 1.00 | 16 | 17 | */ 18 | 19 | SELECT ROUND(SQRT(MIN((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y))), 2) AS shortest 20 | FROM point_2d p1, point_2d p2 21 | WHERE p1.x <> p2.x OR p1.y <> p2.y 22 | 23 | 24 | -------------------------------------------------------------------------------- /MySQL/613. Shortest Distance in a Line.sql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Table point holds the x coordinate of some points on x-axis in a plane, which are all integers. 5 | Write a query to find the shortest distance between two points in these points. 6 | 7 | | x | 8 | |-----| 9 | | -1 | 10 | | 0 | 11 | | 2 | 12 | The shortest distance is '1' obviously, which is from point '-1' to '0'. So the output is as below: 13 | | shortest| 14 | |---------| 15 | | 1 | 16 | 17 | */ 18 | 19 | SELECT MIN(ABS(p1.x - p2.x)) AS shortest 20 | FROM point p1, point p2 21 | WHERE p1.x <> p2.x 22 | 23 | 24 | -------------------------------------------------------------------------------- /MySQL/614. Second Degree Follower.sql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | In facebook, there is a follow table with two columns: followee, follower. 5 | Please write a sql query to get the amount of each follower’s follower if he/she has one. 6 | 7 | For example: 8 | +-------------+------------+ 9 | | followee | follower | 10 | +-------------+------------+ 11 | | A | B | 12 | | B | C | 13 | | B | D | 14 | | D | E | 15 | +-------------+------------+ 16 | should output: 17 | +-------------+------------+ 18 | | follower | num | 19 | +-------------+------------+ 20 | | B | 2 | 21 | | D | 1 | 22 | +-------------+------------+ 23 | 24 | */ 25 | 26 | SELECT DISTINCT follower, num 27 | FROM follow, 28 | (SELECT followee, COUNT(DISTINCT follower) AS num FROM follow 29 | GROUP BY followee) as tmp 30 | WHERE follower = tmp.followee 31 | ORDER BY follower 32 | 33 | 34 | -------------------------------------------------------------------------------- /MySQL/619. Biggest Single Number.sql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Table my_numbers contains many numbers in column num including duplicated ones. 5 | Can you write a SQL query to find the biggest number, which only appears once. 6 | +---+ 7 | |num| 8 | +---+ 9 | | 8 | 10 | | 8 | 11 | | 3 | 12 | | 3 | 13 | | 1 | 14 | | 4 | 15 | | 5 | 16 | | 6 | 17 | For the sample data above, your query should return the following result: 18 | +---+ 19 | |num| 20 | +---+ 21 | | 6 | 22 | 23 | */ 24 | 25 | SELECT ( 26 | SELECT num FROM my_numbers 27 | GROUP BY num 28 | HAVING COUNT(*) = 1 29 | ORDER BY num DESC LIMIT 1 30 | ) AS num 31 | 32 | 33 | -------------------------------------------------------------------------------- /MySQL/627. Swap Salary.sql: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a table salary, such as the one below, that has m=male and f=female values. 5 | Swap all f and m values (i.e., change all f values to m and vice versa) with a single update statement 6 | and no intermediate temp table. 7 | Note that you must write a single update statement, DO NOT write any select statement for this problem. 8 | 9 | Example: 10 | | id | name | sex | salary | 11 | |----|------|-----|--------| 12 | | 1 | A | m | 2500 | 13 | | 2 | B | f | 1500 | 14 | | 3 | C | m | 5500 | 15 | | 4 | D | f | 500 | 16 | After running your update statement, the above salary table should have the following rows: 17 | | id | name | sex | salary | 18 | |----|------|-----|--------| 19 | | 1 | A | f | 2500 | 20 | | 2 | B | m | 1500 | 21 | | 3 | C | f | 5500 | 22 | | 4 | D | m | 500 | 23 | 24 | */ 25 | 26 | UPDATE salary 27 | SET sex = IF(sex = 'm', 'f', 'm') 28 | 29 | 30 | -------------------------------------------------------------------------------- /Other/386. Lexicographical Numbers.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an integer n, return 1 - n in lexicographical order. 5 | For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9]. 6 | Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000. 7 | 8 | */ 9 | 10 | /* 11 | 12 | O(10^n),O(n) where n is the number of digits not the number itself 13 | 14 | */ 15 | 16 | public List lexicalOrder(int n) { 17 | List ans = new ArrayList<>(); 18 | for (int i = 1; i < 10; ++i) dfs(ans, i, n); 19 | return ans; 20 | } 21 | 22 | private void dfs(List ans, int cur, int n) { 23 | if (cur > n) return; 24 | ans.add(cur); 25 | for (int i = 0; i < 10; ++i) dfs(ans, cur * 10 + i, n); 26 | } 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /Other/479. Largest Palindrome Product.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Find the largest palindrome made from the product of two n-digit numbers. 5 | Since the result could be very large, you should return the largest palindrome mod 1337. 6 | 7 | Example: 8 | Input: 2 9 | Output: 987 10 | Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 11 | 12 | */ 13 | 14 | /* 15 | 16 | O(10^n),O(1) 17 | 18 | */ 19 | 20 | public int largestPalindrome(int n) { 21 | long max = (long)Math.pow(10, n) - 1, min = max / 10 + 1; 22 | for (long left = max; left >= min; --left) { 23 | long target = buildPalindrome(left + ""); 24 | for (long i = max; i * i >= target; --i) { 25 | if (target % i == 0) { 26 | return (int)(target % 1337); 27 | } 28 | } 29 | } 30 | return 9; 31 | } 32 | 33 | private long buildPalindrome(String left) { 34 | String right = ""; 35 | for (char c : left.toCharArray()) { 36 | right = c + right; 37 | } 38 | return Long.valueOf(left + right); 39 | } 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Other/504. Base 7.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an integer, return its base 7 string representation. 5 | 6 | Example 1: 7 | Input: 100 8 | Output: "202" 9 | 10 | Example 2: 11 | Input: -7 12 | Output: "-10" 13 | 14 | */ 15 | 16 | /* 17 | 18 | O(logn),O(1) 19 | 20 | */ 21 | 22 | public String convertToBase7(int num) { 23 | if (num < 0) { 24 | return "-" + convertToBase7(-num); 25 | } 26 | if (num < 7) { 27 | return String.valueOf(num); 28 | } 29 | return convertToBase7(num / 7) + num % 7; 30 | } 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Queue/346. Moving Average from Data Stream.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. 5 | 6 | Example: 7 | MovingAverage m = new MovingAverage(3); 8 | m.next(1) = 1 9 | m.next(10) = (1 + 10) / 2 10 | m.next(3) = (1 + 10 + 3) / 3 11 | m.next(5) = (10 + 3 + 5) / 3 12 | 13 | */ 14 | 15 | /* 16 | 17 | O(1),O(n) 18 | 19 | */ 20 | 21 | class MovingAverage { 22 | 23 | private Deque deque; 24 | private int size; 25 | private int sum; 26 | 27 | /** Initialize your data structure here. */ 28 | public MovingAverage(int size) { 29 | this.deque = new LinkedList<>(); 30 | this.size = size; 31 | this.sum = 0; 32 | } 33 | 34 | public double next(int val) { 35 | deque.offerLast(val); 36 | sum += val; 37 | if (deque.size() > size) sum -= deque.pollFirst(); 38 | return sum * 1.0 / deque.size(); 39 | } 40 | } 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /Sliding Window/159. Longest Substring with At Most Two Distinct Characters.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a string s , find the length of the longest substring t that contains at most 2 distinct characters. 5 | 6 | Example 1: 7 | Input: "eceba" 8 | Output: 3 9 | Explanation: t is "ece" which its length is 3. 10 | 11 | Example 2: 12 | Input: "ccaabbb" 13 | Output: 5 14 | Explanation: t is "aabbb" which its length is 5. 15 | 16 | */ 17 | 18 | /* 19 | 20 | O(n),O(1) 21 | 22 | */ 23 | 24 | public int lengthOfLongestSubstringTwoDistinct(String s) { 25 | int[] buckets = new int[128]; 26 | int ans = 0, cnt = 0; 27 | for (int i = 0, j = 0; j < s.length(); ++j) { 28 | char right = s.charAt(j); 29 | if (buckets[right] == 0) cnt++; 30 | buckets[right]++; 31 | while (cnt > 2) { 32 | char left = s.charAt(i); 33 | buckets[left]--; 34 | if (buckets[left] == 0) cnt--; 35 | i++; 36 | } 37 | ans = Math.max(ans, j - i + 1); 38 | } 39 | return ans; 40 | } 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /Sliding Window/567. Permutation in String.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. 5 | In other words, one of the first string's permutations is the substring of the second string. 6 | 7 | Example 1: 8 | Input: s1 = "ab" s2 = "eidbaooo" 9 | Output: True 10 | Explanation: s2 contains one permutation of s1 ("ba"). 11 | 12 | Example 2: 13 | Input:s1= "ab" s2 = "eidboaoo" 14 | Output: False 15 | 16 | */ 17 | 18 | /* 19 | 20 | O(n),O(1) 21 | 22 | */ 23 | 24 | public boolean checkInclusion(String s1, String s2) { 25 | int[] buckets = new int[128]; 26 | for (char c : s1.toCharArray()) { 27 | buckets[c]++; 28 | } 29 | for (int i = 0, j = 0; j < s2.length(); ++j) { 30 | buckets[s2.charAt(j)]--; 31 | while (buckets[s2.charAt(j)] < 0) { 32 | buckets[s2.charAt(i)]++; 33 | i++; 34 | } 35 | if (j - i + 1 == s1.length()) { 36 | return true; 37 | } 38 | } 39 | return false; 40 | } 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /Sort/252. Meeting Rooms.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), 5 | determine if a person could attend all meetings. 6 | 7 | Example 1: 8 | Input: [[0,30],[5,10],[15,20]] 9 | Output: false 10 | 11 | Example 2: 12 | Input: [[7,10],[2,4]] 13 | Output: true 14 | 15 | */ 16 | 17 | /* 18 | 19 | O(nlogn),O(1) 20 | 21 | */ 22 | 23 | public boolean canAttendMeetings(Interval[] intervals) { 24 | Arrays.sort(intervals, (a, b) -> a.start - b.start); 25 | for (int i = 1; i < intervals.length; ++i) { 26 | if (intervals[i].start < intervals[i - 1].end) return false; 27 | } 28 | return true; 29 | } 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /Sort/324. Wiggle Sort II.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... 5 | 6 | Example 1: 7 | Input: nums = [1, 5, 1, 1, 6, 4] 8 | Output: One possible answer is [1, 4, 1, 5, 1, 6]. 9 | 10 | Example 2: 11 | Input: nums = [1, 3, 2, 2, 3, 1] 12 | Output: One possible answer is [2, 3, 1, 3, 1, 2]. 13 | 14 | */ 15 | 16 | /* 17 | 18 | Solution 1: sort the array and find the middle element, reorder to get wiggle sort 19 | O(nlogn),O(n) 20 | 21 | */ 22 | 23 | public void wiggleSort(int[] nums) { 24 | Arrays.sort(nums); 25 | int n = nums.length, mid = n % 2 == 0 ? n / 2 - 1 : n / 2; 26 | int[] tmp = Arrays.copyOf(nums, n); 27 | int idx = 0; 28 | for (int i = 0; i <= mid; ++i) { 29 | nums[idx] = tmp[mid - i]; 30 | if (idx + 1 < n) nums[idx + 1] = tmp[n - i - 1]; 31 | idx += 2; 32 | } 33 | } 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /Sort/912. Sort an Array.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array of integers nums, sort the array in ascending order. 5 | 6 | Example 1: 7 | Input: [5,2,3,1] 8 | Output: [1,2,3,5] 9 | 10 | Example 2: 11 | Input: [5,1,1,2,0,0] 12 | Output: [0,0,1,1,2,5] 13 | 14 | */ 15 | 16 | /* 17 | 18 | Solution: O(nlogn),O(n) 19 | 20 | */ 21 | 22 | public int[] sortArray(int[] nums) { 23 | Arrays.sort(nums); 24 | return nums; 25 | } 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /Stack/739. Daily Temperatures.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a list of daily temperatures T, return a list such that, 5 | for each day in the input, tells you how many days you would have to wait until a warmer temperature. 6 | If there is no future day for which this is possible, put 0 instead. 7 | 8 | For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0]. 9 | 10 | */ 11 | 12 | /* 13 | 14 | O(n),O(n) 15 | 16 | */ 17 | 18 | public int[] dailyTemperatures(int[] T) { 19 | int n = T.length; 20 | int[] ans = new int[n]; 21 | Deque deque = new ArrayDeque<>(); 22 | for (int i = 0; i < n; ++i) { 23 | while (!deque.isEmpty() && T[i] > T[deque.peekLast()]) { 24 | int prev = deque.pollLast(); 25 | ans[prev] = i - prev; 26 | } 27 | deque.offerLast(i); 28 | } 29 | return ans; 30 | } 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /Stack/856. Score of Parentheses.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a balanced parentheses string S, compute the score of the string based on the following rule: 5 | () has score 1 6 | AB has score A + B, where A and B are balanced parentheses strings. 7 | (A) has score 2 * A, where A is a balanced parentheses string. 8 | 9 | Example 1: 10 | Input: "()" 11 | Output: 1 12 | 13 | Example 2: 14 | Input: "(())" 15 | Output: 2 16 | 17 | Example 3: 18 | Input: "()()" 19 | Output: 2 20 | 21 | Example 4: 22 | Input: "(()(()))" 23 | Output: 6 24 | 25 | */ 26 | 27 | /* 28 | 29 | O(n),O(n) 30 | 31 | */ 32 | 33 | public int scoreOfParentheses(String S) { 34 | int ans = 0; 35 | Deque deque = new ArrayDeque<>(); 36 | for (char c : S.toCharArray()) { 37 | if (c == '(') { 38 | deque.offerLast(ans); 39 | ans = 0; 40 | } else { 41 | ans = deque.pollLast() + Math.max(2 * ans, 1); 42 | } 43 | } 44 | return ans; 45 | } 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /String/1016. Binary String With Substrings Representing 1 To N.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a binary string S (a string consisting only of '0' and '1's) and a positive integer N, 5 | return true if and only if for every integer X from 1 to N, the binary representation of X is a substring of S. 6 | 7 | Example 1: 8 | Input: S = "0110", N = 3 9 | Output: true 10 | 11 | Example 2: 12 | Input: S = "0110", N = 4 13 | Output: false 14 | 15 | */ 16 | 17 | /* 18 | 19 | O(nm),O(1) 20 | 21 | */ 22 | 23 | public boolean queryString(String S, int N) { 24 | for (int i = N; i > 1; --i) { 25 | if (!S.contains(Integer.toBinaryString(i))) { 26 | return false; 27 | } 28 | } 29 | return true; 30 | } 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /String/1071. Greatest Common Divisor of Strings.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | For strings S and T, we say "T divides S" if and only if S = T + ... + T (T concatenated with itself 1 or more times) 5 | Return the largest string X such that X divides str1 and X divides str2. 6 | 7 | Example 1: 8 | Input: str1 = "ABCABC", str2 = "ABC" 9 | Output: "ABC" 10 | 11 | Example 2: 12 | Input: str1 = "ABABAB", str2 = "ABAB" 13 | Output: "AB" 14 | 15 | Example 3: 16 | Input: str1 = "LEET", str2 = "CODE" 17 | Output: "" 18 | 19 | */ 20 | 21 | /* 22 | 23 | O(n^2),O(1) 24 | 25 | */ 26 | 27 | public String gcdOfStrings(String str1, String str2) { 28 | int n = str1.length(), m = str2.length(); 29 | if (n < m) { 30 | return gcdOfStrings(str2, str1); 31 | } 32 | if (!str1.startsWith(str2)) { 33 | return ""; 34 | } 35 | if (m == 0) { 36 | return str1; 37 | } 38 | return gcdOfStrings(str1.substring(str2.length()), str2); 39 | } 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /String/1078. Occurrences After Bigram.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given words first and second, consider occurrences in some text of the form "first second third", 5 | where second comes immediately after first, and third comes immediately after second. 6 | For each such occurrence, add "third" to the answer, and return the answer. 7 | 8 | Example 1: 9 | Input: text = "alice is a good girl she is a good student", first = "a", second = "good" 10 | Output: ["girl","student"] 11 | 12 | Example 2: 13 | Input: text = "we will we will rock you", first = "we", second = "will" 14 | Output: ["we","rock"] 15 | 16 | */ 17 | 18 | /* 19 | 20 | O(n),O(n) 21 | 22 | */ 23 | 24 | public String[] findOcurrences(String text, String first, String second) { 25 | String[] words = text.split("\\s+"); 26 | List ans = new ArrayList<>(); 27 | for (int i = 2; i < words.length; ++i) { 28 | if (first.equals(words[i - 2]) && second.equals(words[i - 1])) { 29 | ans.add(words[i]); 30 | } 31 | } 32 | return ans.toArray(new String[0]); 33 | } 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /String/1108. Defanging an IP Address.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a valid (IPv4) IP address, return a defanged version of that IP address. 5 | A defanged IP address replaces every period "." with "[.]". 6 | 7 | Example 1: 8 | Input: address = "1.1.1.1" 9 | Output: "1[.]1[.]1[.]1" 10 | 11 | Example 2: 12 | Input: address = "255.100.50.0" 13 | Output: "255[.]100[.]50[.]0" 14 | 15 | */ 16 | 17 | /* 18 | 19 | O(1),O(1) 20 | 21 | */ 22 | 23 | public String defangIPaddr(String address) { 24 | String[] ips = address.split("\\."); 25 | StringBuilder ans = new StringBuilder(); 26 | for (String ip : ips) { 27 | ans.append(ip).append("[.]"); 28 | } 29 | ans.setLength(ans.length() - 3); 30 | return ans.toString(); 31 | } 32 | 33 | 34 | -------------------------------------------------------------------------------- /String/1119. Remove Vowels from a String.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a string S, remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and return the new string. 5 | 6 | Example 1: 7 | Input: "leetcodeisacommunityforcoders" 8 | Output: "ltcdscmmntyfrcdrs" 9 | 10 | Example 2: 11 | Input: "aeiou" 12 | Output: "" 13 | 14 | */ 15 | 16 | /* 17 | 18 | O(n),O(1) 19 | 20 | */ 21 | 22 | public String removeVowels(String S) { 23 | return S.replaceAll("['a', 'e', 'i', 'o', 'u']", ""); 24 | } 25 | 26 | 27 | -------------------------------------------------------------------------------- /String/125. Valid Palindrome.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 5 | Note: For the purpose of this problem, we define empty string as valid palindrome. 6 | 7 | Example 1: 8 | Input: "A man, a plan, a canal: Panama" 9 | Output: true 10 | 11 | Example 2: 12 | Input: "race a car" 13 | Output: false 14 | 15 | */ 16 | 17 | /* 18 | 19 | O(n),O(1) 20 | 21 | */ 22 | 23 | public boolean isPalindrome(String s) { 24 | int l = 0, r = s.length() - 1; 25 | while (l < r) { 26 | if (!Character.isLetterOrDigit(s.charAt(l))) l++; 27 | else if (!Character.isLetterOrDigit(s.charAt(r))) r--; 28 | else if (Character.toLowerCase(s.charAt(l)) != Character.toLowerCase(s.charAt(r))) return false; 29 | else { 30 | l++; 31 | r--; 32 | } 33 | } 34 | return true; 35 | } 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /String/14. Longest Common Prefix.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Write a function to find the longest common prefix string amongst an array of strings. 5 | 6 | If there is no common prefix, return an empty string "". 7 | 8 | Example 1: 9 | Input: ["flower","flow","flight"] 10 | Output: "fl" 11 | 12 | Example 2: 13 | Input: ["dog","racecar","car"] 14 | Output: "" 15 | Explanation: There is no common prefix among the input strings. 16 | 17 | */ 18 | 19 | /* 20 | 21 | O(nk^2),O(1) 22 | 23 | */ 24 | 25 | public String longestCommonPrefix(String[] strs) { 26 | if (strs.length == 0) 27 | return ""; 28 | String ans = strs[0]; 29 | for (int i = 1; i < strs.length; ++i) { 30 | while (strs[i].indexOf(ans) != 0) 31 | ans = ans.substring(0, ans.length() - 1); 32 | } 33 | return ans; 34 | } 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /String/151. Reverse Words in a String.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an input string, reverse the string word by word. 5 | 6 | Example: 7 | Input: "the sky is blue", 8 | Output: "blue is sky the". 9 | 10 | Note: 11 | A word is defined as a sequence of non-space characters. 12 | Input string may contain leading or trailing spaces. 13 | However, your reversed string should not contain leading or trailing spaces. 14 | You need to reduce multiple spaces between two words to a single space in the reversed string. 15 | 16 | */ 17 | 18 | /* 19 | 20 | O(n),O(n) 21 | 22 | */ 23 | 24 | public String reverseWords(String s) { 25 | s = s.trim(); 26 | String[] strs = s.split("\\s+"); 27 | StringBuilder sb = new StringBuilder(); 28 | for (int i = strs.length - 1; i >= 0; --i) sb.append(strs[i]).append(" "); 29 | sb.setLength(sb.length() - 1); 30 | return sb.toString(); 31 | } 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /String/159. Longest Substring with At Most Two Distinct Characters.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a string s , find the length of the longest substring t that contains at most 2 distinct characters. 5 | 6 | Example 1: 7 | Input: "eceba" 8 | Output: 3 9 | Explanation: t is "ece" which its length is 3. 10 | 11 | Example 2: 12 | Input: "ccaabbb" 13 | Output: 5 14 | Explanation: t is "aabbb" which its length is 5. 15 | 16 | */ 17 | 18 | /* 19 | 20 | O(n),O(1) 21 | 22 | */ 23 | 24 | public int lengthOfLongestSubstringTwoDistinct(String s) { 25 | int[] buckets = new int[128]; 26 | int ans = 0, cnt = 0; 27 | for (int i = 0, j = 0; j < s.length(); ++j) { 28 | char right = s.charAt(j); 29 | if (buckets[right] == 0) cnt++; 30 | buckets[right]++; 31 | while (cnt > 2) { 32 | char left = s.charAt(i); 33 | buckets[left]--; 34 | if (buckets[left] == 0) cnt--; 35 | i++; 36 | } 37 | ans = Math.max(ans, j - i + 1); 38 | } 39 | return ans; 40 | } 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /String/186. Reverse Words in a String II.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an input string , reverse the string word by word. 5 | 6 | Example: 7 | Input: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"] 8 | Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"] 9 | 10 | Note: 11 | A word is defined as a sequence of non-space characters. 12 | The input string does not contain leading or trailing spaces. 13 | The words are always separated by a single space. 14 | 15 | */ 16 | 17 | /* 18 | 19 | O(n),O(1) 20 | 21 | */ 22 | 23 | public void reverseWords(char[] str) { 24 | int n = str.length; 25 | reverse(str, 0, n - 1); 26 | for (int i = 0, j = 0; j <= n; ++j) { 27 | if (j == n || str[j] == ' ') { 28 | reverse(str, i, j - 1); 29 | i = j + 1; 30 | } 31 | } 32 | } 33 | 34 | private void reverse(char[] s, int i, int j) { 35 | while (i < j) { 36 | char tmp = s[i]; 37 | s[i] = s[j]; 38 | s[j] = tmp; 39 | i++; 40 | j--; 41 | } 42 | } 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /String/22. Generate Parentheses.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 5 | 6 | For example, given n = 3, a solution set is: 7 | [ 8 | "((()))", 9 | "(()())", 10 | "(())()", 11 | "()(())", 12 | "()()()" 13 | ] 14 | 15 | */ 16 | 17 | /* 18 | 19 | O(2^n),O(n) 20 | 21 | */ 22 | 23 | public List generateParenthesis(int n) { 24 | List ans = new ArrayList<>(); 25 | dfs(ans, new StringBuilder(), n, 0, 0); 26 | return ans; 27 | } 28 | 29 | private void dfs(List ans, StringBuilder sb, int n, int left, int right) { 30 | if (left == n && right == n) { 31 | ans.add(sb.toString()); 32 | return; 33 | } 34 | if (left < n) { 35 | sb.append("("); 36 | dfs(ans, sb, n, left + 1, right); 37 | sb.setLength(sb.length() - 1); 38 | } 39 | if (right < left) { 40 | sb.append(")"); 41 | dfs(ans, sb, n, left, right + 1); 42 | sb.setLength(sb.length() - 1); 43 | } 44 | } 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /String/28. Implement strStr().java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Implement strStr(). 5 | Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 6 | 7 | Example 1: 8 | Input: haystack = "hello", needle = "ll" 9 | Output: 2 10 | 11 | Example 2: 12 | Input: haystack = "aaaaa", needle = "bba" 13 | Output: -1 14 | 15 | */ 16 | 17 | /* 18 | 19 | Solution 1: check each prefix of haystack with needle 20 | O(n^2),O(1) 21 | 22 | */ 23 | 24 | public int strStr(String haystack, String needle) { 25 | for (int i = 0; ; ++i) { 26 | for (int j = 0; ; ++j) { 27 | if (j == needle.length()) return i; 28 | if (i + j == haystack.length()) return -1; 29 | if (haystack.charAt(i + j) != needle.charAt(j)) break; 30 | } 31 | } 32 | } 33 | 34 | 35 | /* 36 | 37 | Solution 2: KMP algorithm 38 | 39 | */ 40 | 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /String/293. Flip Game.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | You are playing the following Flip Game with your friend: Given a string that contains only these two characters: + and -, 5 | you and your friend take turns to flip two consecutive "++" into "--". 6 | The game ends when a person can no longer make a move and therefore the other person will be the winner. 7 | Write a function to compute all possible states of the string after one valid move. 8 | 9 | Example: 10 | Input: s = "++++" 11 | Output: 12 | [ 13 | "--++", 14 | "+--+", 15 | "++--" 16 | ] 17 | 18 | */ 19 | 20 | /* 21 | 22 | O(n),O(n) 23 | 24 | */ 25 | 26 | public List generatePossibleNextMoves(String s) { 27 | List ans = new ArrayList<>(); 28 | for (int i = 1; i < s.length(); ++i) { 29 | if (s.charAt(i) == '+' && s.charAt(i - 1) == '+') ans.add(s.substring(0, i - 1) + "--" + s.substring(i + 1)); 30 | } 31 | return ans; 32 | } 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /String/344. Reverse String.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Write a function that reverses a string. The input string is given as an array of characters char[]. 5 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 6 | You may assume all the characters consist of printable ascii characters. 7 | 8 | Example 1: 9 | Input: ["h","e","l","l","o"] 10 | Output: ["o","l","l","e","h"] 11 | 12 | Example 2: 13 | Input: ["H","a","n","n","a","h"] 14 | Output: ["h","a","n","n","a","H"] 15 | 16 | */ 17 | 18 | /* 19 | 20 | O(n),O(1) 21 | 22 | */ 23 | 24 | public void reverseString(char[] s) { 25 | int l = 0, r = s.length - 1; 26 | while (l < r) { 27 | char tmp = s[l]; 28 | s[l] = s[r]; 29 | s[r] = tmp; 30 | l++; 31 | r--; 32 | } 33 | } 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /String/345. Reverse Vowels of a String.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Write a function that takes a string as input and reverse only the vowels of a string. 5 | 6 | Example 1: 7 | Input: "hello" 8 | Output: "holle" 9 | 10 | Example 2: 11 | Input: "leetcode" 12 | Output: "leotcede" 13 | 14 | */ 15 | 16 | /* 17 | 18 | O(n),O(1) 19 | 20 | */ 21 | 22 | public String reverseVowels(String s) { 23 | char[] chars = s.toCharArray(); 24 | int l = 0, r = chars.length - 1; 25 | while (l < r) { 26 | while (l < r && !isVowel(chars[l])) l++; 27 | while (l < r && !isVowel(chars[r])) r--; 28 | char tmp = chars[l]; 29 | chars[l] = chars[r]; 30 | chars[r] = tmp; 31 | l++; 32 | r--; 33 | } 34 | return new String(chars); 35 | } 36 | 37 | private boolean isVowel(char c) { 38 | return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || 39 | c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'; 40 | } 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /String/383. Ransom Note.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an arbitrary ransom note string and another string containing letters from all the magazines, 5 | write a function that will return true if the ransom note can be constructed from the magazines ; 6 | otherwise, it will return false. 7 | Each letter in the magazine string can only be used once in your ransom note. 8 | 9 | canConstruct("a", "b") -> false 10 | canConstruct("aa", "ab") -> false 11 | canConstruct("aa", "aab") -> true 12 | 13 | */ 14 | 15 | /* 16 | 17 | O(n+m),O(1) 18 | 19 | */ 20 | 21 | public boolean canConstruct(String ransomNote, String magazine) { 22 | int[] buckets = new int[26]; 23 | for (char c : magazine.toCharArray()) buckets[c - 'a']++; 24 | for (char c : ransomNote.toCharArray()) { 25 | if (buckets[c - 'a'] <= 0) return false; 26 | buckets[c - 'a']--; 27 | } 28 | return true; 29 | } 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /String/387. First Unique Character in a String.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. 5 | 6 | Examples: 7 | s = "leetcode" 8 | return 0. 9 | 10 | s = "loveleetcode", 11 | return 2. 12 | 13 | */ 14 | 15 | /* 16 | 17 | O(n),O(1) 18 | 19 | */ 20 | 21 | public int firstUniqChar(String s) { 22 | int[] buckets = new int[26]; 23 | for (char c : s.toCharArray()) buckets[c - 'a']++; 24 | for (int i = 0; i < s.length(); ++i) { 25 | if (buckets[s.charAt(i) - 'a'] == 1) return i; 26 | } 27 | return -1; 28 | } 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /String/415. Add Strings.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. 5 | 6 | */ 7 | 8 | /* 9 | 10 | O(n1+n2),O(1) 11 | 12 | */ 13 | 14 | public String addStrings(String num1, String num2) { 15 | String ans = ""; 16 | int sum = 0, n1 = num1.length(), n2 = num2.length(); 17 | while (n1 > 0 || n2 > 0) { 18 | sum /= 10; 19 | if (n1 > 0) { 20 | sum += num1.charAt(n1 - 1) - '0'; 21 | n1--; 22 | } 23 | if (n2 > 0) { 24 | sum += num2.charAt(n2 - 1) - '0'; 25 | n2--; 26 | } 27 | ans = (sum % 10) + ans; 28 | } 29 | if (sum >= 10) ans = "1" + ans; 30 | return ans; 31 | } 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /String/434. Number of Segments in a String.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters. 5 | Please note that the string does not contain any non-printable characters. 6 | 7 | Example: 8 | Input: "Hello, my name is John" 9 | Output: 5 10 | 11 | */ 12 | 13 | /* 14 | 15 | O(n),O(1) 16 | 17 | */ 18 | 19 | public int countSegments(String s) { 20 | s = s.trim(); 21 | if (s.length() == 0) return 0; 22 | return s.split("\\s+").length; 23 | } 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /String/49. Group Anagrams.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array of strings, group anagrams together. 5 | 6 | Example: 7 | Input: ["eat", "tea", "tan", "ate", "nat", "bat"], 8 | Output: 9 | [ 10 | ["ate","eat","tea"], 11 | ["nat","tan"], 12 | ["bat"] 13 | ] 14 | 15 | */ 16 | 17 | /* 18 | 19 | O(nmlogm),O(nm), where m is the average length of the strings 20 | 21 | */ 22 | 23 | public List> groupAnagrams(String[] strs) { 24 | List> ans = new ArrayList<>(); 25 | Map> map = new HashMap<>(); 26 | for (String s : strs) { 27 | char[] ch = s.toCharArray(); 28 | Arrays.sort(ch); 29 | String key = new String(ch); 30 | List values = map.getOrDefault(key, new ArrayList<>()); 31 | values.add(s); 32 | map.put(key, values); 33 | } 34 | for (String key : map.keySet()) ans.add(map.get(key)); 35 | return ans; 36 | } 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /String/520. Detect Capital.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a word, you need to judge whether the usage of capitals in it is right or not. 5 | We define the usage of capitals in a word to be right when one of the following cases holds: 6 | All letters in this word are capitals, like "USA". 7 | All letters in this word are not capitals, like "leetcode". 8 | Only the first letter in this word is capital, like "Google". 9 | Otherwise, we define that this word doesn't use capitals in a right way. 10 | 11 | Example 1: 12 | Input: "USA" 13 | Output: True 14 | 15 | Example 2: 16 | Input: "FlaG" 17 | Output: False 18 | 19 | */ 20 | 21 | /* 22 | 23 | O(n),O(1) 24 | 25 | */ 26 | 27 | public boolean detectCapitalUse(String word) { 28 | if (word.length() < 2) { 29 | return true; 30 | } else if (word.toUpperCase().equals(word)) { 31 | return true; 32 | } else if (word.substring(1).toLowerCase().equals(word.substring(1))) { 33 | return true; 34 | } 35 | return false; 36 | } 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /String/557. Reverse Words in a String III.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a string, you need to reverse the order of characters in each word within a sentence 5 | while still preserving whitespace and initial word order. 6 | 7 | Example 1: 8 | Input: "Let's take LeetCode contest" 9 | Output: "s'teL ekat edoCteeL tsetnoc" 10 | 11 | */ 12 | 13 | /* 14 | 15 | O(n),O(n) 16 | 17 | */ 18 | 19 | public String reverseWords(String s) { 20 | int i = 0, j = 0, n = s.length(); 21 | char[] chars = s.toCharArray(); 22 | while (j < n) { 23 | while (j < n && s.charAt(j) != ' ') { 24 | j++; 25 | } 26 | reverse(chars, i, j - 1); 27 | j++; 28 | i = j; 29 | } 30 | return new String(chars); 31 | } 32 | 33 | private void reverse(char[] chars, int i, int j) { 34 | while (i < j) { 35 | char tmp = chars[i]; 36 | chars[i] = chars[j]; 37 | chars[j] = tmp; 38 | i++; 39 | j--; 40 | } 41 | } 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /String/58. Length of Last Word.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word. 5 | If the last word does not exist, return 0. 6 | Note: A word is defined as a character sequence consists of non-space characters only. 7 | 8 | Example: 9 | Input: "Hello World" 10 | Output: 5 11 | 12 | */ 13 | 14 | /* 15 | 16 | O(n),O(1) 17 | 18 | */ 19 | 20 | public int lengthOfLastWord(String s) { 21 | s = s.trim(); 22 | int ans = 0; 23 | for (int i = s.length() - 1; i >= 0; --i) { 24 | if (s.charAt(i) == ' ') break; 25 | else ans++; 26 | } 27 | return ans; 28 | } 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /String/67. Add Binary.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given two binary strings, return their sum (also a binary string). 5 | The input strings are both non-empty and contains only characters 1 or 0. 6 | 7 | Example 1: 8 | Input: a = "11", b = "1" 9 | Output: "100" 10 | 11 | Example 2: 12 | Input: a = "1010", b = "1011" 13 | Output: "10101" 14 | 15 | */ 16 | 17 | /* 18 | 19 | O(n+m),O(1) 20 | 21 | */ 22 | 23 | public String addBinary(String a, String b) { 24 | StringBuilder ans = new StringBuilder(); 25 | int n = a.length(), m = b.length(), sum = 0; 26 | while (n > 0 || m > 0) { 27 | sum /= 2; 28 | if (n > 0) { 29 | sum += a.charAt(n - 1) - '0'; 30 | n--; 31 | } 32 | if (m > 0) { 33 | sum += b.charAt(m - 1) - '0'; 34 | m--; 35 | } 36 | ans.append(sum % 2); 37 | } 38 | if (sum >= 2) ans.append("1"); 39 | return ans.reverse().toString(); 40 | } 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /String/686. Repeated String Match.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. 5 | If no such solution, return -1. 6 | For example, with A = "abcd" and B = "cdabcdab". 7 | Return 3, because by repeating A three times (“abcdabcdabcd”), B is a substring of it; 8 | and B is not a substring of A repeated two times ("abcdabcd"). 9 | 10 | */ 11 | 12 | /* 13 | 14 | O(n),O(n) 15 | 16 | */ 17 | 18 | public int repeatedStringMatch(String A, String B) { 19 | StringBuilder sb = new StringBuilder(A); 20 | int ans = 1; 21 | while (sb.indexOf(B) == -1) { 22 | if (sb.length() > A.length() + B.length()) { 23 | return -1; 24 | } 25 | sb.append(A); 26 | ans++; 27 | } 28 | return ans; 29 | } 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /String/709. To Lower Case.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase. 5 | 6 | Example 1: 7 | Input: "Hello" 8 | Output: "hello" 9 | 10 | Example 2: 11 | Input: "here" 12 | Output: "here" 13 | 14 | Example 3: 15 | Input: "LOVELY" 16 | Output: "lovely" 17 | 18 | */ 19 | 20 | /* 21 | 22 | O(n),O(n) 23 | 24 | */ 25 | 26 | public String toLowerCase(String str) { 27 | char[] chars = str.toCharArray(); 28 | for (int i = 0; i < chars.length; ++i) { 29 | if (chars[i] >= 'A' && chars[i] <= 'Z') { 30 | chars[i] += 32; 31 | } 32 | } 33 | return new String(chars); 34 | } 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Tree/104. Maximum Depth of Binary Tree.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a binary tree, find its maximum depth. 5 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 6 | Note: A leaf is a node with no children. 7 | 8 | Example: 9 | Given binary tree [3,9,20,null,null,15,7], 10 | 11 | 3 12 | / \ 13 | 9 20 14 | / \ 15 | 15 7 16 | return its depth = 3. 17 | 18 | */ 19 | 20 | /* 21 | 22 | O(n),O(logn) 23 | 24 | */ 25 | 26 | public int maxDepth(TreeNode root) { 27 | if (root == null) return 0; 28 | int left = maxDepth(root.left); 29 | int right = maxDepth(root.right); 30 | return 1 + Math.max(left, right); 31 | } 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Tree/257. Binary Tree Paths.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a binary tree, return all root-to-leaf paths. 5 | Note: A leaf is a node with no children. 6 | 7 | Example: 8 | Input: 9 | 1 10 | / \ 11 | 2 3 12 | \ 13 | 5 14 | Output: ["1->2->5", "1->3"] 15 | Explanation: All root-to-leaf paths are: 1->2->5, 1->3 16 | 17 | */ 18 | 19 | /* 20 | 21 | O(nlogn),O(logn) 22 | 23 | */ 24 | 25 | public List binaryTreePaths(TreeNode root) { 26 | List ans = new ArrayList<>(); 27 | dfs(ans, new StringBuilder(), root); 28 | return ans; 29 | } 30 | 31 | private void dfs(List ans, StringBuilder tmp, TreeNode root) { 32 | if (root == null) return; 33 | tmp.append(tmp.length() == 0 ? "" : "->").append(root.val); 34 | if (root.left == null && root.right == null) { 35 | ans.add(tmp.toString()); 36 | return; 37 | } 38 | int len = tmp.length(); 39 | dfs(ans, tmp, root.left); 40 | tmp.setLength(len); 41 | dfs(ans, tmp, root.right); 42 | tmp.setLength(len); 43 | } 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /Tree/366. Find Leaves of Binary Tree.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a binary tree, collect a tree's nodes as if you were doing this: 5 | Collect and remove all leaves, repeat until the tree is empty. 6 | 7 | Example: 8 | Input: [1,2,3,4,5] 9 | 1 10 | / \ 11 | 2 3 12 | / \ 13 | 4 5 14 | Output: [[4,5,3],[2],[1]] 15 | 16 | */ 17 | 18 | /* 19 | 20 | O(n),O(logn) 21 | 22 | */ 23 | 24 | public List> findLeaves(TreeNode root) { 25 | List> ans = new ArrayList<>(); 26 | dfs(ans, root); 27 | return ans; 28 | } 29 | 30 | private int dfs(List> ans, TreeNode root) { 31 | if (root == null) return -1; 32 | int level = 1 + Math.max(dfs(ans, root.left), dfs(ans, root.right)); 33 | if (ans.size() == level) ans.add(new ArrayList<>()); 34 | ans.get(level).add(root.val); 35 | return level; 36 | } 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /Tree/429. N-ary Tree Level Order Traversal.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). 5 | We should return its level order traversal: 6 | [ 7 | [1], 8 | [3,2,4], 9 | [5,6] 10 | ] 11 | 12 | */ 13 | 14 | /* 15 | 16 | O(n),O(n) 17 | 18 | */ 19 | 20 | public List> levelOrder(Node root) { 21 | List> ans = new ArrayList<>(); 22 | if (root == null) return ans; 23 | Node cur = root; 24 | Queue queue = new LinkedList<>(); 25 | queue.offer(cur); 26 | while (!queue.isEmpty()) { 27 | int size = queue.size(); 28 | List tmp = new ArrayList<>(); 29 | for (int i = 0; i < size; ++i) { 30 | cur = queue.poll(); 31 | tmp.add(cur.val); 32 | for (Node child : cur.children) { 33 | if (child != null) queue.offer(child); 34 | } 35 | } 36 | ans.add(tmp); 37 | } 38 | return ans; 39 | } 40 | 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /Tree/559. Maximum Depth of N-ary Tree.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a n-ary tree, find its maximum depth. 5 | The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 6 | 7 | */ 8 | 9 | /* 10 | 11 | O(n),O(logn) 12 | 13 | */ 14 | 15 | public int maxDepth(Node root) { 16 | if (root == null) { 17 | return 0; 18 | } 19 | int ans = 0; 20 | for (int i = 0; i < root.children.size(); ++i) { 21 | ans = Math.max(ans, maxDepth(root.children.get(i))); 22 | } 23 | return ans + 1; 24 | } 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /Tree/653. Two Sum IV - Input is a BST.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a Binary Search Tree and a target number, 5 | return true if there exist two elements in the BST such that their sum is equal to the given target. 6 | 7 | Example 1: 8 | Input: 9 | 5 10 | / \ 11 | 3 6 12 | / \ \ 13 | 2 4 7 14 | Target = 9 15 | Output: True 16 | 17 | Example 2: 18 | Input: 19 | 5 20 | / \ 21 | 3 6 22 | / \ \ 23 | 2 4 7 24 | Target = 28 25 | Output: False 26 | 27 | */ 28 | 29 | /* 30 | 31 | O(n),O(n) 32 | 33 | */ 34 | 35 | public boolean findTarget(TreeNode root, int k) { 36 | Set set = new HashSet<>(); 37 | return dfs(root, set, k); 38 | } 39 | 40 | private boolean dfs(TreeNode root, Set set, int k) { 41 | if (root == null) { 42 | return false; 43 | } 44 | if (set.contains(k - root.val)) { 45 | return true; 46 | } 47 | set.add(root.val); 48 | return dfs(root.left, set, k) || dfs(root.right, set, k); 49 | } 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /Tree/965. Univalued Binary Tree.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | A binary tree is univalued if every node in the tree has the same value. 5 | Return true if and only if the given tree is univalued. 6 | 7 | Example 1: 8 | Input: [1,1,1,1,1,null,1] 9 | Output: true 10 | 11 | Example 2: 12 | Input: [2,2,2,5,2] 13 | Output: false 14 | 15 | */ 16 | 17 | /* 18 | 19 | O(n),O(logn) 20 | 21 | */ 22 | 23 | public boolean isUnivalTree(TreeNode root) { 24 | if (root == null) { 25 | return true; 26 | } 27 | if (root.left != null && root.val != root.left.val) { 28 | return false; 29 | } 30 | if (root.right != null && root.val != root.right.val) { 31 | return false; 32 | } 33 | return isUnivalTree(root.left) && isUnivalTree(root.right); 34 | } 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /Two Pointers/11. Container With Most Water.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn 5 | such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, 6 | such that the container contains the most water. 7 | 8 | Note: You may not slant the container and n is at least 2. 9 | 10 | */ 11 | 12 | /* 13 | 14 | O(n),O(1) 15 | 16 | */ 17 | 18 | public int maxArea(int[] height) { 19 | int l = 0, r = height.length - 1, ans = 0; 20 | while (l < r) { 21 | ans = Math.max(ans, (r - l) * Math.min(height[l], height[r])); 22 | if (height[l] < height[r]) l++; 23 | else r--; 24 | } 25 | return ans; 26 | } 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /Two Pointers/125. Valid Palindrome.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 5 | Note: For the purpose of this problem, we define empty string as valid palindrome. 6 | 7 | Example 1: 8 | Input: "A man, a plan, a canal: Panama" 9 | Output: true 10 | 11 | Example 2: 12 | Input: "race a car" 13 | Output: false 14 | 15 | */ 16 | 17 | /* 18 | 19 | O(n),O(1) 20 | 21 | */ 22 | 23 | public boolean isPalindrome(String s) { 24 | int l = 0, r = s.length() - 1; 25 | while (l < r) { 26 | if (!Character.isLetterOrDigit(s.charAt(l))) l++; 27 | else if (!Character.isLetterOrDigit(s.charAt(r))) r--; 28 | else if (Character.toLowerCase(s.charAt(l)) != Character.toLowerCase(s.charAt(r))) return false; 29 | else { 30 | l++; 31 | r--; 32 | } 33 | } 34 | return true; 35 | } 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Two Pointers/159. Longest Substring with At Most Two Distinct Characters.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a string s , find the length of the longest substring t that contains at most 2 distinct characters. 5 | 6 | Example 1: 7 | Input: "eceba" 8 | Output: 3 9 | Explanation: t is "ece" which its length is 3. 10 | 11 | Example 2: 12 | Input: "ccaabbb" 13 | Output: 5 14 | Explanation: t is "aabbb" which its length is 5. 15 | 16 | */ 17 | 18 | /* 19 | 20 | O(n),O(1) 21 | 22 | */ 23 | 24 | public int lengthOfLongestSubstringTwoDistinct(String s) { 25 | int[] buckets = new int[128]; 26 | int ans = 0, cnt = 0; 27 | for (int i = 0, j = 0; j < s.length(); ++j) { 28 | char right = s.charAt(j); 29 | if (buckets[right] == 0) cnt++; 30 | buckets[right]++; 31 | while (cnt > 2) { 32 | char left = s.charAt(i); 33 | buckets[left]--; 34 | if (buckets[left] == 0) cnt--; 35 | i++; 36 | } 37 | ans = Math.max(ans, j - i + 1); 38 | } 39 | return ans; 40 | } 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /Two Pointers/19. Remove Nth Node From End of List.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a linked list, remove the n-th node from the end of list and return its head. 5 | 6 | Example: 7 | Given linked list: 1->2->3->4->5, and n = 2. 8 | After removing the second node from the end, the linked list becomes 1->2->3->5. 9 | 10 | Note: 11 | Given n will always be valid. 12 | 13 | */ 14 | 15 | /* 16 | 17 | O(n),O(1) 18 | 19 | */ 20 | 21 | public ListNode removeNthFromEnd(ListNode head, int n) { 22 | ListNode dummy = new ListNode(0); 23 | dummy.next = head; 24 | ListNode fast = dummy, slow = dummy; 25 | while (n > 0) { 26 | fast = fast.next; 27 | n--; 28 | } 29 | while (fast.next != null) { 30 | fast = fast.next; 31 | slow = slow.next; 32 | } 33 | slow.next = slow.next.next; 34 | return dummy.next; 35 | } 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /Two Pointers/234. Palindrome Linked List.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a singly linked list, determine if it is a palindrome. 5 | 6 | Example 1: 7 | Input: 1->2 8 | Output: false 9 | 10 | Example 2: 11 | Input: 1->2->2->1 12 | Output: true 13 | 14 | */ 15 | 16 | /* 17 | 18 | O(n),O(1) 19 | 20 | */ 21 | 22 | public boolean isPalindrome(ListNode head) { 23 | ListNode fast = head, slow = head; 24 | while (fast != null && fast.next != null) { 25 | fast = fast.next.next; 26 | slow = slow.next; 27 | } 28 | slow = reverse(slow); 29 | fast = head; 30 | while (slow != null) { 31 | if (fast.val != slow.val) return false; 32 | fast = fast.next; 33 | slow = slow.next; 34 | } 35 | return true; 36 | } 37 | 38 | private ListNode reverse(ListNode head) { 39 | if (head == null || head.next == null) return head; 40 | ListNode newHead = reverse(head.next); 41 | head.next.next = head; 42 | head.next = null; 43 | return newHead; 44 | } 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /Two Pointers/259. 3Sum Smaller.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n 5 | that satisfy the condition nums[i] + nums[j] + nums[k] < target. 6 | 7 | Example: 8 | Input: nums = [-2,0,1,3], and target = 2 9 | Output: 2 10 | Explanation: Because there are two triplets which sums are less than 2: 11 | [-2,0,1] 12 | [-2,0,3] 13 | 14 | */ 15 | 16 | /* 17 | 18 | O(n^2),O(1) 19 | 20 | */ 21 | 22 | public int threeSumSmaller(int[] nums, int target) { 23 | int ans = 0; 24 | Arrays.sort(nums); 25 | for (int i = 0; i < nums.length; ++i) { 26 | int j = i + 1, k = nums.length - 1; 27 | while (j < k) { 28 | int sum = nums[i] + nums[j] + nums[k]; 29 | if (sum < target) { 30 | ans += k - j; 31 | j++; 32 | } else k--; 33 | } 34 | } 35 | return ans; 36 | } 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /Two Pointers/28. Implement strStr().java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Implement strStr(). 5 | Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. 6 | 7 | Example 1: 8 | Input: haystack = "hello", needle = "ll" 9 | Output: 2 10 | 11 | Example 2: 12 | Input: haystack = "aaaaa", needle = "bba" 13 | Output: -1 14 | 15 | */ 16 | 17 | /* 18 | 19 | O(n^2),O(1) 20 | 21 | */ 22 | 23 | public int strStr(String haystack, String needle) { 24 | for (int i = 0; ; ++i) { 25 | for (int j = 0; ; ++j) { 26 | if (j == needle.length()) return i; 27 | if (i + j == haystack.length()) return -1; 28 | if (haystack.charAt(i + j) != needle.charAt(j)) break; 29 | } 30 | } 31 | } 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Two Pointers/283. Move Zeroes.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array nums, write a function to move all 0's to the end of it while maintaining the order of the other elements. 5 | 6 | Example: 7 | Input: [0,1,0,3,12] 8 | Output: [1,3,12,0,0] 9 | 10 | */ 11 | 12 | /* 13 | 14 | O(n),O(1) 15 | 16 | */ 17 | 18 | public void moveZeroes(int[] nums) { 19 | int i = 0; 20 | for (int num : nums) { 21 | if (num != 0) nums[i++] = num; 22 | } 23 | while (i < nums.length) nums[i++] = 0; 24 | } 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /Two Pointers/344. Reverse String.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Write a function that reverses a string. The input string is given as an array of characters char[]. 5 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 6 | You may assume all the characters consist of printable ascii characters. 7 | 8 | Example 1: 9 | Input: ["h","e","l","l","o"] 10 | Output: ["o","l","l","e","h"] 11 | 12 | Example 2: 13 | Input: ["H","a","n","n","a","h"] 14 | Output: ["h","a","n","n","a","H"] 15 | 16 | */ 17 | 18 | /* 19 | 20 | O(n),O(1) 21 | 22 | */ 23 | 24 | public void reverseString(char[] s) { 25 | int l = 0, r = s.length - 1; 26 | while (l < r) { 27 | char tmp = s[l]; 28 | s[l] = s[r]; 29 | s[r] = tmp; 30 | l++; 31 | r--; 32 | } 33 | } 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /Two Pointers/345. Reverse Vowels of a String.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Write a function that takes a string as input and reverse only the vowels of a string. 5 | 6 | Example 1: 7 | Input: "hello" 8 | Output: "holle" 9 | 10 | Example 2: 11 | Input: "leetcode" 12 | Output: "leotcede" 13 | 14 | */ 15 | 16 | /* 17 | 18 | O(n),O(1) 19 | 20 | */ 21 | 22 | public String reverseVowels(String s) { 23 | char[] chars = s.toCharArray(); 24 | int l = 0, r = chars.length - 1; 25 | while (l < r) { 26 | while (l < r && !isVowel(chars[l])) l++; 27 | while (l < r && !isVowel(chars[r])) r--; 28 | char tmp = chars[l]; 29 | chars[l] = chars[r]; 30 | chars[r] = tmp; 31 | l++; 32 | r--; 33 | } 34 | return new String(chars); 35 | } 36 | 37 | private boolean isVowel(char c) { 38 | return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || 39 | c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'; 40 | } 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /Two Pointers/567. Permutation in String.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. 5 | In other words, one of the first string's permutations is the substring of the second string. 6 | 7 | Example 1: 8 | Input: s1 = "ab" s2 = "eidbaooo" 9 | Output: True 10 | Explanation: s2 contains one permutation of s1 ("ba"). 11 | 12 | Example 2: 13 | Input:s1= "ab" s2 = "eidboaoo" 14 | Output: False 15 | 16 | */ 17 | 18 | /* 19 | 20 | O(n),O(1) 21 | 22 | */ 23 | 24 | public boolean checkInclusion(String s1, String s2) { 25 | int[] buckets = new int[128]; 26 | for (char c : s1.toCharArray()) { 27 | buckets[c]++; 28 | } 29 | for (int i = 0, j = 0; j < s2.length(); ++j) { 30 | buckets[s2.charAt(j)]--; 31 | while (buckets[s2.charAt(j)] < 0) { 32 | buckets[s2.charAt(i)]++; 33 | i++; 34 | } 35 | if (j - i + 1 == s1.length()) { 36 | return true; 37 | } 38 | } 39 | return false; 40 | } 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /Two Pointers/633. Sum of Square Numbers.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c. 5 | 6 | Example 1: 7 | Input: 5 8 | Output: True 9 | Explanation: 1 * 1 + 2 * 2 = 5 10 | 11 | Example 2: 12 | Input: 3 13 | Output: False 14 | 15 | */ 16 | 17 | /* 18 | 19 | O(sqrt(n)),O(1) 20 | 21 | */ 22 | 23 | public boolean judgeSquareSum(int c) { 24 | int l = 0, r = (int)Math.sqrt(c); 25 | while (l <= r) { 26 | int n = l * l + r * r; 27 | if (n == c) { 28 | return true; 29 | } else if (n > c) { 30 | r--; 31 | } else { 32 | l++; 33 | } 34 | } 35 | return false; 36 | } 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /Two Pointers/86. Partition List.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. 5 | You should preserve the original relative order of the nodes in each of the two partitions. 6 | 7 | Example: 8 | Input: head = 1->4->3->2->5->2, x = 3 9 | Output: 1->2->2->4->3->5 10 | 11 | */ 12 | 13 | /* 14 | 15 | O(n),O(1) 16 | 17 | */ 18 | 19 | public ListNode partition(ListNode head, int x) { 20 | ListNode dummy1 = new ListNode(0), prev1 = dummy1; 21 | ListNode dummy2 = new ListNode(0), prev2 = dummy2; 22 | ListNode cur = head; 23 | while (cur != null) { 24 | if (cur.val < x) { 25 | prev1.next = cur; 26 | prev1 = prev1.next; 27 | } else { 28 | prev2.next = cur; 29 | prev2 = prev2.next; 30 | } 31 | cur = cur.next; 32 | } 33 | prev1.next = dummy2.next; 34 | prev2.next = null; 35 | return dummy1.next; 36 | } 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /Two Pointers/88. Merge Sorted Array.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. 5 | 6 | Note: 7 | The number of elements initialized in nums1 and nums2 are m and n respectively. 8 | You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. 9 | 10 | Example: 11 | Input: 12 | nums1 = [1,2,3,0,0,0], m = 3 13 | nums2 = [2,5,6], n = 3 14 | Output: [1,2,2,3,5,6] 15 | 16 | */ 17 | 18 | /* 19 | 20 | O(n+m),O(1) 21 | 22 | */ 23 | 24 | public void merge(int[] nums1, int m, int[] nums2, int n) { 25 | int i = m - 1, j = n - 1, k = m + n - 1; 26 | while (i >= 0 && j >= 0) { 27 | if (nums1[i] > nums2[j]) nums1[k--] = nums1[i--]; 28 | else nums1[k--] = nums2[j--]; 29 | } 30 | while (j >= 0) nums1[k--] = nums2[j--]; 31 | } 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Two Pointers/977. Squares of a Sorted Array.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | 4 | Given an array of integers A sorted in non-decreasing order, 5 | return an array of the squares of each number, also in sorted non-decreasing order. 6 | 7 | Example 1: 8 | Input: [-4,-1,0,3,10] 9 | Output: [0,1,9,16,100] 10 | 11 | Example 2: 12 | Input: [-7,-3,2,3,11] 13 | Output: [4,9,9,49,121] 14 | 15 | */ 16 | 17 | /* 18 | 19 | O(n),O(n) 20 | 21 | */ 22 | 23 | public int[] sortedSquares(int[] A) { 24 | int n = A.length, i = 0, j = n - 1; 25 | int[] ans = new int[n]; 26 | for (int k = n - 1; k >= 0; --k) { 27 | if (Math.abs(A[i]) < Math.abs(A[j])) { 28 | ans[k] = A[j] * A[j]; 29 | j--; 30 | } else { 31 | ans[k] = A[i] * A[i]; 32 | i++; 33 | } 34 | } 35 | return ans; 36 | } 37 | 38 | 39 | 40 | 41 | --------------------------------------------------------------------------------