├── 099. Two Sum Less Than K └── main.py ├── 1. Two Sum └── main.py ├── 100. Same Tree └── main.py ├── 1002. Find Common Characters └── main.py ├── 1004. Max Consecutive Ones III └── main.py ├── 1021. Remove Outermost Parentheses └── main.py ├── 1025. Divisor Game └── main.py ├── 1026. Maximum Difference Between Node and Ancestor └── main.py ├── 1038. Binary Search Tree to Greater Sum Tree └── main.py ├── 1043. Partition Array for Maximum Sum └── main.py ├── 1048. Longest String Chain └── main.py ├── 1051. Height Checker └── main.py ├── 1052. Grumpy Bookstore Owner └── main.py ├── 1057. Campus Bikes └── main.py ├── 1062. Longest Repeating Substring └── main.py ├── 1066. Campus Bikes II └── main.py ├── 1068. Product Sales Analysis I └── main.py ├── 1072. Flip Columns For Maximum Number of Equal Rows └── main.py ├── 1074. Number of Submatrices That Sum to Target └── main.py ├── 108. Convert Sorted Array to Binary Search Tree └── main.py ├── 1095. Find in Mountain Array └── main.py ├── 1099. Two Sum Less Than K └── main.py ├── 11. Container With Most Water └── main.py ├── 1101. The Earliest Moment When Everyone Become Friends └── main.py ├── 1105. Filling Bookcase Shelves └── main.py ├── 1106. Parsing A Boolean Expression └── main.py ├── 1108. Defanging an IP Address └── main.py ├── 1110. Delete Nodes And Return Forest └── main.py ├── 1119. Remove Vowels from a String └── main.py ├── 1120. Maximum Average Subtree └── main.py ├── 1122. Relative Sort Array └── main.py ├── 1133. Largest Unique Number └── main.py ├── 1137. N-th Tribonacci Number └── main.py ├── 1140. Stone Game II └── main.py ├── 1141. User Activity for the Past 30 Days I └── main.sql ├── 1143. Longest Common Subsequence └── main.py ├── 1148. Article Views I └── main.sql ├── 1155. Number of Dice Rolls With Target Sum └── main.py ├── 1160. Find Words That Can Be Formed by Characters └── main.py ├── 1165. Single-Row Keyboard └── main.py ├── 1167. Minimum Cost to Connect Sticks └── main.py ├── 1171. Remove Zero Sum Consecutive Nodes from Linked List └── main.py ├── 118. Pascal's Triangle └── main.py ├── 1180. Count Substrings with Only One Distinct Letter └── main.py ├── 1185. Day of the Week └── main.py ├── 119. Pascal's Triangle II └── main.py ├── 1190. Reverse Substrings Between Each Pair of Parentheses └── main.py ├── 12. Integer to Roman └── main.py ├── 1207. Unique Number of Occurrences └── main.py ├── 1208. Get Equal Substrings Within Budget └── main.py ├── 121. Best Time to Buy and Sell Stock └── main.py ├── 1213. Intersection of Three Sorted Arrays └── main.py ├── 1219. Path with Maximum Gold └── main.py ├── 122. Best Time to Buy and Sell Stock II └── main.py ├── 1220. Count Vowels Permutation └── main.py ├── 1221. Split a String in Balanced Strings └── main.py ├── 1229. Meeting Scheduler └── main.py ├── 1230. Toss Strange Coins └── main.py ├── 1233. Remove Sub-Folders from the Filesystem └── main.py ├── 1235. Maximum Profit in Job Scheduling └── main.py ├── 1239. Maximum Length of a Concatenated String with Unique Characters └── main.py ├── 1245. Tree Diameter └── main.py ├── 1248. Count Number of Nice Subarrays └── main.py ├── 1249. Minimum Remove to Make Valid Parentheses └── main.py ├── 125. Valid Palindrome └── main.py ├── 1251. Average Selling Price └── main.sql ├── 1255. Maximum Score Words Formed by Letters └── main.py ├── 1257. Smallest Common Region └── main.py ├── 1265. Print Immutable Linked List in Reverse └── main.py ├── 1266. Minimum Time Visiting All Points └── main.py ├── 1269. Number of Ways to Stay in the Same Place After Some Steps └── main.py ├── 1272. Remove Interval └── main.py ├── 1277. Count Square Submatrices with All Ones └── main.py ├── 128. Longest Consecutive Sequence └── main.py ├── 1280. Students and Examinations └── main.sql ├── 1287. Element Appearing More Than 25% In Sorted Array └── main.py ├── 1289. Minimum Falling Path Sum II └── main.py ├── 129. Sum Root to Leaf Numbers └── main.py ├── 1291. Sequential Digits └── main.py ├── 13. Roman to Integer └── main.py ├── 1309. Decrypt String from Alphabet to Integer Mapping └── main.py ├── 131. Palindrome Partitioning └── main.py ├── 1310. XOR Queries of a Subarray └── main.py ├── 1323. Maximum 69 Number └── main.py ├── 1325. Delete Leaves With a Given Value └── main.py ├── 1331. Rank Transform of an Array └── main.py ├── 1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance └── main.py ├── 1335. Minimum Difficulty of a Job Schedule └── main.py ├── 134. Gas Station └── main.py ├── 1346. Check If N and Its Double Exist └── main.py ├── 1347. Minimum Number of Steps to Make Two Strings Anagram └── main.py ├── 135. Candy └── main.py ├── 1356. Sort Integers by The Number of 1 Bits └── main.py ├── 136. Single Number └── main.py ├── 1361. Validate Binary Tree Nodes └── main.py ├── 1365. How Many Numbers Are Smaller Than the Current Number └── main.py ├── 1367. Linked List in Binary Tree └── main.py ├── 137. Single Number II └── main.py ├── 1371. Find the Longest Substring Containing Vowels in Even Counts └── main.py ├── 1378. Replace Employee ID With The Unique Identifier └── main.sql ├── 1380. Lucky Numbers in a Matrix └── main.py ├── 1381. Design a Stack With Increment Operation └── main.py ├── 1382. Balance a Binary Search Tree └── main.py ├── 1395. Count Number of Teams └── main.py ├── 14. Longest Common Prefix └── main.py ├── 140. Word Break II └── main.py ├── 1402. Reducing Dishes └── main.py ├── 1404. Number of Steps to Reduce a Number in Binary Representation to One └── main.py ├── 1405. Longest Happy String └── main.py ├── 1408. String Matching in an Array └── main.py ├── 141. Linked List Cycle └── main.py ├── 1420. Build Array Where You Can Find The Maximum Exactly K Comparisons └── main.py ├── 1422. Maximum Score After Splitting a String └── main.py ├── 1424. Diagonal Traverse II └── main.py ├── 1425. Constrained Subsequence Sum └── main.py ├── 1428. Leftmost Column with at Least a One └── main.py ├── 1429. First Unique Number └── main.py ├── 143. Reorder List └── main.py ├── 1431. Kids With the Greatest Number of Candies └── main.py ├── 1436. Destination City └── main.py ├── 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit └── main.py ├── 1441. Build an Array With Stack Operations └── main.py ├── 1442. Count Triplets That Can Form Two Arrays of Equal XOR └── main.py ├── 145. Binary Tree Postorder Traversal └── main.py ├── 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence └── main.py ├── 1457. Pseudo-Palindromic Paths in a Binary Tree └── main.py ├── 1460. Make Two Arrays Equal by Reversing Subarrays └── main.py ├── 1463. Cherry Pickup II └── main.py ├── 1464. Maximum Product of Two Elements in an Array └── main.py ├── 1469. Find All The Lonely Nodes └── main.py ├── 1470. Shuffle the Array └── main.py ├── 1480. Running Sum of 1d Array └── main.java ├── 1481. Least Number of Unique Integers after K Removals └── main.py ├── 1482. Minimum Number of Days to Make m Bouquets └── main.py ├── 1496. Path Crossing └── main.py ├── 1497. Check If Array Pairs Are Divisible by k └── main.py ├── 15. 3Sum ├── brute-force.py └── main.py ├── 150. Evaluate Reverse Polish Notation └── main.py ├── 1503. Last Moment Before All Ants Fall Out of a Plank └── main.py ├── 1508. Range Sum of Sorted Subarray Sums └── main.py ├── 1509. Minimum Difference Between Largest and Smallest Value in Three Moves └── main.py ├── 151. Reverse Words in a String └── main.py ├── 1512. Number of Good Pairs └── main.py ├── 1514. Path with Maximum Probability └── main.py ├── 1517. Find Users With Valid E-Mails └── main.sql ├── 1518. Water Bottles └── main.py ├── 1527. Patients With a Condition └── main.py ├── 1528. Shuffle String └── main.py ├── 1530. Number of Good Leaf Nodes Pairs └── main.py ├── 1531. String Compression II └── main.py ├── 1535. Find the Winner of an Array Game └── main.py ├── 1544. Make The String Great └── main.py ├── 1545. Find Kth Bit in Nth Binary String └── main.py ├── 155. Min Stack └── main.py ├── 1550. Three Consecutive Odds └── main.py ├── 1552. Magnetic Force Between Two Balls └── main.py ├── 1561. Maximum Number of Coins You Can Get └── main.py ├── 1568. Minimum Number of Days to Disconnect Island └── main.py ├── 1572. Matrix Diagonal Sum └── main.py ├── 1574. Shortest Subarray to be Removed to Make Array Sorted └── main.py ├── 1578. Minimum Time to Make Rope Colorful └── main.py ├── 1579. Remove Max Number of Edges to Keep Graph Fully Traversable └── main.py ├── 1580. Put Boxes Into the Warehouse II └── main.py ├── 1581. Customer Who Visited but Did Not Make Any Transactions └── main.sql ├── 1582. Special Positions in a Binary Matrix └── main.py ├── 159. Longest Substring with At Most Two Distinct Characters └── main.py ├── 1590. Make Sum Divisible by P └── main.py ├── 1593. Split a String Into the Max Number of Unique Substrings └── main.py ├── 1598. Crawler Log Folder └── main.py ├── 1605. Find Valid Matrix Given Row and Column Sums └── main.py ├── 1608. Special Array With X Elements Greater Than or Equal X └── main.py ├── 1609. Even Odd Tree └── main.py ├── 1611. Minimum One Bit Operations to Make Integers Zero └── main.py ├── 1614. Maximum Nesting Depth of the Parentheses └── main.py ├── 1624. Largest Substring Between Two Equal Characters └── main.py ├── 1630. Arithmetic Subarrays └── main.py ├── 1634. Add Two Polynomials Represented as Linked Lists └── main.py ├── 1636. Sort Array by Increasing Frequency └── main.py ├── 1637. Widest Vertical Area Between Two Points Containing No Points └── main.py ├── 1642. Furthest Building You Can Reach └── main.py ├── 165. Compare Version Numbers └── main.py ├── 1652. Defuse the Bomb └── main.py ├── 1653. Minimum Deletions to Make String Balanced └── main.py ├── 1656. Design an Ordered Stream └── main.py ├── 1657. Determine if Two Strings Are Close └── main.py ├── 1661. Average Time of Process per Machine └── main.sql ├── 1662. Check If Two String Arrays are Equivalent └── main.py ├── 1667. Fix Names in a Table └── main.py ├── 1669. Merge In Between Linked Lists └── main.py ├── 167. Two Sum II - Input Array Is Sorted └── main.py ├── 1671. Minimum Number of Removals to Make Mountain Array └── main.py ├── 1672. Richest Customer Wealth └── main.py ├── 1683. Invalid Tweets └── main.sql ├── 1684. Count the Number of Consistent Strings └── main.py ├── 1685. Sum of Absolute Differences in a Sorted Array └── main.py ├── 1688. Count of Matches in Tournament └── main.py ├── 1689. Partitioning Into Minimum Number Of Deci-Binary Numbers └── main.py ├── 169. Majority Element ├── main.cpp └── main.py ├── 17. Letter Combinations of a Phone Number └── main.py ├── 1700. Number of Students Unable to Eat Lunch └── main.py ├── 1701. Average Waiting Time └── main.py ├── 1704. Determine if String Halves Are Alike └── main.py ├── 1716. Calculate Money in Leetcode Bank └── main.py ├── 1717. Maximum Score From Removing Substrings └── main.py ├── 172. Factorial Trailing Zeroes └── main.py ├── 1727. Largest Submatrix With Rearrangements └── main.py ├── 1740. Find Distance in a Binary Tree └── main.py ├── 1743. Restore the Array From Adjacent Pairs └── main.py ├── 1750. Minimum Length of String After Deleting Similar Ends └── main.py ├── 1757. Recyclable and Low Fat Products └── main.sql ├── 1758. Minimum Changes To Make Alternating Binary String └── main.py ├── 1759. Count Number of Homogenous Substrings └── main.py ├── 1760. Minimum Limit of Balls in a Bag └── main.py ├── 1769. Minimum Number of Operations to Move All Balls to Each Box └── main.py ├── 1773. Count Items Matching a Rule └── main.py ├── 179. Largest Number └── main.py ├── 1793. Maximum Score of a Good Subarray └── main.py ├── 18. 4Sum └── main.py ├── 1812. Determine Color of a Chessboard Square └── main.py ├── 1813. Sentence Similarity III └── main.py ├── 1814. Count Nice Pairs in an Array └── main.py ├── 1816. Truncate Sentence └── main.py ├── 1823. Find the Winner of the Circular Game └── main.py ├── 1827. Minimum Operations to Make the Array Increasing └── main.py ├── 1829. Maximum XOR for Each Query └── main.py ├── 1832. Check if the Sentence Is Pangram └── main.py ├── 1836. Remove Duplicates From an Unsorted Linked List └── main.py ├── 1838. Frequency of the Most Frequent Element └── main.py ├── 1844. Replace All Digits with Characters └── main.py ├── 1845. Seat Reservation Manager └── main.py ├── 1846. Maximum Element After Decreasing and Rearranging └── main.py ├── 1858. Longest Word With All Prefixes └── main.py ├── 1859. Sorting the Sentence └── main.py ├── 1861. Rotating the Box └── main.py ├── 1863. Sum of All Subset XOR Totals └── main.py ├── 1874. Minimize Product Sum of Two Arrays └── main.py ├── 1877. Minimize Maximum Pair Sum in Array └── main.py ├── 1887. Reduction Operations to Make the Array Elements Equal └── main.py ├── 189. Rotate Array └── main.py ├── 1894. Find the Student that Will Replace the Chalk └── main.py ├── 1897. Redistribute Characters to Make All Strings Equal └── main.py ├── 19. Remove Nth Node From End of List └── main.py ├── 190. Reverse Bits └── main.py ├── 1903. Largest Odd Number in String └── main.py ├── 1905. Count Sub Islands └── main.py ├── 1913. Maximum Product Difference Between Two Pairs └── main.py ├── 1915. Number of Wonderful Substrings └── main.py ├── 1920. Build Array from Permutation └── main.py ├── 1921. Eliminate Maximum Number of Monsters └── main.py ├── 1930. Unique Length-3 Palindromic Subsequences └── main.py ├── 1935. Maximum Number of Words You Can Type └── main.py ├── 1937. Maximum Number of Points with Cost └── main.py ├── 1940. Longest Common Subsequence Between Sorted Arrays └── main.py ├── 1942. The Number of the Smallest Unoccupied Chair └── main.py ├── 1944. Number of Visible People in a Queue ├── brute-force.py └── main.py ├── 1945. Sum of Digits of String After Convert └── main.py ├── 1957. Delete Characters to Make Fancy String └── main.py ├── 1963. Minimum Number of Swaps to Make the String Balanced 2 └── main.py ├── 1967. Number of Strings That Appear as Substrings in Word └── main.java ├── 197. Rising Temperature └── main.sql ├── 1971. Find if Path Exists in Graph └── main.py ├── 1975. Maximum Matrix Sum └── main.py ├── 198. House Robber └── main.py ├── 1992. Find All Groups of Farmland └── main.py ├── 2. Add Two Numbers └── main.py ├── 20. Valid Parentheses └── main.py ├── 200. Number of Islands └── main.py ├── 2000. Reverse Prefix of Word └── main.py ├── 2006. Count Number of Pairs With Absolute Difference K └── main.py ├── 2009. Minimum Number of Operations to Make Array Continuous └── main.py ├── 201. Bitwise AND of Numbers Range └── main.py ├── 2011. Final Value of Variable After Performing Operations └── main.py ├── 202. Happy Number └── main.py ├── 2022. Convert 1D Array Into 2D Array └── main.py ├── 2028. Find Missing Observations └── main.py ├── 2037. Minimum Number of Moves to Seat Everyone └── main.py ├── 2038. Remove Colored Pieces if Both Neighbors are the Same Color ├── main.py └── slow_visualization.py ├── 2044. Count Number of Maximum Bitwise-OR Subsets └── main.py ├── 2045. Second Minimum Time to Reach Destination └── main.py ├── 205. Isomorphic Strings └── main.py ├── 2050. Parallel Courses III └── main.py ├── 2053. Kth Distinct String in an Array └── main.py ├── 2054. Two Best Non-Overlapping Events └── main.py ├── 2058. Find the Minimum and Maximum Number of Nodes Between Critical Points └── main.py ├── 206. Reverse Linked List └── main.py ├── 2061. Number of Spaces Cleaning Robot Cleaned └── main.py ├── 2064. Minimized Maximum of Products Distributed to Any Store └── main.py ├── 2070. Most Beautiful Item for Each Query └── main.py ├── 2073. Time Needed to Buy Tickets └── main.py ├── 2083. Substrings That Begin and End With the Same Letter └── main.py ├── 209. Minimum Size Subarray Sum └── main.py ├── 2092. Find All People With Secret └── main.py ├── 2093. Minimum Cost to Reach City With Discounts └── main.py ├── 2096. Step-By-Step Directions From a Binary Tree Node to Another └── main.py ├── 2097. Valid Arrangement of Pairs └── main.py ├── 21. Merge Two Sorted Lists └── main.py ├── 2103. Rings and Rods └── main.py ├── 2107. Number of Unique Flavors After Sharing K Candies └── main.py ├── 2108. Find First Palindromic String in the Array └── main.py ├── 2114. Maximum Number of Words Found in Sentences └── main.py ├── 2125. Number of Laser Beams in a Bank └── main.py ├── 2134. Minimum Swaps to Group All 1's Together II └── main.py ├── 214. Shortest Palindrome └── main.py ├── 2147. Number of Ways to Divide a Long Corridor └── main.py ├── 2149. Rearrange Array Elements by Sign └── main.py ├── 215. Kth Largest Element in an Array └── main.py ├── 2160. Minimum Sum of Four Digit Number After Splitting Digits └── main.py ├── 217. Contains Duplicate └── main.py ├── 2181. Merge Nodes in Between Zeros └── main.py ├── 219. Contains Duplicate II └── main.py ├── 2191. Sort the Jumbled Numbers └── main.py ├── 2192. All Ancestors of a Node in a Directed Acyclic Graph └── main.py ├── 2194. Cells in a Range on an Excel Sheet └── main.py ├── 2196. Create Binary Tree From Descriptions └── main.py ├── 2220. Minimum Bit Flips to Convert Number └── main.py ├── 2225. Find Players With Zero or One Losses └── main.py ├── 2257. Count Unguarded Cells in the Grid └── main.py ├── 2264. Largest 3-Same-Digit Number in String └── main.py ├── 2265. Count Nodes Equal to Average of Subtree └── main.py ├── 2275. Largest Combination With Bitwise AND Greater Than Zero └── main.py ├── 228. Summary Ranges └── main.py ├── 2285. Maximum Total Importance of Roads └── main.py ├── 229. Majority Element II └── main.py ├── 2290. Minimum Obstacle Removal to Reach Corner └── main.py ├── 231. Power of Two └── main.py ├── 2315. Count Asterisks └── main.py ├── 232. Implement Queue using Stacks └── main.py ├── 2325. Decode the Message └── main.py ├── 2326. Spiral Matrix IV └── main.py ├── 2331. Evaluate Boolean Binary Tree └── main.py ├── 2337. Move Pieces to Obtain a String └── main.py ├── 234. Palindrome Linked List └── main.py ├── 235. Add Two Integers └── main.py ├── 2353. Design a Food Rating System └── main.py ├── 2356. Number of Unique Subjects Taught by Each Teacher └── main.sql ├── 237. Delete Node in a Linked List └── main.py ├── 2370. Longest Ideal Subsequence └── main.py ├── 2373. Largest Local Values in a Matrix └── main.py ├── 238. Product of Array Except Self └── main.py ├── 2385. Amount of Time for Binary Tree to Be Infected └── main.py ├── 2391. Minimum Amount of Time to Collect Garbage └── main.py ├── 2392. Build a Matrix With Conditions └── main.py ├── 2402. Meeting Rooms III └── main.py ├── 2406. Divide Intervals Into Minimum Number of Groups └── main.py ├── 241. Different Ways to Add Parentheses └── main.py ├── 2416. Sum of Prefix Scores of Strings └── main.py ├── 2418. Sort the People └── main.py ├── 2419. Longest Subarray With Maximum Bitwise AND └── main.py ├── 242. Valid Anagram └── main.py ├── 243. Shortest Word Distance └── main.py ├── 2433. Find The Original Array of Prefix Xor └── main.py ├── 2441. Largest Positive Integer That Exists With Its Negative └── main.py ├── 2444. Count Subarrays With Fixed Bounds └── main.py ├── 2458. Height of Binary Tree After Subtree Removal Queries └── main.py ├── 2461. Maximum Sum of Distinct Subarrays With Length K └── main.py ├── 2463. Minimum Total Distance Traveled └── main.py ├── 2469. Convert the Temperature └── main.py ├── 2473. Minimum Cost to Buy Apples └── main.py ├── 2482. Difference Between Ones and Zeros in Row and Column └── main.py ├── 2485. Find the Pivot Integer └── main.py ├── 2486. Append Characters to String to Make Subsequence └── main.py ├── 2487. Remove Nodes From Linked List └── main.py ├── 2490. Circular Sentence └── main.py ├── 2491. Divide Players Into Teams of Equal Skill └── main.py ├── 2501. Longest Square Streak in an Array └── main.py ├── 2505. Bitwise OR of All Subsequence Sums └── main.py ├── 2516. Take K of Each Character From Left and Right └── main.py ├── 252. Meeting Rooms └── main.py ├── 253. Meeting Rooms II └── main.py ├── 2530. Maximal Score After Applying K Operations └── main.py ├── 2540. Minimum Common Value └── main.py ├── 255. Verify Preorder Sequence in Binary Search Tree └── main.py ├── 2554. Maximum Number of Integers to Choose From a Range I └── main.py ├── 256. Paint House └── main.py ├── 2563. Count the Number of Fair Pairs └── main.py ├── 2577. Minimum Time to Visit a Cell In a Grid └── main.py ├── 2582. Pass the Pillow └── main.py ├── 2583. Kth Largest Sum in a Binary Tree └── main.py ├── 2597. The Number of Beautiful Subsets └── main.py ├── 26. Remove Duplicates from Sorted Array └── main.py ├── 260. Single Number III └── main.py ├── 2601. Prime Subtraction Operation └── main.py ├── 2610. Convert an Array Into a 2D Array With Conditions └── main.py ├── 2620. Counter └── main.js ├── 2621. Sleep └── main.js ├── 2623. Memoize └── main.py ├── 2626. Array Reduce Transformation └── main.js ├── 2627. Debounce └── main.js ├── 2629. Function Composition └── main.py ├── 2634. Filter Elements from Array └── main.js ├── 2635. Apply Transform Over Each Element in Array └── main.js ├── 264. Ugly Number II └── main.py ├── 2641. Cousins in Binary Tree II └── main.py ├── 2642. Design Graph With Shortest Path Calculator └── main.py ├── 265. Paint House II └── main.py ├── 2656. Maximum Sum With Exactly K Elements └── main.py ├── 2664. The Knight’s Tour └── main.py ├── 2665. Counter II └── main.js ├── 2666. Allow One Function Call └── main.js ├── 2667. Create Hello World Function └── main.js ├── 2678. Number of Senior Citizens └── main.py ├── 268. Missing Number └── main.py ├── 2684. Maximum Number of Moves in a Grid └── main.py ├── 2696. Minimum String Length After Removing Substrings └── main.py ├── 2697. Lexicographically Smallest Palindrome └── main.py ├── 2699. Modify Graph Edge Weights └── main.py ├── 27. Remove Element └── main.py ├── 2703. Return Length of Arguments Passed └── main.js ├── 2704. To Be Or Not To Be └── main.js ├── 2706. Buy Two Chocolates └── main.py ├── 2707. Extra Characters in a String └── main.py ├── 2709. Greatest Common Divisor Traversal └── main.py ├── 2710. Remove Trailing Zeros From a String └── main.py ├── 2723. Add Two Promises └── main.js ├── 2727. Is Object Empty └── main.js ├── 273. Integer to English Words └── main.py ├── 274. H-Index └── main.py ├── 2742. Painting the Walls └── main.py ├── 2743. Count Substrings Without Repeating Character └── main.py ├── 2744. Find Maximum Number of String Pairs └── main.py ├── 2751. Robot Collisions └── main.py ├── 276. Paint Fence └── main.py ├── 2769. Find the Maximum Achievable Number └── main.py ├── 2785. Sort Vowels in a String └── main.py ├── 279. Perfect Squares └── main.py ├── 2796. Repeat String └── main.js ├── 2798. Number of Employees Who Met the Target └── main.cpp ├── 28. Find the Index of the First Occurrence in a String └── main.py ├── 2802. Find The K-th Lucky Number └── main.py ├── 2807. Insert Greatest Common Divisors in Linked List └── main.py ├── 2810. Faulty Keyboard └── main.py ├── 2812. Find the Safest Path in a Grid └── main.py ├── 2816. Double a Number Represented as a Linked List └── main.py ├── 2824. Count Pairs Whose Sum is Less than Target └── main.py ├── 2825. Make String a Subsequence Using Cyclic Increments └── main.py ├── 2828. Check if a String Is an Acronym of Words └── main.py ├── 2838. Maximum Coins Heroes Can Collect └── main.py ├── 2864. Maximum Odd Binary Number └── main.py ├── 287. Find the Duplicate Number └── main.py ├── 2870. Minimum Number of Operations to Make Array Empty └── main.py ├── 2879. Display the First Three Rows └── main.py ├── 289. Game of Life └── main.py ├── 2894. Divisible and Non-divisible Sums Difference └── main.py ├── 290. Word Pattern └── main.py ├── 2908. Minimum Sum of Mountain Triplets I └── main.py ├── 291. Word Pattern II └── main.py ├── 2913. Subarrays Distinct Element Sum of Squares I └── main.py ├── 2914. Minimum Number of Changes to Make Binary String Beautiful └── main.py ├── 2915. Length of the Longest Subsequence That Sums to Target └── main.py ├── 2923. Find Champion I └── main.py ├── 2924. Find Champion II └── main.py ├── 2928. Distribute Candies Among Children I └── main.py ├── 2929. Distribute Candies Among Children II └── main.py ├── 293. Flip Game └── main.py ├── 2930. Number of Strings Which Can Be Rearranged to Contain Substring └── main.py ├── 2931. Maximum Spending After Buying Items └── main.py ├── 2932. Maximum Strong Pair XOR I └── main.py ├── 2933. High-Access Employees └── main.py ├── 2934. Minimum Operations to Maximize Last Elements in Arrays └── main.py ├── 2938. Separate Black and White Balls └── main.py ├── 2942. Find Words Containing Character └── main.py ├── 2943. Maximize Area of Square Hole in Grid └── main.py ├── 2944. Minimum Number of Coins for Fruits └── main.cpp ├── 2955. Number of Same-End Substrings └── main.py ├── 2958. Length of Longest Subarray With at Most K Frequency └── main.py ├── 296. Best Meeting Point └── main.py ├── 2962. Count Subarrays Where Max Element Appears at Least K Times └── main.py ├── 2966. Divide Array Into Arrays With Max Difference └── main.py ├── 2971. Find Polygon With the Largest Perimeter └── main.py ├── 2976. Minimum Cost to Convert String I └── main.py ├── 2981. Find Longest Special Substring That Occurs Thrice I └── main.py ├── 2997. Minimum Number of Operations to Make Array XOR Equal to K └── main.py ├── 3. Longest Substring Without Repeating Characters └── main.py ├── 30. Substring with Concatenation of All Words └── main.py ├── 300. Longest Increasing Subsequence └── main.py ├── 3005. Count Elements With Maximum Frequency └── main.py ├── 3011. Find if Array Can Be Sorted └── main.py ├── 3016. Minimum Number of Pushes to Type Word II └── main.py ├── 303. Range Sum Query - Immutable └── main.py ├── 3043. Find the Length of the Longest Common Prefix └── main.py ├── 305. Number of Islands II └── main.py ├── 3062. Winner of the Linked List Game └── main.py ├── 3063. Linked List Frequency └── main.py ├── 3068. Find the Maximum Sum of Node Values └── main.py ├── 3075. Maximize Happiness of Selected Children └── main.py ├── 3097. Shortest Subarray With OR at Least K II └── main.py ├── 310. Minimum Height Trees └── main.py ├── 3110. Score of a String └── main.py ├── 3133. Minimum Array End └── main.py ├── 3152. Special Array II └── main.py ├── 3163. String Compression III └── main.py ├── 3189. Minimum Moves to Get a Peaceful Board └── main.py ├── 320. Generalized Abbreviation └── main.py ├── 3217. Delete Nodes From Linked List Present in Array └── main.py ├── 3243. Shortest Distance After Road Addition Queries I └── main.py ├── 3254. Find the Power of K-Size Subarrays I └── main.py ├── 326. Power of Three └── main.py ├── 330. Patching Array └── main.py ├── 338. Counting Bits └── main.py ├── 34. Find First and Last Position of Element in Sorted Array └── main.py ├── 340. Longest Substring with At Most K Distinct Characters └── main.py ├── 341. Flatten Nested List Iterator └── main.py ├── 342. Power of Four └── main.py ├── 343. Integer Break └── main.py ├── 344. Reverse String └── main.py ├── 346. Moving Average from Data Stream └── main.py ├── 349. Intersection of Two Arrays └── main.py ├── 35. Search Insert Position └── main.py ├── 350. Intersection of Two Arrays II └── main.py ├── 351. Android Unlock Patterns └── main.py ├── 36. Valid Sudoku └── main.py ├── 368. Largest Divisible Subset └── main.py ├── 380. Insert Delete GetRandom O(1) └── main.py ├── 383. Ransom Note └── main.py ├── 386. Lexicographical Numbers └── main.py ├── 387. First Unique Character in a String └── main.py ├── 392. Is Subsequence └── main.py ├── 4. Median of Two Sorted Arrays └── main.py ├── 40. Combination Sum II └── main.py ├── 402. Remove K Digits └── main.py ├── 404. Sum of Left Leaves └── main.py ├── 409. Longest Palindrome └── main.py ├── 41. First Missing Positive └── main.py ├── 412. Fizz Buzz └── main.py ├── 42. Trapping Rain Water ├── main.py └── slow.py ├── 432. All O`one Data Structure └── main.py ├── 438. Find All Anagrams in a String └── main.py ├── 440. K-th Smallest in Lexicographical Order └── main.py ├── 442. Find All Duplicates in an Array └── main.py ├── 446. Arithmetic Slices II - Subsequence └── main.py ├── 45. Jump Game II └── main.py ├── 451. Sort Characters By Frequency └── main.py ├── 452. Minimum Number of Arrows to Burst Balloons └── main.py ├── 455. Assign Cookies └── main.py ├── 456. 132 Pattern └── main.py ├── 458. Max Dot Product of Two Subsequences └── main.py ├── 458. Poor Pigs └── main.py ├── 463. Island Perimeter └── main.py ├── 476. Number Complement └── main.py ├── 48. Rotate Image └── main.py ├── 485. Max Consecutive Ones └── main.py ├── 487. Max Consecutive Ones II └── main.py ├── 49. Group Anagrams └── main.py ├── 5. Longest Palindromic Substring └── main.py ├── 50. Pow(x, n) └── main.py ├── 501. Find Mode in Binary Search Tree └── main.py ├── 502. IPO └── main.py ├── 506. Relative Ranks └── main.py ├── 509. Fibonacci Number └── main.py ├── 513. Find Bottom Left Tree Value └── main.py ├── 514. Freedom Trail └── main.py ├── 515. Find Largest Value in Each Tree Row └── main.py ├── 523. Continuous Subarray Sum └── main.py ├── 525. Contiguous Array └── main.py ├── 535. Encode and Decode TinyURL └── main.py ├── 539. Minimum Time Difference └── main.py ├── 54. Spiral Matrix └── main.py ├── 543. Diameter of Binary Tree └── main.py ├── 55. Jump Game └── main.py ├── 552. Student Attendance Record II └── main.py ├── 557. Reverse Words in a String III └── main.py ├── 56. Merge Intervals └── main.py ├── 564. Find the Closest Palindrome └── main.py ├── 567. Permutation in String └── main.py ├── 57. Insert Interval └── main.py ├── 573. Squirrel Simulation └── main.py ├── 576. Out of Boundary Paths └── main.py ├── 577. Employee Bonus └── main.sql ├── 58. Length of Last Word └── main.py ├── 584. Find Customer Referee └── main.sql ├── 590. N-ary Tree Postorder Traversal └── main.py ├── 592. Fraction Addition and Subtraction └── main.py ├── 595. Big Countries └── main.sql ├── 6. Zigzag Conversion └── main.py ├── 606. Construct String from Binary Tree └── main.py ├── 620. Not Boring Movies └── main.sql ├── 621. Task Scheduler └── main.py ├── 623. Add One Row to Tree └── main.py ├── 624. Maximum Distance in Arrays └── main.py ├── 629. K Inverse Pairs Array └── main.py ├── 632. Smallest Range Covering Elements from K Lists └── main.py ├── 633. Sum of Square Numbers └── main.py ├── 641. Design Circular Deque └── main.py ├── 645. Set Mismatch └── main.py ├── 647. Palindromic Substrings └── main.py ├── 648. Replace Words └── main.py ├── 650. 2 Keys Keyboard └── main.py ├── 66. Plus One └── main.py ├── 661. Image Smoother └── main.py ├── 664. Strange Printer └── main.py ├── 666. Path Sum IV └── main.py ├── 67. Add Binary └── main.py ├── 670. Maximum Swap └── main.py ├── 678. Valid Parenthesis String └── main.py ├── 68. Text Justification └── main.py ├── 69. Sqrt(x) └── main.py ├── 7. Reverse Integer └── main.py ├── 70. Climbing Stairs └── main.py ├── 703. Kth Largest Element in a Stream └── main.py ├── 704. Binary Search └── main.py ├── 706. Design HashMap └── main.py ├── 709. To Lower Case └── main.py ├── 71. Simplify Path └── main.py ├── 713. Subarray Product Less Than K └── main.py ├── 719. Find K-th Smallest Pair Distance └── main.py ├── 725. Split Linked List in Parts └── main.py ├── 726. Number of Atoms └── main.py ├── 729. My Calendar I └── main.py ├── 73. Set Matrix Zeroes └── main.py ├── 731. My Calendar II └── main.py ├── 739. Daily Temperatures └── main.py ├── 746. Min Cost Climbing Stairs └── main.py ├── 75. Sort Colors └── main.py ├── 752. Open the Lock └── main.py ├── 76. Minimum Window Substring └── main.py ├── 771. Jewels and Stones └── main.py ├── 773. Sliding Puzzle └── main.py ├── 776. Split BST └── main.py ├── 779. K-th Symbol in Grammar └── main.py ├── 78. Subsets └── main.py ├── 786. K-th Smallest Prime Fraction └── main.py ├── 787. Cheapest Flights Within K Stops └── main.py ├── 79. Word Search └── main.py ├── 791. Custom Sort String └── main.py ├── 791. Find Center of Star Graph └── main.py ├── 796. Rotate String └── main.py ├── 8. String to Integer (atoi) └── main.py ├── 80. Remove Duplicates from Sorted Array II └── main.py ├── 804. Unique Morse Code Words └── main.py ├── 815. Bus Routes └── main.py ├── 823. Binary Trees With Factors └── main.py ├── 826. Most Profit Assigning Work └── main.py ├── 83. Remove Duplicates from Sorted List └── main.py ├── 834. Sum of Distances in Tree └── main.py ├── 840. Magic Squares In Grid └── main.py ├── 844. Backspace String Compare └── main.py ├── 846. Hand of Straights └── main.py ├── 85. Maximal Rectangle └── main.py ├── 857. Minimum Cost to Hire K Workers └── main.py ├── 860. Lemonade Change └── main.py ├── 861. Score After Flipping Matrix └── main.py ├── 862. Shortest Subarray with Sum at Least K └── main.py ├── 867. Transpose Matrix └── main.py ├── 872. Leaf-Similar Trees └── main.py ├── 874. Walking Robot Simulation └── main.py ├── 876. Middle of the Linked List └── main.py ├── 88. Merge Sorted Array └── main.py ├── 880. Decoded String at Index └── main.py ├── 881. Boats to Save People └── main.py ├── 884. Uncommon Words from Two Sentences └── main.py ├── 885. Count Pairs in Two Arrays └── main.py ├── 885. Spiral Matrix III └── main.py ├── 896. Monotonic Array └── main.py ├── 9. Palindrome Number └── main.py ├── 904. Fruit Into Baskets └── main.py ├── 905. Sort Array By Parity └── main.py ├── 907. Sum of Subarray Minimums └── main.py ├── 91. Decode Ways └── main.py ├── 912. Sort an Array └── main.py ├── 921. Minimum Add to Make Parentheses Valid └── main.py ├── 925. Long Pressed Name └── main.py ├── 929. Unique Email Addresses └── main.py ├── 930. Binary Subarrays With Sum └── main.py ├── 931. Minimum Falling Path Sum └── main.py ├── 935. Knight Dialer └── main.py ├── 938. Range Sum of BST └── main.py ├── 94. Binary Tree Inorder Traversal └── main.py ├── 942. DI String Match └── main.py ├── 945. Minimum Increment to Make Array Unique └── main.py ├── 947. Most Stones Removed with Same Row or Column └── main.py ├── 948. Bag of Tokens └── main.py ├── 950. Reveal Cards In Increasing Order └── main.py ├── 951. Flip Equivalent Binary Trees └── main.py ├── 959. Regions Cut By Slashes └── main.py ├── 962. Maximum Width Ramp └── main.py ├── 974. Subarray Sums Divisible by K └── main.py ├── 977. Squares of a Sorted Array └── main.py ├── 979. Distribute Coins in Binary Tree └── main.py ├── 980. Find Unique Binary String └── main.py ├── 988. Smallest String Starting From Leaf └── main.py ├── 992. Subarrays with K Different Integers └── main.py ├── 995. Minimum Number of K Consecutive Bit Flips └── main.py ├── 997. Find the Town Judge └── main.py └── README.md /099. Two Sum Less Than K/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSumLessThanK(self, nums: List[int], k: int) -> int: 3 | res = [] 4 | for i in range(len(nums)-1): 5 | for j in range(i+1,len(nums)): 6 | if nums[i] + nums[j] < k: 7 | res.append(nums[i] + nums[j]) 8 | return -1 if not len(res) else max(res) 9 | -------------------------------------------------------------------------------- /1. Two Sum/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums: List[int], target: int) -> List[int]: 3 | for i,x in enumerate(nums): 4 | for j,y in enumerate(nums[i+1:],i+1): 5 | if x+y == target: 6 | return [i,j] 7 | -------------------------------------------------------------------------------- /100. Same Tree/main.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isSameTree(self, p, q): 3 | if not p and not q: 4 | return True 5 | if not p or not q: 6 | return False 7 | return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) 8 | -------------------------------------------------------------------------------- /1002. Find Common Characters/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def commonChars(self, words: List[str]) -> List[str]: 3 | if len(words) < 2: 4 | return words 5 | res = [] 6 | word1 = set(words[0]) 7 | for char in word1: 8 | frequency = min([word.count(char) for word in words]) 9 | res += [char] * frequency 10 | return res 11 | -------------------------------------------------------------------------------- /1004. Max Consecutive Ones III/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestOnes(self, nums: List[int], k: int) -> int: 3 | left = 0 4 | right = 0 5 | for right in range(len(nums)): 6 | 7 | k -= 1 - nums[right] 8 | 9 | if k < 0: 10 | k += 1 - nums[left] 11 | left += 1 12 | return right - left + 1 13 | -------------------------------------------------------------------------------- /1021. Remove Outermost Parentheses/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeOuterParentheses(self, s: str) -> str: 3 | res, opened = [], 0 4 | for c in s: 5 | if c == '(' and opened > 0: res.append(c) 6 | if c == ')' and opened > 1: res.append(c) 7 | opened += 1 if c == '(' else -1 8 | 9 | return "".join(res) 10 | -------------------------------------------------------------------------------- /1025. Divisor Game/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def divisorGame(self, n: int) -> bool: 3 | return not n%2 4 | -------------------------------------------------------------------------------- /1038. Binary Search Tree to Greater Sum Tree/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def bstToGst(self, root: TreeNode) -> TreeNode: 3 | self.val = 0 4 | 5 | def dfs(node): 6 | if not node: 7 | return 8 | 9 | dfs(node.right) 10 | self.val += node.val 11 | node.val = self.val 12 | dfs(node.left) 13 | 14 | dfs(root) 15 | return roo 16 | -------------------------------------------------------------------------------- /1043. Partition Array for Maximum Sum/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSumAfterPartitioning(self, a: List[int], k: int) -> int: 3 | @cache 4 | def calc(i, m, l): 5 | if i != len(a): 6 | m = max(m,a[i]) 7 | l += 1 8 | # end of part 9 | r = m*l + calc(i+1, 0, 0) 10 | if l < k: 11 | # continue part 12 | r = max(r, calc(i+1, m, l)) 13 | 14 | return r 15 | 16 | return m*l 17 | 18 | return calc(0, 0, 0) 19 | -------------------------------------------------------------------------------- /1048. Longest String Chain/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestStrChain(self, words: List[str]) -> int: 3 | #words.sort(key=len) 4 | d = defaultdict(int) 5 | 6 | for word in sorted(words,key = len): 7 | d[word] = 1 8 | for i in range(len(word)): 9 | w = word[:i] + word[i+1:] 10 | 11 | if w in d: 12 | d[word] = max(d[word], d[w] +1) 13 | 14 | return max(d.values()) -------------------------------------------------------------------------------- /1051. Height Checker/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def heightChecker(self, heights: List[int]) -> int: 3 | res = 0 4 | for i, x in enumerate(sorted(heights)): 5 | if not x == heights[i]: 6 | res +=1 7 | return res 8 | -------------------------------------------------------------------------------- /1062. Longest Repeating Substring/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestRepeatingSubstring(self, s: str) -> int: 3 | n = len(s) 4 | ans = 0 5 | for i in range(1,n): 6 | if s[i-ans:i+1] in s[:i]: ans+=1 7 | return ans 8 | 9 | -------------------------------------------------------------------------------- /1068. Product Sales Analysis I/main.py: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | /* Write your T-SQL query statement below */ 3 | SELECT p.product_name,s.year,s.price 4 | from Sales s,Product p 5 | where p.product_id = s.product_id 6 | -------------------------------------------------------------------------------- /108. Convert Sorted Array to Binary Search Tree/main.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 sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]: 9 | if len(nums) == 0: 10 | return None 11 | mid = len(nums)//2 12 | root = TreeNode(nums[mid]) 13 | root.left = self.sortedArrayToBST(nums[:mid]) 14 | root.right = self.sortedArrayToBST(nums[mid+1:]) 15 | return root 16 | -------------------------------------------------------------------------------- /1099. Two Sum Less Than K/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSumLessThanK(self, nums: List[int], k: int) -> int: 3 | res = -1 4 | for i in range(len(nums)-1): 5 | for j in range(i+1,len(nums)): 6 | if nums[i] + nums[j] < k: 7 | res = max(res,nums[i] + nums[j]) 8 | return res 9 | -------------------------------------------------------------------------------- /11. Container With Most Water/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxArea(self, H: List[int]) -> int: 3 | ans = 0 4 | left = 0 5 | right = len(H)-1 6 | while left < right: 7 | area = (right-left) * min(H[left],H[right]) 8 | ans = max(area,ans) 9 | if H[left] > H[right]: 10 | right -= 1 11 | else: 12 | left += 1 13 | return ans 14 | -------------------------------------------------------------------------------- /1105. Filling Bookcase Shelves/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | 3 | def minHeightShelves(self, books: List[List[int]], shelfWidth: int) -> int: 4 | 5 | n = len(books) 6 | 7 | f = [0] * (n + 1) 8 | 9 | for i, (w, h) in enumerate(books, 1): 10 | 11 | f[i] = f[i - 1] + h 12 | 13 | for j in range(i - 1, 0, -1): 14 | 15 | w += books[j - 1][0] 16 | 17 | if w > shelfWidth: 18 | 19 | break 20 | 21 | h = max(h, books[j - 1][1]) 22 | 23 | f[i] = min(f[i], f[j - 1] + h) 24 | 25 | return f[n] 26 | -------------------------------------------------------------------------------- /1108. Defanging an IP Address/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def defangIPaddr(self, addr: str) -> str: 3 | return addr.replace(".","[.]") 4 | -------------------------------------------------------------------------------- /1110. Delete Nodes And Return Forest/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def delNodes(self, root: Optional[TreeNode], to_delete: List[int]) -> List[TreeNode]: 3 | s = set(to_delete) 4 | res = [] 5 | def dfs(root, flag): 6 | if not root: return None 7 | toDelete = (root.val in s) 8 | root.left = dfs(root.left, toDelete) 9 | root.right = dfs(root.right, toDelete) 10 | if not toDelete and flag: res.append(root) 11 | return None if toDelete else root 12 | dfs(root, True) 13 | return res 14 | 15 | -------------------------------------------------------------------------------- /1119. Remove Vowels from a String/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeVowels(self, s: str) -> str: 3 | return re.sub('[aeiou]', '', s) 4 | return re.subn("a|e|i|o|u", "", s)[0] 5 | return ''.join(c for c in S if c not in 'aeiou') 6 | return ''.join(list(filter(lambda x:x not in 'aeiou',S))) 7 | return s.replace('a','').replace('e','').replace('i','').replace('o','').replace('u','') 8 | -------------------------------------------------------------------------------- /1122. Relative Sort Array/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def relativeSortArray(self, arr1, arr2): 3 | result = [] 4 | 5 | for i in range(len(arr2)): 6 | for j in range(len(arr1)): 7 | if arr1[j] == arr2[i]: 8 | result.append(arr1[j]) 9 | arr1[j] = -1 10 | 11 | arr1.sort() 12 | 13 | for num in arr1: 14 | if num != -1: 15 | result.append(num) 16 | 17 | return result 18 | 19 | -------------------------------------------------------------------------------- /1133. Largest Unique Number/main.py: -------------------------------------------------------------------------------- 1 | # nums - integer array 2 | # 3 | # return the largest in that only occurs once 4 | # or -1 if it doesn't exist 5 | 6 | from collections import defaultdict 7 | class Solution: 8 | def largestUniqueNumber(self, nums: List[int]) -> int: 9 | num_frequency = defaultdict(int) 10 | largest_uniq_num = -1 11 | 12 | for num in nums: 13 | num_frequency[num] += 1 14 | 15 | for num, freq in num_frequency.items(): 16 | if freq == 1: 17 | largest_uniq_num = max(largest_uniq_num, num) 18 | 19 | return largest_uniq_num 20 | 21 | -------------------------------------------------------------------------------- /1137. N-th Tribonacci Number/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def tribonacci(self, n: int) -> int: 3 | if n < 2: 4 | return n 5 | 6 | dp = [0, 1, 1] 7 | 8 | for i in range(3, n + 1): 9 | next_val = dp[0] + dp[1] + dp[2] 10 | dp[0], dp[1], dp[2] = dp[1], dp[2], next_val 11 | 12 | return dp[2] 13 | -------------------------------------------------------------------------------- /1141. User Activity for the Past 30 Days I/main.sql: -------------------------------------------------------------------------------- 1 | SELECT activity_date AS day, COUNT(DISTINCT user_id) AS active_users 2 | FROM Activity 3 | WHERE (activity_date > "2019-06-27" AND activity_date <= "2019-07-27") 4 | GROUP BY activity_date; 5 | -------------------------------------------------------------------------------- /1148. Article Views I/main.sql: -------------------------------------------------------------------------------- 1 | select distinct author_id as id 2 | from Views 3 | Where author_id = viewer_id 4 | order by author_id 5 | -------------------------------------------------------------------------------- /1155. Number of Dice Rolls With Target Sum/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | @cache 3 | def numRollsToTarget(self, n: int, k: int, t: int) -> int: 4 | return sum(self.numRollsToTarget(n-1, k, t-f) for f in range(1, k+1))%(10**9+7) if n else t == 0 5 | -------------------------------------------------------------------------------- /1160. Find Words That Can Be Formed by Characters/main.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | class Solution: 3 | def countCharacters(self, words: List[str], chars: str) -> int: 4 | cChars = Counter(chars) 5 | return sum(len(w) for w in words if not (Counter(w) - cChars)) 6 | -------------------------------------------------------------------------------- /1165. Single-Row Keyboard/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def calculateTime(self, keyboard: str, word: str) -> int: 3 | prev = 0 4 | res = 0 5 | for c in word: 6 | i = keyboard.index(c) 7 | res += abs(prev - i) 8 | prev = i 9 | return res 10 | -------------------------------------------------------------------------------- /1167. Minimum Cost to Connect Sticks/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def connectSticks(self, sticks: List[int]) -> int: 3 | ans = 0 4 | while len(sticks) != 1: 5 | sticks.sort() 6 | sv = sticks[0] + sticks[1] 7 | sticks = sticks[2:] + [sv] 8 | ans += sv 9 | return ans 10 | -------------------------------------------------------------------------------- /118. Pascal's Triangle/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generate(self, numRows: int) -> List[List[int]]: 3 | ans = [[1]] 4 | for i in range(1, numRows): 5 | row = [1] * (i + 1) 6 | for j in range(1, len(row) - 1): 7 | row[j] = ans[i - 1][j - 1] + ans[i - 1][j] 8 | ans.append(row) 9 | return ans 10 | -------------------------------------------------------------------------------- /1180. Count Substrings with Only One Distinct Letter/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countLetters(self, S: str) -> int: 3 | count = total = 1 4 | for i in range(len(S)-1): 5 | if S[i] == S[i+1]: 6 | count += 1 7 | else: 8 | count = 1 9 | total += count 10 | return total 11 | -------------------------------------------------------------------------------- /1185. Day of the Week/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def dayOfTheWeek(self, day: int, month: int, year: int) -> str: 3 | return date(year, month, day).strftime("%A") 4 | -------------------------------------------------------------------------------- /119. Pascal's Triangle II/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getRow(self, n: int) -> List[int]: 3 | ans = [1] 4 | for k in range(1, n + 1): 5 | ans.append(ans[k-1] * (n - k + 1) // k) 6 | return ans 7 | -------------------------------------------------------------------------------- /12. Integer to Roman/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def intToRoman(self, num: int) -> str: 3 | m = ["", "M", "MM", "MMM"] 4 | c = ["", "C", "CC", "CCC", "CD", "D","DC", "DCC", "DCCC", "CM"] 5 | x = ["", "X", "XX", "XXX", "XL", "L","LX", "LXX", "LXXX", "XC"] 6 | i = ["", "I", "II", "III", "IV", "V","VI", "VII", "VIII", "IX"] 7 | ans = m[num // 1000] 8 | ans += c[(num%1000) // 100] 9 | ans += x[(num%100) // 10] 10 | ans += i[(num%10)] 11 | 12 | return ans 13 | -------------------------------------------------------------------------------- /1207. Unique Number of Occurrences/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def uniqueOccurrences(self, arr: List[int]) -> bool: 3 | hm = Counter(arr).values() 4 | return len(set(hm))==len(hm) 5 | -------------------------------------------------------------------------------- /1208. Get Equal Substrings Within Budget/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def equalSubstring(self, s: str, t: str, maxCost: int) -> int: 3 | res: int = 0 4 | cur_cost: int = 0 5 | cur_start: int = 0 6 | 7 | for last_ind in range(len(s)): 8 | cur_cost += abs(ord(s[last_ind]) - ord(t[last_ind])) 9 | 10 | while cur_cost > maxCost: 11 | cur_cost -= abs(ord(s[cur_start]) - ord(t[cur_start])) 12 | cur_start += 1 13 | 14 | if last_ind - cur_start + 1 > res: 15 | res = last_ind - cur_start + 1 16 | 17 | return res 18 | -------------------------------------------------------------------------------- /1220. Count Vowels Permutation/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countVowelPermutation(self, n: int) -> int: 3 | MOD = 1000000007 4 | a = e = i = o = u = 1 5 | 6 | for length in range(2, n + 1): 7 | new_a = (e + u + i) % MOD 8 | new_e = (a + i) % MOD 9 | new_i = (e + o) % MOD 10 | new_o = i % MOD 11 | new_u = (o + i) % MOD 12 | 13 | a, e, i, o, u = new_a, new_e, new_i, new_o, new_u 14 | 15 | count = (a + e + i + o + u) % MOD 16 | return int(count) 17 | -------------------------------------------------------------------------------- /1221. Split a String in Balanced Strings/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def balancedStringSplit(self, s: str) -> int: 3 | count, ans = 0, 0 4 | 5 | for char in s: 6 | count += 1 if char == 'R' else -1 7 | ans += count == 0 8 | 9 | return ans 10 | -------------------------------------------------------------------------------- /1230. Toss Strange Coins/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def probabilityOfHeads(self, prob: List[float], target: int) -> float: 3 | 4 | length = len(prob) - target + 1 5 | 6 | dp, comp = [1.0] * length, [1-p for p in prob] 7 | for i in range(length-1): 8 | dp[i+1] = dp[i] * comp[i] 9 | 10 | for i in range(target): 11 | dp[0] *= prob[0] 12 | for j in range(1, length): 13 | dp[j] = dp[j-1] * comp[j] + dp[j] * prob[j] 14 | prob.pop(0), comp.pop(0) 15 | 16 | return dp[-1] 17 | -------------------------------------------------------------------------------- /1233. Remove Sub-Folders from the Filesystem/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeSubfolders(self, folder: List[str]) -> List[str]: 3 | folder.sort() 4 | 5 | result = [] 6 | for f in folder: 7 | if not result or not f.startswith(result[-1] + '/'): 8 | result.append(f) 9 | 10 | return result 11 | -------------------------------------------------------------------------------- /1235. Maximum Profit in Job Scheduling/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: 3 | 4 | endTime, startTime, profit = zip(*sorted(zip(endTime, startTime, profit))) 5 | 6 | dp = [profit[0]] + ([0] * ((n := len(profit))-1)) 7 | 8 | for i in range(1, n): 9 | 10 | index = bisect_right(endTime, startTime[i]) - 1 11 | dp[i] = max(dp[i - 1], (dp[index] if index >= 0 else 0) + profit[i]) 12 | 13 | return dp[-1] 14 | -------------------------------------------------------------------------------- /1248. Count Number of Nice Subarrays/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numberOfSubarrays(self, nums: List[int], k: int) -> int: 3 | for i in range(len(nums)): 4 | nums[i] %= 2 5 | 6 | prefix_count = [0] * (len(nums) + 1) 7 | prefix_count[0] = 1 8 | s = 0 9 | ans = 0 10 | 11 | for num in nums: 12 | s += num 13 | if s >= k: 14 | ans += prefix_count[s - k] 15 | prefix_count[s] += 1 16 | 17 | return ans 18 | -------------------------------------------------------------------------------- /1249. Minimum Remove to Make Valid Parentheses/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minRemoveToMakeValid(self, s: str) -> str: 3 | t=[] 4 | p=0 5 | for c in s: 6 | p+=(c=='(')-(c==')') 7 | if p>=0: t.append(c) 8 | else: p=0 9 | p=0 10 | q=deque() 11 | for c in t[::-1]: 12 | p+=(c=='(')-(c==')') 13 | if p<=0: q.appendleft(c) 14 | else: p=0 15 | return ''.join(q) 16 | -------------------------------------------------------------------------------- /125. Valid Palindrome/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPalindrome(self, s: str) -> bool: 3 | ans = '' 4 | for c in s.lower(): 5 | if c.isalnum(): 6 | ans += c 7 | 8 | return ans==ans[::-1] 9 | -------------------------------------------------------------------------------- /1251. Average Selling Price/main.sql: -------------------------------------------------------------------------------- 1 | SELECT p.product_id, IFNULL(ROUND(SUM(units*price)/SUM(units),2),0) AS average_price 2 | FROM Prices p LEFT JOIN UnitsSold u 3 | ON p.product_id = u.product_id AND 4 | u.purchase_date BETWEEN start_date AND end_date 5 | group by product_id 6 | -------------------------------------------------------------------------------- /1265. Print Immutable Linked List in Reverse/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def printLinkedListInReverse(self, head: 'ImmutableListNode') -> None: 3 | if head is not None: 4 | self.printLinkedListInReverse(head.getNext()) 5 | head.printValue() 6 | -------------------------------------------------------------------------------- /1266. Minimum Time Visiting All Points/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minTimeToVisitAllPoints(self, p: List[List[int]]) -> int: 3 | return sum(max(abs(p[i-1][0]-p[i][0]),abs(p[i-1][1]-p[i][1])) for i in range(1,len(p))) 4 | -------------------------------------------------------------------------------- /1269. Number of Ways to Stay in the Same Place After Some Steps/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numWays(self, steps: int, arrLen: int) -> int: 3 | m = steps 4 | n = min(steps // 2 + 1, arrLen) 5 | dp = [[0] * n for _ in range(m + 1)] 6 | dp[0][0] = 1 7 | for i in range(1, m + 1): 8 | for j in range(n): 9 | dp[i][j] = dp[i-1][j] 10 | if j > 0: 11 | dp[i][j] += dp[i-1][j-1] 12 | if j < n - 1: 13 | dp[i][j] += dp[i-1][j+1] 14 | return dp[m][0] % (10 ** 9 + 7) 15 | -------------------------------------------------------------------------------- /128. Longest Consecutive Sequence/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestConsecutive(self, nums: List[int]) -> int: 3 | if len(nums) == 1: 4 | return 1 5 | if len(nums) == 0: 6 | return 0 7 | 8 | temp = sorted(list(set(nums))) 9 | i = 0 10 | j = 1 11 | count = 1 12 | curr = 1 13 | 14 | while j < len(temp): 15 | if temp[j] - 1 == temp[i]: 16 | curr += 1 17 | count = max(curr, count) 18 | else: 19 | curr = 1 20 | i = j 21 | j += 1 22 | return count 23 | -------------------------------------------------------------------------------- /1280. Students and Examinations/main.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | s.student_id, 3 | s.student_name, 4 | sub.subject_name, 5 | COUNT(e.subject_name) AS attended_exams 6 | FROM 7 | Students s 8 | CROSS JOIN 9 | Subjects sub 10 | LEFT JOIN 11 | Examinations e 12 | ON s.student_id = e.student_id AND sub.subject_name = e.subject_name 13 | GROUP BY 14 | s.student_id, 15 | s.student_name, 16 | sub.subject_name 17 | ORDER BY 18 | s.student_id, 19 | sub.subject_name; 20 | -------------------------------------------------------------------------------- /1287. Element Appearing More Than 25% In Sorted Array/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findSpecialInteger(self, arr: List[int]) -> int: 3 | more_than = len(arr) * 0.25 4 | for x in set(arr): 5 | if arr.count(x) > more_than: 6 | return x 7 | -------------------------------------------------------------------------------- /129. Sum Root to Leaf Numbers/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sumNumbers(self, root: TreeNode) -> int: 3 | def dfs(node, path): 4 | nonlocal ans 5 | if not node: 6 | return 7 | if not node.left and not node.right: 8 | ans += path * 10 + node.val 9 | return 10 | dfs(node.left, path * 10 + node.val) 11 | dfs(node.right, path * 10 + node.val) 12 | 13 | ans = 0 14 | dfs(root, 0) 15 | return ans 16 | -------------------------------------------------------------------------------- /1291. Sequential Digits/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sequentialDigits(self, low, high): 3 | a = [] 4 | 5 | for i in range(1, 10): 6 | num = i 7 | next_digit = i + 1 8 | 9 | while num <= high and next_digit <= 9: 10 | num = num * 10 + next_digit 11 | if low <= num <= high: 12 | a.append(num) 13 | next_digit += 1 14 | 15 | a.sort() 16 | return a 17 | 18 | -------------------------------------------------------------------------------- /13. Roman to Integer/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def romanToInt(self, s: str) -> int: 3 | ans = 0 4 | r = ['I', 'IV','V', 'IX','X', 'XL','L', 'XC','C', 'CD','D','CM', 'M'] 5 | n = [1,4, 5, 9,10,40, 50, 90,100, 400,500,900, 1000] 6 | i = 0 7 | while i < len(s): 8 | try: 9 | ans += n[r.index(s[i]+s[i+1])] 10 | i+=1 11 | except: 12 | ans += n[r.index(s[i])] 13 | i+=1 14 | return ans 15 | -------------------------------------------------------------------------------- /1323. Maximum 69 Number/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximum69Number (self, num: int) -> int: 3 | sv = list(str(num)) 4 | for i,x in enumerate(sv): 5 | if x == "6": 6 | sv[i] = "9" 7 | break 8 | return int("".join(sv)) 9 | -------------------------------------------------------------------------------- /134. Gas Station/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: 3 | if sum(gas) < sum(cost): 4 | return -1 5 | n = len(gas) 6 | tank = 0 7 | ans = 0 8 | 9 | for i in range(n): 10 | tank += gas[i] - cost[i] 11 | if tank < 0: 12 | tank = 0 13 | ans = i+1 14 | 15 | return ans 16 | -------------------------------------------------------------------------------- /1346. Check If N and Its Double Exist/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkIfExist(self, arr: List[int]) -> bool: 3 | # Use a set to track visited numbers 4 | seen = set() 5 | for num in arr: 6 | # Check if the current number's double or half (if even) is in the set 7 | if 2 * num in seen or (num % 2 == 0 and num // 2 in seen): 8 | return True 9 | # Add the current number to the set 10 | seen.add(num) 11 | return False 12 | -------------------------------------------------------------------------------- /1347. Minimum Number of Steps to Make Two Strings Anagram/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minSteps(self, s: str, t: str) -> int: 3 | for x in s: 4 | try: 5 | i = t.index(x) 6 | t = t[:i] + t[i+1:] 7 | del t[i] 8 | except: 9 | pass 10 | print(t) 11 | return len(t) 12 | -------------------------------------------------------------------------------- /135. Candy/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def candy(self, ratings: List[int]) -> int: 3 | n = len(ratings) 4 | ans = [1] * len(ratings) 5 | for i in range(n-1): 6 | if ratings[i] < ratings[i+1]: 7 | ans[i+1] = max(1 + ans[i], ans[i+1]) 8 | for i in range(n-2,-1,-1): 9 | if ratings[i+1] < ratings[i]: 10 | ans[i] = max(1 + ans[i+1], ans[i]) 11 | print(ans) 12 | return sum(ans) 13 | -------------------------------------------------------------------------------- /1356. Sort Integers by The Number of 1 Bits/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortByBits(self, arr: List[int]) -> List[int]: 3 | return sorted(arr, key=lambda x: (bin(x).count('1'), x)) 4 | -------------------------------------------------------------------------------- /136. Single Number/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def singleNumber(self, nums: List[int]) -> int: 3 | set_nums = set(nums) 4 | for x in set_nums: 5 | if nums.count(x) == 1: 6 | return x 7 | -------------------------------------------------------------------------------- /1365. How Many Numbers Are Smaller Than the Current Number/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: 3 | return [sorted(nums).index(a) for a in nums] 4 | -------------------------------------------------------------------------------- /1367. Linked List in Binary Tree/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isSubPath(self, head, root): 3 | def checkPath(head, root): 4 | if not head: return True 5 | if not root or head.val != root.val: return False 6 | return checkPath(head.next, root.left) or checkPath(head.next, root.right) 7 | 8 | if not root: return False 9 | if checkPath(head, root): return True 10 | return self.isSubPath(head, root.left) or self.isSubPath(head, root.right) 11 | -------------------------------------------------------------------------------- /137. Single Number II/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def singleNumber(self, nums: List[int]) -> int: 3 | set_nums = set(nums) 4 | for x in set_nums: 5 | if nums.count(x) == 1: 6 | return x 7 | -------------------------------------------------------------------------------- /1378. Replace Employee ID With The Unique Identifier/main.sql: -------------------------------------------------------------------------------- 1 | SELECT unique_id, name 2 | FROM Employees e 3 | LEFT JOIN EmployeeUNI eui ON e.id = eui.id; 4 | -------------------------------------------------------------------------------- /14. Longest Common Prefix/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestCommonPrefix(self, strs: List[str]) -> str: 3 | pref= "" 4 | sv ="" 5 | for i,x in enumerate(strs[0]): 6 | sv += x 7 | for j in range(1, len(strs)): 8 | if strs[j][:i+1] != sv: 9 | return pref 10 | pref = sv 11 | return pref 12 | -------------------------------------------------------------------------------- /1402. Reducing Dishes/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSatisfaction(self, satisfaction: List[int]) -> int: 3 | satisfaction.sort(reverse=True) 4 | result, prefix, sum_dishes = 0, 0, 0 5 | 6 | for i in range(len(satisfaction)): 7 | prefix += satisfaction[i] 8 | sum_dishes += prefix 9 | result = max(result, sum_dishes) 10 | 11 | return result 12 | -------------------------------------------------------------------------------- /1404. Number of Steps to Reduce a Number in Binary Representation to One/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numSteps(self, s: str) -> int: 3 | steps = 0 4 | carry = 0 5 | n = len(s) - 1 6 | for i in range(n, 0, -1): 7 | if int(s[i]) + carry == 1: 8 | carry = 1 9 | steps += 2 10 | else: 11 | steps += 1 12 | return steps + carry 13 | 14 | 15 | -------------------------------------------------------------------------------- /141. Linked List Cycle/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hasCycle(self, head: Optional[ListNode]) -> bool: 3 | fast = head 4 | while fast and fast.next: 5 | head = head.next 6 | fast = fast.next.next 7 | if head is fast: 8 | return True 9 | return False 10 | -------------------------------------------------------------------------------- /1422. Maximum Score After Splitting a String/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxScore(self, s: str) -> int: 3 | return s.count('1') + max(accumulate((c=='0')-(c=='1') for c in s[:-1])) 4 | -------------------------------------------------------------------------------- /1424. Diagonal Traverse II/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]: 3 | diagonal = defaultdict(list) 4 | 5 | for i in range(len(nums)): 6 | for j in range(len(nums[i])): 7 | diagonal[i+j] = [nums[i][j]] + diagonal[i+j] 8 | 9 | res = [] 10 | for _, val in diagonal.items(): 11 | res += val 12 | return res 13 | -------------------------------------------------------------------------------- /1425. Constrained Subsequence Sum/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def constrainedSubsetSum(self, nums: List[int], k: int) -> int: 3 | maxSum = nums[0] 4 | MSL = deque() 5 | 6 | for i in range(len(nums)): 7 | nums[i] += MSL[0] if MSL else 0 8 | maxSum = max(maxSum, nums[i]) 9 | while MSL and nums[i] > MSL[-1]: 10 | MSL.pop() 11 | if nums[i] > 0: 12 | MSL.append(nums[i]) 13 | if i >= k and MSL and MSL[0] == nums[i - k]: 14 | MSL.popleft() 15 | 16 | return maxSum 17 | -------------------------------------------------------------------------------- /1431. Kids With the Greatest Number of Candies/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]: 3 | return [x+extraCandies >= max(candies)for x in candies] 4 | -------------------------------------------------------------------------------- /1436. Destination City/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def destCity(self, paths: List[List[str]]) -> str: 3 | maps = {} 4 | for start, end in paths: 5 | maps[start] = end 6 | ans = paths[0][0] 7 | while True: 8 | try: 9 | ans = maps[ans] 10 | except: 11 | return ans 12 | -------------------------------------------------------------------------------- /1441. Build an Array With Stack Operations/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def buildArray(self, target: List[int], n: int) -> List[str]: 3 | ans=[] 4 | best=0 5 | for i in range(1,n+1): 6 | if i in target: 7 | ans.append("Push") 8 | best=max(len(ans),best) 9 | else: 10 | ans.append("Push") 11 | ans.append("Pop") 12 | return ans[:best] 13 | -------------------------------------------------------------------------------- /145. Binary Tree Postorder Traversal/main.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: 4 | res = [] 5 | def pot(root): 6 | if root: 7 | pot(root.left) 8 | pot(root.right) 9 | res.append(root.val) 10 | pot(root) 11 | return res 12 | -------------------------------------------------------------------------------- /1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPrefixOfWord(self, sentence: str, searchWord: str) -> int: 3 | # Split the sentence into words 4 | words = sentence.split() 5 | 6 | # Iterate through each word along with its index 7 | for index, word in enumerate(words, start=1): # Start indexing from 1 8 | # Check if the searchWord is a prefix of the current word 9 | if word.startswith(searchWord): 10 | return index 11 | 12 | # If no word matches, return -1 13 | return -1 14 | -------------------------------------------------------------------------------- /1457. Pseudo-Palindromic Paths in a Binary Tree/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def pseudoPalindromicPaths(self, root): 3 | count = 0 4 | stack = [(root, 0)] 5 | 6 | while stack: 7 | node, path = stack.pop() 8 | 9 | if node: 10 | path ^= 1 << node.val 11 | 12 | if not node.left and not node.right: 13 | if path & (path - 1) == 0: 14 | count += 1 15 | else: 16 | stack.append((node.right, path)) 17 | stack.append((node.left, path)) 18 | 19 | return count 20 | 21 | -------------------------------------------------------------------------------- /1460. Make Two Arrays Equal by Reversing Subarrays/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canBeEqual(self, target: List[int], arr: List[int]) -> bool: 3 | return Counter(target) == Counter(arr) 4 | -------------------------------------------------------------------------------- /1463. Cherry Pickup II/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def cherryPickup(self, grid: List[List[int]]) -> int: 3 | m=len(grid) 4 | n=len(grid[0]) 5 | @cache 6 | def dp(i,j,k): 7 | if not 0<=j<=k int: 3 | nums = sorted(nums) 4 | return (nums[-1]-1) * (nums[-2]-1) 5 | -------------------------------------------------------------------------------- /1470. Shuffle the Array/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def shuffle(self, nums: List[int], n: int) -> List[int]: 3 | res = [] 4 | for i in range(n): 5 | res.append(nums[i]) 6 | res.append(nums[n+i]) 7 | return res 8 | -------------------------------------------------------------------------------- /1480. Running Sum of 1d Array/main.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] runningSum(int[] nums) { 3 | for (int i = 1; i < nums.length; i++) { 4 | nums[i] += nums[i-1]; 5 | } 6 | return nums; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /1481. Least Number of Unique Integers after K Removals/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int: 3 | cntr = Counter(arr) 4 | set_arr = set(arr) 5 | least_common_to_most = sorted(cntr, key=lambda x: cntr[x]) 6 | i = 0 7 | 8 | while k > 0: 9 | if cntr[least_common_to_most[i]] <= k: 10 | set_arr.remove(least_common_to_most[i]) 11 | k -= cntr[least_common_to_most[i]] 12 | i += 1 13 | else: 14 | break 15 | 16 | return len(set_arr) 17 | -------------------------------------------------------------------------------- /1496. Path Crossing/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPathCrossing(self, path: str) -> bool: 3 | moves = { 4 | "N": (0, 1), 5 | "S": (0, -1), 6 | "W": (-1, 0), 7 | "E": (1, 0) 8 | } 9 | 10 | visited = {(0, 0)} 11 | x = 0 12 | y = 0 13 | 14 | for c in path: 15 | dx, dy = moves[c] 16 | x += dx 17 | y += dy 18 | 19 | if (x, y) in visited: 20 | return True 21 | 22 | visited.add((x, y)) 23 | 24 | return False 25 | -------------------------------------------------------------------------------- /1497. Check If Array Pairs Are Divisible by k/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canArrange(self, arr: List[int], k: int) -> bool: 3 | freq = [0] * k 4 | 5 | for num in arr: 6 | remainder = (num % k + k) % k 7 | freq[remainder] += 1 8 | 9 | if freq[0] % 2 != 0: 10 | return False 11 | 12 | for i in range(1, k // 2 + 1): 13 | if freq[i] != freq[k - i]: 14 | return False 15 | 16 | return True 17 | -------------------------------------------------------------------------------- /15. 3Sum/brute-force.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def threeSum(self, nums: List[int]) -> List[List[int]]: 3 | n = len(nums) 4 | setn = set({}) 5 | nums = sorted(nums) 6 | for i in range(n): 7 | for j in range(i+1,n): 8 | for k in range(j+1,n): 9 | if nums[i] + nums[j] + nums[k] == 0: 10 | sv = [nums[i], nums[j], nums[k]] 11 | setn.add(tuple(sv)) 12 | return setn 13 | -------------------------------------------------------------------------------- /150. Evaluate Reverse Polish Notation/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def evalRPN(self, tokens: List[str]) -> int: 3 | stack = [] 4 | ops = { 5 | "+": lambda a, b: a + b, 6 | "-": lambda a, b: b - a, 7 | "/": lambda a, b: int(b / a), 8 | "*": lambda a, b: a * b 9 | } 10 | for i in tokens: 11 | if i in ops: 12 | stack.append(ops[i](stack.pop(), stack.pop())) 13 | else: 14 | stack.append(int(i)) 15 | return stack[0] 16 | -------------------------------------------------------------------------------- /1503. Last Moment Before All Ants Fall Out of a Plank/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getLastMoment(self, n, left, right): 3 | ans = 0 4 | for i in left: 5 | ans = max(ans, abs(0 - i)) 6 | 7 | for i in right: 8 | ans = max(ans, abs(n - i)) 9 | 10 | return ans 11 | -------------------------------------------------------------------------------- /1508. Range Sum of Sorted Subarray Sums/main.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def rangeSum(self, nums, n, left, right): 3 | arr = [] 4 | i = 0 5 | while i < n: 6 | prefix = 0 7 | for j in range(i,n): 8 | prefix += nums[j] 9 | arr.append(prefix) 10 | i += 1 11 | arr.sort() 12 | return sum(arr[left-1:right]) % 1000000007 13 | -------------------------------------------------------------------------------- /151. Reverse Words in a String/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseWords(self, s: str) -> str: 3 | return " ".join([x for x in s.split(' ') if x !=''][::-1]) 4 | -------------------------------------------------------------------------------- /1512. Number of Good Pairs/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numIdenticalPairs(self, nums: List[int]) -> int: 3 | ans = 0 4 | for i in range(len(nums)-1): 5 | for j in range(i+1,len(nums)): 6 | if nums[i] == nums[j]: 7 | ans +=1 8 | return ans 9 | -------------------------------------------------------------------------------- /1517. Find Users With Valid E-Mails/main.sql: -------------------------------------------------------------------------------- 1 | SELECT * 2 | FROM users 3 | WHERE mail REGEXP '^[a-zA-Z][a-zAZ0-9_.-]*@leetcode[.]com' 4 | -------------------------------------------------------------------------------- /1518. Water Bottles/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numWaterBottles(self, numBottles: int, numExchange: int) -> int: 3 | res = numBottles 4 | 5 | while numBottles >= numExchange: 6 | newBottles = numBottles // numExchange 7 | res += newBottles 8 | numBottles = newBottles + numBottles % numExchange 9 | 10 | return res 11 | 12 | -------------------------------------------------------------------------------- /1527. Patients With a Condition/main.py: -------------------------------------------------------------------------------- 1 | select patient_id, patient_name, conditions 2 | from patients 3 | where conditions regexp '\\bDIAB1' 4 | -------------------------------------------------------------------------------- /1528. Shuffle String/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def restoreString(self, s: str, indices: List[int]) -> str: 3 | return ''.join([x[0] for x in sorted(zip(s, indices), key=lambda z: z[1])]) 4 | -------------------------------------------------------------------------------- /1535. Find the Winner of an Array Game/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getWinner(self, arr: List[int], k: int) -> int: 3 | n=len(arr) 4 | cur=arr[0] 5 | count=0 6 | for i in range(1,n): 7 | if arr[i]>cur: 8 | cur=arr[i] 9 | count=0 10 | count+=1 11 | if count==k: 12 | break 13 | return cur 14 | -------------------------------------------------------------------------------- /1544. Make The String Great/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def makeGood(self, s: str) -> str: 3 | 4 | ss = [] 5 | 6 | for c in s: 7 | if ss and ss[-1] == c.swapcase(): # if the stack is not empty and the last letter on the stack is 8 | ss.pop() # a match for the current letter (e.g., 'a' and 'A'), remove both 9 | else: 10 | ss.append(c) # continue adding to stack to compare with next letter 11 | 12 | return "".join(ss) 13 | -------------------------------------------------------------------------------- /155. Min Stack/main.py: -------------------------------------------------------------------------------- 1 | class MinStack: 2 | def __init__(self): 3 | self.list = [] 4 | 5 | def push(self, val: int) -> None: 6 | if self.list: 7 | minVal = self.list[-1][1] 8 | if val < minVal: 9 | minVal = val 10 | self.list.append((val, minVal)) 11 | else: 12 | self.list.append((val, val)) 13 | 14 | def pop(self) -> None: 15 | self.list.pop() 16 | 17 | def top(self) -> int: 18 | return self.list[-1][0] 19 | 20 | def getMin(self) -> int: 21 | return self.list[-1][1] 22 | -------------------------------------------------------------------------------- /1561. Maximum Number of Coins You Can Get/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxCoins(self, piles: List[int]) -> int: 3 | piles.sort() 4 | queue = deque(piles) 5 | res = 0 6 | while queue: 7 | queue.pop() # alice 8 | res += queue.pop() # us 9 | queue.popleft() # bob 10 | 11 | return res 12 | -------------------------------------------------------------------------------- /1572. Matrix Diagonal Sum/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def diagonalSum(self, mat: List[List[int]]) -> int: 3 | ans = 0 4 | n = len(mat) 5 | for i in range(n): 6 | ans += mat[i][i] 7 | if not i == n-i-1: 8 | ans += mat[i][n-i-1] 9 | return ans 10 | -------------------------------------------------------------------------------- /1578. Minimum Time to Make Rope Colorful/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minCost(self, colors: str, neededTime: List[int]) -> int: 3 | totalTime = 0 4 | i = 0 5 | j = 0 6 | 7 | while i < len(neededTime) and j < len(neededTime): 8 | currTotal = 0 9 | currMax = 0 10 | 11 | while j < len(neededTime) and colors[i] == colors[j]: 12 | currTotal += neededTime[j] 13 | currMax = max(currMax, neededTime[j]) 14 | j += 1 15 | 16 | totalTime += currTotal - currMax 17 | i = j 18 | 19 | return totalTime 20 | 21 | -------------------------------------------------------------------------------- /1581. Customer Who Visited but Did Not Make Any Transactions/main.sql: -------------------------------------------------------------------------------- 1 | SELECT v.customer_id, COUNT(v.visit_id) AS count_no_trans 2 | from Visits v 3 | LEFT JOIN Transactions t 4 | ON v.visit_id = t.visit_id 5 | WHERE t.transaction_id IS NULL 6 | GROUP BY v.customer_id; 7 | -------------------------------------------------------------------------------- /1582. Special Positions in a Binary Matrix/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numSpecial(self, mat: List[List[int]]) -> int: 3 | m, n = len(mat), len(mat[0]) 4 | res = 0 5 | 6 | for i in range(m): 7 | for j in range(n): 8 | if mat[i][j] == 1: 9 | if sum(mat[i]) == 1 and sum(mat[k][j] for k in range(m)) == 1: 10 | res += 1 11 | 12 | return res 13 | -------------------------------------------------------------------------------- /1598. Crawler Log Folder/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minOperations(self, logs: list[str]) -> int: 3 | paths_stack: list[str] = [] 4 | 5 | for log in logs: 6 | if log == "../": 7 | if paths_stack: 8 | paths_stack.pop() 9 | elif log != "./": 10 | paths_stack.append(log) 11 | 12 | return len(paths_stack) 13 | -------------------------------------------------------------------------------- /1608. Special Array With X Elements Greater Than or Equal X/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def specialArray(self, a: List[int]) -> int: 3 | return a.sort() or next((x for l,x,r in zip([-inf]+a,count(len(a),-1),a) if l int: 3 | n = list(bin(n)[2:]) 4 | cnt = 0 5 | for i in range(len(n) - 1, -1, -1): 6 | if n[i] == "0": continue 7 | else: 8 | cnt = - cnt - (2 ** (len(n) - i) - 1) 9 | return abs(cnt) 10 | -------------------------------------------------------------------------------- /1614. Maximum Nesting Depth of the Parentheses/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxDepth(self, s: str) -> int: 3 | res = 0 4 | sv = 0 5 | for x in s: 6 | if x =="(": 7 | sv += 1 8 | if x == ")": 9 | res = max(res,sv) 10 | sv -= 1 11 | return res 12 | -------------------------------------------------------------------------------- /1624. Largest Substring Between Two Equal Characters/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxLengthBetweenEqualCharacters(self, s: str) -> int: 3 | return max(s.rfind(ch) - s.find(ch) - 1 for ch in set(s)) 4 | -------------------------------------------------------------------------------- /1630. Arithmetic Subarrays/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: 3 | def arithmetic(arr): 4 | arr.sort() 5 | diff = arr[1] - arr[0] 6 | for i in range(len(arr)-1): 7 | if arr[i+1] - arr[i] != diff: 8 | return False 9 | return True 10 | 11 | res = [] 12 | for i in range(len(l)): 13 | res.append(arithmetic(nums[l[i]:r[i]+1])) 14 | 15 | return res 16 | -------------------------------------------------------------------------------- /1636. Sort Array by Increasing Frequency/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def frequencySort(self, nums: list[int]) -> list[int]: 3 | count: list[int] = [0 for _ in range(201)] 4 | for num in nums: 5 | count[num + 100] += 1 6 | nums.sort(key=lambda val: (count[val + 100], -val)) 7 | return nums 8 | -------------------------------------------------------------------------------- /1637. Widest Vertical Area Between Two Points Containing No Points/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: 3 | points.sort(key=lambda x: x[0]) 4 | 5 | max_width = 0 6 | 7 | for i in range(1, len(points)): 8 | width = points[i][0] - points[i-1][0] 9 | max_width = max(max_width, width) 10 | 11 | return max_width 12 | -------------------------------------------------------------------------------- /1642. Furthest Building You Can Reach/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int: 3 | pq = [] 4 | for i in range(len(heights) - 1): 5 | diff = heights[i + 1] - heights[i] 6 | if diff <= 0: 7 | continue 8 | heappush(pq, diff) 9 | if len(pq) > ladders: 10 | bricks -= heappop(pq) 11 | if bricks < 0: 12 | return i 13 | return len(heights) - 1 14 | -------------------------------------------------------------------------------- /1652. Defuse the Bomb/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def decrypt(self, code: List[int], k: int) -> List[int]: 3 | n = len(code) 4 | 5 | # If k == 0, all elements should be 0 6 | if k == 0: 7 | return [0] * n 8 | 9 | # Double the array to simulate circular behavior 10 | extended_code = code * 2 11 | 12 | # Handle positive and negative k 13 | if k > 0: 14 | return [sum(extended_code[i + 1:i + 1 + k]) for i in range(n)] 15 | else: 16 | k = abs(k) 17 | return [sum(extended_code[i + n - k:i + n]) for i in range(n)] 18 | -------------------------------------------------------------------------------- /1653. Minimum Deletions to Make String Balanced/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumDeletions(self, s: str) -> int: 3 | n = len(s) 4 | f = [0] * (n + 1) 5 | b = 0 6 | for i, c in enumerate(s, 1): 7 | if c == 'b': 8 | f[i] = f[i - 1] 9 | b += 1 10 | else: 11 | f[i] = min(f[i - 1] + 1, b) 12 | return f[n] 13 | -------------------------------------------------------------------------------- /1656. Design an Ordered Stream/main.py: -------------------------------------------------------------------------------- 1 | class OrderedStream: 2 | 3 | def __init__(self, n: int): 4 | self.a, self.i = [None] * (n+2), 1 5 | 6 | def insert(self, id: int, value: str) -> List[str]: 7 | a, i, self.a[id] = self.a, self.i, value 8 | if a[i]: 9 | self.i = a.index(None, i+1) 10 | return a[i:self.i] 11 | -------------------------------------------------------------------------------- /1657. Determine if Two Strings Are Close/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def closeStrings(self, word1: str, word2: str) -> bool: 3 | return set(word1)==set(word2) and sorted(Counter(word1).values())==sorted(Counter(word2).values()) 4 | 5 | -------------------------------------------------------------------------------- /1661. Average Time of Process per Machine/main.sql: -------------------------------------------------------------------------------- 1 | select a1.machine_id, round(avg(a2.timestamp-a1.timestamp), 3) as processing_time 2 | from Activity a1 3 | join Activity a2 4 | on a1.machine_id=a2.machine_id and a1.process_id=a2.process_id 5 | and a1.activity_type='start' and a2.activity_type='end' 6 | group by a1.machine_id 7 | -------------------------------------------------------------------------------- /1662. Check If Two String Arrays are Equivalent/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool: 3 | return ''.join(word1) == ''.join(word2) 4 | -------------------------------------------------------------------------------- /1667. Fix Names in a Table/main.py: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | select user_id , concat(upper(substr(name, 1,1)), lower(substr(name,2)))as name 3 | from users order by user_id 4 | -------------------------------------------------------------------------------- /167. Two Sum II - Input Array Is Sorted/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, N: List[int], target: int) -> List[int]: 3 | i = 0 4 | j = len(N) - 1 5 | ans = [] 6 | while i < j: 7 | summ = N[i] + N[j] 8 | if summ == target: 9 | return [i+1, j+1] 10 | elif summ > target: 11 | j -= 1 12 | else: 13 | i += 1 14 | return ans 15 | -------------------------------------------------------------------------------- /1672. Richest Customer Wealth/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximumWealth(self, accounts: List[List[int]]) -> int: 3 | return max(sum(x) for x in accounts) 4 | -------------------------------------------------------------------------------- /1683. Invalid Tweets/main.sql: -------------------------------------------------------------------------------- 1 | Select tweet_id 2 | from Tweets 3 | where LENGTH(content)>15 4 | -------------------------------------------------------------------------------- /1684. Count the Number of Consistent Strings/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countConsistentStrings(self, allowed: str, words: List[str]) -> int: 3 | return sum(1 for x in words if set(x).issubset(set(allowed))) 4 | -------------------------------------------------------------------------------- /1685. Sum of Absolute Differences in a Sorted Array/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getSumAbsoluteDifferences(self, nums: List[int]) -> List[int]: 3 | n=len(nums) 4 | nums.append(0) 5 | A=0 6 | B=sum(nums[1:]) 7 | ans=[0]*n 8 | 9 | for i in range(n): 10 | ans[i]=(2*i-n+1)*nums[i]+B-A 11 | A+=nums[i] 12 | B-=nums[i+1] 13 | return ans 14 | -------------------------------------------------------------------------------- /1688. Count of Matches in Tournament/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numberOfMatches(self, n: int) -> int: 3 | return n-1 4 | -------------------------------------------------------------------------------- /1689. Partitioning Into Minimum Number Of Deci-Binary Numbers/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minPartitions(self, n: str) -> int: 3 | return int(max(n)) 4 | -------------------------------------------------------------------------------- /169. Majority Element/main.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int majorityElement(vector& nums) { 4 | int n = nums.size() / 2; 5 | set numsSet(nums.begin(), nums.end()); 6 | for(int num : numsSet){ 7 | if(count(nums.begin(), nums.end(), num) > n ){ 8 | return num; 9 | } 10 | } 11 | return 0; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /169. Majority Element/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def majorityElement(self, nums: List[int]) -> int: 3 | n = len(nums)//2 4 | for x in set(nums): 5 | if nums.count(x) > n: 6 | return x 7 | -------------------------------------------------------------------------------- /17. Letter Combinations of a Phone Number/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def letterCombinations(self, digits: str) -> List[str]: 3 | if not digits: 4 | return [] 5 | 6 | phone = {"2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"} 7 | 8 | def solve(combi, digits): 9 | if not digits: 10 | return [combi] 11 | 12 | results = [] 13 | for letter in phone[digits[0]]: 14 | results.extend(solve(combi + letter, digits[1:])) 15 | 16 | return results 17 | 18 | return solve("", digits) 19 | -------------------------------------------------------------------------------- /1700. Number of Students Unable to Eat Lunch/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countStudents(self, students: List[int], sandwiches: List[int]) -> int: 3 | count = [0, 0] 4 | for student in students: 5 | count[student] += 1 6 | 7 | for i in range(len(sandwiches)): 8 | if count[sandwiches[i]] == 0: 9 | return len(sandwiches) - i 10 | count[sandwiches[i]] -= 1 11 | 12 | return 0 13 | -------------------------------------------------------------------------------- /1704. Determine if String Halves Are Alike/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def halvesAreAlike(self, s: str) -> bool: 3 | vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] 4 | a = 0 5 | b = 0 6 | half = len(s)//2 7 | for i in range(half): 8 | if s[i] in vowels: 9 | a += 1 10 | if s[half + i] in vowels: 11 | b += 1 12 | return a == b 13 | -------------------------------------------------------------------------------- /1716. Calculate Money in Leetcode Bank/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def totalMoney(self, n: int) -> int: 3 | ans = 0 4 | sv = 0 5 | for i in range(1, n+1): 6 | res = i % 7 7 | if res % 7 == 0: 8 | res += 7 9 | ans += sv + res 10 | if i % 7 == 0: 11 | sv += 1 12 | return ans 13 | 14 | -------------------------------------------------------------------------------- /172. Factorial Trailing Zeroes/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def trailingZeroes(self, n: int) -> int: 3 | ans = 0 4 | while n >= 5: 5 | n //= 5 6 | ans += n 7 | return ans 8 | -------------------------------------------------------------------------------- /1727. Largest Submatrix With Rearrangements/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestSubmatrix(self, matrix: List[List[int]]) -> int: 3 | m = len(matrix) 4 | n = len(matrix[0]) 5 | ans = 0 6 | 7 | for row in range(m): 8 | for col in range(n): 9 | if matrix[row][col] != 0 and row > 0: 10 | matrix[row][col] += matrix[row - 1][col] 11 | 12 | curr_row = sorted(matrix[row], reverse=True) 13 | for i in range(n): 14 | ans = max(ans, curr_row[i] * (i + 1)) 15 | 16 | return ans 17 | -------------------------------------------------------------------------------- /1750. Minimum Length of String After Deleting Similar Ends/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumLength(self, s: str) -> int: 3 | l, r = 0, len(s) - 1 4 | while l < r and s[l] == s[r]: 5 | ch = s[l] 6 | while l <= r and s[l] == ch: 7 | l += 1 8 | while l <= r and s[r] == ch: 9 | r -= 1 10 | return r - l + 1 11 | -------------------------------------------------------------------------------- /1757. Recyclable and Low Fat Products/main.sql: -------------------------------------------------------------------------------- 1 | Select product_id 2 | from Products 3 | where low_fats = 'Y' and recyclable = 'Y' 4 | -------------------------------------------------------------------------------- /1758. Minimum Changes To Make Alternating Binary String/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minOperations(self, s: str) -> int: 3 | r0 = 0 4 | r1 = 0 5 | for i in range(len(s)): 6 | print(r0,r1,i) 7 | if i % 2: 8 | if s[i] == '1': 9 | r0 += 1 10 | else: 11 | if s[i] == '0': 12 | r0 += 1 13 | if i % 2: 14 | if s[i] == '0': 15 | r1 += 1 16 | else: 17 | if s[i] == '1': 18 | r1 += 1 19 | return min(r0,r1) 20 | -------------------------------------------------------------------------------- /1759. Count Number of Homogenous Substrings/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countHomogenous(self, s: str) -> int: 3 | res, l = 0, 0 4 | 5 | for i, c in enumerate(s): 6 | if c == s[l]: 7 | res += i - l + 1 8 | else: 9 | l = i 10 | res += 1 11 | 12 | return res % (pow(10, 9) + 7) 13 | -------------------------------------------------------------------------------- /1769. Minimum Number of Operations to Move All Balls to Each Box/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minOperations(self, boxes: str) -> List[int]: 3 | res = [] 4 | for i in range(len(boxes)): 5 | sv = 0 6 | for j in range(len(boxes)): 7 | if(boxes[j] == '1'): 8 | sv += abs(i- j) 9 | res.append(sv) 10 | return res 11 | -------------------------------------------------------------------------------- /1773. Count Items Matching a Rule/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int: 3 | d = {'type': 0, 'color': 1, 'name': 2} 4 | return sum(1 for item in items if item[d[ruleKey]] == ruleValue) 5 | -------------------------------------------------------------------------------- /18. 4Sum/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fourSum(self, nums: List[int], target: int) -> List[List[int]]: 3 | nums.sort() 4 | ll = set() 5 | for i in range(len(nums)): 6 | for j in range(i+1,len(nums)): 7 | l = j+1 8 | r = len(nums)-1 9 | while l bool: 3 | return (ord(coordinates[0]) + int(coordinates[1])) % 2 4 | -------------------------------------------------------------------------------- /1814. Count Nice Pairs in an Array/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countNicePairs(self, nums: List[int]) -> int: 3 | for i in range(len(nums)): 4 | nums[i] = nums[i] - int(str(nums[i])[::-1]) 5 | 6 | res = 0 7 | dic = collections.defaultdict(int) 8 | for num in nums: 9 | res = (res+dic[num]) % 1000000007 10 | dic[num] += 1 11 | 12 | return res 13 | -------------------------------------------------------------------------------- /1816. Truncate Sentence/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def truncateSentence(self, s: str, k: int) -> str: 3 | return " ".join(s.split(" ")[:k]) 4 | -------------------------------------------------------------------------------- /1823. Find the Winner of the Circular Game/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findTheWinner(self, n: int, k: int) -> int: 3 | circle: list[int] = [num for num in range(1, n + 1, 1)] 4 | cur_ind: int = 0 5 | 6 | while len(circle) != 1: 7 | next_to_remove: int = (cur_ind + k - 1) % len(circle) 8 | circle.pop(next_to_remove) 9 | cur_ind = next_to_remove 10 | 11 | return circle[0] 12 | -------------------------------------------------------------------------------- /1827. Minimum Operations to Make the Array Increasing/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minOperations(self, nums: List[int]) -> int: 3 | prev = nums[0] 4 | res = 0 5 | for x in nums[1:]: 6 | if x <= prev: 7 | diff = abs(x-prev)+1 8 | prev = x + diff 9 | res += diff 10 | else: 11 | prev = x 12 | return res 13 | 14 | -------------------------------------------------------------------------------- /1832. Check if the Sentence Is Pangram/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkIfPangram(self, sentence: str) -> bool: 3 | return len(set(sentence)) == 26 4 | -------------------------------------------------------------------------------- /1838. Frequency of the Most Frequent Element/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxFrequency(self, nums: List[int], k: int) -> int: 3 | i, j = 0, 0 4 | nums.sort() 5 | 6 | while j < len(nums): 7 | k += nums[j] 8 | if k < nums[j] * (j - i + 1): 9 | k -= nums[i] 10 | i += 1 11 | j += 1 12 | 13 | return j - i 14 | -------------------------------------------------------------------------------- /1844. Replace All Digits with Characters/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def replaceDigits(self, s: str) -> str: 3 | s = list(s) 4 | sub = "" 5 | if len(s) % 2 == 1: 6 | sub = s[-1] 7 | return "".join(s[i] + chr(ord(s[i])+int(s[i+1])) for i in range(0,len(s)-1,2))+sub 8 | -------------------------------------------------------------------------------- /1845. Seat Reservation Manager/main.py: -------------------------------------------------------------------------------- 1 | class SeatManager: 2 | 3 | def __init__(self, n: int): 4 | self.last = 0 5 | self.pq = [] 6 | 7 | def reserve(self) -> int: 8 | if not self.pq: 9 | self.last += 1 10 | return self.last 11 | return heapq.heappop(self.pq) 12 | 13 | def unreserve(self, seatNumber: int) -> None: 14 | if seatNumber == self.last: 15 | self.last -= 1 16 | else: 17 | heapq.heappush(self.pq, seatNumber) 18 | -------------------------------------------------------------------------------- /1846. Maximum Element After Decreasing and Rearranging/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int: 3 | res = 1 4 | for x in sorted(arr)[1:]: 5 | if x > res: 6 | res += 1 7 | return res 8 | -------------------------------------------------------------------------------- /1859. Sorting the Sentence/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortSentence(self, s: str) -> str: 3 | l = s.split() 4 | l = [x[::-1] for x in l] 5 | l.sort() 6 | l = [x[::-1] for x in l] 7 | 8 | return " ".join([x[:-1] for x in l]) 9 | -------------------------------------------------------------------------------- /1861. Rotating the Box/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: 3 | 4 | n = len(box[0])-1 5 | 6 | for row in box: 7 | 8 | i,j = n,n 9 | while i >= 0: 10 | 11 | if row[i] == '#': 12 | if i < j: row[i], row[j] = '.', '#' 13 | j -= 1 14 | 15 | elif row[i] == '*': j = i - 1 16 | i -= 1 17 | 18 | return map(list, zip(*(box[::-1]))) 19 | -------------------------------------------------------------------------------- /1863. Sum of All Subset XOR Totals/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subsetXORSum(self, nums: List[int]) -> int: 3 | n = len(nums) 4 | total_sum = 0 5 | # Iterate through all possible subsets 6 | for i in range(1 << n): 7 | subset_xor = 0 8 | for j in range(n): 9 | # Check if the j-th element is in the i-th subset 10 | if i & (1 << j): 11 | subset_xor ^= nums[j] 12 | total_sum += subset_xor 13 | return total_sum 14 | -------------------------------------------------------------------------------- /1874. Minimize Product Sum of Two Arrays/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minProductSum(self, nums1: List[int], nums2: List[int]) -> int: 3 | nums1.sort() 4 | nums2.sort(reverse=True) 5 | return sum(nums1[i] * nums2[i] for i in range(len(nums1))) 6 | -------------------------------------------------------------------------------- /1877. Minimize Maximum Pair Sum in Array/main.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minPairSum(self, nums): 3 | nums.sort() 4 | l, r = 0, len(nums) - 1 5 | 6 | min_max_pair_sum = -1 7 | 8 | while l < r: 9 | current_pair_sum = nums[l] + nums[r] 10 | min_max_pair_sum = max(min_max_pair_sum, current_pair_sum) 11 | 12 | l += 1 13 | r -= 1 14 | 15 | return min_max_pair_sum 16 | -------------------------------------------------------------------------------- /1887. Reduction Operations to Make the Array Elements Equal/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reductionOperations(self, nums: List[int]) -> int: 3 | nums.sort(reverse=True) 4 | 5 | res = 0 6 | for i in range(1, len(nums)): 7 | if nums[i] != nums[i-1]: 8 | res += i 9 | 10 | return res 11 | -------------------------------------------------------------------------------- /189. Rotate Array/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotate(self, nums: List[int], k: int) -> None: 3 | """ 4 | Do not return anything, modify nums in-place instead. 5 | """ 6 | sv = nums[len(nums)-(k%len(nums)):] + nums[:len(nums)-(k%len(nums))] 7 | for i,x in enumerate(sv): 8 | nums[i] = x 9 | -------------------------------------------------------------------------------- /1894. Find the Student that Will Replace the Chalk/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def chalkReplacer(self, chalk: List[int], k: int) -> int: 3 | for i in range(1, len(chalk)): 4 | chalk[i]+=chalk[i-1] 5 | k%=chalk[-1] 6 | return bisect.bisect_right(chalk, k) 7 | 8 | -------------------------------------------------------------------------------- /1897. Redistribute Characters to Make All Strings Equal/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def makeEqual(self, w: List[str]) -> bool: 3 | return all(f%len(w)==0 for f in Counter(chain(*w)).values()) 4 | -------------------------------------------------------------------------------- /19. Remove Nth Node From End of List/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: 3 | if n==0: 4 | return head 5 | fast=slow=head 6 | for _ in range(n): 7 | fast=fast.next 8 | if not fast: 9 | return head.next 10 | while fast.next: 11 | fast=fast.next 12 | slow=slow.next 13 | slow.next=slow.next.next 14 | return head 15 | -------------------------------------------------------------------------------- /190. Reverse Bits/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseBits(self, n: int) -> int: 3 | binary_number = bin(n)[2:] 4 | binary_number = '0'*(32-len(binary_number))+binary_number 5 | reverse_binary_number = binary_number[::-1] 6 | return int(reverse_binary_number, 2) 7 | -------------------------------------------------------------------------------- /1903. Largest Odd Number in String/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestOddNumber(self, num: str) -> str: 3 | i = len(num)-1 4 | while i >= 0: 5 | check = int(num[i]) 6 | if check % 2 != 0: 7 | return(num[:i+1]) 8 | break 9 | else: 10 | num=num[:i] 11 | i-=1 12 | return("") 13 | -------------------------------------------------------------------------------- /1913. Maximum Product Difference Between Two Pairs/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProductDifference(self, nums: List[int]) -> int: 3 | nums.sort() 4 | return nums[-1] * nums[-2] - nums[0] * nums[1] 5 | -------------------------------------------------------------------------------- /1915. Number of Wonderful Substrings/main.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def wonderfulSubstrings(self, word): 3 | count = [0] * 1024 # 2^10 to store XOR values 4 | result = 0 5 | prefix_xor = 0 6 | count[prefix_xor] = 1 7 | 8 | for char in word: 9 | char_index = ord(char) - ord('a') 10 | prefix_xor ^= 1 << char_index 11 | result += count[prefix_xor] 12 | for i in range(10): 13 | result += count[prefix_xor ^ (1 << i)] 14 | count[prefix_xor] += 1 15 | 16 | return result 17 | -------------------------------------------------------------------------------- /1920. Build Array from Permutation/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def buildArray(self, nums: List[int]) -> List[int]: 3 | return [nums[nums[i]] for i in range(len(nums))] 4 | -------------------------------------------------------------------------------- /1921. Eliminate Maximum Number of Monsters/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int: 3 | time = [dist[i] / speed[i] for i in range(len(dist))] 4 | time.sort() 5 | 6 | for i in range(len(time)): 7 | if time[i] <= i: 8 | return i 9 | 10 | return len(time) 11 | -------------------------------------------------------------------------------- /1930. Unique Length-3 Palindromic Subsequences/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countPalindromicSubsequence(self, s: str) -> int: 3 | res = 0 4 | for i in range(26): 5 | l, r = s.find(chr(i + 97)), s.rfind(chr(i + 97)) 6 | if l != -1 and r != -1: 7 | res += len(set(s[l + 1:r])) 8 | return res 9 | -------------------------------------------------------------------------------- /1935. Maximum Number of Words You Can Type/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canBeTypedWords(self, text: str, brokenLetters: str) -> int: 3 | return sum(1 for i in text.split(' ') if not any(j in i for j in brokenLetters)) 4 | -------------------------------------------------------------------------------- /1937. Maximum Number of Points with Cost/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxPoints(self, points: List[List[int]]) -> int: 3 | n = len(points) 4 | m = len(points[0]) 5 | a = points[0].copy() 6 | 7 | for i in range(n - 1): 8 | b = [a[0]] 9 | 10 | for j in range(1, m): 11 | b.append(max(b[-1] - 1, a[j])) 12 | 13 | for j in range(m - 2, -1, -1): 14 | b[j] = max(b[j], b[j + 1] - 1) 15 | 16 | for j in range(m): 17 | a[j] = b[j] + points[i + 1][j] 18 | 19 | return max(a) 20 | -------------------------------------------------------------------------------- /1940. Longest Common Subsequence Between Sorted Arrays/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestCommonSubsequence(self, A): 3 | return (lambda count: [i for i in sorted(count) if count[i] == len(A)]) (reduce(lambda p, c: p + Counter(c), A, Counter())) 4 | -------------------------------------------------------------------------------- /1944. Number of Visible People in a Queue/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canSeePersonsCount(self, heights: List[int]) -> List[int]: 3 | ans, stack = [0] * len(heights), deque() 4 | for i, H in enumerate(heights[::-1]): 5 | while stack and stack[-1] < H: 6 | ans[i]+= 1 7 | stack.pop() 8 | if stack: ans[i] += 1 9 | stack.append(H) 10 | return ans[::-1] 11 | -------------------------------------------------------------------------------- /1957. Delete Characters to Make Fancy String/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def makeFancyString(self, s: str) -> str: 3 | # Initialize an empty list to build the result string 4 | result = [] 5 | 6 | for char in s: 7 | # Only add char if it does not form three consecutive same characters 8 | if len(result) < 2 or not (result[-1] == result[-2] == char): 9 | result.append(char) 10 | 11 | # Join the list into a string and return 12 | return ''.join(result) 13 | -------------------------------------------------------------------------------- /1967. Number of Strings That Appear as Substrings in Word/main.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numOfStrings(String[] patterns, String word) { 3 | int res = 0; 4 | for(String e: patterns){ 5 | if(word.contains(e)){ 6 | res++; 7 | } 8 | } 9 | return res; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /197. Rising Temperature/main.sql: -------------------------------------------------------------------------------- 1 | SELECT w1.id 2 | FROM Weather w1, Weather w2 3 | WHERE DATEDIFF(w1.recordDate, w2.recordDate) = 1 AND w1.temperature > w2.temperature; 4 | -------------------------------------------------------------------------------- /1975. Maximum Matrix Sum/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxMatrixSum(self, matrix: List[List[int]]) -> int: 3 | parity_neg, min_abs_num, sum_abs_num = 0, inf, 0 4 | for row in matrix: 5 | for num in row: 6 | parity_neg ^= (num < 0) 7 | min_abs_num = min(abs(num), min_abs_num) 8 | sum_abs_num += abs(num) 9 | return sum_abs_num - parity_neg * min_abs_num * 2 10 | -------------------------------------------------------------------------------- /198. House Robber/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rob(self, nums: List[int]) -> int: 3 | if len(nums) < 3: return max(nums) 4 | 5 | M = nums[0], max(nums[0], nums[1]) 6 | 7 | for i in range(2, len(nums)): 8 | M = M[1], max(nums[i]+M[0], M[1]) 9 | return M[1] 10 | -------------------------------------------------------------------------------- /20. Valid Parentheses/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isValid(self, s: str) -> bool: 3 | while '()' in s or '[]'in s or '{}' in s: 4 | s = s.replace('()','').replace('[]','').replace('{}','') 5 | return len(s) == 0 6 | -------------------------------------------------------------------------------- /2000. Reverse Prefix of Word/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reversePrefix(self, word: str, ch: str) -> str: 3 | return word[:word.index(ch)+1][::-1] + word[word.index(ch)+1:] if ch in word else word 4 | -------------------------------------------------------------------------------- /2006. Count Number of Pairs With Absolute Difference K/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countKDifference(self, nums: List[int], k: int) -> int: 3 | res = 0 4 | for i in range(len(nums)-1): 5 | for j in range(i+1, len(nums)): 6 | if abs(nums[i]-nums[j]) == k: 7 | res += 1 8 | return res 9 | 10 | -------------------------------------------------------------------------------- /2009. Minimum Number of Operations to Make Array Continuous/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minOperations(self, nums: List[int]) -> int: 3 | n = len(nums) 4 | uniq = list(set(nums)) 5 | uniq.sort() 6 | ans,j = n,0 7 | n2 = len(uniq) 8 | for i in range(0,n2): 9 | while(j < n2 and uniq[j] < uniq[i] + n): 10 | j += 1 11 | ans = min(ans, n-j+i) 12 | return ans 13 | -------------------------------------------------------------------------------- /201. Bitwise AND of Numbers Range/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rangeBitwiseAnd(self, m: int, n: int) -> int: 3 | shift = 0 4 | while m < n: 5 | m = m >> 1 6 | n = n >> 1 7 | shift += 1 8 | return m << shift 9 | -------------------------------------------------------------------------------- /2011. Final Value of Variable After Performing Operations/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def finalValueAfterOperations(self, op: List[str]) -> int: 3 | return sum(1 if x[1] =="+" else -1 for x in op) 4 | -------------------------------------------------------------------------------- /202. Happy Number/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isHappy(self, n: int) -> bool: 3 | visted = set() 4 | while n != 1 and n not in visted: 5 | visted.add(n) 6 | n = sum(int(digit) ** 2 for digit in str(n)) 7 | return n == 1 8 | -------------------------------------------------------------------------------- /2028. Find Missing Observations/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]: 3 | m=len(rolls) 4 | sum_rolles=sum(rolls) 5 | total=(n+m)*mean 6 | miss=total-sum_rolles 7 | if miss>6*n or miss int: 3 | seats.sort() 4 | students.sort() 5 | return sum(abs(seats[i]-students[i])for i in range(len(seats))) 6 | -------------------------------------------------------------------------------- /2038. Remove Colored Pieces if Both Neighbors are the Same Color/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def winnerOfGame(self, C: str) -> bool: 3 | a = 0 4 | b = 0 5 | for i in range(1,len(C)-1): 6 | s = C[i-1] + C[i] + C[i+1] 7 | if s == "AAA": 8 | a += 1 9 | elif s == "BBB": 10 | b += 1 11 | return a>b 12 | -------------------------------------------------------------------------------- /205. Isomorphic Strings/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isIsomorphic(self, s: str, t: str) -> bool: 3 | return [s.index(x) for x in s] == [t.index(x) for x in t] 4 | -------------------------------------------------------------------------------- /2053. Kth Distinct String in an Array/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kthDistinct(self, arr: List[str], k: int) -> str: 3 | counter = Counter(arr) 4 | for v in arr: 5 | if counter[v] == 1: 6 | k -= 1 7 | if k == 0: 8 | return v 9 | return '' 10 | -------------------------------------------------------------------------------- /206. Reverse Linked List/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: 3 | prev_node = None 4 | current_node = head 5 | 6 | while current_node is not None: 7 | next_node = current_node.next 8 | current_node.next = prev_node 9 | prev_node = current_node 10 | current_node = next_node 11 | 12 | return prev_node 13 | -------------------------------------------------------------------------------- /2073. Time Needed to Buy Tickets/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def timeRequiredToBuy(self, t: List[int], k: int) -> int: 3 | #loop with sum min(buy, tickets[i]) 4 | n=len(t) 5 | x=t[k] 6 | time=0 7 | for i, y in enumerate(t): 8 | buy=x 9 | if i>k: buy=x-1 10 | time+=min(buy, y) 11 | return time 12 | 13 | -------------------------------------------------------------------------------- /2083. Substrings That Begin and End With the Same Letter/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numberOfSubstrings(self, s: str) -> int: 3 | ans = 0 4 | d = collections.defaultdict(int) 5 | for c in s: 6 | d[c] += 1 7 | ans += d[c] 8 | return ans 9 | -------------------------------------------------------------------------------- /209. Minimum Size Subarray Sum/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minSubArrayLen(self, target: int, nums: List[int]) -> int: 3 | ans = len(nums) 4 | if sum(nums) < target: 5 | return 0 6 | sv = 0 7 | j = 0 8 | for i,val in enumerate(nums): 9 | sv+=val 10 | while sv >= target: 11 | sv-=nums[j] 12 | ans = min(ans,i-j+1) 13 | j+=1 14 | return ans 15 | -------------------------------------------------------------------------------- /21. Merge Two Sorted Lists/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: 3 | head = ListNode() 4 | current = head 5 | while list1 and list2: 6 | if list1.val < list2.val: 7 | current.next = list1 8 | list1 = list1.next 9 | else: 10 | current.next = list2 11 | list2 = list2.next 12 | current = current.next 13 | 14 | current.next = list1 or list2 15 | return head.next 16 | 17 | -------------------------------------------------------------------------------- /2103. Rings and Rods/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countPoints(self, rings: str) -> int: 3 | count = 0 4 | for i in range(10): 5 | c = str(i) 6 | if "B"+c in rings and "G"+c in rings and "R"+c in rings: 7 | count += 1 8 | return count 9 | 10 | -------------------------------------------------------------------------------- /2107. Number of Unique Flavors After Sharing K Candies/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def shareCandies(self, candies: List[int], k: int) -> int: 3 | d = {} 4 | for c in candies[k:]: 5 | d[c] = d.get(c, 0) + 1 6 | 7 | res = len(d) 8 | for j in range(k, len(candies)): 9 | d[candies[j]] -= 1 10 | d[candies[j - k]] = d.get(candies[j - k], 0) + 1 11 | if d[candies[j]] == 0: d.pop(candies[j]) 12 | res = max(res, len(d)) 13 | return res 14 | -------------------------------------------------------------------------------- /2108. Find First Palindromic String in the Array/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def firstPalindrome(self, words: List[str]) -> str: 3 | for w in words: 4 | if w == w[::-1]: 5 | return w 6 | return "" 7 | -------------------------------------------------------------------------------- /2114. Maximum Number of Words Found in Sentences/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def mostWordsFound(self, sentences: List[str]) -> int: 3 | return max(len(x.split(" ")) for x in sentences) 4 | return max(x.count(" ") for x in sentences)+1 5 | -------------------------------------------------------------------------------- /2125. Number of Laser Beams in a Bank/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numberOfBeams(self, bank: List[str]) -> int: 3 | ans=0 4 | prev=0 5 | for row in bank: 6 | dev=row.count('1') 7 | if dev>0: 8 | ans+=dev*prev 9 | prev=dev 10 | return ans 11 | -------------------------------------------------------------------------------- /214. Shortest Palindrome/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def shortestPalindrome(self, s: str) -> str: 3 | r = s[::-1] 4 | for i in range(len(s) + 1): 5 | if s.startswith(r[i:]): 6 | return r[:i] + s 7 | -------------------------------------------------------------------------------- /2147. Number of Ways to Divide a Long Corridor/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numberOfWays(self, corridor: str) -> int: 3 | S = 0 4 | P = 0 5 | res = 1 6 | 7 | for letter in corridor: 8 | if letter == "S": 9 | S += 1 10 | if S % 2 == 0 or S == 1: 11 | P = 0 12 | else: 13 | res = res * (P + 1) 14 | res = res % (10 ** 9 + 7) 15 | else: 16 | P += 1 17 | 18 | return res if S != 0 and S % 2 == 0 else 0 19 | -------------------------------------------------------------------------------- /2149. Rearrange Array Elements by Sign/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rearrangeArray(self, nums: List[int]) -> List[int]: 3 | pos = [x for x in nums if x > 0] 4 | neg = [x for x in nums if x < 0] 5 | i = 0 6 | res = [] 7 | while len(res) < len(nums): 8 | res.append(pos[i]) 9 | if i < len(neg): 10 | res.append(neg[i]) 11 | i += 1 12 | return res 13 | -------------------------------------------------------------------------------- /215. Kth Largest Element in an Array/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findKthLargest(self, nums: List[int], k: int) -> int: 3 | return sorted(nums, reverse=True)[k-1] 4 | -------------------------------------------------------------------------------- /2160. Minimum Sum of Four Digit Number After Splitting Digits/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumSum(self, num: int) -> int: 3 | d = sorted(str(num)) 4 | return int(d[0] + d[2]) + int(d[1] + d[3]) 5 | -------------------------------------------------------------------------------- /217. Contains Duplicate/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def containsDuplicate(self, nums: List[int]) -> bool: 3 | return len(set(nums)) != len(nums) 4 | -------------------------------------------------------------------------------- /219. Contains Duplicate II/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: 3 | x = {} 4 | for i in range(len(nums)): 5 | if nums[i] in x and abs(i - x[nums[i]]) <= k: 6 | return True 7 | x[nums[i]] = i 8 | return False 9 | -------------------------------------------------------------------------------- /2194. Cells in a Range on an Excel Sheet/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def cellsInRange(self, s: str) -> List[str]: 3 | res = [] 4 | for ch in range(ord(s[0]), ord(s[3])+1): 5 | for i in range(int(s[1]), int(s[4])+1): 6 | res.append(f'{chr(ch)}{i}') 7 | return res 8 | -------------------------------------------------------------------------------- /2220. Minimum Bit Flips to Convert Number/main.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def minBitFlips(self, start, goal): 3 | """ 4 | :type start: int 5 | :type goal: int 6 | :rtype: int 7 | """ 8 | 9 | xor_result = start ^ goal 10 | count = 0 11 | 12 | while xor_result > 0: 13 | count += xor_result & 1 14 | xor_result >>= 1 15 | 16 | return count 17 | -------------------------------------------------------------------------------- /2225. Find Players With Zero or One Losses/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findWinners(self, matches: List[List[int]]) -> List[List[int]]: 3 | loss={} 4 | for p in matches: 5 | x, y=p 6 | if x not in loss: loss[x]=0 7 | if y in loss: loss[y]+=1 8 | else: loss[y]=1 9 | ans=[[], []] 10 | for i, f in loss.items(): 11 | if f==0: 12 | ans[0].append(i) 13 | elif f==1: 14 | ans[1].append(i) 15 | 16 | return [sorted(ans[0]), sorted(ans[1])] 17 | 18 | -------------------------------------------------------------------------------- /2264. Largest 3-Same-Digit Number in String/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestGoodInteger(self, num: str) -> str: 3 | for i in range(9,-1,-1): 4 | if str(i)*3 in num: 5 | return str(i)*3 6 | return "" 7 | -------------------------------------------------------------------------------- /228. Summary Ranges/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def summaryRanges(self, nums: List[int]) -> List[str]: 3 | ans = [] 4 | for i, n in enumerate(nums): 5 | if ans and ans[-1][1] == n-1: 6 | ans[-1][1] = n 7 | else: 8 | ans.append([n, n]) 9 | return [f'{x}->{y}' if x != y else f'{x}' for x, y in ans] 10 | -------------------------------------------------------------------------------- /2285. Maximum Total Importance of Roads/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximumImportance(self, n: int, roads: List[List[int]]) -> int: 3 | res = 0 4 | cost = 1 5 | conn = [0] * n 6 | for road in roads: 7 | conn[road[0]] += 1 8 | conn[road[1]] += 1 9 | 10 | conn.sort() 11 | for con in conn: 12 | res += con * cost 13 | cost += 1 14 | return res 15 | -------------------------------------------------------------------------------- /229. Majority Element II/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def majorityElement(self, nums: List[int]) -> List[int]: 3 | ans = [] 4 | dct = {} 5 | n = len(nums) 6 | for x in set(nums): 7 | dct[x] = nums.count(x) 8 | for k, x in dct.items(): 9 | if x > n//3: 10 | ans.append(k) 11 | return ans 12 | -------------------------------------------------------------------------------- /231. Power of Two/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPowerOfTwo(self, n: int) -> bool: 3 | return bin(n)[2] == "1" and bin(n).count("1") == 1 4 | -------------------------------------------------------------------------------- /2315. Count Asterisks/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countAsterisks(self, s: str) -> int: 3 | return sum(x.count('*') for x in s.split('|')[::2]) 4 | -------------------------------------------------------------------------------- /232. Implement Queue using Stacks/main.py: -------------------------------------------------------------------------------- 1 | class MyQueue: 2 | def __init__(self): 3 | self.s1 = [] 4 | self.s2 = [] 5 | 6 | def push(self, x): 7 | while self.s1: 8 | self.s2.append(self.s1.pop()) 9 | self.s1.append(x) 10 | while self.s2: 11 | self.s1.append(self.s2.pop()) 12 | 13 | def pop(self): 14 | return self.s1.pop() 15 | 16 | def peek(self): 17 | return self.s1[-1] 18 | 19 | def empty(self): 20 | return not self.s1 21 | 22 | -------------------------------------------------------------------------------- /2325. Decode the Message/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def decodeMessage(self, key: str, message: str) -> str: 3 | hashT = {' ': ' '} 4 | i=97 5 | for k in key: 6 | if k not in hashT and k is not ' ': 7 | hashT[k] = chr(i) 8 | i+=1 9 | return "".join(hashT[m] for m in message) 10 | -------------------------------------------------------------------------------- /234. Palindrome Linked List/main.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isPalindrome(self, head): 3 | slow = fast = head 4 | while fast and fast.next: 5 | fast = fast.next.next 6 | slow = slow.next 7 | 8 | stack1=[] 9 | stack2 = [] 10 | 11 | fast = slow 12 | slow = head 13 | while fast: 14 | stack2.append(slow.val) 15 | stack1.append(fast.val) 16 | fast = fast.next 17 | slow = slow.next 18 | 19 | stack2.reverse() 20 | return stack1 == stack2 21 | 22 | -------------------------------------------------------------------------------- /235. Add Two Integers/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sum(self, num1: int, num2: int) -> int: 3 | if num1==0 and num2==0: return 0 4 | if 0 None: 9 | node.val = node.next.val 10 | node.next = node.next.next 11 | # node.val, node.next = node.next.val, node.next.next 12 | -------------------------------------------------------------------------------- /2370. Longest Ideal Subsequence/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestIdealString(self, s: str, k: int) -> int: 3 | dp = [0] * 27 4 | n = len(s) 5 | 6 | for i in range(n - 1, -1, -1): 7 | cc = s[i] 8 | idx = ord(cc) - ord('a') 9 | maxi = float('-inf') 10 | 11 | left = max((idx - k), 0) 12 | right = min((idx + k), 26) 13 | 14 | for j in range(left, right + 1): 15 | maxi = max(maxi, dp[j]) 16 | 17 | dp[idx] = maxi + 1 18 | 19 | return max(dp) 20 | -------------------------------------------------------------------------------- /2373. Largest Local Values in a Matrix/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: 3 | n = len(grid) 4 | ans = [] 5 | 6 | for i in range(n-2): 7 | row = [] 8 | for j in range(n-2): 9 | k = [(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)] 10 | row.append(max(grid[i+x][j+y] for x,y in k)) 11 | ans.append(row) 12 | 13 | return ans 14 | -------------------------------------------------------------------------------- /238. Product of Array Except Self/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def productExceptSelf(self, nums: List[int]) -> List[int]: 3 | ans = [0]*(len(nums)) 4 | prefix = 1 5 | postfix = 1 6 | 7 | for i in range(len(nums)): 8 | ans[i] = prefix 9 | prefix*=nums[i] 10 | for j in range(len(nums)-1,-1,-1): 11 | ans[j]*=postfix 12 | postfix*=nums[j] 13 | return ans 14 | -------------------------------------------------------------------------------- /2406. Divide Intervals Into Minimum Number of Groups/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minGroups(self, intervals: List[List[int]]) -> int: 3 | start_times = sorted(i[0] for i in intervals) 4 | end_times = sorted(i[1] for i in intervals) 5 | end_ptr, group_count = 0, 0 6 | 7 | for start in start_times: 8 | if start > end_times[end_ptr]: 9 | end_ptr += 1 10 | else: 11 | group_count += 1 12 | 13 | return group_count 14 | -------------------------------------------------------------------------------- /2418. Sort the People/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: 3 | return [name for _, name in sorted(zip(heights, names), reverse = True)] 4 | 5 | -------------------------------------------------------------------------------- /2419. Longest Subarray With Maximum Bitwise AND/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestSubarray(self, nums: List[int]) -> int: 3 | n=len(nums) 4 | maxLen, xMax, Len=0, 0, 0 5 | i=0 6 | while i bool: 3 | return sorted(s) == sorted(t) 4 | -------------------------------------------------------------------------------- /243. Shortest Word Distance/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def shortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int: 3 | d = defaultdict(list) 4 | for i, val in enumerate(wordsDict): 5 | d[val].append(i) 6 | return min(abs(x - y) for x in d[word1] for y in d[word2]) 7 | -------------------------------------------------------------------------------- /2433. Find The Original Array of Prefix Xor/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findArray(self, pref: List[int]) -> List[int]: 3 | return [pref[0]] + [pref[i] ^ pref[i-1] for i in range(1, len(pref))] 4 | -------------------------------------------------------------------------------- /2441. Largest Positive Integer That Exists With Its Negative/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMaxK(self, nums: List[int]) -> int: 3 | nums.sort() 4 | n = len(nums) 5 | for i in range(n-1, -1, -1): 6 | if nums[i] > 0 and -nums[i] in nums: 7 | return nums[i] 8 | return -1 # If no such pair found 9 | -------------------------------------------------------------------------------- /2444. Count Subarrays With Fixed Bounds/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countSubarrays(self, nums: List[int], mink: int, maxK: int) -> int: 3 | 4 | res = 0 5 | bad_idx = left_idx = right_idx = -1 6 | 7 | for i, num in enumerate(nums) : 8 | if not mink <= num <= maxK: 9 | bad_idx = i 10 | 11 | if num == mink: 12 | left_idx = i 13 | 14 | if num == maxK: 15 | right_idx = i 16 | 17 | res += max(0, min(left_idx, right_idx) - bad_idx) 18 | 19 | return res 20 | -------------------------------------------------------------------------------- /2469. Convert the Temperature/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def convertTemperature(self, celsius: float) -> List[float]: 3 | return celsius + 273.15, celsius * 1.80 + 32.00 4 | -------------------------------------------------------------------------------- /2482. Difference Between Ones and Zeros in Row and Column/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def onesMinusZeros(self, grid: List[List[int]]) -> List[List[int]]: 3 | R, C = len(grid), len(grid[0]) 4 | row, col = [0] * R, [0] * C 5 | for r in range(R): 6 | for c in range(C): 7 | offset = 2 * grid[r][c] - 1 8 | row[r] += offset 9 | col[c] += offset 10 | return [[row[r] + col[c] for c in range(C)] for r in range(R)] 11 | -------------------------------------------------------------------------------- /2485. Find the Pivot Integer/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def pivotInteger(self, n: int) -> int: 3 | sum = n * (n + 1) // 2 4 | a = math.sqrt(sum) 5 | 6 | if a - math.ceil(a) == 0: 7 | return int(a) 8 | else: 9 | return -1 10 | 11 | -------------------------------------------------------------------------------- /2486. Append Characters to String to Make Subsequence/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def appendCharacters(self, s: str, t: str) -> int: 3 | i, j = 0, 0 # Start both pointers at the beginning of s and t 4 | 5 | while i < len(s) and j < len(t): # Continue until one of the strings is fully scanned 6 | if s[i] == t[j]: # If characters match 7 | j += 1 # Move the pointer in t forward 8 | i += 1 # Always move the pointer in s forward 9 | 10 | return len(t) - j # The number of characters in t not matched in s 11 | 12 | -------------------------------------------------------------------------------- /2487. Remove Nodes From Linked List/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]: 3 | cur = head 4 | stack = [] 5 | while cur: 6 | while stack and stack[-1].val < cur.val: 7 | stack.pop() 8 | stack.append(cur) 9 | cur = cur.next 10 | 11 | nxt = None 12 | while stack: 13 | cur = stack.pop() 14 | cur.next = nxt 15 | nxt = cur 16 | 17 | return cur 18 | -------------------------------------------------------------------------------- /2505. Bitwise OR of All Subsequence Sums/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subsequenceSumOr(self, nums: List[int]) -> int: 3 | res,tot = 0,0 4 | for i in nums: 5 | res|=i 6 | tot+=i 7 | res|=tot 8 | return res 9 | -------------------------------------------------------------------------------- /252. Meeting Rooms/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canAttendMeetings(self, intervals: List[List[int]]) -> bool: 3 | intervals.sort() 4 | for i, (start, end) in enumerate(intervals[:-1]): 5 | if end > intervals[i+1][0]: 6 | return False 7 | 8 | return True 9 | 10 | -------------------------------------------------------------------------------- /253. Meeting Rooms II/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minMeetingRooms(self, intervals: List[List[int]]) -> int: 3 | 4 | rooms = 0 5 | 6 | if not intervals: 7 | return 0 8 | 9 | endp = 0 10 | 11 | starts = sorted([i[0] for i in intervals]) 12 | ends = sorted([i[1] for i in intervals]) 13 | 14 | for i in range(len(starts)): 15 | if starts[i]>=ends[endp]: 16 | endp+=1 17 | else: 18 | rooms+=1 19 | 20 | return rooms 21 | -------------------------------------------------------------------------------- /2530. Maximal Score After Applying K Operations/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxKelements(self, nums: List[int], k: int) -> int: 3 | heapify(pq:=[-x for x in nums]) 4 | score=0 5 | for i in range(k): 6 | x=-heappop(pq) 7 | score+=x 8 | if x==1: 9 | score+=k-1-i 10 | break 11 | heappush(pq, -((x+2)//3)) 12 | return score 13 | 14 | -------------------------------------------------------------------------------- /2540. Minimum Common Value/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getCommon(self, nums1: List[int], nums2: List[int]) -> int: 3 | n1, n2= len(nums1), len(nums2) 4 | if n1>n2: return self.getCommon(nums2, nums1) 5 | prev=0 6 | for x in nums1: 7 | j=bisect_left(nums2, x, lo=prev) 8 | if j==n2: return -1 9 | elif x==nums2[j]: return x 10 | else: prev=j 11 | return -1 12 | 13 | -------------------------------------------------------------------------------- /256. Paint House/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minCost(self, costs): 3 | prev = [0] * 3 4 | for now in costs: 5 | prev = [now[i] + min(prev[:i] + prev[i+1:]) for i in range(3)] 6 | return min(prev) 7 | -------------------------------------------------------------------------------- /2582. Pass the Pillow/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def passThePillow(self, n: int, time: int) -> int: 3 | return 1+x if (x:=time% (N:=2*n-2)) < n else N+1-x 4 | 5 | -------------------------------------------------------------------------------- /26. Remove Duplicates from Sorted Array/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeDuplicates(self, nums: List[int]) -> int: 3 | i = 0 4 | while i < len(nums): 5 | try: 6 | if nums[i] in nums[i+1:]: 7 | del nums[i] 8 | else: 9 | i += 1 10 | except: 11 | break 12 | -------------------------------------------------------------------------------- /260. Single Number III/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def singleNumber(self, nums: list[int]) -> list[int]: 3 | n: int = len(nums) 4 | result: list[int] = [0, 0] 5 | index = 0 6 | 7 | for i in range(n): 8 | found = False 9 | for j in range(n): 10 | if i != j and nums[i] == nums[j]: 11 | found = True 12 | break 13 | if not found: 14 | result[index] = nums[i] 15 | index += 1 16 | if index == 2: 17 | break 18 | 19 | return result 20 | -------------------------------------------------------------------------------- /2610. Convert an Array Into a 2D Array With Conditions/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMatrix(self, nums: List[int]) -> List[List[int]]: 3 | freq = [0] * (len(nums) + 1) 4 | ans = [] 5 | 6 | for c in nums: 7 | if freq[c] >= len(ans): 8 | ans.append([]) 9 | 10 | ans[freq[c]].append(c) 11 | freq[c] += 1 12 | 13 | return ans 14 | -------------------------------------------------------------------------------- /2620. Counter/main.js: -------------------------------------------------------------------------------- 1 | var createCounter = function(n) { 2 | 3 | return function() { 4 | return n++; 5 | }; 6 | }; 7 | 8 | /** 9 | * const counter = createCounter(10) 10 | * counter() // 10 11 | * counter() // 11 12 | * counter() // 12 13 | */ 14 | -------------------------------------------------------------------------------- /2621. Sleep/main.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} millis 3 | * @return {Promise} 4 | */ 5 | async function sleep(millis) { 6 | return new Promise(resolve => setTimeout(resolve, millis)) 7 | } 8 | 9 | /** 10 | * let t = Date.now() 11 | * sleep(100).then(() => console.log(Date.now() - t)) // 100 12 | */ 13 | -------------------------------------------------------------------------------- /2623. Memoize/main.py: -------------------------------------------------------------------------------- 1 | function memoize(fn) { 2 | const cache = new Map(); 3 | return function() { 4 | let key = arguments[0]; 5 | if (arguments[1]) { 6 | key += arguments[1] * 100001; 7 | } 8 | const result = cache.get(key); 9 | if (result !== undefined) { 10 | return result; 11 | } 12 | const functionOutput = fn.apply(null, arguments); 13 | cache.set(key, functionOutput); 14 | return functionOutput; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /2626. Array Reduce Transformation/main.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {Function} fn 4 | * @param {number} init 5 | * @return {number} 6 | */ 7 | var reduce = function(nums, fn, init) { 8 | for (let i = 0; i < nums.length; i++) { 9 | init = fn(init, nums[i]) 10 | } 11 | return init 12 | }; 13 | -------------------------------------------------------------------------------- /2627. Debounce/main.js: -------------------------------------------------------------------------------- 1 | var debounce = function(fn, t) { 2 | let id; 3 | return function(...args) { 4 | clearTimeout(id); 5 | id = setTimeout(() => fn(...args),t); 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /2629. Function Composition/main.py: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {Function[]} functions 3 | * @return {Function} 4 | */ 5 | var compose = function(functions) { 6 | if (functions.length === 0) { 7 | return function(x) { return x; }; 8 | } else { 9 | return function(x) { 10 | var result = functions[functions.length - 1](x); 11 | for (var i = functions.length - 2; i >= 0; i--) { 12 | result = functions[i](result); 13 | } 14 | return result; 15 | }; 16 | } 17 | }; 18 | 19 | /** 20 | * const fn = compose([x => x + 1, x => 2 * x]) 21 | * fn(4) // 9 22 | */ 23 | -------------------------------------------------------------------------------- /2634. Filter Elements from Array/main.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @param {Function} fn 4 | * @return {number[]} 5 | */ 6 | var filter = function(arr, fn) { 7 | var arr2 = [] 8 | for (let i = 0; i < arr.length; i++) { 9 | if(fn(arr[i],i)){ 10 | arr2.push(arr[i]) 11 | } 12 | } 13 | return arr2 14 | }; 15 | -------------------------------------------------------------------------------- /2635. Apply Transform Over Each Element in Array/main.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @param {Function} fn 4 | * @return {number[]} 5 | */ 6 | var map = function(arr, fn) { 7 | var arr2 = [] 8 | for (let i = 0; i < arr.length; i++) { 9 | arr2.push(fn(arr[i],i)) 10 | } 11 | return arr2 12 | 13 | }; 14 | -------------------------------------------------------------------------------- /264. Ugly Number II/main.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def nthUglyNumber(self, n): 3 | primes = [2,3,5] 4 | uglyHeap = [1] 5 | visited = set() 6 | visited.add(1) 7 | for _ in range(n): 8 | curr = heappop(uglyHeap) 9 | for prime in primes: 10 | new_ugly = curr * prime 11 | if new_ugly not in visited: 12 | heappush(uglyHeap, new_ugly) 13 | visited.add(new_ugly) 14 | return curr 15 | -------------------------------------------------------------------------------- /2656. Maximum Sum With Exactly K Elements /main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximizeSum(self, nums: List[int], k: int) -> int: 3 | return k * max(nums) + k * (k - 1) // 2 4 | -------------------------------------------------------------------------------- /2665. Counter II/main.js: -------------------------------------------------------------------------------- 1 | var createCounter = function(init) { 2 | let currentCount = init; 3 | return{ 4 | increment: function() { 5 | currentCount++; 6 | return currentCount 7 | }, 8 | decrement: function() { 9 | currentCount--; 10 | return currentCount 11 | }, 12 | reset: function() { 13 | currentCount = init 14 | return currentCount 15 | } 16 | } 17 | }; 18 | 19 | /** 20 | * const counter = createCounter(5) 21 | * counter.increment(); // 6 22 | * counter.reset(); // 5 23 | * counter.decrement(); // 4 24 | */ 25 | -------------------------------------------------------------------------------- /2666. Allow One Function Call/main.js: -------------------------------------------------------------------------------- 1 | var once = f => (...a) => f ? [f(...a), f=undefined][0] : f 2 | -------------------------------------------------------------------------------- /2667. Create Hello World Function/main.js: -------------------------------------------------------------------------------- 1 | var createHelloWorld = function() { 2 | return () => "Hello World" 3 | }; 4 | 5 | /** 6 | * const f = createHelloWorld(); 7 | * f(); // "Hello World" 8 | */ 9 | -------------------------------------------------------------------------------- /2678. Number of Senior Citizens/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countSeniors(self, details: List[str]) -> int: 3 | return sum(int(x[11:13]) > 60 for x in details) 4 | -------------------------------------------------------------------------------- /268. Missing Number/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def missingNumber(self, nums: List[int]) -> int: 3 | expected_sum = sum(range(len(nums) + 1)) 4 | actual_sum = sum(nums) 5 | return expected_sum - actual_sum 6 | -------------------------------------------------------------------------------- /2697. Lexicographically Smallest Palindrome/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def makeSmallestPalindrome(self, s: str) -> str: 3 | before = 0 4 | after = len(s)-1 5 | l = list(s) 6 | while before <= len(s)/2: 7 | l[before] = min(l[before], l[after]) 8 | l[after] = l[before] 9 | before+=1 10 | after-=1 11 | return ''.join(l) 12 | -------------------------------------------------------------------------------- /27. Remove Element/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeElement(self, nums: List[int], val: int) -> int: 3 | i = 0 4 | while i < len(nums): 5 | try: 6 | if nums[i] == val: 7 | del nums[i] 8 | i -=1 9 | except: 10 | break 11 | i+=1 12 | -------------------------------------------------------------------------------- /2703. Return Length of Arguments Passed/main.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {...(null|boolean|number|string|Array|Object)} args 3 | * @return {number} 4 | */ 5 | var argumentsLength = function(...args) { 6 | return args.length 7 | }; 8 | 9 | /** 10 | * argumentsLength(1, 2, 3); // 3 11 | */ 12 | -------------------------------------------------------------------------------- /2704. To Be Or Not To Be/main.js: -------------------------------------------------------------------------------- 1 | var expect = function(val) { 2 | const throwError = (errorStr) => {throw new Error(errorStr)}; 3 | 4 | return { 5 | toBe: (val2) => val2 === val || throwError('Not Equal'), 6 | notToBe: (val2) => val2 !== val || throwError('Equal'), 7 | }; 8 | }; 9 | 10 | /** 11 | * expect(5).toBe(5); // true 12 | * expect(5).notToBe(5); // throws "Equal" 13 | */ 14 | -------------------------------------------------------------------------------- /2706. Buy Two Chocolates/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def buyChoco(self, prices: List[int], money: int) -> int: 3 | prices.sort() 4 | return money - (prices[0] + prices[1]) if (prices[0] + prices[1])<= money else money 5 | -------------------------------------------------------------------------------- /2709. Greatest Common Divisor Traversal/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canTraverseAllPairs(self, nums: List[int]) -> bool: 3 | if len(nums)==1:return True 4 | nums = set(nums) 5 | if 1 in nums:return False 6 | if len(nums)==1:return True 7 | 8 | nums = sorted(nums,reverse=True) 9 | 10 | for i in range(len(nums)-1): 11 | for j in range(i+1,len(nums)): 12 | if gcd(nums[i],nums[j])-1: 13 | nums[j]*=nums[i] 14 | break 15 | else: 16 | return False 17 | return True 18 | -------------------------------------------------------------------------------- /2710. Remove Trailing Zeros From a String/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeTrailingZeros(self, num: str) -> str: 3 | #return num.strip("0") 4 | for i,x in enumerate(num[::-1]): 5 | if not x == "0": 6 | return num[:len(num)-i] 7 | return '' 8 | -------------------------------------------------------------------------------- /2723. Add Two Promises/main.js: -------------------------------------------------------------------------------- 1 | const addTwoPromises = async (p1, p2) => await p1 + await p2; 2 | -------------------------------------------------------------------------------- /2727. Is Object Empty/main.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {Object|Array} obj 3 | * @return {boolean} 4 | */ 5 | var isEmpty = function(obj) { 6 | for (let key in obj) 7 | return false; 8 | return true; 9 | }; 10 | -------------------------------------------------------------------------------- /274. H-Index/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hIndex(self, citations: List[int]) -> int: 3 | citations.sort() 4 | ans = 0 5 | n = len(citations) 6 | for i in range(n): 7 | if citations[i] < n - i: 8 | ans = citations[i] 9 | else: 10 | ans = max(ans,n - i) 11 | return ans 12 | -------------------------------------------------------------------------------- /2742. Painting the Walls/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def paintWalls(self, cost: List[int], time: List[int]) -> int: 3 | n = len(cost) 4 | dp = [float('inf')] * (n + 1) 5 | dp[0] = 0 6 | 7 | for i in range(n): 8 | for j in range(n, 0, -1): 9 | dp[j] = min(dp[j], dp[max(j - time[i] - 1, 0)] + cost[i]) 10 | return dp[n] 11 | -------------------------------------------------------------------------------- /2743. Count Substrings Without Repeating Character/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numberOfSpecialSubstrings(self, s: str) -> int: 3 | N = len(s) 4 | l = 0 5 | total = 0 6 | 7 | lookup = defaultdict(int) 8 | 9 | for r in range(N): 10 | lookup[s[r]] += 1 11 | 12 | while lookup[s[r]] > 1: 13 | lookup[s[l]] -= 1 14 | l += 1 15 | 16 | total += r - l + 1 17 | 18 | return total 19 | 20 | -------------------------------------------------------------------------------- /2744. Find Maximum Number of String Pairs/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximumNumberOfStringPairs(self, words: List[str]) -> int: 3 | new_words = [''.join(sorted(word)) for word in words] 4 | return len(new_words) - len(set(new_words)) 5 | -------------------------------------------------------------------------------- /276. Paint Fence/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numWays(self, n: int, k: int) -> int: 3 | if n == 0: return 0 4 | if n == 1: return k 5 | if n == 2: return k * k 6 | table = [0, k, k*k] + [-1] * (n-2) 7 | print(table) 8 | for i in range(3, n + 1): 9 | table[i] = (table[i-1] + table[i-2]) * (k-1) 10 | 11 | return table[n] 12 | -------------------------------------------------------------------------------- /2769. Find the Maximum Achievable Number/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def theMaximumAchievableX(self, num: int, t: int) -> int: 3 | return num+2*t 4 | -------------------------------------------------------------------------------- /2785. Sort Vowels in a String/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortVowels(self, s: str) -> str: 3 | vowels = 'aeiouAEIOU' 4 | sorted_vowels = sorted([c for c in s if c in vowels]) 5 | new_string = "" 6 | for c in s: 7 | if c in vowels: 8 | new_string += sorted_vowels.pop(0) 9 | else: 10 | new_string += c 11 | return new_string 12 | -------------------------------------------------------------------------------- /279. Perfect Squares/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numSquares(self, n: int) -> int: 3 | dp=[0]*(n+1) 4 | for i in range(1,n+1): 5 | dp[i]=i 6 | for j in range(1,int(math.sqrt(i))+1): 7 | dp[i]=min(dp[i],dp[i-j*j]+1) 8 | return dp[n] 9 | -------------------------------------------------------------------------------- /2796. Repeat String/main.js: -------------------------------------------------------------------------------- 1 | String.prototype.replicate = function(times) { 2 | return this.repeat(times); 3 | } 4 | -------------------------------------------------------------------------------- /2798. Number of Employees Who Met the Target/main.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numberOfEmployeesWhoMetTarget(vector& hours, int target) { 4 | int ans = 0; 5 | for(int i = 0; i < hours.size(); i++){ 6 | if(hours[i] >= target){ 7 | ans++; 8 | } 9 | } 10 | return ans; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /28. Find the Index of the First Occurrence in a String/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def strStr(self, haystack: str, needle: str) -> int: 3 | if needle in haystack: 4 | return haystack.index(needle) 5 | else: 6 | return -1 7 | -------------------------------------------------------------------------------- /2802. Find The K-th Lucky Number/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kthLuckyNumber(self, k: int) -> str: 3 | n = 1 4 | while k > (1 << n): 5 | k -= 1 << n 6 | n += 1 7 | return bin(k - 1)[2:].zfill(n).replace('0', '4').replace('1', '7') 8 | -------------------------------------------------------------------------------- /2810. Faulty Keyboard/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def finalString(self, s: str) -> str: 3 | res = "" 4 | for c in s: 5 | if c == 'i': 6 | res = res[::-1] 7 | else: 8 | res = res + c 9 | return res 10 | -------------------------------------------------------------------------------- /2824. Count Pairs Whose Sum is Less than Target/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countPairs(self, nums: List[int], target: int) -> int: 3 | n=len(nums) 4 | ans=0 5 | for i in range(n): 6 | for j in range(i,n): 7 | if i bool: 3 | j=0 4 | for i in range(len(str1)): 5 | #print(i,j,str1[i],str2[j],(ord(str1[i])-97+1)%26,ord(str2[j])-97) 6 | if (ord(str1[i])-97+1)%26==ord(str2[j])-97 or str1[i]==str2[j]: 7 | j+=1 8 | if j==len(str2): 9 | return True 10 | #print(j) 11 | return False 12 | 13 | -------------------------------------------------------------------------------- /2828. Check if a String Is an Acronym of Words/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isAcronym(self, words: List[str], s: str) -> bool: 3 | return "".join(x[0] for x in words) == s 4 | -------------------------------------------------------------------------------- /2838. Maximum Coins Heroes Can Collect/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximumCoins(self, heroes: List[int], monsters: List[int], 3 | coins: List[int]) -> List[int]: 4 | 5 | ans = [] 6 | monsters, coins = zip(*sorted(zip(monsters, coins))) # <-- 1. 7 | 8 | pref = list(accumulate(coins, initial = 0)) # <-- 2. 9 | 10 | for hero in heroes: # <-- 3. 11 | ans.append(pref[bisect_right(monsters, hero)]) # 12 | 13 | return ans 14 | -------------------------------------------------------------------------------- /2864. Maximum Odd Binary Number/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximumOddBinaryNumber(self, s: str) -> str: 3 | ones = s.count('1') 4 | zeros = s.count('0') 5 | 6 | return (ones-1)*'1' + zeros*'0' + '1' 7 | -------------------------------------------------------------------------------- /287. Find the Duplicate Number/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDuplicate(self, nums: List[int]) -> int: 3 | seen = set() 4 | for num in nums: 5 | if num in seen: 6 | return num 7 | seen.add(num) 8 | -------------------------------------------------------------------------------- /2870. Minimum Number of Operations to Make Array Empty/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minOperations(self, nums: List[int]) -> int: 3 | cnt = Counter(nums) 4 | if cnt.most_common()[-1][1] == 1 : return -1 5 | return sum((c-1) // 3 + 1 for c in cnt.values()) 6 | -------------------------------------------------------------------------------- /2879. Display the First Three Rows/main.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | 3 | def selectFirstRows(employees: pd.DataFrame) -> pd.DataFrame: 4 | return employees.head(3) 5 | -------------------------------------------------------------------------------- /2894. Divisible and Non-divisible Sums Difference/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def differenceOfSums(self, n: int, m: int) -> int: 3 | return sum(x if x%m else -x for x in range(1,n+1)) 4 | -------------------------------------------------------------------------------- /290. Word Pattern/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def wordPattern(self, pattern: str, s: str) -> bool: 3 | s = s.split() 4 | return (len(set(pattern)) == len(set(zip_longest(pattern,s))) == len(set(s))) 5 | -------------------------------------------------------------------------------- /2913. Subarrays Distinct Element Sum of Squares I/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sumCounts(self, nums: List[int]) -> int: 3 | n = len(nums) 4 | ans = 0 5 | for i in range(n): 6 | distinct_db = set() 7 | for j in range(i, n): 8 | distinct_db.add(nums[j]) 9 | ans += len(distinct_db) * len(distinct_db) 10 | return ans 11 | -------------------------------------------------------------------------------- /2914. Minimum Number of Changes to Make Binary String Beautiful/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minChanges(self, s: str) -> int: 3 | return sum(s[i]!=s[i+1] for i in range(0,len(s)-1,2)) 4 | -------------------------------------------------------------------------------- /2915. Length of the Longest Subsequence That Sums to Target/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLongestSubsequence(self, nums: List[int], target: int) -> int: 3 | n = len(nums) 4 | dp = [float('-inf')]*(target+1) 5 | dp[0] = 0 6 | for num in nums: 7 | for i in range(target, num-1, -1): 8 | dp[i] = max(dp[i], dp[i-num]+1) 9 | 10 | if dp[target] <= 0: 11 | return -1 12 | return dp[target] 13 | -------------------------------------------------------------------------------- /2923. Find Champion I/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findChampion(self, grid: List[List[int]]) -> int: 3 | n = len(grid) 4 | 5 | for i in range(n): 6 | if sum(grid[i]) == n - 1: 7 | return i 8 | -------------------------------------------------------------------------------- /2924. Find Champion II/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findChampion(self, n: int, edges: List[List[int]]) -> int: 3 | winner = set() 4 | for i in range(n): 5 | winner.add(i) 6 | 7 | for ed in edges: 8 | winner.discard(ed[1]) 9 | 10 | if len(winner)>1: 11 | return -1 12 | 13 | for i in winner: 14 | return i 15 | 16 | -------------------------------------------------------------------------------- /2928. Distribute Candies Among Children I/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def distributeCandies(self, n: int, limit: int) -> int: 3 | count = 0 4 | 5 | for i in range(min(n, limit) + 1): 6 | for j in range(min(n - i, limit) + 1): 7 | k = n - i - j 8 | if 0 <= k <= limit: 9 | count += 1 10 | return count 11 | -------------------------------------------------------------------------------- /2929. Distribute Candies Among Children II/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def distributeCandies(self, n: int, limit: int) -> int: 3 | count = 0 4 | 5 | for i in range(min(n, limit) + 1): 6 | max_j = min(n - i, limit) 7 | min_k = max(0, n - i - limit) 8 | max_k = min(n - i, limit) 9 | 10 | count += max(0, max_k - min_k + 1) 11 | 12 | return count 13 | -------------------------------------------------------------------------------- /293. Flip Game/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generatePossibleNextMoves(self, currentState: str) -> List[str]: 3 | next_states = [] 4 | for i in range(1, len(currentState)): 5 | if currentState[i - 1] == currentState[i] == "+": 6 | new_state = currentState[:i - 1] + "--" + currentState[i + 1:] 7 | next_states.append(new_state) 8 | 9 | return next_states 10 | -------------------------------------------------------------------------------- /2930. Number of Strings Which Can Be Rearranged to Contain Substring/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def stringCount(self, n: int) -> int: 3 | if(n<4): 4 | return 0 5 | a=26**n 6 | b=25**n 7 | c=24**n 8 | d=23**n 9 | return ((a)-(3*b+(n*(b//25))-3*c-(2*n*(c//24))+d+(n*(d//23))))%1000000007 10 | -------------------------------------------------------------------------------- /2931. Maximum Spending After Buying Items/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSpending(self, values ) -> int: 3 | ans = 0 4 | for i, k in enumerate(sorted(sum(values, []))): 5 | ans += (i+1) * k 6 | return ans 7 | -------------------------------------------------------------------------------- /2932. Maximum Strong Pair XOR I/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximumStrongPairXor(self, nums: List[int]) -> int: 3 | ans = 0 4 | for x in nums: 5 | for y in nums: 6 | if abs(x-y) <= min(x,y): 7 | ans = max(ans, x^y) 8 | return ans 9 | -------------------------------------------------------------------------------- /2933. High-Access Employees/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findHighAccessEmployees(self, access_times: List[List[str]]) -> List[str]: 3 | eDict = defaultdict(list) 4 | for e, t in access_times: 5 | eDict[e].append(int(t)) 6 | 7 | res = [] 8 | for e, t in eDict.items(): 9 | t.sort() 10 | n = len(t) 11 | for i in range(n - 2): 12 | if t[i + 2] - t[i] < 100: 13 | res.append(e) 14 | break 15 | 16 | return res 17 | -------------------------------------------------------------------------------- /2938. Separate Black and White Balls/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumSteps(self, s: str) -> int: 3 | white=0 4 | res=0 5 | j=0 6 | n=len(s) 7 | while(j List[int]: 3 | res = [] 4 | for i, word in enumerate(words): 5 | if x in word: 6 | res.append(i) 7 | return res 8 | -------------------------------------------------------------------------------- /2944. Minimum Number of Coins for Fruits/main.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumCoins(vector& prices) { 4 | int n = prices.size(); 5 | 6 | vectordp(n+1); 7 | 8 | for(int i=n-1; i>=0; i--){ 9 | dp[i] = prices[i]; 10 | int nextI = i+1; 11 | int val = INT_MAX; 12 | for(int j=i+1; j<=min(n,i+nextI+1); j++){ 13 | val = min(dp[j], val); 14 | } 15 | if(val < INT_MAX)dp[i] += val; 16 | 17 | } 18 | return dp[0]; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /2958. Length of Longest Subarray With at Most K Frequency/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSubarrayLength(self, nums: List[int], k: int) -> int: 3 | ans = 0 4 | mp = {} 5 | l = 0 6 | n = len(nums) 7 | for r in range(n): 8 | mp[nums[r]] = mp.get(nums[r], 0) + 1 9 | if mp[nums[r]] > k: 10 | while nums[l] != nums[r]: 11 | mp[nums[l]] -= 1 12 | l += 1 13 | mp[nums[l]] -= 1 14 | l += 1 15 | ans = max(ans, r - l + 1) 16 | return ans 17 | -------------------------------------------------------------------------------- /296. Best Meeting Point/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minTotalDistance(self, grid: List[List[int]]) -> int: 3 | m, n = len(grid), len(grid[0]) 4 | xs = [i for i in range(m) for j in range(n) if grid[i][j]] 5 | ys = [j for i in range(m) for j in range(n) if grid[i][j]] 6 | xs.sort() 7 | ys.sort() 8 | x, y = xs[len(xs)//2], ys[len(ys)//2] 9 | res = 0 10 | for i in range(m): 11 | for j in range(n): 12 | if grid[i][j]: 13 | res += abs(i-x) + abs(j-y) 14 | return res 15 | -------------------------------------------------------------------------------- /2962. Count Subarrays Where Max Element Appears at Least K Times/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countSubarrays(self, nums: List[int], k: int) -> int: 3 | mx,ans,l,r,n=max(nums),0,0,0,len(nums) 4 | while r int: 3 | nums = sorted(nums) 4 | res = 0 5 | sv_res = sum(nums[:2]) 6 | 7 | for x in nums[2:]: 8 | if sv_res > x: 9 | res = sv_res + x 10 | sv_res += x 11 | 12 | return -1 if not res else res 13 | -------------------------------------------------------------------------------- /2997. Minimum Number of Operations to Make Array XOR Equal to K/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minOperations(self, nums: List[int], k: int) -> int: 3 | return (reduce(xor, nums)^k).bit_count() 4 | 5 | -------------------------------------------------------------------------------- /3. Longest Substring Without Repeating Characters/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLongestSubstring(self, s: str) -> int: 3 | if len(s) == 1: 4 | return 1 5 | ans = 0 6 | for i,x in enumerate(s): 7 | sv = x 8 | for y in s[i+1:]: 9 | if not y in sv: 10 | sv += y 11 | else: 12 | break 13 | ans = max(ans,len(sv)) 14 | return ans 15 | -------------------------------------------------------------------------------- /300. Longest Increasing Subsequence/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLIS(self, nums: List[int]) -> int: 3 | arr = [nums.pop(0)] 4 | for n in nums: 5 | if n > arr[-1]: 6 | arr.append(n) 7 | else: 8 | arr[bisect_left(arr, n)] = n 9 | return len(arr) 10 | -------------------------------------------------------------------------------- /3005. Count Elements With Maximum Frequency/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxFrequencyElements(self, a: List[int]) -> int: 3 | return (m:=max(f:=Counter(a).values()))*[*f].count(m) 4 | -------------------------------------------------------------------------------- /3016. Minimum Number of Pushes to Type Word II/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumPushes(self, word: str) -> int: 3 | return sum(f*(i//8+1) for i, f in enumerate(sorted(Counter(word).values(), reverse=True))) 4 | 5 | -------------------------------------------------------------------------------- /303. Range Sum Query - Immutable/main.py: -------------------------------------------------------------------------------- 1 | class NumArray: 2 | 3 | def __init__(self, nums: List[int]): 4 | self.nums=nums 5 | 6 | 7 | def sumRange(self, left: int, right: int) -> int: 8 | return sum(self.nums[left:right+1]) 9 | -------------------------------------------------------------------------------- /3075. Maximize Happiness of Selected Children/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximumHappinessSum(self, happiness: List[int], k: int) -> int: 3 | happiness.sort(reverse=True) 4 | i = 0 5 | res = 0 6 | 7 | while k > 0: 8 | happiness[i] = max(happiness[i] - i, 0) 9 | res += happiness[i] 10 | i += 1 11 | k -= 1 12 | 13 | return res 14 | -------------------------------------------------------------------------------- /3110. Score of a String/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def scoreOfString(self, s: str) -> int: 3 | score = 0 4 | for i in range(len(s) - 1): 5 | score += abs(ord(s[i]) - ord(s[i + 1])) 6 | return score 7 | -------------------------------------------------------------------------------- /3163. String Compression III/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def compressedString(self, word: str) -> str: 3 | comp = "" 4 | i = 0 5 | n = len(word) 6 | 7 | while i < n: 8 | # Get the current character 9 | char = word[i] 10 | # Count the number of consecutive chars up to 9 11 | count = 0 12 | while i < n and word[i] == char and count < 9: 13 | count += 1 14 | i += 1 15 | # Append the count and character to the result string 16 | comp += str(count) + char 17 | 18 | return comp 19 | -------------------------------------------------------------------------------- /3189. Minimum Moves to Get a Peaceful Board/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minMoves(self, rooks: List[List[int]]) -> int: 3 | 4 | abdiff = lambda y: abs(y[0] - y[1]) 5 | 6 | f = lambda x: sum(map(abdiff, enumerate(sorted(x)))) 7 | 8 | row, col = zip(*rooks) 9 | 10 | return f(row) + f(col) 11 | -------------------------------------------------------------------------------- /320. Generalized Abbreviation/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generateAbbreviations(self, word: str) -> List[str]: 3 | res = [] 4 | n = len(word) 5 | def dfs(i: int, cur: str) -> None: 6 | if i >= n: 7 | res.append(cur) 8 | return 9 | dfs(i + 1, cur + word[i]) 10 | if cur and cur[-1].isnumeric(): return 11 | for j in range(i, n): 12 | dfs(j + 1, cur + str(j - i + 1)) 13 | dfs(0, "") 14 | return res 15 | -------------------------------------------------------------------------------- /326. Power of Three/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPowerOfThree(self, n: int) -> bool: 3 | return n>0 and 3**round(log(n,3)) == n 4 | -------------------------------------------------------------------------------- /338. Counting Bits/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countBits(self, n: int) -> List[int]: 3 | ans = [] 4 | cnt = 0 5 | for x in range(n+1): 6 | cnt = bin(x).count("1") 7 | ans.append(cnt) 8 | return ans 9 | -------------------------------------------------------------------------------- /34. Find First and Last Position of Element in Sorted Array/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchRange(self, nums: List[int], target: int) -> List[int]: 3 | if not target in nums: 4 | return [-1,-1] 5 | if len(nums) == 1: 6 | return [0,0] 7 | ans = [-1,-1] 8 | for i,x in enumerate(nums): 9 | if ans[0] == -1 and x == target: 10 | ans[0] = i 11 | elif ans[0] != -1 and x != target: 12 | ans[1]=i-1 13 | return ans 14 | ans[1]= len(nums)-1 15 | return ans 16 | -------------------------------------------------------------------------------- /341. Flatten Nested List Iterator/main.py: -------------------------------------------------------------------------------- 1 | class NestedIterator: 2 | def __init__(self, nestedList: [NestedInteger]): 3 | self.stack = nestedList[::-1] 4 | 5 | def next(self) -> int: 6 | return self.stack.pop().getInteger() 7 | 8 | def hasNext(self) -> bool: 9 | while self.stack: 10 | if self.stack[-1].isInteger(): 11 | return True 12 | self.stack.extend(self.stack.pop().getList()[::-1]) 13 | return False 14 | -------------------------------------------------------------------------------- /342. Power of Four/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPowerOfFour(self, n: int) -> bool: 3 | return n>0 and log(n,4).is_integer() 4 | -------------------------------------------------------------------------------- /343. Integer Break/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def integerBreak(self, n: int) -> int: 3 | if n < 4: 4 | n-=1 5 | ans = 1 6 | while n > 4: 7 | ans *= 3 8 | n -= 3 9 | return ans * n 10 | -------------------------------------------------------------------------------- /344. Reverse String/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseString(self, s: List[str]) -> None: 3 | s.reverse() 4 | -------------------------------------------------------------------------------- /346. Moving Average from Data Stream/main.py: -------------------------------------------------------------------------------- 1 | class MovingAverage: 2 | 3 | def __init__(self, size: int): 4 | self.size = size 5 | self.queue = [0] * self.size 6 | self.head = self.window_sum = 0 7 | self.count = 0 8 | 9 | def next(self, val: int) -> float: 10 | self.count += 1 11 | tail = (self.head+1) % self.size 12 | self.window_sum = self.window_sum - self.queue[tail] + val 13 | self.head = (self.head + 1) % self.size 14 | self.queue[self.head] = val 15 | return self.window_sum / min(self.size, self.count) 16 | -------------------------------------------------------------------------------- /349. Intersection of Two Arrays/main.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: 3 | return set(nums1).intersection(set(nums2)) 4 | -------------------------------------------------------------------------------- /35. Search Insert Position/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchInsert(self, nums: List[int], target: int) -> int: 3 | for i in range(len(nums)): 4 | if nums[i] >= target: 5 | return i 6 | return len(nums) 7 | -------------------------------------------------------------------------------- /350. Intersection of Two Arrays II/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: 3 | freq=[0]*1001 4 | for x in nums1: 5 | freq[x]+=1 6 | ans=[] 7 | for x in nums2: 8 | if freq[x]>0: 9 | ans.append(x) 10 | freq[x]-=1 11 | return ans 12 | 13 | -------------------------------------------------------------------------------- /368. Largest Divisible Subset/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestDivisibleSubset(self, nums: List[int]) -> List[int]: 3 | nums.sort() 4 | n=len(nums) 5 | if n<2: 6 | return nums 7 | ans=[ [num] for num in nums] 8 | for i in range(n): 9 | for j in range(i): 10 | if nums[i]%nums[j]==0 and len(ans[i]) bool: 3 | return Counter(magazine) >= Counter(ransomNote) 4 | -------------------------------------------------------------------------------- /386. Lexicographical Numbers/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lexicalOrder(self, n: int) -> List[int]: 3 | result = [] 4 | curr = 1 5 | for _ in range(n): 6 | result.append(curr) 7 | if curr * 10 <= n: 8 | curr *= 10 # Move to the next depth (append 0 at the end) 9 | else: 10 | while curr % 10 == 9 or curr + 1 > n: 11 | curr //= 10 # Backtrack by removing the last digit 12 | curr += 1 # Increment to the next number in lexicographical order 13 | return result 14 | -------------------------------------------------------------------------------- /387. First Unique Character in a String/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def firstUniqChar(self, s: str) -> int: 3 | for i,c in enumerate(s): 4 | if s.count(c) == 1: 5 | return i 6 | return -1 7 | -------------------------------------------------------------------------------- /392. Is Subsequence/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isSubsequence(self, s: str, t: str) -> bool: 3 | i = 0 4 | j = 0 5 | while i < len(s) and j < len(t): 6 | if s[i] == t[j]: 7 | i += 1 8 | j += 1 9 | return i == len(s) 10 | -------------------------------------------------------------------------------- /4. Median of Two Sorted Arrays/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: 3 | merged_array = nums1 + nums2 4 | merged_array.sort() 5 | median = 0 6 | if len(merged_array) %2 != 0: 7 | median = merged_array[len(merged_array) // 2] 8 | else: 9 | if len(merged_array) > 1: 10 | median = (merged_array[len(merged_array)//2-1] + merged_array[len(merged_array)//2]) /2 11 | else: 12 | median = merged_array[0] 13 | return median 14 | -------------------------------------------------------------------------------- /404. Sum of Left Leaves/main.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 sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int: 9 | def f(root, isLeft): 10 | if not root: return 0 11 | if not root.left and not root.right and isLeft: return root.val 12 | return f(root.left, True)+f(root.right, False) 13 | return f(root, False) 14 | 15 | -------------------------------------------------------------------------------- /41. First Missing Positive/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def firstMissingPositive(self, nums: List[int]) -> int: 3 | nums=set(nums) 4 | for i in range(1,2147483647): 5 | if i not in nums: return i 6 | -------------------------------------------------------------------------------- /412. Fizz Buzz/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fizzBuzz(self, n: int) -> List[str]: 3 | ans = [] 4 | for i in range(1,n+1): 5 | fizz = i % 3 == 0 6 | buzz = i % 5 == 0 7 | if fizz and buzz: 8 | ans.append("FizzBuzz") 9 | elif fizz: 10 | ans.append("Fizz") 11 | elif buzz: 12 | ans.append("Buzz") 13 | else: 14 | ans.append(str(i)) 15 | return ans 16 | -------------------------------------------------------------------------------- /42. Trapping Rain Water/main.py: -------------------------------------------------------------------------------- 1 | class Solution:# done using two pointers 2 | def trap(self, H: List[int]) -> int: 3 | L = 0 4 | R = len(H) - 1 5 | Lmax = 0 6 | Rmax = 0 7 | ans = 0 8 | while L <= R: 9 | if H[L] <= H[R]: 10 | Lmax = max(Lmax, H[L]) 11 | ans += Lmax - H[L] 12 | L += 1 13 | else: 14 | Rmax = max(Rmax, H[R]) 15 | ans += Rmax - H[R] 16 | R -= 1 17 | return ans 18 | -------------------------------------------------------------------------------- /438. Find All Anagrams in a String/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findAnagrams(self, s: str, p: str) -> List[int]: 3 | # lets loop in s 4 | res = [] 5 | p_sorted = sorted(p) 6 | for i in range(len(s)-len(p)+1): 7 | #we gonna check s[i:i+len(p)] in sorted is equal to sorted(p) 8 | #so we have "bcaqqq" ans "abc" 9 | # we gonna check if sorted("bca") = "abc" == sorted("abc") 10 | if sorted(s[i:i + len(p)]) == p_sorted: 11 | res.append(i) 12 | return res 13 | -------------------------------------------------------------------------------- /440. K-th Smallest in Lexicographical Order/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getReqNum(self, a, b, n): 3 | gap = 0 4 | while a <= n: 5 | gap += min(n + 1, b) - a 6 | a *= 10 7 | b *= 10 8 | return gap 9 | 10 | def findKthNumber(self, n: int, k: int) -> int: 11 | num = 1 12 | i = 1 13 | while i < k: 14 | req = self.getReqNum(num, num + 1, n) 15 | if i + req <= k: 16 | i += req 17 | num += 1 18 | else: 19 | i += 1 20 | num *= 10 21 | return num 22 | -------------------------------------------------------------------------------- /442. Find All Duplicates in an Array/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDuplicates(self, nums: List[int]) -> List[int]: 3 | s = set() 4 | res = set() 5 | for x in nums: 6 | if x in s: 7 | res.add(x) 8 | else: 9 | s.add(x) 10 | return res 11 | -------------------------------------------------------------------------------- /446. Arithmetic Slices II - Subsequence/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numberOfArithmeticSlices(self, nums: List[int]) -> int: 3 | n = len(nums);ans = 0 4 | dp = defaultdict(Counter) 5 | for i in range(1,n): 6 | for j in range(i): 7 | d = nums[i] - nums[j] 8 | dp[i][d] += dp[j][d] + 1 9 | ans += sum(dp[i].values()) - i 10 | return ans 11 | -------------------------------------------------------------------------------- /45. Jump Game II/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def jump(self, nums: List[int]) -> int: 3 | for i,x in enumerate(nums[1:]): 4 | nums[i+1] = max(nums[i+1] + i+1, nums[i]) 5 | dist = 0 6 | ans = 0 7 | while dist < len(nums)-1: 8 | ans += 1 9 | dist = nums[dist] 10 | return ans 11 | -------------------------------------------------------------------------------- /451. Sort Characters By Frequency/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def frequencySort(self, s: str) -> str: 3 | freq = Counter(s) 4 | print(Counter(s)) 5 | sort = [key for key, _ in freq.most_common()] 6 | 7 | res = "" 8 | for c in sort: 9 | res += freq[c]*c 10 | return res 11 | -------------------------------------------------------------------------------- /452. Minimum Number of Arrows to Burst Balloons/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMinArrowShots(self, points: List[List[int]]) -> int: 3 | points.sort(key=lambda x: x[1]) 4 | 5 | arrows = 0 6 | end = -maxsize 7 | 8 | for s, e in points: 9 | if s > end: 10 | arrows += 1 11 | end = e 12 | 13 | return arrows 14 | -------------------------------------------------------------------------------- /455. Assign Cookies/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findContentChildren(self, g: List[int], s: List[int]) -> int: 3 | g.sort(reverse = True) 4 | s.sort(reverse = True) 5 | res, i , j = 0 ,0,0 6 | while i bool: 3 | stack = [] 4 | cur_min = nums[0] 5 | for n in nums[1:]: 6 | while stack and n >= stack[-1][0]: 7 | stack.pop() 8 | if stack and n > stack[-1][1]: 9 | return True 10 | stack.append([n, cur_min]) 11 | cur_min = min(cur_min, n) 12 | return False 13 | -------------------------------------------------------------------------------- /458. Max Dot Product of Two Subsequences/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int: 3 | n = len(nums1) 4 | m = len(nums2) 5 | dp = [[float('-inf')] * (m+1) for _ in range(n+1)] 6 | 7 | for i in range(1, n+1): 8 | for j in range(1, m+1): 9 | sv = nums1[i-1] * nums2[j-1] 10 | dp[i][j] = max(dp[i][j], sv, dp[i-1][j], dp[i][j-1], sv + dp[i-1][j-1]) 11 | return dp[n][m] 12 | -------------------------------------------------------------------------------- /458. Poor Pigs/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def poorPigs(self, buckets: int, a: int, b: int) -> int: 3 | pigs = 0 4 | while (b / a + 1) ** pigs < buckets: 5 | pigs += 1 6 | 7 | return pigs 8 | -------------------------------------------------------------------------------- /463. Island Perimeter/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def islandPerimeter(self, grid: List[List[int]]) -> int: 3 | m = len(grid) 4 | n = len(grid[0]) 5 | 6 | islands = 0 7 | neighbors = 0 8 | 9 | for i in range(m): 10 | for j in range(n): 11 | if grid[i][j] == 1: 12 | islands += 1 13 | if i + 1 < m and grid[i + 1][j] == 1: 14 | neighbors += 1 15 | if j + 1 < n and grid[i][j + 1] == 1: 16 | neighbors += 1 17 | 18 | return islands * 4 - neighbors * 2 19 | -------------------------------------------------------------------------------- /476. Number Complement/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findComplement(self, num: int) -> int: 3 | bit_length = num.bit_length() 4 | 5 | mask = (1 << bit_length) - 1 6 | 7 | return num ^ mask 8 | -------------------------------------------------------------------------------- /48. Rotate Image/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotate(self, matrix: List[List[int]]) -> None: 3 | n = len(matrix) 4 | for i in range(n): 5 | for j in range(i+1): 6 | matrix[i][j],matrix[j][i] = matrix[j][i], matrix[i][j] 7 | for l in matrix: 8 | l.reverse() 9 | -------------------------------------------------------------------------------- /485. Max Consecutive Ones/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMaxConsecutiveOnes(self, nums: List[int]) -> int: 3 | res = 0 4 | sv = 0 5 | for num in nums: 6 | if num == 1: 7 | sv += 1 8 | else: 9 | res = max(res,sv) 10 | sv = 0 11 | return max(res,sv) 12 | -------------------------------------------------------------------------------- /487. Max Consecutive Ones II/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMaxConsecutiveOnes(self, nums: List[int]) -> int: 3 | res = 0 4 | curr, prev, seenZero = 0, 0, 0 5 | for num in nums: 6 | if num == 0: 7 | seenZero = 1 8 | prev = curr 9 | curr = 0 10 | else: 11 | curr += 1 12 | res = max(res, curr+ prev+ seenZero) 13 | return res 14 | -------------------------------------------------------------------------------- /49. Group Anagrams/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 3 | d = {} 4 | 5 | for word in strs: 6 | temp = ''.join(sorted(word)) 7 | if temp not in d: 8 | d[temp] = [word] 9 | else: 10 | d[temp].append(word) 11 | return d.values() 12 | -------------------------------------------------------------------------------- /5. Longest Palindromic Substring/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestPalindrome(self, s: str) -> str: 3 | t,ans="","" 4 | size=0 5 | for i in range(len(s)): 6 | for j in range(i,len(s)): 7 | t+=s[j] 8 | if t==t[::-1] and len(t)>size: 9 | ans=t 10 | size=len(t) 11 | t="" 12 | return ans 13 | -------------------------------------------------------------------------------- /50. Pow(x, n)/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def myPow(self, x: float, n: int) -> float: 3 | p = self.myPow(x * x, abs(n) // 2) * (x if n % 2 else 1) if n else 1 4 | return p if n >= 0 else 1 / p 5 | -------------------------------------------------------------------------------- /501. Find Mode in Binary Search Tree/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMode(self, root: Optional[TreeNode]) -> List[int]: 3 | def dfs(root: TreeNode)-> None: 4 | if not root: return 5 | d[root.val]+=1 6 | dfs(root.left) 7 | dfs(root.right) 8 | return 9 | d, ans = defaultdict(int), [] 10 | dfs(root) 11 | mx = max(d.values()) 12 | 13 | return [key for key in d if d[key] == mx] 14 | -------------------------------------------------------------------------------- /502. IPO/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMaximizedCapital( 3 | self, k: int, w: int, profits: List[int], capital: List[int] 4 | ) -> int: 5 | n = len(profits) 6 | projects = [(capital[i], profits[i]) for i in range(n)] 7 | projects.sort() 8 | maxHeap = [] 9 | i = 0 10 | for _ in range(k): 11 | while i < n and projects[i][0] <= w: 12 | heapq.heappush(maxHeap, -projects[i][1]) 13 | i += 1 14 | if not maxHeap: 15 | break 16 | w -= heapq.heappop(maxHeap) 17 | 18 | return w 19 | -------------------------------------------------------------------------------- /509. Fibonacci Number/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fib(self, n: int) -> int: 3 | if n <= 1: 4 | return n 5 | return self.fib(n - 1) + self.fib(n - 2) 6 | -------------------------------------------------------------------------------- /513. Find Bottom Left Tree Value/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findBottomLeftValue(self, root): 3 | last = 0 4 | q = deque([root]) 5 | 6 | while q: 7 | count = len(q) 8 | for i in range(count): 9 | curr = q.popleft() 10 | if i == 0: 11 | last = curr.val # last leftMost val 12 | if curr.left: 13 | q.append(curr.left) 14 | if curr.right: 15 | q.append(curr.right) 16 | 17 | return last 18 | -------------------------------------------------------------------------------- /535. Encode and Decode TinyURL/main.py: -------------------------------------------------------------------------------- 1 | class Codec: 2 | 3 | def encode(self, longUrl: str) -> str: 4 | return longUrl 5 | 6 | 7 | 8 | def decode(self, shortUrl: str) -> str: 9 | return shortUrl 10 | -------------------------------------------------------------------------------- /543. Diameter of Binary Tree/main.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 diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int: 9 | max_d = [0] 10 | def dfs(root): 11 | if not root:return -1 12 | left = dfs(root.left) 13 | right=dfs(root.right) 14 | max_d[0]=max(max_d[0],left+right+2) 15 | return 1+max(left,right) 16 | dfs(root) 17 | return max_d[0] 18 | -------------------------------------------------------------------------------- /55. Jump Game/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canJump(self, nums: List[int]) -> bool: 3 | dist = 0 4 | for i,x in enumerate(nums): 5 | if i > dist: 6 | return False 7 | dist = max(dist, x+i) 8 | return True 9 | -------------------------------------------------------------------------------- /557. Reverse Words in a String III/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseWords(self, s: str) -> str: 3 | return " ".join([x[::-1] for x in s.split(" ")]) 4 | -------------------------------------------------------------------------------- /56. Merge Intervals/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def merge(self, intervals: List[List[int]]) -> List[List[int]]: 3 | intervals.sort(key =lambda x: x[0]) 4 | merged =[] 5 | for i in intervals: 6 | if not merged or merged[-1][1] < i[0]: 7 | merged.append(i) 8 | 9 | else: 10 | merged[-1][1] = max(merged[-1][1], i[-1]) 11 | return merged 12 | -------------------------------------------------------------------------------- /567. Permutation in String/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkInclusion(self, s1: str, s2: str) -> bool: 3 | n1, n2=len(s1), len(s2) 4 | if n2 List[List[int]]: 3 | intervals.append(newInterval) 4 | intervals.sort(key =lambda x: x[0]) 5 | merged =[] 6 | for i in intervals: 7 | if not merged or merged[-1][1] < i[0]: 8 | merged.append(i) 9 | 10 | else: 11 | merged[-1][1] = max(merged[-1][1], i[-1]) 12 | return merged 13 | -------------------------------------------------------------------------------- /577. Employee Bonus/main.sql: -------------------------------------------------------------------------------- 1 | SELECT Employee.name,Bonus.bonus FROM Employee 2 | LEFT JOIN Bonus ON Employee.empID = Bonus.empID 3 | WHERE bonus < 1000 OR Bonus IS NULL ; 4 | -------------------------------------------------------------------------------- /58. Length of Last Word/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLastWord(self, s: str) -> int: 3 | n = 0 4 | for x in s[::-1]: 5 | if x == ' ' and n > 0: 6 | return n 7 | elif x != ' ': 8 | n+=1 9 | return n 10 | -------------------------------------------------------------------------------- /584. Find Customer Referee/main.sql: -------------------------------------------------------------------------------- 1 | Select name 2 | from Customer 3 | where (not referee_id = 2) or (referee_id is null) 4 | -------------------------------------------------------------------------------- /592. Fraction Addition and Subtraction/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fractionAddition(self, expression: str) -> str: 3 | nums = list(map(int, re.findall(r'[+-]?\d+', expression))) 4 | numerator = 0 5 | denominator = 1 6 | 7 | for i in range(0, len(nums), 2): 8 | num, den = nums[i], nums[i + 1] 9 | numerator = numerator * den + num * denominator 10 | denominator *= den 11 | 12 | common_divisor = gcd(numerator, denominator) 13 | return f"{numerator // common_divisor}/{denominator // common_divisor}" 14 | -------------------------------------------------------------------------------- /595. Big Countries/main.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | Select name, population, area 3 | From World 4 | Where area >= 3000000 or population >= 25000000 5 | -------------------------------------------------------------------------------- /6. Zigzag Conversion/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def convert(self, s: str, numRows: int) -> str: 3 | x = 0 4 | rows = [""]*numRows 5 | while True: 6 | if x == len(s): 7 | break 8 | for i in range(0, numRows): 9 | if x == len(s): 10 | break 11 | rows[i] += s[x] 12 | x += 1 13 | 14 | for i in range(numRows-2, 0, -1): 15 | if x == len(s): 16 | break 17 | rows[i] += s[x] 18 | x += 1 19 | return "".join(rows) 20 | -------------------------------------------------------------------------------- /606. Construct String from Binary Tree/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def tree2str(self, r: Optional[TreeNode]) -> str: 3 | if not r: 4 | return '' 5 | 6 | s = f'{r.val}' 7 | if r.left or r.right: 8 | s += f'({self.tree2str(r.left)})' 9 | if r.right: 10 | s += f'({self.tree2str(r.right)})' 11 | 12 | return s 13 | -------------------------------------------------------------------------------- /620. Not Boring Movies/main.sql: -------------------------------------------------------------------------------- 1 | SELECT id, movie, description, rating 2 | FROM Cinema 3 | WHERE id % 2 = 1 4 | AND description != 'boring' 5 | ORDER BY rating DESC; 6 | -------------------------------------------------------------------------------- /624. Maximum Distance in Arrays/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxDistance(self, arrays: List[List[int]]) -> int: 3 | max_val, min_val, res = float("-inf"), float("inf"), 0 4 | 5 | for arr in arrays: 6 | res = max(res, arr[-1] - min_val, max_val - arr[0]) 7 | min_val = min(min_val,arr[0]) 8 | max_val = max(max_val,arr[-1]) 9 | return res 10 | -------------------------------------------------------------------------------- /629. K Inverse Pairs Array/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kInversePairs(self, n: int, k: int) -> int: 3 | @cache 4 | def f(n, k): 5 | if k==0: return 1 6 | if k<0 or n<=0: return 0 7 | return (f(n-1, k)+f(n, k-1)-f(n-1, k-n)+10**9+7)%(10**9+7) 8 | return f(n, k) 9 | -------------------------------------------------------------------------------- /633. Sum of Square Numbers/main.py: -------------------------------------------------------------------------------- 1 | from math import sqrt 2 | 3 | class Solution: 4 | def judgeSquareSum(self, c: int) -> bool: 5 | for a in range(int(sqrt(c)) + 1): # Iterate through all possible values of `a` 6 | b = sqrt(c - a * a) # Compute `b` as the square root of `c - a^2` 7 | if b == int(b): # Check if `b` is an integer 8 | return True # If `b` is an integer, return true 9 | return False # If no such pair `(a, b)` is found, return false 10 | -------------------------------------------------------------------------------- /645. Set Mismatch/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findErrorNums(self, nums: List[int]) -> List[int]: 3 | return [sum(nums)-sum(set(nums)), len(nums)*(len(nums)+1)//2-sum(set(nums))] 4 | -------------------------------------------------------------------------------- /647. Palindromic Substrings/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countSubstrings(self, s: str) -> int: 3 | n, ans = len(s), 0 4 | 5 | def palindromeCount(left: int, right: int) -> int: 6 | count = 0 7 | while left >= 0 and right < n and s[left] == s[right]: 8 | left -= 1 9 | right += 1 10 | count += 1 11 | return count 12 | 13 | for i in range(n): 14 | even = palindromeCount(i, i + 1) 15 | odd = palindromeCount(i, i) 16 | ans += even + odd 17 | 18 | return ans 19 | -------------------------------------------------------------------------------- /648. Replace Words/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def replaceWords(self, d: List[str], s: str) -> str: 3 | s=s.split(' ') 4 | d.sort() 5 | ans="" 6 | for i in s: 7 | flg=False 8 | for j in d: 9 | if i.startswith(j): 10 | ans+=j+' ' 11 | flg=True 12 | break 13 | if not flg: 14 | ans+=i+' ' 15 | return ans[:-1] 16 | -------------------------------------------------------------------------------- /650. 2 Keys Keyboard/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minSteps(self, n: int) -> int: 3 | if n == 1: 4 | return 0 5 | 6 | steps = 0 7 | factor = 2 8 | 9 | while n > 1: 10 | while n % factor == 0: 11 | steps += factor 12 | n //= factor 13 | factor += 1 14 | 15 | return steps 16 | -------------------------------------------------------------------------------- /66. Plus One/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def plusOne(self, D: List[int]) -> List[int]: 3 | return list(map(int,list(str(int("".join(list(map(str,D))))+1)))) 4 | -------------------------------------------------------------------------------- /67. Add Binary/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addBinary(self, a: str, b: str) -> str: 3 | return bin(int(a, 2) + int(b, 2))[2:] 4 | -------------------------------------------------------------------------------- /678. Valid Parenthesis String/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkValidString(self, s: str) -> bool: 3 | low = high = 0 4 | for c in s: 5 | low += 1 if c == '(' else -1 6 | high += 1 if c != ')' else -1 7 | if high < 0: 8 | return False 9 | low = max(low, 0) 10 | return low == 0 11 | -------------------------------------------------------------------------------- /69. Sqrt(x)/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def mySqrt(self, x: int) -> int: 3 | i = 1 4 | while True: 5 | if i*i > x: 6 | return i-1 7 | i+=1 8 | -------------------------------------------------------------------------------- /7. Reverse Integer/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverse(self, x: int) -> int: 3 | flag = -1 if x < 0 else 1 4 | 5 | s = str(abs(x)) 6 | x = int(s[::-1]) 7 | 8 | return x*flag if x < 2**31 else 0 9 | -------------------------------------------------------------------------------- /70. Climbing Stairs/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def climbStairs(self, n: int) -> int: 3 | if n <= 0: 4 | return 0 5 | if n == 1: 6 | return 1 7 | if n == 2: 8 | return 2 9 | # F(n) = F(n-1) + F(n-2) 10 | prev1, prev2 = 1, 2 11 | ans = 0 12 | for i in range(3, n + 1): 13 | ans = prev1 + prev2 14 | prev1, prev2 = prev2, ans 15 | return ans 16 | -------------------------------------------------------------------------------- /704. Binary Search/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def search(self, nums: List[int], target: int) -> int: 3 | lo = 0 4 | hi = len(nums) - 1 5 | while lo <= hi: 6 | mid = (hi+lo) // 2 7 | if nums[mid] == target: 8 | return mid 9 | elif target < nums[mid]: 10 | hi = mid - 1 11 | else: 12 | lo = mid + 1 13 | return -1 14 | -------------------------------------------------------------------------------- /706. Design HashMap/main.py: -------------------------------------------------------------------------------- 1 | class MyHashMap: 2 | 3 | def __init__(self): 4 | self.data = [None] * (10**6+1) 5 | 6 | def put(self, key: int, value: int) -> None: 7 | self.data[key] = value 8 | 9 | def get(self, key: int) -> int: 10 | return self.data[key] if self.data[key] != None else -1 11 | 12 | def remove(self, key: int) -> None: 13 | self.data[key] = None 14 | -------------------------------------------------------------------------------- /709. To Lower Case/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def toLowerCase(self, s: str) -> str: 3 | for i in range(len(s)): 4 | # If s[i] is uppercase, convert it to lowercase. 5 | if 65 <= ord(s[i]) <= 90: 6 | s = s[:i] + chr(ord(s[i]) + 32) + s[i+1:] 7 | return s 8 | -------------------------------------------------------------------------------- /71. Simplify Path/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def simplifyPath(self, path: str) -> str: 3 | stack = [] 4 | temp = path.split('/') 5 | 6 | for x in temp: 7 | if x != '.' and x != '' and x != '..': 8 | stack.append(x) 9 | 10 | elif x == '..': 11 | if stack: 12 | stack.pop() 13 | 14 | return '/' + '/'.join(stack) 15 | -------------------------------------------------------------------------------- /73. Set Matrix Zeroes/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def setZeroes(self, matrix: List[List[int]]) -> None: 3 | zeroRows = set() 4 | zeroCols = set() 5 | n = len(matrix) 6 | m = len(matrix[0]) 7 | for i in range(n): 8 | for j in range(m): 9 | if matrix[i][j] == 0: 10 | zeroRows.add(i) 11 | zeroCols.add(j) 12 | 13 | for i in range(n): 14 | for j in range(m): 15 | if i in zeroRows or j in zeroCols: 16 | matrix[i][j] = 0 17 | -------------------------------------------------------------------------------- /739. Daily Temperatures/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def dailyTemperatures(self, temperatures: List[int]) -> List[int]: 3 | n = len(temperatures) 4 | answer = [0] * n 5 | stack = [] 6 | 7 | for curr_day, curr_temp in enumerate(temperatures): 8 | while stack and temperatures[stack[-1]] < curr_temp: 9 | prev_day = stack.pop() 10 | answer[prev_day] = curr_day - prev_day 11 | stack.append(curr_day) 12 | 13 | return answer 14 | -------------------------------------------------------------------------------- /746. Min Cost Climbing Stairs/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minCostClimbingStairs(self, cost: List[int]) -> int: 3 | n = len(cost) 4 | prev1, prev2 = 0, 0 5 | for i in range(2, n+1): 6 | current = min(prev1 + cost[i-1], prev2 + cost[i-2]) 7 | prev2, prev1 = prev1, current 8 | return prev1 9 | -------------------------------------------------------------------------------- /75. Sort Colors/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortColors(self, nums: List[int]) -> None: 3 | """ 4 | Do not return anything, modify nums in-place instead. 5 | """ 6 | zeros, ones, n = 0, 0, len(nums) 7 | for num in nums: 8 | if num == 0: 9 | zeros += 1 10 | elif num == 1: 11 | ones += 1 12 | 13 | for i in range(0, zeros): 14 | nums[i] = 0 15 | 16 | for i in range(zeros, zeros + ones): 17 | nums[i] = 1 18 | 19 | for i in range(zeros + ones, n): 20 | nums[i] = 2 21 | 22 | -------------------------------------------------------------------------------- /771. Jewels and Stones/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numJewelsInStones(self, jewels: str, stones: str) -> int: 3 | return sum(x in jewels for x in stones) 4 | -------------------------------------------------------------------------------- /779. K-th Symbol in Grammar/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kthGrammar(self, n: int, k: int) -> int: 3 | if n==1 and k == 1 : 4 | return 0 5 | mid = 2**(n-2) 6 | if k <= mid: 7 | return self.kthGrammar(n-1,k) 8 | if k > mid: 9 | return 1-self.kthGrammar(n-1,k-mid) 10 | return self.kthGrammar(n,k) 11 | -------------------------------------------------------------------------------- /78. Subsets/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subsets(self, nums: List[int]) -> List[List[int]]: 3 | result = [] 4 | 5 | def explore(index, curr): 6 | if index == len(nums): 7 | result.append(curr.copy()) 8 | return 9 | 10 | curr.append(nums[index]) 11 | explore(index + 1, curr) 12 | curr.pop() 13 | explore(index + 1, curr) 14 | 15 | explore(0, []) 16 | return result 17 | -------------------------------------------------------------------------------- /787. Cheapest Flights Within K Stops/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int: 3 | dp = [float('inf')] * n 4 | dp[src] = 0 5 | 6 | for _ in range(k + 1): 7 | temp = dp[:] 8 | for flight in flights: 9 | if dp[flight[0]] != float('inf'): 10 | temp[flight[1]] = min(temp[flight[1]], dp[flight[0]] + flight[2]) 11 | dp = temp 12 | 13 | return dp[dst] if dp[dst] != float('inf') else -1 14 | -------------------------------------------------------------------------------- /791. Custom Sort String/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def customSortString(self, order: str, s: str) -> str: 3 | 4 | ctr = Counter(s) 5 | 6 | ans = [ch*ctr[ch] for ch in order] 7 | 8 | ans.extend(filter(lambda x: x not in order,s)) 9 | 10 | return ''.join(ans) 11 | 12 | -------------------------------------------------------------------------------- /791. Find Center of Star Graph/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findCenter(self, e: List[List[int]]) -> int: 3 | return e[0][0] if e[0][0]==e[1][0] or e[0][0]==e[1][1] else e[0][1] 4 | 5 | 6 | -------------------------------------------------------------------------------- /796. Rotate String/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotateString(self, s: str, goal: str) -> bool: 3 | s += s 4 | return len(s) / 2 == len(goal) and goal in s 5 | -------------------------------------------------------------------------------- /804. Unique Morse Code Words/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def uniqueMorseRepresentations(self, words: List[str]) -> int: 3 | morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] 4 | res = [] 5 | for x in words: 6 | res.append(''.join([morse[ord(c)-97] for c in x])) 7 | return len(set(res)) 8 | -------------------------------------------------------------------------------- /823. Binary Trees With Factors/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numFactoredBinaryTrees(self, arr: List[int]) -> int: 3 | mod=10**9+7 4 | arr.sort() 5 | ans=defaultdict(int) 6 | for a in arr: 7 | tmp=1 8 | for b in arr: 9 | if b>a: 10 | break 11 | tmp+=(ans[b]*ans[a/b]) 12 | ans[a]=tmp 13 | return sum(ans.values())%mod 14 | 15 | -------------------------------------------------------------------------------- /83. Remove Duplicates from Sorted List/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]: 3 | curr = head 4 | while curr and curr.next: 5 | if curr.val == curr.next.val: 6 | curr.next = curr.next.next 7 | else: 8 | curr = curr.next 9 | return head 10 | -------------------------------------------------------------------------------- /844. Backspace String Compare/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def backspaceCompare(self, s: str, t: str) -> bool: 3 | def solve(string): 4 | while '#' in string: 5 | string = re.sub(r'^#|[a-z]#', '', string) 6 | return string 7 | return solve(s) == solve(t) 8 | -------------------------------------------------------------------------------- /861. Score After Flipping Matrix/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def matrixScore(self, grid: List[List[int]]) -> int: 3 | n, m = len(grid), len(grid[0]) 4 | res = (1 << (m - 1)) * n 5 | 6 | for j in range(1, m): 7 | val = 1 << (m - 1 - j) 8 | set_count = 0 9 | 10 | for i in range(n): 11 | if grid[i][j] == grid[i][0]: 12 | set_count += 1 13 | 14 | res += max(set_count, n - set_count) * val 15 | 16 | return res 17 | -------------------------------------------------------------------------------- /862. Shortest Subarray with Sum at Least K/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def shortestSubarray(self, nums: List[int], k: int) -> int: 3 | heap = [] 4 | curr_sum = 0 5 | res = float('inf') 6 | 7 | for i in range(len(nums)): 8 | curr_sum += nums[i] 9 | if k <= curr_sum: 10 | res = min(res, i + 1) 11 | 12 | while heap and k <= curr_sum - heap[0][0]: 13 | res = min(res, i - heapq.heappop(heap)[1]) 14 | 15 | heapq.heappush(heap, (curr_sum, i)) 16 | 17 | return res if res != float('inf') else -1 18 | -------------------------------------------------------------------------------- /867. Transpose Matrix/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def transpose(self, matrix: List[List[int]]) -> List[List[int]]: 3 | res = [] 4 | for i in range(len(matrix[0])): 5 | sv = [] 6 | for j in range(len(matrix)): 7 | sv.append(matrix[j][i]) 8 | res.append(sv) 9 | return res 10 | -------------------------------------------------------------------------------- /876. Middle of the Linked List/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: 3 | slow_pointer = head 4 | fast_pointer = head 5 | 6 | while fast_pointer is not None and fast_pointer.next is not None: 7 | slow_pointer = slow_pointer.next 8 | fast_pointer = fast_pointer.next.next 9 | 10 | return slow_pointer 11 | -------------------------------------------------------------------------------- /88. Merge Sorted Array/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: 3 | """ 4 | Do not return anything, modify nums1 in-place instead. 5 | """ 6 | for i in range(n): 7 | nums1[m+i] = nums2[i] 8 | nums1.sort() 9 | -------------------------------------------------------------------------------- /884. Uncommon Words from Two Sentences/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def uncommonFromSentences(self, s1: str, s2: str) -> List[str]: 3 | # Split the sentences into words 4 | words_s1 = s1.split() 5 | words_s2 = s2.split() 6 | 7 | # Combine all words into one list 8 | all_words = words_s1 + words_s2 9 | 10 | # Count the frequency of each word 11 | word_count = Counter(all_words) 12 | 13 | # Find words that occur exactly once 14 | return [word for word in word_count if word_count[word] == 1] 15 | -------------------------------------------------------------------------------- /896. Monotonic Array/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isMonotonic(self, nums: List[int]) -> bool: 3 | sortedList = sorted(nums) 4 | reversedSorted = sorted(nums) 5 | reversedSorted.reverse() 6 | return sortedList == nums or reversedSorted == nums 7 | -------------------------------------------------------------------------------- /9. Palindrome Number/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPalindrome(self, x: int) -> bool: 3 | s = str(x) 4 | if s == s[::-1]: 5 | return True 6 | else: 7 | return False 8 | -------------------------------------------------------------------------------- /904. Fruit Into Baskets/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def totalFruit(self, fruits: List[int]) -> int: 3 | count = defaultdict(int) 4 | i, j = 0, 0 5 | for j in range(len(fruits)): 6 | count[fruits[j]] += 1 7 | if len(count) > 2: 8 | count[fruits[i]] -= 1 9 | if count[fruits[i]] == 0: 10 | del count[fruits[i]] 11 | i += 1 12 | return j - i + 1 13 | -------------------------------------------------------------------------------- /905. Sort Array By Parity/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortArrayByParity(self, nums: List[int]) -> List[int]: 3 | parity = [] 4 | nonParity = [] 5 | for x in nums: 6 | if x % 2 == 0: 7 | parity.append(x) 8 | else: 9 | nonParity.append(x) 10 | return parity + nonParity 11 | -------------------------------------------------------------------------------- /907. Sum of Subarray Minimums/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sumSubarrayMins(self, arr: List[int]) -> int: 3 | MOD = 10**9+7 4 | ans = 0 5 | minstack = [(-inf, -1, 0)] 6 | for i, x in enumerate(arr): 7 | while minstack[-1][0] >= x: 8 | minstack.pop() 9 | sz = i - minstack[-1][1] 10 | minstack.append((arr[i], i, arr[i]*sz+minstack[-1][2])) 11 | ans += minstack[-1][2] 12 | ans %= MOD 13 | return ans 14 | -------------------------------------------------------------------------------- /91. Decode Ways/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numDecodings(self, s: str) -> int: 3 | forw1 = 1 4 | forw2 = 0 5 | 6 | for i in range(len(s)-1, -1, -1): 7 | if s[i] == "0": 8 | ans = 0 9 | else: 10 | ans = forw1 11 | 12 | if i+1 < len(s) and "0" < s[i:i+2] < "27": 13 | ans += forw2 14 | 15 | forw2 = forw1 16 | forw1 = ans 17 | 18 | return forw1 19 | -------------------------------------------------------------------------------- /921. Minimum Add to Make Parentheses Valid/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minAddToMakeValid(self, s: str) -> int: 3 | open_c = close_c = 0 4 | for c in s: 5 | if c == '(': 6 | open_c += 1 7 | elif c == ')' and open_c > 0: 8 | open_c -= 1 9 | else: 10 | close_c += 1 11 | return open_c + close_c 12 | -------------------------------------------------------------------------------- /929. Unique Email Addresses/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numUniqueEmails(self, emails: List[str]) -> int: 3 | res = set() 4 | for email in emails: 5 | local,domain = email.split('@') 6 | tmp = "" 7 | for c in local: 8 | if c==".": continue 9 | elif c=="+": break 10 | else: tmp+=c 11 | res.add(tmp+"@"+domain) 12 | 13 | return len(res) 14 | -------------------------------------------------------------------------------- /930. Binary Subarrays With Sum/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numSubarraysWithSum(self, nums: List[int], goal: int) -> int: 3 | count = 0 4 | prefix_sum = 0 5 | sum_count = defaultdict(int) 6 | 7 | for num in nums: 8 | prefix_sum += num 9 | if prefix_sum == goal: 10 | count += 1 11 | if prefix_sum - goal in sum_count: 12 | count += sum_count[prefix_sum - goal] 13 | sum_count[prefix_sum] += 1 14 | 15 | return count 16 | -------------------------------------------------------------------------------- /931. Minimum Falling Path Sum/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minFallingPathSum(self, matrix: List[List[int]]) -> int: 3 | m=len(matrix) 4 | for i in range(1,m): 5 | for j in range(m): 6 | matrix[i][j]+=min(matrix[i-1][k] for k in (j-1,j,j+1) if 0<=k and k List[int]: 3 | if root is None: 4 | return [] 5 | return self.inorderTraversal(root.left)+[root.val] + self.inorderTraversal(root.right) 6 | -------------------------------------------------------------------------------- /942. DI String Match/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def diStringMatch(self, s: str) -> List[int]: 3 | res = [] 4 | l, r = 0, len(s) 5 | for char in s: 6 | if char == 'I': 7 | res.append(l) 8 | l += 1 9 | else: 10 | res.append(r) 11 | r -= 1 12 | return res + [l] 13 | 14 | -------------------------------------------------------------------------------- /945. Minimum Increment to Make Array Unique/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minIncrementForUnique(self, nums: List[int]) -> int: 3 | # nums = [3,2,1,2,1,7] 4 | # [1,1,2,2,3,7] 5 | 6 | # mySet = set({ num for num in nums }), 2+4 7 | nums.sort() 8 | numTracker = 0 9 | minIncreament = 0 10 | 11 | for num in nums: 12 | numTracker = max(numTracker, num) 13 | minIncreament += numTracker - num 14 | numTracker += 1 15 | return minIncreament 16 | -------------------------------------------------------------------------------- /948. Bag of Tokens/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def bagOfTokensScore(self, tokens: List[int], power: int) -> int: 3 | r=scr=0 4 | tokens.sort() 5 | i,j= 0,len(tokens)-1 6 | while i<=j: 7 | if power>=tokens[i]: 8 | scr+=1 9 | power-=tokens[i] 10 | i+=1 11 | r=max(r,scr) 12 | elif scr>0: 13 | scr-=1 14 | power+=tokens[j] 15 | j-=1 16 | else: 17 | break 18 | return r 19 | -------------------------------------------------------------------------------- /950. Reveal Cards In Increasing Order/main.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | from collections import deque 3 | 4 | class Solution: 5 | def deckRevealedIncreasing(self, deck: List[int]) -> List[int]: 6 | deck.sort(reverse=True) 7 | dq = deque() 8 | n = len(deck) 9 | dq.appendleft(deck[0]) 10 | for i in range(1, n): 11 | x = dq.pop() 12 | dq.appendleft(x) 13 | dq.appendleft(deck[i]) 14 | 15 | ans = [] 16 | while dq: 17 | ans.append(dq.popleft()) 18 | return ans 19 | -------------------------------------------------------------------------------- /974. Subarray Sums Divisible by K/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subarraysDivByK(self, a: List[int], k: int) -> int: 3 | return (c:=Counter([0])) and sum(c.update([p%k]) or c[p%k]-1 for p in accumulate(a)) 4 | -------------------------------------------------------------------------------- /977. Squares of a Sorted Array/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortedSquares(self, nums: List[int]) -> List[int]: 3 | for i in range(len(nums)): 4 | nums[i] = nums[i]**2 5 | return sorted(nums) 6 | -------------------------------------------------------------------------------- /980. Find Unique Binary String/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDifferentBinaryString(self, nums: List[str]) -> str: 3 | res = [] 4 | for i in range(len(nums)): 5 | if nums[i][i] == '1': 6 | res.append('0') 7 | else: 8 | res.append('1') 9 | return "".join(res) 10 | -------------------------------------------------------------------------------- /995. Minimum Number of K Consecutive Bit Flips/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minKBitFlips(self, nums: List[int], k: int) -> int: 3 | n=len(nums) 4 | x=0 5 | f=[0]*n 6 | 7 | for idx,val in enumerate(nums): 8 | if idx>=k: 9 | x^=f[idx-k] 10 | if x!=val: 11 | continue 12 | if k>n-idx: 13 | return -1 14 | x^=1 15 | f[idx]=1 16 | 17 | return sum(f) 18 | -------------------------------------------------------------------------------- /997. Find the Town Judge/main.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findJudge(self, n: int, trust: List[List[int]]) -> int: 3 | d = {} 4 | for i in range(1, n+1): 5 | d[i] = 0 6 | 7 | for x,y in trust: 8 | d[y] += 1 9 | 10 | trust2 = [x for x,y in trust] 11 | for i in range(1,n+1): 12 | if i not in trust2 and d[i] == n-1: 13 | return i 14 | 15 | return -1 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # leetcode 2 | https://leetcode.com/31b4/ 3 | --------------------------------------------------------------------------------