├── BinarySearch └── 718. Every Sublist Containing Unique Element │ └── Solution.py ├── CSES ├── Dice Probability │ └── Solution.java └── Inversion Probability │ └── Solution.java ├── DailyCoding └── StableMarriage.py ├── DataStructure ├── Skiplist.java ├── StackQueue │ ├── StackQueueHelper.class │ └── StackQueueHelper.java ├── Trie.java └── UnionFind.java ├── GeeksForGeeks ├── 0 - 1 Knapsack Problem │ └── GFG.java ├── Matrix Chain Multiplication │ └── GFG.java ├── Maximum distinct elements after removing K elements │ └── Solution.py ├── Optimal binary search tree │ └── GFG.java └── Word Wrap │ └── GFG.java ├── Hacker Cup └── 2011 │ └── Qualification │ └── Studious Student │ └── Solution.py ├── HackerEarth └── Tower Research C++ Developer Hiring Challenge │ └── Longest Common Subsequence Again │ └── Solution.cpp ├── HackerRank ├── Abbreviation │ └── Solution.java ├── Array Manipulation │ └── Solution.java ├── Arrays: Left Rotation │ └── Solution.java ├── Introduction to Nim Game │ └── Solution.py ├── Is This a Binary Search Tree? │ └── Solution.java ├── Merge Sort: Counting Inversions │ └── Solution.java ├── Prim's (MST) : Special Subtree │ └── Solution.java ├── Reverse a doubly linked list │ └── Solution.java ├── Reverse a linked list │ └── Solution.java ├── Time Complexity: Primality │ └── Solution.java └── Tree: Huffman Decoding │ └── Solution.java ├── Helper.java ├── LeetCode ├── 1. Two Sum │ └── Solution.java ├── 10. Regular Expression Matching │ └── Solution.java ├── 100. Same Tree │ └── Solution.java ├── 1000. Minimum Cost to Merge Stones │ ├── Solution.py │ └── Solution2.py ├── 1002. Find Common Characters │ └── Solution.py ├── 1004. Max Consecutive Ones III │ └── Solution.java ├── 1007. Minimum Domino Rotations For Equal Row │ ├── Solution.java │ └── Solution2.java ├── 1008. Construct Binary Search Tree from Preorder Traversal │ └── Solution.java ├── 101. Symmetric Tree │ └── Solution.java ├── 1010. Pairs of Songs With Total Durations Divisible by 60 │ └── Solution.py ├── 1011. Capacity To Ship Packages Within D Days │ └── Solution.py ├── 1015. Smallest Integer Divisible by K │ └── Solution.cpp ├── 1016. Binary String With Substrings Representing 1 To N │ └── Solution.py ├── 1019. Next Greater Node In Linked List │ └── Solution.java ├── 102. Binary Tree Level Order Traversal │ └── Solution.java ├── 1021. Remove Outermost Parentheses │ └── Solution.py ├── 1022. Sum of Root To Leaf Binary Numbers │ └── Solution.py ├── 1024. Video Stitching │ ├── Solution.py │ └── Solution2.py ├── 1025. Divisor Game │ ├── Solution.py │ └── Solution2.py ├── 1026. Maximum Difference Between Node and Ancestor │ └── Solution.py ├── 1027. Longest Arithmetic Subsequence │ └── Solution.java ├── 1029. Two City Scheduling │ └── Solution.py ├── 103. Binary Tree Zigzag Level Order Traversal │ └── Solution.java ├── 1031. Maximum Sum of Two Non-Overlapping Subarrays │ └── Solution.py ├── 1032. Stream of Characters │ └── Solution.py ├── 1035. Uncrossed Lines │ └── Solution.py ├── 1037. Valid Boomerang │ └── Solution.py ├── 1038. Binary Search Tree to Greater Sum Tre │ └── Solution.py ├── 1039. Minimum Score Triangulation of Polygon │ └── Solution.java ├── 1041. Robot Bounded In Circle │ └── Solution.py ├── 1043. Partition Array for Maximum Sum │ └── Solution.py ├── 1044. Longest Duplicate Substring │ └── Solution.py ├── 1046. Last Stone Weight │ └── Solution.java ├── 1047. Remove All Adjacent Duplicates In String │ └── Solution.py ├── 1048. Longest String Chain │ └── Solution.java ├── 1049. Last Stone Weight II │ └── Solution.java ├── 105. Construct Binary Tree from Preorder and Inorder Traversal │ ├── Solution.java │ └── Solution.py ├── 1051. Height Checker │ └── Solution.py ├── 1052. Grumpy Bookstore Owner │ └── Solution.java ├── 1055. Shortest Way to Form String │ ├── Solution.java │ └── Solution2.java ├── 1056. Confusing Number │ └── Solution.py ├── 1057. Campus Bikes │ └── Solution.java ├── 1059. All Paths from Source Lead to Destination │ └── Solution.py ├── 106. Construct Binary Tree from Inorder and Postorder Traversal │ └── Solution.java ├── 1060. Missing Element in Sorted Array │ └── Solution.py ├── 1064. Fixed Point │ └── Solution.java ├── 1066. Campus Bikes II │ └── Solution.java ├── 107. Binary Tree Level Order Traversal II │ └── Solution.py ├── 1071. Greatest Common Divisor of Strings │ └── Solution.py ├── 1073. Adding Two Negabinary Numbers │ └── Solution.py ├── 1074. Number of Submatrices That Sum to Target │ └── Solution.py ├── 1078. Occurrences After Bigram │ └── Solution.py ├── 1079. Letter Tile Possibilities │ └── Solution.py ├── 108. Convert Sorted Array to Binary Search Tree │ └── Solution.py ├── 1081. Smallest Subsequence of Distinct Characters │ └── Solution.py ├── 1086. High Five │ └── Solution.py ├── 1088. Confusing Number II │ └── Solution.py ├── 1089. Duplicate Zeros │ └── Solution.py ├── 109. Convert Sorted List to Binary Search Tree │ └── Solution.java ├── 1090. Largest Values From Labels │ └── Solution.py ├── 1091. Shortest Path in Binary Matrix │ └── Solution.py ├── 1092. Shortest Common Supersequence │ └── Solution.java ├── 1094. Car Pooling │ └── Solution.py ├── 1095. Find in Mountain Array │ └── Solution.py ├── 1096. Brace Expansion II │ └── Solution.py ├── 1099. Two Sum Less Than K │ └── Solution.java ├── 11. Container With Most Water │ └── Solution.java ├── 1101. The Earliest Moment When Everyone Become Friends │ └── Solution.py ├── 1102. Path With Maximum Minimum Value │ └── Solution.py ├── 1103. Distribute Candies to People │ └── Solution.py ├── 1105. Filling Bookcase Shelves │ └── Solution.py ├── 1108. Defanging an IP Address │ └── Solution.py ├── 111. Minimum Depth of Binary Tree │ └── Solution.py ├── 1110. Delete Nodes And Return Forest │ └── Solution.java ├── 1114. Print in Order │ └── Solution.java ├── 1115. Print FooBar Alternately │ └── Solution.java ├── 1116. Print Zero Even Odd │ └── Solution.java ├── 1117. Building H2O │ └── Solution.cpp ├── 1119. Remove Vowels from a String │ └── Solution.py ├── 112. Path Sum │ └── Solution.py ├── 1120. Maximum Average Subtree │ └── Solution.java ├── 1123. Lowest Common Ancestor of Deepest Leaves │ └── Solution.py ├── 1125. Smallest Sufficient Team │ └── Solution.py ├── 1129. Shortest Path with Alternating Colors │ └── Solution.py ├── 113. Path Sum II │ └── Solution.java ├── 1130. Minimum Cost Tree From Leaf Values │ └── Solution.java ├── 1133. Largest Unique Number │ └── Solution.py ├── 1135. Connecting Cities With Minimum Cost │ └── Solution.java ├── 1136. Parallel Courses │ └── Solution.py ├── 1137. N-th Tribonacci Number │ └── Solution.java ├── 1138. Alphabet Board Path │ └── Solution.py ├── 114. Flatten Binary Tree to Linked List │ └── Solution.java ├── 1143. Longest Common Subsequence │ └── Solution.py ├── 1146. Snapshot Array │ └── Solution.java ├── 1147. Longest Chunked Palindrome Decomposition │ └── Solution.java ├── 115. Distinct Subsequences │ └── Solution.java ├── 1150. Check If a Number Is Majority Element in a Sorted Array │ └── Solution.py ├── 1151. Minimum Swaps to Group All 1's Together │ └── Solution.py ├── 1152. Analyze User Website Visit Pattern │ └── Solution.py ├── 1153. String Transforms Into Another String │ └── Solution.java ├── 1155. Number of Dice Rolls With Target Sum │ └── Solution.py ├── 1156. Swap For Longest Repeated Character Substring │ └── Solution.py ├── 1157. Online Majority Element In Subarray │ ├── Solution.py │ └── Solution2.py ├── 116. Populating Next Right Pointers in Each Node │ └── Solution.java ├── 1160. Find Words That Can Be Formed by Characters │ └── Solution.py ├── 1161. Maximum Level Sum of a Binary Tree │ └── Solution.java ├── 1162. As Far from Land as Possible │ └── Solution.py ├── 1163. Last Substring in Lexicographical Order │ └── Solution.java ├── 1165. Single-Row Keyboard │ └── Solution.py ├── 1166. Design File System │ └── Solution.py ├── 1167. Minimum Cost to Connect Sticks │ └── Solution.py ├── 1168. Optimize Water Distribution in a Village │ └── Solution.py ├── 1169. Invalid Transactions │ └── Solution.py ├── 117. Populating Next Right Pointers in Each Node II │ └── Solution.java ├── 1175. Prime Arrangements │ └── Solution.java ├── 1176. Diet Plan Performance │ └── Solution.py ├── 118. Pascal's Triangle │ └── Solution.py ├── 1180. Count Substrings with Only One Distinct Letter │ └── Solution.py ├── 1181. Before and After Puzzle │ └── Solution.java ├── 1182. Shortest Distance to Target Color │ └── Solution.py ├── 1188. Design Bounded Blocking Queue │ └── Solution.java ├── 119. Pascal's Triangle II │ └── Solution.java ├── 1192. Critical Connections in a Network │ └── Solution.java ├── 1195. Fizz Buzz Multithreaded │ └── Solution.java ├── 1196. How Many Apples Can You Put into the Basket │ └── Solution.py ├── 1197. Minimum Knight Moves │ └── Solution.py ├── 1198. Find Smallest Common Element in All Rows │ └── Solution.py ├── 1199. Minimum Time to Build Blocks │ └── Solution.py ├── 12. Integer to Roman │ └── Solution.java ├── 120. Triangle │ └── Solution.py ├── 1200. Minimum Absolute Difference │ └── Solution.java ├── 1202. Smallest String With Swaps │ └── Solution.py ├── 1206. Design Skiplist │ └── Solution.java ├── 1207. Unique Number of Occurrences │ └── Solution.rs ├── 1209. Remove All Adjacent Duplicates in String II │ └── Solution.py ├── 121. Best Time to Buy and Sell Stock │ └── Solution.java ├── 1213. Intersection of Three Sorted Arrays │ └── Solution.py ├── 1214. Two Sum BSTs │ └── Solution.java ├── 1215. Stepping Numbers │ └── Solution.py ├── 1216. Valid Palindrome III │ └── Solution.py ├── 1217. Minimum Cost to Move Chips to The Same Position │ └── Solution.py ├── 1218. Longest Arithmetic Subsequence of Given Difference │ └── Solution.java ├── 1219. Path with Maximum Gold │ └── Solution.java ├── 122. Best Time to Buy and Sell Stock II │ └── Solution.java ├── 1220. Count Vowels Permutation │ └── Solution.py ├── 1223. Dice Roll Simulation │ └── Solution.java ├── 1226. The Dining Philosophers │ └── Solution.java ├── 1228. Missing Number In Arithmetic Progression │ └── Solution.py ├── 1229. Meeting Scheduler │ └── Solution.java ├── 123. Best Time to Buy and Sell Stock III │ └── Solution.java ├── 1231. Divide Chocolate │ └── Solution.py ├── 1232. Check If It Is a Straight Line │ └── Solution.java ├── 1235. Maximum Profit in Job Scheduling │ └── Solution.py ├── 1236. Web Crawler │ └── Solution.py ├── 1237. Find Positive Integer Solution for a Given Equation │ └── Solution.py ├── 1239. Maximum Length of a Concatenated String with Unique Characters │ └── Solution.py ├── 124. Binary Tree Maximum Path Sum │ └── Solution.java ├── 1240. Tiling a Rectangle with the Fewest Squares │ └── Solution.py ├── 1242. Web Crawler Multithreaded │ └── Solution.java ├── 1243. Array Transformation │ └── Solution.py ├── 1244. Design A Leaderboard │ ├── Solution.py │ └── Solution2.py ├── 1245. Tree Diameter │ └── Solution.py ├── 1246. Palindrome Removal │ └── Solution.py ├── 1248. Count Number of Nice Subarrays │ └── Solution.py ├── 1249. Minimum Remove to Make Valid Parentheses │ └── Solution.py ├── 125. Valid Palindrome │ └── Solution.java ├── 1254. Number of Closed Islands │ └── Solution.py ├── 126. Word Ladder II │ └── Solution.java ├── 1263. Minimum Moves to Move a Box to Their Target Location │ └── Solution.py ├── 1265. Print Immutable Linked List in Reverse │ └── Solution.java ├── 1266. Minimum Time Visiting All Points │ └── Solution.py ├── 1269. Number of Ways to Stay in the Same Place After Some Steps │ └── Solution.py ├── 127. Word Ladder │ └── Solution.java ├── 1271. Hexspeak │ └── Solution.py ├── 1272. Remove Interval │ └── Solution.py ├── 1273. Delete Tree Nodes │ └── Solution.py ├── 1275. Find Winner on a Tic Tac Toe Game │ └── Solution.py ├── 1276. Number of Burgers with No Waste of Ingredients │ └── Solution.py ├── 1277. Count Square Submatrices with All Ones │ └── Solution.py ├── 1279. Traffic Light Controlled Intersection │ └── Solution.java ├── 128. Longest Consecutive Sequence │ ├── Solution.java │ └── Solution2.java ├── 1281. Subtract the Product and Sum of Digits of an Integer │ └── Solution.java ├── 1282. Group the People Given the Group Size They Belong To │ └── Solution.py ├── 1283. Find the Smallest Divisor Given a Threshold │ └── Solution.py ├── 1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix │ └── Solution.py ├── 1286. Iterator for Combination │ └── Solution.py ├── 1287. Element Appearing More Than 25% In Sorted Array │ └── Solution.py ├── 1288. Remove Covered Intervals │ └── Solution.py ├── 129. Sum Root to Leaf Numbers │ └── Solution.java ├── 1290. Convert Binary Number in a Linked List to Integer │ └── Solution.py ├── 1291. Sequential Digits │ ├── Solution.py │ └── Solution2.py ├── 1293. Shortest Path in a Grid with Obstacles Elimination │ └── Solution.py ├── 1295. Find Numbers with Even Number of Digits │ ├── Solution.cpp │ └── Solution.py ├── 1297. Maximum Number of Occurrences of a Substring │ └── Solution.py ├── 1299. Replace Elements with Greatest Element on Right Side │ └── Solution.py ├── 13. Roman to Integer │ └── Solution.java ├── 130. Surrounded Regions │ └── Solution.java ├── 1302. Deepest Leaves Sum │ └── Solution.py ├── 1304. Find N Unique Integers Sum up to Zero │ └── Solution.java ├── 1306. Jump Game III │ └── Solution.java ├── 1307. Verbal Arithmetic Puzzle │ └── Solution.java ├── 131. Palindrome Partitioning │ └── Solution.py ├── 1310. XOR Queries of a Subarray │ ├── Solution.py │ └── Solution2.py ├── 1311. Get Watched Videos by Your Friends │ └── Solution.java ├── 1312. Minimum Insertion Steps to Make a String Palindrome │ └── Solution.java ├── 1313. Decompress Run-Length Encoded List │ └── Solution.java ├── 1315. Sum of Nodes with Even-Valued Grandparent │ └── Solution.py ├── 1316. Distinct Echo Substrings │ └── Solution.java ├── 1317. Convert Integer to the Sum of Two No-Zero Integers │ └── Solution.py ├── 1319. Number of Operations to Make Network Connected │ └── Solution.py ├── 132. Palindrome Partitioning II │ └── Solution.java ├── 1320. Minimum Distance to Type a Word Using Two Fingers │ └── Solution.py ├── 1323. Maximum 69 Number │ └── Solution.py ├── 1325. Delete Leaves With a Given Value │ └── Solution.java ├── 1326. Minimum Number of Taps to Open to Water a Garden │ └── Solution.py ├── 1329. Sort the Matrix Diagonally │ └── Solution.py ├── 133. Clone Graph │ └── Solution.java ├── 1332. Remove Palindromic Subsequences │ └── Solution.py ├── 1335. Minimum Difficulty of a Job Schedule │ └── Solution.java ├── 1337. The K Weakest Rows in a Matrix │ └── Solution.py ├── 1338. Reduce Array Size to The Half │ └── Solution.py ├── 1339. Maximum Product of Splitted Binary Tree │ └── Solution.java ├── 134. Gas Station │ └── Solution.java ├── 1342. Number of Steps to Reduce a Number to Zero │ └── Solution.py ├── 1344. Angle Between Hands of a Clock │ └── Solution.py ├── 1345. Jump Game IV │ ├── Solution.py │ └── Solution2.py ├── 1347. Minimum Number of Steps to Make Two Strings Anagram │ └── Solution.py ├── 1348. Tweet Counts Per Frequency │ ├── Solution.py │ └── Solution2.py ├── 1349. Maximum Students Taking Exam │ └── Solution.py ├── 135. Candy │ └── Solution.py ├── 1351. Count Negative Numbers in a Sorted Matrix │ └── Solution.py ├── 1352. Product of the Last K Numbers │ └── Solution.py ├── 1353. Maximum Number of Events That Can Be Attended │ └── Solution.py ├── 1357. Apply Discount Every n Orders │ └── Solution.py ├── 1359. Count All Valid Pickup and Delivery Options │ └── Solution.py ├── 136. Single Number │ └── Solution.java ├── 1360. Number of Days Between Two Dates │ └── Solution.py ├── 1361. Validate Binary Tree Nodes │ └── Solution.py ├── 1365. How Many Numbers Are Smaller Than the Current Number │ └── Solution.cpp ├── 1367. Linked List in Binary Tree │ └── Solution.py ├── 137. Single Number │ └── Solution.py ├── 1372. Longest ZigZag Path in a Binary Tree │ └── Solution.py ├── 1373. Maximum Sum BST in Binary Tree │ └── Solution.java ├── 1375. Bulb Switcher III │ └── Solution.py ├── 1376. Time Needed to Inform All Employees │ └── Solution.py ├── 1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree │ └── Solution.py ├── 138. Copy List with Random Pointer │ └── Solution.java ├── 1381. Design a Stack With Increment Operation │ └── CustomStack.py ├── 1382. Balance a Binary Search Tree │ └── Solution.py ├── 1383. Maximum Performance of a Team │ └── Solution.py ├── 139. Word Break │ └── Solution.java ├── 1391. Check if There is a Valid Path in a Grid │ └── Solution.py ├── 1392. Longest Happy Prefix │ └── Solution.py ├── 1395. Count Number of Teams │ └── Solution.py ├── 1396. Design Underground System │ └── UndergroundSystem.py ├── 14. Longest Common Prefix │ └── Solution.py ├── 140. Word Break II │ └── Solution.java ├── 1405. Longest Happy String │ └── Solution.py ├── 1406. Stone Game III │ └── Solution.py ├── 141. Linked List Cycle │ └── Solution.java ├── 1411. Number of Ways to Paint N × 3 Grid │ └── Solution.py ├── 1416. Restore The Array │ └── Solution.py ├── 142. Linked List Cycle II │ └── Solution.java ├── 1423. Maximum Points You Can Obtain from Cards │ └── Solution.py ├── 1424. Diagonal Traverse II │ ├── Solution.py │ └── Solution2.py ├── 1425. Constrained Subsequence Sum │ ├── Solution.py │ └── Solution2.py ├── 1426. Counting Elements │ └── Solution.py ├── 1427. Perform String Shifts │ └── Solution.py ├── 1428. Leftmost Column with at Least a One │ └── Solution.py ├── 1429. First Unique Number │ └── Solution.py ├── 143. Reorder List │ └── Solution.java ├── 1430. Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree │ └── Solution.py ├── 1431. Kids With the Greatest Number of Candies │ └── Solution.cpp ├── 1437. Check If All 1's Are at Least Length K Places Away │ └── Solution.py ├── 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit │ └── Solution.py ├── 1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows │ └── Solution.py ├── 144. Binary Tree Preorder Traversal │ └── Solution.java ├── 1441. Build an Array With Stack Operations │ └── Solution.py ├── 1444. Number of Ways of Cutting a Pizza │ └── Solution.py ├── 1446. Consecutive Characters │ └── Solution.py ├── 1448. Count Good Nodes in Binary Tree │ └── Solution.py ├── 145. Binary Tree Postorder Traversal │ └── Solution.java ├── 1456. Maximum Number of Vowels in a Substring of Given Length │ └── Solution.py ├── 1457. Pseudo-Palindromic Paths in a Binary Tree │ └── Solution.py ├── 1458. Max Dot Product of Two Subsequences │ └── Solution.py ├── 146. LRU Cache │ └── Solution.java ├── 1460. Make Two Arrays Equal by Reversing Sub-arrays │ └── Solution.py ├── 1461. Check If a String Contains All Binary Codes of Size K │ ├── Solution.py │ └── Solution2.py ├── 1463. Cherry Pickup II │ └── Solution.py ├── 1464. Maximum Product of Two Elements in an Array │ └── Solution.py ├── 1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts │ └── Solution.py ├── 1466. Reorder Routes to Make All Paths Lead to the City Zero │ └── Solution.py ├── 1469. Find All The Lonely Nodes │ └── Solution.py ├── 147. Insertion Sort List │ └── Solution.java ├── 1470. Shuffle the Array │ └── Solution.py ├── 1472. Design Browser History │ └── Solution.py ├── 1477. Find Two Non-overlapping Sub-arrays Each With Target Sum │ └── Solution.py ├── 1478. Allocate Mailboxes │ └── Solution.py ├── 148. Sort List │ └── Solution.java ├── 1480. Running Sum of 1d Array │ └── Solution.py ├── 1483. Kth Ancestor of a Tree Node │ └── TreeAncestor.py ├── 1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree │ └── Solution.py ├── 149. Max Points on a Line │ └── Solution.java ├── 1490. Clone N-ary Tree │ └── Solution.java ├── 1492. The kth Factor of n │ └── Solution.py ├── 1493. Longest Subarray of 1's After Deleting One Element │ └── Solution.py ├── 1497. Check If Array Pairs Are Divisible by k │ └── Solution.py ├── 15. 3Sum │ └── Solution.java ├── 150. Evaluate Reverse Polish Notation │ └── Solution.java ├── 1500. Design a File Sharing System │ └── Solution.py ├── 1504. Count Submatrices With All Ones │ └── Solution.py ├── 1506. Find Root of N-Ary Tree │ └── Solution.py ├── 1509. Minimum Difference Between Largest and Smallest Value in Three Moves │ └── Solution.py ├── 151. Reverse Words in a String │ └── Solution.java ├── 1510. Stone Game IV │ └── Solution.java ├── 1512. Number of Good Pairs │ └── Solution.rs ├── 1519. Number of Nodes in the Sub-Tree With the Same Label │ └── Solution.py ├── 152. Maximum Product Subarray │ └── Solution.Java ├── 1520. Maximum Number of Non-Overlapping Substrings │ └── Solution.py ├── 1522. Diameter of N-Ary Tree │ └── Solution.py ├── 1528. Shuffle String │ └── Solution.py ├── 153. Find Minimum in Rotated Sorted Array │ └── Solution.java ├── 1530. Number of Good Leaf Nodes Pairs │ └── Solution.py ├── 1534. Count Good Triplets │ └── Solution.rs ├── 1539. Kth Missing Positive Number │ └── Solution.py ├── 154. Find Minimum in Rotated Sorted Array II │ └── Solution.py ├── 1541. Minimum Insertions to Balance a Parentheses String │ └── Solution.py ├── 1547. Minimum Cost to Cut a Stick │ └── Solution.py ├── 155. Min Stack │ └── Solution.java ├── 1551. Minimum Operations to Make Array Equal │ └── Solution.py ├── 1554. Strings Differ by One Character │ ├── Solution.py │ └── Solution2.py ├── 1557. Minimum Number of Vertices to Reach All Nodes │ └── Solution.py ├── 1559. Detect Cycles in 2D Grid │ └── Solution.py ├── 156. Binary Tree Upside Down │ └── Solution.py ├── 1564. Put Boxes Into the Warehouse I │ └── Solution.py ├── 1566. Detect Pattern of Length M Repeated K or More Times │ └── Solution.py ├── 157. Read N Characters Given Read4 │ └── Solution.py ├── 1570. Dot Product of Two Sparse Vectors │ └── Solution.py ├── 1572. Matrix Diagonal │ └── Solution.java ├── 1573. Number of Ways to Split a String │ └── Solution.py ├── 1576. Replace All ?'s to Avoid Consecutive Repeating Characters │ └── Solution.py ├── 1578. Minimum Deletion Cost to Avoid Repeating Letters │ └── Solution.py ├── 158. Read N Characters Given Read4 II - Call multiple times │ └── Solution.java ├── 1584. Min Cost to Connect All Points │ └── Solution.py ├── 1588. Sum of All Odd Length Subarrays │ └── Solution.py ├── 1589. Maximum Sum Obtained of Any Permutation │ └── Solution.py ├── 159. Longest Substring with At Most Two Distinct Characters │ └── Solution.java ├── 1592. Rearrange Spaces Between Words │ └── Solution.py ├── 16. 3Sum Closest │ └── Solution.py ├── 160. Intersection of Two Linked Lists │ └── Solution.java ├── 1602. Find Nearest Right Node in Binary Tree │ └── Solution.py ├── 1603. Design Parking System │ └── Solution.py ├── 1604. Alert Using Same Key-Card Three or More Times in a One Hour Period │ └── Solution.py ├── 1605. Find Valid Matrix Given Row and Column Sums │ └── Solution.py ├── 1606. Find Servers That Handled Most Number of Requests │ └── Solution.py ├── 161. One Edit Distance │ └── Solution.py ├── 1610. Maximum Number of Visible Points │ └── Solution.py ├── 1611. Minimum One Bit Operations to Make Integers Zero │ └── Solution.py ├── 1614. Maximum Nesting Depth of the Parentheses │ └── Solution.py ├── 1619. Mean of Array After Removing Some Elements │ └── Solution.py ├── 162. Find Peak Element │ └── Solution.java ├── 1622. Fancy Sequence │ └── Solution.py ├── 1629. Slowest Key │ └── Solution.py ├── 163. Missing Ranges │ └── Solution.py ├── 1631. Path With Minimum Effort │ └── Solution.py ├── 1632. Rank Transform of a Matrix │ └── Solution.py ├── 1636. Sort Array by Increasing Frequency │ └── Solution.py ├── 164. Maximum Gap │ └── Solution.py ├── 1640. Check Array Formation Through Concatenation │ └── Solution.py ├── 1641. Count Sorted Vowel Strings │ └── Solution.py ├── 1646. Get Maximum in Generated Array │ └── Solution.py ├── 1647. Minimum Deletions to Make Character Frequencies Unique │ └── Solution.py ├── 1649. Create Sorted Array through Instructions │ └── Solution.java ├── 165. Compare Version Numbers │ └── Solution.py ├── 1650. Lowest Common Ancestor of a Binary Tree III │ └── Solution.py ├── 1653. Minimum Deletions to Make String Balanced │ └── Solution.py ├── 1657. Determine if Two Strings Are Close │ └── Solution.py ├── 1658. Minimum Operations to Reduce X to Zero │ └── Solution.py ├── 166. Fraction to Recurring Decimal │ └── Solution.py ├── 1660. Correct a Binary Tree │ └── Solution.py ├── 1662. Check If Two String Arrays are Equivalent │ └── Solution.py ├── 1663. Smallest String With A Given Numeric Value │ └── Solution.py ├── 167. Two Sum II - Input array is sorted │ └── Solution.java ├── 1671. Minimum Number of Removals to Make Mountain Array │ └── Solution.py ├── 1672. Richest Customer Wealth │ └── Solution.rs ├── 1673. Find the Most Competitive Subsequence │ └── Solution.py ├── 1675. Minimize Deviation in Array │ └── Solution.py ├── 1679. Max Number of K-Sum Pairs │ └── Solution.py ├── 1680. Concatenation of Consecutive Binary Numbers │ └── Solution.py ├── 1684. Count the Number of Consistent Strings │ └── Solution.py ├── 169. Majority Element │ └── Solution.java ├── 1692. Count Ways to Distribute Candies │ └── Solution.py ├── 1697. Checking Existence of Edge Length Limited Paths │ └── Solution.py ├── 17. Letter Combinations of a Phone Number │ └── Solution.java ├── 170. Two Sum III - Data structure design │ └── Solution.py ├── 1700. Number of Students Unable to Eat Lunch │ └── Solution.py ├── 1704. Determine if String Halves Are Alike │ └── Solution.py ├── 1707. Maximum XOR With an Element From Array │ └── Solution.java ├── 171. Excel Sheet Column Number │ └── Solution.py ├── 1710. Maximum Units on a Truck │ └── Solution.py ├── 1711. Count Good Meals │ └── Solution.py ├── 1712. Ways to Split Array Into Three Subarrays │ └── Solution.py ├── 1718. Construct the Lexicographically Largest Valid Sequence │ └── Solution.py ├── 172. Factorial Trailing Zeroes │ └── Solution.java ├── 1721. Swapping Nodes in a Linked List │ └── Solution.py ├── 1724. Checking Existence of Edge Length Limited Paths II │ └── Solution.py ├── 173. Binary Search Tree Iterator │ └── Solution.java ├── 1730. Shortest Path to Get Food │ └── Solution.py ├── 174. Dungeon Game │ └── Solution.py ├── 1740. Find Distance in a Binary Tree │ └── Solution.py ├── 1743. Restore the Array From Adjacent Pairs │ └── Solution.py ├── 1748. Sum of Unique Elements │ └── Solution.py ├── 1751. Maximum Number of Events That Can Be Attended II │ ├── Solution.py │ └── Solution2.py ├── 1762. Buildings With an Ocean View │ └── Solution.py ├── 1774. Closest Dessert Cost │ └── Solution.py ├── 1775. Equal Sum Arrays With Minimum Number of Operations │ └── Solution.py ├── 1785. Minimum Elements to Add to Form a Given Sum │ └── Solution.py ├── 1786. Number of Restricted Paths From First to Last Node │ └── Solution.py ├── 179. Largest Number │ └── Solution.java ├── 1797. Design Authentication Manager │ └── Solution.py ├── 18. 4Sum │ └── Solution.java ├── 1801. Number of Orders in the Backlog │ └── Solution.py ├── 1817. Finding the Users Active Minutes │ └── Solution.py ├── 1820. Maximum Number of Accepted Invitations │ └── Solution.py ├── 1824. Minimum Sideway Jumps │ └── Solution.java ├── 1832. Check if the Sentence Is Pangram │ └── Solution.cpp ├── 1834. Single-Threaded CPU │ └── Solution.py ├── 1838. Frequency of the Most Frequent Element │ └── Solution.py ├── 1849. Splitting a String Into Descending Consecutive Values │ └── Solution.py ├── 1857. Largest Color Value in a Directed Graph │ └── Solution.py ├── 1859. Sorting the Sentence │ └── Solution.py ├── 186. Reverse Words in a String II │ └── Solution.java ├── 1861. Rotating the Box │ └── Solution.py ├── 1866. Number of Ways to Rearrange Sticks With K Sticks Visible │ └── Solution.py ├── 1868. Product of Two Run-Length Encoded Arrays │ └── Solution.py ├── 187. Repeated DNA Sequences │ └── Solution.py ├── 188. Best Time to Buy and Sell Stock IV │ ├── Solution.java │ └── Solution2.py ├── 189. Rotate Array │ └── Solution.java ├── 1891. Cutting Ribbons │ └── Solution.py ├── 190. Reverse Bits │ └── Solution.java ├── 1901. Find a Peak Element II │ └── Solution.py ├── 1908. Game of Nim │ └── Solution.py ├── 191. Number of 1 Bits │ └── Solution.java ├── 1926. Nearest Exit from Entrance in Maze │ └── Solution.py ├── 1928. Minimum Cost to Reach Destination in Time │ └── Solution.py ├── 1929. Concatenation of Array │ └── Solution.cpp ├── 1937. Maximum Number of Points with Cost │ └── Solution.py ├── 1938. Maximum Genetic Difference Query │ └── Solution.java ├── 1944. Number of Visible People in a Queue │ └── Solution.py ├── 1973. Count Nodes Equal to Sum of Descendants │ └── Solution.py ├── 199. Binary Tree Right Side View │ └── Solution.java ├── 1996. The Number of Weak Characters in the Game │ ├── Solution.java │ └── Solution2.py ├── 1997. First Day Where You Have Been in All the Rooms │ └── Solution.py ├── 2. Add Two Numbers │ └── Solution.java ├── 20. Valid Parentheses │ └── Solution.java ├── 200. Number of Islands │ ├── Solution.java │ └── Solution2.java ├── 2003. Smallest Missing Genetic Value in Each Subtree │ └── Solution.py ├── 2007. Find Original Array From Doubled Array │ └── Solution.py ├── 201. Bitwise AND of Numbers Range │ └── Solution.py ├── 2013. Detect Squares │ └── Solution.py ├── 2018. Check if Word Can Be Placed In Crossword │ └── Solution.py ├── 202. Happy Number │ ├── Solution.java │ └── Solution2.java ├── 203. Remove Linked List Elements │ ├── Solution.java │ └── Solution2.java ├── 2034. Stock Price Fluctuation │ └── Solution.java ├── 204. Count Primes │ └── Solution.java ├── 205. Isomorphic Strings │ └── Solution.py ├── 2059. Minimum Operations to Convert Number │ └── Solution.java ├── 206. Reverse Linked List │ └── Solution.java ├── 207. Course Schedule │ └── Solution.java ├── 208. Implement Trie (Prefix Tree) │ └── Solution.java ├── 2080. Range Frequency Queries │ └── Solution.py ├── 2085. Count Common Words With One Occurrence │ └── Solution.cpp ├── 209. Minimum Size Subarray Sum │ └── Solution.py ├── 2092. Find All People With Secret │ └── Solution.py ├── 2096. Step-By-Step Directions From a Binary Tree Node to Another │ └── Solution.py ├── 21. Merge Two Sorted Lists │ └── Solution.java ├── 210. Course Schedule II │ └── Solution.java ├── 2101. Detonate the Maximum Bombs │ └── Solution.py ├── 211. Add and Search Word - Data structure design │ └── WordDictionary.java ├── 2115. Find All Possible Recipes from Given Supplies │ └── Solution.py ├── 212. Word Search II │ └── Solution.java ├── 2128. Remove All Ones With Row and Column Flips │ └── Solution.py ├── 213. House Robber II │ └── Solution.cpp ├── 2135. Count Words Obtained After Adding a Letter │ └── Solution.py ├── 214. Shortest Palindrome │ └── Solution.py ├── 215. Kth Largest Element in an Array │ └── Solution.java ├── 2158. Amount of New Area Painted Each Day │ └── Solution.py ├── 216. Combination Sum III │ └── Solution.py ├── 2162. Minimum Cost to Set Cooking Time │ └── Solution.py ├── 2164. Sort Even and Odd Indices Independently │ └── Solution.py ├── 217. Contains Duplicate │ └── Solution.java ├── 2178. Maximum Split of Positive Even Integers │ └── Solution.py ├── 218. The Skyline Problem │ └── Solution.py ├── 219. Contains Duplicate II │ └── Solution.py ├── 22. Generate Parentheses │ └── Solution.java ├── 220. Contains Duplicate III │ └── Solution.py ├── 221. Maximal Square │ └── Solution.java ├── 222. Count Complete Tree Nodes │ ├── Solution.java │ └── Solution2.py ├── 223. Rectangle Area │ └── Solution.java ├── 224. Basic Calculator │ └── Solution.java ├── 2246. Longest Path With Different Adjacent Characters │ └── Solution.py ├── 225. Implement Stack using Queues │ └── Solution.java ├── 226. Invert Binary Tree │ └── Solution.java ├── 227. Basic Calculator II │ └── Solution.java ├── 2271. Maximum White Tiles Covered by a Carpet │ └── Solution.py ├── 228. Summary Ranges │ └── Solution.java ├── 2285. Maximum Total Importance of Roads │ └── Solution.py ├── 229. Majority Element II │ └── Solution.py ├── 2296. Design a Text Editor │ └── Solution.py ├── 23. Merge k Sorted Lists │ └── Solution.java ├── 230. Kth Smallest Element in a BST │ └── Solution.py ├── 231. Power of Two │ └── Solution.java ├── 232. Implement Queue using Stacks │ └── Solution.java ├── 234. Palindrome Linked List │ └── Solution.java ├── 235. Lowest Common Ancestor of a Binary Search Tree │ └── Solution.java ├── 236. Lowest Common Ancestor of a Binary Tree │ └── Solution.java ├── 2361. Minimum Costs Using the Train Line │ └── Solution.cpp ├── 237. Delete Node in a Linked List │ └── Solution.java ├── 2375. Construct Smallest Number From DI String │ └── Solution.py ├── 2376. Count Special Integers │ └── Solution.py ├── 238. Product of Array Except Self │ └── Solution.java ├── 239. Sliding Window Maximum │ └── Solution.java ├── 2392. Build a Matrix With Conditions │ └── Solution.cpp ├── 2398. Maximum Number of Robots Within Budget │ └── Solution.py ├── 24. Swap Nodes in Pairs │ └── Solution.java ├── 240. Search a 2D Matrix II │ ├── Solution.java │ └── Solution2.py ├── 2400. Number of Ways to Reach a Position After Exactly k Steps │ ├── Solution.py │ └── Solution2.cpp ├── 2402. Meeting Rooms III │ └── Solution.py ├── 241. Different Ways to Add Parentheses │ └── Solution.py ├── 242. Valid Anagram │ └── Solution.java ├── 2424. Longest Uploaded Prefix │ └── Solution.py ├── 243. Shortest Word Distance │ └── Solution.py ├── 244. Shortest Word Distance II │ └── Solution.py ├── 245. Shortest Word Distance III │ └── Solution.py ├── 246. Strobogrammatic Number │ └── Solution.py ├── 247. Strobogrammatic Number II │ └── Solution.py ├── 249. Group Shifted Strings │ └── Solution.py ├── 25. Reverse Nodes in k-Group │ └── Solution.java ├── 250. Count Univalue Subtrees │ └── Solution.py ├── 2501. Longest Square Streak in an Array │ └── Solution.py ├── 2502. Design Memory Allocator │ └── Solution.cpp ├── 2508. Add Edges to Make Degrees of All Nodes Even │ └── Solution.py ├── 251. Flatten 2D Vector │ └── Solution.py ├── 252. Meeting Rooms │ └── Solution.py ├── 253. Meeting Rooms II │ └── Solution.java ├── 254. Factor Combinations │ └── Solution.java ├── 255. Verify Preorder Sequence in Binary Search Tree │ └── Solution.py ├── 256. Paint House │ └── Solution.java ├── 257. Binary Tree Paths │ └── Solution.py ├── 258. Add Digits │ └── Solution.py ├── 259. 3Sum Smaller │ └── Solution.py ├── 26. Remove Duplicates from Sorted Array │ └── Solution.java ├── 260. Single Number III │ └── Solution.py ├── 261. Graph Valid Tree │ └── Solution.java ├── 263. Ugly Number │ └── Solution.cpp ├── 264. Ugly Number II │ └── Solution.java ├── 265. Paint House II │ └── Solution.java ├── 266. Palindrome Permutation │ └── Solution.py ├── 268. Missing Number │ └── Solution.java ├── 269. Alien Dictionary │ └── Solution.java ├── 27. Remove Element │ └── Solution.java ├── 270. Closest Binary Search Tree Value │ └── Solution.py ├── 271. Encode and Decode Strings │ └── Solution.py ├── 273. Integer to English Words │ └── Solution.py ├── 274. H-Index │ └── Solution.py ├── 275. H-Index II │ └── Solution.py ├── 276. Paint Fence │ └── Solution.py ├── 277. Find the Celebrity │ └── Solution.java ├── 278. First Bad Version │ └── Solution.java ├── 279. Perfect Squares │ └── Solution.java ├── 28. Implement strStr() │ └── Solution.cpp ├── 280. Wiggle Sort │ └── Solution.java ├── 281. Zigzag Iterator │ └── Solution.py ├── 282. Expression Add Operators │ └── Solution.py ├── 283. Move Zeroes │ └── Solution.java ├── 284. Peeking Iterator │ └── Solution.java ├── 285. Inorder Successor in BST │ └── Solution.py ├── 286. Walls and Gates │ └── Solution.py ├── 287. Find the Duplicate Number │ ├── Solution.java │ └── Solution2.py ├── 288. Unique Word Abbreviation │ └── ValidWordAbbr.py ├── 289. Game of Life │ └── Solution.java ├── 29. Divide Two Integers │ └── Solution.py ├── 290. Word Pattern │ └── Solution.py ├── 292. Nim Game │ └── Solution.java ├── 294. Flip Game II │ └── Solution.py ├── 295. Find Median from Data Stream │ └── MedianFinder.py ├── 296. Best Meeting Point │ └── Solution.py ├── 297. Serialize and Deserialize Binary Tree │ └── Codec.java ├── 298. Binary Tree Longest Consecutive Sequence │ └── Solution.py ├── 299. Bulls and Cows │ └── Solution.py ├── 3. Longest Substring Without Repeating Characters │ └── Solution.java ├── 300. Longest Increasing Subsequence │ ├── Solution.java │ └── Solution2.java ├── 301. Remove Invalid Parentheses │ └── Solution.java ├── 302. Smallest Rectangle Enclosing Black Pixels │ └── Solution.py ├── 303. Range Sum Query - Immutable │ └── Solution.java ├── 304. Range Sum Query 2D - Immutable │ └── Solution.java ├── 305. Number of Islands II │ └── Solution.py ├── 306. Additive Number │ └── Solution.py ├── 307. Range Sum Query - Mutable │ ├── Solution.java │ └── Solution2.java ├── 308. Range Sum Query 2D - Mutable │ └── NumMatrix.java ├── 309. Best Time to Buy and Sell Stock with Cooldown │ └── Solution.java ├── 31. Next Permutation │ └── Solution.java ├── 310. Minimum Height Trees │ └── Solution.java ├── 311. Sparse Matrix Multiplication │ └── Solution.py ├── 313. Super Ugly Number │ └── Solution.java ├── 314. Binary Tree Vertical Order Traversal │ └── Solution.py ├── 315. Count of Smaller Numbers After Self │ └── Solution.java ├── 316. Remove Duplicate Letters │ ├── Solution.java │ └── Solution.py ├── 317. Shortest Distance from All Buildings │ └── Solution.py ├── 319. Bulb Switcher │ └── Solution.java ├── 32. Longest Valid Parentheses │ └── Solution.java ├── 322. Coin Change │ └── Solution.java ├── 323. Number of Connected Components in an Undirected Graph │ └── Solution.py ├── 325. Maximum Size Subarray Sum Equals k │ └── Solution.py ├── 326. Power of Three │ └── Solution.py ├── 327. Count of Range Sum │ └── Solution.py ├── 328. Odd Even Linked List │ └── Solution.java ├── 329. Longest Increasing Path in a Matrix │ └── Solution.java ├── 33. Search in Rotated Sorted Array │ └── Solution.java ├── 330. Patching Array │ └── Solution.py ├── 331. Verify Preorder Serialization of a Binary Tree │ └── Solution.py ├── 332. Reconstruct Itinerary │ └── Solution.java ├── 333. Largest BST Subtree │ └── Solution.py ├── 334. Increasing Triplet Subsequence │ └── Solution.py ├── 336. Palindrome Pairs │ └── Solution.java ├── 337. House Robber III │ └── Solution.java ├── 338. Counting Bits │ └── Solution.java ├── 339. Nested List Weight Sum │ └── Solution.py ├── 34. Find First and Last Position of Element in Sorted Array │ └── Solution.java ├── 340. Longest Substring with At Most K Distinct Characters │ └── Solution.java ├── 341. Flatten Nested List Iterator │ └── Solution.java ├── 342. Power of Four │ └── Solution.java ├── 343. Integer Break │ └── Solution.java ├── 344. Reverse String │ └── Solution.java ├── 345. Reverse Vowels of a String │ └── Solution.java ├── 346. Moving Average from Data Stream │ └── Solution.java ├── 347. Top K Frequent Elements │ └── Solution.java ├── 348. Design Tic-Tac-Toe │ └── Solution.py ├── 349. Intersection of Two Arrays │ └── Solution.java ├── 35. Search Insert Position │ └── Solution.java ├── 350. Intersection of Two Arrays II │ └── Solution.java ├── 351. Android Unlock Patterns │ └── Solution.py ├── 352. Data Stream as Disjoint Intervals │ └── Solution.java ├── 353. Design Snake Game │ └── Solution.py ├── 354. Russian Doll Envelopes │ ├── Solution.java │ └── Solution2.java ├── 355. Design Twitter │ └── Solution.py ├── 356. Line Reflection │ └── Solution.py ├── 357. Count Numbers with Unique Digits │ └── Solution.java ├── 358. Rearrange String k Distance Apart │ └── Solution.py ├── 359. Logger Rate Limiter │ └── Solution.py ├── 360. Sort Transformed Array │ └── Solution.py ├── 361. Bomb Enemy │ └── Solution.py ├── 362. Design Hit Counter │ └── Solution.java ├── 364. Nested List Weight Sum II │ └── Solution.java ├── 365. Water and Jug Problem │ └── Solution.java ├── 366. Find Leaves of Binary Tree │ └── Solution.java ├── 367. Valid Perfect Square │ └── Solution.py ├── 368. Largest Divisible Subset │ └── Solution.py ├── 369. Plus One Linked List │ └── Solution.py ├── 37. Sudoku Solver │ └── Solution.java ├── 370. Range Addition │ └── Solution.py ├── 372. Super Pow │ └── Solution.java ├── 373. Find K Pairs with Smallest Sums │ └── Solution.py ├── 374. Guess Number Higher or Lower │ └── Solution.py ├── 375. Guess Number Higher or Lower II │ └── Solution.py ├── 376. Wiggle Subsequence │ └── Solution.java ├── 377. Combination Sum IV │ └── Solution.py ├── 378. Kth Smallest Element in a Sorted Matrix │ └── Solution.py ├── 379. Design Phone Directory │ └── PhoneDirectory.py ├── 38. Count and Say │ └── Solution.py ├── 380. Insert Delete GetRandom O(1) │ └── Solution.java ├── 381. Insert Delete GetRandom O(1) - Duplicates allowed │ └── Solution.py ├── 382. Linked List Random Node │ └── Solution.java ├── 383. Ransom Note │ └── Solution.py ├── 384. Shuffle an Array │ └── Solution.java ├── 386. Lexicographical Numbers │ ├── Solution.cpp │ └── Solution.java ├── 387. First Unique Character in a String │ └── Solution.java ├── 388. Longest Absolute File Path │ └── Solution.java ├── 389. Find the Difference │ └── Solution.py ├── 39. Combination Sum │ └── Solution.java ├── 392. Is Subsequence │ └── Solution.java ├── 393. UTF-8 Validation │ └── Solution.py ├── 394. Decode String │ ├── Solution.java │ └── Solution2.py ├── 395. Longest Substring with At Least K Repeating Characters │ └── Solution.py ├── 396. Rotate Function │ └── Solution.py ├── 397. Integer Replacement │ └── Solution.py ├── 398. Random Pick Index │ └── Solution.py ├── 399. Evaluate Division │ └── Solution.java ├── 4. Median of Two Sorted Arrays │ └── Solution.java ├── 40. Combination Sum II │ └── Solution.cpp ├── 402. Remove K Digits │ └── Solution.java ├── 403. Frog Jump │ └── Solution.py ├── 404. Sum of Left Leaves │ └── Solution.py ├── 406. Queue Reconstruction by Height │ └── Solution.java ├── 408. Valid Word Abbreviation │ └── Solution.py ├── 409. Longest Palindrome │ └── Solution.py ├── 41. First Missing Positive │ └── Solution.java ├── 410. Split Array Largest Sum │ ├── Solution.java │ └── Solution2.java ├── 412. Fizz Buzz │ └── Solution.py ├── 413. Arithmetic Slices │ └── Solution.java ├── 414. Third Maximum Number │ └── Solution.py ├── 415. Add Strings │ └── Solution.java ├── 416. Partition Equal Subset Sum │ └── Solution.java ├── 417. Pacific Atlantic Water Flow │ └── Solution.py ├── 418. Sentence Screen Fitting │ └── Solution.py ├── 419. Battleships in a Board │ └── Solution.py ├── 42. Trapping Rain Water │ └── Solution.java ├── 420. Strong Password Checker │ └── Solution.py ├── 421. Maximum XOR of Two Numbers in an Array │ └── Solution.py ├── 423. Reconstruct Original Digits from English │ └── Solution.py ├── 424. Longest Repeating Character Replacement │ └── Solution.py ├── 425. Word Squares │ └── Solution.py ├── 426. Convert Binary Search Tree to Sorted Doubly Linked List │ └── Solution.java ├── 427. Construct Quad Tree │ └── Solution.py ├── 428. Serialize and Deserialize N-ary Tree │ └── Solution.py ├── 43. Multiply Strings │ ├── Solution.java │ └── Solution.py ├── 430. Flatten a Multilevel Doubly Linked List │ └── Solution.java ├── 431. Encode N-ary Tree to Binary Tree │ └── Solution.java ├── 432. All O(1) Data Structure │ └── Solution.java ├── 433. Minimum Genetic Mutation │ └── Solution.py ├── 434. Number of Segments in a String │ └── Solution.py ├── 435. Non-overlapping Intervals │ └── sol.py ├── 436. Find Right Interval │ └── Solution.py ├── 437. Path Sum III │ └── Solution.py ├── 438. Find All Anagrams in a String │ └── Solution.java ├── 44. Wildcard Matching │ └── Solution.java ├── 441. Arranging Coins │ └── Solution.py ├── 442. Find All Duplicates in an Array │ └── Solution.py ├── 443. String Compression │ └── Solution.java ├── 444. Sequence Reconstruction │ └── Solution.py ├── 445. Add Two Numbers II │ └── Solution.java ├── 447. Number of Boomerangs │ └── Solution.py ├── 448. Find All Numbers Disappeared in an Array │ └── Solution.py ├── 449. Serialize and Deserialize BST │ └── Solution.py ├── 45. Jump Game II │ └── Solution.java ├── 450. Delete Node in a BST │ └── Solution.java ├── 451. Sort Characters By Frequency │ ├── Solution.java │ └── Solution2.java ├── 452. Minimum Number of Arrows to Burst Balloons │ └── Solution.py ├── 453. Minimum Moves to Equal Array Elements │ └── Solution.py ├── 454. 4Sum II │ └── Solution.java ├── 455. Assign Cookies │ └── Solution.py ├── 456. 132 Pattern │ └── Solution.java ├── 457. Circular Array Loop │ └── Solution.java ├── 458. Poor Pigs │ └── Solution.py ├── 459. Repeated Substring Pattern │ └── Solution.py ├── 46. Permutations │ └── Solution.java ├── 460. LFU Cache │ └── Solution.java ├── 461. Hamming Distance │ └── Solution.java ├── 462. Minimum Moves to Equal Array Elements II │ └── Solution.py ├── 463. Island Perimeter │ └── Solution.java ├── 464. Can I Win │ └── Solution.py ├── 465. Optimal Account Balancing │ └── Solution.java ├── 468. Validate IP Address │ └── Solution.java ├── 47. Permutations II │ └── Solution.py ├── 470. Implement Rand10() Using Rand7() │ └── Solution.java ├── 472. Concatenated Words │ └── Solution.java ├── 473. Matchsticks to Square │ └── Solution.java ├── 474. Ones and Zeroes │ └── Solution.py ├── 476. Number Complement │ └── Solution.py ├── 477. Total Hamming Distance │ └── Solution.py ├── 478. Generate Random Point in a Circle │ ├── Solution.java │ └── Solution2.java ├── 48. Rotate Image │ └── Solution.java ├── 480. Sliding Window Median │ └── Solution.java ├── 482. License Key Formatting │ └── Solution.py ├── 483. Smallest Good Base │ ├── Solution.py │ └── Solution2.py ├── 484. Find Permutation │ └── Solution.py ├── 485. Max Consecutive Ones │ └── Solution.cpp ├── 486. Predict the Winner │ └── Solution.java ├── 487. Max Consecutive Ones II │ └── Solution.cpp ├── 489. Robot Room Cleaner │ └── Solution.java ├── 49. Group Anagrams │ └── Solution.java ├── 490. The Maze │ └── Solution.py ├── 493. Reverse Pairs │ └── Solution.java ├── 494. Target Sum │ └── Solution.py ├── 495. Teemo Attacking │ └── Solution.java ├── 496. Next Greater Element I │ └── Solution.py ├── 497. Random Point in Non-overlapping Rectangles │ └── Solution.py ├── 498. Diagonal Traverse │ └── Solution.py ├── 5. Longest Palindromic Substring │ └── Solution.java ├── 50. Pow(x, n) │ └── Solution.java ├── 502. IPO │ └── Solution.java ├── 503. Next Greater Element II │ └── Solution.py ├── 505. The Maze II │ └── Solution.py ├── 508. Most Frequent Subtree Sum │ └── Solution.py ├── 509. Fibonacci Number │ └── Solution.py ├── 51. N-Queens │ └── Solution.java ├── 510. Inorder Successor in BST II │ └── Solution.py ├── 513. Find Bottom Left Tree Value │ └── Solution.py ├── 515. Find Largest Value in Each Tree Row │ └── Solution.java ├── 518. Coin Change 2 │ └── Solution.py ├── 52. N-Queens II │ └── Solution.java ├── 520. Detect Capital │ └── Solution.py ├── 523. Continuous Subarray Sum │ └── Solution.py ├── 524. Longest Word in Dictionary through Deleting │ └── Solution.py ├── 525. Contiguous Array │ └── Solution.py ├── 526. Beautiful Arrangement │ └── Solution.py ├── 528. Random Pick with Weight │ └── Solution.java ├── 529. Minesweeper │ └── Solution.py ├── 53. Maximum Subarray │ └── Solution.java ├── 530. Minimum Absolute Difference in BST │ └── Solution.py ├── 532. K-diff Pairs in an Array │ └── Solution.py ├── 535. Encode and Decode TinyURL │ └── Codec.java ├── 536. Construct Binary Tree from String │ └── Solution.py ├── 538. Convert BST to Greater Tree │ └── Solution.py ├── 539. Minimum Time Difference │ └── Solution.java ├── 54. Spiral Matrix │ └── Solution.java ├── 540. Single Element in a Sorted Array │ └── Solution.py ├── 542. 01 Matrix │ └── Solution.py ├── 543. Diameter of Binary Tree │ └── Solution.java ├── 545. Boundary of Binary Tree │ └── Solution.py ├── 546. Remove Boxes │ └── Solution.py ├── 547. Friend Circles │ ├── Solution.java │ └── Solution2.java ├── 548. Split Array with Equal Sum │ └── Solution.py ├── 549. Binary Tree Longest Consecutive Sequence II │ └── Solution.py ├── 55. Jump Game │ └── Solution.py ├── 551. Student Attendance Record I │ └── Solution.cpp ├── 552. Student Attendance Record II │ └── Solution.java ├── 554. Brick Wall │ └── Solution.py ├── 556. Next Greater Element III │ └── Solution.py ├── 557. Reverse Words in a String III │ └── Solution.py ├── 559. Maximum Depth of N-ary Tree │ └── Solution.java ├── 56. Merge Intervals │ └── Solution.java ├── 560. Subarray Sum Equals K │ └── Solution.java ├── 561. Array Partition I │ └── Solution.py ├── 562. Longest Line of Consecutive One in Matrix │ └── Solution.py ├── 563. Binary Tree Tilt │ └── Solution.py ├── 565. Array Nesting │ └── Solution.py ├── 566. Reshape the Matrix │ └── Solution.py ├── 567. Permutation in String │ └── Solution.py ├── 57. Insert Interval │ └── Solution.java ├── 572. Subtree of Another Tree │ ├── Solution.java │ └── Solution2.py ├── 573. Squirrel Simulation │ └── Solution.py ├── 575. Distribute Candies │ └── Solution.py ├── 58. Length of Last Word │ └── Solution.py ├── 581. Shortest Unsorted Continuous Subarray │ └── Solution.java ├── 582. Kill Process │ └── Solution.py ├── 583. Delete Operation for Two Strings │ └── Solution.java ├── 587. Erect the Fence │ └── Solution.java ├── 588. Design In-Memory File System │ └── Solution.py ├── 589. N-ary Tree Preorder Traversal │ └── Solution.py ├── 59. Spiral Matrix II │ └── Solution.java ├── 593. Valid Square │ └── Solution.py ├── 594. Longest Harmonious Subsequence │ └── Solution.py ├── 599. Minimum Index Sum of Two Lists │ └── Solution.py ├── 6. ZigZag Conversion │ └── Solution.java ├── 60. Permutation Sequence │ └── Solution.py ├── 600. Non-negative Integers without Consecutive Ones │ └── Solution.py ├── 604. Design Compressed String Iterator │ └── Solution.java ├── 605. Can Place Flowers │ └── Solution.py ├── 609. Find Duplicate File in System │ └── Solution.py ├── 61. Rotate List │ └── Solution.java ├── 611. Valid Triangle Number │ └── Solution.py ├── 616. Add Bold Tag in String │ ├── Solution.py │ └── Solution2.py ├── 617. Merge Two Binary Trees │ └── Solution.java ├── 62. Unique Paths │ └── Solution.java ├── 621. Task Scheduler │ └── Solution.java ├── 622. Design Circular Queue │ └── MyCircularQueue.java ├── 623. Add One Row to Tree │ └── Solution.py ├── 624. Maximum Distance in Arrays │ └── Solution.py ├── 628. Maximum Product of Three Numbers │ └── Solution.py ├── 629. K Inverse Pairs Array │ └── Solution.java ├── 63. Unique Paths II │ └── Solution.java ├── 630. Course Schedule III │ └── Solution.py ├── 631. Design Excel Sum Formula │ └── Solution.py ├── 633. Sum of Square Numbers │ └── Solution.py ├── 635. Design Log Storage System │ ├── Solution.py │ └── Solution2.py ├── 636. Exclusive Time of Functions │ └── Solution.java ├── 637. Average of Levels in Binary Tree │ └── Solution.py ├── 639. Decode Ways II │ └── Solution.java ├── 64. Minimum Path Sum │ └── Solution.java ├── 641. Design Circular Deque │ └── MyCircularDeque.java ├── 642. Design Search Autocomplete System │ └── AutocompleteSystem.java ├── 643. Maximum Average Subarray I │ └── Solution.java ├── 644. Maximum Average Subarray II │ ├── Solution.py │ └── Solution2.py ├── 645. Set Mismatch │ └── Solution.py ├── 647. Palindromic Substrings │ └── Solution.py ├── 65. Valid Number │ └── Solution.py ├── 652. Find Duplicate Subtrees │ └── Solution.py ├── 653. Two Sum IV - Input is a BST │ └── Solution.py ├── 654. Maximum Binary Tree │ └── Solution.java ├── 657. Robot Return to Origin │ └── Solution.java ├── 658. Find K Closest Elements │ └── Solution.java ├── 659. Split Array into Consecutive Subsequences │ └── Solution.py ├── 66. Plus One │ └── Solution.java ├── 662. Maximum Width of Binary Tree │ └── Solution.py ├── 663. Equal Tree Partition │ └── Solution.py ├── 667. Beautiful Arrangement II │ └── Solution.py ├── 669. Trim a Binary Search Tree │ └── Solution.py ├── 67. Add Binary │ └── Solution.py ├── 670. Maximum Swap │ └── Solution.py ├── 673. Number of Longest Increasing Subsequence │ └── Solution.py ├── 674. Longest Continuous Increasing Subsequence │ └── Solution.py ├── 676. Implement Magic Dictionary │ └── Solution.java ├── 677. Map Sum Pairs │ └── Solution.py ├── 678. Valid Parenthesis String │ └── Solution.py ├── 679. 24 Game │ └── Solution.py ├── 68. Text Justification │ └── Solution.java ├── 680. Valid Palindrome II │ └── Solution.java ├── 681. Next Closest Time │ └── Solution.java ├── 682. Baseball Game │ └── Solution.py ├── 683. K Empty Slots │ └── Solution.py ├── 684. Redundant Connection │ ├── Solution.java │ └── Solution2.java ├── 687. Longest Univalue Path │ └── Solution.py ├── 688. Knight Probability in Chessboard │ └── Solution.java ├── 689. Maximum Sum of 3 Non-Overlapping Subarrays │ └── Solution.py ├── 69. Sqrt(x) │ └── Solution.java ├── 690. Employee Importance │ └── Solution.py ├── 691. Stickers to Spell Word │ └── Solution.py ├── 692. Top K Frequent Words │ └── Solution.py ├── 693. Binary Number with Alternating Bits │ └── Solution.c ├── 694. Number of Distinct Islands │ └── Solution.py ├── 695. Max Area of Island │ └── Solution.py ├── 696. Count Binary Substrings │ └── Solution.py ├── 697. Degree of an Array │ └── Solution.py ├── 698. Partition to K Equal Sum Subsets │ └── Solution.py ├── 699. Falling Squares │ └── Solution.py ├── 70. Climbing Stairs │ └── Solution.java ├── 700. Search in a Binary Search Tree │ └── Solution.java ├── 701. Insert into a Binary Search Tree │ └── Solution.py ├── 702. Search in a Sorted Array of Unknown Size │ └── Solution.py ├── 703. Kth Largest Element in a Stream │ └── Solution.py ├── 704. Binary Search │ └── Solution.py ├── 705. Design HashSet │ └── Solution.py ├── 706. Design HashMap │ └── Solution.py ├── 708. Insert into a Sorted Circular Linked List │ └── Solution.py ├── 709. To Lower Case │ └── Solution.java ├── 71. Simplify Path │ └── Solution.py ├── 710. Random Pick with Blacklist │ └── Solution.py ├── 713. Subarray Product Less Than K │ └── Solution.java ├── 714. Best Time to Buy and Sell Stock with Transaction Fee │ └── Solution.py ├── 715. Range Module │ └── Solution.py ├── 716. Max Stack │ └── Solution.java ├── 717. 1-bit and 2-bit Characters │ └── Solution.py ├── 718. Maximum Length of Repeated Subarray │ ├── Solution.java │ └── Solution2.py ├── 72. Edit Distance │ └── Solution.java ├── 720. Longest Word in Dictionary │ └── Solution.py ├── 721. Accounts Merge │ └── Solution.py ├── 722. Remove Comments │ └── Solution.py ├── 724. Find Pivot Index │ └── Solution.py ├── 725. Split Linked List in Parts │ └── Solution.java ├── 726. Number of Atoms │ └── Solution.py ├── 727. Minimum Window Subsequence │ └── Solution.java ├── 728. Self Dividing Numbers │ └── Solution.py ├── 729. My Calendar I │ └── Solution.java ├── 73. Set Matrix Zeroes │ └── Solution.java ├── 731. My Calendar II │ ├── Solution.java │ └── Solution.py ├── 732. My Calendar III │ └── Solution.java ├── 733. Flood Fill │ └── Solution.java ├── 734. Sentence Similarity │ └── Solution.py ├── 735. Asteroid Collision │ └── Solution.java ├── 737. Sentence Similarity II │ └── Solution.py ├── 738. Monotone Increasing Digits │ ├── Solution.java │ └── Solution2.java ├── 739. Daily Temperatures │ └── Solution.java ├── 74. Search a 2D Matrix │ └── Solution.java ├── 740. Delete and Earn │ └── Solution.py ├── 741. Cherry Pickup │ └── Solution.java ├── 742. Closest Leaf in a Binary Tree │ └── Solution.py ├── 743. Network Delay Time │ ├── Solution.java │ └── Solution2.java ├── 744. Find Smallest Letter Greater Than Target │ └── Solution.cpp ├── 746. Min Cost Climbing Stairs │ └── Solution.java ├── 75. Sort Colors │ └── Solution.java ├── 750. Number Of Corner Rectangles │ └── Solution.py ├── 752. Open the Lock │ └── Solution.py ├── 753. Cracking the Safe │ └── Solution.java ├── 754. Reach a Number │ ├── Solution.py │ └── Solution2.py ├── 755. Pour Water │ └── Solution.py ├── 759. Employee Free Time │ ├── Solution.py │ └── Solution2.py ├── 76. Minimum Window Substring │ └── Solution.java ├── 760. Find Anagram Mappings │ └── Solution.rs ├── 763. Partition Labels │ └── Solution.java ├── 764. Largest Plus Sign │ └── Solution.py ├── 765. Couples Holding Hands │ └── Solution.py ├── 766. Toeplitz Matrix │ └── Solution.py ├── 767. Reorganize String │ └── Solution.py ├── 77. Combinations │ └── Solution.java ├── 771. Jewels and Stones │ └── Solution.java ├── 773. Sliding Puzzle │ └── Solution.py ├── 774. Minimize Max Distance to Gas Station │ └── Solution.py ├── 775. Global and Local Inversions │ └── Solution.py ├── 778. Swim in Rising Water │ └── Solution.py ├── 78. Subsets │ ├── Solution.java │ └── Solution.scala ├── 780. Reaching Points │ └── Solution.py ├── 783. Minimum Distance Between BST Nodes │ └── Solution.py ├── 784. Letter Case Permutation │ └── Solution.py ├── 785. Is Graph Bipartite? │ └── Solution.java ├── 786. K-th Smallest Prime Fraction │ ├── Solution.py │ └── Solution2.py ├── 787. Cheapest Flights Within K Stops │ └── Solution.java ├── 788. Rotated Digits │ └── Solution.py ├── 79. Word Search │ └── Solution.java ├── 790. Domino and Tromino Tiling │ └── Solution.java ├── 791. Custom Sort String │ └── Solution.py ├── 792. Number of Matching Subsequences │ └── Solution.py ├── 794. Valid Tic-Tac-Toe State │ └── Solution.py ├── 796. Rotate String │ └── Solution.py ├── 797. All Paths From Source to Target │ └── Solution.py ├── 799. Champagne Tower │ └── Solution.py ├── 8. String to Integer (atoi) │ └── Solution.java ├── 80. Remove Duplicates from Sorted Array II │ └── Solution.java ├── 801. Minimum Swaps To Make Sequences Increasing │ └── Solution.py ├── 802. Find Eventual Safe States │ ├── Solution.py │ └── Solution2.py ├── 804. Unique Morse Code Words │ └── Solution.py ├── 805. Split Array With Same Average │ └── Solution.java ├── 809. Expressive Words │ └── Solution.py ├── 81. Search in Rotated Sorted Array II │ └── Solution.py ├── 811. Subdomain Visit Count │ └── Solution.py ├── 814. Binary Tree Pruning │ └── Solution.py ├── 815. Bus Routes │ └── Solution.py ├── 817. Linked List Components │ └── Solution.py ├── 818. Race Car │ └── Solution.py ├── 819. Most Common Word │ └── Solution.java ├── 82. Remove Duplicates from Sorted List II │ └── Solution.java ├── 820. Short Encoding of Words │ └── Solution.py ├── 821. Shortest Distance to a Character │ └── Solution.py ├── 823. Binary Trees With Factors │ └── Solution.py ├── 824. Goat Latin │ └── Solution.py ├── 825. Friends Of Appropriate Ages │ ├── Solution.py │ └── Solution2.py ├── 827. Making A Large Island │ └── Solution.py ├── 828. Count Unique Characters of All Substrings of a Given String │ └── Solution.py ├── 829. Consecutive Numbers Sum │ └── Solution.java ├── 83. Remove Duplicates from Sorted List │ └── Solution.java ├── 830. Positions of Large Groups │ └── Solution.py ├── 831. Masking Personal Information │ └── Solution.py ├── 832. Flipping an Image │ └── Solution.java ├── 833. Find And Replace in String │ └── Solution.py ├── 834. Sum of Distances in Tree │ └── Solution.py ├── 835. Image Overlap │ └── Solution.java ├── 838. Push Dominoes │ └── Solution.py ├── 839. Similar String Groups │ └── Solution.py ├── 84. Largest Rectangle in Histogram │ └── Solution.java ├── 841. Keys and Rooms │ └── Solution.py ├── 843. Guess the Word │ └── Solution.java ├── 844. Backspace String Compare │ └── Solution.java ├── 845. Longest Mountain in Array │ └── Solution.py ├── 848. Shifting Letters │ └── Solution.py ├── 849. Maximize Distance to Closest Person │ └── Solution.py ├── 85. Maximal Rectangle │ └── Solution.java ├── 850. Rectangle Area II │ └── Solution.py ├── 851. Loud and Rich │ └── Solution.py ├── 852. Peak Index in a Mountain Array │ └── Solution.py ├── 855. Exam Room │ └── Solution.py ├── 856. Score of Parentheses │ ├── Solution.java │ └── Solution2.java ├── 858. Mirror Reflection │ └── Solution.py ├── 859. Buddy Strings │ └── Solution.py ├── 86. Partition List │ └── Solution.java ├── 862. Shortest Subarray with Sum at Least K │ └── Solution.java ├── 863. All Nodes Distance K in Binary Tree │ └── Solution.py ├── 864. Shortest Path to Get All Keys │ └── Solution.py ├── 865. Smallest Subtree with all the Deepest Nodes │ └── Solution.py ├── 867. Transpose Matrix │ └── Solution.py ├── 868. Binary Gap │ └── Solution.py ├── 869. Reordered Power of 2 │ └── Solution.py ├── 87. Scramble String │ └── Solution.py ├── 870. Advantage Shuffle │ └── Solution.py ├── 872. Leaf-Similar Trees │ └── Solution.py ├── 874. Walking Robot Simulation │ └── Solution.java ├── 875. Koko Eating Bananas │ └── Solution.py ├── 876. Middle of the Linked List │ └── Solution.java ├── 877. Stone Game │ └── Solution.py ├── 88. Merge Sorted Array │ └── Solution.java ├── 880. Decoded String at Index │ └── Solution.py ├── 881. Boats to Save People │ └── Solution.py ├── 884. Uncommon Words from Two Sentences │ └── Solution.py ├── 886. Possible Bipartition │ └── Solution.py ├── 887. Super Egg Drop │ ├── Solution.java │ └── Solution2.java ├── 889. Construct Binary Tree from Preorder and Postorder Traversal │ └── Solution.java ├── 89. Gray Code │ └── Solution.java ├── 894. All Possible Full Binary Trees │ └── Solution.py ├── 895. Maximum Frequency Stack │ └── Solution.py ├── 896. Monotonic Array │ └── Solution.java ├── 897. Increasing Order Search Tree │ └── Solution.py ├── 90. Subsets II │ └── Solution.py ├── 900. RLE Iterator │ └── Solution.py ├── 901. Online Stock Span │ └── Solution.java ├── 902. Numbers At Most N Given Digit Set │ └── Solution.java ├── 903. Valid Permutations for DI Sequence │ └── Solution.py ├── 904. Fruit Into Baskets │ └── Solution.java ├── 905. Sort Array By Parity │ └── Solution.java ├── 907. Sum of Subarray Minimums │ └── Solution.java ├── 91. Decode Ways │ └── Solution.java ├── 910. Smallest Range II │ └── Solution.py ├── 911. Online Election │ └── Solution.py ├── 914. X of a Kind in a Deck of Cards │ └── Solution.java ├── 915. Partition Array into Disjoint Intervals │ └── Solution.py ├── 916. Word Subsets │ └── Solution.py ├── 917. Reverse Only Letters │ └── Solution.py ├── 918. Maximum Sum Circular Subarray │ └── Solution.py ├── 92. Reverse Linked List II │ └── Solution.java ├── 920. Number of Music Playlists │ └── Solution.py ├── 921. Minimum Add to Make Parentheses Valid │ └── Solution.py ├── 923. 3Sum With Multiplicity │ └── Solution.py ├── 924. Minimize Malware Spread │ └── Solution.py ├── 925. Long Pressed Name │ └── Solution.py ├── 926. Flip String to Monotone Increasing │ └── Solution.py ├── 927. Three Equal Parts │ └── Solution.py ├── 929. Unique Email Addresses │ └── Solution.py ├── 93. Restore IP Addresses │ └── Solution.py ├── 930. Binary Subarrays With Sum │ ├── Solution.py │ └── Solution2.py ├── 931. Minimum Falling Path Sum │ └── Solution.java ├── 932. Beautiful Array │ └── Solution.py ├── 933. Number of Recent Calls │ └── Solution.py ├── 934. Shortest Bridge │ └── Solution.py ├── 935. Knight Dialer │ ├── Solution.java │ └── Solution2.java ├── 936. Stamping The Sequence │ └── Solution.py ├── 937. Reorder Data in Log Files │ └── Solution.py ├── 938. Range Sum of BST │ └── Solution.java ├── 939. Minimum Area Rectangle │ └── Solution.java ├── 94. Binary Tree Inorder Traversal │ └── Solution.java ├── 940. Distinct Subsequences II │ └── Solution.java ├── 941. Valid Mountain Array │ └── Solution.py ├── 942. DI String Match │ └── Solution.py ├── 943. Find the Shortest Superstring │ └── Solution.java ├── 945. Minimum Increment to Make Array Unique │ └── Solution.py ├── 946. Validate Stack Sequences │ └── Solution.java ├── 947. Most Stones Removed with Same Row or Column │ └── Solution.py ├── 948. Bag of Tokens │ └── Solution.py ├── 949. Largest Time for Given Digits │ └── Solution.py ├── 95. Unique Binary Search Trees II │ └── Solution.py ├── 951. Flip Equivalent Binary Trees │ └── Solution.py ├── 952. Largest Component Size by Common Factor │ └── Solution.py ├── 953. Verifying an Alien Dictionary │ └── Solution.java ├── 957. Prison Cells After N Days │ └── Solution.py ├── 958. Check Completeness of a Binary Tree │ └── Solution.py ├── 96. Unique Binary Search Trees │ └── Solution.java ├── 963. Minimum Area Rectangle II │ └── Solution.py ├── 965. Univalued Binary Tree │ └── Solution.cpp ├── 966. Vowel Spellchecker │ └── Solution.py ├── 967. Numbers With Same Consecutive Differences │ └── Solution.py ├── 968. Binary Tree Cameras │ └── Solution.py ├── 969. Pancake Sorting │ └── Solution.java ├── 97. Interleaving String │ └── Solution.java ├── 971. Flip Binary Tree To Match Preorder Traversal │ └── Solution.py ├── 973. K Closest Points to Origin │ ├── Solution.java │ └── Solution2.py ├── 974. Subarray Sums Divisible by K │ └── Solution.java ├── 975. Odd Even Jump │ └── Solution.py ├── 976. Largest Perimeter │ └── Solution.py ├── 977. Squares of a Sorted Array │ └── Solution.py ├── 978. Longest Turbulent Subarray │ └── Solution.py ├── 979. Distribute Coins in Binary Tree │ └── Solution.py ├── 98. Validate Binary Search Tree │ └── Solution.java ├── 980. Unique Paths III │ └── Solution.java ├── 981. Time Based Key-Value Store │ └── Solution.java ├── 983. Minimum Cost For Tickets │ └── Solution.py ├── 986. Interval List Intersections │ └── Solution.java ├── 987. Vertical Order Traversal of a Binary Tree │ └── Solution.java ├── 988. Smallest String Starting From Leaf │ └── Solution.java ├── 99. Recover Binary Search Tree │ ├── Solution.py │ └── Solution2.py ├── 990. Satisfiability of Equality Equations │ └── Solution.java ├── 991. Broken Calculator │ └── Solution.py ├── 993. Cousins in Binary Tree │ └── Solution.py ├── 994. Rotting Oranges │ └── Solution.java └── 997. Find the Town Judge │ └── Solution.py ├── LintCode ├── 399. Nuts & Bolts Problem │ └── Solution.java ├── 499. Word Count │ └── WordCount.java ├── 504. Inverted Index (Map Reduce) │ └── InvertedIndex.java ├── 537. N-Gram (Map Reduce) │ └── NGram.java └── 960. First Unique Number in Data Stream II │ └── DataStream.py ├── OtherProblems ├── Binary Search │ └── Missing Number in Sorted Array │ │ └── Solution.py └── Design Text Editor │ └── TextEditor.py └── README.md /DataStructure/StackQueue/StackQueueHelper.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nhatsmrt/AlgorithmPractice/f27ba208b97ed2d92b4c059848cc60f6b90ce75e/DataStructure/StackQueue/StackQueueHelper.class -------------------------------------------------------------------------------- /DataStructure/StackQueue/StackQueueHelper.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class StackQueueHelper { 4 | 5 | public void q2s(Queue q, Stack s) { 6 | while (!q.isEmpty()) 7 | s.push(q.remove()); 8 | } 9 | 10 | public void s2q(Stack s, Queue q) { 11 | while (!s.isEmpty()) 12 | q.add(s.pop()); 13 | } 14 | 15 | public void reverseStack(Stack s) { 16 | Queue q = new LinkedList(); 17 | s2q(s, q); 18 | q2s(q, s); 19 | } 20 | 21 | public void reverseQueue(Queue q) { 22 | Stack s = new Stack(); 23 | q2s(q, s); 24 | s2q(s, q); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /HackerRank/Introduction to Nim Game/Solution.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import math 4 | import os 5 | import random 6 | import re 7 | import sys 8 | 9 | # Complete the nimGame function below. 10 | def nimGame(pile): 11 | ret = pile[0] 12 | for i in range(1, len(pile)): 13 | ret = ret ^ pile[i] 14 | 15 | if ret == 0: 16 | return "Second" 17 | else: 18 | return "First" 19 | 20 | 21 | if __name__ == '__main__': 22 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 23 | 24 | g = int(input()) 25 | 26 | for g_itr in range(g): 27 | n = int(input()) 28 | 29 | pile = list(map(int, input().rstrip().split())) 30 | 31 | result = nimGame(pile) 32 | 33 | fptr.write(result + '\n') 34 | 35 | fptr.close() 36 | -------------------------------------------------------------------------------- /Helper.java: -------------------------------------------------------------------------------- 1 | class Helper { 2 | private static void printArray(int[][] arr) { 3 | String rep = "["; 4 | for (int i = 0; i < arr.length; i++) { 5 | String subarr = "["; 6 | for (int j = 0; j < arr[0].length; j++) { 7 | subarr += arr[i][j]; 8 | if (j < arr[0].length - 1) 9 | subarr += ", "; 10 | } 11 | subarr += "]"; 12 | rep += "" + subarr; 13 | if (i < arr.length - 1) 14 | rep += ", "; 15 | } 16 | rep += "]"; 17 | System.out.println(rep); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /LeetCode/1. Two Sum/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] twoSum(int[] nums, int target) { 3 | Map hashTable = new HashMap(); 4 | for (int i = 0; i < nums.length; i++) { 5 | hashTable.put(nums[i], i); 6 | } 7 | 8 | int[] ret = new int[2]; 9 | for (int i = 0; i < nums.length; i++) { 10 | if (hashTable.containsKey(target - nums[i]) && hashTable.get(target - nums[i]) != i) { 11 | ret[0] = i; 12 | ret[1] = hashTable.get(target - nums[i]); 13 | break; 14 | } 15 | } 16 | return ret; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /LeetCode/100. Same Tree/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | class Solution { 11 | public boolean isSameTree(TreeNode p, TreeNode q) { 12 | if (p == null) 13 | return q == null; 14 | if (q == null) 15 | return p == null; 16 | 17 | if (p.val != q.val) 18 | return false; 19 | 20 | return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /LeetCode/1002. Find Common Characters/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def commonChars(self, A: List[str]) -> List[str]: 3 | char_cnts = list(map(self.char_cnt, A)) 4 | 5 | ret = [] 6 | for i in range(26): 7 | cnt = min([char_cnts[j][i] for j in range(len(A))]) 8 | 9 | for _ in range(cnt): 10 | ret.append(chr(i + ord('a'))) 11 | 12 | return ret 13 | 14 | def char_cnt(self, string: str) -> List[int]: 15 | ret = [0] * 26 16 | 17 | for char in string: 18 | ret[ord(char) - ord('a')] += 1 19 | 20 | return ret 21 | -------------------------------------------------------------------------------- /LeetCode/1010. Pairs of Songs With Total Durations Divisible by 60/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numPairsDivisibleBy60(self, time: List[int]) -> int: 3 | counter = Counter() 4 | 5 | for t in time: 6 | counter[t % 60] += 1 7 | 8 | 9 | ret = 0 10 | for t in counter: 11 | if t == 30 or t == 0: 12 | ret += counter[t] * (counter[t] - 1) // 2 13 | elif t < 60 - t: 14 | ret += counter[t] * counter[60 - t] 15 | 16 | return ret 17 | -------------------------------------------------------------------------------- /LeetCode/1015. Smallest Integer Divisible by K/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int smallestRepunitDivByK(int K) { 4 | // Time Complexity: O(K) 5 | // Space Complexity: O(1) 6 | 7 | if (K == 1) 8 | return 1; 9 | 10 | if (K % 2 == 0 || K % 5 == 0) 11 | return -1; 12 | 13 | 14 | int remainder = 0; 15 | for (int num_digs = 1; num_digs < K + 1; num_digs++) { 16 | remainder = (remainder * 10 + 1) % K; 17 | 18 | if (remainder == 0) 19 | return num_digs; 20 | } 21 | 22 | return -1; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /LeetCode/1016. Binary String With Substrings Representing 1 To N/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def queryString(self, s: str, n: int) -> bool: 3 | # Time Complexity: O(s log(n)) 4 | # Space Complexity: O(n) 5 | values = set() 6 | num_digs = math.ceil(math.log2(n)) 7 | 8 | for i in range(len(s)): 9 | if s[i] == "1": 10 | cur = 1 11 | values.add(cur) 12 | 13 | for j in range(i + 1, min(len(s), i + num_digs)): 14 | cur = cur * 2 + int(s[j]) 15 | 16 | if cur <= n: 17 | values.add(cur) 18 | 19 | return len(values) == n 20 | -------------------------------------------------------------------------------- /LeetCode/1021. Remove Outermost Parentheses/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeOuterParentheses(self, s: str) -> str: 3 | # Time and Space Complexity: O(N) 4 | primitive_ends = [] 5 | 6 | opening = 0 7 | 8 | for i, char in enumerate(s): 9 | if char == "(": 10 | opening += 1 11 | else: 12 | opening -= 1 13 | 14 | if opening == 0: 15 | primitive_ends.append(i) 16 | 17 | ret = [] 18 | start = 0 19 | 20 | for primitive_end in primitive_ends: 21 | ret.append(s[start + 1:primitive_end]) 22 | start = primitive_end + 1 23 | 24 | return "".join(ret) 25 | -------------------------------------------------------------------------------- /LeetCode/1025. Divisor Game/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def divisorGame(self, n: int) -> bool: 3 | # The game concludes when n == 1 4 | 5 | # If any player gets an even number, they win (by subtracting 1) 6 | # The opponent, since they can't subtract an even number, must subtract an odd number 7 | # giving the player back an even number 8 | 9 | return not n % 2 10 | -------------------------------------------------------------------------------- /LeetCode/1029. Two City Scheduling/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoCitySchedCost(self, costs: List[List[int]]) -> int: 3 | costs.sort(key=lambda cost: -abs(cost[0] - cost[1])) 4 | 5 | ret = 0 6 | assigned = [0, 0] 7 | 8 | for cost in costs: 9 | argmin = self.argmin(cost) 10 | 11 | if assigned[argmin] < len(costs) // 2: 12 | assigned[argmin] += 1 13 | ret += cost[argmin] 14 | else: 15 | assigned[1 - argmin] += 1 16 | ret += cost[1 - argmin] 17 | 18 | return ret 19 | 20 | def argmin(self, cost: List[int]) -> int: 21 | if cost[0] < cost[1]: 22 | return 0 23 | 24 | return 1 25 | -------------------------------------------------------------------------------- /LeetCode/1035. Uncrossed Lines/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxUncrossedLines(self, A: List[int], B: List[int]) -> int: 3 | self.dp = [[-1 for j in range(len(B))] for i in range(len(A))] 4 | return self.match(A, B, 0, 0) 5 | 6 | def match(self, A: List[int], B: List[int], i: int, j: int) -> int: 7 | if i == len(A) or j == len(B): 8 | return 0 9 | 10 | if self.dp[i][j] != -1: 11 | return self.dp[i][j] 12 | 13 | ret = max(self.match(A, B, i + 1, j), self.match(A, B, i, j + 1)) 14 | 15 | if A[i] == B[j]: 16 | ret = max(ret, 1 + self.match(A, B, i + 1, j + 1)) 17 | 18 | self.dp[i][j] = ret 19 | return ret 20 | -------------------------------------------------------------------------------- /LeetCode/1037. Valid Boomerang/Solution.py: -------------------------------------------------------------------------------- 1 | def area(points: List[List[int]]) -> int: # shoelace formula 2 | fst = sum(points[i][0] * points[(i + 1) % len(points)][1] for i in range(len(points))) 3 | snd = sum(points[i][1] * points[(i + 1) % len(points)][0] for i in range(len(points))) 4 | 5 | return 0.5 * abs(fst - snd) 6 | 7 | class Solution: 8 | def isBoomerang(self, points: List[List[int]]) -> bool: 9 | # Time and Space Complexity: O(1) 10 | return area(points) > 0 11 | -------------------------------------------------------------------------------- /LeetCode/1046. Last Stone Weight/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int lastStoneWeight(int[] stones) { 3 | PriorityQueue queue = new PriorityQueue(); 4 | for (int stone : stones) { 5 | queue.add(-stone); 6 | } 7 | 8 | while (queue.size() > 1) { 9 | int stone1 = -queue.poll(); 10 | int stone2 = -queue.poll(); 11 | 12 | if (stone1 != stone2) { 13 | int newStone = stone1 > stone2 ? stone1 - stone2 : stone2 - stone1; 14 | queue.add(-newStone); 15 | } 16 | } 17 | 18 | if (queue.size() == 0) 19 | return 0; 20 | 21 | return -queue.poll(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /LeetCode/1047. Remove All Adjacent Duplicates In String/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeDuplicates(self, S: str) -> str: 3 | # Time and Space Complexity: O(N) 4 | stack = [] 5 | 6 | for char in S: 7 | removed = False 8 | while stack and stack[-1] == char: 9 | removed = True 10 | stack.pop() 11 | 12 | if not removed: 13 | stack.append(char) 14 | 15 | return "".join(stack) 16 | -------------------------------------------------------------------------------- /LeetCode/1051. Height Checker/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def heightChecker(self, heights: List[int]) -> int: 3 | # Time Complexity: O(N log N) 4 | # Space Complexity: O(N) 5 | 6 | expected = sorted(heights) 7 | 8 | expected_ind = {} 9 | 10 | for i, height in enumerate(expected): 11 | if height not in expected_ind: 12 | expected_ind[height] = set() 13 | 14 | expected_ind[height].add(i) 15 | 16 | ret = 0 17 | for i, height in enumerate(heights): 18 | if i not in expected_ind[height]: 19 | ret += 1 20 | 21 | return ret 22 | -------------------------------------------------------------------------------- /LeetCode/1056. Confusing Number/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def confusingNumber(self, N: int) -> bool: 3 | confusing_digits = set([0, 1, 6, 8, 9]) 4 | digit_map = {0: 0, 1: 1, 6: 9, 8: 8, 9: 6} 5 | changed = False 6 | new_num = 0 7 | old_num = N 8 | 9 | while N > 0: 10 | digit = N % 10 11 | if digit not in confusing_digits: 12 | return False 13 | changed = changed or (digit == 6) or (digit == 9) 14 | N = N // 10 15 | new_num = new_num * 10 + digit_map[digit] 16 | 17 | return new_num != old_num 18 | -------------------------------------------------------------------------------- /LeetCode/1060. Missing Element in Sorted Array/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def missingElement(self, nums: List[int], k: int) -> int: 3 | low = 0 4 | high = len(nums) 5 | 6 | 7 | while low + 1 < high: 8 | mid = low + (high - low) // 2 9 | 10 | num_missing = nums[mid] - nums[low] + low - mid 11 | if num_missing >= k: 12 | high = mid 13 | else: 14 | low = mid 15 | k -= num_missing 16 | 17 | return nums[low] + k 18 | -------------------------------------------------------------------------------- /LeetCode/1064. Fixed Point/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int fixedPoint(int[] A) { 3 | return fixedPoint(A, 0, A.length - 1); 4 | } 5 | 6 | private int fixedPoint(int[] A, int i, int j) { 7 | if (A[i] - i == 0) 8 | return i; 9 | 10 | if (i >= j) 11 | return -1; 12 | 13 | int mid = i + (j - i) / 2; 14 | if (A[mid] - mid > 0) 15 | return fixedPoint(A, i + 1, mid - 1); 16 | else if (A[mid] - mid == 0) 17 | return fixedPoint(A, i + 1, mid); 18 | else 19 | return fixedPoint(A, mid + 1, j); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /LeetCode/1071. Greatest Common Divisor of Strings/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def gcdOfStrings(self, str1: str, str2: str) -> str: 3 | # Time and Space Complexity: O(N^3) 4 | for i in range(min(len(str1), len(str2)), -1, -1): 5 | prefix = str1[:i] 6 | if self.is_repeat(prefix, str1) and self.is_repeat(prefix, str2): 7 | return prefix 8 | 9 | 10 | def is_repeat(self, prefix, string): 11 | if not prefix: 12 | return True 13 | 14 | if len(string) % len(prefix): 15 | return False 16 | 17 | for i in range(0, len(string), len(prefix)): 18 | if string[i:i + len(prefix)] != prefix: 19 | return False 20 | 21 | return True 22 | -------------------------------------------------------------------------------- /LeetCode/1078. Occurrences After Bigram/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findOcurrences(self, text: str, first: str, second: str) -> List[str]: 3 | # Time and Space Complexity: O(|text|) 4 | 5 | words = text.split(" ") 6 | 7 | ret = [] 8 | for i in range(len(words) - 2): 9 | if words[i] == first and words[i + 1] == second: 10 | ret.append(words[i + 2]) 11 | 12 | return ret 13 | -------------------------------------------------------------------------------- /LeetCode/1079. Letter Tile Possibilities/Solution.py: -------------------------------------------------------------------------------- 1 | def count(cnter) -> int: 2 | ret = 1 3 | 4 | for char in cnter: 5 | if cnter[char] > 0: 6 | cnter[char] -= 1 7 | ret += count(cnter) 8 | cnter[char] += 1 9 | 10 | return ret 11 | 12 | class Solution: 13 | def numTilePossibilities(self, tiles: str) -> int: 14 | # Time Complexity: O(26^N) 15 | # Space Complexity: O(N) 16 | 17 | cnter = Counter(tiles) 18 | return count(cnter) - 1 19 | -------------------------------------------------------------------------------- /LeetCode/11. Container With Most Water/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxArea(int[] height) { 3 | int left = 0; 4 | int right = height.length - 1; 5 | int maxArea = 0; 6 | 7 | while (left < right) { 8 | int cand = Math.min(height[left], height[right]) * (right - left); 9 | if (cand > maxArea) 10 | maxArea = cand; 11 | if (height[left] < height[right]) 12 | left += 1; 13 | else 14 | right -= 1; 15 | } 16 | 17 | return maxArea; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /LeetCode/1108. Defanging an IP Address/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def defangIPaddr(self, address: str) -> str: 3 | return address.replace(".", "[.]") 4 | -------------------------------------------------------------------------------- /LeetCode/111. Minimum Depth of Binary Tree/Solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def minDepth(self, root: TreeNode) -> int: 9 | if not root: 10 | return 0 11 | elif not any((root.left, root.right)): 12 | return 1 13 | elif not root.left: 14 | return 1 + self.minDepth(root.right) 15 | elif not root.right: 16 | return 1 + self.minDepth(root.left) 17 | else: 18 | return 1 + min(self.minDepth(root.left), self.minDepth(root.right)) 19 | -------------------------------------------------------------------------------- /LeetCode/1119. Remove Vowels from a String/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeVowels(self, S: str) -> str: 3 | return "".join(filter(lambda c: c not in set(["a", "e", "i", "o", "u"]), S)) 4 | -------------------------------------------------------------------------------- /LeetCode/112. Path Sum/Solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool: 9 | if not root: 10 | return False 11 | 12 | if not (root.left or root.right): 13 | return targetSum == root.val 14 | 15 | remain = targetSum - root.val 16 | return (root.left and self.hasPathSum(root.left, remain)) or (root.right and self.hasPathSum(root.right, remain)) 17 | -------------------------------------------------------------------------------- /LeetCode/1133. Largest Unique Number/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestUniqueNumber(self, A: List[int]) -> int: 3 | cnter = Counter(A) 4 | only_once = [val for val in cnter if cnter[val] == 1] 5 | return max(only_once) if only_once else -1 6 | -------------------------------------------------------------------------------- /LeetCode/1150. Check If a Number Is Majority Element in a Sorted Array/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isMajorityElement(self, nums: List[int], target: int) -> bool: 3 | # Time Complexity: O(log N) 4 | # Space Complexity: O(1) 5 | 6 | start = bisect.bisect_left(nums, target) 7 | end = bisect.bisect_right(nums, target) # exclusive 8 | 9 | return end - start > len(nums) / 2 10 | -------------------------------------------------------------------------------- /LeetCode/1151. Minimum Swaps to Group All 1's Together/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minSwaps(self, data: List[int]) -> int: 3 | # Time Complexity: O(N) 4 | # Space Complexity: O(1) 5 | 6 | # Let C be number of ones in data 7 | # min number of swaps = C - C' 8 | # where C' is the number of ones in the window of size C 9 | # with most ones. 10 | 11 | num_ones = sum(data) 12 | cur_cnt = sum(data[:num_ones]) 13 | ret = num_ones - cur_cnt # first window 14 | 15 | for i in range(num_ones, len(data)): 16 | cur_cnt += data[i] 17 | cur_cnt -= data[i - num_ones] 18 | ret = min(ret, num_ones - cur_cnt) 19 | 20 | return ret 21 | -------------------------------------------------------------------------------- /LeetCode/1160. Find Words That Can Be Formed by Characters/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countCharacters(self, words: List[str], chars: str) -> int: 3 | # Time Complexity: O(|chars| + sum(|word| for word in words)) 4 | # Space Complexity: O(|chars| + max_len_word) 5 | 6 | cnter = Counter(chars) 7 | 8 | def is_good(word): 9 | word_cnter = Counter(word) 10 | 11 | for char in word_cnter: 12 | if cnter[char] < word_cnter[char]: 13 | return False 14 | 15 | return True 16 | 17 | return sum(map(len, filter(is_good, words))) 18 | -------------------------------------------------------------------------------- /LeetCode/1165. Single-Row Keyboard/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def calculateTime(self, keyboard: str, word: str) -> int: 3 | # Time Complexity: O(N) 4 | # Space Complexity: O(1) 5 | 6 | index = [-1] * 26 7 | for i, char in enumerate(keyboard): 8 | index[ord(char) - ord('a')] = i 9 | 10 | ret = index[ord(word[0]) - ord('a')] 11 | for i in range(1, len(word)): 12 | ret += abs(index[ord(word[i]) - ord('a')] - index[ord(word[i - 1]) - ord('a')]) 13 | 14 | return ret 15 | -------------------------------------------------------------------------------- /LeetCode/1167. Minimum Cost to Connect Sticks/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def connectSticks(self, sticks: List[int]) -> int: 3 | heapq.heapify(sticks); 4 | 5 | ret = 0 6 | while len(sticks) > 1: 7 | num1 = heapq.heappop(sticks) 8 | num2 = heapq.heappop(sticks) 9 | num = num1 + num2 10 | ret += num 11 | heapq.heappush(sticks, num) 12 | 13 | return ret 14 | 15 | -------------------------------------------------------------------------------- /LeetCode/1176. Diet Plan Performance/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def dietPlanPerformance(self, calories: List[int], k: int, lower: int, upper: int) -> int: 3 | # Time and Space Complexity: O(N) 4 | 5 | prefixes = [0] + list(itertools.accumulate(calories)) 6 | 7 | ret = 0 8 | for i in range(len(prefixes) - k): 9 | window_sum = prefixes[i + k] - prefixes[i] 10 | 11 | if window_sum > upper: 12 | ret += 1 13 | elif window_sum < lower: 14 | ret -= 1 15 | 16 | return ret 17 | -------------------------------------------------------------------------------- /LeetCode/118. Pascal's Triangle/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generate(self, numRows: int) -> List[List[int]]: 3 | if not numRows: 4 | return [] 5 | 6 | ret = [[1]] 7 | 8 | for _ in range(1, numRows): 9 | new_row = [1] 10 | 11 | for i in range(1, len(ret[-1])): 12 | new_row.append(ret[-1][i] + ret[-1][i - 1]) 13 | 14 | new_row.append(1) 15 | ret.append(new_row) 16 | 17 | return ret 18 | -------------------------------------------------------------------------------- /LeetCode/1196. How Many Apples Can You Put into the Basket/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxNumberOfApples(self, arr: List[int]) -> int: 3 | arr = list(itertools.accumulate(sorted(arr))) 4 | 5 | low = 0 6 | high = len(arr) 7 | 8 | while low < high: 9 | mid = high - (high - low) // 2 10 | 11 | if mid == 0: 12 | cand = 0 13 | else: 14 | cand = arr[mid - 1] 15 | 16 | if cand <= 5000: 17 | low = mid 18 | else: 19 | high = mid - 1 20 | 21 | return low 22 | -------------------------------------------------------------------------------- /LeetCode/120. Triangle/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minimumTotal(self, triangle): 3 | """ 4 | :type triangle: List[List[int]] 5 | :rtype: int 6 | """ 7 | cur = [triangle[0][0]] 8 | for d in range(1, len(triangle)): 9 | new_level = [] 10 | for i in range(len(triangle[d])): 11 | if i == 0: 12 | new_level.append(cur[0] + triangle[d][i]) 13 | elif i == len(triangle[d]) - 1: 14 | new_level.append(cur[len(cur) - 1] + triangle[d][i]) 15 | else: 16 | new_level.append(min(cur[i - 1], cur[i]) + triangle[d][i]) 17 | cur = new_level 18 | 19 | return min(cur) 20 | 21 | -------------------------------------------------------------------------------- /LeetCode/1207. Unique Number of Occurrences/Solution.rs: -------------------------------------------------------------------------------- 1 | use std::collections::{HashMap, HashSet}; 2 | 3 | impl Solution { 4 | pub fn unique_occurrences(arr: Vec) -> bool { 5 | let cnter = get_counter(&arr); 6 | let counts : Vec<&i32> = cnter.values().collect(); 7 | let mut unique_counts : HashSet<&i32> = HashSet::new(); 8 | 9 | for val in counts.iter() { 10 | unique_counts.insert(val); 11 | } 12 | 13 | counts.len() == unique_counts.len() 14 | } 15 | } 16 | 17 | fn get_counter(arr: &Vec) -> HashMap { 18 | arr.iter().fold(HashMap::new(), |mut cnter, x| { 19 | let cnt = *cnter.get(x).get_or_insert(&(0 as i32)); 20 | cnter.insert(*x, cnt + 1); 21 | cnter 22 | }) 23 | } 24 | -------------------------------------------------------------------------------- /LeetCode/1209. Remove All Adjacent Duplicates in String II/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeDuplicates(self, s: str, k: int) -> str: 3 | # Time and Space Complexity: O(N) 4 | 5 | stack = [] 6 | adj_cnt = [] 7 | 8 | for char in s: 9 | if stack and char == stack[-1]: 10 | adj_cnt[-1] += 1 11 | else: 12 | adj_cnt.append(1) 13 | 14 | stack.append(char) 15 | 16 | if adj_cnt[-1] == k: 17 | for _ in range(k): 18 | stack.pop() 19 | adj_cnt.pop() 20 | 21 | return "".join(stack) 22 | -------------------------------------------------------------------------------- /LeetCode/1217. Minimum Cost to Move Chips to The Same Position/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minCostToMoveChips(self, position: List[int]) -> int: 3 | # Time Complexity: O(N) 4 | # Space Complexity: O(1) 5 | 6 | evens = len(list(filter(lambda pos: pos % 2 == 0, position))) 7 | odds = len(list(filter(lambda pos: pos % 2 == 1, position))) 8 | 9 | return min(evens, odds) 10 | -------------------------------------------------------------------------------- /LeetCode/1228. Missing Number In Arithmetic Progression/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def missingNumber(self, arr: List[int]) -> int: 3 | # Time Complexity: O(N) 4 | # Space Complexity: O(1) 5 | 6 | expected_sum = (arr[0] + arr[-1]) * (len(arr) + 1) // 2 7 | return expected_sum - sum(arr) 8 | -------------------------------------------------------------------------------- /LeetCode/1232. Check If It Is a Straight Line/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean checkStraightLine(int[][] coordinates) { 3 | for (int i = 0; i < coordinates.length - 2; i++) 4 | if (!checkStraightLine(coordinates, i)) 5 | return false; 6 | return true; 7 | } 8 | 9 | public boolean checkStraightLine(int[][] coordinates, int i) { 10 | return 11 | (coordinates[i + 1][1] - coordinates[i][1]) * (coordinates[i + 2][0] - coordinates[i + 1][0]) == (coordinates[i + 1][0] - coordinates[i][0]) * (coordinates[i + 2][1] - coordinates[i + 1][1]); 12 | 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /LeetCode/1248. Count Number of Nice Subarrays/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numberOfSubarrays(self, nums: List[int], k: int) -> int: 3 | # Time and Space Complexity: O(N) 4 | prefix_odd = list(accumulate(map(lambda x: x % 2, nums))) 5 | 6 | cnter = Counter() 7 | cnter[0] = 1 8 | ret = 0 9 | 10 | for prefix_cnt in prefix_odd: 11 | ret += cnter[prefix_cnt - k] 12 | cnter[prefix_cnt] += 1 13 | 14 | return ret 15 | -------------------------------------------------------------------------------- /LeetCode/1265. Print Immutable Linked List in Reverse/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * // This is the ImmutableListNode's API interface. 3 | * // You should not implement it, or speculate about its implementation. 4 | * interface ImmutableListNode { 5 | * public void printValue(); // print the value of this node. 6 | * public ImmutableListNode getNext(); // return the next node. 7 | * }; 8 | */ 9 | 10 | class Solution { 11 | public void printLinkedListInReverse(ImmutableListNode head) { 12 | if (head != null) { 13 | printLinkedListInReverse(head.getNext()); 14 | head.printValue(); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /LeetCode/1266. Minimum Time Visiting All Points/Solution.py: -------------------------------------------------------------------------------- 1 | def traverse(point1: List[int], point2: List[int]) -> int: 2 | dx, dy = abs(point1[0] - point2[0]), abs(point1[1] - point2[1]) 3 | return max(dx, dy) # min(dx, dy) + max(dx, dy) - min(dx, dy) 4 | 5 | class Solution: 6 | def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int: 7 | ret = 0 8 | 9 | for i in range(len(points) - 1): 10 | ret += traverse(points[i], points[i + 1]) 11 | 12 | return ret 13 | -------------------------------------------------------------------------------- /LeetCode/1271. Hexspeak/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def toHexspeak(self, num: str) -> str: 3 | hex_rep = hex(int(num))[2:].replace("1", "I").replace("0", "O").upper() 4 | 5 | if list(filter(lambda char: char not in "ABCDEFIO", hex_rep)): 6 | return "ERROR" 7 | else: 8 | return hex_rep 9 | -------------------------------------------------------------------------------- /LeetCode/1272. Remove Interval/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeInterval(self, intervals: List[List[int]], toBeRemoved: List[int]) -> List[List[int]]: 3 | ret = [] 4 | for interval in intervals: 5 | if interval[1] < toBeRemoved[0] or interval[0] > toBeRemoved[1]: 6 | ret.append(interval) 7 | else: 8 | if interval[0] < toBeRemoved[0]: 9 | ret.append([interval[0], toBeRemoved[0]]) 10 | if interval[1] > toBeRemoved[1]: 11 | ret.append([toBeRemoved[1], interval[1]]) 12 | 13 | return ret 14 | -------------------------------------------------------------------------------- /LeetCode/1276. Number of Burgers with No Waste of Ingredients/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numOfBurgers(self, tomatoSlices: int, cheeseSlices: int) -> List[int]: 3 | # 4x + 2y = tomatoSlices 4 | # x + y = cheeseSlices 5 | # Time and Space Complexity: O(1) 6 | 7 | if tomatoSlices % 2 != 0 or tomatoSlices - 2 * cheeseSlices < 0: 8 | return [] 9 | 10 | jumbo = (tomatoSlices - 2 * cheeseSlices) // 2 11 | small = cheeseSlices - jumbo 12 | 13 | if small < 0: 14 | return [] 15 | 16 | return [jumbo, small] 17 | 18 | -------------------------------------------------------------------------------- /LeetCode/128. Longest Consecutive Sequence/Solution2.java: -------------------------------------------------------------------------------- 1 | class Solution2 { 2 | public int longestConsecutive(int[] nums) { 3 | // O(n) time and space complexity 4 | Set numSet = new HashSet<>(); 5 | for (int num : nums) 6 | numSet.add(num); 7 | 8 | int ret = 0; 9 | for (int num : nums) { 10 | if (!numSet.contains(num - 1)) { 11 | int end = num + 1; 12 | 13 | while (numSet.contains(end)) 14 | end += 1; 15 | 16 | int candidate = end - num; 17 | if (candidate > ret) 18 | ret = candidate; 19 | } 20 | } 21 | 22 | return ret; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /LeetCode/1281. Subtract the Product and Sum of Digits of an Integer/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int subtractProductAndSum(int n) { 3 | List digits = digits(n); 4 | 5 | return digits.stream().reduce(1, (x, y) -> x * y) - digits.stream().reduce(0, (x, y) -> x + y); 6 | } 7 | 8 | private List digits(int n) { 9 | List ret = new ArrayList<>(); 10 | 11 | while (n > 0) { 12 | ret.add(n % 10); 13 | n /= 10; 14 | } 15 | 16 | return ret; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /LeetCode/1282. Group the People Given the Group Size They Belong To/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]: 3 | # Time and Space Complexity: O(N) 4 | 5 | by_size = {} 6 | ret = [] 7 | 8 | for i, size in enumerate(groupSizes): 9 | if size not in by_size: 10 | by_size[size] = [] 11 | 12 | by_size[size].append(i) 13 | 14 | for size in range(max(groupSizes) + 1): 15 | if size in by_size: 16 | for j in range(0, len(by_size[size]), size): 17 | ret.append(by_size[size][j:j + size]) 18 | 19 | 20 | return ret 21 | -------------------------------------------------------------------------------- /LeetCode/1287. Element Appearing More Than 25% In Sorted Array/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findSpecialInteger(self, arr: List[int]) -> int: 3 | # Time Complexity: O(N) 4 | # Space Complexity: O(1) 5 | 6 | start = 0 7 | end = 0 8 | 9 | while start < len(arr): 10 | if end + 1 < len(arr) and arr[end + 1] == arr[start]: 11 | end += 1 12 | else: 13 | cnt = end - start + 1 14 | 15 | if cnt > 0.25 * len(arr): 16 | return arr[start] 17 | 18 | start = end + 1 19 | end += 1 20 | -------------------------------------------------------------------------------- /LeetCode/1288. Remove Covered Intervals/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeCoveredIntervals(self, intervals: List[List[int]]) -> int: 3 | # Time Complexity: O(N log N) 4 | # Space Complexity: O(1) 5 | 6 | intervals.sort(key=lambda interval: (interval[0], -interval[1])) 7 | 8 | start = 0 9 | end = 0 10 | 11 | ret = 0 12 | 13 | while start < len(intervals): 14 | if end + 1 < len(intervals) and intervals[end + 1][1] <= intervals[start][1]: 15 | end += 1 16 | else: 17 | ret += 1 18 | start = end + 1 19 | 20 | return ret 21 | 22 | -------------------------------------------------------------------------------- /LeetCode/1290. Convert Binary Number in a Linked List to Integer/Solution.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def getDecimalValue(self, head: ListNode) -> int: 8 | it = head 9 | ret = 0 10 | 11 | while it: 12 | ret = ret * 2 + it.val 13 | it = it.next 14 | 15 | return ret 16 | -------------------------------------------------------------------------------- /LeetCode/1295. Find Numbers with Even Number of Digits/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | int num_digit(int num) { 4 | int ret = 0; 5 | 6 | while (num > 0) { 7 | ret += 1; 8 | num /= 10; 9 | } 10 | 11 | return ret; 12 | } 13 | public: 14 | int findNumbers(vector& nums) { 15 | int ret = 0; 16 | 17 | for (int num : nums) 18 | ret += 1 - (num_digit(num) % 2); 19 | return ret; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /LeetCode/1295. Find Numbers with Even Number of Digits/Solution.py: -------------------------------------------------------------------------------- 1 | def num_digit(number): 2 | ret = 0 3 | 4 | while number > 0: 5 | ret += 1 6 | number //= 10 7 | 8 | return ret 9 | 10 | class Solution: 11 | def findNumbers(self, nums: List[int]) -> int: 12 | return len(list(filter(lambda l: l % 2 == 0, map(num_digit, nums)))) 13 | -------------------------------------------------------------------------------- /LeetCode/1299. Replace Elements with Greatest Element on Right Side/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def replaceElements(self, arr: List[int]) -> List[int]: 3 | # Time and Space Complexity: O(N) 4 | ret = [] 5 | 6 | greatest = -1 7 | for num in reversed(arr): 8 | ret.append(greatest) 9 | greatest = max(greatest, num) 10 | 11 | return ret[::-1] 12 | -------------------------------------------------------------------------------- /LeetCode/1304. Find N Unique Integers Sum up to Zero/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] sumZero(int n) { 3 | int[] ret = new int[n]; 4 | int half = n / 2; 5 | int cnt = 0; 6 | 7 | for (int i = 1; i <= half; i++) { 8 | ret[cnt] = -i; 9 | ret[cnt + 1] = i; 10 | cnt += 2; 11 | } 12 | 13 | if (n % 2 == 1) 14 | ret[cnt] = 0; 15 | return ret; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /LeetCode/1310. XOR Queries of a Subarray/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]: 3 | prefix_xor = [0] 4 | for num in arr: 5 | prefix_xor.append(num ^ prefix_xor[-1]) 6 | 7 | 8 | ret = [] 9 | for query in queries: 10 | ret.append(prefix_xor[query[1] + 1] ^ prefix_xor[query[0]]) 11 | 12 | return ret 13 | -------------------------------------------------------------------------------- /LeetCode/1313. Decompress Run-Length Encoded List/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] decompressRLElist(int[] nums) { 3 | int retSize = 0; 4 | for (int i = 0; i < nums.length; i += 2) 5 | retSize += nums[i]; 6 | 7 | int[] ret = new int[retSize]; 8 | int ind = 0; 9 | 10 | for (int i = 0; i < nums.length; i += 2) { 11 | for (int j = 0; j < nums[i]; j++) { 12 | ret[ind] = nums[i + 1]; 13 | ind += 1; 14 | } 15 | } 16 | 17 | return ret; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /LeetCode/1323. Maximum 69 Number/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximum69Number (self, num: int) -> int: 3 | # Time Complexity: O(W) 4 | # Space Complexity: O(1) 5 | 6 | ret = 0 7 | changed = False 8 | 9 | for dig in str(num): 10 | ret *= 10 11 | 12 | if not changed and dig == "6": 13 | ret += 9 14 | changed = True 15 | else: 16 | ret += int(dig) 17 | 18 | return ret 19 | -------------------------------------------------------------------------------- /LeetCode/1325. Delete Leaves With a Given Value/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | class Solution { 11 | public TreeNode removeLeafNodes(TreeNode root, int target) { 12 | if (root == null) 13 | return root; 14 | 15 | root.left = removeLeafNodes(root.left, target); 16 | root.right = removeLeafNodes(root.right, target); 17 | 18 | if (root.val == target && root.left == null && root.right == null) 19 | return null; 20 | 21 | return root; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /LeetCode/1332. Remove Palindromic Subsequences/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removePalindromeSub(self, s: str) -> int: 3 | # Time and Space Complexity: O(N) 4 | 5 | if not s: 6 | return 0 7 | elif s == "".join(reversed(s)): 8 | return 1 9 | else: 10 | return 2 11 | -------------------------------------------------------------------------------- /LeetCode/1342. Number of Steps to Reduce a Number to Zero/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numberOfSteps (self, num: int) -> int: 3 | # Time Complexity: O(W) = O(log N) 4 | # Space Complexity: O(1) 5 | 6 | ret = 0 7 | 8 | while num > 1: 9 | if num & 1: 10 | ret += 2 11 | else: 12 | ret += 1 13 | 14 | num >>= 1 15 | 16 | if num == 1: 17 | ret += 1 18 | 19 | return ret 20 | -------------------------------------------------------------------------------- /LeetCode/1344. Angle Between Hands of a Clock/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def angleClock(self, hour: int, minutes: int) -> float: 3 | min_angle = minutes * 6 4 | hour_angle = (hour % 12 + minutes / 60) * 30 5 | 6 | return min(abs(hour_angle - min_angle), 360 -abs(hour_angle - min_angle)) 7 | -------------------------------------------------------------------------------- /LeetCode/1347. Minimum Number of Steps to Make Two Strings Anagram/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minSteps(self, s: str, t: str) -> int: 3 | hist1 = self.build_freq_dict(s) 4 | hist2 = self.build_freq_dict(t) 5 | 6 | return self.diff(hist1, hist2) 7 | 8 | def build_freq_dict(self, s: str): 9 | ret = [0] * 26 10 | for char in s: 11 | ret[ord(char) - ord('a')] += 1 12 | 13 | return ret 14 | 15 | def diff(self, hist1, hist2): 16 | ret = 0 17 | for i in range(26): 18 | ret += abs(hist1[i] - hist2[i]) 19 | return ret // 2 20 | -------------------------------------------------------------------------------- /LeetCode/1352. Product of the Last K Numbers/Solution.py: -------------------------------------------------------------------------------- 1 | class ProductOfNumbers: 2 | 3 | def __init__(self): 4 | self.prefix = [1] 5 | 6 | 7 | def add(self, num: int) -> None: 8 | if num == 0: 9 | self.prefix = [1] 10 | else: 11 | self.prefix.append(self.prefix[-1] * num) 12 | 13 | 14 | def getProduct(self, k: int) -> int: 15 | if k > len(self.prefix) - 1: 16 | return 0 17 | return self.prefix[-1] // self.prefix[-k - 1] 18 | 19 | 20 | 21 | # Your ProductOfNumbers object will be instantiated and called as such: 22 | # obj = ProductOfNumbers() 23 | # obj.add(num) 24 | # param_2 = obj.getProduct(k) 25 | -------------------------------------------------------------------------------- /LeetCode/1359. Count All Valid Pickup and Delivery Options/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countOrders(self, n: int) -> int: 3 | # f(n) = n * f(n - 1) * [2(n - 1) + 1] 4 | # Time and Space Complexity: O(N) 5 | 6 | MOD = 1000000007 7 | 8 | ret = 1 9 | for i in range(2, n + 1): 10 | ret *= i 11 | ret %= MOD 12 | 13 | ret *= (2 * (i - 1) + 1) 14 | ret %= MOD 15 | 16 | return ret 17 | -------------------------------------------------------------------------------- /LeetCode/136. Single Number/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int singleNumber(int[] nums) { 3 | int ret = nums[0]; 4 | for (int i = 1; i < nums.length; i++) { 5 | ret = ret ^ nums[i]; 6 | } 7 | return ret; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /LeetCode/1360. Number of Days Between Two Dates/Solution.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | 3 | class Solution: 4 | def daysBetweenDates(self, date1: str, date2: str) -> int: 5 | return abs(date.fromisoformat(date1) - date.fromisoformat(date2)).days 6 | -------------------------------------------------------------------------------- /LeetCode/1365. How Many Numbers Are Smaller Than the Current Number/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector smallerNumbersThanCurrent(vector& nums) { 4 | vector sorted(nums); 5 | sort(sorted.begin(), sorted.end()); 6 | vector ret; 7 | 8 | vector::iterator it = nums.begin(); 9 | while (it != nums.end()) { 10 | ret.push_back(find(sorted.begin(), sorted.end(), *it) - sorted.begin()); 11 | it++; 12 | } 13 | 14 | return ret; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /LeetCode/137. Single Number /Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def singleNumber(self, nums: List[int]) -> int: 3 | unique = dup = 0 4 | 5 | for num in nums: 6 | # If a number appears once, it will stay in unique 7 | # If a number appears three time: it will be added to unique 8 | # then remove from unique and add to dup (2nd appearance) 9 | # then doesn't get added to unique in the third appearance 10 | 11 | unique = ~dup & (unique ^ num) 12 | dup = ~unique & (dup ^ num) 13 | 14 | return unique 15 | 16 | -------------------------------------------------------------------------------- /LeetCode/1375. Bulb Switcher III/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numTimesAllBlue(self, light: List[int]) -> int: 3 | # Time Complexity: O(N) 4 | # Space Complexity: O(1) 5 | 6 | cur_max_light_on = 0 7 | ret = 0 8 | 9 | for mom, light_ind in enumerate(light): 10 | cur_max_light_on = max(cur_max_light_on, light_ind) 11 | if cur_max_light_on == mom + 1: 12 | ret += 1 13 | 14 | 15 | return ret 16 | -------------------------------------------------------------------------------- /LeetCode/1423. Maximum Points You Can Obtain from Cards/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxScore(self, cardPoints: List[int], k: int) -> int: 3 | # Time and Space Complexity: O(k) 4 | 5 | prefix = [0] 6 | suffix = [0] 7 | 8 | for i in range(k): 9 | prefix.append(prefix[-1] + cardPoints[i]) 10 | suffix.append(suffix[-1] + cardPoints[len(cardPoints) - 1 - i]) 11 | 12 | ret = 0 13 | for i in range(k + 1): 14 | ret = max(ret, prefix[i] + suffix[len(suffix) - 1 - i]) 15 | 16 | return ret 17 | -------------------------------------------------------------------------------- /LeetCode/1424. Diagonal Traverse II/Solution2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]: 3 | # Space and Space Complexity: O(N) 4 | 5 | # anti-diagnal: r + c = const 6 | diagonals = {} 7 | 8 | for r in range(len(nums)): 9 | for c in range(len(nums[r])): 10 | diag_sum = r + c 11 | 12 | if diag_sum not in diagonals: 13 | diagonals[diag_sum] = [] 14 | 15 | diagonals[diag_sum].append((r, c)) 16 | 17 | ret = [] 18 | for diag_sum in diagonals: 19 | for coord in reversed(diagonals[diag_sum]): 20 | ret.append(nums[coord[0]][coord[1]]) 21 | 22 | return ret 23 | -------------------------------------------------------------------------------- /LeetCode/1426. Counting Elements/Solution.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | class Solution: 5 | def countElements(self, arr: List[int]) -> int: 6 | cnter = Counter() 7 | for num in arr: 8 | cnter[num] += 1 9 | 10 | ret = 0 11 | for num in cnter: 12 | if num + 1 in cnter: 13 | ret += cnter[num] 14 | 15 | return ret 16 | -------------------------------------------------------------------------------- /LeetCode/1427. Perform String Shifts/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def stringShift(self, s: str, shift: List[List[int]]) -> str: 3 | offset = 0 4 | for sh in shift: 5 | if sh[0] == 0: 6 | offset += sh[1] 7 | else: 8 | offset -= sh[1] 9 | 10 | offset %= len(s) 11 | return s[offset:] + s[:offset] 12 | -------------------------------------------------------------------------------- /LeetCode/1437. Check If All 1's Are at Least Length K Places Away/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kLengthApart(self, nums: List[int], k: int) -> bool: 3 | last_one = -1 4 | 5 | for i, num in enumerate(nums): 6 | if num == 1: 7 | if last_one >= 0 and i - last_one <= k: 8 | return False 9 | 10 | last_one = i 11 | 12 | return True 13 | -------------------------------------------------------------------------------- /LeetCode/1441. Build an Array With Stack Operations/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def buildArray(self, target: List[int], n: int) -> List[str]: 3 | # Time and Space Complexity: O(N) 4 | 5 | cur = 0 6 | 7 | ret = [] 8 | for num in target: 9 | for _ in range(cur, num - 1): 10 | ret.extend(["Push", "Pop"]) 11 | 12 | ret.append("Push") 13 | cur = num 14 | 15 | return ret 16 | -------------------------------------------------------------------------------- /LeetCode/1446. Consecutive Characters/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxPower(self, s: str) -> int: 3 | # Time Complexity: O(N) 4 | # Space Complexity: O(1) 5 | 6 | ret = 0 7 | start = 0 8 | end = 0 9 | 10 | while start < len(s): 11 | if end + 1 < len(s) and s[end + 1] == s[start]: 12 | end += 1 13 | else: 14 | ret = max(ret, end - start + 1) 15 | start = end + 1 16 | end += 1 17 | 18 | return ret 19 | -------------------------------------------------------------------------------- /LeetCode/145. Binary Tree Postorder Traversal/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | class Solution { 11 | public List postorderTraversal(TreeNode root) { 12 | List ret = new ArrayList(); 13 | 14 | if (root == null) 15 | return ret; 16 | 17 | List leftList = postorderTraversal(root.left); 18 | List rightList = postorderTraversal(root.right); 19 | 20 | ret.addAll(leftList); 21 | ret.addAll(rightList); 22 | ret.add(root.val); 23 | 24 | return ret; 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /LeetCode/1456. Maximum Number of Vowels in a Substring of Given Length/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxVowels(self, s: str, k: int) -> int: 3 | # Time Complexity: O(N) 4 | # Space Complexity: O(1) 5 | def is_vowel(char): 6 | return char in "aeiou" 7 | 8 | 9 | ret = 0 10 | for i in range(k): 11 | ret += int(is_vowel(s[i])) 12 | cur = ret 13 | 14 | for end in range(k, len(s)): 15 | cur += int(is_vowel(s[end])) - int(is_vowel(s[end - k])) 16 | ret = max(ret, cur) 17 | 18 | return ret 19 | -------------------------------------------------------------------------------- /LeetCode/1460. Make Two Arrays Equal by Reversing Sub-arrays/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canBeEqual(self, target: List[int], arr: List[int]) -> bool: 3 | return Counter(target) == Counter(arr) 4 | -------------------------------------------------------------------------------- /LeetCode/1464. Maximum Product of Two Elements in an Array/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProduct(self, nums: List[int]) -> int: 3 | # Time Complexity: O(N) 4 | # Space Complexity: O(1) 5 | 6 | largest = -1 7 | secondLargest = -1 8 | 9 | for num in nums: 10 | if num >= largest: 11 | secondLargest = largest 12 | largest = num 13 | elif num > secondLargest: 14 | secondLargest = num 15 | 16 | return (largest - 1) * (secondLargest - 1) 17 | -------------------------------------------------------------------------------- /LeetCode/1470. Shuffle the Array/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def shuffle(self, nums: List[int], n: int) -> List[int]: 3 | ret = [] 4 | for i in range(n): 5 | ret.append(nums[i]) 6 | ret.append(nums[i + n]) 7 | 8 | return ret 9 | -------------------------------------------------------------------------------- /LeetCode/1480. Running Sum of 1d Array/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def runningSum(self, nums: List[int]) -> List[int]: 3 | return list(itertools.accumulate(nums)) 4 | -------------------------------------------------------------------------------- /LeetCode/1492. The kth Factor of n/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kthFactor(self, n: int, k: int) -> int: 3 | # Time and Space Complexity: O(sqrt(N)) 4 | 5 | factors = [] 6 | 7 | for i in range(1, int(math.sqrt(n)) + 1): 8 | if n % i == 0: 9 | k -= 1 10 | factors.append(i) 11 | 12 | if not k: 13 | return i 14 | 15 | if factors[-1] ** 2 < n: 16 | if k <= len(factors): 17 | return n // factors[-k] 18 | else: 19 | if k < len(factors): 20 | return n // factors[-k - 1] 21 | 22 | return -1 23 | 24 | -------------------------------------------------------------------------------- /LeetCode/1497. Check If Array Pairs Are Divisible by k/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canArrange(self, arr: List[int], k: int) -> bool: 3 | mods = [0] * k 4 | for num in arr: 5 | mods[num % k] += 1 6 | 7 | for i in range(k): 8 | if i == (k - i) % k and mods[i] % 2 != 0: 9 | return False 10 | elif i != (k - i) % k and mods[i] != mods[k - i]: 11 | return False 12 | 13 | return True 14 | 15 | 16 | -------------------------------------------------------------------------------- /LeetCode/1506. Find Root of N-Ary Tree/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Definition for a Node. 3 | class Node: 4 | def __init__(self, val=None, children=None): 5 | self.val = val 6 | self.children = children if children is not None else [] 7 | """ 8 | 9 | class Solution: 10 | def findRoot(self, tree: List['Node']) -> 'Node': 11 | # Time Complexity: O(N) 12 | # Space Complexity: O(1) 13 | 14 | flag = 0 15 | 16 | for node in tree: 17 | flag = flag ^ node.val 18 | 19 | for child in node.children: 20 | flag = flag ^ child.val 21 | 22 | for node in tree: 23 | if node.val == flag: 24 | return node 25 | -------------------------------------------------------------------------------- /LeetCode/151. Reverse Words in a String/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String reverseWords(String s) { 3 | s = s.trim(); 4 | String[] words = s.split("[ ]+"); 5 | String ret = ""; 6 | 7 | for (int i = words.length - 1; i >= 0; i--) { 8 | ret = ret + words[i]; 9 | if (i != 0) 10 | ret = ret + " "; 11 | } 12 | 13 | return ret; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /LeetCode/1512. Number of Good Pairs/Solution.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn num_identical_pairs(nums: Vec) -> i32 { 3 | let mut ret = 0; 4 | 5 | for i in 0..(nums.len()) { 6 | for j in (i + 1)..(nums.len()) { 7 | if nums[i] == nums[j] { 8 | ret += 1; 9 | } 10 | } 11 | } 12 | 13 | ret 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /LeetCode/1528. Shuffle String/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def restoreString(self, s: str, indices: List[int]) -> str: 3 | # Time and Space Complexity: O(N) 4 | 5 | ret = [""] * len(s) 6 | 7 | for char, new_ind in zip(s, indices): 8 | ret[new_ind] = char 9 | 10 | return "".join(ret) 11 | -------------------------------------------------------------------------------- /LeetCode/1534. Count Good Triplets/Solution.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn count_good_triplets(arr: Vec, a: i32, b: i32, c: i32) -> i32 { 3 | let mut ret = 0; 4 | 5 | for i in 0..arr.len() { 6 | for j in (i + 1)..arr.len() { 7 | for k in (j + 1)..arr.len() { 8 | if (arr[i] - arr[j]).abs() <= a && (arr[j] - arr[k]).abs() <= b && (arr[k] - arr[i]).abs() <= c { 9 | ret += 1; 10 | } 11 | } 12 | } 13 | } 14 | 15 | ret 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /LeetCode/1539. Kth Missing Positive Number/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findKthPositive(self, arr: List[int], k: int) -> int: 3 | # Time Complexity: O(log N) 4 | # Space Complexity: O(1) 5 | 6 | if arr[0] > k: 7 | return k 8 | 9 | low = 0 10 | high = len(arr) - 1 11 | 12 | while low < high: 13 | mid = high - (high - low) // 2 14 | 15 | num_missing = arr[mid] - mid - 1 16 | 17 | if num_missing >= k: 18 | high = mid - 1 19 | else: 20 | low = mid 21 | 22 | offset = k - (arr[low] - low - 1) 23 | return arr[low] + offset 24 | 25 | -------------------------------------------------------------------------------- /LeetCode/154. Find Minimum in Rotated Sorted Array II/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMin(self, nums: List[int]) -> int: 3 | low = 0 4 | high = len(nums) - 1 5 | 6 | while low < high: 7 | mid = low + (high - low) // 2 8 | 9 | if nums[mid] < nums[high]: 10 | high = mid 11 | elif nums[mid] > nums[high]: 12 | low = mid + 1 13 | else: 14 | high -= 1 15 | 16 | return nums[low] 17 | 18 | -------------------------------------------------------------------------------- /LeetCode/1551. Minimum Operations to Make Array Equal/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minOperations(self, n: int) -> int: 3 | # Time and Space Complexity: O(1) 4 | 5 | # target: n (median of array) 6 | # num_operations = sum_{0 <= i < floor(n / 2)} n - (2 * i + 1) 7 | # = (floor(n / 2)) * (n - 1) - floor(n / 2) * (floor(n / 2) - 1) 8 | 9 | return (n // 2) * (n - 1) - (n // 2) * (n // 2 - 1) 10 | -------------------------------------------------------------------------------- /LeetCode/1554. Strings Differ by One Character/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def differByOne(self, dict: List[str]) -> bool: 3 | # Time Complexity: O(L^2 N) 4 | # Space Complexity: O(L^3 N) 5 | 6 | patterns = {} 7 | 8 | for string in dict: 9 | for i in range(len(string)): 10 | pattern = string[:i] + "*" + string[i + 1:] 11 | 12 | if pattern in patterns: 13 | return True 14 | 15 | patterns[pattern] = set([string]) 16 | 17 | return False 18 | -------------------------------------------------------------------------------- /LeetCode/1557. Minimum Number of Vertices to Reach All Nodes/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: 3 | # Time Complexity: O(V + E) 4 | # Space Complexity: O(V) 5 | 6 | candidates = set(range(n)) 7 | 8 | for edge in edges: 9 | if edge[1] in candidates: 10 | candidates.remove(edge[1]) 11 | 12 | return list(candidates) 13 | -------------------------------------------------------------------------------- /LeetCode/156. Binary Tree Upside Down/Solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def upsideDownBinaryTree(self, root: TreeNode) -> TreeNode: 10 | if not root: 11 | return root 12 | 13 | return self.rotate(root, None, None) 14 | 15 | def rotate(self, node: TreeNode, new_left: TreeNode, new_right: TreeNode): 16 | old_left, old_right = node.left, node.right 17 | node.left, node.right = new_left, new_right 18 | 19 | if old_left is None: 20 | return node # new root 21 | 22 | return self.rotate(old_left, old_right, node) 23 | -------------------------------------------------------------------------------- /LeetCode/1572. Matrix Diagonal/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int diagonalSum(int[][] mat) { 3 | List values = new ArrayList<>(); 4 | 5 | for (int i = 0; i < mat.length; i++) { 6 | values.add(mat[i][i]); 7 | 8 | if (mat.length - 1 - i != i) 9 | values.add(mat[i][mat.length - 1 - i]); 10 | } 11 | 12 | return values.stream().reduce(0, (x, y) -> x + y); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /LeetCode/1573. Number of Ways to Split a String/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numWays(self, s: str) -> int: 3 | # Time and Space Complexity: O(N) 4 | prefix = list(accumulate(map(int, s))) 5 | cnter = Counter(prefix) 6 | total = prefix[-1] 7 | 8 | if total % 3: 9 | return 0 10 | 11 | if not total: 12 | return ((len(s) - 2) * (len(s) - 1) // 2) % (1000000007) 13 | 14 | first_third = total // 3 15 | second_third = total // 3 * 2 16 | 17 | return (cnter[first_third] * cnter[second_third]) % (1000000007) 18 | -------------------------------------------------------------------------------- /LeetCode/1588. Sum of All Odd Length Subarrays/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sumOddLengthSubarrays(self, arr: List[int]) -> int: 3 | # Time and Space Complexity: O(N) 4 | 5 | # num_subarr[i] = # subarrays of odd length containing arr[i] 6 | # num_subarr[i] = (i + 2) // 2 * (len(arr) - i) // 2 + (i + 1) // 2 * (len(arr) - i + 1) // 2 - 1 7 | 8 | num_subarr = map(lambda i: ((i + 2) // 2) * ((len(arr) + 1 - i) // 2) + ((i + 1) // 2) * ((len(arr) - i) // 2), range(len(arr))) 9 | 10 | return reduce(lambda acc, pair: acc + pair[0] * pair[1], zip(num_subarr, arr), 0) 11 | -------------------------------------------------------------------------------- /LeetCode/1592. Rearrange Spaces Between Words/Solution.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | class Solution: 4 | def reorderSpaces(self, text: str) -> str: 5 | # Time and Space Complexity: O(N) 6 | 7 | words = list(filter(lambda w: len(w), re.split("\s+", text))) 8 | num_chars = sum(map(len, words)) 9 | num_spaces = len(text) - num_chars 10 | if len(words) == 1: 11 | return " ".join(words) + " " * num_spaces 12 | 13 | num_spaces_per_words = num_spaces // (len(words) - 1) 14 | return (" " * num_spaces_per_words).join(words) + " " * (num_spaces - num_spaces_per_words * (len(words) - 1)) 15 | -------------------------------------------------------------------------------- /LeetCode/16. 3Sum Closest/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def threeSumClosest(self, nums: List[int], target: int) -> int: 3 | nums.sort() 4 | ret = 1000000000 5 | 6 | for i in range(len(nums) - 2): 7 | j = i + 1 8 | k = len(nums) - 1 9 | 10 | while j < k: 11 | candidate = nums[i] + nums[j] + nums[k] 12 | if abs(candidate - target) < abs(ret - target): 13 | ret = candidate 14 | 15 | if candidate == target: 16 | return candidate 17 | 18 | if candidate < target: 19 | j += 1 20 | else: 21 | k -= 1 22 | 23 | return ret 24 | -------------------------------------------------------------------------------- /LeetCode/1603. Design Parking System/Solution.py: -------------------------------------------------------------------------------- 1 | class ParkingSystem: 2 | 3 | def __init__(self, big: int, medium: int, small: int): 4 | self.counter = collections.Counter() 5 | self.counter[1] = big 6 | self.counter[2] = medium 7 | self.counter[3] = small 8 | 9 | def addCar(self, carType: int) -> bool: 10 | if self.counter[carType]: 11 | self.counter[carType] -= 1 12 | return True 13 | return False 14 | 15 | 16 | # Your ParkingSystem object will be instantiated and called as such: 17 | # obj = ParkingSystem(big, medium, small) 18 | # param_1 = obj.addCar(carType) 19 | -------------------------------------------------------------------------------- /LeetCode/1605. Find Valid Matrix Given Row and Column Sums/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]: 3 | # Time and Space Complexity: O(MN) 4 | ret = [] 5 | 6 | for row_ind, rs in enumerate(rowSum): 7 | col_ind = 0 8 | row = [0] * len(colSum) 9 | 10 | while rs > 0: 11 | row[col_ind] = min(colSum[col_ind], rs) 12 | rs -= row[col_ind] 13 | colSum[col_ind] -= row[col_ind] 14 | col_ind += 1 15 | 16 | ret.append(row) 17 | 18 | 19 | return ret 20 | -------------------------------------------------------------------------------- /LeetCode/1614. Maximum Nesting Depth of the Parentheses/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxDepth(self, s: str) -> int: 3 | # Time Complexity: O(N) 4 | # Space Complexity: O(1) 5 | 6 | ret = 0 7 | num_open = 0 8 | 9 | for char in s: 10 | if char == "(": 11 | num_open += 1 12 | elif char == ")": 13 | num_open -= 1 14 | 15 | ret = max(ret, num_open) 16 | 17 | return ret 18 | -------------------------------------------------------------------------------- /LeetCode/1619. Mean of Array After Removing Some Elements/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def trimMean(self, arr: List[int]) -> float: 3 | # Time Complexity: O(N log N) 4 | # Space Complexity: O(1) 5 | 6 | arr.sort() 7 | trim_len = len(arr) // 20 8 | 9 | return sum(arr[trim_len:len(arr) - trim_len]) / (len(arr) - 2 * trim_len) 10 | -------------------------------------------------------------------------------- /LeetCode/1629. Slowest Key/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: 3 | # Time and Space Complexity: O(N) 4 | durations = {} 5 | for i, char in enumerate(keysPressed): 6 | start = 0 if not i else releaseTimes[i - 1] 7 | duration = releaseTimes[i] - start 8 | durations[char] = max(duration, durations.get(char, 0)) 9 | 10 | return max([(durations[char], char) for char in durations])[1] 11 | -------------------------------------------------------------------------------- /LeetCode/1636. Sort Array by Increasing Frequency/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def frequencySort(self, nums: List[int]) -> List[int]: 3 | cnter = Counter(nums) 4 | return sorted(nums, key=lambda val: (cnter[val], -val)) 5 | -------------------------------------------------------------------------------- /LeetCode/1640. Check Array Formation Through Concatenation/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: 3 | # Time Complexity: O(|arr| + |pieces|) 4 | # Space Complexity: O(|pieces|) 5 | 6 | initial = {piece[0]: piece for piece in pieces} 7 | 8 | i = 0 9 | while i < len(arr): 10 | if arr[i] not in initial: 11 | return False 12 | 13 | piece = initial[arr[i]] 14 | 15 | if len(arr) - i < len(piece): 16 | return False 17 | 18 | for j in range(len(piece)): 19 | if piece[j] != arr[i + j]: 20 | return False 21 | 22 | i += len(piece) 23 | 24 | return True 25 | -------------------------------------------------------------------------------- /LeetCode/1641. Count Sorted Vowel Strings/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countVowelStrings(self, n: int) -> int: 3 | # Time and Space Complexity: O(N) 4 | self.dp = {} 5 | return self.count(n, 0) 6 | 7 | def count(self, n: int, lowest: int) -> int: 8 | if not n: 9 | return 1 10 | else: 11 | if (n, lowest) in self.dp: 12 | return self.dp[(n, lowest)] 13 | ret = 0 14 | 15 | for i in range(lowest, 5): 16 | ret += self.count(n - 1, i) 17 | 18 | self.dp[(n, lowest)] = ret 19 | return ret 20 | -------------------------------------------------------------------------------- /LeetCode/1646. Get Maximum in Generated Array/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getMaximumGenerated(self, n: int) -> int: 3 | # Time and Space Complexity: O(N) 4 | 5 | if n <= 1: 6 | return n 7 | 8 | arr = [0, 1] 9 | 10 | for i in range(2, n + 1): 11 | if i % 2: 12 | arr.append(arr[i // 2] + arr[i // 2 + 1]) 13 | else: 14 | arr.append(arr[i // 2]) 15 | 16 | return max(arr) 17 | -------------------------------------------------------------------------------- /LeetCode/1647. Minimum Deletions to Make Character Frequencies Unique/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minDeletions(self, s: str) -> int: 3 | # Time Complexity: O(n log n) 4 | # Space Complexity: O(n) 5 | 6 | # Greedy strategy: consider characters by descending order of frequency 7 | # (proof: cut-and-paste) 8 | 9 | cnter = Counter(iter(s)) 10 | freqs = [(char, cnter[char]) for char in cnter] 11 | freqs.sort(key=lambda pair: -pair[-1]) 12 | 13 | cur_max = 100000000000 14 | max_len = 0 15 | for char, freq in freqs: 16 | freq = max(0, min(freq, cur_max - 1)) 17 | cur_max = freq 18 | max_len += freq 19 | 20 | return len(s) - max_len 21 | -------------------------------------------------------------------------------- /LeetCode/1657. Determine if Two Strings Are Close/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def closeStrings(self, word1: str, word2: str) -> bool: 3 | # Time and Space Complexity: O(N) 4 | 5 | cnter1 = Counter(word1) 6 | cnter2 = Counter(word2) 7 | 8 | return set([k for k in cnter1]) == set([k for k in cnter2]) and self.get_cnt_of_cnt(cnter1) == self.get_cnt_of_cnt(cnter2) 9 | 10 | def get_cnt_of_cnt(self, cnter): 11 | ret = Counter() 12 | 13 | for key in cnter: 14 | ret[cnter[key]] += 1 15 | 16 | return ret 17 | -------------------------------------------------------------------------------- /LeetCode/1663. Smallest String With A Given Numeric Value/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getSmallestString(self, n: int, k: int) -> str: 3 | # Time and Space Complexity: O(N) 4 | ret = [] 5 | 6 | for i in range(n): 7 | max_remain = (n - i - 1) * 26 8 | choice = max(1, k - max_remain) 9 | k -= choice 10 | 11 | ret.append(chr(ord('a') + choice - 1)) 12 | 13 | return "".join(ret) 14 | -------------------------------------------------------------------------------- /LeetCode/1672. Richest Customer Wealth/Solution.rs: -------------------------------------------------------------------------------- 1 | impl Solution { 2 | pub fn maximum_wealth(accounts: Vec>) -> i32 { 3 | return accounts.iter().map(|acc| acc.iter().sum()).max().unwrap() 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /LeetCode/1673. Find the Most Competitive Subsequence/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def mostCompetitive(self, nums: List[int], k: int) -> List[int]: 3 | # Time and Space Complexity: O(N) 4 | 5 | stack = [] 6 | 7 | for i, num in enumerate(nums): 8 | poppable = (len(nums) - i + len(stack)) - k 9 | 10 | while stack and poppable > 0 and stack[-1] > num: 11 | stack.pop() 12 | poppable -= 1 13 | 14 | stack.append(num) 15 | 16 | return stack[:k] 17 | -------------------------------------------------------------------------------- /LeetCode/1679. Max Number of K-Sum Pairs/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxOperations(self, nums: List[int], k: int) -> int: 3 | # Time and Space Complexity: O(N) 4 | counter = Counter(nums) 5 | 6 | ret = 0 7 | for num in counter: 8 | if num * 2 == k: 9 | ret += counter[num] // 2 10 | elif num < k - num: 11 | ret += min(counter[num], counter[k - num]) 12 | 13 | return ret 14 | -------------------------------------------------------------------------------- /LeetCode/1680. Concatenation of Consecutive Binary Numbers/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def concatenatedBinary(self, n: int) -> int: 3 | # Time Complexity: O(N) 4 | # Space Complexity: O(1) 5 | 6 | ret = 1 7 | num_dig = 1 8 | MOD = 1000000007 9 | 10 | for i in range(2, n + 1): 11 | if not (i & (i - 1)): 12 | # i is a power of 2 13 | num_dig += 1 14 | 15 | ret = (ret << num_dig) | i 16 | ret %= MOD 17 | 18 | return ret 19 | -------------------------------------------------------------------------------- /LeetCode/1684. Count the Number of Consistent Strings/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countConsistentStrings(self, allowed: str, words: List[str]) -> int: 3 | # Time Complexity: O(sum(|word|)) 4 | # Space Complexity: O(1) 5 | 6 | allowed_set = set(iter(allowed)) # size at most 26 7 | return sum(map(partial(self.is_str_allow, allowed=allowed_set), words)) 8 | 9 | def is_str_allow(self, string, allowed): 10 | return all(map(lambda c: c in allowed, string)) 11 | -------------------------------------------------------------------------------- /LeetCode/169. Majority Element/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int majorityElement(int[] nums) { 3 | int curMajor = 0; 4 | int counter = 0; 5 | for (int i = 0; i < nums.length; i++) { 6 | if (counter == 0) { 7 | curMajor = nums[i]; 8 | counter = 1; 9 | } 10 | else if (curMajor == nums[i]) 11 | counter += 1; 12 | else 13 | counter -= 1; 14 | } 15 | return curMajor; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /LeetCode/1700. Number of Students Unable to Eat Lunch/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countStudents(self, students: List[int], sandwiches: List[int]) -> int: 3 | # Time and Space Complexity: O(N) 4 | 5 | students_counter = Counter(students) 6 | 7 | for i, sandwich in enumerate(sandwiches): 8 | if students_counter[sandwich]: 9 | students_counter[sandwich] -= 1 10 | else: 11 | return len(students) - i 12 | 13 | return 0 14 | -------------------------------------------------------------------------------- /LeetCode/1704. Determine if String Halves Are Alike/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def halvesAreAlike(self, s: str) -> bool: 3 | # Time and Space Complexity: O(N) 4 | s = s.lower() 5 | 6 | lower_half = Counter(s[:len(s) // 2]) 7 | upper_half = Counter(s[len(s) // 2:]) 8 | 9 | def get_vowel_cnt(counter): 10 | return sum([counter[char] for char in "aeiou"]) 11 | 12 | return get_vowel_cnt(lower_half) == get_vowel_cnt(upper_half) 13 | -------------------------------------------------------------------------------- /LeetCode/171. Excel Sheet Column Number/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def titleToNumber(self, s: str) -> int: 3 | ret = 0 4 | 5 | for char in s: 6 | ret = ret * 26 + 1 + ord(char) - ord("A") 7 | 8 | return ret 9 | -------------------------------------------------------------------------------- /LeetCode/1710. Maximum Units on a Truck/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int: 3 | # Time Complexity: O(N log N) 4 | # Space Complexity: O(1) 5 | 6 | # Greedy: load the boxes in decreasing order of units 7 | # Proof: cut-and-paste 8 | 9 | boxTypes.sort(key=lambda pair: -pair[-1]) 10 | ret = 0 11 | remaining = truckSize 12 | box_ind = 0 13 | 14 | while box_ind < len(boxTypes) and remaining > 0: 15 | ret += boxTypes[box_ind][1] * min(remaining, boxTypes[box_ind][0]) 16 | remaining -= min(remaining, boxTypes[box_ind][0]) 17 | box_ind += 1 18 | 19 | return ret 20 | -------------------------------------------------------------------------------- /LeetCode/172. Factorial Trailing Zeroes/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int trailingZeroes(int n) { 3 | if (n < 0) 4 | return trailingZeroes(-n); 5 | 6 | return vp(n, 5); 7 | } 8 | 9 | private int vp(int n, int p) { 10 | // p must be prime 11 | // v_p(n) = highest power k such that p^k | n 12 | // Legendre's theorem: 13 | // v_p(n) = \sum_{k: p^k <= n} floor(n / p^k) 14 | // Complexity: O(log_p(n)) 15 | 16 | int ret = 0; 17 | 18 | while (n > 0) { 19 | n /= p; 20 | ret += n; 21 | } 22 | 23 | return ret; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /LeetCode/1721. Swapping Nodes in a Linked List/Solution.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def swapNodes(self, head: ListNode, k: int) -> ListNode: 8 | # Time and Space Complexity: O(N) 9 | 10 | data = [] 11 | 12 | while head: 13 | data.append(head.val) 14 | head = head.next 15 | 16 | tmp = data[k - 1] 17 | data[k - 1] = data[-k] 18 | data[-k] = tmp 19 | 20 | ret = ListNode(data[0]) 21 | it = ret 22 | 23 | for datum in data[1:]: 24 | it.next = ListNode(datum) 25 | it = it.next 26 | 27 | return ret 28 | -------------------------------------------------------------------------------- /LeetCode/1748. Sum of Unique Elements/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sumOfUnique(self, nums: List[int]) -> int: 3 | ret = 0 4 | counts = Counter(nums) 5 | 6 | for num in counts: 7 | if counts[num] == 1: 8 | ret += num 9 | 10 | return ret 11 | -------------------------------------------------------------------------------- /LeetCode/1762. Buildings With an Ocean View/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findBuildings(self, heights: List[int]) -> List[int]: 3 | # Time and Space Complexity: O(N) 4 | 5 | ret = [] 6 | 7 | cur_max = -1 8 | for i in range(len(heights) - 1, -1, -1): 9 | if heights[i] > cur_max: 10 | ret.append(i) 11 | 12 | cur_max = max(cur_max, heights[i]) 13 | 14 | return ret[::-1] 15 | -------------------------------------------------------------------------------- /LeetCode/1785. Minimum Elements to Add to Form a Given Sum/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minElements(self, nums: List[int], limit: int, goal: int) -> int: 3 | # Time Complexity: O(N) 4 | # Space Complexity: O(1) 5 | 6 | numsum = sum(nums) 7 | delta = abs(goal - numsum) 8 | 9 | return math.ceil(delta / limit) 10 | -------------------------------------------------------------------------------- /LeetCode/1817. Finding the Users Active Minutes/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]: 3 | # Time and Space Complexity: O(N) 4 | 5 | minutes = {} 6 | 7 | for user, minute in logs: 8 | if user not in minutes: 9 | minutes[user] = set() 10 | 11 | minutes[user].add(minute) 12 | 13 | ret = [0] * k 14 | for user in minutes: 15 | ret[len(minutes[user]) - 1] += 1 16 | 17 | return ret 18 | -------------------------------------------------------------------------------- /LeetCode/1832. Check if the Sentence Is Pangram/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkIfPangram(string sentence) { 4 | // Time Complexity: O(N) 5 | // Space Complexity: O(1) 6 | 7 | unordered_set contains; 8 | 9 | for (auto it = sentence.begin(); it != sentence.end(); it++) { 10 | contains.insert({*it}); 11 | } 12 | 13 | return contains.size() == 26; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /LeetCode/1859. Sorting the Sentence/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortSentence(self, s: str) -> str: 3 | # Time and Space Complexity: O(N) 4 | 5 | words = sorted(s.split(" "), key=itemgetter(-1)) 6 | return " ".join(map(lambda w: w[:-1], words)) 7 | -------------------------------------------------------------------------------- /LeetCode/1891. Cutting Ribbons/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxLength(self, ribbons: List[int], k: int) -> int: 3 | # Time Complexity: O(N log(max_ribbons)) 4 | # Space Complexity: O(1) 5 | 6 | low = 1 7 | high = max(ribbons) 8 | 9 | def cut(ribbons, target_len): 10 | return sum(map(lambda ribbon: ribbon // target_len, ribbons)) 11 | 12 | 13 | while low < high: 14 | mid = high - (high - low) // 2 15 | 16 | num_ribbons = cut(ribbons, mid) 17 | if num_ribbons < k: 18 | high = mid - 1 19 | else: 20 | low = mid 21 | 22 | 23 | if cut(ribbons, low) >= k: 24 | return low 25 | 26 | return 0 27 | -------------------------------------------------------------------------------- /LeetCode/190. Reverse Bits/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | // you need treat n as an unsigned value 3 | public int reverseBits(int n) { 4 | int ret = 0; 5 | 6 | for (int i = 0; i < 32; i++) { 7 | ret = (ret << 1) | (n & 1); 8 | n >>= 1; 9 | } 10 | 11 | return ret; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /LeetCode/1908. Game of Nim/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def nimGame(self, piles: List[int]) -> bool: 3 | # Time Complexity: O(N) 4 | # Space Complexity: O(1) 5 | 6 | # Theorem (Sprague-Gundy): Alice wins i.f.f XOR(piles) != 0 7 | # Strategy: pick the number of stones that would bring this to 0 8 | 9 | return reduce(lambda x, y: x ^ y, piles) != 0 10 | 11 | -------------------------------------------------------------------------------- /LeetCode/191. Number of 1 Bits/Solution.java: -------------------------------------------------------------------------------- 1 | // based on https://www.geeksforgeeks.org/count-set-bits-in-an-integer/ 2 | public class Solution { 3 | // you need to treat n as an unsigned value 4 | public int hammingWeight(int n) { 5 | if (n == 0) 6 | return 0; 7 | else 8 | return 1 + hammingWeight(n & (n - 1)); 9 | 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /LeetCode/1929. Concatenation of Array/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector getConcatenation(vector& nums) { 4 | vector ret; 5 | 6 | for (int i = 0; i < 2; i++) { 7 | for (auto it = nums.begin(); it != nums.end(); it++) { 8 | ret.push_back(*it); 9 | } 10 | } 11 | 12 | return ret; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /LeetCode/1944. Number of Visible People in a Queue/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canSeePersonsCount(self, heights: List[int]) -> List[int]: 3 | # Time and Space Complexity: O(N) 4 | 5 | ret = [] 6 | stack = [] 7 | 8 | for height in heights[::-1]: 9 | can_see = 0 10 | 11 | while stack and stack[-1] < height: 12 | can_see += 1 13 | stack.pop() 14 | 15 | if stack: 16 | can_see += 1 17 | 18 | ret.append(can_see) 19 | stack.append(height) 20 | 21 | return ret[::-1] 22 | -------------------------------------------------------------------------------- /LeetCode/2007. Find Original Array From Doubled Array/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findOriginalArray(self, changed: List[int]) -> List[int]: 3 | # Time Complexity: O(N log N) 4 | # Space Complexity: O(N) 5 | 6 | changed.sort() 7 | 8 | cnter = Counter(changed) 9 | 10 | ret = [] 11 | 12 | for val in changed: 13 | if cnter[val] > 0: 14 | cnter[val] -= 1 15 | 16 | if cnter[val * 2] == 0: 17 | return [] 18 | 19 | cnter[val * 2] -= 1 20 | ret.append(val) 21 | 22 | return ret 23 | -------------------------------------------------------------------------------- /LeetCode/201. Bitwise AND of Numbers Range/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rangeBitwiseAnd(self, m: int, n: int) -> int: 3 | while m < n: 4 | n &= (n - 1) 5 | 6 | return m & n 7 | 8 | -------------------------------------------------------------------------------- /LeetCode/202. Happy Number/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isHappy(int n) { 3 | if (n < 10) { 4 | if (n == 1 || n == 7) 5 | return true; 6 | else 7 | return false; 8 | } 9 | return isHappy(transform(n)); 10 | } 11 | 12 | private int transform(int n) { 13 | int ret = 0; 14 | while (n > 0) { 15 | int dig = n % 10; 16 | n /= 10; 17 | ret += dig * dig; 18 | } 19 | 20 | return ret; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /LeetCode/202. Happy Number/Solution2.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isHappy(int n) { 3 | if (n == 1) 4 | return true; 5 | Set nums = new HashSet(); 6 | 7 | do { 8 | nums.add(n); 9 | n = transform(n); 10 | if (n == 1) 11 | return true; 12 | } while(!nums.contains(n)); 13 | 14 | return false; 15 | } 16 | 17 | private int transform(int n) { 18 | int ret = 0; 19 | while (n > 0) { 20 | int dig = n % 10; 21 | n /= 10; 22 | ret += dig * dig; 23 | } 24 | 25 | return ret; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /LeetCode/203. Remove Linked List Elements/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | class Solution { 10 | public ListNode removeElements(ListNode head, int val) { 11 | while (head != null && head.val == val) 12 | head = head.next; 13 | 14 | if (head != null) { 15 | ListNode par = head; 16 | 17 | while (par.next != null) { 18 | if (par.next.val == val) 19 | par.next = par.next.next; 20 | else 21 | par = par.next; 22 | } 23 | } 24 | 25 | return head; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /LeetCode/203. Remove Linked List Elements/Solution2.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | class Solution2 { 10 | public ListNode removeElements(ListNode head, int val) { 11 | if (head == null) 12 | return null; 13 | 14 | if (head.val == val) 15 | return removeElements(head.next, val); 16 | 17 | head.next = removeElements(head.next, val); 18 | return head; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /LeetCode/204. Count Primes/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countPrimes(int n) { 3 | int ret = 0; 4 | int[] sieve = new int[n + 1]; 5 | 6 | for (int i = 2; i < n; i++) { 7 | if (sieve[i] == 0) { 8 | ret += 1; 9 | for (int j = 1; j <= n / i; j++) 10 | sieve[i * j] = -1; 11 | } 12 | } 13 | 14 | return ret; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /LeetCode/205. Isomorphic Strings/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isIsomorphic(self, s: str, t: str) -> bool: 3 | # Time and Space Complexity: O(N) 4 | 5 | bimap = Bimap() 6 | 7 | for i in range(len(s)): 8 | if not bimap.put(s[i], t[i]): 9 | return False 10 | 11 | return True 12 | 13 | 14 | class Bimap: 15 | def __init__(self): 16 | self.forward, self.backward = {}, {} 17 | 18 | def put(self, first, second): 19 | if self.forward.get(first, second) == second and self.backward.get(second, first) == first: 20 | self.forward[first] = second 21 | self.backward[second] = first 22 | 23 | return True 24 | 25 | return False 26 | -------------------------------------------------------------------------------- /LeetCode/206. Reverse Linked List/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | class Solution { 10 | public ListNode reverseList(ListNode head) { 11 | if (head != null && head.next != null) { 12 | ListNode tmp1 = head; 13 | ListNode tmp2 = head.next; 14 | 15 | head = reverseList(head.next); 16 | tmp1.next = null; 17 | tmp2.next = tmp1; 18 | 19 | return head; 20 | } 21 | else 22 | return head; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /LeetCode/216. Combination Sum III/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def combinationSum3(self, k: int, n: int) -> List[List[int]]: 3 | ret = [] 4 | self.build(k, n, [], 0, ret) 5 | return ret 6 | 7 | 8 | def build(self, k: int, n: int, sol: List[int], sol_sum: int, ret: List[List[int]]): 9 | if len(sol) == k: 10 | if sol_sum == n: 11 | ret.append(copy.deepcopy(sol)) 12 | else: 13 | lower_bound = 1 if not sol else sol[-1] + 1 14 | upper_bound = min(n - sol_sum + 1, 10) 15 | 16 | for val in range(lower_bound, upper_bound): 17 | sol.append(val) 18 | self.build(k, n, sol, sol_sum + val, ret) 19 | sol.pop() 20 | -------------------------------------------------------------------------------- /LeetCode/2164. Sort Even and Odd Indices Independently/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortEvenOdd(self, nums: List[int]) -> List[int]: 3 | evens = sorted(nums[i] for i in range(0, len(nums), 2)) 4 | odds = sorted([nums[i] for i in range(1, len(nums), 2)], reverse=True) 5 | ret = [] 6 | 7 | for i in range(len(nums)): 8 | if i % 2 == 0: 9 | ret.append(evens[i // 2]) 10 | else: 11 | ret.append(odds[i // 2]) 12 | 13 | return ret 14 | -------------------------------------------------------------------------------- /LeetCode/217. Contains Duplicate/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean containsDuplicate(int[] nums) { 3 | Set numSet = new HashSet(); 4 | for (int i = 0; i < nums.length; i++) 5 | numSet.add(nums[i]); 6 | return numSet.size() != nums.length; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /LeetCode/219. Contains Duplicate II/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: 3 | # Time and Space Complexity: O(N) 4 | 5 | index = {} 6 | 7 | for i, num in enumerate(nums): 8 | if num in index and i - index[num] <= k: 9 | return True 10 | 11 | index[num] = i 12 | 13 | return False 14 | -------------------------------------------------------------------------------- /LeetCode/223. Rectangle Area/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int computeAreaRectangle(int A, int B, int C, int D) { 3 | return (C - A) * (D - B); 4 | } 5 | public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { 6 | int areaI = computeAreaRectangle(A, B, C, D); 7 | int areaII = computeAreaRectangle(E, F, G, H); 8 | 9 | int M = A > E ? A : E; 10 | int N = B > F ? B : F; 11 | int P = C < G ? C : G; 12 | int Q = D < H ? D : H; 13 | 14 | if (M > P || N > Q) 15 | return areaI + areaII; 16 | else 17 | return areaI + areaII - computeAreaRectangle(M, N, P, Q); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /LeetCode/226. Invert Binary Tree/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | class Solution { 11 | public TreeNode invertTree(TreeNode root) { 12 | if (root == null) 13 | return root; 14 | 15 | TreeNode tmp = invertTree(root.left); 16 | root.left = invertTree(root.right); 17 | root.right = tmp; 18 | 19 | return root; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /LeetCode/231. Power of Two/Solution.java: -------------------------------------------------------------------------------- 1 | public boolean isPowerOfTwo(int n) { 2 | if (n <= 0) 3 | return false; 4 | 5 | return (n & (n - 1)) == 0; 6 | } 7 | -------------------------------------------------------------------------------- /LeetCode/235. Lowest Common Ancestor of a Binary Search Tree/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | class Solution { 11 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 12 | if ((root.val - p.val) * (root.val - q.val) <= 0) 13 | return root; 14 | 15 | if (root.val > p.val) 16 | return lowestCommonAncestor(root.left, p, q); 17 | else 18 | return lowestCommonAncestor(root.right, p, q); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /LeetCode/237. Delete Node in a Linked List/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | class Solution { 10 | public void deleteNode(ListNode node) { 11 | ListNode cur = node; 12 | 13 | if (cur.next.next != null) { 14 | while (cur.next.next != null) { 15 | cur.val = cur.next.val; 16 | cur = cur.next; 17 | } 18 | } 19 | 20 | cur.val = cur.next.val; 21 | cur.next = null; 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /LeetCode/238. Product of Array Except Self/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] productExceptSelf(int[] nums) { 3 | int [] ret = new int[nums.length]; 4 | 5 | ret[0] = 1; 6 | for (int i = 1; i < nums.length; i++) { 7 | ret[i] = ret[i - 1] * nums[i - 1]; 8 | } 9 | 10 | int R = 1; 11 | for (int j = nums.length - 2; j >= 0; j--) { 12 | R *= nums[j + 1]; 13 | ret[j] *= R; 14 | } 15 | return ret; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /LeetCode/240. Search a 2D Matrix II/Solution2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchMatrix(self, matrix, target): 3 | # Time Complexity: O(M + N) 4 | # Space Complexity: O(1) 5 | 6 | i = 0 7 | j = len(matrix[0]) - 1 8 | 9 | while i < len(matrix) and j >= 0: 10 | if matrix[i][j] == target: 11 | return True 12 | elif matrix[i][j] < target: 13 | i += 1 14 | else: 15 | j -= 1 16 | 17 | return False 18 | -------------------------------------------------------------------------------- /LeetCode/2400. Number of Ways to Reach a Position After Exactly k Steps/Solution.py: -------------------------------------------------------------------------------- 1 | MOD = 10 ** 9 + 7 2 | 3 | 4 | @cache 5 | def count(dist, remain): 6 | if remain == 0: 7 | return 1 if dist == 0 else 0 8 | 9 | if dist > remain: 10 | return 0 11 | 12 | return (count(dist - 1, remain - 1) + count(dist + 1, remain - 1)) % MOD 13 | 14 | 15 | class Solution: 16 | def numberOfWays(self, startPos: int, endPos: int, k: int) -> int: 17 | # Time and Space Complexity: O(k^2) 18 | return count(endPos - startPos, k) 19 | -------------------------------------------------------------------------------- /LeetCode/243. Shortest Word Distance/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def shortestDistance(self, words: List[str], word1: str, word2: str) -> int: 3 | index = {} 4 | 5 | for i, word in enumerate(words): 6 | if word not in index: 7 | index[word] = [] 8 | 9 | index[word].append(i) 10 | 11 | ret = 10000000000 12 | 13 | occ1 = index[word1] 14 | occ2 = index[word2] 15 | 16 | 17 | i = 0 18 | j = 0 19 | 20 | while i < len(occ1) and j < len(occ2): 21 | ret = min(ret, abs(occ1[i] - occ2[j])) 22 | 23 | if occ1[i] < occ2[j]: 24 | i += 1 25 | else: 26 | j += 1 27 | 28 | return ret 29 | -------------------------------------------------------------------------------- /LeetCode/246. Strobogrammatic Number/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isStrobogrammatic(self, num: str) -> bool: 3 | reflection = {"8": "8", "6": "9", "9": "6", "1": "1", "0": "0"} 4 | 5 | for i in range(len(num)): 6 | if num[i] not in reflection: 7 | return False 8 | 9 | if reflection[num[i]] != num[len(num) - 1 - i]: 10 | return False 11 | 12 | return True 13 | -------------------------------------------------------------------------------- /LeetCode/249. Group Shifted Strings/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def groupStrings(self, strings: List[str]) -> List[List[str]]: 3 | # Time and Space Complexity: O(sum(len(string))) 4 | 5 | def shift_seq(string): 6 | ret = [] 7 | 8 | for i in range(1, len(string)): 9 | ret.append((ord(string[i]) - ord(string[i - 1]) + 26) % 26) 10 | 11 | return tuple(ret) 12 | 13 | ret = [] 14 | 15 | groups = {} 16 | for string in strings: 17 | key = shift_seq(string) 18 | 19 | if key not in groups: 20 | groups[key] = [] 21 | 22 | groups[key].append(string) 23 | 24 | return [groups[key] for key in groups] 25 | -------------------------------------------------------------------------------- /LeetCode/252. Meeting Rooms/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canAttendMeetings(self, intervals: List[List[int]]) -> bool: 3 | # Time Complexity: O(n log n) 4 | # Space Complexity: O(1) 5 | 6 | intervals.sort(key=lambda x:x[0]) 7 | for i in range(len(intervals) - 1): 8 | if intervals[i][1] > intervals[i + 1][0]: 9 | return False 10 | 11 | return True 12 | 13 | -------------------------------------------------------------------------------- /LeetCode/255. Verify Preorder Sequence in Binary Search Tree/Solution.py: -------------------------------------------------------------------------------- 1 | INF = 1000000 2 | 3 | 4 | class Solution: 5 | def verifyPreorder(self, preorder: List[int]) -> bool: 6 | # Time Complexity: O(N) 7 | # Space Complexity: O(H) 8 | 9 | return self.verify(preorder, 0, -INF, INF) == len(preorder) 10 | 11 | def verify(self, preorder: List[int], i: int, lower: int, upper: int): 12 | if i >= len(preorder): 13 | return i 14 | 15 | if preorder[i] <= lower or preorder[i] >= upper: 16 | return i 17 | 18 | left_end = self.verify(preorder, i + 1, lower, preorder[i]) 19 | right_end = self.verify(preorder, left_end, preorder[i], upper) 20 | 21 | return right_end 22 | -------------------------------------------------------------------------------- /LeetCode/258. Add Digits/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addDigits(self, num: int) -> int: 3 | if num == 0: 4 | return 0 5 | 6 | if num % 9 != 0: 7 | return num % 9 8 | 9 | return 9 10 | -------------------------------------------------------------------------------- /LeetCode/259. 3Sum Smaller/Solution.py: -------------------------------------------------------------------------------- 1 | import bisect 2 | 3 | 4 | class Solution: 5 | def threeSumSmaller(self, nums: List[int], target: int) -> int: 6 | # Time Complexity: O(N^2) 7 | # Space Complexity: O(1) 8 | nums.sort() 9 | ret = 0 10 | 11 | for i in range(len(nums) - 2): 12 | j = i + 1 13 | k = len(nums) - 1 14 | 15 | while j < k: 16 | while j < k and nums[i] + nums[j] + nums[k] >= target: 17 | k -= 1 18 | 19 | if j < k: 20 | ret += (k - j) 21 | 22 | j += 1 23 | 24 | return ret 25 | -------------------------------------------------------------------------------- /LeetCode/26. Remove Duplicates from Sorted Array/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int removeDuplicates(int[] nums) { 3 | if (nums.length <= 1) 4 | return 1; 5 | 6 | int it = 1; 7 | int curInd = 0; 8 | 9 | while (it < nums.length) { 10 | if (nums[it] != nums[curInd]) { 11 | curInd += 1; 12 | nums[curInd] = nums[it]; 13 | } 14 | it += 1; 15 | } 16 | 17 | return curInd + 1; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /LeetCode/260. Single Number III/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def singleNumber(self, nums: List[int]) -> List[int]: 3 | bitmask = reduce(lambda x, y: x^y, nums) 4 | x_check = bitmask & (-bitmask) 5 | x = reduce(lambda x, y: x^y, filter(lambda x: x & x_check, nums)) 6 | y = bitmask ^ x 7 | 8 | return [x, y] 9 | -------------------------------------------------------------------------------- /LeetCode/263. Ugly Number/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isUgly(int n) { 4 | // Time Complexity: O(log n) 5 | // Space Complexity: O(1) 6 | 7 | if (n <= 0) 8 | return false; 9 | 10 | int divisors[3] = { 2, 3, 5 }; 11 | 12 | for (int divisor : divisors) { 13 | while (n != 0 && n % divisor == 0) 14 | n /= divisor; 15 | } 16 | 17 | return n == 1; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /LeetCode/266. Palindrome Permutation/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canPermutePalindrome(self, s: str) -> bool: 3 | # Time and Space Complexity: O(N) 4 | 5 | cnter = Counter(s) 6 | 7 | num_odd = 0 8 | 9 | for char in cnter: 10 | num_odd += cnter[char] % 2 11 | 12 | return num_odd <= 1 13 | -------------------------------------------------------------------------------- /LeetCode/268. Missing Number/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int missingNumber(int[] nums) { 3 | int sum = 0; 4 | for (int i = 0; i < nums.length; i++) 5 | sum += nums[i]; 6 | return (nums.length + 1) * nums.length / 2 - sum; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /LeetCode/27. Remove Element/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int removeElement(int[] nums, int val) { 3 | int finalLength = nums.length; 4 | int i = 0; 5 | 6 | while (i < nums.length && i < finalLength) { 7 | if (nums[i] == val) { 8 | for (int j = i + 1;j < finalLength; j++) 9 | nums[j - 1] = nums[j]; 10 | finalLength -= 1; 11 | } 12 | else 13 | i += 1; 14 | } 15 | 16 | return finalLength; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /LeetCode/275. H-Index II/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hIndex(self, citations: List[int]) -> int: 3 | low = 0 4 | high = len(citations) 5 | 6 | while low < high: 7 | h = high - (high - low) // 2 8 | 9 | ind = len(citations) - h 10 | 11 | if citations[ind] >= h: 12 | low = h 13 | else: 14 | high = h - 1 15 | 16 | return low 17 | 18 | 19 | -------------------------------------------------------------------------------- /LeetCode/278. First Bad Version/Solution.java: -------------------------------------------------------------------------------- 1 | /* The isBadVersion API is defined in the parent class VersionControl. 2 | boolean isBadVersion(int version); */ 3 | 4 | public class Solution extends VersionControl { 5 | public int firstBadVersion(int n) { 6 | return findBadVersion(1, n); 7 | } 8 | 9 | private int findBadVersion(int start, int end) { 10 | if (start == end) 11 | return start; 12 | 13 | long midLong = ((long) start + end) >> 1; 14 | int mid = (int) midLong; 15 | if (super.isBadVersion(mid)) 16 | return findBadVersion(start, mid); 17 | else 18 | return findBadVersion(mid + 1, end); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /LeetCode/280. Wiggle Sort/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void wiggleSort(int[] nums) { 3 | int tmp; 4 | for (int i = 0; i < nums.length - 1; i++) { 5 | if (i % 2 == 0) { 6 | if (nums[i] > nums[i + 1]) { 7 | tmp = nums[i]; 8 | nums[i] = nums[i + 1]; 9 | nums[i + 1] = tmp; 10 | } 11 | } 12 | else { 13 | if (nums[i] < nums[i + 1]) { 14 | tmp = nums[i]; 15 | nums[i] = nums[i + 1]; 16 | nums[i + 1] = tmp; 17 | } 18 | } 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /LeetCode/283. Move Zeroes/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void moveZeroes(int[] nums) { 3 | int firstZero = 0; 4 | while (firstZero < nums.length && nums[firstZero] != 0) 5 | firstZero += 1; 6 | if (firstZero < nums.length) { 7 | int i = firstZero + 1; 8 | while (i < nums.length) { 9 | if (nums[i] != 0) { 10 | nums[firstZero] = nums[i]; 11 | nums[i] = 0; 12 | firstZero += 1; 13 | } 14 | i += 1; 15 | } 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /LeetCode/287. Find the Duplicate Number/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findDuplicate(int[] nums) { 3 | int slow = nums[0]; 4 | int fast = nums[0]; 5 | 6 | do { 7 | slow = nums[slow]; 8 | fast = nums[nums[fast]]; 9 | } while (slow != fast); 10 | 11 | int start = nums[0]; 12 | 13 | while (start != slow) { 14 | start = nums[start]; 15 | slow = nums[slow]; 16 | } 17 | 18 | return slow; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /LeetCode/292. Nim Game/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canWinNim(int n) { 3 | return n % 4 != 0; 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /LeetCode/300. Longest Increasing Subsequence/Solution2.java: -------------------------------------------------------------------------------- 1 | class Solution2 { 2 | // O(n log n) solution 3 | public int lengthOfLIS(int[] nums) { 4 | int[] initial = new int[nums.length]; 5 | int curLen = 0; 6 | 7 | for (int i = nums.length - 1; i >= 0; i--) { 8 | int insertPoint = Arrays.binarySearch(initial, 0, curLen, -nums[i]); 9 | if (insertPoint < 0) 10 | insertPoint = -insertPoint - 1; 11 | initial[insertPoint] = -nums[i]; 12 | if (insertPoint == curLen) { 13 | curLen += 1; 14 | } 15 | } 16 | 17 | return curLen; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /LeetCode/303. Range Sum Query - Immutable/Solution.java: -------------------------------------------------------------------------------- 1 | class NumArray { 2 | private int[] prefix; 3 | 4 | public NumArray(int[] nums) { 5 | if (nums.length > 0) { 6 | prefix = new int[nums.length]; 7 | prefix[0] = nums[0]; 8 | 9 | for (int i = 1; i < nums.length; i++) 10 | prefix[i] = nums[i] + prefix[i - 1]; 11 | } 12 | } 13 | 14 | public int sumRange(int i, int j) { 15 | if (i == 0) 16 | return prefix[j]; 17 | else 18 | return prefix[j] - prefix[i - 1]; 19 | } 20 | } 21 | 22 | /** 23 | * Your NumArray object will be instantiated and called as such: 24 | * NumArray obj = new NumArray(nums); 25 | * int param_1 = obj.sumRange(i,j); 26 | */ 27 | -------------------------------------------------------------------------------- /LeetCode/319. Bulb Switcher/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int bulbSwitch(int n) { 3 | int ret = 0; 4 | int cnt = 1; 5 | while (cnt * cnt <= n) { 6 | ret += 1; 7 | cnt += 1; 8 | } 9 | return ret; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /LeetCode/325. Maximum Size Subarray Sum Equals k/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSubArrayLen(self, nums: List[int], k: int) -> int: 3 | # Time and Space Complexity: O(n) 4 | 5 | prefixes = [0] 6 | for num in nums: 7 | prefixes.append(num + prefixes[-1]) 8 | 9 | inverted_index = {} 10 | length = 0 11 | for i in range(len(prefixes)): 12 | if prefixes[i] - k in inverted_index: 13 | length = max(length, i - inverted_index[prefixes[i] - k]) 14 | 15 | if prefixes[i] not in inverted_index: 16 | inverted_index[prefixes[i]] = i 17 | 18 | return length 19 | 20 | -------------------------------------------------------------------------------- /LeetCode/326. Power of Three/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPowerOfThree(self, n: int) -> bool: 3 | cur = 1 4 | 5 | while cur < n: 6 | cur *= 3 7 | 8 | return cur == n 9 | -------------------------------------------------------------------------------- /LeetCode/331. Verify Preorder Serialization of a Binary Tree/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isValidSerialization(self, preorder: str) -> bool: 3 | # Time and Space Complexity: O(N) 4 | values = preorder.split(",") 5 | return self.validate(values, 0) == len(values) 6 | 7 | def validate(self, values: List[str], i: int): 8 | if values[i] == "#": 9 | return i + 1 # null node, no children 10 | 11 | if i + 1 == len(values): 12 | return None 13 | 14 | right_start = self.validate(values, i + 1) 15 | if right_start is None or right_start == len(values): 16 | return None 17 | 18 | return self.validate(values, right_start) 19 | -------------------------------------------------------------------------------- /LeetCode/334. Increasing Triplet Subsequence/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def increasingTriplet(self, nums: List[int]) -> bool: 3 | # Time complexity: O(N) 4 | # Space complexity: O(1) 5 | 6 | if len(nums) < 3: 7 | return False 8 | 9 | first = 1000000000000 10 | second = 1000000000000 11 | 12 | for num in nums: 13 | if num < first: 14 | first = num 15 | elif num < second and num > first: 16 | second = num 17 | elif num > second: 18 | return True 19 | 20 | return False 21 | -------------------------------------------------------------------------------- /LeetCode/338. Counting Bits/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int[] numBits; 3 | public int countBitsDP(int n) { 4 | if (numBits[n] != -1) 5 | return numBits[n]; 6 | 7 | numBits[n] = n % 2 + countBitsDP(n / 2); 8 | return numBits[n]; 9 | } 10 | 11 | public int[] countBits(int num) { 12 | 13 | numBits = new int[num + 1]; 14 | Arrays.fill(numBits, - 1); 15 | numBits[0] = 0; 16 | 17 | int[] ret = new int[num + 1]; 18 | for (int i = 0; i <= num; i++) 19 | ret[i] = countBitsDP(i); 20 | 21 | return ret; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /LeetCode/342. Power of Four/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isPowerOfFour(int num) { 3 | if (num <= 0) 4 | return false; 5 | 6 | if (num == 1) 7 | return true; 8 | 9 | boolean isPower2 = (num & (num - 1)) == 0; 10 | int numBinDig = 0; 11 | while (num > 0) { 12 | numBinDig += 1; 13 | num = num >> 1; 14 | } 15 | 16 | return isPower2 && numBinDig % 2 == 1; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /LeetCode/344. Reverse String/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void reverseString(char[] s) { 3 | char tmp; 4 | for (int i = 0; i < s.length / 2; i++) { 5 | tmp = s[i]; 6 | s[i] = s[s.length - 1 - i]; 7 | s[s.length - 1 - i] = tmp; 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /LeetCode/349. Intersection of Two Arrays/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] intersection(int[] nums1, int[] nums2) { 3 | Set nums1Set = new HashSet(); 4 | Set nums2Set = new HashSet(); 5 | for (int i = 0; i < nums1.length; i++) 6 | nums1Set.add(nums1[i]); 7 | for (int i = 0; i < nums2.length; i++) 8 | nums2Set.add(nums2[i]); 9 | 10 | nums1Set.retainAll(nums2Set); 11 | 12 | int[] ret = new int[nums1Set.size()]; 13 | int i = 0; 14 | for (Integer num : nums1Set) { 15 | ret[i] = num; 16 | i += 1; 17 | } 18 | 19 | return ret; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /LeetCode/35. Search Insert Position/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int searchInsert(int[] nums, int target) { 3 | int low = 0; 4 | int high = nums.length; 5 | 6 | while (low < high) { 7 | int mid = (low + high) / 2; 8 | 9 | if (nums[mid] >= target) 10 | high = mid; 11 | else 12 | low = mid + 1; 13 | } 14 | 15 | return low; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /LeetCode/356. Line Reflection/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isReflected(self, points: List[List[int]]) -> bool: 3 | points_set = set() 4 | 5 | leftmost = 1000000000 6 | rightmost = -1000000000 7 | 8 | for point in points: 9 | leftmost = min(leftmost, point[0]) 10 | rightmost = max(rightmost, point[0]) 11 | points_set.add((point[0], point[1])) 12 | 13 | mid = (leftmost + rightmost) / 2 14 | for point in points: 15 | if (2 * mid - point[0], point[1]) not in points_set: 16 | return False 17 | 18 | return True 19 | 20 | -------------------------------------------------------------------------------- /LeetCode/367. Valid Perfect Square/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPerfectSquare(self, num: int) -> bool: 3 | # Time Complexity: O(log N) = O(W) 4 | # Space Complexity: O(1) 5 | 6 | low = 1 7 | high = num - 1 8 | 9 | while low < high: 10 | mid = low + (high - low) // 2 11 | 12 | if mid * mid == num: 13 | return True 14 | elif mid * mid < num: 15 | low = mid + 1 16 | else: 17 | high = mid - 1 18 | 19 | return low * low == num 20 | 21 | -------------------------------------------------------------------------------- /LeetCode/370. Range Addition/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getModifiedArray(self, length: int, updates: List[List[int]]) -> List[int]: 3 | # diff[i] = arr[i] - arr[i - 1] 4 | # (arr[-1] = 0) 5 | # increment a[i:j + 1] by increasing diff[i] and decreasing diff[j + 1] 6 | 7 | # Time and space complexity: O(N) 8 | 9 | diff = [0] * length 10 | for update in updates: 11 | diff[update[0]] += update[2] 12 | 13 | if update[1] + 1 < length: 14 | diff[update[1] + 1] -= update[2] 15 | 16 | ret = [] 17 | cumsum = 0 18 | 19 | for i in range(length): 20 | cumsum += diff[i] 21 | ret.append(cumsum) 22 | 23 | return ret 24 | -------------------------------------------------------------------------------- /LeetCode/374. Guess Number Higher or Lower/Solution.py: -------------------------------------------------------------------------------- 1 | # The guess API is already defined for you. 2 | # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 3 | # def guess(num: int) -> int: 4 | 5 | class Solution: 6 | def guessNumber(self, n: int) -> int: 7 | low = 1 8 | high = n 9 | 10 | while (low < high): 11 | mid = low + (high - low) // 2 12 | res = guess(mid) 13 | if res == 0: 14 | return mid 15 | elif res == -1: 16 | high = mid - 1 17 | else: 18 | low = mid + 1 19 | 20 | return low 21 | -------------------------------------------------------------------------------- /LeetCode/375. Guess Number Higher or Lower II/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getMoneyAmount(self, n: int) -> int: 3 | self.dp = [[-1] * n for i in range(n)] 4 | return self.minMoney(1, n) 5 | 6 | def minMoney(self, low: int, high: int): 7 | if low >= high: 8 | return 0 9 | 10 | if self.dp[low - 1][high - 1] != -1: 11 | return self.dp[low - 1][high - 1] 12 | 13 | ret = 1000000 14 | for k in range(low, high + 1): 15 | candidate = k + max(self.minMoney(k + 1, high), self.minMoney(low, k - 1)) 16 | ret = min(candidate, ret) 17 | 18 | self.dp[low - 1][high - 1] = ret 19 | return ret 20 | -------------------------------------------------------------------------------- /LeetCode/376. Wiggle Subsequence/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int wiggleMaxLength(int[] nums) { 3 | // Time complexity: O(n) 4 | // Space complexity: O(1) 5 | 6 | 7 | if (nums.length < 2) 8 | return nums.length; 9 | 10 | int prevDiff = nums[1] - nums[0]; 11 | int ret = prevDiff != 0 ? 2 : 1; 12 | for (int i = 1; i < nums.length - 1; i++) { 13 | int diff = nums[i + 1] - nums[i]; 14 | if ((diff > 0 && prevDiff <= 0) || (diff < 0 && prevDiff >= 0)) { 15 | ret += 1; 16 | prevDiff = diff; 17 | } 18 | } 19 | 20 | return ret; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /LeetCode/377. Combination Sum IV/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def combinationSum4(self, nums: List[int], target: int) -> int: 3 | # Time Complexity: O(target * N) 4 | # Space Complexity: O(target) 5 | 6 | self.dp = {} 7 | return self.build(nums, target) 8 | 9 | def build(self, nums: List[int], target: int) -> int: 10 | if target in self.dp: 11 | return self.dp[target] 12 | 13 | ret = 0 14 | 15 | if target: 16 | for num in nums: 17 | if num <= target: 18 | ret += self.build(nums, target - num) 19 | else: 20 | ret += 1 21 | 22 | self.dp[target] = ret 23 | return ret 24 | -------------------------------------------------------------------------------- /LeetCode/378. Kth Smallest Element in a Sorted Matrix/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kthSmallest(self, matrix: List[List[int]], k: int) -> int: 3 | # Time Complexity: O(num_row + K log(num_row)) 4 | # Space Complexity: O(num_row) 5 | 6 | heap = [(matrix[i][0], i) for i in range(len(matrix))] 7 | heapq.heapify(heap) 8 | cur_inds = [0 for i in range(len(matrix))] 9 | 10 | for _ in range(k - 1): 11 | val, row_ind = heapq.heappop(heap) 12 | 13 | if cur_inds[row_ind] + 1 < len(matrix[0]): 14 | cur_inds[row_ind] += 1 15 | heapq.heappush(heap, (matrix[row_ind][cur_inds[row_ind]], row_ind)) 16 | 17 | return heapq.heappop(heap)[0] 18 | -------------------------------------------------------------------------------- /LeetCode/38. Count and Say/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countAndSay(self, n: int) -> str: 3 | cur = "1" 4 | for i in range(n - 1): 5 | cur = self.nextCountAndSay(cur) 6 | 7 | return cur 8 | 9 | def nextCountAndSay(self, num: str) -> str: 10 | ret = [] 11 | 12 | start = 0 13 | while start < len(num): 14 | end = start 15 | 16 | while end < len(num) and num[start] == num[end]: 17 | end += 1 18 | 19 | ret.append(str(end - start)) 20 | ret.append(num[start]) 21 | start = end 22 | 23 | return "".join(ret) 24 | -------------------------------------------------------------------------------- /LeetCode/383. Ransom Note/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canConstruct(self, ransomNote: str, magazine: str) -> bool: 3 | note_cnt = self.generate_cnt(ransomNote) 4 | magazine_cnt = self.generate_cnt(magazine) 5 | 6 | for i in range(26): 7 | if note_cnt[i] > magazine_cnt[i]: 8 | return False 9 | 10 | return True 11 | 12 | def generate_cnt(self, text: str) -> List[int]: 13 | ret = [0] * 26 14 | for char in text: 15 | ret[ord(char) - ord('a')] += 1 16 | 17 | return ret 18 | 19 | -------------------------------------------------------------------------------- /LeetCode/386. Lexicographical Numbers/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector lexicalOrder(int n) { 4 | vector ret; 5 | for (int i = 1; i < 10; i++) { 6 | build(i, n, ret); 7 | } 8 | 9 | return ret; 10 | } 11 | 12 | private: 13 | void build(int cur, int bound, vector &ret) { 14 | if (cur <= bound) { 15 | ret.push_back(cur); 16 | cur *= 10; 17 | for (int i = 0; i < 10; i++) 18 | build(cur + i, bound, ret); 19 | } 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /LeetCode/386. Lexicographical Numbers/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List lexicalOrder(int n) { 3 | List ret = new ArrayList<>(n); 4 | for (int i = 1; i < 10; i++) 5 | build(i, n, ret); 6 | return ret; 7 | } 8 | 9 | private void build(int cur, int bound, List ret) { 10 | if (cur <= bound) { 11 | ret.add(cur); 12 | for (int i = 0; i < 10; i++) 13 | build(cur * 10 + i, bound, ret); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /LeetCode/389. Find the Difference/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findTheDifference(self, s: str, t: str) -> str: 3 | def compute_freq(s: str) -> List[int]: 4 | ret = [0] * 26 5 | 6 | for char in s: 7 | ret[ord(char) - ord('a')] += 1 8 | 9 | return ret 10 | 11 | freq_s, freq_t = compute_freq(s), compute_freq(t) 12 | 13 | for i in range(26): 14 | if freq_t[i] - freq_s[i] == 1: 15 | return chr(i + ord('a')) 16 | 17 | return -1 18 | -------------------------------------------------------------------------------- /LeetCode/392. Is Subsequence/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public boolean isSubsequence(String s, String t) { 4 | int i = 0; 5 | int j = 0; 6 | 7 | while (i < s.length() && j < t.length()) { 8 | if (s.charAt(i) == t.charAt(j)) 9 | i += 1; 10 | 11 | j += 1; 12 | } 13 | 14 | if (i == s.length()) 15 | return true; 16 | 17 | return false; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /LeetCode/397. Integer Replacement/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | _dp = {} 3 | 4 | def integerReplacement(self, n: int) -> int: 5 | # Time and Space Complexity: O(N) 6 | 7 | if n in self._dp: 8 | return self._dp[n] 9 | 10 | if n == 1: 11 | ret = 0 12 | elif n % 2 == 0: 13 | ret = 1 + self.integerReplacement(n // 2) 14 | else: 15 | ret = 1 + min(self.integerReplacement(n + 1), self.integerReplacement(n - 1)) 16 | 17 | self._dp[n] = ret 18 | return ret 19 | -------------------------------------------------------------------------------- /LeetCode/398. Random Pick Index/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | 3 | def __init__(self, nums: List[int]): 4 | # Time and Space Complexity: O(N) 5 | self.index = {} 6 | 7 | for i, val in enumerate(nums): 8 | if val not in self.index: 9 | self.index[val] = [] 10 | 11 | self.index[val].append(i) 12 | 13 | 14 | def pick(self, target: int) -> int: 15 | # Time and Space Complexity: O(1) 16 | occs = self.index[target] 17 | return occs[random.randrange(len(occs))] 18 | 19 | 20 | 21 | # Your Solution object will be instantiated and called as such: 22 | # obj = Solution(nums) 23 | # param_1 = obj.pick(target) 24 | -------------------------------------------------------------------------------- /LeetCode/409. Longest Palindrome/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestPalindrome(self, s: str) -> int: 3 | # Time and Space Complexity: O(N) 4 | 5 | counter = collections.Counter() 6 | 7 | for char in s: 8 | counter[char] += 1 9 | 10 | ret = 0 11 | for char in counter: 12 | if counter[char] % 2 == 0: 13 | ret += counter[char] 14 | else: 15 | ret += counter[char] - 1 16 | 17 | if ret < len(s): 18 | ret += 1 19 | 20 | return ret 21 | -------------------------------------------------------------------------------- /LeetCode/412. Fizz Buzz/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fizzBuzz(self, n: int) -> List[str]: 3 | ret = [] 4 | for i in range(1, n + 1): 5 | if i % 15 == 0: 6 | ret.append("FizzBuzz") 7 | elif i % 5 == 0: 8 | ret.append("Buzz") 9 | elif i % 3 == 0: 10 | ret.append("Fizz") 11 | else: 12 | ret.append(str(i)) 13 | 14 | return ret 15 | -------------------------------------------------------------------------------- /LeetCode/414. Third Maximum Number/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def thirdMax(self, nums: List[int]) -> int: 3 | # Time Compleixty: O(N) 4 | # Space Complexity: O(1) 5 | 6 | top_3 = [None] * 3 7 | 8 | for num in nums: 9 | if top_3[0] is None or num > top_3[0]: 10 | top_3 = [num] + top_3[:2] 11 | elif top_3[0] is not None and top_3[0] > num and (top_3[1] is None or num > top_3[1]): 12 | top_3 = [top_3[0], num] + [top_3[1]] 13 | elif top_3[1] is not None and top_3[1] > num and (top_3[2] is None or num > top_3[2]): 14 | top_3 = top_3[:2] + [num] 15 | 16 | return top_3[-1] if top_3[-1] is not None else top_3[0] 17 | -------------------------------------------------------------------------------- /LeetCode/419. Battleships in a Board/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countBattleships(self, board: List[List[str]]) -> int: 3 | ret = 0 4 | 5 | for i in range(len(board)): 6 | for j in range(len(board[0])): 7 | if self.is_head(board, i, j): 8 | ret += 1 9 | 10 | return ret 11 | 12 | def is_head(self, board: List[List[str]], i: int, j: int) -> bool: 13 | if board[i][j] == ".": 14 | return False 15 | 16 | if i > 0 and board[i - 1][j] == "X": 17 | return False 18 | 19 | if j > 0 and board[i][j - 1] == "X": 20 | return False 21 | 22 | return True 23 | -------------------------------------------------------------------------------- /LeetCode/434. Number of Segments in a String/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countSegments(self, s: str) -> int: 3 | # Time Complexity: O(N) 4 | # Space Complexity: O(1) 5 | 6 | start, end, ret = 0, 0, 0 7 | 8 | while start < len(s): 9 | if s[start] == " ": 10 | start += 1 11 | end = start 12 | elif end + 1 < len(s) and s[end + 1] != " ": 13 | end += 1 14 | else: 15 | ret += 1 16 | start = end + 1 17 | end = start 18 | 19 | return ret 20 | -------------------------------------------------------------------------------- /LeetCode/435. Non-overlapping Intervals/sol.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: 3 | if (len(intervals) <= 1): return 0 4 | 5 | intervals.sort(key=lambda interval: interval[1]) 6 | curTime = intervals[0][1] 7 | ind = 1 8 | ret = 0 9 | 10 | while ind < len(intervals): 11 | if intervals[ind][0] < curTime: 12 | ret += 1 13 | else: 14 | curTime = intervals[ind][1] 15 | ind += 1 16 | 17 | return ret 18 | -------------------------------------------------------------------------------- /LeetCode/441. Arranging Coins/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def arrangeCoins(self, n: int) -> int: 3 | low = 0 4 | high = n 5 | 6 | while low < high: 7 | mid = high - (high - low) // 2 8 | cand = mid * (mid + 1) // 2 9 | 10 | if cand == n: 11 | return mid 12 | elif cand < n: 13 | low = mid 14 | else: 15 | high = mid - 1 16 | 17 | return low 18 | 19 | 20 | -------------------------------------------------------------------------------- /LeetCode/442. Find All Duplicates in an Array/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDuplicates(self, nums: List[int]) -> List[int]: 3 | # Idea: use nums[abs(num) - 1] as the flag for num 4 | 5 | for num in nums: 6 | nums[abs(num) - 1] = -nums[abs(num) - 1] 7 | 8 | ret = [] 9 | for num in nums: 10 | if nums[abs(num) - 1] > 0: 11 | ret.append(abs(num)) 12 | nums[abs(num) - 1] = -nums[abs(num) - 1] 13 | 14 | return ret 15 | -------------------------------------------------------------------------------- /LeetCode/447. Number of Boomerangs/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numberOfBoomerangs(self, points: List[List[int]]) -> int: 3 | # Time Complexity: O(N^2) 4 | # Space Complexity: O(N) 5 | 6 | dist_cnt = [Counter() for i in range(len(points))] 7 | 8 | ret = 0 9 | for i in range(len(points)): 10 | for j in range(i + 1, len(points)): 11 | fst, snd = points[i], points[j] 12 | 13 | dist_sq = (fst[0] - snd[0]) ** 2 + (fst[1] - snd[1]) ** 2 14 | ret += dist_cnt[i][dist_sq] + dist_cnt[j][dist_sq] 15 | 16 | dist_cnt[i][dist_sq] += 1 17 | dist_cnt[j][dist_sq] += 1 18 | 19 | return ret * 2 20 | -------------------------------------------------------------------------------- /LeetCode/448. Find All Numbers Disappeared in an Array/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDisappearedNumbers(self, nums: List[int]) -> List[int]: 3 | # Time Complexity: O(N) 4 | # Space Complexity: no extra space 5 | 6 | for num in nums: 7 | nums[abs(num) - 1] = -abs(nums[abs(num) - 1]) 8 | 9 | ret = [] 10 | for i in range(1, len(nums) + 1): 11 | if nums[i - 1] > 0: 12 | ret.append(i) 13 | 14 | return ret 15 | 16 | -------------------------------------------------------------------------------- /LeetCode/453. Minimum Moves to Equal Array Elements/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minMoves(self, nums: List[int]) -> int: 3 | # Time Complexity: O(N) 4 | # Space Complexity: O(1) 5 | 6 | min_val = min(nums) 7 | return sum(map(lambda val: val - min_val, nums)) 8 | -------------------------------------------------------------------------------- /LeetCode/459. Repeated Substring Pattern/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def repeatedSubstringPattern(self, s: str) -> bool: 3 | # Time and Space Complexity: O(N) 4 | 5 | lps = [0] 6 | 7 | for i in range(1, len(s)): 8 | end = lps[-1] 9 | 10 | while s[end] != s[i] and end > 0: 11 | end = lps[end - 1] 12 | 13 | if s[end] == s[i]: 14 | lps.append(end + 1) 15 | else: 16 | lps.append(0) 17 | 18 | return lps[-1] and not (len(s) % (len(s) - lps[-1])) 19 | -------------------------------------------------------------------------------- /LeetCode/461. Hamming Distance/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int hammingDistance(int x, int y) { 3 | return Integer.bitCount(x ^ y); 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /LeetCode/476. Number Complement/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findComplement(self, num: int) -> int: 3 | if num == 0: 4 | return 1 5 | 6 | ret = 0 7 | i = 0 8 | 9 | while num > 0: 10 | ret += ((num & 1) ^ 1) << i 11 | i += 1 12 | num >>= 1 13 | 14 | return ret 15 | -------------------------------------------------------------------------------- /LeetCode/477. Total Hamming Distance/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def totalHammingDistance(self, nums: List[int]) -> int: 3 | # Time Complexity: O(NW) = O(N log MAX) 4 | # Space Complexity: O(N) 5 | 6 | one_cnter = [] 7 | 8 | for num in nums: 9 | i = 0 10 | while num > 0: 11 | if num % 2 == 1: 12 | if i == len(one_cnter): 13 | one_cnter.append(1) 14 | else: 15 | one_cnter[i] += 1 16 | elif i == len(one_cnter): 17 | one_cnter.append(0) 18 | 19 | 20 | i += 1 21 | num //= 2 22 | 23 | return sum(map(lambda cnt: cnt * (len(nums) - cnt), one_cnter)) 24 | -------------------------------------------------------------------------------- /LeetCode/482. License Key Formatting/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def licenseKeyFormatting(self, S: str, K: int) -> str: 3 | components = S.split("-") 4 | characters = [] 5 | for comp in components: 6 | for char in comp: 7 | characters.append(char.upper()) 8 | ret = [] 9 | for i in range(len(characters)): 10 | ret.append(characters[i]) 11 | if i < len(characters) - 1 and (len(characters) - i - 1) % K == 0: 12 | ret.append("-") 13 | return "".join(ret) 14 | -------------------------------------------------------------------------------- /LeetCode/484. Find Permutation/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findPermutation(self, s: str) -> List[int]: 3 | ret = [1] 4 | self.build(s, 0, ret) 5 | return ret 6 | 7 | def build(self, s, pos, ret): 8 | # increase the peak: 9 | 10 | cnt = 0 11 | while pos < len(s) and s[pos] == "D": 12 | ret[-1] += 1 13 | pos += 1 14 | cnt += 1 15 | 16 | peak = ret[-1] 17 | 18 | for i in range(1, cnt + 1): 19 | ret.append(peak - i) 20 | 21 | if pos < len(s): 22 | ret.append(peak + 1) 23 | self.build(s, pos + 1, ret) 24 | 25 | -------------------------------------------------------------------------------- /LeetCode/485. Max Consecutive Ones/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMaxConsecutiveOnes(vector& nums) { 4 | // Time Complexity: O(N) 5 | // Space Complexity: O(1) 6 | 7 | int cnt = 0, ret = 0; 8 | 9 | for (int val : nums) { 10 | if (val == 1) 11 | cnt += 1; 12 | else { 13 | ret = max(ret, cnt); 14 | cnt = 0; 15 | } 16 | } 17 | 18 | return max(ret, cnt); 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /LeetCode/494. Target Sum/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findTargetSumWays(self, nums: List[int], S: int) -> int: 3 | # Time and space complexity: O((S + sum_i nums[i]) * n) 4 | 5 | self.dp = {} 6 | return self.find(nums, 0, S) 7 | 8 | def find(self, nums, i, target): 9 | if i == len(nums): 10 | return 1 if target == 0 else 0 11 | 12 | if (i, target) in self.dp: 13 | return self.dp[(i, target)] 14 | 15 | ret = self.find(nums, i + 1, target - nums[i]) + self.find(nums, i + 1, target + nums[i]) 16 | self.dp[(i, target)] = ret 17 | return ret 18 | -------------------------------------------------------------------------------- /LeetCode/520. Detect Capital/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def detectCapitalUse(self, word: str) -> bool: 3 | return self.is_lower(word) or self.is_upper(word) or (self.is_upper(word[0]) and self.is_lower(word[1:])) 4 | 5 | def is_lower(self, word: str): 6 | return word.lower() == word 7 | 8 | def is_upper(self, word: str): 9 | return word.upper() == word 10 | 11 | -------------------------------------------------------------------------------- /LeetCode/526. Beautiful Arrangement/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countArrangement(self, N: int) -> int: 3 | return self.count_solutions(set(i for i in range(1, N + 1))) 4 | 5 | def count_solutions(self, remaining: set) -> int: 6 | if remaining: 7 | choices = list(remaining) 8 | index = len(remaining) 9 | 10 | ret = 0 11 | 12 | for choice in choices: 13 | if not (index % choice) or not (choice % index): 14 | remaining.remove(choice) 15 | ret += self.count_solutions(remaining) 16 | remaining.add(choice) 17 | 18 | return ret 19 | else: 20 | return 1 21 | -------------------------------------------------------------------------------- /LeetCode/53. Maximum Subarray/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxSubArray(int[] nums) { 3 | // Kadane's algorithm: https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/ 4 | 5 | if (nums.length == 0) 6 | return 0; 7 | if (nums.length == 1) 8 | return nums[0]; 9 | 10 | int curMax = -100000; 11 | int maxEndingHere = -100000; 12 | for (int i = 0; i < nums.length; i++) { 13 | maxEndingHere += nums[i]; 14 | if (maxEndingHere < nums[i]) 15 | maxEndingHere = nums[i]; 16 | if (curMax < maxEndingHere) 17 | curMax = maxEndingHere; 18 | } 19 | return curMax; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /LeetCode/530. Minimum Absolute Difference in BST/Solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def getMinimumDifference(self, root: TreeNode) -> int: 9 | vals = [] 10 | self.inorder(root, vals) 11 | 12 | ret = 1000000000 13 | for i in range(len(vals) - 1): 14 | ret = min(ret, vals[i + 1] - vals[i]) 15 | 16 | return ret 17 | 18 | def inorder(self, node: TreeNode, ret: List[int]): 19 | if node: 20 | self.inorder(node.left, ret) 21 | ret.append(node.val) 22 | self.inorder(node.right, ret) 23 | -------------------------------------------------------------------------------- /LeetCode/532. K-diff Pairs in an Array/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findPairs(self, nums: List[int], k: int) -> int: 3 | # Time and Space Complexity: O(N) 4 | 5 | if k < 0: 6 | return 0 7 | 8 | if not k: 9 | counter = collections.Counter(nums) 10 | return len(set(filter(lambda x: counter[x] > 1, nums))) 11 | 12 | nums = set(nums) 13 | 14 | ret = 0 15 | for num in nums: 16 | if num + k in nums: 17 | ret += 1 18 | 19 | return ret 20 | -------------------------------------------------------------------------------- /LeetCode/55. Jump Game/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canJump(self, nums: List[int]) -> bool: 3 | start = 0 4 | end = 0 5 | 6 | while end < len(nums) - 1: 7 | newEnd = end 8 | for i in range(start, end + 1): 9 | newEnd = max(newEnd, i + nums[i]) 10 | 11 | if newEnd == end: 12 | return False 13 | 14 | start = end + 1 15 | end = newEnd 16 | 17 | return True 18 | 19 | -------------------------------------------------------------------------------- /LeetCode/551. Student Attendance Record I/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkRecord(string s) { 4 | // Time Complexity: O(N) 5 | // Space Complexity: O(1) 6 | 7 | int consec_late = 0; 8 | int abs_cnt = 0; 9 | 10 | for (auto c : s) { 11 | if (c == 'L') 12 | consec_late += 1; 13 | else 14 | consec_late = 0; 15 | 16 | if (c == 'A') 17 | abs_cnt += 1; 18 | 19 | if (consec_late == 3) 20 | return false; 21 | } 22 | 23 | 24 | return abs_cnt < 2; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /LeetCode/554. Brick Wall/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def leastBricks(self, wall: List[List[int]]) -> int: 3 | # Time and Space Complexity: O(num_bricks) 4 | 5 | prefixes = list(map(list, map(itertools.accumulate, wall))) 6 | 7 | counter = Counter() 8 | for row in prefixes: 9 | for prefix_sum in row[:len(row) - 1]: 10 | counter[prefix_sum] += 1 11 | 12 | 13 | if counter: 14 | return len(wall) - max([counter[prefix_sum] for prefix_sum in counter]) 15 | 16 | return len(wall) 17 | -------------------------------------------------------------------------------- /LeetCode/557. Reverse Words in a String III/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseWords(self, s: str) -> str: 3 | return " ".join(map(self.reverse, s.split(" "))) 4 | 5 | def reverse(self, s: str) -> str: 6 | return s[::-1] 7 | -------------------------------------------------------------------------------- /LeetCode/560. Subarray Sum Equals K/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int subarraySum(int[] nums, int k) { 3 | Map prefixIndex = new HashMap(); 4 | int cumSum = 0; 5 | prefixIndex.put(0, 1); 6 | int ret = 0; 7 | 8 | for (int i = 1; i < nums.length + 1; i++) { 9 | cumSum += nums[i - 1]; 10 | if (prefixIndex.containsKey(cumSum - k)) 11 | ret += prefixIndex.get(cumSum - k); 12 | if (!prefixIndex.containsKey(cumSum)) 13 | prefixIndex.put(cumSum, 0); 14 | prefixIndex.put(cumSum, prefixIndex.get(cumSum) + 1); 15 | 16 | } 17 | 18 | return ret; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /LeetCode/561. Array Partition I/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def arrayPairSum(self, nums: List[int]) -> int: 3 | # Time and Space Complexity: O(N + range(nums)) 4 | 5 | low, high = min(nums), max(nums) 6 | buckets = [0] * (high - low + 1) 7 | sorted_nums = [0] * len(nums) 8 | 9 | for num in nums: 10 | buckets[num - low] += 1 11 | 12 | for i in range(1, len(buckets)): 13 | buckets[i] += buckets[i - 1] 14 | 15 | for i in range(len(nums) - 1, -1, -1): 16 | sorted_nums[buckets[nums[i] - low] - 1] = nums[i] 17 | buckets[nums[i] - low] -= 1 18 | 19 | return sum(sorted_nums[i] for i in range(len(nums)) if i % 2 == 0) 20 | 21 | -------------------------------------------------------------------------------- /LeetCode/563. Binary Tree Tilt/Solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def findTilt(self, root: TreeNode) -> int: 9 | return self.dfs(root)[0] 10 | 11 | def dfs(self, node: TreeNode): 12 | if not node: 13 | return 0, 0 14 | 15 | left_tilt, left_sum = self.dfs(node.left) 16 | right_tilt, right_sum = self.dfs(node.right) 17 | 18 | return (left_tilt + right_tilt + abs(left_sum - right_sum), left_sum + right_sum + node.val) 19 | -------------------------------------------------------------------------------- /LeetCode/566. Reshape the Matrix/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]: 3 | # Time Complexity: O(MN) 4 | # Space Complexity: O(MN); O(1) extra space 5 | if not (r * c == len(mat) * len(mat[0])): 6 | return mat 7 | 8 | 9 | ret = [[0 for j in range(c)] for i in range(r)] 10 | 11 | for ind in range(len(mat) * len(mat[0])): 12 | old_r = ind // len(mat[0]) 13 | old_c = ind - old_r * len(mat[0]) 14 | 15 | new_r = ind // c 16 | new_c = ind - new_r * c 17 | 18 | ret[new_r][new_c] = mat[old_r][old_c] 19 | 20 | return ret 21 | -------------------------------------------------------------------------------- /LeetCode/575. Distribute Candies/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def distributeCandies(self, candyType: List[int]) -> int: 3 | # Time and Space Complexity: O(N) 4 | return min(len(candyType) // 2, len(set(candyType))) 5 | -------------------------------------------------------------------------------- /LeetCode/58. Length of Last Word/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLastWord(self, s: str) -> int: 3 | return len(s.strip().split(" ")[-1]) 4 | -------------------------------------------------------------------------------- /LeetCode/582. Kill Process/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def killProcess(self, pid: List[int], ppid: List[int], kill: int) -> List[int]: 3 | # Time and Space Complexity: O(N) 4 | 5 | self.children = {id: set() for id in pid} 6 | 7 | for id, par in zip(pid, ppid): 8 | if par: 9 | self.children[par].add(id) 10 | 11 | ret = [] 12 | visited = set() 13 | 14 | self.dfs(kill, ret, visited) 15 | return ret 16 | 17 | def dfs(self, node: int, ret: int, visited: set): 18 | ret.append(node) 19 | 20 | for child in self.children[node]: 21 | if child not in visited: 22 | visited.add(child) 23 | self.dfs(child, ret, visited) 24 | -------------------------------------------------------------------------------- /LeetCode/589. N-ary Tree Preorder Traversal/Solution.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Definition for a Node. 3 | class Node: 4 | def __init__(self, val=None, children=None): 5 | self.val = val 6 | self.children = children 7 | """ 8 | 9 | class Solution: 10 | def preorder(self, root: 'Node') -> List[int]: 11 | if not root: 12 | return [] 13 | 14 | ret = [] 15 | self.dfs(root, ret) 16 | 17 | return ret 18 | 19 | def dfs(self, node: 'Node', ret: List[int]): 20 | ret.append(node.val) 21 | 22 | for child in node.children: 23 | self.dfs(child, ret) 24 | -------------------------------------------------------------------------------- /LeetCode/594. Longest Harmonious Subsequence/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findLHS(self, nums: List[int]) -> int: 3 | # Time and Space Complexity: O(N) 4 | 5 | cnter = Counter(nums) 6 | 7 | ret = 0 8 | for val in cnter: 9 | if cnter[val + 1]: 10 | ret = max(cnter[val] + cnter[val + 1], ret) 11 | 12 | return ret 13 | -------------------------------------------------------------------------------- /LeetCode/611. Valid Triangle Number/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def triangleNumber(self, nums: List[int]) -> int: 3 | # Time Complexity: O(N^2) 4 | # Space Complexity: O(1) 5 | 6 | nums.sort() 7 | 8 | ret = 0 9 | for i in range(2, len(nums)): 10 | j = 0 11 | k = i - 1 12 | 13 | while j < k: 14 | if nums[j] + nums[k] > nums[i]: 15 | ret += (k - 1 - j + 1) 16 | k -= 1 17 | else: 18 | j += 1 19 | 20 | return ret 21 | -------------------------------------------------------------------------------- /LeetCode/617. Merge Two Binary Trees/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | class Solution { 11 | public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { 12 | if (t1 == null) 13 | return t2; 14 | else if (t2 == null) 15 | return t1; 16 | 17 | t1.left = mergeTrees(t1.left, t2.left); 18 | t1.right = mergeTrees(t1.right, t2.right); 19 | t1.val += t2.val; 20 | 21 | return t1; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /LeetCode/62. Unique Paths/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int[][] paths = new int[101][101]; 3 | public int uniquePaths(int m, int n) { 4 | if (m == 1) { 5 | paths[1][n] = 1; 6 | return 1; 7 | } 8 | 9 | if (n == 1) { 10 | paths[m][1] = 1; 11 | return 1; 12 | } 13 | 14 | if (paths[m][n] != 0) 15 | return paths[m][n]; 16 | 17 | paths[m][n] = uniquePaths(m - 1, n) + uniquePaths(m, n - 1); 18 | return paths[m][n]; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /LeetCode/628. Maximum Product of Three Numbers/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximumProduct(self, nums: List[int]) -> int: 3 | # Time Complexity: O(N) 4 | # Space Complexity: O(1) 5 | 6 | max_3 = [None] * 3 7 | min_2 = [None] * 2 8 | 9 | for num in nums: 10 | for i in range(3): 11 | if max_3[i] is None or max_3[i] < num: 12 | max_3 = max_3[:i] + [num] + max_3[i:2] 13 | break 14 | 15 | for i in range(2): 16 | if min_2[i] is None or min_2[i] > num: 17 | min_2 = min_2[:i] + [num] + min_2[i:1] 18 | break 19 | 20 | return max(min_2[0] * min_2[1] * max_3[0], max_3[0] * max_3[1] * max_3[2]) 21 | -------------------------------------------------------------------------------- /LeetCode/630. Course Schedule III/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def scheduleCourse(self, courses: List[List[int]]) -> int: 3 | courses.sort(key=lambda course: course[1]) 4 | ret = 0 5 | curTotalTime = 0 6 | durations = [] 7 | 8 | for course in courses: 9 | if course[0] + curTotalTime <= course[1]: 10 | ret += 1 11 | curTotalTime += course[0] 12 | heapq.heappush(durations, -course[0]) 13 | elif len(durations) > 0 and -durations[0] >= course[0]: 14 | curTotalTime += course[0] + durations[0] 15 | heapq.heappop(durations) 16 | heapq.heappush(durations, -course[0]) 17 | return ret 18 | 19 | -------------------------------------------------------------------------------- /LeetCode/633. Sum of Square Numbers/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def judgeSquareSum(self, c: int) -> bool: 3 | # Time Complexity: O(sqrt(c) log c) 4 | # Space Complexity: O(1) 5 | 6 | if c <= 1: 7 | return True 8 | 9 | if c % 4 == 3: 10 | return False 11 | 12 | if c % 4 == 0: 13 | return self.judgeSquareSum(c // 4) 14 | 15 | def is_square(x): 16 | sqrted = int(math.sqrt(x)) 17 | return sqrted ** 2 == x 18 | 19 | for i in range(1, math.floor(math.sqrt(c)) + 1, 2): 20 | if is_square(c - i ** 2): 21 | return True 22 | 23 | return False 24 | -------------------------------------------------------------------------------- /LeetCode/643. Maximum Average Subarray I/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public double findMaxAverage(int[] nums, int k) { 3 | double sum = 0; 4 | for (int i = 0; i < k; i++) 5 | sum += nums[i]; 6 | 7 | int ind = k; 8 | double candidate = sum; 9 | while (ind < nums.length) { 10 | candidate += nums[ind] - nums[ind - k]; 11 | if (candidate > sum) 12 | sum = candidate; 13 | ind += 1; 14 | } 15 | 16 | return sum / k; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /LeetCode/65. Valid Number/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | INTEGER_PATTERN = r"[-+]?\d+" 3 | DECIMAL_PATTERN = r"[-+]?(\d+\.\d*|\.\d+)" 4 | VALID_PATTERN = f"^({INTEGER_PATTERN}|{DECIMAL_PATTERN})([eE]{INTEGER_PATTERN})?$" 5 | MATCHER = re.compile(VALID_PATTERN) 6 | 7 | def isNumber(self, s: str) -> bool: 8 | # Time Complexity: O(|s|) 9 | # Space Complexity: O(1) 10 | return self.MATCHER.match(s) is not None 11 | -------------------------------------------------------------------------------- /LeetCode/657. Robot Return to Origin/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean judgeCircle(String moves) { 3 | int x = 0; 4 | int y = 0; 5 | 6 | for (int i = 0; i < moves.length(); i++) { 7 | if (moves.charAt(i) == 'U') 8 | y += 1; 9 | else if (moves.charAt(i) == 'D') 10 | y -= 1; 11 | else if (moves.charAt(i) == 'L') 12 | x -= 1; 13 | else 14 | x += 1; 15 | } 16 | 17 | return x == 0 && y == 0; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /LeetCode/667. Beautiful Arrangement II/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def constructArray(self, n: int, k: int) -> List[int]: 3 | # Time and Space Complexity: O(N) 4 | ret = [1] 5 | used = set([1]) 6 | 7 | for i in range(k): 8 | diff = k - i 9 | 10 | if i % 2 == 0: 11 | ret.append(ret[-1] + diff) 12 | else: 13 | ret.append(ret[-1] - diff) 14 | used.add(ret[-1]) 15 | 16 | 17 | for i in range(1, n + 1): 18 | if i not in used: 19 | ret.append(i) 20 | 21 | 22 | return ret 23 | -------------------------------------------------------------------------------- /LeetCode/669. Trim a Binary Search Tree/Solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode: 9 | if not root: 10 | return root 11 | elif root.val < low: 12 | return self.trimBST(root.right, low, high) 13 | elif root.val > high: 14 | return self.trimBST(root.left, low, high) 15 | else: 16 | root.left = self.trimBST(root.left, low, high) 17 | root.right = self.trimBST(root.right, low, high) 18 | 19 | return root 20 | -------------------------------------------------------------------------------- /LeetCode/674. Longest Continuous Increasing Subsequence/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findLengthOfLCIS(self, nums: List[int]) -> int: 3 | if not nums: 4 | return 0 5 | 6 | ret = 1 7 | 8 | start = 0 9 | end = 0 10 | 11 | while start < len(nums): 12 | if end + 1 < len(nums) and nums[end + 1] > nums[end]: 13 | end += 1 14 | else: 15 | ret = max(ret, end - start + 1) 16 | start = end + 1 17 | end += 1 18 | 19 | return ret 20 | -------------------------------------------------------------------------------- /LeetCode/678. Valid Parenthesis String/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkValidString(self, s: str) -> bool: 3 | # Keep track of the range of the number of available openings 4 | 5 | low, high = 0, 0 6 | 7 | for char in s: 8 | if char == "(": 9 | low += 1 10 | high += 1 11 | 12 | elif char == "*": 13 | high += 1 14 | low -= 1 15 | else: 16 | low -= 1 17 | high -= 1 18 | 19 | if high < 0: 20 | return False 21 | 22 | low = max(low, 0) 23 | 24 | return low == 0 25 | -------------------------------------------------------------------------------- /LeetCode/682. Baseball Game/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def calPoints(self, operations: List[str]) -> int: 3 | # Time and Space Complexity: O(N) 4 | record = [] 5 | 6 | for token in operations: 7 | if token not in "+DC": 8 | record.append(int(token)) 9 | elif token == "C": 10 | record.pop() 11 | elif token == "D": 12 | record.append(record[-1] * 2) 13 | elif token == "+": 14 | record.append(record[-1] + record[-2]) 15 | 16 | return sum(record) 17 | -------------------------------------------------------------------------------- /LeetCode/69. Sqrt(x)/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int mySqrt(int x) { 3 | if (x == 0) 4 | return 0; 5 | 6 | double ret = 1; 7 | for (int i = 0; i < 20; i++) 8 | ret = (ret + x / ret) / 2; 9 | return (int) ret; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /LeetCode/693. Binary Number with Alternating Bits/Solution.c: -------------------------------------------------------------------------------- 1 | bool hasAlternatingBits(int n){ 2 | // Time Complexity: O(log n) 3 | // Space Complexity: O(1) 4 | 5 | int parity = n % 2; 6 | n /= 2; 7 | 8 | while (n > 0) { 9 | if (n % 2 == parity) 10 | return false; 11 | 12 | parity = n % 2; 13 | n /= 2; 14 | } 15 | 16 | return true; 17 | } 18 | -------------------------------------------------------------------------------- /LeetCode/696. Count Binary Substrings/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countBinarySubstrings(self, s: str) -> int: 3 | # Time Complexity: O(N) 4 | # Space Complexity: O(1) 5 | 6 | ret = 0 7 | start = 0 8 | end = 0 9 | 10 | previous = None 11 | 12 | while start < len(s): 13 | if end + 1 < len(s) and s[end + 1] == s[start]: 14 | end += 1 15 | else: 16 | if previous is not None: 17 | ret += min(previous, end - start + 1) 18 | 19 | previous = end - start + 1 20 | end += 1 21 | start = end 22 | 23 | return ret 24 | -------------------------------------------------------------------------------- /LeetCode/701. Insert into a Binary Search Tree/Solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode: 9 | if not root: 10 | return TreeNode(val) 11 | 12 | if root.val < val: 13 | root.right = self.insertIntoBST(root.right, val) 14 | elif root.val > val: 15 | root.left = self.insertIntoBST(root.left, val) 16 | 17 | return root 18 | -------------------------------------------------------------------------------- /LeetCode/704. Binary Search/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def search(self, nums: List[int], target: int) -> int: 3 | low = 0 4 | high = len(nums) - 1 5 | 6 | while low < high: 7 | mid = low + (high - low) // 2 8 | 9 | if nums[mid] == target: 10 | return mid 11 | elif nums[mid] < target: 12 | low = mid + 1 13 | else: 14 | high = mid - 1 15 | 16 | if nums[low] == target: 17 | return low 18 | 19 | return -1 20 | -------------------------------------------------------------------------------- /LeetCode/709. To Lower Case/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String toLowerCase(String str) { 3 | StringBuilder ret = new StringBuilder(); 4 | for (int i = 0; i < str.length(); i++) { 5 | if (str.charAt(i) <= 'Z' && str.charAt(i) >= 'A') 6 | ret.append((char) (str.charAt(i) - 'A' + 'a')); 7 | else 8 | ret.append(str.charAt(i)); 9 | } 10 | 11 | return ret.toString(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /LeetCode/71. Simplify Path/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def simplifyPath(self, path: str) -> str: 3 | stack = [] 4 | components = path.split("/") 5 | 6 | for component in components: 7 | if len(component) > 0: 8 | if component == "..": 9 | if len(stack) > 0: 10 | stack.pop() 11 | elif component != '.': 12 | stack.append(component) 13 | 14 | return "/" + "/".join(stack) 15 | -------------------------------------------------------------------------------- /LeetCode/717. 1-bit and 2-bit Characters/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isOneBitCharacter(self, bits: List[int]) -> bool: 3 | cur = 0 4 | 5 | while cur < len(bits): 6 | if bits[cur] == 1: 7 | if cur == len(bits) - 2: 8 | return False 9 | else: 10 | cur += 2 11 | else: 12 | if cur == len(bits) - 1: 13 | return True 14 | else: 15 | cur += 1 16 | -------------------------------------------------------------------------------- /LeetCode/724. Find Pivot Index/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def pivotIndex(self, nums: List[int]) -> int: 3 | # Time Complexity: O(N) 4 | # Space Complexity: O(1) 5 | 6 | cumsum = 0 7 | total_sum = sum(nums) 8 | 9 | for i, num in enumerate(nums): 10 | if cumsum == total_sum - num - cumsum: 11 | return i 12 | cumsum += num 13 | 14 | return -1 15 | -------------------------------------------------------------------------------- /LeetCode/728. Self Dividing Numbers/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def selfDividingNumbers(self, left: int, right: int) -> List[int]: 3 | ret = [] 4 | 5 | for num in range(left, right + 1): 6 | tmp = num 7 | 8 | while tmp > 0: 9 | dig = tmp % 10 10 | 11 | if dig == 0 or num % dig: 12 | break 13 | 14 | tmp //= 10 15 | else: 16 | ret.append(num) 17 | 18 | return ret 19 | -------------------------------------------------------------------------------- /LeetCode/740. Delete and Earn/Solution.py: -------------------------------------------------------------------------------- 1 | def find_max_point(cur_val, cnter, solutions): 2 | if cur_val <= 1: 3 | return cnter[cur_val] 4 | 5 | if solutions[cur_val - 1] is not None: 6 | return solutions[cur_val - 1] 7 | 8 | solutions[cur_val - 1] = max( 9 | find_max_point(cur_val - 1, cnter, solutions), 10 | find_max_point(cur_val - 2, cnter, solutions) + cnter[cur_val] * cur_val, 11 | ) 12 | 13 | return solutions[cur_val - 1] 14 | 15 | 16 | 17 | class Solution: 18 | def deleteAndEarn(self, nums: List[int]) -> int: 19 | # Time and Space Complexity: O(N + max_val) 20 | cnter = Counter(nums) 21 | max_val = max(nums) 22 | 23 | return find_max_point(max_val, cnter, [None] * max_val) 24 | -------------------------------------------------------------------------------- /LeetCode/744. Find Smallest Letter Greater Than Target/Solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | char nextGreatestLetter(vector& letters, char target) { 4 | // Time Complexity: O(log N) 5 | // Space Complexity: O(1) 6 | 7 | auto it = std::upper_bound(letters.begin(), letters.end(), target); 8 | return it == letters.end() ? letters[0] : *it; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /LeetCode/746. Min Cost Climbing Stairs/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minCostClimbingStairs(int[] cost) { 3 | for (int j = cost.length - 3; j >= 0; j--) { 4 | cost[j] += Math.min(cost[j + 1], cost[j + 2]); 5 | } 6 | 7 | return Math.min(cost[0], cost[1]); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /LeetCode/750. Number Of Corner Rectangles/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countCornerRectangles(self, grid: List[List[int]]) -> int: 3 | # Time Complexity: O(R * C^2) 4 | # Space Complexity: O(C^2) 5 | 6 | counter = Counter() # count[(i, j)] = # rows with row[i] = row[j] = 1 7 | 8 | for row in grid: 9 | for i, val in enumerate(row): 10 | if val: 11 | for j in range(i + 1, len(row)): 12 | if row[j]: 13 | counter[(i, j)] += 1 14 | 15 | return sum([counter[key] * (counter[key] - 1) // 2 for key in counter]) 16 | -------------------------------------------------------------------------------- /LeetCode/754. Reach a Number/Solution2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reachNumber(self, target: int) -> int: 3 | # Time and Space Complexity: O(1) 4 | 5 | if not target: 6 | return 0 7 | 8 | if target < 0: 9 | return self.reachNumber(-target) 10 | 11 | # n * (n + 1) // 2 - target = 2 * x 12 | # n * (n + 1) = 2 * target + 4 * x 13 | # n^2 + n >= 2 * target 14 | # (n + 0.5)^2 >= 2 * target + 0.25 15 | # n >= ceil(-0.5 + sqrt(2 * target + 0.25)) 16 | 17 | ret = math.ceil(-0.5 + math.sqrt(2 * target + 0.25)) 18 | 19 | while (ret * (ret + 1) - 2 * target) % 4: 20 | ret += 1 21 | 22 | return ret 23 | -------------------------------------------------------------------------------- /LeetCode/766. Toeplitz Matrix/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: 3 | for i in range(1, len(matrix)): 4 | for j in range(1, len(matrix[0])): 5 | if matrix[i][j] != matrix[i - 1][j - 1]: 6 | return False 7 | 8 | return True 9 | 10 | -------------------------------------------------------------------------------- /LeetCode/771. Jewels and Stones/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numJewelsInStones(String J, String S) { 3 | Set jewels = new HashSet(); 4 | for (int i = 0; i < J.length(); i++) 5 | jewels.add(J.charAt(i)); 6 | 7 | int ret = 0; 8 | for (int i = 0; i < S.length(); i++) { 9 | if (jewels.contains(S.charAt(i))) 10 | ret += 1; 11 | } 12 | 13 | return ret; 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /LeetCode/775. Global and Local Inversions/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isIdealPermutation(self, A: List[int]) -> bool: 3 | # Time Complexity: O(N) 4 | # Space Complexity: O(1) 5 | 6 | cumsum = 0 7 | target = 0 8 | 9 | for i, num in enumerate(A): 10 | cumsum += num 11 | target += i 12 | 13 | if abs(cumsum - target) > 1: 14 | return False 15 | 16 | return True 17 | -------------------------------------------------------------------------------- /LeetCode/78. Subsets/Solution.scala: -------------------------------------------------------------------------------- 1 | object Solution { 2 | // Time and Space Complexity: O(2^n) 3 | // Immutability changes EVERYTHING! 4 | 5 | def subsets(nums: Array[Int]): List[List[Int]] = 6 | backtrack(nums, 0, Nil, Nil) 7 | 8 | def backtrack(nums: Array[Int], cur: Int, partial: List[Int], ret: List[List[Int]]): List[List[Int]] = { 9 | if (cur == nums.length) { 10 | partial :: ret 11 | } else { 12 | val left = backtrack(nums, cur + 1, partial, ret) 13 | backtrack(nums, cur + 1, nums(cur) :: partial, left) 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /LeetCode/783. Minimum Distance Between BST Nodes/Solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def minDiffInBST(self, root: TreeNode) -> int: 9 | vals = [] 10 | self.inorder(root, vals) 11 | 12 | ret = 1000000000 13 | for i in range(len(vals) - 1): 14 | ret = min(ret, vals[i + 1] - vals[i]) 15 | 16 | return ret 17 | 18 | def inorder(self, node: TreeNode, ret: List[int]): 19 | if node: 20 | self.inorder(node.left, ret) 21 | ret.append(node.val) 22 | self.inorder(node.right, ret) 23 | -------------------------------------------------------------------------------- /LeetCode/784. Letter Case Permutation/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def letterCasePermutation(self, S: str) -> List[str]: 3 | # Time and Space Complexity: O(N 2^N) 4 | 5 | def is_digit(char): 6 | return char in "0123456789" 7 | 8 | S_iter = iter(S) 9 | S_both_cases = map(lambda char: [char] if is_digit(char) else [char.lower(), char.upper()], S_iter) 10 | all_cases = product(*S_both_cases) 11 | 12 | return list(map(lambda comps: "".join(comps), all_cases)) 13 | -------------------------------------------------------------------------------- /LeetCode/786. K-th Smallest Prime Fraction/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kthSmallestPrimeFraction(self, A: List[int], K: int) -> List[int]: 3 | # Time Complexity: O(K log N + N) 4 | # Space Complexity: O(N) 5 | 6 | index = [len(A) - 1] * len(A) 7 | candidates = [(A[i] / A[-1], i) for i in range(len(A))] 8 | heapq.heapify(candidates) 9 | 10 | for _ in range(K - 1): 11 | _, num_index = heapq.heappop(candidates) 12 | if index[num_index] > num_index: 13 | index[num_index] -= 1 14 | value = A[num_index] / A[index[num_index]] 15 | 16 | heapq.heappush(candidates, (value, num_index)) 17 | 18 | return [A[candidates[0][1]], A[index[candidates[0][1]]]] 19 | -------------------------------------------------------------------------------- /LeetCode/791. Custom Sort String/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def customSortString(self, S: str, T: str) -> str: 3 | cnt = [0] * len(S) 4 | others = [] 5 | inverted_index = {S[i]: i for i in range(len(S))} 6 | 7 | for char in T: 8 | if char in inverted_index: 9 | cnt[inverted_index[char]] += 1 10 | else: 11 | others.append(char) 12 | 13 | ret = [] 14 | for i in range(len(S)): 15 | for j in range(cnt[i]): 16 | ret.append(S[i]) 17 | 18 | for char in others: 19 | ret.append(char) 20 | 21 | return ''.join(ret) 22 | -------------------------------------------------------------------------------- /LeetCode/797. All Paths From Source to Target/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: 3 | # Time and Space Complexity: O(N 2^N) 4 | 5 | ret = [] 6 | self.dfs(graph, 0, [0], ret) 7 | 8 | return ret 9 | 10 | def dfs(self, graph: List[List[int]], node: int, path: List[int], ret: List[List[int]]): 11 | if node == len(graph) - 1: 12 | ret.append(path.copy()) 13 | else: 14 | for neighbor in graph[node]: 15 | path.append(neighbor) 16 | self.dfs(graph, neighbor, path, ret) 17 | path.pop() 18 | 19 | -------------------------------------------------------------------------------- /LeetCode/799. Champagne Tower/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: 3 | cur_row = [poured] 4 | 5 | for r in range(query_row): 6 | next_row = [0] * (len(cur_row) + 1) 7 | 8 | 9 | for i in range(len(cur_row)): 10 | if cur_row[i] > 1.0: 11 | amount_added_next_row = (cur_row[i] - 1.0) / 2 12 | next_row[i] += amount_added_next_row 13 | next_row[i + 1] += amount_added_next_row 14 | 15 | cur_row = next_row 16 | 17 | if cur_row[query_glass] > 1.0: 18 | return 1.0 19 | return cur_row[query_glass] 20 | -------------------------------------------------------------------------------- /LeetCode/80. Remove Duplicates from Sorted Array II/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int removeDuplicates(int[] nums) { 3 | int cur = 1; 4 | 5 | for (int check = 1; check < nums.length; check++) { 6 | if (nums[check] != nums[cur - 1] || (cur == 1 || nums[check] != nums[cur - 2])) { 7 | nums[cur] = nums[check]; 8 | cur += 1; 9 | } 10 | } 11 | 12 | return cur; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /LeetCode/804. Unique Morse Code Words/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | MORSE = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] 3 | 4 | def uniqueMorseRepresentations(self, words: List[str]) -> int: 5 | # Time and Space Complexity: O(num_char) 6 | 7 | def char_to_ind(c): 8 | return ord(c) - ord('a') 9 | 10 | def word_to_morse(word): 11 | return "".join(map(lambda c: self.MORSE[char_to_ind(c)], word)) 12 | 13 | return len(set(map(word_to_morse, words))) 14 | -------------------------------------------------------------------------------- /LeetCode/811. Subdomain Visit Count/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subdomainVisits(self, cpdomains: List[str]) -> List[str]: 3 | visit_cnt = {} 4 | 5 | for info in cpdomains: 6 | cnt, domain = info.split(" ") 7 | cnt = int(cnt) 8 | subdomains = domain.split(".") 9 | 10 | subdomain = "" 11 | for i in range(len(subdomains)): 12 | if len(subdomain) > 0: 13 | subdomain = "." + subdomain 14 | subdomain = subdomains[len(subdomains) - 1 - i] + subdomain 15 | visit_cnt[subdomain] = visit_cnt.get(subdomain, 0) + cnt 16 | 17 | return [str(visit_cnt[subdomain]) + " " + subdomain for subdomain in visit_cnt] 18 | -------------------------------------------------------------------------------- /LeetCode/814. Binary Tree Pruning/Solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def pruneTree(self, root: TreeNode) -> TreeNode: 9 | if not root: 10 | return None 11 | 12 | root.left = self.pruneTree(root.left) 13 | root.right = self.pruneTree(root.right) 14 | 15 | if root.left or root.right or root.val == 1: 16 | return root 17 | 18 | return None 19 | -------------------------------------------------------------------------------- /LeetCode/817. Linked List Components/Solution.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | from typing import Set 7 | 8 | class Solution: 9 | def numComponents(self, head: ListNode, G: List[int]) -> int: 10 | return self.recursion(head, False, set(G)) 11 | 12 | def recursion(self, node: ListNode, in_comp: bool, Gset: Set[int]) -> int: 13 | if node is None: 14 | return 1 if in_comp else 0 15 | 16 | if node.val not in Gset and in_comp: 17 | return 1 + self.recursion(node.next, False, Gset) 18 | 19 | return self.recursion(node.next, node.val in Gset, Gset) 20 | 21 | -------------------------------------------------------------------------------- /LeetCode/824. Goat Latin/Solution.py: -------------------------------------------------------------------------------- 1 | from itertools import starmap 2 | 3 | 4 | class Solution: 5 | def toGoatLatin(self, S: str) -> str: 6 | words = S.split(" ") 7 | return " ".join(starmap(self.process, enumerate(words))) 8 | 9 | def process(self, index: int, word: str) -> str: 10 | ret = [] 11 | if word[0].lower() in ("a", "e", "i", "o", "u"): 12 | ret.append(word) 13 | else: 14 | ret.append(word[1:]) 15 | ret.append(word[0]) 16 | 17 | ret.append("ma") 18 | ret.extend(["a" for i in range(index + 1)]) 19 | 20 | return "".join(ret) 21 | -------------------------------------------------------------------------------- /LeetCode/829. Consecutive Numbers Sum/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int consecutiveNumbersSum(int N) { 3 | // Time: O(sqrt(N)); Space: O(1) 4 | int ret = 0; 5 | int product = 2 * N; 6 | int upperBound = (int) Math.sqrt(product); 7 | 8 | for (int i = 1; i <= upperBound; i++) { 9 | if (product % i == 0) { 10 | int y = product / i + 1 - i; 11 | if (y > 1 && y % 2 == 0) 12 | ret += 1; 13 | } 14 | } 15 | 16 | return ret; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /LeetCode/83. Remove Duplicates from Sorted List/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | class Solution { 10 | public ListNode deleteDuplicates(ListNode head) { 11 | ListNode it = head; 12 | while (it != null && it.next != null) { 13 | if (it.val == it.next.val) 14 | it.next = it.next.next; 15 | else 16 | it = it.next; 17 | } 18 | return head; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /LeetCode/830. Positions of Large Groups/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largeGroupPositions(self, s: str) -> List[List[int]]: 3 | ret = [] 4 | start = 0 5 | end = 0 6 | 7 | while start < len(s): 8 | if end + 1 < len(s) and s[end + 1] == s[start]: 9 | end += 1 10 | else: 11 | if end - start + 1 >= 3: 12 | ret.append([start, end]) 13 | 14 | end += 1 15 | start = end 16 | 17 | return ret 18 | -------------------------------------------------------------------------------- /LeetCode/832. Flipping an Image/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[][] flipAndInvertImage(int[][] A) { 3 | for (int i = 0; i < A.length; i++) { 4 | for (int j = 0; j < (A[0].length + 1) / 2; j++) { 5 | int tmp = A[i][j]; 6 | A[i][j] = 1 - A[i][A[0].length - 1 - j]; 7 | A[i][A[0].length - 1 - j] = 1 - tmp; 8 | } 9 | } 10 | return A; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /LeetCode/841. Keys and Rooms/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: 3 | # Time and Space Complexity: O(V + E) 4 | 5 | adj_list = {i: room for i, room in enumerate(rooms)} 6 | 7 | visited = set() 8 | self.dfs(0, visited, adj_list) 9 | return len(visited) == len(rooms) 10 | 11 | def dfs(self, node, visited, adj_list): 12 | visited.add(node) 13 | 14 | for neighbor in adj_list[node]: 15 | if neighbor not in visited: 16 | self.dfs(neighbor, visited, adj_list) 17 | -------------------------------------------------------------------------------- /LeetCode/848. Shifting Letters/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def shiftingLetters(self, s: str, shifts: List[int]) -> str: 3 | # Time and Space Complexity: O(N) 4 | 5 | cum_shift = reversed(list(accumulate(reversed(shifts)))) 6 | 7 | def shift_char(s: str, shift_amount: int) -> str: 8 | return chr((ord(s) - ord('a') + shift_amount) % 26 + ord('a')) 9 | 10 | return "".join(starmap(shift_char, zip(s, cum_shift))) 11 | -------------------------------------------------------------------------------- /LeetCode/852. Peak Index in a Mountain Array/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def peakIndexInMountainArray(self, A: List[int]) -> int: 3 | low = 0 4 | high = len(A) - 1 5 | 6 | # Ternary search to find Peak: 7 | while low < high: 8 | 9 | m1 = low + (high - low) // 3 10 | m2 = high - (high - low) // 3 11 | 12 | v1 = A[m1] 13 | v2 = A[m2] 14 | 15 | if v1 == v2: 16 | low = m1 + 1 17 | high = m2 - 1 18 | elif v1 < v2: 19 | low = m1 + 1 20 | else: 21 | high = m2 - 1 22 | 23 | return low 24 | 25 | 26 | -------------------------------------------------------------------------------- /LeetCode/856. Score of Parentheses/Solution2.java: -------------------------------------------------------------------------------- 1 | class Solution2 { 2 | public int scoreOfParentheses(String S) { 3 | // O(n) time, O(1) space 4 | int opening = 0; 5 | int ret = 0; 6 | 7 | for (int i = 0; i < S.length(); i++) { 8 | if (S.charAt(i) == '(') 9 | opening += 1; 10 | else { 11 | if (S.charAt(i - 1) == '(') 12 | ret += 1 << (opening - 1); 13 | opening -= 1; 14 | } 15 | } 16 | 17 | return ret; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /LeetCode/859. Buddy Strings/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def buddyStrings(self, A: str, B: str) -> bool: 3 | # Time and Space Complexity: O(N) 4 | 5 | if len(A) != len(B): 6 | return False 7 | 8 | diff_inds = [] 9 | 10 | for i, (char1, char2) in enumerate(zip(A, B)): 11 | if char1 != char2: 12 | diff_inds.append(i) 13 | 14 | return (not diff_inds and len(set(iter(A))) < len(A)) or (len(diff_inds) == 2 and A[diff_inds[0]] == B[diff_inds[1]] and A[diff_inds[1]] == B[diff_inds[0]]) 15 | -------------------------------------------------------------------------------- /LeetCode/867. Transpose Matrix/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def transpose(self, matrix: List[List[int]]) -> List[List[int]]: 3 | # Time and Space Complexity: O(MN) 4 | ret = [[0 for i in range(len(matrix))] for j in range(len(matrix[0]))] 5 | 6 | for i in range(len(matrix)): 7 | for j in range(len(matrix[0])): 8 | ret[j][i] = matrix[i][j] 9 | 10 | return ret 11 | -------------------------------------------------------------------------------- /LeetCode/868. Binary Gap/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def binaryGap(self, n: int) -> int: 3 | # Time Complexity: O(log N) 4 | # Space Complexity: O(1) 5 | 6 | ret = 0 7 | lastOcc = -1 8 | i = 0 9 | 10 | while n > 0: 11 | if n & 1: 12 | if lastOcc >= 0: 13 | ret = max(i - lastOcc, ret) 14 | 15 | lastOcc = i 16 | 17 | i += 1 18 | n >>= 1 19 | 20 | return ret 21 | 22 | -------------------------------------------------------------------------------- /LeetCode/869. Reordered Power of 2/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reorderedPowerOf2(self, N: int) -> bool: 3 | # Time and Space Complexity: O(log(N)^2) 4 | 5 | def get_digits(num: int) -> Counter: 6 | digs = [] 7 | while num > 0: 8 | digs.append(num % 10) 9 | num //= 10 10 | 11 | return len(digs), Counter(digs) 12 | 13 | 14 | cur_pow = 1 15 | num_cur_pow_digs, cur_pow_digits = get_digits(cur_pow) 16 | num_digs, digits = get_digits(N) 17 | 18 | while num_cur_pow_digs <= num_digs and cur_pow_digits != digits: 19 | cur_pow *= 2 20 | num_cur_pow_digs, cur_pow_digits = get_digits(cur_pow) 21 | 22 | return cur_pow_digits == digits 23 | -------------------------------------------------------------------------------- /LeetCode/875. Koko Eating Bananas/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minEatingSpeed(self, piles: List[int], H: int) -> int: 3 | low = 1 4 | high = max(piles) 5 | 6 | while low < high: 7 | mid = low + (high - low) // 2 8 | 9 | time = sum(map( 10 | lambda pile : pile // mid if pile % mid == 0 else pile // mid + 1, 11 | piles 12 | )) 13 | 14 | if time > H: 15 | low = mid + 1 16 | else: 17 | high = mid 18 | 19 | 20 | return low 21 | 22 | -------------------------------------------------------------------------------- /LeetCode/876. Middle of the Linked List/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | class Solution { 10 | public ListNode middleNode(ListNode head) { 11 | ListNode slow = head; 12 | ListNode fast = head; 13 | 14 | while(fast != null && fast.next != null) { 15 | fast = fast.next.next; 16 | slow = slow.next; 17 | } 18 | 19 | return slow; 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /LeetCode/88. Merge Sorted Array/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void merge(int[] nums1, int m, int[] nums2, int n) { 3 | for (int i = 0; i < n; i++) { 4 | nums1[m + i] = nums2[i]; 5 | } 6 | Arrays.sort(nums1, 0, m + n); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /LeetCode/881. Boats to Save People/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numRescueBoats(self, people: List[int], limit: int) -> int: 3 | # Time Complexity: O(N log N) 4 | # Space Complexity O(sort(N)) 5 | 6 | people.sort() 7 | ret = 0 8 | 9 | light = 0 10 | heavy = len(people) - 1 11 | 12 | while light <= heavy: 13 | ret += 1 14 | 15 | if light == heavy: 16 | light += 1 17 | else: 18 | if people[heavy] + people[light] <= limit: 19 | light += 1 20 | heavy -= 1 21 | else: 22 | heavy -= 1 23 | 24 | 25 | return ret 26 | 27 | -------------------------------------------------------------------------------- /LeetCode/884. Uncommon Words from Two Sentences/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def uncommonFromSentences(self, s1: str, s2: str) -> List[str]: 3 | # Time and Space Complexity: O(|len(word)| for word in s1 + s2) 4 | 5 | words1 = Counter(s1.split(" ")) 6 | words2 = Counter(s2.split(" ")) 7 | 8 | ret = [] 9 | 10 | for cnter in [words1, words2]: 11 | for word in cnter: 12 | if words1[word] + words2[word] == 1: 13 | ret.append(word) 14 | 15 | return ret 16 | -------------------------------------------------------------------------------- /LeetCode/887. Super Egg Drop/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // O(KN) solution 3 | private int[] dp; 4 | 5 | public int superEggDrop(int K, int N) { 6 | dp = new int[N + 1]; 7 | for (int i = 0; i <= N; i++) 8 | dp[i] = i; 9 | 10 | for (int k = 2; k <= K; k++) { 11 | int[] dpNext = new int[N + 1]; 12 | int f = 1; 13 | for (int n = 1; n <= N; n++) { 14 | while (f < n && Math.max(dp[f - 1], dpNext[n - f]) > Math.max(dp[f], dpNext[n - f - 1])) 15 | f += 1; 16 | dpNext[n] = 1 + Math.max(dp[f - 1], dpNext[n - f]); 17 | } 18 | dp = dpNext; 19 | } 20 | 21 | return dp[N]; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /LeetCode/89. Gray Code/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List grayCode(int n) { 3 | List ret = new ArrayList(); 4 | ret.add(0); 5 | 6 | int numCodes = (int) Math.pow(2.0, n); 7 | int ind = 1; 8 | while (ind < numCodes) { 9 | ret.add(ind ^ (ind >> 1)); 10 | ind += 1; 11 | } 12 | 13 | return ret; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /LeetCode/905. Sort Array By Parity/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] sortArrayByParity(int[] A) { 3 | int lower = 0; 4 | int faster = 0; 5 | 6 | while (faster < A.length) { 7 | if (A[faster] % 2 == 0) { 8 | int tmp = A[lower]; 9 | A[lower] = A[faster]; 10 | A[faster] = tmp; 11 | lower += 1; 12 | } 13 | faster += 1; 14 | } 15 | 16 | return A; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /LeetCode/915. Partition Array into Disjoint Intervals/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def partitionDisjoint(self, nums: List[int]) -> int: 3 | # Time and Space Complexity: O(N) 4 | maxes = accumulate(nums, lambda a, b: max(a, b)) 5 | mins = iter(reversed(list(accumulate(reversed(nums), lambda a, b: min(a, b))))) 6 | 7 | next(mins) 8 | for i, (prefix_max, suffix_min) in enumerate(zip(maxes, mins)): 9 | if prefix_max <= suffix_min: 10 | return i + 1 11 | -------------------------------------------------------------------------------- /LeetCode/921. Minimum Add to Make Parentheses Valid/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minAddToMakeValid(self, S: str) -> int: 3 | # Time Complexity: O(N) 4 | # Space Complexity: O(1) 5 | 6 | opening = 0 7 | ret = 0 8 | 9 | for paren in S: 10 | if paren == "(": 11 | opening += 1 12 | else: 13 | if opening > 0: 14 | opening -= 1 15 | else: 16 | ret += 1 17 | 18 | return ret + opening 19 | -------------------------------------------------------------------------------- /LeetCode/929. Unique Email Addresses/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numUniqueEmails(self, emails: List[str]) -> int: 3 | emails_set = set() 4 | for email in emails: 5 | emails_set.add(self.process(email)) 6 | return len(emails_set) 7 | 8 | def process(self, email: str) -> str: 9 | ret = [] 10 | 11 | local_name, domain_name = email.split('@') 12 | for i in range(len(local_name)): 13 | if local_name[i] != "." and local_name[i] != "+": 14 | ret.append(local_name[i]) 15 | elif local_name[i] == "+": 16 | break 17 | 18 | ret.append("@") 19 | ret.append(domain_name) 20 | 21 | return ''.join(ret) 22 | -------------------------------------------------------------------------------- /LeetCode/930. Binary Subarrays With Sum/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numSubarraysWithSum(self, nums: List[int], goal: int) -> int: 3 | # Time and Space Complexity: O(N) 4 | 5 | prefix = [0] + list(accumulate(nums)) 6 | cnter = [] 7 | 8 | for pre_sum in prefix: 9 | if pre_sum == len(cnter): 10 | cnter.append(0) 11 | 12 | cnter[-1] += 1 13 | 14 | 15 | ret = 0 16 | for fst in range(len(cnter)): 17 | snd = fst + goal 18 | 19 | if snd < len(cnter): 20 | if fst == snd: 21 | ret += cnter[fst] * (cnter[fst] - 1) // 2 22 | else: 23 | ret += cnter[fst] * cnter[snd] 24 | 25 | return ret 26 | -------------------------------------------------------------------------------- /LeetCode/933. Number of Recent Calls/Solution.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | 4 | class RecentCounter: 5 | 6 | def __init__(self): 7 | self.data = deque() 8 | 9 | 10 | def ping(self, t: int) -> int: 11 | while len(self.data) > 0 and self.data[0] < t - 3000: 12 | self.data.popleft() 13 | 14 | self.data.append(t) 15 | return len(self.data) 16 | 17 | 18 | 19 | # Your RecentCounter object will be instantiated and called as such: 20 | # obj = RecentCounter() 21 | # param_1 = obj.ping(t) 22 | -------------------------------------------------------------------------------- /LeetCode/937. Reorder Data in Log Files/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reorderLogFiles(self, logs: List[str]) -> List[str]: 3 | return sorted(logs, key=Solution.key) 4 | 5 | @staticmethod 6 | def key(log: str) -> str: 7 | words = log.split(" ") 8 | if words[1].isnumeric(): 9 | return "a" 10 | else: 11 | return "$" + log[len(words[0]):] + words[0] 12 | 13 | -------------------------------------------------------------------------------- /LeetCode/938. Range Sum of BST/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | class Solution { 11 | public int rangeSumBST(TreeNode root, int L, int R) { 12 | if (root == null) 13 | return 0; 14 | 15 | if (root.val < L) 16 | return rangeSumBST(root.right, L, R); 17 | 18 | if (root.val > R) 19 | return rangeSumBST(root.left, L, R); 20 | 21 | return root.val + rangeSumBST(root.left, L, R) + rangeSumBST(root.right, L, R); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /LeetCode/94. Binary Tree Inorder Traversal/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | class Solution { 11 | public List inorderTraversal(TreeNode root) { 12 | if (root == null) 13 | return new ArrayList(); 14 | 15 | List ret = inorderTraversal(root.left); 16 | ret.add(root.val); 17 | List right = inorderTraversal(root.right); 18 | ret.addAll(right); 19 | 20 | return ret; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /LeetCode/941. Valid Mountain Array/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def validMountainArray(self, A: List[int]) -> bool: 3 | if len(A) < 3: 4 | return False 5 | i = 0 6 | while i < len(A) - 1: 7 | if A[i] == A[i + 1]: 8 | return False 9 | elif A[i] < A[i + 1]: 10 | i += 1 11 | else: 12 | break 13 | 14 | if i == len(A) - 1 or i == 0: 15 | return False 16 | 17 | while i < len(A) - 1: 18 | if A[i] <= A[i + 1]: 19 | return False 20 | i += 1 21 | 22 | return True 23 | -------------------------------------------------------------------------------- /LeetCode/945. Minimum Increment to Make Array Unique/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minIncrementForUnique(self, A: List[int]) -> int: 3 | # Time Complexity: O(N log N) 4 | # Space Complexity: O(sort) 5 | 6 | A.sort() 7 | cur_max = -1 8 | ret = 0 9 | 10 | for num in A: 11 | if num > cur_max: 12 | cur_max = num 13 | else: 14 | ret += cur_max + 1 - num 15 | cur_max += 1 16 | 17 | return ret 18 | -------------------------------------------------------------------------------- /LeetCode/948. Bag of Tokens/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def bagOfTokensScore(self, tokens: List[int], P: int) -> int: 3 | tokens.sort() 4 | 5 | start = 0 6 | end = len(tokens) - 1 7 | 8 | score = 0 9 | ret = 0 10 | 11 | while start <= end: 12 | if tokens[start] <= P: 13 | score += 1 14 | P -= tokens[start] 15 | start += 1 16 | else: 17 | if score > 0: 18 | score -= 1 19 | P += tokens[end] 20 | end -= 1 21 | else: 22 | break 23 | 24 | ret = max(score, ret) 25 | 26 | return ret 27 | -------------------------------------------------------------------------------- /LeetCode/951. Flip Equivalent Binary Trees/Solution.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool: 9 | # Time Complexity: O(N) 10 | 11 | if not (root1 and root2): 12 | return not (root1 or root2) 13 | 14 | if root1.val != root2.val: 15 | return False 16 | 17 | return (self.flipEquiv(root1.left, root2.left) and self.flipEquiv(root1.right, root2.right)) or (self.flipEquiv(root1.left, root2.right) and self.flipEquiv(root1.right, root2.left)) 18 | -------------------------------------------------------------------------------- /LeetCode/974. Subarray Sums Divisible by K/Solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private int[] prefix; 3 | 4 | 5 | public int subarraysDivByK(int[] A, int K) { 6 | prefix = new int[A.length]; 7 | 8 | 9 | prefix[0] = A[0]; 10 | for (int i = 1; i < A.length; i++) { 11 | prefix[i] = prefix[i - 1] + A[i]; 12 | } 13 | 14 | 15 | int ret = 0; 16 | for (int i = 0; i < A.length; i++) { 17 | for (int j = i; j < A.length; j++) { 18 | int remainder = (prefix[j] - prefix[i] + A[i]) % K; 19 | if (remainder == 0) 20 | ret += 1; 21 | } 22 | } 23 | 24 | return ret; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /LeetCode/976. Largest Perimeter/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestPerimeter(self, A: List[int]) -> int: 3 | # Time complexity: O(N log N) 4 | # Space complexity: O(N) 5 | 6 | A.sort() 7 | 8 | for i in range(len(A) - 1, 1, -1): 9 | if A[i] < A[i - 1] + A[i - 2]: 10 | return A[i] + A[i - 1] + A[i - 2] 11 | 12 | return 0 13 | -------------------------------------------------------------------------------- /LeetCode/977. Squares of a Sorted Array/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortedSquares(self, A: List[int]) -> List[int]: 3 | 4 | i = 0 5 | while i < len(A) and A[i] < 0: 6 | i += 1 7 | 8 | if i == 0: 9 | return [val ** 2 for val in A] 10 | 11 | j = i - 1 12 | ret = [] 13 | while j >= 0 and i < len(A): 14 | if A[i] ** 2 < A[j] ** 2: 15 | ret.append(A[i] ** 2) 16 | i += 1 17 | else: 18 | ret.append(A[j] ** 2) 19 | j -= 1 20 | 21 | 22 | for k in range(i, len(A)): 23 | ret.append(A[k] ** 2) 24 | 25 | for k in range(j, -1, -1): 26 | ret.append(A[k] ** 2) 27 | 28 | return ret 29 | -------------------------------------------------------------------------------- /LeetCode/978. Longest Turbulent Subarray/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxTurbulenceSize(self, A: List[int]) -> int: 3 | # Time Complexity: O(N) 4 | # Space Complexity: O(1) 5 | 6 | if len(A) <= 1: 7 | return len(A) 8 | 9 | start = 0 10 | ret = 1 11 | 12 | while start + 1 < len(A): 13 | if A[start + 1] != A[start]: 14 | end = start + 2 15 | 16 | while end < len(A) and (A[end] - A[end - 1]) * (A[end - 1] - A[end - 2]) < 0: 17 | end += 1 18 | 19 | ret = max(ret, end - start) 20 | 21 | start = end - 1 22 | else: 23 | start += 1 24 | 25 | return ret 26 | 27 | -------------------------------------------------------------------------------- /LeetCode/991. Broken Calculator/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def brokenCalc(self, X: int, Y: int) -> int: 3 | # Idea: work backwards from Y to X 4 | 5 | # When Y is not divisible by 2, can only add 1 to it 6 | # When Y is divisible by 2, if Y < X, increment 7 | # otherwise, divide by 2 8 | 9 | ret = 0 10 | 11 | while Y > X: 12 | if Y % 2: 13 | Y += 1 14 | else: 15 | Y //= 2 16 | ret += 1 17 | 18 | return ret + X - Y 19 | -------------------------------------------------------------------------------- /LeetCode/997. Find the Town Judge/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findJudge(self, N: int, trust: List[List[int]]) -> int: 3 | indeg = [0] * N 4 | outdeg = [0] * N 5 | 6 | for t in trust: 7 | indeg[t[1] - 1] += 1 8 | outdeg[t[0] - 1] += 1 9 | 10 | satisfy = [] 11 | 12 | for i in range(N): 13 | if indeg[i] == N - 1 and outdeg[i] == 0: 14 | satisfy.append(i) 15 | 16 | return (satisfy[0] + 1) if len(satisfy) == 1 else -1 17 | 18 | -------------------------------------------------------------------------------- /OtherProblems/Binary Search/Missing Number in Sorted Array/Solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def missingNumber(self, nums: List[int]) -> int: 3 | low = 0 4 | high = len(nums) - 1 5 | 6 | while low < high: 7 | mid = low + (high - low) // 2 8 | if nums[mid] == mid: 9 | low = mid + 1 10 | else: 11 | high = mid 12 | 13 | if nums[low] != low: 14 | return low 15 | 16 | return len(nums) 17 | --------------------------------------------------------------------------------