├── .vscode └── settings.json ├── Algorithms ├── README.md └── src │ ├── 1105. Filling Bookcase Shelves │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1106. Parsing A Boolean Expression │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1140. Stone Game II │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1267. Count Servers that Communicate │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1277. Count Square Submatrices with All Ones │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1331. Rank Transform of an Array │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1368. Minimum Cost to Make at Least One Valid Path in a Grid │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1381. Design a Stack With Increment Operation │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1400. Construct K Palindrome Strings │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1405. Longest Happy String │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1408. String Matching in an Array │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1460. Make Two Arrays Equal by Reversing Subarrays │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1462. Course Schedule IV │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1497. Check If Array Pairs Are Divisible by k │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1509. Minimum Difference Between Largest and Smallest Value in Three Moves │ └── Explanation │ │ └── explanation.md │ ├── 1545. Find Kth Bit in Nth Binary String │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1568. Minimum Number of Days to Disconnect Island │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1574. Shortest Subarray to be Removed to Make Array Sorted │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1590. Make Sum Divisible by P │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1598. Crawler Log Folder │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1671. Minimum Number of Removals to Make Mountain Array │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1701. Average Waiting Time │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1765. Map of Highest Peak │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1769. Minimum Number of Operations to Move All Balls to Each Box │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1813. Sentence Similarity III │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1823. Find the Winner of the Circular Game │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1829. Maximum XOR for Each Query │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1894. Find the Student that Will Replace the Chalk │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1930. Unique Length-3 Palindromic Subsequences │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1937. Maximum Number of Points with Cost │ ├── Code │ │ ├── solutions.cpp │ │ ├── solutions.go │ │ ├── solutions.java │ │ ├── solutions.js │ │ └── solutions.py │ └── Explanation │ │ └── explanation.md │ ├── 1942. The Number of the Smallest Unoccupied Chair │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 1957. Delete Characters to Make Fancy String │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2017. Grid Game │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2022. Convert 1D Array Into 2D Array │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2044. Count Number of Maximum Bitwise-OR Subsets │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2053. Kth Distinct String in an Array │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2064. Minimized Maximum of Products Distributed to Any Store │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2070. Most Beautiful Item for Each Query │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2116. Check if a Parentheses String Can Be Valid │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2127. Maximum Employees to Be Invited to a Meeting │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2134. Minimum Swaps to Group All 1's Together II │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2185. Counting Words With a Given Prefix │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2270. Number of Ways to Split Array │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2275. Largest Combination With Bitwise AND Greater Than Zero │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2381. Shifting Letters II │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2406. Divide Intervals Into Minimum Number of Groups │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2416. Sum of Prefix Scores of Strings │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2425. Bitwise XOR of All Pairings │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2429. Minimize XOR │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2490. Circular Sentence │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2491. Divide Players Into Teams of Equal Skill │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2501. Longest Square Streak in an Array │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2530. Maximal Score After Applying K Operations │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2559. Count Vowel Strings in Ranges │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2563. Count the Number of Fair Pairs │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2601. Prime Subtraction Operation │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2658. Maximum Number of Fish in a Grid │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2661. First Completely Painted Row or Column │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2678. Number of Senior Citizens │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2683. Neighboring Bitwise XOR │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2684. Maximum Number of Moves in a Grid │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2696. Minimum String Length After Removing Substrings │ ├── Code │ │ ├── solution.c++ │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2707. Extra Characters in a String │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 273. Integer to English Words │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2751. Robot Collisions │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 2938. Separate Black and White Balls │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 3042. Count Prefix and Suffix Pairs I │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 3043. Find the Length of the Longest Common Prefix │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 3163. String Compression III │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 3254. Find the Power of K-Size Subarrays I │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 350. Intersection of Two Arrays II │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 386. Lexicographical Numbers │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 40. Combination Sum II │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 407. Trapping Rain Water II │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 432. All O`one Data Structure │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 440. K-th Smallest in Lexicographical Order │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 476. Number Complement │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 567. Permutation in String │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 632. Smallest Range Covering Elements from K Lists │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 641. Design Circular Deque │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 650. 2 Keys Keyboard │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 664. Strange Printer │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 670. Maximum Swap │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 684. Redundant Connection │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 703. Kth Largest Element in a Stream │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 719. Find K-th Smallest Pair Distance │ ├── Code │ │ ├── solution.c++ │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 729. My Calendar I │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 731. My Calendar II │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 796. Rotate String │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 802. Find Eventual Safe States │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 840. Magic Squares In Grid │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 862. Shortest Subarray with Sum at Least K │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 885. Spiral Matrix III │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 916. Word Subsets │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 947. Most Stones Removed with Same Row or Column │ ├── Code │ │ ├── solution.cpp │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ ├── 959. Regions Cut By Slashes │ ├── Code │ │ ├── solution.c++ │ │ ├── solution.go │ │ ├── solution.java │ │ ├── solution.js │ │ └── solution.py │ └── Explanation │ │ └── explanation.md │ └── 962. Maximum Width Ramp │ ├── Code │ ├── solution.cpp │ ├── solution.go │ ├── solution.java │ ├── solution.js │ └── solution.py │ └── Explanation │ └── explanation.md └── README.md /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "array": "cpp", 4 | "deque": "cpp", 5 | "initializer_list": "cpp", 6 | "list": "cpp", 7 | "queue": "cpp", 8 | "ranges": "cpp", 9 | "span": "cpp", 10 | "utility": "cpp", 11 | "vector": "cpp", 12 | "xhash": "cpp", 13 | "xstring": "cpp", 14 | "xutility": "cpp", 15 | "format": "cpp" 16 | } 17 | } -------------------------------------------------------------------------------- /Algorithms/src/1267. Count Servers that Communicate/Code/solution.go: -------------------------------------------------------------------------------- 1 | func countServers(grid [][]int) int { 2 | rows := len(grid) 3 | cols := len(grid[0]) 4 | rowCount := make([]int, rows) 5 | colCount := make([]int, cols) 6 | 7 | // First pass: Count servers in each row and column 8 | for i := 0; i < rows; i++ { 9 | for j := 0; j < cols; j++ { 10 | if grid[i][j] == 1 { 11 | rowCount[i]++ 12 | colCount[j]++ 13 | } 14 | } 15 | } 16 | 17 | // Second pass: Count communicable servers 18 | count := 0 19 | for i := 0; i < rows; i++ { 20 | for j := 0; j < cols; j++ { 21 | if grid[i][j] == 1 && (rowCount[i] > 1 || colCount[j] > 1) { 22 | count++ 23 | } 24 | } 25 | } 26 | return count 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms/src/1267. Count Servers that Communicate/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countServers(int[][] grid) { 3 | int rows = grid.length; 4 | int cols = grid[0].length; 5 | int[] rowCount = new int[rows]; 6 | int[] colCount = new int[cols]; 7 | 8 | // First pass: Count servers in each row and column 9 | for (int i = 0; i < rows; i++) { 10 | for (int j = 0; j < cols; j++) { 11 | if (grid[i][j] == 1) { 12 | rowCount[i]++; 13 | colCount[j]++; 14 | } 15 | } 16 | } 17 | 18 | // Second pass: Count communicable servers 19 | int count = 0; 20 | for (int i = 0; i < rows; i++) { 21 | for (int j = 0; j < cols; j++) { 22 | if (grid[i][j] == 1 && (rowCount[i] > 1 || colCount[j] > 1)) { 23 | count++; 24 | } 25 | } 26 | } 27 | return count; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Algorithms/src/1267. Count Servers that Communicate/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} grid 3 | * @return {number} 4 | */ 5 | var countServers = function (grid) { 6 | const rows = grid.length; 7 | const cols = grid[0].length; 8 | const rowCount = new Array(rows).fill(0); 9 | const colCount = new Array(cols).fill(0); 10 | 11 | // First pass: Count servers in each row and column 12 | for (let i = 0; i < rows; i++) { 13 | for (let j = 0; j < cols; j++) { 14 | if (grid[i][j] === 1) { 15 | rowCount[i]++; 16 | colCount[j]++; 17 | } 18 | } 19 | } 20 | 21 | // Second pass: Count communicable servers 22 | let count = 0; 23 | for (let i = 0; i < rows; i++) { 24 | for (let j = 0; j < cols; j++) { 25 | if (grid[i][j] === 1 && (rowCount[i] > 1 || colCount[j] > 1)) { 26 | count++; 27 | } 28 | } 29 | } 30 | return count; 31 | }; 32 | -------------------------------------------------------------------------------- /Algorithms/src/1267. Count Servers that Communicate/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countServers(self, grid: List[List[int]]) -> int: 3 | rows, cols = len(grid), len(grid[0]) 4 | rowCount = [0] * rows 5 | colCount = [0] * cols 6 | 7 | # First pass: Count servers in each row and column 8 | for i in range(rows): 9 | for j in range(cols): 10 | if grid[i][j] == 1: 11 | rowCount[i] += 1 12 | colCount[j] += 1 13 | 14 | # Second pass: Count communicable servers 15 | count = 0 16 | for i in range(rows): 17 | for j in range(cols): 18 | if grid[i][j] == 1 and (rowCount[i] > 1 or colCount[j] > 1): 19 | count += 1 20 | 21 | return count 22 | -------------------------------------------------------------------------------- /Algorithms/src/1277. Count Square Submatrices with All Ones/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class Solution 5 | { 6 | public: 7 | int countSquares(std::vector> &matrix) 8 | { 9 | int m = matrix.size(); 10 | int n = matrix[0].size(); 11 | std::vector> dp(m, std::vector(n, 0)); 12 | int totalSquares = 0; 13 | 14 | for (int i = 0; i < m; ++i) 15 | { 16 | for (int j = 0; j < n; ++j) 17 | { 18 | if (matrix[i][j] == 1) 19 | { 20 | if (i == 0 || j == 0) 21 | { 22 | dp[i][j] = 1; 23 | } 24 | else 25 | { 26 | dp[i][j] = std::min({dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]}) + 1; 27 | } 28 | totalSquares += dp[i][j]; 29 | } 30 | } 31 | } 32 | 33 | return totalSquares; 34 | } 35 | }; -------------------------------------------------------------------------------- /Algorithms/src/1277. Count Square Submatrices with All Ones/Code/solution.go: -------------------------------------------------------------------------------- 1 | func countSquares(matrix [][]int) int { 2 | m := len(matrix) 3 | n := len(matrix[0]) 4 | dp := make([][]int, m) 5 | for i := range dp { 6 | dp[i] = make([]int, n) 7 | } 8 | totalSquares := 0 9 | 10 | for i := 0; i < m; i++ { 11 | for j := 0; j < n; j++ { 12 | if matrix[i][j] == 1 { 13 | if i == 0 || j == 0 { 14 | dp[i][j] = 1 15 | } else { 16 | dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1 17 | } 18 | totalSquares += dp[i][j] 19 | } 20 | } 21 | } 22 | 23 | return totalSquares 24 | } 25 | 26 | func min(a, b, c int) int { 27 | if a < b && a < c { 28 | return a 29 | } 30 | if b < c { 31 | return b 32 | } 33 | return c 34 | } -------------------------------------------------------------------------------- /Algorithms/src/1277. Count Square Submatrices with All Ones/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countSquares(int[][] matrix) { 3 | int m = matrix.length; 4 | int n = matrix[0].length; 5 | int[][] dp = new int[m][n]; 6 | int totalSquares = 0; 7 | 8 | for (int i = 0; i < m; i++) { 9 | for (int j = 0; j < n; j++) { 10 | if (matrix[i][j] == 1) { 11 | if (i == 0 || j == 0) { 12 | dp[i][j] = 1; 13 | } else { 14 | dp[i][j] = Math.min(Math.min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) + 1; 15 | } 16 | totalSquares += dp[i][j]; 17 | } 18 | } 19 | } 20 | 21 | return totalSquares; 22 | } 23 | } -------------------------------------------------------------------------------- /Algorithms/src/1277. Count Square Submatrices with All Ones/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} matrix 3 | * @return {number} 4 | */ 5 | var countSquares = function (matrix) { 6 | const m = matrix.length; 7 | const n = matrix[0].length; 8 | const dp = Array.from({ length: m }, () => Array(n).fill(0)); 9 | let totalSquares = 0; 10 | 11 | for (let i = 0; i < m; i++) { 12 | for (let j = 0; j < n; j++) { 13 | if (matrix[i][j] === 1) { 14 | if (i === 0 || j === 0) { 15 | dp[i][j] = 1; 16 | } else { 17 | dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1; 18 | } 19 | totalSquares += dp[i][j]; 20 | } 21 | } 22 | } 23 | 24 | return totalSquares; 25 | }; 26 | -------------------------------------------------------------------------------- /Algorithms/src/1277. Count Square Submatrices with All Ones/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countSquares(self, matrix: List[List[int]]) -> int: 3 | m, n = len(matrix), len(matrix[0]) 4 | dp = [[0] * n for _ in range(m)] 5 | total_squares = 0 6 | 7 | for i in range(m): 8 | for j in range(n): 9 | if matrix[i][j] == 1: 10 | if i == 0 or j == 0: 11 | dp[i][j] = 1 12 | else: 13 | dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1 14 | total_squares += dp[i][j] 15 | 16 | return total_squares -------------------------------------------------------------------------------- /Algorithms/src/1331. Rank Transform of an Array/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector arrayRankTransform(vector& arr) { 4 | if (arr.empty()) return {}; 5 | 6 | // Step 1: Copy and sort the array 7 | vector sorted_arr = arr; 8 | sort(sorted_arr.begin(), sorted_arr.end()); 9 | 10 | // Step 2: Create a map to assign ranks 11 | unordered_map rank_map; 12 | int rank = 1; 13 | 14 | // Step 3: Assign ranks to sorted elements 15 | for (int num : sorted_arr) { 16 | if (rank_map.find(num) == rank_map.end()) { 17 | rank_map[num] = rank++; 18 | } 19 | } 20 | 21 | // Step 4: Replace each element in the original array with its rank 22 | for (int i = 0; i < arr.size(); ++i) { 23 | arr[i] = rank_map[arr[i]]; 24 | } 25 | 26 | return arr; 27 | } 28 | }; -------------------------------------------------------------------------------- /Algorithms/src/1331. Rank Transform of an Array/Code/solution.go: -------------------------------------------------------------------------------- 1 | import "sort" 2 | 3 | func arrayRankTransform(arr []int) []int { 4 | if len(arr) == 0 { 5 | return []int{} 6 | } 7 | 8 | // Step 1: Create a sorted copy of the array 9 | sortedArr := make([]int, len(arr)) 10 | copy(sortedArr, arr) 11 | sort.Ints(sortedArr) 12 | 13 | // Step 2: Create a map to assign ranks 14 | rankMap := make(map[int]int) 15 | rank := 1 16 | 17 | // Step 3: Assign ranks to sorted elements 18 | for _, num := range sortedArr { 19 | if _, exists := rankMap[num]; !exists { 20 | rankMap[num] = rank 21 | rank++ 22 | } 23 | } 24 | 25 | // Step 4: Replace each element in the original array with its rank 26 | for i, num := range arr { 27 | arr[i] = rankMap[num] 28 | } 29 | 30 | return arr 31 | } -------------------------------------------------------------------------------- /Algorithms/src/1331. Rank Transform of an Array/Code/solution.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Solution { 4 | public int[] arrayRankTransform(int[] arr) { 5 | if (arr.length == 0) return new int[0]; 6 | 7 | // Step 1: Create a sorted copy of the array 8 | int[] sortedArr = arr.clone(); 9 | Arrays.sort(sortedArr); 10 | 11 | // Step 2: Create a map to store the rank of each element 12 | Map rankMap = new HashMap<>(); 13 | int rank = 1; 14 | 15 | // Step 3: Assign ranks to sorted elements 16 | for (int num : sortedArr) { 17 | if (!rankMap.containsKey(num)) { 18 | rankMap.put(num, rank++); 19 | } 20 | } 21 | 22 | // Step 4: Replace each element in the original array with its rank 23 | for (int i = 0; i < arr.length; i++) { 24 | arr[i] = rankMap.get(arr[i]); 25 | } 26 | 27 | return arr; 28 | } 29 | } -------------------------------------------------------------------------------- /Algorithms/src/1331. Rank Transform of an Array/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @return {number[]} 4 | */ 5 | var arrayRankTransform = function (arr) { 6 | if (arr.length === 0) return []; 7 | 8 | // Step 1: Create a sorted copy of the array 9 | let sortedArr = [...arr]; 10 | sortedArr.sort((a, b) => a - b); 11 | 12 | // Step 2: Create a map to store the rank of each element 13 | let rankMap = new Map(); 14 | let rank = 1; 15 | 16 | // Step 3: Assign ranks to sorted elements 17 | for (let num of sortedArr) { 18 | if (!rankMap.has(num)) { 19 | rankMap.set(num, rank++); 20 | } 21 | } 22 | 23 | // Step 4: Replace each element in the original array with its rank 24 | for (let i = 0; i < arr.length; i++) { 25 | arr[i] = rankMap.get(arr[i]); 26 | } 27 | 28 | return arr; 29 | }; 30 | -------------------------------------------------------------------------------- /Algorithms/src/1331. Rank Transform of an Array/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def arrayRankTransform(self, arr: List[int]) -> List[int]: 3 | if not arr: 4 | return [] 5 | 6 | # Step 1: Create a sorted copy of the array 7 | sorted_arr = sorted(arr) 8 | 9 | # Step 2: Create a dictionary to assign ranks 10 | rank_map = {} 11 | rank = 1 12 | 13 | # Step 3: Assign ranks to sorted elements 14 | for num in sorted_arr: 15 | if num not in rank_map: 16 | rank_map[num] = rank 17 | rank += 1 18 | 19 | # Step 4: Replace each element in the original array with its rank 20 | return [rank_map[num] for num in arr] -------------------------------------------------------------------------------- /Algorithms/src/1368. Minimum Cost to Make at Least One Valid Path in a Grid/Code/solution.js: -------------------------------------------------------------------------------- 1 | var minCost = function (grid) { 2 | const m = grid.length, 3 | n = grid[0].length; 4 | const directions = [ 5 | [0, 1], 6 | [0, -1], 7 | [1, 0], 8 | [-1, 0], 9 | ]; 10 | const cost = Array.from({ length: m }, () => Array(n).fill(Infinity)); 11 | const deque = []; 12 | deque.push([0, 0]); 13 | cost[0][0] = 0; 14 | 15 | while (deque.length) { 16 | const [x, y] = deque.shift(); 17 | for (let i = 0; i < 4; i++) { 18 | const nx = x + directions[i][0]; 19 | const ny = y + directions[i][1]; 20 | const newCost = cost[x][y] + (grid[x][y] !== i + 1 ? 1 : 0); 21 | 22 | if (nx >= 0 && ny >= 0 && nx < m && ny < n && newCost < cost[nx][ny]) { 23 | cost[nx][ny] = newCost; 24 | if (grid[x][y] === i + 1) deque.unshift([nx, ny]); 25 | else deque.push([nx, ny]); 26 | } 27 | } 28 | } 29 | return cost[m - 1][n - 1]; 30 | }; 31 | -------------------------------------------------------------------------------- /Algorithms/src/1368. Minimum Cost to Make at Least One Valid Path in a Grid/Code/solution.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | class Solution: 4 | def minCost(self, grid: List[List[int]]) -> int: 5 | m, n = len(grid), len(grid[0]) 6 | directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] 7 | cost = [[float('inf')] * n for _ in range(m)] 8 | dq = deque([(0, 0)]) 9 | cost[0][0] = 0 10 | 11 | while dq: 12 | x, y = dq.popleft() 13 | for i, (dx, dy) in enumerate(directions): 14 | nx, ny = x + dx, y + dy 15 | new_cost = cost[x][y] + (grid[x][y] != i + 1) 16 | 17 | if 0 <= nx < m and 0 <= ny < n and new_cost < cost[nx][ny]: 18 | cost[nx][ny] = new_cost 19 | if grid[x][y] == i + 1: 20 | dq.appendleft((nx, ny)) 21 | else: 22 | dq.append((nx, ny)) 23 | return cost[m - 1][n - 1] 24 | -------------------------------------------------------------------------------- /Algorithms/src/1381. Design a Stack With Increment Operation/Code/solution.js: -------------------------------------------------------------------------------- 1 | var CustomStack = function (maxSize) { 2 | this.maxSize = maxSize; 3 | this.stack = []; 4 | this.inc = []; 5 | }; 6 | 7 | CustomStack.prototype.push = function (x) { 8 | if (this.stack.length < this.maxSize) { 9 | this.stack.push(x); 10 | this.inc.push(0); // Initialize increment for this element 11 | } 12 | }; 13 | 14 | CustomStack.prototype.pop = function () { 15 | if (this.stack.length === 0) { 16 | return -1; 17 | } 18 | let idx = this.stack.length - 1; 19 | let result = this.stack[idx] + this.inc[idx]; // Apply any pending increments 20 | if (idx > 0) { 21 | this.inc[idx - 1] += this.inc[idx]; // Propagate increment to the next element 22 | } 23 | this.stack.pop(); 24 | this.inc.pop(); 25 | return result; 26 | }; 27 | 28 | CustomStack.prototype.increment = function (k, val) { 29 | let limit = Math.min(k, this.stack.length) - 1; 30 | if (limit >= 0) { 31 | this.inc[limit] += val; // Add increment to the bottom k-th element 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Algorithms/src/1381. Design a Stack With Increment Operation/Code/solution.py: -------------------------------------------------------------------------------- 1 | class CustomStack: 2 | 3 | def __init__(self, maxSize: int): 4 | self.maxSize = maxSize 5 | self.stack = [] 6 | self.inc = [] 7 | 8 | def push(self, x: int) -> None: 9 | if len(self.stack) < self.maxSize: 10 | self.stack.append(x) 11 | self.inc.append(0) # Initialize increment for this element 12 | 13 | def pop(self) -> int: 14 | if not self.stack: 15 | return -1 16 | idx = len(self.stack) - 1 17 | result = self.stack[idx] + self.inc[idx] # Apply any pending increments 18 | if idx > 0: 19 | self.inc[idx - 1] += self.inc[idx] # Propagate increment to the next element 20 | self.stack.pop() 21 | self.inc.pop() 22 | return result 23 | 24 | def increment(self, k: int, val: int) -> None: 25 | limit = min(k, len(self.stack)) - 1 26 | if limit >= 0: 27 | self.inc[limit] += val # Add increment to the bottom k-th element -------------------------------------------------------------------------------- /Algorithms/src/1400. Construct K Palindrome Strings/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canConstruct(string s, int k) { 4 | if (k > s.length()) return false; // More palindromes than characters 5 | vector freq(26, 0); // Frequency array for lowercase letters 6 | for (char c : s) { 7 | freq[c - 'a']++; 8 | } 9 | int oddCount = 0; 10 | for (int count : freq) { 11 | if (count % 2 != 0) { 12 | oddCount++; 13 | } 14 | } 15 | return oddCount <= k; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Algorithms/src/1400. Construct K Palindrome Strings/Code/solution.go: -------------------------------------------------------------------------------- 1 | func canConstruct(s string, k int) bool { 2 | if k > len(s) { 3 | return false // More palindromes than characters 4 | } 5 | freq := make([]int, 26) // Frequency array for lowercase letters 6 | for _, char := range s { 7 | freq[char-'a']++ 8 | } 9 | oddCount := 0 10 | for _, count := range freq { 11 | if count%2 != 0 { 12 | oddCount++ 13 | } 14 | } 15 | return oddCount <= k 16 | } 17 | -------------------------------------------------------------------------------- /Algorithms/src/1400. Construct K Palindrome Strings/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canConstruct(String s, int k) { 3 | if (k > s.length()) 4 | return false; // More palindromes than characters 5 | int[] freq = new int[26]; // Frequency array for lowercase letters 6 | for (char c : s.toCharArray()) { 7 | freq[c - 'a']++; 8 | } 9 | int oddCount = 0; 10 | for (int count : freq) { 11 | if (count % 2 != 0) { 12 | oddCount++; 13 | } 14 | } 15 | return oddCount <= k; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Algorithms/src/1400. Construct K Palindrome Strings/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @param {number} k 4 | * @return {boolean} 5 | */ 6 | var canConstruct = function (s, k) { 7 | if (k > s.length) return false; // More palindromes than characters 8 | let freq = Array(26).fill(0); // Frequency array for lowercase letters 9 | for (let char of s) { 10 | freq[char.charCodeAt(0) - 97]++; 11 | } 12 | let oddCount = 0; 13 | for (let count of freq) { 14 | if (count % 2 !== 0) { 15 | oddCount++; 16 | } 17 | } 18 | return oddCount <= k; 19 | }; 20 | -------------------------------------------------------------------------------- /Algorithms/src/1400. Construct K Palindrome Strings/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canConstruct(self, s: str, k: int) -> bool: 3 | if k > len(s): 4 | return False # More palindromes than characters 5 | freq = [0] * 26 # Frequency array for lowercase letters 6 | for char in s: 7 | freq[ord(char) - ord('a')] += 1 8 | odd_count = sum(1 for count in freq if count % 2 != 0) 9 | return odd_count <= k 10 | -------------------------------------------------------------------------------- /Algorithms/src/1408. String Matching in an Array/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector stringMatching(vector &words) 5 | { 6 | // Sort words by length 7 | sort(words.begin(), words.end(), [](const string &a, const string &b) 8 | { return a.size() < b.size(); }); 9 | 10 | vector result; 11 | 12 | // Check for substrings 13 | for (int i = 0; i < words.size(); ++i) 14 | { 15 | for (int j = i + 1; j < words.size(); ++j) 16 | { 17 | if (words[j].find(words[i]) != string::npos) 18 | { 19 | result.push_back(words[i]); 20 | break; 21 | } 22 | } 23 | } 24 | 25 | return result; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Algorithms/src/1408. String Matching in an Array/Code/solution.go: -------------------------------------------------------------------------------- 1 | import "sort" 2 | 3 | func stringMatching(words []string) []string { 4 | // Sort words by length 5 | sort.Slice(words, func(i, j int) bool { 6 | return len(words[i]) < len(words[j]) 7 | }) 8 | 9 | result := []string{} 10 | 11 | // Check for substrings 12 | for i := 0; i < len(words); i++ { 13 | for j := i + 1; j < len(words); j++ { 14 | if strings.Contains(words[j], words[i]) { 15 | result = append(result, words[i]) 16 | break 17 | } 18 | } 19 | } 20 | 21 | return result 22 | } 23 | -------------------------------------------------------------------------------- /Algorithms/src/1408. String Matching in an Array/Code/solution.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Solution { 4 | public List stringMatching(String[] words) { 5 | // Sort words by length 6 | Arrays.sort(words, (a, b) -> a.length() - b.length()); 7 | 8 | List result = new ArrayList<>(); 9 | 10 | // Check for substrings 11 | for (int i = 0; i < words.length; i++) { 12 | for (int j = i + 1; j < words.length; j++) { 13 | if (words[j].contains(words[i])) { 14 | result.add(words[i]); 15 | break; 16 | } 17 | } 18 | } 19 | 20 | return result; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Algorithms/src/1408. String Matching in an Array/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string[]} words 3 | * @return {string[]} 4 | */ 5 | var stringMatching = function (words) { 6 | // Sort words by length 7 | words.sort((a, b) => a.length - b.length); 8 | 9 | const result = []; 10 | 11 | // Check for substrings 12 | for (let i = 0; i < words.length; i++) { 13 | for (let j = i + 1; j < words.length; j++) { 14 | if (words[j].includes(words[i])) { 15 | result.push(words[i]); 16 | break; 17 | } 18 | } 19 | } 20 | 21 | return result; 22 | }; 23 | -------------------------------------------------------------------------------- /Algorithms/src/1408. String Matching in an Array/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def stringMatching(self, words: List[str]) -> List[str]: 3 | # Sort words by length 4 | words.sort(key=len) 5 | 6 | result = [] 7 | 8 | # Check for substrings 9 | for i in range(len(words)): 10 | for j in range(i + 1, len(words)): 11 | if words[i] in words[j]: 12 | result.append(words[i]) 13 | break 14 | 15 | return result 16 | -------------------------------------------------------------------------------- /Algorithms/src/1460. Make Two Arrays Equal by Reversing Subarrays/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include // For std::sort 3 | 4 | class Solution 5 | { 6 | public: 7 | bool canBeEqual(std::vector &target, std::vector &arr) 8 | { 9 | // Step 1: Sort the 'target' array 10 | // Sorting helps in comparing the arrays element by element in a straightforward manner 11 | std::sort(target.begin(), target.end()); 12 | 13 | // Step 2: Sort the 'arr' array 14 | // After sorting both arrays, they should have the same elements in the same order if they can be made equal 15 | std::sort(arr.begin(), arr.end()); 16 | 17 | // Step 3: Compare the sorted arrays 18 | // If the sorted arrays are identical, it means the original arrays can be made equal by reordering 19 | return target == arr; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Algorithms/src/1460. Make Two Arrays Equal by Reversing Subarrays/Code/solution.go: -------------------------------------------------------------------------------- 1 | import "sort" 2 | 3 | // canBeEqual checks if the target array can be made equal to the arr array 4 | // by sorting both arrays and comparing their elements. 5 | func canBeEqual(target []int, arr []int) bool { 6 | // Step 1: Sort the target array in ascending order. 7 | sort.Ints(target) 8 | // Step 2: Sort the arr array in ascending order. 9 | sort.Ints(arr) 10 | 11 | // Step 3: Compare each element of the sorted target array with the sorted arr array. 12 | for i := range target { 13 | // Step 4: If any corresponding elements are not equal, return false. 14 | if target[i] != arr[i] { 15 | return false 16 | } 17 | } 18 | // Step 5: If all elements match, return true. 19 | return true 20 | } 21 | -------------------------------------------------------------------------------- /Algorithms/src/1460. Make Two Arrays Equal by Reversing Subarrays/Code/solution.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class Solution { 4 | /** 5 | * This method checks if two arrays can be made equal by sorting them. 6 | * 7 | * @param target The target array we want to compare to. 8 | * @param arr The array that we want to manipulate and compare to the target 9 | * array. 10 | * @return true if both arrays can be made equal by sorting, otherwise false. 11 | */ 12 | public boolean canBeEqual(int[] target, int[] arr) { 13 | // Step 1: Sort the target array 14 | Arrays.sort(target); 15 | 16 | // Step 2: Sort the arr array 17 | Arrays.sort(arr); 18 | 19 | // Step 3: Compare the sorted target and arr arrays 20 | // If they are equal, it means the original arrays can be rearranged to match 21 | // each other 22 | return Arrays.equals(target, arr); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Algorithms/src/1460. Make Two Arrays Equal by Reversing Subarrays/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Determines if one array can be made equal to another by sorting. 3 | * 4 | * @param {number[]} target - The target array to compare against. 5 | * @param {number[]} arr - The array that needs to be checked for equality with the target array. 6 | * @return {boolean} - Returns true if the sorted arrays are equal, otherwise false. 7 | */ 8 | var canBeEqual = function (target, arr) { 9 | // Step 1: Sort the target array in ascending order 10 | target.sort((a, b) => a - b); 11 | 12 | // Step 2: Sort the arr array in ascending order 13 | arr.sort((a, b) => a - b); 14 | 15 | // Step 3: Convert both sorted arrays to strings and compare them 16 | // If both strings are equal, it means both arrays have the same elements in the same order 17 | return target.toString() === arr.toString(); 18 | }; 19 | -------------------------------------------------------------------------------- /Algorithms/src/1460. Make Two Arrays Equal by Reversing Subarrays/Code/solution.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def canBeEqual(self, target: List[int], arr: List[int]) -> bool: 5 | # Step 1: Sort the target array 6 | target.sort() 7 | 8 | # Step 2: Sort the arr array 9 | arr.sort() 10 | 11 | # Step 3: Compare the sorted target and arr arrays 12 | # If they are equal, it means that one can be rearranged to match the other 13 | return target == arr 14 | -------------------------------------------------------------------------------- /Algorithms/src/1462. Course Schedule IV/Code/solution.go: -------------------------------------------------------------------------------- 1 | func checkIfPrerequisite(numCourses int, prerequisites [][]int, queries [][]int) []bool { 2 | // Initialize the graph 3 | graph := make([][]bool, numCourses) 4 | for i := 0; i < numCourses; i++ { 5 | graph[i] = make([]bool, numCourses) 6 | } 7 | 8 | // Build the direct edges from prerequisites 9 | for _, edge := range prerequisites { 10 | graph[edge[0]][edge[1]] = true 11 | } 12 | 13 | // Floyd-Warshall to compute transitive closure 14 | for k := 0; k < numCourses; k++ { 15 | for i := 0; i < numCourses; i++ { 16 | for j := 0; j < numCourses; j++ { 17 | if graph[i][k] && graph[k][j] { 18 | graph[i][j] = true 19 | } 20 | } 21 | } 22 | } 23 | 24 | // Answer the queries 25 | result := make([]bool, len(queries)) 26 | for i, query := range queries { 27 | result[i] = graph[query[0]][query[1]] 28 | } 29 | 30 | return result 31 | } 32 | -------------------------------------------------------------------------------- /Algorithms/src/1462. Course Schedule IV/Code/solution.js: -------------------------------------------------------------------------------- 1 | var checkIfPrerequisite = function (numCourses, prerequisites, queries) { 2 | // Initialize the graph 3 | const graph = Array.from({ length: numCourses }, () => 4 | Array(numCourses).fill(false) 5 | ); 6 | 7 | // Build the direct edges from prerequisites 8 | for (const [u, v] of prerequisites) { 9 | graph[u][v] = true; 10 | } 11 | 12 | // Floyd-Warshall to compute transitive closure 13 | for (let k = 0; k < numCourses; k++) { 14 | for (let i = 0; i < numCourses; i++) { 15 | for (let j = 0; j < numCourses; j++) { 16 | if (graph[i][k] && graph[k][j]) { 17 | graph[i][j] = true; 18 | } 19 | } 20 | } 21 | } 22 | 23 | // Answer the queries 24 | return queries.map(([u, v]) => graph[u][v]); 25 | }; 26 | -------------------------------------------------------------------------------- /Algorithms/src/1462. Course Schedule IV/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]: 3 | # Initialize the graph 4 | graph = [[False] * numCourses for _ in range(numCourses)] 5 | 6 | # Build the direct edges from prerequisites 7 | for u, v in prerequisites: 8 | graph[u][v] = True 9 | 10 | # Floyd-Warshall to compute transitive closure 11 | for k in range(numCourses): 12 | for i in range(numCourses): 13 | for j in range(numCourses): 14 | if graph[i][k] and graph[k][j]: 15 | graph[i][j] = True 16 | 17 | # Answer the queries 18 | return [graph[u][v] for u, v in queries] 19 | -------------------------------------------------------------------------------- /Algorithms/src/1497. Check If Array Pairs Are Divisible by k/Code/solution.go: -------------------------------------------------------------------------------- 1 | func canArrange(arr []int, k int) bool { 2 | // Frequency array to store the count of remainders 3 | remainderFreq := make([]int, k) 4 | 5 | // Step 1: Calculate the remainder for each element and store the frequency 6 | for _, num := range arr { 7 | remainder := ((num % k) + k) % k // Ensure non-negative remainder 8 | remainderFreq[remainder]++ 9 | } 10 | 11 | // Step 2: Check if the pairing condition holds 12 | for i := 0; i <= k/2; i++ { 13 | if i == 0 { 14 | // Elements with remainder 0 must pair among themselves 15 | if remainderFreq[i] % 2 != 0 { 16 | return false 17 | } 18 | } else { 19 | // Remainder i must pair with remainder k-i 20 | if remainderFreq[i] != remainderFreq[k-i] { 21 | return false 22 | } 23 | } 24 | } 25 | 26 | return true 27 | } -------------------------------------------------------------------------------- /Algorithms/src/1497. Check If Array Pairs Are Divisible by k/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canArrange(int[] arr, int k) { 3 | // Frequency array to store the count of remainders 4 | int[] remainderFreq = new int[k]; 5 | 6 | // Step 1: Calculate the remainder for each element and store the frequency 7 | for (int num : arr) { 8 | int remainder = (num % k + k) % k; // Ensure non-negative remainder 9 | remainderFreq[remainder]++; 10 | } 11 | 12 | // Step 2: Check if the pairing condition holds 13 | for (int i = 0; i <= k / 2; i++) { 14 | if (i == 0) { 15 | // Elements with remainder 0 must pair among themselves 16 | if (remainderFreq[i] % 2 != 0) 17 | return false; 18 | } else { 19 | // Remainder i must pair with remainder k-i 20 | if (remainderFreq[i] != remainderFreq[k - i]) 21 | return false; 22 | } 23 | } 24 | 25 | return true; 26 | } 27 | } -------------------------------------------------------------------------------- /Algorithms/src/1497. Check If Array Pairs Are Divisible by k/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @param {number} k 4 | * @return {boolean} 5 | */ 6 | var canArrange = function (arr, k) { 7 | // Frequency array to store the count of remainders 8 | let remainderFreq = new Array(k).fill(0); 9 | 10 | // Step 1: Calculate the remainder for each element and store the frequency 11 | for (let num of arr) { 12 | let remainder = ((num % k) + k) % k; // Ensure non-negative remainder 13 | remainderFreq[remainder]++; 14 | } 15 | 16 | // Step 2: Check if the pairing condition holds 17 | for (let i = 0; i <= Math.floor(k / 2); i++) { 18 | if (i === 0) { 19 | // Elements with remainder 0 must pair among themselves 20 | if (remainderFreq[i] % 2 !== 0) return false; 21 | } else { 22 | // Remainder i must pair with remainder k-i 23 | if (remainderFreq[i] !== remainderFreq[k - i]) return false; 24 | } 25 | } 26 | 27 | return true; 28 | }; 29 | -------------------------------------------------------------------------------- /Algorithms/src/1497. Check If Array Pairs Are Divisible by k/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canArrange(self, arr: List[int], k: int) -> bool: 3 | # Frequency array to store the count of remainders 4 | remainderFreq = [0] * k 5 | 6 | # Step 1: Calculate the remainder for each element and store the frequency 7 | for num in arr: 8 | remainder = (num % k + k) % k # Ensure non-negative remainder 9 | remainderFreq[remainder] += 1 10 | 11 | # Step 2: Check if the pairing condition holds 12 | for i in range(k // 2 + 1): 13 | if i == 0: 14 | # Elements with remainder 0 must pair among themselves 15 | if remainderFreq[i] % 2 != 0: 16 | return False 17 | else: 18 | # Remainder i must pair with remainder k-i 19 | if remainderFreq[i] != remainderFreq[k - i]: 20 | return False 21 | 22 | return True -------------------------------------------------------------------------------- /Algorithms/src/1545. Find Kth Bit in Nth Binary String/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | char findKthBit(int n, int k) 5 | { 6 | // Base case: When n = 1, the binary string is "0" 7 | if (n == 1) 8 | return '0'; 9 | 10 | // Find the length of the current string Sn, which is 2^n - 1 11 | int length = (1 << n) - 1; 12 | 13 | // Find the middle position 14 | int mid = length / 2 + 1; 15 | 16 | // If k is the middle position, return '1' 17 | if (k == mid) 18 | return '1'; 19 | 20 | // If k is in the first half, find the bit in Sn-1 21 | if (k < mid) 22 | return findKthBit(n - 1, k); 23 | 24 | // If k is in the second half, find the bit in Sn-1 and invert it 25 | return findKthBit(n - 1, length - k + 1) == '0' ? '1' : '0'; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Algorithms/src/1545. Find Kth Bit in Nth Binary String/Code/solution.go: -------------------------------------------------------------------------------- 1 | func findKthBit(n int, k int) byte { 2 | // Base case: When n = 1, the binary string is "0" 3 | if n == 1 { 4 | return '0' 5 | } 6 | 7 | // Find the length of the current string Sn, which is 2^n - 1 8 | length := (1 << n) - 1 9 | 10 | // Find the middle position 11 | mid := length / 2 + 1 12 | 13 | // If k is the middle position, return '1' 14 | if k == mid { 15 | return '1' 16 | } 17 | 18 | // If k is in the first half, find the bit in Sn-1 19 | if k < mid { 20 | return findKthBit(n - 1, k) 21 | } 22 | 23 | // If k is in the second half, find the bit in Sn-1 and invert it 24 | if findKthBit(n - 1, length - k + 1) == '0' { 25 | return '1' 26 | } 27 | return '0' 28 | } 29 | -------------------------------------------------------------------------------- /Algorithms/src/1545. Find Kth Bit in Nth Binary String/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public char findKthBit(int n, int k) { 3 | // Base case: When n = 1, the binary string is "0" 4 | if (n == 1) 5 | return '0'; 6 | 7 | // Find the length of the current string Sn, which is 2^n - 1 8 | int length = (1 << n) - 1; 9 | 10 | // Find the middle position 11 | int mid = length / 2 + 1; 12 | 13 | // If k is the middle position, return '1' 14 | if (k == mid) 15 | return '1'; 16 | 17 | // If k is in the first half, find the bit in Sn-1 18 | if (k < mid) 19 | return findKthBit(n - 1, k); 20 | 21 | // If k is in the second half, find the bit in Sn-1 and invert it 22 | return findKthBit(n - 1, length - k + 1) == '0' ? '1' : '0'; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Algorithms/src/1545. Find Kth Bit in Nth Binary String/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} n 3 | * @param {number} k 4 | * @return {character} 5 | */ 6 | var findKthBit = function (n, k) { 7 | // Base case: When n = 1, the binary string is "0" 8 | if (n === 1) return "0"; 9 | 10 | // Find the length of the current string Sn, which is 2^n - 1 11 | let length = (1 << n) - 1; 12 | 13 | // Find the middle position 14 | let mid = Math.floor(length / 2) + 1; 15 | 16 | // If k is the middle position, return '1' 17 | if (k === mid) return "1"; 18 | 19 | // If k is in the first half, find the bit in Sn-1 20 | if (k < mid) return findKthBit(n - 1, k); 21 | 22 | // If k is in the second half, find the bit in Sn-1 and invert it 23 | return findKthBit(n - 1, length - k + 1) === "0" ? "1" : "0"; 24 | }; 25 | -------------------------------------------------------------------------------- /Algorithms/src/1545. Find Kth Bit in Nth Binary String/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findKthBit(self, n: int, k: int) -> str: 3 | # Base case: When n = 1, the binary string is "0" 4 | if n == 1: 5 | return '0' 6 | 7 | # Find the length of the current string Sn, which is 2^n - 1 8 | length = (1 << n) - 1 9 | 10 | # Find the middle position 11 | mid = length // 2 + 1 12 | 13 | # If k is the middle position, return '1' 14 | if k == mid: 15 | return '1' 16 | 17 | # If k is in the first half, find the bit in Sn-1 18 | if k < mid: 19 | return self.findKthBit(n - 1, k) 20 | 21 | # If k is in the second half, find the bit in Sn-1 and invert it 22 | return '1' if self.findKthBit(n - 1, length - k + 1) == '0' else '0' 23 | -------------------------------------------------------------------------------- /Algorithms/src/1590. Make Sum Divisible by P/Code/solution.go: -------------------------------------------------------------------------------- 1 | func minSubarray(nums []int, p int) int { 2 | totalSum := 0 3 | for _, num := range nums { 4 | totalSum += num 5 | } 6 | 7 | rem := totalSum % p 8 | if rem == 0 { 9 | return 0 10 | } 11 | 12 | prefixMod := make(map[int]int) 13 | prefixMod[0] = -1 14 | prefixSum, minLength := 0, len(nums) 15 | 16 | for i, num := range nums { 17 | prefixSum += num 18 | currentMod := prefixSum % p 19 | targetMod := (currentMod - rem + p) % p 20 | 21 | if idx, ok := prefixMod[targetMod]; ok { 22 | if i-idx < minLength { 23 | minLength = i - idx 24 | } 25 | } 26 | 27 | prefixMod[currentMod] = i 28 | } 29 | 30 | if minLength == len(nums) { 31 | return -1 32 | } 33 | return minLength 34 | } -------------------------------------------------------------------------------- /Algorithms/src/1590. Make Sum Divisible by P/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} p 4 | * @return {number} 5 | */ 6 | var minSubarray = function (nums, p) { 7 | let totalSum = nums.reduce((a, b) => a + b, 0); 8 | 9 | // Find the remainder when total sum is divided by p 10 | let rem = totalSum % p; 11 | if (rem === 0) return 0; // If the remainder is 0, no subarray needs to be removed 12 | 13 | let prefixMod = new Map(); 14 | prefixMod.set(0, -1); // Initialize to handle full prefix 15 | let prefixSum = 0; 16 | let minLength = nums.length; 17 | 18 | for (let i = 0; i < nums.length; i++) { 19 | prefixSum += nums[i]; 20 | let currentMod = prefixSum % p; 21 | let targetMod = (currentMod - rem + p) % p; 22 | 23 | if (prefixMod.has(targetMod)) { 24 | minLength = Math.min(minLength, i - prefixMod.get(targetMod)); 25 | } 26 | 27 | prefixMod.set(currentMod, i); 28 | } 29 | 30 | return minLength === nums.length ? -1 : minLength; 31 | }; 32 | -------------------------------------------------------------------------------- /Algorithms/src/1590. Make Sum Divisible by P/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minSubarray(self, nums: List[int], p: int) -> int: 3 | totalSum = sum(nums) 4 | rem = totalSum % p 5 | 6 | if rem == 0: 7 | return 0 8 | 9 | prefixMod = {0: -1} 10 | prefixSum = 0 11 | minLength = len(nums) 12 | 13 | for i, num in enumerate(nums): 14 | prefixSum += num 15 | currentMod = prefixSum % p 16 | targetMod = (currentMod - rem + p) % p 17 | 18 | if targetMod in prefixMod: 19 | minLength = min(minLength, i - prefixMod[targetMod]) 20 | 21 | prefixMod[currentMod] = i 22 | 23 | return minLength if minLength < len(nums) else -1 -------------------------------------------------------------------------------- /Algorithms/src/1598. Crawler Log Folder/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int minOperations(vector &logs) 5 | { 6 | int depth = 0; // Initialize depth to 0, representing the root directory 7 | for (const string &log : logs) 8 | { // Iterate over each log in the logs vector 9 | if (log == "../") 10 | { // If the log is "../", move one level up 11 | if (depth > 0) 12 | depth--; // Only move up if depth is greater than 0 13 | } 14 | else if (log != "./") 15 | { // If the log is not "./", move one level down 16 | depth++; // Increase depth to represent moving into a subdirectory 17 | } 18 | // No action is needed for "./" since it represents staying in the current directory 19 | } 20 | return depth; // Return the final depth, representing the folder level from the root 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Algorithms/src/1598. Crawler Log Folder/Code/solution.go: -------------------------------------------------------------------------------- 1 | // minOperations calculates the minimum number of operations to reach the main folder 2 | // given a list of folder navigation logs. 3 | func minOperations(logs []string) int { 4 | // Initialize depth to 0, representing the main folder 5 | depth := 0 6 | 7 | // Iterate through each log entry 8 | for _, log := range logs { 9 | // If the log is "../", move up one directory if not already at the root 10 | if log == "../" { 11 | if depth > 0 { 12 | depth-- // Decrease depth to move up one directory 13 | } 14 | // If the log is "./", stay in the current directory (do nothing) 15 | } else if log != "./" { 16 | depth++ // Increase depth to move into a subdirectory 17 | } 18 | } 19 | 20 | // Return the current depth, representing the minimum operations needed 21 | return depth 22 | } 23 | -------------------------------------------------------------------------------- /Algorithms/src/1598. Crawler Log Folder/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minOperations(String[] logs) { 3 | int depth = 0; // Initialize depth to 0, representing the root directory 4 | 5 | // Iterate over each log entry in the logs array 6 | for (String log : logs) { 7 | // If the log entry is "../", move one directory up if not already at the root 8 | if (log.equals("../")) { 9 | if (depth > 0) { 10 | depth--; // Decrease depth by 1 11 | } 12 | } 13 | // If the log entry is "./", it means stay in the same directory, do nothing 14 | else if (!log.equals("./")) { 15 | depth++; // For any other log entry (representing a folder), increase depth by 1 16 | } 17 | } 18 | 19 | // Return the final calculated depth, which is the minimum number of operations 20 | // to return to the main folder 21 | return depth; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Algorithms/src/1598. Crawler Log Folder/Code/solution.js: -------------------------------------------------------------------------------- 1 | var minOperations = function (logs) { 2 | // Initialize the depth of the current directory to 0 3 | let depth = 0; 4 | 5 | // Loop through each log in the logs array 6 | for (const log of logs) { 7 | // If the log indicates moving up one directory level 8 | if (log === "../") { 9 | // Decrease depth if it's greater than 0 (cannot go above the root directory) 10 | if (depth > 0) depth--; 11 | } 12 | // If the log is not a no-op ("./") 13 | else if (log !== "./") { 14 | // Move into a subdirectory, increase depth 15 | depth++; 16 | } 17 | } 18 | 19 | // Return the final depth, which represents the minimum number of operations needed 20 | return depth; 21 | }; 22 | -------------------------------------------------------------------------------- /Algorithms/src/1598. Crawler Log Folder/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minOperations(self, logs: List[str]) -> int: 3 | # Initialize depth to track the current folder level 4 | depth = 0 5 | 6 | # Iterate through each log entry 7 | for log in logs: 8 | # If the log is "../", move up one directory if not already at the root 9 | if log == "../": 10 | if depth > 0: 11 | depth -= 1 12 | # If the log is "./", do nothing (stay in the same directory) 13 | elif log != "./": 14 | # Any other log means moving into a subdirectory 15 | depth += 1 16 | 17 | # Return the final depth, which represents the minimum number of operations to go back to the main folder 18 | return depth 19 | -------------------------------------------------------------------------------- /Algorithms/src/1671. Minimum Number of Removals to Make Mountain Array/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumMountainRemovals(self, nums: List[int]) -> int: 3 | n = len(nums) 4 | LIS = [1] * n 5 | LDS = [1] * n 6 | 7 | # Compute LIS for each index 8 | for i in range(n): 9 | for j in range(i): 10 | if nums[i] > nums[j]: 11 | LIS[i] = max(LIS[i], LIS[j] + 1) 12 | 13 | # Compute LDS from each index 14 | for i in range(n - 1, -1, -1): 15 | for j in range(n - 1, i, -1): 16 | if nums[i] > nums[j]: 17 | LDS[i] = max(LDS[i], LDS[j] + 1) 18 | 19 | maxMountainLength = 0 20 | 21 | # Find the maximum mountain length 22 | for i in range(1, n - 1): 23 | if LIS[i] > 1 and LDS[i] > 1: # Valid peak 24 | maxMountainLength = max(maxMountainLength, LIS[i] + LDS[i] - 1) 25 | 26 | return n - maxMountainLength -------------------------------------------------------------------------------- /Algorithms/src/1701. Average Waiting Time/Code/solution.js: -------------------------------------------------------------------------------- 1 | var averageWaitingTime = function (customers) { 2 | // Initialize total waiting time to 0 3 | let totalWaitingTime = 0; 4 | // Initialize current time to 0 5 | let currentTime = 0; 6 | 7 | // Iterate through each customer in the customers array 8 | for (const customer of customers) { 9 | // Extract the arrival time and cooking time for the current customer 10 | let arrivalTime = customer[0]; 11 | let cookingTime = customer[1]; 12 | 13 | // Update the current time to be the maximum of the current time and the arrival time, 14 | // then add the cooking time of the current customer 15 | currentTime = Math.max(currentTime, arrivalTime) + cookingTime; 16 | 17 | // Calculate the waiting time for the current customer and add it to the total waiting time 18 | totalWaitingTime += currentTime - arrivalTime; 19 | } 20 | 21 | // Calculate and return the average waiting time by dividing the total waiting time 22 | // by the number of customers 23 | return totalWaitingTime / customers.length; 24 | }; 25 | -------------------------------------------------------------------------------- /Algorithms/src/1765. Map of Highest Peak/Code/solution.js: -------------------------------------------------------------------------------- 1 | var highestPeak = function (isWater) { 2 | const m = isWater.length, 3 | n = isWater[0].length; 4 | const height = Array.from({ length: m }, () => Array(n).fill(-1)); 5 | const queue = []; 6 | 7 | // Initialize water cells 8 | for (let i = 0; i < m; i++) { 9 | for (let j = 0; j < n; j++) { 10 | if (isWater[i][j] === 1) { 11 | height[i][j] = 0; 12 | queue.push([i, j]); 13 | } 14 | } 15 | } 16 | 17 | // Directions for BFS 18 | const directions = [ 19 | [0, 1], 20 | [0, -1], 21 | [1, 0], 22 | [-1, 0], 23 | ]; 24 | 25 | // BFS 26 | while (queue.length > 0) { 27 | const [x, y] = queue.shift(); 28 | for (const [dx, dy] of directions) { 29 | const nx = x + dx, 30 | ny = y + dy; 31 | if (nx >= 0 && ny >= 0 && nx < m && ny < n && height[nx][ny] === -1) { 32 | height[nx][ny] = height[x][y] + 1; 33 | queue.push([nx, ny]); 34 | } 35 | } 36 | } 37 | 38 | return height; 39 | }; 40 | -------------------------------------------------------------------------------- /Algorithms/src/1765. Map of Highest Peak/Code/solution.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | class Solution: 4 | def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]: 5 | m, n = len(isWater), len(isWater[0]) 6 | height = [[-1] * n for _ in range(m)] 7 | queue = deque() 8 | 9 | # Initialize water cells 10 | for i in range(m): 11 | for j in range(n): 12 | if isWater[i][j] == 1: 13 | height[i][j] = 0 14 | queue.append((i, j)) 15 | 16 | # Directions for BFS 17 | directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] 18 | 19 | # BFS 20 | while queue: 21 | x, y = queue.popleft() 22 | for dx, dy in directions: 23 | nx, ny = x + dx, y + dy 24 | if 0 <= nx < m and 0 <= ny < n and height[nx][ny] == -1: 25 | height[nx][ny] = height[x][y] + 1 26 | queue.append((nx, ny)) 27 | 28 | return height 29 | -------------------------------------------------------------------------------- /Algorithms/src/1769. Minimum Number of Operations to Move All Balls to Each Box/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector minOperations(string boxes) 5 | { 6 | int n = boxes.size(); 7 | vector answer(n, 0); 8 | 9 | // Left-to-right pass 10 | int balls = 0, operations = 0; 11 | for (int i = 0; i < n; ++i) 12 | { 13 | answer[i] += operations; 14 | balls += (boxes[i] == '1'); // Count balls 15 | operations += balls; // Add the current number of balls to operations 16 | } 17 | 18 | // Right-to-left pass 19 | balls = 0, operations = 0; 20 | for (int i = n - 1; i >= 0; --i) 21 | { 22 | answer[i] += operations; 23 | balls += (boxes[i] == '1'); // Count balls 24 | operations += balls; // Add the current number of balls to operations 25 | } 26 | 27 | return answer; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Algorithms/src/1769. Minimum Number of Operations to Move All Balls to Each Box/Code/solution.go: -------------------------------------------------------------------------------- 1 | func minOperations(boxes string) []int { 2 | n := len(boxes) 3 | answer := make([]int, n) 4 | 5 | // Left-to-right pass 6 | balls, operations := 0, 0 7 | for i := 0; i < n; i++ { 8 | answer[i] += operations 9 | if boxes[i] == '1' { 10 | balls++ // Count balls 11 | } 12 | operations += balls // Add the current number of balls to operations 13 | } 14 | 15 | // Right-to-left pass 16 | balls, operations = 0, 0 17 | for i := n - 1; i >= 0; i-- { 18 | answer[i] += operations 19 | if boxes[i] == '1' { 20 | balls++ // Count balls 21 | } 22 | operations += balls // Add the current number of balls to operations 23 | } 24 | 25 | return answer 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms/src/1769. Minimum Number of Operations to Move All Balls to Each Box/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] minOperations(String boxes) { 3 | int n = boxes.length(); 4 | int[] answer = new int[n]; 5 | 6 | // Left-to-right pass 7 | int balls = 0, operations = 0; 8 | for (int i = 0; i < n; i++) { 9 | answer[i] += operations; 10 | balls += (boxes.charAt(i) == '1' ? 1 : 0); // Count balls 11 | operations += balls; // Add the current number of balls to operations 12 | } 13 | 14 | // Right-to-left pass 15 | balls = 0; 16 | operations = 0; 17 | for (int i = n - 1; i >= 0; i--) { 18 | answer[i] += operations; 19 | balls += (boxes.charAt(i) == '1' ? 1 : 0); // Count balls 20 | operations += balls; // Add the current number of balls to operations 21 | } 22 | 23 | return answer; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Algorithms/src/1769. Minimum Number of Operations to Move All Balls to Each Box/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} boxes 3 | * @return {number[]} 4 | */ 5 | var minOperations = function (boxes) { 6 | const n = boxes.length; 7 | const answer = new Array(n).fill(0); 8 | 9 | // Left-to-right pass 10 | let balls = 0, 11 | operations = 0; 12 | for (let i = 0; i < n; i++) { 13 | answer[i] += operations; 14 | balls += boxes[i] === "1" ? 1 : 0; // Count balls 15 | operations += balls; // Add the current number of balls to operations 16 | } 17 | 18 | // Right-to-left pass 19 | balls = 0; 20 | operations = 0; 21 | for (let i = n - 1; i >= 0; i--) { 22 | answer[i] += operations; 23 | balls += boxes[i] === "1" ? 1 : 0; // Count balls 24 | operations += balls; // Add the current number of balls to operations 25 | } 26 | 27 | return answer; 28 | }; 29 | -------------------------------------------------------------------------------- /Algorithms/src/1769. Minimum Number of Operations to Move All Balls to Each Box/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minOperations(self, boxes: str) -> List[int]: 3 | n = len(boxes) 4 | answer = [0] * n 5 | 6 | # Left-to-right pass 7 | balls = 0 8 | operations = 0 9 | for i in range(n): 10 | answer[i] += operations 11 | balls += int(boxes[i]) # Count balls 12 | operations += balls # Add the current number of balls to operations 13 | 14 | # Right-to-left pass 15 | balls = 0 16 | operations = 0 17 | for i in range(n - 1, -1, -1): 18 | answer[i] += operations 19 | balls += int(boxes[i]) # Count balls 20 | operations += balls # Add the current number of balls to operations 21 | 22 | return answer 23 | -------------------------------------------------------------------------------- /Algorithms/src/1813. Sentence Similarity III/Code/solution.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "strings" 5 | ) 6 | 7 | func areSentencesSimilar(sentence1 string, sentence2 string) bool { 8 | // Split sentences into words 9 | words1 := strings.Split(sentence1, " ") 10 | words2 := strings.Split(sentence2, " ") 11 | 12 | // Ensure words1 is the longer sentence 13 | if len(words1) < len(words2) { 14 | words1, words2 = words2, words1 15 | } 16 | 17 | start, end := 0, 0 18 | n1, n2 := len(words1), len(words2) 19 | 20 | // Compare from the start 21 | for start < n2 && words1[start] == words2[start] { 22 | start++ 23 | } 24 | 25 | // Compare from the end 26 | for end < n2 && words1[n1-end-1] == words2[n2-end-1] { 27 | end++ 28 | } 29 | 30 | // Check if the remaining unmatched part is in the middle 31 | return start+end >= n2 32 | } -------------------------------------------------------------------------------- /Algorithms/src/1813. Sentence Similarity III/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} sentence1 3 | * @param {string} sentence2 4 | * @return {boolean} 5 | */ 6 | var areSentencesSimilar = function (sentence1, sentence2) { 7 | // Helper function to split a sentence into words 8 | const splitWords = (sentence) => sentence.split(" "); 9 | 10 | // Split both sentences into arrays of words 11 | let words1 = splitWords(sentence1); 12 | let words2 = splitWords(sentence2); 13 | 14 | // Ensure words1 is the longer sentence 15 | if (words1.length < words2.length) [words1, words2] = [words2, words1]; 16 | 17 | let start = 0, 18 | end = 0; 19 | let n1 = words1.length, 20 | n2 = words2.length; 21 | 22 | // Compare from the start 23 | while (start < n2 && words1[start] === words2[start]) start++; 24 | 25 | // Compare from the end 26 | while (end < n2 && words1[n1 - end - 1] === words2[n2 - end - 1]) end++; 27 | 28 | // Check if the remaining unmatched part is in the middle 29 | return start + end >= n2; 30 | }; 31 | -------------------------------------------------------------------------------- /Algorithms/src/1813. Sentence Similarity III/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool: 3 | # Split the sentences into words 4 | words1 = sentence1.split() 5 | words2 = sentence2.split() 6 | 7 | # Ensure words1 is the longer sentence 8 | if len(words1) < len(words2): 9 | words1, words2 = words2, words1 10 | 11 | start, end = 0, 0 12 | n1, n2 = len(words1), len(words2) 13 | 14 | # Compare from the start 15 | while start < n2 and words1[start] == words2[start]: 16 | start += 1 17 | 18 | # Compare from the end 19 | while end < n2 and words1[n1 - end - 1] == words2[n2 - end - 1]: 20 | end += 1 21 | 22 | # Check if the remaining unmatched part is in the middle 23 | return start + end >= n2 -------------------------------------------------------------------------------- /Algorithms/src/1823. Find the Winner of the Circular Game/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int findTheWinner(int n, int k) 5 | { 6 | // The problem is equivalent to the Josephus problem. 7 | // We need to convert the 0-indexed result from the Josephus function to 1-indexed. 8 | return josephus(n, k) + 1; 9 | } 10 | 11 | int josephus(int n, int k) 12 | { 13 | // Base case: when there is only one person, they are the winner. 14 | if (n == 1) 15 | { 16 | return 0; 17 | } 18 | // Recursive case: 19 | // josephus(n - 1, k) finds the position of the winner in the reduced problem (n-1 persons) 20 | // Adding k accounts for the step size in the problem. 21 | // Taking modulo n wraps around the position if it exceeds the number of people. 22 | return (josephus(n - 1, k) + k) % n; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Algorithms/src/1823. Find the Winner of the Circular Game/Code/solution.go: -------------------------------------------------------------------------------- 1 | // Function to find the winner of the game 2 | func findTheWinner(n int, k int) int { 3 | // The josephus function returns the position in 0-indexed format 4 | // Adding 1 to convert it to 1-indexed format for the final result 5 | return josephus(n, k) + 1 6 | } 7 | 8 | // Helper function to solve the Josephus problem 9 | func josephus(n int, k int) int { 10 | // Base case: when there is only one person, they are the winner 11 | if n == 1 { 12 | return 0 13 | } 14 | // Recursive case: 15 | // - Solve the problem for (n-1) people 16 | // - Adjust the position by adding k (the step count) 17 | // - Use modulo n to wrap around if the position exceeds the number of people 18 | return (josephus(n-1, k) + k) % n 19 | } 20 | -------------------------------------------------------------------------------- /Algorithms/src/1823. Find the Winner of the Circular Game/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findTheWinner(int n, int k) { 3 | // Calls the recursive Josephus function and adjusts the result from 0-indexed 4 | // to 1-indexed 5 | return josephus(n, k) + 1; 6 | } 7 | 8 | private int josephus(int n, int k) { 9 | // Base case: when there's only one person left, they are the winner 10 | if (n == 1) { 11 | return 0; 12 | } 13 | // Recursive case: calculate the position of the winner for the current state 14 | // josephus(n - 1, k) finds the winner position in the reduced group of (n-1) 15 | // people 16 | // (josephus(n - 1, k) + k) % n adjusts the position for the current group size 17 | // n 18 | return (josephus(n - 1, k) + k) % n; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Algorithms/src/1823. Find the Winner of the Circular Game/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findTheWinner(self, n: int, k: int) -> int: 3 | # Call the josephus function to find the winner in 0-indexed form, 4 | # then add 1 to convert it to 1-indexed as required by the problem. 5 | return self.josephus(n, k) + 1 6 | 7 | def josephus(self, n: int, k: int) -> int: 8 | # Base case: If there is only one person left, that person is the winner (0-indexed). 9 | if n == 1: 10 | return 0 11 | # Recursive case: Reduce the problem size by one (n-1), find the position of the winner 12 | # in the smaller problem, adjust by k steps, and take modulo n to wrap around the circle. 13 | return (self.josephus(n - 1, k) + k) % n 14 | -------------------------------------------------------------------------------- /Algorithms/src/1829. Maximum XOR for Each Query/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector getMaximumXor(vector &nums, int maximumBit) 5 | { 6 | int n = nums.size(); 7 | vector answer(n); 8 | int XORed = 0; 9 | 10 | // Calculate the cumulative XOR of the entire nums array 11 | for (int num : nums) 12 | { 13 | XORed ^= num; 14 | } 15 | 16 | // max_k is 2^maximumBit - 1 17 | int max_k = (1 << maximumBit) - 1; 18 | 19 | // Process each query in reverse 20 | for (int i = 0; i < n; ++i) 21 | { 22 | // Calculate the k that maximizes XOR 23 | answer[i] = XORed ^ max_k; 24 | 25 | // Update XORed by removing the effect of the last element 26 | XORed ^= nums[n - 1 - i]; 27 | } 28 | 29 | return answer; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Algorithms/src/1829. Maximum XOR for Each Query/Code/solution.go: -------------------------------------------------------------------------------- 1 | func getMaximumXor(nums []int, maximumBit int) []int { 2 | n := len(nums) 3 | answer := make([]int, n) 4 | XORed := 0 5 | 6 | // Calculate the cumulative XOR of the entire nums array 7 | for _, num := range nums { 8 | XORed ^= num 9 | } 10 | 11 | // max_k is 2^maximumBit - 1 12 | max_k := (1 << maximumBit) - 1 13 | 14 | // Process each query in reverse 15 | for i := 0; i < n; i++ { 16 | // Calculate the k that maximizes XOR 17 | answer[i] = XORed ^ max_k 18 | 19 | // Update XORed by removing the effect of the last element 20 | XORed ^= nums[n - 1 - i] 21 | } 22 | 23 | return answer 24 | } 25 | -------------------------------------------------------------------------------- /Algorithms/src/1829. Maximum XOR for Each Query/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] getMaximumXor(int[] nums, int maximumBit) { 3 | int n = nums.length; 4 | int[] answer = new int[n]; 5 | int XORed = 0; 6 | 7 | // Calculate the cumulative XOR of the entire nums array 8 | for (int num : nums) { 9 | XORed ^= num; 10 | } 11 | 12 | // max_k is 2^maximumBit - 1 13 | int max_k = (1 << maximumBit) - 1; 14 | 15 | // Process each query in reverse 16 | for (int i = 0; i < n; i++) { 17 | // Calculate the k that maximizes XOR 18 | answer[i] = XORed ^ max_k; 19 | 20 | // Update XORed by removing the effect of the last element 21 | XORed ^= nums[n - 1 - i]; 22 | } 23 | 24 | return answer; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms/src/1829. Maximum XOR for Each Query/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} maximumBit 4 | * @return {number[]} 5 | */ 6 | var getMaximumXor = function (nums, maximumBit) { 7 | let n = nums.length; 8 | let answer = new Array(n); 9 | let XORed = 0; 10 | 11 | // Calculate the cumulative XOR of the entire nums array 12 | for (let num of nums) { 13 | XORed ^= num; 14 | } 15 | 16 | // max_k is 2^maximumBit - 1 17 | let max_k = (1 << maximumBit) - 1; 18 | 19 | // Process each query in reverse 20 | for (let i = 0; i < n; i++) { 21 | // Calculate the k that maximizes XOR 22 | answer[i] = XORed ^ max_k; 23 | 24 | // Update XORed by removing the effect of the last element 25 | XORed ^= nums[n - 1 - i]; 26 | } 27 | 28 | return answer; 29 | }; 30 | -------------------------------------------------------------------------------- /Algorithms/src/1829. Maximum XOR for Each Query/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]: 3 | n = len(nums) 4 | answer = [0] * n 5 | XORed = 0 6 | 7 | # Calculate the cumulative XOR of the entire nums array 8 | for num in nums: 9 | XORed ^= num 10 | 11 | # max_k is 2^maximumBit - 1 12 | max_k = (1 << maximumBit) - 1 13 | 14 | # Process each query in reverse 15 | for i in range(n): 16 | # Calculate the k that maximizes XOR 17 | answer[i] = XORed ^ max_k 18 | 19 | # Update XORed by removing the effect of the last element 20 | XORed ^= nums[n - 1 - i] 21 | 22 | return answer 23 | -------------------------------------------------------------------------------- /Algorithms/src/1930. Unique Length-3 Palindromic Subsequences/Code/solution.go: -------------------------------------------------------------------------------- 1 | func countPalindromicSubsequence(s string) int { 2 | first := make([]int, 26) 3 | last := make([]int, 26) 4 | for i := range first { 5 | first[i] = -1 6 | } 7 | 8 | for i, char := range s { 9 | index := int(char - 'a') 10 | if first[index] == -1 { 11 | first[index] = i 12 | } 13 | last[index] = i 14 | } 15 | 16 | result := 0 17 | for i := 0; i < 26; i++ { 18 | if first[i] != -1 && last[i] > first[i] { 19 | middleChars := make(map[byte]bool) 20 | for j := first[i] + 1; j < last[i]; j++ { 21 | middleChars[s[j]] = true 22 | } 23 | result += len(middleChars) 24 | } 25 | } 26 | 27 | return result 28 | } 29 | -------------------------------------------------------------------------------- /Algorithms/src/1930. Unique Length-3 Palindromic Subsequences/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countPalindromicSubsequence(String s) { 3 | int[] first = new int[26]; 4 | int[] last = new int[26]; 5 | Arrays.fill(first, -1); 6 | 7 | int n = s.length(); 8 | for (int i = 0; i < n; i++) { 9 | int index = s.charAt(i) - 'a'; 10 | if (first[index] == -1) 11 | first[index] = i; 12 | last[index] = i; 13 | } 14 | 15 | int result = 0; 16 | for (int i = 0; i < 26; i++) { 17 | if (first[i] != -1 && last[i] > first[i]) { 18 | Set middleChars = new HashSet<>(); 19 | for (int j = first[i] + 1; j < last[i]; j++) { 20 | middleChars.add(s.charAt(j)); 21 | } 22 | result += middleChars.size(); 23 | } 24 | } 25 | 26 | return result; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Algorithms/src/1930. Unique Length-3 Palindromic Subsequences/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {number} 4 | */ 5 | var countPalindromicSubsequence = function (s) { 6 | let first = Array(26).fill(-1); 7 | let last = Array(26).fill(-1); 8 | 9 | for (let i = 0; i < s.length; i++) { 10 | let index = s.charCodeAt(i) - 97; 11 | if (first[index] === -1) first[index] = i; 12 | last[index] = i; 13 | } 14 | 15 | let result = 0; 16 | for (let i = 0; i < 26; i++) { 17 | if (first[i] !== -1 && last[i] > first[i]) { 18 | let middleChars = new Set(); 19 | for (let j = first[i] + 1; j < last[i]; j++) { 20 | middleChars.add(s[j]); 21 | } 22 | result += middleChars.size; 23 | } 24 | } 25 | 26 | return result; 27 | }; 28 | -------------------------------------------------------------------------------- /Algorithms/src/1930. Unique Length-3 Palindromic Subsequences/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countPalindromicSubsequence(self, s: str) -> int: 3 | first = [-1] * 26 4 | last = [-1] * 26 5 | 6 | for i, char in enumerate(s): 7 | index = ord(char) - ord('a') 8 | if first[index] == -1: 9 | first[index] = i 10 | last[index] = i 11 | 12 | result = 0 13 | for i in range(26): 14 | if first[i] != -1 and last[i] > first[i]: 15 | middle_chars = set(s[first[i] + 1:last[i]]) 16 | result += len(middle_chars) 17 | 18 | return result 19 | -------------------------------------------------------------------------------- /Algorithms/src/1957. Delete Characters to Make Fancy String/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | string makeFancyString(string s) 5 | { 6 | string result; 7 | for (char c : s) 8 | { 9 | int n = result.size(); 10 | if (n < 2 || !(result[n - 1] == c && result[n - 2] == c)) 11 | { 12 | result += c; 13 | } 14 | } 15 | return result; 16 | } 17 | }; -------------------------------------------------------------------------------- /Algorithms/src/1957. Delete Characters to Make Fancy String/Code/solution.go: -------------------------------------------------------------------------------- 1 | func makeFancyString(s string) string { 2 | result := []byte{} 3 | for i := 0; i < len(s); i++ { 4 | n := len(result) 5 | if n < 2 || !(result[n-1] == s[i] && result[n-2] == s[i]) { 6 | result = append(result, s[i]) 7 | } 8 | } 9 | return string(result) 10 | } -------------------------------------------------------------------------------- /Algorithms/src/1957. Delete Characters to Make Fancy String/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String makeFancyString(String s) { 3 | StringBuilder result = new StringBuilder(); 4 | for (char c : s.toCharArray()) { 5 | int n = result.length(); 6 | if (n < 2 || !(result.charAt(n - 1) == c && result.charAt(n - 2) == c)) { 7 | result.append(c); 8 | } 9 | } 10 | return result.toString(); 11 | } 12 | } -------------------------------------------------------------------------------- /Algorithms/src/1957. Delete Characters to Make Fancy String/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {string} 4 | */ 5 | var makeFancyString = function (s) { 6 | let result = ""; 7 | for (let i = 0; i < s.length; i++) { 8 | let n = result.length; 9 | if (n < 2 || !(result[n - 1] === s[i] && result[n - 2] === s[i])) { 10 | result += s[i]; 11 | } 12 | } 13 | return result; 14 | }; 15 | -------------------------------------------------------------------------------- /Algorithms/src/1957. Delete Characters to Make Fancy String/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def makeFancyString(self, s: str) -> str: 3 | result = [] 4 | for c in s: 5 | if len(result) < 2 or not (result[-1] == c and result[-2] == c): 6 | result.append(c) 7 | return ''.join(result) -------------------------------------------------------------------------------- /Algorithms/src/2017. Grid Game/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long gridGame(int[][] grid) { 3 | int n = grid[0].length; 4 | long[] topSuffix = new long[n]; 5 | long[] bottomPrefix = new long[n]; 6 | 7 | // Calculate suffix sum for the top row 8 | topSuffix[n - 1] = grid[0][n - 1]; 9 | for (int i = n - 2; i >= 0; --i) { 10 | topSuffix[i] = topSuffix[i + 1] + grid[0][i]; 11 | } 12 | 13 | // Calculate prefix sum for the bottom row 14 | bottomPrefix[0] = grid[1][0]; 15 | for (int i = 1; i < n; ++i) { 16 | bottomPrefix[i] = bottomPrefix[i - 1] + grid[1][i]; 17 | } 18 | 19 | // Find the minimum maximum points Robot 2 can collect 20 | long result = Long.MAX_VALUE; 21 | for (int i = 0; i < n; ++i) { 22 | long top = (i + 1 < n) ? topSuffix[i + 1] : 0; 23 | long bottom = (i > 0) ? bottomPrefix[i - 1] : 0; 24 | result = Math.min(result, Math.max(top, bottom)); 25 | } 26 | 27 | return result; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Algorithms/src/2017. Grid Game/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} grid 3 | * @return {number} 4 | */ 5 | var gridGame = function (grid) { 6 | const n = grid[0].length; 7 | const topSuffix = Array(n).fill(0); 8 | const bottomPrefix = Array(n).fill(0); 9 | 10 | // Calculate suffix sum for the top row 11 | topSuffix[n - 1] = grid[0][n - 1]; 12 | for (let i = n - 2; i >= 0; --i) { 13 | topSuffix[i] = topSuffix[i + 1] + grid[0][i]; 14 | } 15 | 16 | // Calculate prefix sum for the bottom row 17 | bottomPrefix[0] = grid[1][0]; 18 | for (let i = 1; i < n; ++i) { 19 | bottomPrefix[i] = bottomPrefix[i - 1] + grid[1][i]; 20 | } 21 | 22 | // Find the minimum maximum points Robot 2 can collect 23 | let result = Infinity; 24 | for (let i = 0; i < n; ++i) { 25 | const top = i + 1 < n ? topSuffix[i + 1] : 0; 26 | const bottom = i > 0 ? bottomPrefix[i - 1] : 0; 27 | result = Math.min(result, Math.max(top, bottom)); 28 | } 29 | 30 | return result; 31 | }; 32 | -------------------------------------------------------------------------------- /Algorithms/src/2017. Grid Game/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def gridGame(self, grid: List[List[int]]) -> int: 3 | n = len(grid[0]) 4 | 5 | # Calculate suffix sum for the top row 6 | top_suffix = [0] * n 7 | top_suffix[n - 1] = grid[0][n - 1] 8 | for i in range(n - 2, -1, -1): 9 | top_suffix[i] = top_suffix[i + 1] + grid[0][i] 10 | 11 | # Calculate prefix sum for the bottom row 12 | bottom_prefix = [0] * n 13 | bottom_prefix[0] = grid[1][0] 14 | for i in range(1, n): 15 | bottom_prefix[i] = bottom_prefix[i - 1] + grid[1][i] 16 | 17 | # Find the minimum maximum points Robot 2 can collect 18 | result = float('inf') 19 | for i in range(n): 20 | top = top_suffix[i + 1] if i + 1 < n else 0 21 | bottom = bottom_prefix[i - 1] if i > 0 else 0 22 | result = min(result, max(top, bottom)) 23 | 24 | return result 25 | -------------------------------------------------------------------------------- /Algorithms/src/2044. Count Number of Maximum Bitwise-OR Subsets/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void backtrack(const vector &nums, int index, int currentOR, int maxOR, int &count) 5 | { 6 | if (currentOR == maxOR) 7 | { 8 | count++; 9 | } 10 | 11 | for (int i = index; i < nums.size(); ++i) 12 | { 13 | backtrack(nums, i + 1, currentOR | nums[i], maxOR, count); 14 | } 15 | } 16 | 17 | int countMaxOrSubsets(vector &nums) 18 | { 19 | int maxOR = 0; 20 | 21 | // Step 1: Compute the maximum OR 22 | for (int num : nums) 23 | { 24 | maxOR |= num; 25 | } 26 | 27 | int count = 0; 28 | // Step 2: Backtrack to count the subsets 29 | backtrack(nums, 0, 0, maxOR, count); 30 | 31 | return count; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Algorithms/src/2044. Count Number of Maximum Bitwise-OR Subsets/Code/solution.go: -------------------------------------------------------------------------------- 1 | func backtrack(nums []int, index int, currentOR int, maxOR int, count *int) { 2 | if currentOR == maxOR { 3 | *count++ 4 | } 5 | 6 | for i := index; i < len(nums); i++ { 7 | backtrack(nums, i+1, currentOR|nums[i], maxOR, count) 8 | } 9 | } 10 | 11 | func countMaxOrSubsets(nums []int) int { 12 | maxOR := 0 13 | 14 | // Step 1: Compute the maximum OR 15 | for _, num := range nums { 16 | maxOR |= num 17 | } 18 | 19 | count := 0 20 | // Step 2: Backtrack to count the subsets 21 | backtrack(nums, 0, 0, maxOR, &count) 22 | 23 | return count 24 | } 25 | -------------------------------------------------------------------------------- /Algorithms/src/2044. Count Number of Maximum Bitwise-OR Subsets/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void backtrack(int[] nums, int index, int currentOR, int maxOR, int[] count) { 3 | if (currentOR == maxOR) { 4 | count[0]++; 5 | } 6 | 7 | for (int i = index; i < nums.length; i++) { 8 | backtrack(nums, i + 1, currentOR | nums[i], maxOR, count); 9 | } 10 | } 11 | 12 | public int countMaxOrSubsets(int[] nums) { 13 | int maxOR = 0; 14 | 15 | // Step 1: Compute the maximum OR 16 | for (int num : nums) { 17 | maxOR |= num; 18 | } 19 | 20 | int[] count = new int[1]; 21 | // Step 2: Backtrack to count the subsets 22 | backtrack(nums, 0, 0, maxOR, count); 23 | 24 | return count[0]; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms/src/2044. Count Number of Maximum Bitwise-OR Subsets/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | var countMaxOrSubsets = function (nums) { 6 | let maxOR = 0; 7 | 8 | // Step 1: Compute the maximum OR 9 | for (let num of nums) { 10 | maxOR |= num; 11 | } 12 | 13 | let count = 0; 14 | 15 | const backtrack = (index, currentOR) => { 16 | if (currentOR === maxOR) { 17 | count++; 18 | } 19 | 20 | for (let i = index; i < nums.length; i++) { 21 | backtrack(i + 1, currentOR | nums[i]); 22 | } 23 | }; 24 | 25 | // Step 2: Backtrack to count the subsets 26 | backtrack(0, 0); 27 | 28 | return count; 29 | }; 30 | -------------------------------------------------------------------------------- /Algorithms/src/2044. Count Number of Maximum Bitwise-OR Subsets/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def backtrack(self, nums, index, currentOR, maxOR, count): 3 | if currentOR == maxOR: 4 | count[0] += 1 5 | 6 | for i in range(index, len(nums)): 7 | self.backtrack(nums, i + 1, currentOR | nums[i], maxOR, count) 8 | 9 | def countMaxOrSubsets(self, nums: List[int]) -> int: 10 | maxOR = 0 11 | 12 | # Step 1: Compute the maximum OR 13 | for num in nums: 14 | maxOR |= num 15 | 16 | count = [0] 17 | # Step 2: Backtrack to count the subsets 18 | self.backtrack(nums, 0, 0, maxOR, count) 19 | 20 | return count[0] 21 | -------------------------------------------------------------------------------- /Algorithms/src/2053. Kth Distinct String in an Array/Code/solution.go: -------------------------------------------------------------------------------- 1 | func kthDistinct(arr []string, k int) string { 2 | // Create a map to count the occurrences of each string 3 | count := make(map[string]int) 4 | 5 | // Create a slice to store distinct strings 6 | distinct := []string{} 7 | 8 | // Loop through each string in the array and count its occurrences 9 | for _, str := range arr { 10 | count[str]++ 11 | } 12 | 13 | // Loop through the array again to collect distinct strings in order 14 | for _, str := range arr { 15 | if count[str] == 1 { 16 | // If a string appears exactly once, add it to the distinct slice 17 | distinct = append(distinct, str) 18 | } 19 | } 20 | 21 | // Check if k is within the range of distinct strings 22 | if k <= len(distinct) { 23 | // Return the k-th distinct string (1-based index) 24 | return distinct[k-1] 25 | } else { 26 | // If k is out of range, return an empty string 27 | return "" 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Algorithms/src/2053. Kth Distinct String in an Array/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kthDistinct(self, arr: List[str], k: int) -> str: 3 | count = {} # Dictionary to store the frequency of each string 4 | distinct = [] # List to store distinct strings 5 | 6 | # Iterate through each string in the array to count occurrences 7 | for str in arr: 8 | count[str] = count.get(str, 0) + 1 # Increment the count for each string 9 | 10 | # Iterate through the array again to collect distinct strings 11 | for str in arr: 12 | if count[str] == 1: # Check if the string is distinct (appears only once) 13 | distinct.append(str) # Add distinct string to the list 14 | 15 | # Check if the k-th distinct string exists 16 | if k <= len(distinct): 17 | return distinct[k-1] # Return the k-th distinct string (1-based index) 18 | else: 19 | return "" # Return an empty string if k is out of range 20 | -------------------------------------------------------------------------------- /Algorithms/src/2064. Minimized Maximum of Products Distributed to Any Store/Code/solution.go: -------------------------------------------------------------------------------- 1 | import "math" 2 | 3 | func minimizedMaximum(n int, quantities []int) int { 4 | canDistribute := func(maxProducts int) bool { 5 | storesNeeded := 0 6 | for _, quantity := range quantities { 7 | storesNeeded += int(math.Ceil(float64(quantity) / float64(maxProducts))) 8 | if storesNeeded > n { 9 | return false 10 | } 11 | } 12 | return storesNeeded <= n 13 | } 14 | 15 | low, high := 1, 0 16 | for _, quantity := range quantities { 17 | if quantity > high { 18 | high = quantity 19 | } 20 | } 21 | answer := high 22 | 23 | for low <= high { 24 | mid := low + (high - low) / 2 25 | if canDistribute(mid) { 26 | answer = mid 27 | high = mid - 1 28 | } else { 29 | low = mid + 1 30 | } 31 | } 32 | 33 | return answer 34 | } -------------------------------------------------------------------------------- /Algorithms/src/2064. Minimized Maximum of Products Distributed to Any Store/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private boolean canDistribute(int[] quantities, int maxProducts, int n) { 3 | int storesNeeded = 0; 4 | for (int quantity : quantities) { 5 | storesNeeded += (int) Math.ceil((double) quantity / maxProducts); 6 | if (storesNeeded > n) 7 | return false; 8 | } 9 | return storesNeeded <= n; 10 | } 11 | 12 | public int minimizedMaximum(int n, int[] quantities) { 13 | int low = 1; 14 | int high = Arrays.stream(quantities).max().getAsInt(); 15 | int answer = high; 16 | 17 | while (low <= high) { 18 | int mid = low + (high - low) / 2; 19 | if (canDistribute(quantities, mid, n)) { 20 | answer = mid; 21 | high = mid - 1; 22 | } else { 23 | low = mid + 1; 24 | } 25 | } 26 | 27 | return answer; 28 | } 29 | } -------------------------------------------------------------------------------- /Algorithms/src/2064. Minimized Maximum of Products Distributed to Any Store/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} n 3 | * @param {number[]} quantities 4 | * @return {number} 5 | */ 6 | var minimizedMaximum = function (n, quantities) { 7 | const canDistribute = (maxProducts) => { 8 | let storesNeeded = 0; 9 | for (const quantity of quantities) { 10 | storesNeeded += Math.ceil(quantity / maxProducts); 11 | if (storesNeeded > n) return false; 12 | } 13 | return storesNeeded <= n; 14 | }; 15 | 16 | let low = 1; 17 | let high = Math.max(...quantities); 18 | let answer = high; 19 | 20 | while (low <= high) { 21 | const mid = Math.floor((low + high) / 2); 22 | if (canDistribute(mid)) { 23 | answer = mid; 24 | high = mid - 1; 25 | } else { 26 | low = mid + 1; 27 | } 28 | } 29 | 30 | return answer; 31 | }; 32 | -------------------------------------------------------------------------------- /Algorithms/src/2064. Minimized Maximum of Products Distributed to Any Store/Code/solution.py: -------------------------------------------------------------------------------- 1 | import math 2 | from typing import List 3 | 4 | class Solution: 5 | def minimizedMaximum(self, n: int, quantities: List[int]) -> int: 6 | def canDistribute(maxProducts): 7 | storesNeeded = 0 8 | for quantity in quantities: 9 | storesNeeded += math.ceil(quantity / maxProducts) 10 | if storesNeeded > n: 11 | return False 12 | return storesNeeded <= n 13 | 14 | low, high = 1, max(quantities) 15 | answer = high 16 | 17 | while low <= high: 18 | mid = (low + high) // 2 19 | if canDistribute(mid): 20 | answer = mid 21 | high = mid - 1 22 | else: 23 | low = mid + 1 24 | 25 | return answer -------------------------------------------------------------------------------- /Algorithms/src/2070. Most Beautiful Item for Each Query/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution 6 | { 7 | public: 8 | vector maximumBeauty(vector> &items, vector &queries) 9 | { 10 | // Sort items by price 11 | sort(items.begin(), items.end()); 12 | 13 | // Prepare price-beauty pairs with running max beauty 14 | vector> priceBeauty; 15 | int maxBeauty = 0; 16 | for (auto &item : items) 17 | { 18 | maxBeauty = max(maxBeauty, item[1]); 19 | priceBeauty.push_back({item[0], maxBeauty}); 20 | } 21 | 22 | // Process each query 23 | vector result; 24 | for (int query : queries) 25 | { 26 | auto it = upper_bound(priceBeauty.begin(), priceBeauty.end(), make_pair(query, INT_MAX)) - 1; 27 | result.push_back(it >= priceBeauty.begin() ? it->second : 0); 28 | } 29 | return result; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Algorithms/src/2070. Most Beautiful Item for Each Query/Code/solution.go: -------------------------------------------------------------------------------- 1 | import ( 2 | "sort" 3 | ) 4 | 5 | func maximumBeauty(items [][]int, queries []int) []int { 6 | sort.Slice(items, func(i, j int) bool { 7 | return items[i][0] < items[j][0] 8 | }) 9 | 10 | priceBeauty := make([][2]int, 0) 11 | maxBeauty := 0 12 | for _, item := range items { 13 | price, beauty := item[0], item[1] 14 | maxBeauty = max(maxBeauty, beauty) 15 | priceBeauty = append(priceBeauty, [2]int{price, maxBeauty}) 16 | } 17 | 18 | result := make([]int, len(queries)) 19 | for i, query := range queries { 20 | idx := sort.Search(len(priceBeauty), func(j int) bool { 21 | return priceBeauty[j][0] > query 22 | }) - 1 23 | if idx >= 0 { 24 | result[i] = priceBeauty[idx][1] 25 | } else { 26 | result[i] = 0 27 | } 28 | } 29 | return result 30 | } 31 | 32 | func max(a, b int) int { 33 | if a > b { 34 | return a 35 | } 36 | return b 37 | } -------------------------------------------------------------------------------- /Algorithms/src/2070. Most Beautiful Item for Each Query/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} items 3 | * @param {number[]} queries 4 | * @return {number[]} 5 | */ 6 | var maximumBeauty = function (items, queries) { 7 | items.sort((a, b) => a[0] - b[0]); 8 | let priceBeauty = []; 9 | let maxBeauty = 0; 10 | 11 | for (let [price, beauty] of items) { 12 | maxBeauty = Math.max(maxBeauty, beauty); 13 | priceBeauty.push([price, maxBeauty]); 14 | } 15 | 16 | return queries.map((query) => { 17 | let left = 0, 18 | right = priceBeauty.length - 1; 19 | while (left <= right) { 20 | let mid = left + Math.floor((right - left) / 2); 21 | if (priceBeauty[mid][0] <= query) left = mid + 1; 22 | else right = mid - 1; 23 | } 24 | return right >= 0 ? priceBeauty[right][1] : 0; 25 | }); 26 | }; 27 | -------------------------------------------------------------------------------- /Algorithms/src/2070. Most Beautiful Item for Each Query/Code/solution.py: -------------------------------------------------------------------------------- 1 | from bisect import bisect_right 2 | from typing import List 3 | 4 | class Solution: 5 | def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]: 6 | items.sort() 7 | price_beauty = [] 8 | max_beauty = 0 9 | 10 | for price, beauty in items: 11 | max_beauty = max(max_beauty, beauty) 12 | price_beauty.append((price, max_beauty)) 13 | 14 | result = [] 15 | for query in queries: 16 | idx = bisect_right(price_beauty, (query, float('inf'))) - 1 17 | result.append(price_beauty[idx][1] if idx >= 0 else 0) 18 | 19 | return result -------------------------------------------------------------------------------- /Algorithms/src/2116. Check if a Parentheses String Can Be Valid/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @param {string} locked 4 | * @return {boolean} 5 | */ 6 | var canBeValid = function (s, locked) { 7 | if (s.length % 2 !== 0) return false; // Odd length can't be balanced 8 | 9 | let open = 0, 10 | flexible = 0; 11 | // Left-to-right pass 12 | for (let i = 0; i < s.length; i++) { 13 | if (locked[i] === "1") { 14 | open += s[i] === "(" ? 1 : -1; 15 | } else { 16 | flexible++; 17 | } 18 | if (open + flexible < 0) return false; 19 | } 20 | 21 | open = 0; 22 | flexible = 0; 23 | // Right-to-left pass 24 | for (let i = s.length - 1; i >= 0; i--) { 25 | if (locked[i] === "1") { 26 | open += s[i] === ")" ? 1 : -1; 27 | } else { 28 | flexible++; 29 | } 30 | if (open + flexible < 0) return false; 31 | } 32 | 33 | return true; 34 | }; 35 | -------------------------------------------------------------------------------- /Algorithms/src/2116. Check if a Parentheses String Can Be Valid/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canBeValid(self, s: str, locked: str) -> bool: 3 | if len(s) % 2 != 0: 4 | return False # Odd length can't be balanced 5 | 6 | open, flexible = 0, 0 7 | # Left-to-right pass 8 | for i in range(len(s)): 9 | if locked[i] == '1': 10 | open += 1 if s[i] == '(' else -1 11 | else: 12 | flexible += 1 13 | if open + flexible < 0: 14 | return False 15 | 16 | open, flexible = 0, 0 17 | # Right-to-left pass 18 | for i in range(len(s) - 1, -1, -1): 19 | if locked[i] == '1': 20 | open += 1 if s[i] == ')' else -1 21 | else: 22 | flexible += 1 23 | if open + flexible < 0: 24 | return False 25 | 26 | return True 27 | -------------------------------------------------------------------------------- /Algorithms/src/2185. Counting Words With a Given Prefix/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int prefixCount(vector &words, string pref) 5 | { 6 | int count = 0; 7 | for (const string &word : words) 8 | { 9 | // Check if the prefix matches the start of the word 10 | if (word.substr(0, pref.size()) == pref) 11 | { 12 | count++; 13 | } 14 | } 15 | return count; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Algorithms/src/2185. Counting Words With a Given Prefix/Code/solution.go: -------------------------------------------------------------------------------- 1 | func prefixCount(words []string, pref string) int { 2 | count := 0 3 | for _, word := range words { 4 | // Check if the prefix matches the start of the word 5 | if len(word) >= len(pref) && word[:len(pref)] == pref { 6 | count++ 7 | } 8 | } 9 | return count 10 | } 11 | -------------------------------------------------------------------------------- /Algorithms/src/2185. Counting Words With a Given Prefix/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int prefixCount(String[] words, String pref) { 3 | int count = 0; 4 | for (String word : words) { 5 | // Check if the word starts with the prefix 6 | if (word.startsWith(pref)) { 7 | count++; 8 | } 9 | } 10 | return count; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Algorithms/src/2185. Counting Words With a Given Prefix/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string[]} words 3 | * @param {string} pref 4 | * @return {number} 5 | */ 6 | var prefixCount = function (words, pref) { 7 | let count = 0; 8 | for (let word of words) { 9 | // Check if the word starts with the prefix 10 | if (word.startsWith(pref)) { 11 | count++; 12 | } 13 | } 14 | return count; 15 | }; 16 | -------------------------------------------------------------------------------- /Algorithms/src/2185. Counting Words With a Given Prefix/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def prefixCount(self, words: List[str], pref: str) -> int: 3 | count = 0 4 | for word in words: 5 | # Check if the word starts with the prefix 6 | if word.startswith(pref): 7 | count += 1 8 | return count 9 | -------------------------------------------------------------------------------- /Algorithms/src/2270. Number of Ways to Split Array/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int waysToSplitArray(vector &nums) 5 | { 6 | long long total_sum = 0; // Total sum of the array 7 | for (int num : nums) 8 | { 9 | total_sum += num; 10 | } 11 | 12 | long long prefix_sum = 0; // Prefix sum 13 | int count = 0; // Count of valid splits 14 | 15 | for (int i = 0; i < nums.size() - 1; i++) 16 | { 17 | prefix_sum += nums[i]; 18 | long long right_sum = total_sum - prefix_sum; 19 | if (prefix_sum >= right_sum) 20 | { 21 | count++; 22 | } 23 | } 24 | 25 | return count; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Algorithms/src/2270. Number of Ways to Split Array/Code/solution.go: -------------------------------------------------------------------------------- 1 | func waysToSplitArray(nums []int) int { 2 | totalSum := 0 3 | for _, num := range nums { 4 | totalSum += num 5 | } 6 | 7 | prefixSum := 0 8 | count := 0 9 | 10 | for i := 0; i < len(nums)-1; i++ { 11 | prefixSum += nums[i] 12 | rightSum := totalSum - prefixSum 13 | if prefixSum >= rightSum { 14 | count++ 15 | } 16 | } 17 | 18 | return count 19 | } 20 | -------------------------------------------------------------------------------- /Algorithms/src/2270. Number of Ways to Split Array/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int waysToSplitArray(int[] nums) { 3 | long totalSum = 0; 4 | for (int num : nums) { 5 | totalSum += num; 6 | } 7 | 8 | long prefixSum = 0; 9 | int count = 0; 10 | 11 | for (int i = 0; i < nums.length - 1; i++) { 12 | prefixSum += nums[i]; 13 | long rightSum = totalSum - prefixSum; 14 | if (prefixSum >= rightSum) { 15 | count++; 16 | } 17 | } 18 | 19 | return count; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Algorithms/src/2270. Number of Ways to Split Array/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | var waysToSplitArray = function (nums) { 6 | let totalSum = nums.reduce((a, b) => a + b, 0); // Total sum of the array 7 | let prefixSum = 0; // Prefix sum 8 | let count = 0; // Count of valid splits 9 | 10 | for (let i = 0; i < nums.length - 1; i++) { 11 | prefixSum += nums[i]; 12 | let rightSum = totalSum - prefixSum; 13 | if (prefixSum >= rightSum) { 14 | count++; 15 | } 16 | } 17 | 18 | return count; 19 | }; 20 | -------------------------------------------------------------------------------- /Algorithms/src/2270. Number of Ways to Split Array/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def waysToSplitArray(self, nums: List[int]) -> int: 3 | total_sum = sum(nums) # Total sum of the array 4 | prefix_sum = 0 # Prefix sum 5 | count = 0 # Count of valid splits 6 | 7 | for i in range(len(nums) - 1): 8 | prefix_sum += nums[i] 9 | right_sum = total_sum - prefix_sum 10 | if prefix_sum >= right_sum: 11 | count += 1 12 | 13 | return count 14 | -------------------------------------------------------------------------------- /Algorithms/src/2275. Largest Combination With Bitwise AND Greater Than Zero/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int largestCombination(vector &candidates) 5 | { 6 | int bitCount[31] = {0}; // Array to count '1's at each bit position 7 | 8 | // Count '1's in each bit position across all numbers 9 | for (int num : candidates) 10 | { 11 | for (int i = 0; i < 31; ++i) 12 | { 13 | if (num & (1 << i)) 14 | { 15 | bitCount[i]++; 16 | } 17 | } 18 | } 19 | 20 | // Find the maximum count in any bit position 21 | int maxCombinationSize = 0; 22 | for (int i = 0; i < 31; ++i) 23 | { 24 | maxCombinationSize = max(maxCombinationSize, bitCount[i]); 25 | } 26 | 27 | return maxCombinationSize; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Algorithms/src/2275. Largest Combination With Bitwise AND Greater Than Zero/Code/solution.go: -------------------------------------------------------------------------------- 1 | func largestCombination(candidates []int) int { 2 | var bitCount [31]int // Array to count '1's at each bit position 3 | 4 | // Count '1's in each bit position across all numbers 5 | for _, num := range candidates { 6 | for i := 0; i < 31; i++ { 7 | if num & (1 << i) != 0 { 8 | bitCount[i]++ 9 | } 10 | } 11 | } 12 | 13 | // Find the maximum count in any bit position 14 | maxCombinationSize := 0 15 | for _, count := range bitCount { 16 | if count > maxCombinationSize { 17 | maxCombinationSize = count 18 | } 19 | } 20 | 21 | return maxCombinationSize 22 | } 23 | -------------------------------------------------------------------------------- /Algorithms/src/2275. Largest Combination With Bitwise AND Greater Than Zero/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int largestCombination(int[] candidates) { 3 | int[] bitCount = new int[31]; // Array to count '1's at each bit position 4 | 5 | // Count '1's in each bit position across all numbers 6 | for (int num : candidates) { 7 | for (int i = 0; i < 31; ++i) { 8 | if ((num & (1 << i)) != 0) { 9 | bitCount[i]++; 10 | } 11 | } 12 | } 13 | 14 | // Find the maximum count in any bit position 15 | int maxCombinationSize = 0; 16 | for (int i = 0; i < 31; ++i) { 17 | maxCombinationSize = Math.max(maxCombinationSize, bitCount[i]); 18 | } 19 | 20 | return maxCombinationSize; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Algorithms/src/2275. Largest Combination With Bitwise AND Greater Than Zero/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} candidates 3 | * @return {number} 4 | */ 5 | var largestCombination = function (candidates) { 6 | let bitCount = Array(31).fill(0); // Array to count '1's at each bit position 7 | 8 | // Count '1's in each bit position across all numbers 9 | for (let num of candidates) { 10 | for (let i = 0; i < 31; ++i) { 11 | if ((num & (1 << i)) !== 0) { 12 | bitCount[i]++; 13 | } 14 | } 15 | } 16 | 17 | // Find the maximum count in any bit position 18 | return Math.max(...bitCount); 19 | }; 20 | -------------------------------------------------------------------------------- /Algorithms/src/2275. Largest Combination With Bitwise AND Greater Than Zero/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestCombination(self, candidates: List[int]) -> int: 3 | bit_count = [0] * 31 # Array to count '1's at each bit position 4 | 5 | # Count '1's in each bit position across all numbers 6 | for num in candidates: 7 | for i in range(31): 8 | if num & (1 << i): 9 | bit_count[i] += 1 10 | 11 | # Find the maximum count in any bit position 12 | return max(bit_count) 13 | -------------------------------------------------------------------------------- /Algorithms/src/2381. Shifting Letters II/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | string shiftingLetters(string s, vector> &shifts) 5 | { 6 | int n = s.length(); 7 | vector diff(n + 1, 0); 8 | 9 | // Build the difference array 10 | for (auto &shift : shifts) 11 | { 12 | int start = shift[0], end = shift[1], direction = shift[2]; 13 | int delta = (direction == 1) ? 1 : -1; 14 | diff[start] += delta; 15 | if (end + 1 < n) 16 | diff[end + 1] -= delta; 17 | } 18 | 19 | // Calculate cumulative shifts 20 | int shift = 0; 21 | for (int i = 0; i < n; ++i) 22 | { 23 | shift += diff[i]; 24 | shift = (shift % 26 + 26) % 26; // Normalize shift to [0, 25] 25 | s[i] = 'a' + (s[i] - 'a' + shift) % 26; 26 | } 27 | 28 | return s; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Algorithms/src/2381. Shifting Letters II/Code/solution.go: -------------------------------------------------------------------------------- 1 | func shiftingLetters(s string, shifts [][]int) string { 2 | n := len(s) 3 | diff := make([]int, n+1) 4 | 5 | // Build the difference array 6 | for _, shift := range shifts { 7 | start, end, direction := shift[0], shift[1], shift[2] 8 | delta := 1 9 | if direction == 0 { 10 | delta = -1 11 | } 12 | diff[start] += delta 13 | if end+1 < n { 14 | diff[end+1] -= delta 15 | } 16 | } 17 | 18 | // Calculate cumulative shifts 19 | shift := 0 20 | result := []byte(s) 21 | for i := 0; i < n; i++ { 22 | shift += diff[i] 23 | shift = (shift%26 + 26) % 26 // Normalize shift to [0, 25] 24 | result[i] = byte('a' + (result[i]-'a'+byte(shift))%26) 25 | } 26 | 27 | return string(result) 28 | } 29 | -------------------------------------------------------------------------------- /Algorithms/src/2381. Shifting Letters II/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String shiftingLetters(String s, int[][] shifts) { 3 | int n = s.length(); 4 | int[] diff = new int[n + 1]; 5 | 6 | // Build the difference array 7 | for (int[] shift : shifts) { 8 | int start = shift[0], end = shift[1], direction = shift[2]; 9 | int delta = (direction == 1) ? 1 : -1; 10 | diff[start] += delta; 11 | if (end + 1 < n) 12 | diff[end + 1] -= delta; 13 | } 14 | 15 | // Calculate cumulative shifts 16 | int shift = 0; 17 | char[] result = s.toCharArray(); 18 | for (int i = 0; i < n; i++) { 19 | shift += diff[i]; 20 | shift = (shift % 26 + 26) % 26; // Normalize shift to [0, 25] 21 | result[i] = (char) ('a' + (result[i] - 'a' + shift) % 26); 22 | } 23 | 24 | return new String(result); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms/src/2381. Shifting Letters II/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @param {number[][]} shifts 4 | * @return {string} 5 | */ 6 | var shiftingLetters = function (s, shifts) { 7 | const n = s.length; 8 | const diff = Array(n + 1).fill(0); 9 | 10 | // Build the difference array 11 | for (const [start, end, direction] of shifts) { 12 | const delta = direction === 1 ? 1 : -1; 13 | diff[start] += delta; 14 | if (end + 1 < n) diff[end + 1] -= delta; 15 | } 16 | 17 | // Calculate cumulative shifts 18 | let shift = 0; 19 | const result = s.split(""); 20 | for (let i = 0; i < n; i++) { 21 | shift += diff[i]; 22 | shift = ((shift % 26) + 26) % 26; // Normalize shift to [0, 25] 23 | result[i] = String.fromCharCode( 24 | "a".charCodeAt(0) + 25 | ((result[i].charCodeAt(0) - "a".charCodeAt(0) + shift) % 26) 26 | ); 27 | } 28 | 29 | return result.join(""); 30 | }; 31 | -------------------------------------------------------------------------------- /Algorithms/src/2381. Shifting Letters II/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str: 3 | n = len(s) 4 | diff = [0] * (n + 1) 5 | 6 | # Build the difference array 7 | for start, end, direction in shifts: 8 | delta = 1 if direction == 1 else -1 9 | diff[start] += delta 10 | if end + 1 < n: 11 | diff[end + 1] -= delta 12 | 13 | # Calculate cumulative shifts 14 | shift = 0 15 | result = list(s) 16 | for i in range(n): 17 | shift += diff[i] 18 | shift = (shift % 26 + 26) % 26 # Normalize shift to [0, 25] 19 | result[i] = chr((ord(result[i]) - ord('a') + shift) % 26 + ord('a')) 20 | 21 | return ''.join(result) 22 | -------------------------------------------------------------------------------- /Algorithms/src/2406. Divide Intervals Into Minimum Number of Groups/Code/solution.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Solution { 4 | public int minGroups(int[][] intervals) { 5 | // Sort intervals by start time 6 | Arrays.sort(intervals, (a, b) -> a[0] - b[0]); 7 | 8 | // Min-heap to track end times of active groups 9 | PriorityQueue pq = new PriorityQueue<>(); 10 | 11 | // Traverse through all intervals 12 | for (int[] interval : intervals) { 13 | int start = interval[0], end = interval[1]; 14 | 15 | // If the top of the heap (earliest end time) is less than the current start, 16 | // we can reuse that group 17 | if (!pq.isEmpty() && pq.peek() < start) { 18 | pq.poll(); 19 | } 20 | 21 | // Add the current interval's end time to the heap 22 | pq.add(end); 23 | } 24 | 25 | // The size of the heap represents the number of groups 26 | return pq.size(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Algorithms/src/2406. Divide Intervals Into Minimum Number of Groups/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} intervals 3 | * @return {number} 4 | */ 5 | var minGroups = function (intervals) { 6 | const events = []; 7 | 8 | // Separate start and end points into events 9 | for (const [start, end] of intervals) { 10 | events.push([start, 1]); // 1 indicates start of interval 11 | events.push([end + 1, -1]); // -1 indicates end of interval 12 | } 13 | 14 | // Sort events: by time first, then by type (-1 ends come before 1 starts) 15 | events.sort((a, b) => (a[0] === b[0] ? a[1] - b[1] : a[0] - b[0])); 16 | 17 | let maxGroups = 0, 18 | currentGroups = 0; 19 | 20 | // Process events 21 | for (const [time, type] of events) { 22 | currentGroups += type; 23 | maxGroups = Math.max(maxGroups, currentGroups); 24 | } 25 | 26 | return maxGroups; 27 | }; 28 | -------------------------------------------------------------------------------- /Algorithms/src/2406. Divide Intervals Into Minimum Number of Groups/Code/solution.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | class Solution: 4 | def minGroups(self, intervals: List[List[int]]) -> int: 5 | # Sort intervals by start time 6 | intervals.sort() 7 | 8 | # Min-heap to track the end times of active groups 9 | pq = [] 10 | 11 | # Traverse through all intervals 12 | for start, end in intervals: 13 | # If the earliest end time is less than the current start, reuse that group 14 | if pq and pq[0] < start: 15 | heapq.heappop(pq) 16 | 17 | # Add the current interval's end time to the heap 18 | heapq.heappush(pq, end) 19 | 20 | # The size of the heap is the number of groups 21 | return len(pq) 22 | -------------------------------------------------------------------------------- /Algorithms/src/2425. Bitwise XOR of All Pairings/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int xorAllNums(vector &nums1, vector &nums2) 5 | { 6 | int xor1 = 0, xor2 = 0; 7 | 8 | // XOR all elements in nums1 9 | for (int num : nums1) 10 | { 11 | xor1 ^= num; 12 | } 13 | 14 | // XOR all elements in nums2 15 | for (int num : nums2) 16 | { 17 | xor2 ^= num; 18 | } 19 | 20 | // If nums1 has odd length, include xor2 21 | // If nums2 has odd length, include xor1 22 | return (nums1.size() % 2 ? xor2 : 0) ^ (nums2.size() % 2 ? xor1 : 0); 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Algorithms/src/2425. Bitwise XOR of All Pairings/Code/solution.go: -------------------------------------------------------------------------------- 1 | func xorAllNums(nums1 []int, nums2 []int) int { 2 | xor1, xor2 := 0, 0 3 | 4 | // XOR all elements in nums1 5 | for _, num := range nums1 { 6 | xor1 ^= num 7 | } 8 | 9 | // XOR all elements in nums2 10 | for _, num := range nums2 { 11 | xor2 ^= num 12 | } 13 | 14 | // If nums1 has odd length, include xor2 15 | // If nums2 has odd length, include xor1 16 | if len(nums1)%2 == 1 { 17 | xor2 ^= xor1 18 | } 19 | if len(nums2)%2 == 1 { 20 | xor2 ^= xor1 21 | } 22 | 23 | return xor2 24 | } 25 | -------------------------------------------------------------------------------- /Algorithms/src/2425. Bitwise XOR of All Pairings/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int xorAllNums(int[] nums1, int[] nums2) { 3 | int xor1 = 0, xor2 = 0; 4 | 5 | // XOR all elements in nums1 6 | for (int num : nums1) { 7 | xor1 ^= num; 8 | } 9 | 10 | // XOR all elements in nums2 11 | for (int num : nums2) { 12 | xor2 ^= num; 13 | } 14 | 15 | // If nums1 has odd length, include xor2 16 | // If nums2 has odd length, include xor1 17 | return ((nums1.length % 2 == 1 ? xor2 : 0) ^ 18 | (nums2.length % 2 == 1 ? xor1 : 0)); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Algorithms/src/2425. Bitwise XOR of All Pairings/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums1 3 | * @param {number[]} nums2 4 | * @return {number} 5 | */ 6 | var xorAllNums = function (nums1, nums2) { 7 | let xor1 = 0, 8 | xor2 = 0; 9 | 10 | // XOR all elements in nums1 11 | for (const num of nums1) { 12 | xor1 ^= num; 13 | } 14 | 15 | // XOR all elements in nums2 16 | for (const num of nums2) { 17 | xor2 ^= num; 18 | } 19 | 20 | // If nums1 has odd length, include xor2 21 | // If nums2 has odd length, include xor1 22 | return (nums1.length % 2 ? xor2 : 0) ^ (nums2.length % 2 ? xor1 : 0); 23 | }; 24 | -------------------------------------------------------------------------------- /Algorithms/src/2425. Bitwise XOR of All Pairings/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def xorAllNums(self, nums1: List[int], nums2: List[int]) -> int: 3 | xor1, xor2 = 0, 0 4 | 5 | # XOR all elements in nums1 6 | for num in nums1: 7 | xor1 ^= num 8 | 9 | # XOR all elements in nums2 10 | for num in nums2: 11 | xor2 ^= num 12 | 13 | # If nums1 has odd length, include xor2 14 | # If nums2 has odd length, include xor1 15 | return ((xor2 if len(nums1) % 2 else 0) ^ 16 | (xor1 if len(nums2) % 2 else 0)) 17 | -------------------------------------------------------------------------------- /Algorithms/src/2429. Minimize XOR/Code/solution.go: -------------------------------------------------------------------------------- 1 | func minimizeXor(num1 int, num2 int) int { 2 | count2 := bits.OnesCount(uint(num2)) // Number of 1s in num2 3 | count1 := bits.OnesCount(uint(num1)) // Number of 1s in num1 4 | 5 | if count1 == count2 { 6 | return num1 7 | } 8 | 9 | result := num1 10 | if count1 > count2 { 11 | for i := 0; i < 32 && count1 > count2; i++ { 12 | if result&(1< count2) { 9 | for (let i = 0; i < 32 && count1 > count2; i++) { 10 | if ((result & (1 << i)) !== 0) { 11 | result &= ~(1 << i); // Clear bit 12 | count1--; 13 | } 14 | } 15 | } else { 16 | for (let i = 0; i < 32 && count1 < count2; i++) { 17 | if ((result & (1 << i)) === 0) { 18 | result |= 1 << i; // Set bit 19 | count1++; 20 | } 21 | } 22 | } 23 | return result; 24 | }; 25 | -------------------------------------------------------------------------------- /Algorithms/src/2429. Minimize XOR/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimizeXor(self, num1: int, num2: int) -> int: 3 | count2 = bin(num2).count('1') # Number of 1s in num2 4 | count1 = bin(num1).count('1') # Number of 1s in num1 5 | 6 | if count1 == count2: 7 | return num1 8 | 9 | result = num1 10 | if count1 > count2: 11 | for i in range(32): 12 | if count1 == count2: 13 | break 14 | if result & (1 << i): 15 | result &= ~(1 << i) # Clear bit 16 | count1 -= 1 17 | else: 18 | for i in range(32): 19 | if count1 == count2: 20 | break 21 | if not (result & (1 << i)): 22 | result |= (1 << i) # Set bit 23 | count1 += 1 24 | 25 | return result 26 | -------------------------------------------------------------------------------- /Algorithms/src/2490. Circular Sentence/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool isCircularSentence(string sentence) 5 | { 6 | // Step 1: Split the sentence into words 7 | vector words; 8 | string word; 9 | stringstream ss(sentence); 10 | 11 | while (ss >> word) 12 | { 13 | words.push_back(word); 14 | } 15 | 16 | // Step 2: Check adjacent pairs and the circular condition 17 | for (int i = 0; i < words.size(); ++i) 18 | { 19 | char lastChar = words[i].back(); 20 | char firstChar = words[(i + 1) % words.size()].front(); 21 | if (lastChar != firstChar) 22 | { 23 | return false; 24 | } 25 | } 26 | 27 | return true; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Algorithms/src/2490. Circular Sentence/Code/solution.go: -------------------------------------------------------------------------------- 1 | import "strings" 2 | 3 | func isCircularSentence(sentence string) bool { 4 | // Step 1: Split the sentence into words 5 | words := strings.Split(sentence, " ") 6 | 7 | // Step 2: Check adjacent pairs and the circular condition 8 | for i := 0; i < len(words); i++ { 9 | lastChar := words[i][len(words[i])-1] 10 | firstChar := words[(i+1)%len(words)][0] 11 | if lastChar != firstChar { 12 | return false 13 | } 14 | } 15 | 16 | return true 17 | } 18 | -------------------------------------------------------------------------------- /Algorithms/src/2490. Circular Sentence/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isCircularSentence(String sentence) { 3 | // Step 1: Split the sentence into words 4 | String[] words = sentence.split(" "); 5 | 6 | // Step 2: Check adjacent pairs and the circular condition 7 | for (int i = 0; i < words.length; i++) { 8 | char lastChar = words[i].charAt(words[i].length() - 1); 9 | char firstChar = words[(i + 1) % words.length].charAt(0); 10 | if (lastChar != firstChar) { 11 | return false; 12 | } 13 | } 14 | 15 | return true; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Algorithms/src/2490. Circular Sentence/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} sentence 3 | * @return {boolean} 4 | */ 5 | var isCircularSentence = function (sentence) { 6 | // Step 1: Split the sentence into words 7 | const words = sentence.split(" "); 8 | 9 | // Step 2: Check adjacent pairs and the circular condition 10 | for (let i = 0; i < words.length; i++) { 11 | let lastChar = words[i].charAt(words[i].length - 1); 12 | let firstChar = words[(i + 1) % words.length].charAt(0); 13 | if (lastChar !== firstChar) { 14 | return false; 15 | } 16 | } 17 | 18 | return true; 19 | }; 20 | -------------------------------------------------------------------------------- /Algorithms/src/2490. Circular Sentence/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isCircularSentence(self, sentence: str) -> bool: 3 | # Step 1: Split the sentence into words 4 | words = sentence.split() 5 | 6 | # Step 2: Check adjacent pairs and the circular condition 7 | for i in range(len(words)): 8 | last_char = words[i][-1] 9 | first_char = words[(i + 1) % len(words)][0] 10 | if last_char != first_char: 11 | return False 12 | 13 | return True 14 | -------------------------------------------------------------------------------- /Algorithms/src/2491. Divide Players Into Teams of Equal Skill/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | long long dividePlayers(vector &skill) 5 | { 6 | // Step 1: Sort the skill array 7 | sort(skill.begin(), skill.end()); 8 | 9 | int n = skill.size(); 10 | int totalSkill = skill[0] + skill[n - 1]; // Required sum for each pair 11 | long long chemistrySum = 0; 12 | 13 | // Step 2: Pair players using two pointers 14 | for (int i = 0; i < n / 2; i++) 15 | { 16 | // Check if the sum of current pair matches the required totalSkill 17 | if (skill[i] + skill[n - i - 1] != totalSkill) 18 | { 19 | return -1; // Invalid configuration, return -1 20 | } 21 | // Calculate the chemistry (product of pair) and add it to the sum 22 | chemistrySum += (long long)skill[i] * skill[n - i - 1]; 23 | } 24 | 25 | return chemistrySum; // Return total chemistry 26 | } 27 | }; -------------------------------------------------------------------------------- /Algorithms/src/2491. Divide Players Into Teams of Equal Skill/Code/solution.go: -------------------------------------------------------------------------------- 1 | import "sort" 2 | 3 | func dividePlayers(skill []int) int64 { 4 | // Step 1: Sort the skill array 5 | sort.Ints(skill) 6 | 7 | totalSkill := skill[0] + skill[len(skill)-1] // Required sum for each pair 8 | var chemistrySum int64 = 0 9 | 10 | // Step 2: Pair players using two pointers 11 | for i := 0; i < len(skill)/2; i++ { 12 | // Check if the sum of current pair matches the required totalSkill 13 | if skill[i]+skill[len(skill)-i-1] != totalSkill { 14 | return -1 // Invalid configuration, return -1 15 | } 16 | // Calculate the chemistry (product of pair) and add it to the sum 17 | chemistrySum += int64(skill[i]) * int64(skill[len(skill)-i-1]) 18 | } 19 | 20 | return chemistrySum // Return total chemistry 21 | } -------------------------------------------------------------------------------- /Algorithms/src/2491. Divide Players Into Teams of Equal Skill/Code/solution.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class Solution { 4 | public long dividePlayers(int[] skill) { 5 | // Step 1: Sort the skill array 6 | Arrays.sort(skill); 7 | 8 | int n = skill.length; 9 | int totalSkill = skill[0] + skill[n - 1]; // Required sum for each pair 10 | long chemistrySum = 0; 11 | 12 | // Step 2: Pair players using two pointers 13 | for (int i = 0; i < n / 2; i++) { 14 | // Check if the sum of current pair matches the required totalSkill 15 | if (skill[i] + skill[n - i - 1] != totalSkill) { 16 | return -1; // Invalid configuration, return -1 17 | } 18 | // Calculate the chemistry (product of pair) and add it to the sum 19 | chemistrySum += (long) skill[i] * skill[n - i - 1]; 20 | } 21 | 22 | return chemistrySum; // Return total chemistry 23 | } 24 | } -------------------------------------------------------------------------------- /Algorithms/src/2491. Divide Players Into Teams of Equal Skill/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} skill 3 | * @return {number} 4 | */ 5 | var dividePlayers = function (skill) { 6 | // Step 1: Sort the skill array 7 | skill.sort((a, b) => a - b); 8 | 9 | let totalSkill = skill[0] + skill[skill.length - 1]; // Required sum for each pair 10 | let chemistrySum = 0; 11 | 12 | // Step 2: Pair players using two pointers 13 | for (let i = 0; i < skill.length / 2; i++) { 14 | // Check if the sum of current pair matches the required totalSkill 15 | if (skill[i] + skill[skill.length - 1 - i] !== totalSkill) { 16 | return -1; // Invalid configuration, return -1 17 | } 18 | // Calculate the chemistry (product of pair) and add it to the sum 19 | chemistrySum += skill[i] * skill[skill.length - 1 - i]; 20 | } 21 | 22 | return chemistrySum; // Return total chemistry 23 | }; 24 | -------------------------------------------------------------------------------- /Algorithms/src/2491. Divide Players Into Teams of Equal Skill/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def dividePlayers(self, skill: List[int]) -> int: 3 | # Step 1: Sort the skill array 4 | skill.sort() 5 | 6 | total_skill = skill[0] + skill[-1] # Required sum for each pair 7 | chemistry_sum = 0 8 | 9 | # Step 2: Pair players using two pointers 10 | for i in range(len(skill) // 2): 11 | # Check if the sum of current pair matches the required total_skill 12 | if skill[i] + skill[-i - 1] != total_skill: 13 | return -1 # Invalid configuration, return -1 14 | # Calculate the chemistry (product of pair) and add it to the sum 15 | chemistry_sum += skill[i] * skill[-i - 1] 16 | 17 | return chemistry_sum # Return total chemistry -------------------------------------------------------------------------------- /Algorithms/src/2501. Longest Square Streak in an Array/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution 7 | { 8 | public: 9 | int longestSquareStreak(vector &nums) 10 | { 11 | sort(nums.begin(), nums.end()); 12 | unordered_set numSet(nums.begin(), nums.end()); 13 | int maxLength = -1; 14 | 15 | for (int num : nums) 16 | { 17 | int length = 0; 18 | long long current = num; 19 | while (numSet.count(current)) 20 | { 21 | length++; 22 | current *= current; 23 | if (current > 1e9) 24 | break; 25 | } 26 | if (length >= 2) 27 | { 28 | maxLength = max(maxLength, length); 29 | } 30 | } 31 | return maxLength; 32 | } 33 | }; -------------------------------------------------------------------------------- /Algorithms/src/2501. Longest Square Streak in an Array/Code/solution.go: -------------------------------------------------------------------------------- 1 | import ( 2 | "sort" 3 | ) 4 | 5 | func longestSquareStreak(nums []int) int { 6 | sort.Ints(nums) 7 | numSet := make(map[int]bool) 8 | for _, num := range nums { 9 | numSet[num] = true 10 | } 11 | 12 | maxLength := -1 13 | 14 | for _, num := range nums { 15 | length := 0 16 | current := num 17 | 18 | for numSet[current] { 19 | length++ 20 | current *= current 21 | if current > 1e9 { 22 | break 23 | } 24 | } 25 | if length >= 2 { 26 | if length > maxLength { 27 | maxLength = length 28 | } 29 | } 30 | } 31 | return maxLength 32 | } -------------------------------------------------------------------------------- /Algorithms/src/2501. Longest Square Streak in an Array/Code/solution.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.HashSet; 3 | 4 | class Solution { 5 | public int longestSquareStreak(int[] nums) { 6 | Arrays.sort(nums); 7 | HashSet numSet = new HashSet<>(); 8 | for (int num : nums) { 9 | numSet.add(num); 10 | } 11 | 12 | int maxLength = -1; 13 | 14 | for (int num : nums) { 15 | int length = 0; 16 | long current = num; 17 | 18 | while (numSet.contains((int) current)) { 19 | length++; 20 | current *= current; 21 | if (current > Integer.MAX_VALUE) 22 | break; 23 | } 24 | 25 | if (length >= 2) { 26 | maxLength = Math.max(maxLength, length); 27 | } 28 | } 29 | return maxLength; 30 | } 31 | } -------------------------------------------------------------------------------- /Algorithms/src/2501. Longest Square Streak in an Array/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | var longestSquareStreak = function (nums) { 6 | nums.sort((a, b) => a - b); 7 | const numSet = new Set(nums); 8 | let maxLength = -1; 9 | 10 | for (let num of nums) { 11 | let length = 0; 12 | let current = num; 13 | 14 | while (numSet.has(current)) { 15 | length++; 16 | current *= current; 17 | if (current > 1e9) break; 18 | } 19 | 20 | if (length >= 2) { 21 | maxLength = Math.max(maxLength, length); 22 | } 23 | } 24 | return maxLength; 25 | }; 26 | -------------------------------------------------------------------------------- /Algorithms/src/2501. Longest Square Streak in an Array/Code/solution.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def longestSquareStreak(self, nums: List[int]) -> int: 5 | nums.sort() 6 | num_set = set(nums) 7 | max_length = -1 8 | 9 | for num in nums: 10 | length = 0 11 | current = num 12 | while current in num_set: 13 | length += 1 14 | current = current * current 15 | if current > 1e9: break 16 | if length >= 2: 17 | max_length = max(max_length, length) 18 | 19 | return max_length -------------------------------------------------------------------------------- /Algorithms/src/2530. Maximal Score After Applying K Operations/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | class Solution 6 | { 7 | public: 8 | long long maxKelements(std::vector &nums, int k) 9 | { 10 | // Max-heap to store the numbers (priority_queue is by default a max-heap) 11 | std::priority_queue maxHeap; 12 | 13 | // Push all elements into the heap 14 | for (int num : nums) 15 | { 16 | maxHeap.push(num); 17 | } 18 | 19 | long long score = 0; 20 | 21 | // Perform k operations 22 | for (int i = 0; i < k; ++i) 23 | { 24 | long long maxVal = maxHeap.top(); 25 | maxHeap.pop(); 26 | 27 | // Add the largest value to the score 28 | score += maxVal; 29 | 30 | // Replace the number with ceil(maxVal / 3) 31 | maxHeap.push((maxVal + 2) / 3); // Using (maxVal + 2) / 3 to simulate ceil 32 | } 33 | 34 | return score; 35 | } 36 | }; -------------------------------------------------------------------------------- /Algorithms/src/2530. Maximal Score After Applying K Operations/Code/solution.java: -------------------------------------------------------------------------------- 1 | import java.util.PriorityQueue; 2 | 3 | class Solution { 4 | public long maxKelements(int[] nums, int k) { 5 | // Priority queue as max-heap 6 | PriorityQueue maxHeap = new PriorityQueue<>((a, b) -> Long.compare(b, a)); 7 | 8 | // Insert all elements into the max-heap 9 | for (int num : nums) { 10 | maxHeap.add((long) num); 11 | } 12 | 13 | long score = 0; 14 | 15 | // Perform k operations 16 | for (int i = 0; i < k; i++) { 17 | long maxVal = maxHeap.poll(); 18 | 19 | // Add the largest value to the score 20 | score += maxVal; 21 | 22 | // Replace the number with ceil(maxVal / 3) 23 | maxHeap.add((maxVal + 2) / 3); // Using (maxVal + 2) / 3 to simulate ceil 24 | } 25 | 26 | return score; 27 | } 28 | } -------------------------------------------------------------------------------- /Algorithms/src/2530. Maximal Score After Applying K Operations/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} k 4 | * @return {number} 5 | */ 6 | var maxKelements = function (nums, k) { 7 | // Max heap using a priority queue simulation 8 | const maxHeap = new MaxPriorityQueue(); 9 | 10 | // Insert all elements into the max-heap 11 | for (let num of nums) { 12 | maxHeap.enqueue(num); 13 | } 14 | 15 | let score = 0; 16 | 17 | // Perform k operations 18 | for (let i = 0; i < k; i++) { 19 | let maxVal = maxHeap.dequeue().element; 20 | 21 | // Add the largest value to the score 22 | score += maxVal; 23 | 24 | // Replace the number with ceil(maxVal / 3) 25 | maxHeap.enqueue(Math.ceil(maxVal / 3)); 26 | } 27 | 28 | return score; 29 | }; 30 | -------------------------------------------------------------------------------- /Algorithms/src/2530. Maximal Score After Applying K Operations/Code/solution.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | import math 3 | 4 | class Solution: 5 | def maxKelements(self, nums: List[int], k: int) -> int: 6 | # Max-heap (we negate values to simulate max-heap behavior) 7 | maxHeap = [-num for num in nums] 8 | heapq.heapify(maxHeap) 9 | 10 | score = 0 11 | 12 | # Perform k operations 13 | for _ in range(k): 14 | # Get the largest element (by negating to retrieve the max) 15 | maxVal = -heapq.heappop(maxHeap) 16 | 17 | # Add to the score 18 | score += maxVal 19 | 20 | # Replace the element with ceil(maxVal / 3) 21 | heapq.heappush(maxHeap, -math.ceil(maxVal / 3)) 22 | 23 | return score -------------------------------------------------------------------------------- /Algorithms/src/2559. Count Vowel Strings in Ranges/Code/solution.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func vowelStrings(words []string, queries [][]int) []int { 4 | vowels := map[byte]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true} 5 | n := len(words) 6 | prefix := make([]int, n) 7 | 8 | // Precompute the prefix sum 9 | for i := 0; i < n; i++ { 10 | if vowels[words[i][0]] && vowels[words[i][len(words[i])-1]] { 11 | prefix[i] = 1 12 | } 13 | if i > 0 { 14 | prefix[i] += prefix[i-1] 15 | } 16 | } 17 | 18 | // Answer the queries 19 | result := make([]int, len(queries)) 20 | for i, query := range queries { 21 | l, r := query[0], query[1] 22 | if l > 0 { 23 | result[i] = prefix[r] - prefix[l-1] 24 | } else { 25 | result[i] = prefix[r] 26 | } 27 | } 28 | return result 29 | } -------------------------------------------------------------------------------- /Algorithms/src/2559. Count Vowel Strings in Ranges/Code/solution.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Solution { 4 | public int[] vowelStrings(String[] words, int[][] queries) { 5 | Set vowels = Set.of('a', 'e', 'i', 'o', 'u'); 6 | int n = words.length; 7 | int[] prefix = new int[n]; 8 | 9 | // Precompute the prefix sum 10 | for (int i = 0; i < n; i++) { 11 | if (vowels.contains(words[i].charAt(0)) && vowels.contains(words[i].charAt(words[i].length() - 1))) { 12 | prefix[i] = 1; 13 | } 14 | if (i > 0) { 15 | prefix[i] += prefix[i - 1]; 16 | } 17 | } 18 | 19 | // Answer the queries 20 | int[] result = new int[queries.length]; 21 | for (int i = 0; i < queries.length; i++) { 22 | int l = queries[i][0], r = queries[i][1]; 23 | result[i] = prefix[r] - (l > 0 ? prefix[l - 1] : 0); 24 | } 25 | return result; 26 | } 27 | } -------------------------------------------------------------------------------- /Algorithms/src/2559. Count Vowel Strings in Ranges/Code/solution.js: -------------------------------------------------------------------------------- 1 | var vowelStrings = function (words, queries) { 2 | const vowels = new Set(["a", "e", "i", "o", "u"]); 3 | const n = words.length; 4 | const prefix = Array(n).fill(0); 5 | 6 | // Precompute the prefix sum 7 | for (let i = 0; i < n; i++) { 8 | if (vowels.has(words[i][0]) && vowels.has(words[i][words[i].length - 1])) { 9 | prefix[i] = 1; 10 | } 11 | if (i > 0) { 12 | prefix[i] += prefix[i - 1]; 13 | } 14 | } 15 | 16 | // Answer the queries 17 | return queries.map(([l, r]) => prefix[r] - (l > 0 ? prefix[l - 1] : 0)); 18 | }; 19 | -------------------------------------------------------------------------------- /Algorithms/src/2559. Count Vowel Strings in Ranges/Code/solution.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]: 5 | vowels = {'a', 'e', 'i', 'o', 'u'} 6 | n = len(words) 7 | prefix = [0] * n 8 | 9 | # Precompute the prefix sum 10 | for i in range(n): 11 | if words[i][0] in vowels and words[i][-1] in vowels: 12 | prefix[i] = 1 13 | if i > 0: 14 | prefix[i] += prefix[i - 1] 15 | 16 | # Answer the queries 17 | result = [] 18 | for l, r in queries: 19 | result.append(prefix[r] - (prefix[l - 1] if l > 0 else 0)) 20 | return result -------------------------------------------------------------------------------- /Algorithms/src/2563. Count the Number of Fair Pairs/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class Solution 5 | { 6 | public: 7 | long long countFairPairs(std::vector &nums, int lower, int upper) 8 | { 9 | // Sort the array for easier range search 10 | std::sort(nums.begin(), nums.end()); 11 | long long count = 0; 12 | int n = nums.size(); 13 | 14 | for (int i = 0; i < n - 1; ++i) 15 | { 16 | int min_val = lower - nums[i]; 17 | int max_val = upper - nums[i]; 18 | 19 | // Binary search to find valid range for nums[j] where i < j 20 | auto start = std::lower_bound(nums.begin() + i + 1, nums.end(), min_val); 21 | auto end = std::upper_bound(nums.begin() + i + 1, nums.end(), max_val); 22 | 23 | count += (end - start); 24 | } 25 | 26 | return count; 27 | } 28 | }; -------------------------------------------------------------------------------- /Algorithms/src/2563. Count the Number of Fair Pairs/Code/solution.go: -------------------------------------------------------------------------------- 1 | import ( 2 | "sort" 3 | ) 4 | 5 | func countFairPairs(nums []int, lower int, upper int) int64 { 6 | sort.Ints(nums) 7 | var count int64 = 0 8 | n := len(nums) 9 | 10 | for i := 0; i < n-1; i++ { 11 | minVal := lower - nums[i] 12 | maxVal := upper - nums[i] 13 | 14 | start := sort.Search(n-i-1, func(j int) bool { return nums[i+1+j] >= minVal }) + i + 1 15 | end := sort.Search(n-i-1, func(j int) bool { return nums[i+1+j] > maxVal }) + i + 1 16 | 17 | count += int64(end - start) 18 | } 19 | 20 | return count 21 | } -------------------------------------------------------------------------------- /Algorithms/src/2563. Count the Number of Fair Pairs/Code/solution.py: -------------------------------------------------------------------------------- 1 | from bisect import bisect_left, bisect_right 2 | from typing import List 3 | 4 | class Solution: 5 | def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int: 6 | nums.sort() 7 | count = 0 8 | n = len(nums) 9 | 10 | for i in range(n - 1): 11 | min_val = lower - nums[i] 12 | max_val = upper - nums[i] 13 | 14 | # Using bisect to find the range 15 | start = bisect_left(nums, min_val, i + 1) 16 | end = bisect_right(nums, max_val, i + 1) 17 | 18 | count += (end - start) 19 | 20 | return count -------------------------------------------------------------------------------- /Algorithms/src/2601. Prime Subtraction Operation/Code/solution.go: -------------------------------------------------------------------------------- 1 | func primeSubOperation(nums []int) bool { 2 | primes := generatePrimes(1000) 3 | for i := len(nums) - 2; i >= 0; i-- { 4 | if nums[i] < nums[i+1] { 5 | continue 6 | } 7 | 8 | target := nums[i] - nums[i+1] 9 | for _, p := range primes { 10 | if p > target { 11 | nums[i] -= p 12 | break 13 | } 14 | } 15 | if nums[i] <= 0 || nums[i] >= nums[i+1] { 16 | return false 17 | } 18 | } 19 | return true 20 | } 21 | 22 | func generatePrimes(maxNum int) []int { 23 | isPrime := make([]bool, maxNum+1) 24 | for i := 2; i <= maxNum; i++ { 25 | isPrime[i] = true 26 | } 27 | for i := 2; i*i <= maxNum; i++ { 28 | if isPrime[i] { 29 | for j := i * i; j <= maxNum; j += i { 30 | isPrime[j] = false 31 | } 32 | } 33 | } 34 | var primes []int 35 | for i := 2; i <= maxNum; i++ { 36 | if isPrime[i] { 37 | primes = append(primes, i) 38 | } 39 | } 40 | return primes 41 | } -------------------------------------------------------------------------------- /Algorithms/src/2601. Prime Subtraction Operation/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private boolean isPrime(int number) { 3 | if (number < 2) 4 | return false; 5 | 6 | for (int i = 2; i <= Math.sqrt(number); i++) { 7 | if (number % i == 0) { 8 | return false; 9 | } 10 | } 11 | return true; 12 | } 13 | 14 | public boolean primeSubOperation(int[] nums) { 15 | for (int i = 0; i < nums.length; i++) { 16 | int bound = (i == 0) ? nums[0] : nums[i] - nums[i - 1]; 17 | 18 | if (bound <= 0) { 19 | return false; 20 | } 21 | 22 | int largestPrime = 0; 23 | for (int j = bound - 1; j >= 2; j--) { 24 | if (isPrime(j)) { 25 | largestPrime = j; 26 | break; 27 | } 28 | } 29 | 30 | nums[i] -= largestPrime; 31 | } 32 | 33 | return true; 34 | } 35 | } -------------------------------------------------------------------------------- /Algorithms/src/2601. Prime Subtraction Operation/Code/solution.js: -------------------------------------------------------------------------------- 1 | const primeSubOperation = function (nums) { 2 | const sieve = new Array(1001).fill(true); 3 | const primes = []; 4 | 5 | for (let i = 2; i <= 1000; i++) { 6 | if (sieve[i]) { 7 | primes.push(i); 8 | for (let j = i * 2; j <= 1000; j += i) sieve[j] = false; 9 | } 10 | } 11 | 12 | for (let i = nums.length - 2; i >= 0; i--) { 13 | if (nums[i] < nums[i + 1]) continue; 14 | 15 | let target = nums[i] - nums[i + 1]; 16 | let prime = primes.find((p) => p > target); 17 | if (!prime) return false; 18 | 19 | nums[i] -= prime; 20 | if (nums[i] <= 0) return false; 21 | } 22 | return true; 23 | }; 24 | -------------------------------------------------------------------------------- /Algorithms/src/2601. Prime Subtraction Operation/Code/solution.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | class Solution: 4 | def primeSubOperation(self, nums): 5 | primes = self.sieve_of_eratosthenes(1000) 6 | 7 | for i in range(len(nums) - 2, -1, -1): 8 | if nums[i] < nums[i + 1]: continue 9 | 10 | target = nums[i] - nums[i + 1] 11 | prime = next((p for p in primes if p > target), None) 12 | if not prime: return False 13 | 14 | nums[i] -= prime 15 | if nums[i] <= 0: return False 16 | 17 | return True 18 | 19 | def sieve_of_eratosthenes(self, max_num): 20 | is_prime = [True] * (max_num + 1) 21 | is_prime[0] = is_prime[1] = False 22 | for i in range(2, int(math.sqrt(max_num)) + 1): 23 | if is_prime[i]: 24 | for j in range(i * i, max_num + 1, i): 25 | is_prime[j] = False 26 | return [i for i in range(2, max_num + 1) if is_prime[i]] -------------------------------------------------------------------------------- /Algorithms/src/2658. Maximum Number of Fish in a Grid/Code/solution.go: -------------------------------------------------------------------------------- 1 | func findMaxFish(grid [][]int) int { 2 | m, n := len(grid), len(grid[0]) 3 | visited := make([][]bool, m) 4 | for i := range visited { 5 | visited[i] = make([]bool, n) 6 | } 7 | maxFish := 0 8 | 9 | var dfs func(r, c int) int 10 | dfs = func(r, c int) int { 11 | if r < 0 || c < 0 || r >= m || c >= n || visited[r][c] || grid[r][c] == 0 { 12 | return 0 13 | } 14 | visited[r][c] = true 15 | fish := grid[r][c] 16 | fish += dfs(r+1, c) 17 | fish += dfs(r-1, c) 18 | fish += dfs(r, c+1) 19 | fish += dfs(r, c-1) 20 | return fish 21 | } 22 | 23 | for i := 0; i < m; i++ { 24 | for j := 0; j < n; j++ { 25 | if !visited[i][j] && grid[i][j] > 0 { 26 | maxFish = max(maxFish, dfs(i, j)) 27 | } 28 | } 29 | } 30 | return maxFish 31 | } 32 | 33 | func max(a, b int) int { 34 | if a > b { 35 | return a 36 | } 37 | return b 38 | } 39 | -------------------------------------------------------------------------------- /Algorithms/src/2658. Maximum Number of Fish in a Grid/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findMaxFish(int[][] grid) { 3 | int m = grid.length, n = grid[0].length; 4 | boolean[][] visited = new boolean[m][n]; 5 | int maxFish = 0; 6 | 7 | int dfs(int r, int c) { 8 | if (r < 0 || c < 0 || r >= m || c >= n || visited[r][c] || grid[r][c] == 0) 9 | return 0; 10 | visited[r][c] = true; 11 | int fish = grid[r][c]; 12 | fish += dfs(r + 1, c); 13 | fish += dfs(r - 1, c); 14 | fish += dfs(r, c + 1); 15 | fish += dfs(r, c - 1); 16 | return fish; 17 | } 18 | 19 | for (int i = 0; i < m; i++) { 20 | for (int j = 0; j < n; j++) { 21 | if (!visited[i][j] && grid[i][j] > 0) { 22 | maxFish = Math.max(maxFish, dfs(i, j)); 23 | } 24 | } 25 | } 26 | return maxFish; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Algorithms/src/2658. Maximum Number of Fish in a Grid/Code/solution.js: -------------------------------------------------------------------------------- 1 | var findMaxFish = function (grid) { 2 | const m = grid.length, 3 | n = grid[0].length; 4 | const visited = Array.from({ length: m }, () => Array(n).fill(false)); 5 | let maxFish = 0; 6 | 7 | const dfs = (r, c) => { 8 | if (r < 0 || c < 0 || r >= m || c >= n || visited[r][c] || grid[r][c] === 0) 9 | return 0; 10 | visited[r][c] = true; 11 | let fish = grid[r][c]; 12 | fish += dfs(r + 1, c); 13 | fish += dfs(r - 1, c); 14 | fish += dfs(r, c + 1); 15 | fish += dfs(r, c - 1); 16 | return fish; 17 | }; 18 | 19 | for (let i = 0; i < m; i++) { 20 | for (let j = 0; j < n; j++) { 21 | if (!visited[i][j] && grid[i][j] > 0) { 22 | maxFish = Math.max(maxFish, dfs(i, j)); 23 | } 24 | } 25 | } 26 | return maxFish; 27 | }; 28 | -------------------------------------------------------------------------------- /Algorithms/src/2658. Maximum Number of Fish in a Grid/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMaxFish(self, grid: List[List[int]]) -> int: 3 | m, n = len(grid), len(grid[0]) 4 | visited = [[False] * n for _ in range(m)] 5 | max_fish = 0 6 | 7 | def dfs(r, c): 8 | if r < 0 or c < 0 or r >= m or c >= n or visited[r][c] or grid[r][c] == 0: 9 | return 0 10 | visited[r][c] = True 11 | fish = grid[r][c] 12 | fish += dfs(r + 1, c) 13 | fish += dfs(r - 1, c) 14 | fish += dfs(r, c + 1) 15 | fish += dfs(r, c - 1) 16 | return fish 17 | 18 | for i in range(m): 19 | for j in range(n): 20 | if not visited[i][j] and grid[i][j] > 0: 21 | max_fish = max(max_fish, dfs(i, j)) 22 | return max_fish 23 | -------------------------------------------------------------------------------- /Algorithms/src/2661. First Completely Painted Row or Column/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int firstCompleteIndex(vector &arr, vector> &mat) 5 | { 6 | int m = mat.size(), n = mat[0].size(); 7 | unordered_map> position; 8 | vector rowCount(m, 0), colCount(n, 0); 9 | 10 | // Map matrix values to their positions 11 | for (int i = 0; i < m; i++) 12 | { 13 | for (int j = 0; j < n; j++) 14 | { 15 | position[mat[i][j]] = {i, j}; 16 | } 17 | } 18 | 19 | // Iterate through the array and simulate painting 20 | for (int i = 0; i < arr.size(); i++) 21 | { 22 | auto [row, col] = position[arr[i]]; 23 | rowCount[row]++; 24 | colCount[col]++; 25 | 26 | if (rowCount[row] == n || colCount[col] == m) 27 | { 28 | return i; 29 | } 30 | } 31 | return -1; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Algorithms/src/2661. First Completely Painted Row or Column/Code/solution.go: -------------------------------------------------------------------------------- 1 | func firstCompleteIndex(arr []int, mat [][]int) int { 2 | m, n := len(mat), len(mat[0]) 3 | position := make(map[int][2]int) 4 | rowCount := make([]int, m) 5 | colCount := make([]int, n) 6 | 7 | // Map matrix values to their positions 8 | for i := 0; i < m; i++ { 9 | for j := 0; j < n; j++ { 10 | position[mat[i][j]] = [2]int{i, j} 11 | } 12 | } 13 | 14 | // Iterate through the array and simulate painting 15 | for i, val := range arr { 16 | pos := position[val] 17 | row, col := pos[0], pos[1] 18 | rowCount[row]++ 19 | colCount[col]++ 20 | 21 | if rowCount[row] == n || colCount[col] == m { 22 | return i 23 | } 24 | } 25 | return -1 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms/src/2661. First Completely Painted Row or Column/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int firstCompleteIndex(int[] arr, int[][] mat) { 3 | int m = mat.length, n = mat[0].length; 4 | Map position = new HashMap<>(); 5 | int[] rowCount = new int[m]; 6 | int[] colCount = new int[n]; 7 | 8 | // Map matrix values to their positions 9 | for (int i = 0; i < m; i++) { 10 | for (int j = 0; j < n; j++) { 11 | position.put(mat[i][j], new int[] { i, j }); 12 | } 13 | } 14 | 15 | // Iterate through the array and simulate painting 16 | for (int i = 0; i < arr.length; i++) { 17 | int[] pos = position.get(arr[i]); 18 | int row = pos[0], col = pos[1]; 19 | rowCount[row]++; 20 | colCount[col]++; 21 | 22 | if (rowCount[row] == n || colCount[col] == m) { 23 | return i; 24 | } 25 | } 26 | return -1; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Algorithms/src/2661. First Completely Painted Row or Column/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} arr 3 | * @param {number[][]} mat 4 | * @return {number} 5 | */ 6 | var firstCompleteIndex = function (arr, mat) { 7 | const m = mat.length, 8 | n = mat[0].length; 9 | const position = new Map(); 10 | const rowCount = Array(m).fill(0); 11 | const colCount = Array(n).fill(0); 12 | 13 | // Map matrix values to their positions 14 | for (let i = 0; i < m; i++) { 15 | for (let j = 0; j < n; j++) { 16 | position.set(mat[i][j], [i, j]); 17 | } 18 | } 19 | 20 | // Iterate through the array and simulate painting 21 | for (let i = 0; i < arr.length; i++) { 22 | const [row, col] = position.get(arr[i]); 23 | rowCount[row]++; 24 | colCount[col]++; 25 | 26 | if (rowCount[row] === n || colCount[col] === m) { 27 | return i; 28 | } 29 | } 30 | return -1; 31 | }; 32 | -------------------------------------------------------------------------------- /Algorithms/src/2661. First Completely Painted Row or Column/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def firstCompleteIndex(self, arr: List[int], mat: List[List[int]]) -> int: 3 | m, n = len(mat), len(mat[0]) 4 | position = {} 5 | rowCount = [0] * m 6 | colCount = [0] * n 7 | 8 | # Map matrix values to their positions 9 | for i in range(m): 10 | for j in range(n): 11 | position[mat[i][j]] = (i, j) 12 | 13 | # Iterate through the array and simulate painting 14 | for i, val in enumerate(arr): 15 | row, col = position[val] 16 | rowCount[row] += 1 17 | colCount[col] += 1 18 | 19 | if rowCount[row] == n or colCount[col] == m: 20 | return i 21 | return -1 22 | -------------------------------------------------------------------------------- /Algorithms/src/2678. Number of Senior Citizens/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution 6 | { 7 | public: 8 | int countSeniors(vector &details) 9 | { 10 | int count = 0; // Initialize a counter to keep track of seniors 11 | 12 | // Iterate through each detail in the details vector 13 | for (const string &detail : details) 14 | { 15 | // Extract the substring representing the age, assuming the age is always at the same position 16 | string age_str = detail.substr(11, 2); 17 | // Convert the extracted substring to an integer to get the age 18 | int age = stoi(age_str); 19 | 20 | // Check if the extracted age is greater than 60 21 | if (age > 60) 22 | { 23 | count++; // Increment the counter if the person is a senior 24 | } 25 | } 26 | 27 | return count; // Return the total count of seniors 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Algorithms/src/2678. Number of Senior Citizens/Code/solution.go: -------------------------------------------------------------------------------- 1 | // countSeniors calculates the number of seniors (age > 60) in the provided details slice. 2 | func countSeniors(details []string) int { 3 | // Initialize the count of seniors 4 | count := 0 5 | 6 | // Iterate over each detail string in the slice 7 | for _, detail := range details { 8 | // Extract the age substring from the string (positions 11 to 12, inclusive) 9 | ageStr := detail[11:13] 10 | 11 | // Convert the age substring to an integer 12 | age, _ := strconv.Atoi(ageStr) 13 | 14 | // If the converted age is greater than 60, increment the count 15 | if age > 60 { 16 | count++ 17 | } 18 | } 19 | 20 | // Return the total count of seniors 21 | return count 22 | } -------------------------------------------------------------------------------- /Algorithms/src/2678. Number of Senior Citizens/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countSeniors(String[] details) { 3 | int count = 0; // Initialize a counter for the number of seniors 4 | 5 | // Iterate through each detail in the input array 6 | for (String detail : details) { 7 | // Extract the age substring from the detail string 8 | // Age is located at index 11 and 12 (2 characters) 9 | String ageStr = detail.substring(11, 13); 10 | 11 | // Convert the age substring to an integer 12 | int age = Integer.parseInt(ageStr); 13 | 14 | // Check if the age is greater than 60 15 | if (age > 60) { 16 | count++; // Increment the counter if the person is a senior 17 | } 18 | } 19 | 20 | // Return the total count of seniors 21 | return count; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Algorithms/src/2678. Number of Senior Citizens/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Function to count the number of seniors (age > 60) based on details provided. 3 | * 4 | * @param {string[]} details - An array of strings where each string contains personal details. 5 | * @return {number} - The count of people whose age is greater than 60. 6 | */ 7 | var countSeniors = function (details) { 8 | let count = 0; // Initialize the count of seniors to 0 9 | 10 | // Iterate over each detail in the details array 11 | for (let detail of details) { 12 | // Extract the substring representing the age from the detail 13 | // Assuming the age is always located at a fixed position in the string 14 | let age_str = detail.substring(11, 13); 15 | 16 | // Convert the extracted substring to an integer 17 | let age = parseInt(age_str); 18 | 19 | // Check if the extracted age is greater than 60 20 | if (age > 60) { 21 | count++; // Increment the count if the condition is true 22 | } 23 | } 24 | 25 | return count; // Return the total count of seniors 26 | }; 27 | -------------------------------------------------------------------------------- /Algorithms/src/2678. Number of Senior Citizens/Code/solution.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def countSeniors(self, details: List[str]) -> int: 5 | # Initialize a counter to keep track of the number of seniors 6 | count = 0 7 | 8 | # Iterate through each detail string in the list 9 | for detail in details: 10 | # Extract the substring that represents the age, located at indices 11 and 12 11 | age_str = detail[11:13] 12 | 13 | # Convert the extracted substring to an integer to get the age 14 | age = int(age_str) 15 | 16 | # Check if the extracted age is greater than 60 17 | if age > 60: 18 | # If the age is greater than 60, increment the senior count 19 | count += 1 20 | 21 | # Return the total count of seniors 22 | return count 23 | -------------------------------------------------------------------------------- /Algorithms/src/2683. Neighboring Bitwise XOR/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution 5 | { 6 | public: 7 | bool doesValidArrayExist(vector &derived) 8 | { 9 | int n = derived.size(); 10 | // Case 1: Assume original[0] = 0 11 | bool validCase1 = true; 12 | int current = 0; // original[0] 13 | for (int i = 0; i < n; ++i) 14 | { 15 | current = derived[i] ^ current; // Compute original[i+1] 16 | } 17 | validCase1 = (current == 0); // Wrap-around condition 18 | 19 | // Case 2: Assume original[0] = 1 20 | bool validCase2 = true; 21 | current = 1; // original[0] 22 | for (int i = 0; i < n; ++i) 23 | { 24 | current = derived[i] ^ current; // Compute original[i+1] 25 | } 26 | validCase2 = (current == 1); // Wrap-around condition 27 | 28 | return validCase1 || validCase2; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Algorithms/src/2683. Neighboring Bitwise XOR/Code/solution.go: -------------------------------------------------------------------------------- 1 | func doesValidArrayExist(derived []int) bool { 2 | n := len(derived) 3 | 4 | // Case 1: Assume original[0] = 0 5 | validCase1 := true 6 | current := 0 // original[0] 7 | for i := 0; i < n; i++ { 8 | current = derived[i] ^ current // Compute original[i+1] 9 | } 10 | validCase1 = (current == 0) // Wrap-around condition 11 | 12 | // Case 2: Assume original[0] = 1 13 | validCase2 := true 14 | current = 1 // original[0] 15 | for i := 0; i < n; i++ { 16 | current = derived[i] ^ current // Compute original[i+1] 17 | } 18 | validCase2 = (current == 1) // Wrap-around condition 19 | 20 | return validCase1 || validCase2 21 | } 22 | -------------------------------------------------------------------------------- /Algorithms/src/2683. Neighboring Bitwise XOR/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean doesValidArrayExist(int[] derived) { 3 | int n = derived.length; 4 | // Case 1: Assume original[0] = 0 5 | boolean validCase1 = true; 6 | int current = 0; // original[0] 7 | for (int i = 0; i < n; i++) { 8 | current = derived[i] ^ current; // Compute original[i+1] 9 | } 10 | validCase1 = (current == 0); // Wrap-around condition 11 | 12 | // Case 2: Assume original[0] = 1 13 | boolean validCase2 = true; 14 | current = 1; // original[0] 15 | for (int i = 0; i < n; i++) { 16 | current = derived[i] ^ current; // Compute original[i+1] 17 | } 18 | validCase2 = (current == 1); // Wrap-around condition 19 | 20 | return validCase1 || validCase2; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Algorithms/src/2683. Neighboring Bitwise XOR/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} derived 3 | * @return {boolean} 4 | */ 5 | var doesValidArrayExist = function (derived) { 6 | const n = derived.length; 7 | 8 | // Case 1: Assume original[0] = 0 9 | let validCase1 = true; 10 | let current = 0; // original[0] 11 | for (let i = 0; i < n; i++) { 12 | current = derived[i] ^ current; // Compute original[i+1] 13 | } 14 | validCase1 = current === 0; // Wrap-around condition 15 | 16 | // Case 2: Assume original[0] = 1 17 | let validCase2 = true; 18 | current = 1; // original[0] 19 | for (let i = 0; i < n; i++) { 20 | current = derived[i] ^ current; // Compute original[i+1] 21 | } 22 | validCase2 = current === 1; // Wrap-around condition 23 | 24 | return validCase1 || validCase2; 25 | }; 26 | -------------------------------------------------------------------------------- /Algorithms/src/2683. Neighboring Bitwise XOR/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def doesValidArrayExist(self, derived: List[int]) -> bool: 3 | n = len(derived) 4 | 5 | # Case 1: Assume original[0] = 0 6 | valid_case1 = True 7 | current = 0 # original[0] 8 | for i in range(n): 9 | current = derived[i] ^ current # Compute original[i+1] 10 | valid_case1 = (current == 0) # Wrap-around condition 11 | 12 | # Case 2: Assume original[0] = 1 13 | valid_case2 = True 14 | current = 1 # original[0] 15 | for i in range(n): 16 | current = derived[i] ^ current # Compute original[i+1] 17 | valid_case2 = (current == 1) # Wrap-around condition 18 | 19 | return valid_case1 or valid_case2 20 | -------------------------------------------------------------------------------- /Algorithms/src/2684. Maximum Number of Moves in a Grid/Code/solution.go: -------------------------------------------------------------------------------- 1 | func maxMoves(grid [][]int) int { 2 | m, n := len(grid), len(grid[0]) 3 | dp := make([][]int, m) 4 | for i := range dp { 5 | dp[i] = make([]int, n) 6 | } 7 | maxMoves := 0 8 | 9 | for col := n - 2; col >= 0; col-- { 10 | for row := 0; row < m; row++ { 11 | if row > 0 && grid[row][col] < grid[row-1][col+1] { 12 | dp[row][col] = max(dp[row][col], dp[row-1][col+1]+1) 13 | } 14 | if grid[row][col] < grid[row][col+1] { 15 | dp[row][col] = max(dp[row][col], dp[row][col+1]+1) 16 | } 17 | if row < m-1 && grid[row][col] < grid[row+1][col+1] { 18 | dp[row][col] = max(dp[row][col], dp[row+1][col+1]+1) 19 | } 20 | } 21 | } 22 | 23 | for row := 0; row < m; row++ { 24 | maxMoves = max(maxMoves, dp[row][0]) 25 | } 26 | return maxMoves 27 | } 28 | 29 | func max(a, b int) int { 30 | if a > b { 31 | return a 32 | } 33 | return b 34 | } -------------------------------------------------------------------------------- /Algorithms/src/2684. Maximum Number of Moves in a Grid/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[][]} grid 3 | * @return {number} 4 | */ 5 | var maxMoves = function (grid) { 6 | const m = grid.length, 7 | n = grid[0].length; 8 | const dp = Array.from({ length: m }, () => Array(n).fill(0)); 9 | let maxMoves = 0; 10 | 11 | for (let col = n - 2; col >= 0; col--) { 12 | for (let row = 0; row < m; row++) { 13 | if (row > 0 && grid[row][col] < grid[row - 1][col + 1]) { 14 | dp[row][col] = Math.max(dp[row][col], dp[row - 1][col + 1] + 1); 15 | } 16 | if (grid[row][col] < grid[row][col + 1]) { 17 | dp[row][col] = Math.max(dp[row][col], dp[row][col + 1] + 1); 18 | } 19 | if (row < m - 1 && grid[row][col] < grid[row + 1][col + 1]) { 20 | dp[row][col] = Math.max(dp[row][col], dp[row + 1][col + 1] + 1); 21 | } 22 | } 23 | } 24 | 25 | for (let row = 0; row < m; row++) { 26 | maxMoves = Math.max(maxMoves, dp[row][0]); 27 | } 28 | return maxMoves; 29 | }; 30 | -------------------------------------------------------------------------------- /Algorithms/src/2684. Maximum Number of Moves in a Grid/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxMoves(self, grid: List[List[int]]) -> int: 3 | m, n = len(grid), len(grid[0]) 4 | dp = [[0] * n for _ in range(m)] 5 | max_moves = 0 6 | 7 | for col in range(n - 2, -1, -1): 8 | for row in range(m): 9 | if row > 0 and grid[row][col] < grid[row - 1][col + 1]: 10 | dp[row][col] = max(dp[row][col], dp[row - 1][col + 1] + 1) 11 | if grid[row][col] < grid[row][col + 1]: 12 | dp[row][col] = max(dp[row][col], dp[row][col + 1] + 1) 13 | if row < m - 1 and grid[row][col] < grid[row + 1][col + 1]: 14 | dp[row][col] = max(dp[row][col], dp[row + 1][col + 1] + 1) 15 | 16 | for row in range(m): 17 | max_moves = max(max_moves, dp[row][0]) 18 | return max_moves -------------------------------------------------------------------------------- /Algorithms/src/2696. Minimum String Length After Removing Substrings/Code/solution.c++: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int minLength(string s) 5 | { 6 | stack stk; // Stack to store characters 7 | 8 | // Traverse through each character in the string 9 | for (char ch : s) 10 | { 11 | // Check if the top of the stack forms "AB" or "CD" with current character 12 | if (!stk.empty() && ((stk.top() == 'A' && ch == 'B') || (stk.top() == 'C' && ch == 'D'))) 13 | { 14 | stk.pop(); // Pop if pair is found and remove the substring 15 | } 16 | else 17 | { 18 | stk.push(ch); // Otherwise, push the character onto the stack 19 | } 20 | } 21 | 22 | return stk.size(); // The size of the stack is the minimum length 23 | } 24 | }; -------------------------------------------------------------------------------- /Algorithms/src/2696. Minimum String Length After Removing Substrings/Code/solution.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func minLength(s string) int { 4 | stack := []rune{} // Stack to store characters 5 | 6 | // Traverse through each character in the string 7 | for _, ch := range s { 8 | // If top of the stack forms "AB" or "CD" with the current character, pop the stack 9 | if len(stack) > 0 && ((stack[len(stack)-1] == 'A' && ch == 'B') || 10 | (stack[len(stack)-1] == 'C' && ch == 'D')) { 11 | stack = stack[:len(stack)-1] // Remove the substring 12 | } else { 13 | stack = append(stack, ch) // Push current character onto the stack if no pair 14 | } 15 | } 16 | 17 | return len(stack) // The size of the stack is the minimum length of the string 18 | } -------------------------------------------------------------------------------- /Algorithms/src/2696. Minimum String Length After Removing Substrings/Code/solution.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | class Solution { 4 | public int minLength(String s) { 5 | Stack stack = new Stack<>(); 6 | 7 | // Traverse through each character in the string 8 | for (char ch : s.toCharArray()) { 9 | // If the top of the stack forms "AB" or "CD" with the current character, pop 10 | // the stack 11 | if (!stack.isEmpty() && ((stack.peek() == 'A' && ch == 'B') || (stack.peek() == 'C' && ch == 'D'))) { 12 | stack.pop(); // Remove the substring 13 | } else { 14 | stack.push(ch); // Push character onto the stack if no pair is found 15 | } 16 | } 17 | 18 | return stack.size(); // The size of the stack is the minimum length of the string 19 | } 20 | } -------------------------------------------------------------------------------- /Algorithms/src/2696. Minimum String Length After Removing Substrings/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {number} 4 | */ 5 | var minLength = function (s) { 6 | let stack = []; 7 | 8 | // Traverse through each character in the string 9 | for (let ch of s) { 10 | // Check if top of the stack forms "AB" or "CD" with current character 11 | if ( 12 | stack.length > 0 && 13 | ((stack[stack.length - 1] === "A" && ch === "B") || 14 | (stack[stack.length - 1] === "C" && ch === "D")) 15 | ) { 16 | stack.pop(); // Pop to remove the pair 17 | } else { 18 | stack.push(ch); // Push current character onto the stack if no match 19 | } 20 | } 21 | 22 | return stack.length; // Remaining stack size is the minimum length of the string 23 | }; 24 | -------------------------------------------------------------------------------- /Algorithms/src/2696. Minimum String Length After Removing Substrings/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minLength(self, s: str) -> int: 3 | stack = [] 4 | 5 | # Traverse through each character in the string 6 | for ch in s: 7 | # If top of the stack forms "AB" or "CD" with the current character, pop the stack 8 | if stack and ((stack[-1] == 'A' and ch == 'B') or (stack[-1] == 'C' and ch == 'D')): 9 | stack.pop() # Remove the substring 10 | else: 11 | stack.append(ch) # Push current character onto the stack if no pair 12 | 13 | return len(stack) # The size of the stack is the minimum length -------------------------------------------------------------------------------- /Algorithms/src/2938. Separate Black and White Balls/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | long long minimumSteps(string s) 5 | { 6 | int n = s.length(); 7 | long long ans = 0; 8 | int cnt = 0; // Tracks the number of black balls (1s) 9 | 10 | // Traverse through the string 11 | for (int i = 0; i < n; i++) 12 | { 13 | if (s[i] == '0') 14 | { 15 | // White ball encountered, add the number of black balls on its left 16 | ans += cnt; 17 | } 18 | else 19 | { 20 | // Black ball encountered, increment the black ball count 21 | cnt++; 22 | } 23 | } 24 | return ans; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Algorithms/src/2938. Separate Black and White Balls/Code/solution.go: -------------------------------------------------------------------------------- 1 | func minimumSteps(s string) int64 { 2 | var ans int64 = 0 3 | var blackCount int = 0 // Tracks the number of black balls (1s) 4 | 5 | // Traverse through the string 6 | for i := 0; i < len(s); i++ { 7 | if s[i] == '0' { 8 | // White ball encountered, add the number of black balls on its left 9 | ans += int64(blackCount) 10 | } else { 11 | // Black ball encountered, increment the black ball count 12 | blackCount++ 13 | } 14 | } 15 | 16 | return ans 17 | } 18 | -------------------------------------------------------------------------------- /Algorithms/src/2938. Separate Black and White Balls/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public long minimumSteps(String s) { 3 | long ans = 0; 4 | int blackCount = 0; // Tracks the number of black balls (1s) 5 | 6 | // Traverse through the string 7 | for (int i = 0; i < s.length(); i++) { 8 | if (s.charAt(i) == '0') { 9 | // White ball encountered, add the number of black balls on its left 10 | ans += blackCount; 11 | } else { 12 | // Black ball encountered, increment the black ball count 13 | blackCount++; 14 | } 15 | } 16 | return ans; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms/src/2938. Separate Black and White Balls/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {number} 4 | */ 5 | var minimumSteps = function (s) { 6 | let ans = 0; 7 | let blackCount = 0; // Tracks the number of black balls (1s) 8 | 9 | // Traverse through the string 10 | for (let i = 0; i < s.length; i++) { 11 | if (s[i] === "0") { 12 | // White ball encountered, add the number of black balls on its left 13 | ans += blackCount; 14 | } else { 15 | // Black ball encountered, increment the black ball count 16 | blackCount++; 17 | } 18 | } 19 | 20 | return ans; 21 | }; 22 | -------------------------------------------------------------------------------- /Algorithms/src/2938. Separate Black and White Balls/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumSteps(self, s: str) -> int: 3 | ans = 0 4 | blackCount = 0 # Tracks the number of black balls (1s) 5 | 6 | # Traverse through the string 7 | for ch in s: 8 | if ch == '0': 9 | # White ball encountered, add the number of black balls on its left 10 | ans += blackCount 11 | else: 12 | # Black ball encountered, increment the black ball count 13 | blackCount += 1 14 | 15 | return ans 16 | -------------------------------------------------------------------------------- /Algorithms/src/3042. Count Prefix and Suffix Pairs I/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int countPrefixSuffixPairs(vector &words) 5 | { 6 | int n = words.size(); 7 | int count = 0; 8 | 9 | for (int i = 0; i < n; ++i) 10 | { 11 | for (int j = i + 1; j < n; ++j) 12 | { 13 | // Check if words[i] is prefix and suffix of words[j] 14 | int len = words[i].size(); 15 | if (words[j].substr(0, len) == words[i] && words[j].substr(words[j].size() - len) == words[i]) 16 | { 17 | count++; 18 | } 19 | } 20 | } 21 | 22 | return count; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Algorithms/src/3042. Count Prefix and Suffix Pairs I/Code/solution.go: -------------------------------------------------------------------------------- 1 | func countPrefixSuffixPairs(words []string) int { 2 | count := 0 3 | n := len(words) 4 | 5 | for i := 0; i < n; i++ { 6 | for j := i + 1; j < n; j++ { 7 | prefix := words[i] 8 | word := words[j] 9 | if len(prefix) <= len(word) && 10 | strings.HasPrefix(word, prefix) && 11 | strings.HasSuffix(word, prefix) { 12 | count++ 13 | } 14 | } 15 | } 16 | 17 | return count 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms/src/3042. Count Prefix and Suffix Pairs I/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countPrefixSuffixPairs(String[] words) { 3 | int n = words.length; 4 | int count = 0; 5 | 6 | for (int i = 0; i < n; i++) { 7 | for (int j = i + 1; j < n; j++) { 8 | String prefix = words[i]; 9 | String word = words[j]; 10 | int len = prefix.length(); 11 | 12 | if (word.startsWith(prefix) && word.endsWith(prefix)) { 13 | count++; 14 | } 15 | } 16 | } 17 | 18 | return count; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Algorithms/src/3042. Count Prefix and Suffix Pairs I/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string[]} words 3 | * @return {number} 4 | */ 5 | var countPrefixSuffixPairs = function (words) { 6 | let count = 0; 7 | let n = words.length; 8 | 9 | for (let i = 0; i < n; i++) { 10 | for (let j = i + 1; j < n; j++) { 11 | let prefix = words[i]; 12 | let word = words[j]; 13 | let len = prefix.length; 14 | 15 | if (word.startsWith(prefix) && word.endsWith(prefix)) { 16 | count++; 17 | } 18 | } 19 | } 20 | 21 | return count; 22 | }; 23 | -------------------------------------------------------------------------------- /Algorithms/src/3042. Count Prefix and Suffix Pairs I/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countPrefixSuffixPairs(self, words: List[str]) -> int: 3 | count = 0 4 | n = len(words) 5 | 6 | for i in range(n): 7 | for j in range(i + 1, n): 8 | prefix = words[i] 9 | word = words[j] 10 | if word.startswith(prefix) and word.endswith(prefix): 11 | count += 1 12 | 13 | return count 14 | -------------------------------------------------------------------------------- /Algorithms/src/3163. String Compression III/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | string compressedString(string word) 5 | { 6 | string comp; 7 | int count = 1; 8 | 9 | for (int i = 1; i <= word.size(); ++i) 10 | { 11 | if (i == word.size() || word[i] != word[i - 1] || count == 9) 12 | { 13 | comp += to_string(count) + word[i - 1]; 14 | count = 1; 15 | } 16 | else 17 | { 18 | count++; 19 | } 20 | } 21 | 22 | return comp; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Algorithms/src/3163. String Compression III/Code/solution.go: -------------------------------------------------------------------------------- 1 | func compressedString(word string) string { 2 | var comp string 3 | count := 1 4 | 5 | for i := 1; i <= len(word); i++ { 6 | if i == len(word) || word[i] != word[i-1] || count == 9 { 7 | comp += fmt.Sprintf("%d%c", count, word[i-1]) 8 | count = 1 9 | } else { 10 | count++ 11 | } 12 | } 13 | 14 | return comp 15 | } 16 | -------------------------------------------------------------------------------- /Algorithms/src/3163. String Compression III/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String compressedString(String word) { 3 | StringBuilder comp = new StringBuilder(); 4 | int count = 1; 5 | 6 | for (int i = 1; i <= word.length(); i++) { 7 | if (i == word.length() || word.charAt(i) != word.charAt(i - 1) || count == 9) { 8 | comp.append(count).append(word.charAt(i - 1)); 9 | count = 1; 10 | } else { 11 | count++; 12 | } 13 | } 14 | 15 | return comp.toString(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Algorithms/src/3163. String Compression III/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} word 3 | * @return {string} 4 | */ 5 | var compressedString = function (word) { 6 | let comp = ""; 7 | let count = 1; 8 | 9 | for (let i = 1; i <= word.length; i++) { 10 | if (i === word.length || word[i] !== word[i - 1] || count === 9) { 11 | comp += count + word[i - 1]; 12 | count = 1; 13 | } else { 14 | count++; 15 | } 16 | } 17 | 18 | return comp; 19 | }; 20 | -------------------------------------------------------------------------------- /Algorithms/src/3163. String Compression III/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def compressedString(self, word: str) -> str: 3 | comp = [] 4 | count = 1 5 | 6 | for i in range(1, len(word) + 1): 7 | if i == len(word) or word[i] != word[i - 1] or count == 9: 8 | comp.append(f"{count}{word[i - 1]}") 9 | count = 1 10 | else: 11 | count += 1 12 | 13 | return ''.join(comp) 14 | -------------------------------------------------------------------------------- /Algorithms/src/3254. Find the Power of K-Size Subarrays I/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} k 4 | * @return {number[]} 5 | */ 6 | var resultsArray = function (nums, k) { 7 | let n = nums.length; 8 | let result = []; 9 | 10 | for (let i = 0; i <= n - k; i++) { 11 | let subarray = nums.slice(i, i + k); 12 | let sortedSubarray = [...subarray].sort((a, b) => a - b); 13 | 14 | // Check if elements are consecutive 15 | let isConsecutive = true; 16 | for (let j = 1; j < k; j++) { 17 | if (sortedSubarray[j] - sortedSubarray[j - 1] !== 1) { 18 | isConsecutive = false; 19 | break; 20 | } 21 | } 22 | 23 | // Add the result based on conditions 24 | if ( 25 | isConsecutive && 26 | subarray.every((val, idx) => val === sortedSubarray[idx]) 27 | ) { 28 | result.push(sortedSubarray[k - 1]); // Max element 29 | } else { 30 | result.push(-1); 31 | } 32 | } 33 | 34 | return result; 35 | }; 36 | -------------------------------------------------------------------------------- /Algorithms/src/3254. Find the Power of K-Size Subarrays I/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def resultsArray(self, nums: List[int], k: int) -> List[int]: 3 | n = len(nums) 4 | result = [] 5 | 6 | for i in range(n - k + 1): 7 | subarray = nums[i:i + k] 8 | sorted_subarray = sorted(subarray) 9 | 10 | # Check if elements are consecutive 11 | is_consecutive = all( 12 | sorted_subarray[j] - sorted_subarray[j - 1] == 1 for j in range(1, k) 13 | ) 14 | 15 | # Add the result based on conditions 16 | if is_consecutive and subarray == sorted_subarray: 17 | result.append(sorted_subarray[-1]) # Max element 18 | else: 19 | result.append(-1) 20 | 21 | return result -------------------------------------------------------------------------------- /Algorithms/src/350. Intersection of Two Arrays II/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector intersect(vector& nums1, vector& nums2) { 8 | vector result; 9 | 10 | // Iterate through nums1 11 | for (int i = 0; i < nums1.size(); i++) { 12 | // Iterate through nums2 to find matching elements 13 | for (int j = 0; j < nums2.size(); j++) { 14 | if (nums1[i] == nums2[j]) { // Found a common element 15 | result.push_back(nums1[i]); // Add it to the result vector 16 | nums2[j] = -1; // Mark nums2[j] as visited (using -1) 17 | break; // Break the inner loop to avoid duplicates in result 18 | } 19 | } 20 | } 21 | 22 | return result; // Return the vector containing intersection elements 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Algorithms/src/350. Intersection of Two Arrays II/Code/solution.go: -------------------------------------------------------------------------------- 1 | func intersect(nums1 []int, nums2 []int) []int { 2 | // Step 1: Create a map to count occurrences of each number in nums1. 3 | countMap := make(map[int]int) 4 | var result []int 5 | 6 | // Step 2: Populate countMap with counts of each number in nums1. 7 | for _, num := range nums1 { 8 | countMap[num]++ 9 | } 10 | 11 | // Step 3: Iterate through nums2 to find common elements. 12 | for _, num := range nums2 { 13 | // Step 4: If num exists in countMap and has remaining counts, add it to result. 14 | if countMap[num] > 0 { 15 | result = append(result, num) 16 | // Step 5: Decrease the count of num in countMap. 17 | countMap[num]-- 18 | } 19 | } 20 | 21 | // Step 6: Return the result containing the intersection of nums1 and nums2. 22 | return result 23 | } 24 | -------------------------------------------------------------------------------- /Algorithms/src/350. Intersection of Two Arrays II/Code/solution.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | class Solution: 4 | def intersect(self, nums1, nums2): 5 | # Step 1: Create a Counter object from nums1 to count occurrences of each number 6 | countMap = Counter(nums1) 7 | 8 | # Step 2: Initialize an empty list to store the intersection result 9 | result = [] 10 | 11 | # Step 3: Iterate through each number in nums2 12 | for num in nums2: 13 | # Step 4: Check if the number exists in countMap and has a count greater than 0 14 | if countMap[num] > 0: 15 | # Step 5: If so, append the number to the result list 16 | result.append(num) 17 | # Step 6: Decrease the count of the number in countMap 18 | countMap[num] -= 1 19 | 20 | # Step 7: Return the intersection result list 21 | return result 22 | -------------------------------------------------------------------------------- /Algorithms/src/432. All O`one Data Structure/Code/solution.py: -------------------------------------------------------------------------------- 1 | class AllOne: 2 | def __init__(self): 3 | self.myDict = {} 4 | 5 | def inc(self, key: str) -> None: 6 | if key in self.myDict: 7 | self.myDict[key] += 1 8 | else: 9 | self.myDict[key] = 1 10 | 11 | def dec(self, key: str) -> None: 12 | if key in self.myDict: 13 | if self.myDict[key] > 1: 14 | self.myDict[key] -= 1 15 | else: 16 | self.myDict.pop(key) 17 | 18 | def getMaxKey(self) -> str: 19 | if not self.myDict: 20 | return "" 21 | maxVal = max(self.myDict.values()) 22 | for key in self.myDict.keys(): 23 | if self.myDict[key] == maxVal: 24 | return key 25 | 26 | def getMinKey(self) -> str: 27 | if not self.myDict: 28 | return "" 29 | minVal = min(self.myDict.values()) 30 | for key in self.myDict.keys(): 31 | if self.myDict[key] == minVal: 32 | return key 33 | -------------------------------------------------------------------------------- /Algorithms/src/440. K-th Smallest in Lexicographical Order/Code/solution.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/withaarzoo/LeetCode-Solutions/5f6d8d0ebfcbbfc17604f36497575b9fcec22987/Algorithms/src/440. K-th Smallest in Lexicographical Order/Code/solution.py -------------------------------------------------------------------------------- /Algorithms/src/567. Permutation in String/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool checkInclusion(string s1, string s2) 5 | { 6 | if (s1.length() > s2.length()) 7 | return false; 8 | 9 | vector s1Count(26, 0), s2Count(26, 0); 10 | 11 | // Count frequencies of s1 and the first window in s2 12 | for (int i = 0; i < s1.length(); ++i) 13 | { 14 | s1Count[s1[i] - 'a']++; 15 | s2Count[s2[i] - 'a']++; 16 | } 17 | 18 | // Slide the window over s2 19 | for (int i = 0; i < s2.length() - s1.length(); ++i) 20 | { 21 | if (s1Count == s2Count) 22 | return true; 23 | // Update the window 24 | s2Count[s2[i] - 'a']--; 25 | s2Count[s2[i + s1.length()] - 'a']++; 26 | } 27 | 28 | // Check the last window 29 | return s1Count == s2Count; 30 | } 31 | }; -------------------------------------------------------------------------------- /Algorithms/src/567. Permutation in String/Code/solution.go: -------------------------------------------------------------------------------- 1 | func checkInclusion(s1 string, s2 string) bool { 2 | if len(s1) > len(s2) { 3 | return false 4 | } 5 | 6 | s1Count := make([]int, 26) 7 | s2Count := make([]int, 26) 8 | 9 | // Initialize counts for s1 and the first window of s2 10 | for i := 0; i < len(s1); i++ { 11 | s1Count[s1[i]-'a']++ 12 | s2Count[s2[i]-'a']++ 13 | } 14 | 15 | // Slide the window over s2 16 | for i := 0; i < len(s2)-len(s1); i++ { 17 | if match(s1Count, s2Count) { 18 | return true 19 | } 20 | s2Count[s2[i]-'a']-- 21 | s2Count[s2[i+len(s1)]-'a']++ 22 | } 23 | 24 | // Check the last window 25 | return match(s1Count, s2Count) 26 | } 27 | 28 | func match(a, b []int) bool { 29 | for i := 0; i < 26; i++ { 30 | if a[i] != b[i] { 31 | return false 32 | } 33 | } 34 | return true 35 | } -------------------------------------------------------------------------------- /Algorithms/src/567. Permutation in String/Code/solution.js: -------------------------------------------------------------------------------- 1 | var checkInclusion = function (s1, s2) { 2 | if (s1.length > s2.length) return false; 3 | 4 | let s1Count = Array(26).fill(0); 5 | let s2Count = Array(26).fill(0); 6 | 7 | // Initialize counts for s1 and the first window in s2 8 | for (let i = 0; i < s1.length; i++) { 9 | s1Count[s1.charCodeAt(i) - 97]++; 10 | s2Count[s2.charCodeAt(i) - 97]++; 11 | } 12 | 13 | // Slide the window over s2 14 | for (let i = 0; i < s2.length - s1.length; i++) { 15 | if (matches(s1Count, s2Count)) return true; 16 | s2Count[s2.charCodeAt(i) - 97]--; 17 | s2Count[s2.charCodeAt(i + s1.length) - 97]++; 18 | } 19 | 20 | // Check the last window 21 | return matches(s1Count, s2Count); 22 | }; 23 | 24 | function matches(s1Count, s2Count) { 25 | for (let i = 0; i < 26; i++) { 26 | if (s1Count[i] !== s2Count[i]) return false; 27 | } 28 | return true; 29 | } 30 | -------------------------------------------------------------------------------- /Algorithms/src/567. Permutation in String/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkInclusion(self, s1: str, s2: str) -> bool: 3 | if len(s1) > len(s2): 4 | return False 5 | 6 | s1Count = [0] * 26 7 | s2Count = [0] * 26 8 | 9 | # Initialize frequency counts for s1 and the first window in s2 10 | for i in range(len(s1)): 11 | s1Count[ord(s1[i]) - ord('a')] += 1 12 | s2Count[ord(s2[i]) - ord('a')] += 1 13 | 14 | # Slide the window over s2 15 | for i in range(len(s2) - len(s1)): 16 | if s1Count == s2Count: 17 | return True 18 | s2Count[ord(s2[i]) - ord('a')] -= 1 19 | s2Count[ord(s2[i + len(s1)]) - ord('a')] += 1 20 | 21 | # Check the last window 22 | return s1Count == s2Count -------------------------------------------------------------------------------- /Algorithms/src/650. 2 Keys Keyboard/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int minSteps(int n) 5 | { 6 | // Initialize the number of operations required to 0 7 | int operations = 0; 8 | 9 | // Start from 2 and iterate up to n 10 | for (int i = 2; i <= n; i++) 11 | { 12 | // Check if the current value of 'n' is divisible by 'i' 13 | while (n % i == 0) 14 | { 15 | // If divisible, add 'i' to the operations count 16 | operations += i; 17 | 18 | // Reduce 'n' by dividing it by 'i' 19 | n /= i; 20 | } 21 | } 22 | 23 | // Return the total number of operations needed 24 | return operations; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Algorithms/src/650. 2 Keys Keyboard/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minSteps(int n) { 3 | // Initialize the number of operations required to 0 4 | int operations = 0; 5 | 6 | // Start checking for divisors from 2 up to n 7 | for (int i = 2; i <= n; i++) { 8 | // While 'n' is divisible by 'i', keep dividing and count the operations 9 | while (n % i == 0) { 10 | // Add 'i' to the operations count as each division represents 'i' copy-paste 11 | // operations 12 | operations += i; 13 | // Divide 'n' by 'i' to reduce 'n' for further factorization 14 | n /= i; 15 | } 16 | } 17 | 18 | // Return the total number of operations required to achieve 'n' 'A's 19 | return operations; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Algorithms/src/670. Maximum Swap/Code/solution.go: -------------------------------------------------------------------------------- 1 | func maximumSwap(num int) int { 2 | // Convert the number to a string array for manipulation 3 | numStr := []rune(fmt.Sprint(num)) 4 | n := len(numStr) 5 | 6 | // Track the last occurrence of each digit (0-9) 7 | last := make([]int, 10) 8 | for i := 0; i < n; i++ { 9 | last[numStr[i]-'0'] = i 10 | } 11 | 12 | // Traverse the number from left to right 13 | for i := 0; i < n; i++ { 14 | // Check if a larger digit can be found later 15 | for d := 9; d > int(numStr[i]-'0'); d-- { 16 | if last[d] > i { 17 | // Swap the digits and return the new number 18 | numStr[i], numStr[last[d]] = numStr[last[d]], numStr[i] 19 | result, _ := strconv.Atoi(string(numStr)) 20 | return result 21 | } 22 | } 23 | } 24 | 25 | // Return the original number if no swap is done 26 | return num 27 | } -------------------------------------------------------------------------------- /Algorithms/src/670. Maximum Swap/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number} num 3 | * @return {number} 4 | */ 5 | var maximumSwap = function (num) { 6 | // Convert the number to a string array 7 | let numArr = num.toString().split(""); 8 | 9 | // Track the last occurrence of each digit 10 | let last = new Array(10).fill(-1); 11 | for (let i = 0; i < numArr.length; i++) { 12 | last[parseInt(numArr[i])] = i; 13 | } 14 | 15 | // Traverse the digits from left to right 16 | for (let i = 0; i < numArr.length; i++) { 17 | // Check if a larger digit can be swapped later 18 | for (let d = 9; d > numArr[i]; d--) { 19 | if (last[d] > i) { 20 | // Swap the digits and return the new number 21 | [numArr[i], numArr[last[d]]] = [numArr[last[d]], numArr[i]]; 22 | return parseInt(numArr.join("")); 23 | } 24 | } 25 | } 26 | 27 | // Return the original number if no swap was performed 28 | return num; 29 | }; 30 | -------------------------------------------------------------------------------- /Algorithms/src/670. Maximum Swap/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximumSwap(self, num: int) -> int: 3 | # Convert the number to a list of characters for easy manipulation 4 | num_list = list(str(num)) 5 | 6 | # Track the last occurrence of each digit (0-9) 7 | last = {int(d): i for i, d in enumerate(num_list)} 8 | 9 | # Traverse the number from left to right 10 | for i, digit in enumerate(num_list): 11 | # Check for a larger digit to swap 12 | for d in range(9, int(digit), -1): 13 | if last.get(d, -1) > i: 14 | # Swap and return the new number 15 | num_list[i], num_list[last[d]] = num_list[last[d]], num_list[i] 16 | return int(''.join(num_list)) 17 | 18 | # If no swap occurred, return the original number 19 | return num -------------------------------------------------------------------------------- /Algorithms/src/684. Redundant Connection/Code/solution.js: -------------------------------------------------------------------------------- 1 | var findRedundantConnection = function (edges) { 2 | let parent = Array(edges.length + 1) 3 | .fill(0) 4 | .map((_, i) => i); 5 | let rank = Array(edges.length + 1).fill(0); 6 | 7 | function find(node) { 8 | if (parent[node] !== node) parent[node] = find(parent[node]); // Path compression 9 | return parent[node]; 10 | } 11 | 12 | function union(u, v) { 13 | let rootU = find(u), 14 | rootV = find(v); 15 | if (rootU === rootV) return false; 16 | if (rank[rootU] > rank[rootV]) parent[rootV] = rootU; 17 | else if (rank[rootU] < rank[rootV]) parent[rootU] = rootV; 18 | else { 19 | parent[rootV] = rootU; 20 | rank[rootU]++; 21 | } 22 | return true; 23 | } 24 | 25 | for (let [u, v] of edges) { 26 | if (!union(u, v)) return [u, v]; 27 | } 28 | return []; 29 | }; 30 | -------------------------------------------------------------------------------- /Algorithms/src/684. Redundant Connection/Code/solution.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: 5 | parent = list(range(len(edges) + 1)) 6 | rank = [0] * (len(edges) + 1) 7 | 8 | def find(node): 9 | if parent[node] != node: 10 | parent[node] = find(parent[node]) # Path compression 11 | return parent[node] 12 | 13 | def union(u, v): 14 | rootU, rootV = find(u), find(v) 15 | if rootU == rootV: 16 | return False # Cycle detected 17 | if rank[rootU] > rank[rootV]: 18 | parent[rootV] = rootU 19 | elif rank[rootU] < rank[rootV]: 20 | parent[rootU] = rootV 21 | else: 22 | parent[rootV] = rootU 23 | rank[rootU] += 1 24 | return True 25 | 26 | for u, v in edges: 27 | if not union(u, v): 28 | return [u, v] 29 | return [] 30 | -------------------------------------------------------------------------------- /Algorithms/src/731. My Calendar II/Code/solution.js: -------------------------------------------------------------------------------- 1 | var MyCalendarTwo = function () { 2 | this.single = []; // Stores single booked intervals 3 | this.doubleBooked = []; // Stores double booked intervals 4 | }; 5 | 6 | /** 7 | * @param {number} start 8 | * @param {number} end 9 | * @return {boolean} 10 | */ 11 | MyCalendarTwo.prototype.book = function (start, end) { 12 | // Check for triple booking by overlapping with double booked intervals 13 | for (let [s, e] of this.doubleBooked) { 14 | if (Math.max(start, s) < Math.min(end, e)) { 15 | return false; // Triple booking detected 16 | } 17 | } 18 | 19 | // Add overlapping parts to double bookings 20 | for (let [s, e] of this.single) { 21 | if (Math.max(start, s) < Math.min(end, e)) { 22 | this.doubleBooked.push([Math.max(start, s), Math.min(end, e)]); 23 | } 24 | } 25 | 26 | // Add the event to single bookings 27 | this.single.push([start, end]); 28 | return true; 29 | }; 30 | -------------------------------------------------------------------------------- /Algorithms/src/731. My Calendar II/Code/solution.py: -------------------------------------------------------------------------------- 1 | class MyCalendarTwo: 2 | 3 | def __init__(self): 4 | self.single = [] # Stores single booked intervals 5 | self.double_booked = [] # Stores double booked intervals 6 | 7 | def book(self, start: int, end: int) -> bool: 8 | # Check if the event overlaps with any double booking, which would cause a triple booking 9 | for s, e in self.double_booked: 10 | if max(start, s) < min(end, e): 11 | return False # Triple booking found 12 | 13 | # Add the overlapping parts to double bookings 14 | for s, e in self.single: 15 | if max(start, s) < min(end, e): 16 | self.double_booked.append((max(start, s), min(end, e))) 17 | 18 | # Add the event to single bookings 19 | self.single.append((start, end)) 20 | return True -------------------------------------------------------------------------------- /Algorithms/src/796. Rotate String/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | bool rotateString(string s, string goal) 5 | { 6 | // If the lengths differ, s can't be rotated to match goal 7 | if (s.length() != goal.length()) 8 | return false; 9 | 10 | // Concatenate s with itself to cover all possible rotations 11 | string doubled = s + s; 12 | 13 | // Check if goal is a substring of doubled 14 | return doubled.find(goal) != string::npos; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Algorithms/src/796. Rotate String/Code/solution.go: -------------------------------------------------------------------------------- 1 | func rotateString(s string, goal string) bool { 2 | // If lengths differ, they cannot be rotations 3 | if len(s) != len(goal) { 4 | return false 5 | } 6 | 7 | // Concatenate s with itself 8 | doubled := s + s 9 | 10 | // Check if goal is a substring of doubled 11 | return strings.Contains(doubled, goal) 12 | } 13 | -------------------------------------------------------------------------------- /Algorithms/src/796. Rotate String/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean rotateString(String s, String goal) { 3 | // If lengths are different, they cannot be rotations 4 | if (s.length() != goal.length()) 5 | return false; 6 | 7 | // Concatenate s with itself 8 | String doubled = s + s; 9 | 10 | // Check if goal is a substring of doubled 11 | return doubled.contains(goal); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Algorithms/src/796. Rotate String/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @param {string} goal 4 | * @return {boolean} 5 | */ 6 | var rotateString = function (s, goal) { 7 | // If lengths differ, s cannot be rotated to match goal 8 | if (s.length !== goal.length) return false; 9 | 10 | // Concatenate s with itself 11 | let doubled = s + s; 12 | 13 | // Check if goal is a substring of doubled 14 | return doubled.includes(goal); 15 | }; 16 | -------------------------------------------------------------------------------- /Algorithms/src/796. Rotate String/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotateString(self, s: str, goal: str) -> bool: 3 | # If lengths differ, s cannot be rotated to match goal 4 | if len(s) != len(goal): 5 | return False 6 | 7 | # Concatenate s with itself 8 | doubled = s + s 9 | 10 | # Check if goal is a substring of doubled 11 | return goal in doubled 12 | -------------------------------------------------------------------------------- /Algorithms/src/802. Find Eventual Safe States/Code/solution.js: -------------------------------------------------------------------------------- 1 | var eventualSafeNodes = function (graph) { 2 | const n = graph.length; 3 | const reversedGraph = Array.from({ length: n }, () => []); 4 | const inDegree = Array(n).fill(0); 5 | 6 | // Reverse the graph and calculate in-degree 7 | for (let i = 0; i < n; i++) { 8 | for (const neighbor of graph[i]) { 9 | reversedGraph[neighbor].push(i); 10 | inDegree[i]++; 11 | } 12 | } 13 | 14 | // Find all terminal nodes 15 | const queue = []; 16 | for (let i = 0; i < n; i++) { 17 | if (inDegree[i] === 0) queue.push(i); 18 | } 19 | 20 | // Topological sorting to find safe nodes 21 | const safeNodes = []; 22 | while (queue.length > 0) { 23 | const node = queue.shift(); 24 | safeNodes.push(node); 25 | 26 | for (const neighbor of reversedGraph[node]) { 27 | inDegree[neighbor]--; 28 | if (inDegree[neighbor] === 0) queue.push(neighbor); 29 | } 30 | } 31 | 32 | return safeNodes.sort((a, b) => a - b); 33 | }; 34 | -------------------------------------------------------------------------------- /Algorithms/src/862. Shortest Subarray with Sum at Least K/Code/solution.go: -------------------------------------------------------------------------------- 1 | func shortestSubarray(nums []int, k int) int { 2 | n := len(nums) 3 | prefix := make([]int64, n+1) 4 | 5 | // Step 1: Compute prefix sums 6 | for i := 0; i < n; i++ { 7 | prefix[i+1] = prefix[i] + int64(nums[i]) 8 | } 9 | 10 | dq := []int{} 11 | minLength := n + 1 12 | 13 | // Step 2: Process prefix sums 14 | for i := 0; i <= n; i++ { 15 | for len(dq) > 0 && prefix[i]-prefix[dq[0]] >= int64(k) { 16 | if i-dq[0] < minLength { 17 | minLength = i - dq[0] 18 | } 19 | dq = dq[1:] 20 | } 21 | 22 | for len(dq) > 0 && prefix[i] <= prefix[dq[len(dq)-1]] { 23 | dq = dq[:len(dq)-1] 24 | } 25 | 26 | dq = append(dq, i) 27 | } 28 | 29 | if minLength == n+1 { 30 | return -1 31 | } 32 | return minLength 33 | } 34 | -------------------------------------------------------------------------------- /Algorithms/src/862. Shortest Subarray with Sum at Least K/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} k 4 | * @return {number} 5 | */ 6 | var shortestSubarray = function (nums, k) { 7 | const n = nums.length; 8 | const prefix = new Array(n + 1).fill(0); 9 | 10 | // Step 1: Compute prefix sums 11 | for (let i = 0; i < n; i++) { 12 | prefix[i + 1] = prefix[i] + nums[i]; 13 | } 14 | 15 | const deque = []; 16 | let minLength = Infinity; 17 | 18 | // Step 2: Process prefix sums 19 | for (let i = 0; i <= n; i++) { 20 | while (deque.length > 0 && prefix[i] - prefix[deque[0]] >= k) { 21 | minLength = Math.min(minLength, i - deque.shift()); 22 | } 23 | 24 | while (deque.length > 0 && prefix[i] <= prefix[deque[deque.length - 1]]) { 25 | deque.pop(); 26 | } 27 | 28 | deque.push(i); 29 | } 30 | 31 | return minLength === Infinity ? -1 : minLength; 32 | }; 33 | -------------------------------------------------------------------------------- /Algorithms/src/862. Shortest Subarray with Sum at Least K/Code/solution.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | class Solution: 4 | def shortestSubarray(self, nums: List[int], k: int) -> int: 5 | n = len(nums) 6 | prefix = [0] * (n + 1) 7 | 8 | # Step 1: Compute prefix sums 9 | for i in range(n): 10 | prefix[i + 1] = prefix[i] + nums[i] 11 | 12 | dq = deque() 13 | min_length = float('inf') 14 | 15 | # Step 2: Process prefix sums 16 | for i in range(n + 1): 17 | while dq and prefix[i] - prefix[dq[0]] >= k: 18 | min_length = min(min_length, i - dq.popleft()) 19 | 20 | while dq and prefix[i] <= prefix[dq[-1]]: 21 | dq.pop() 22 | 23 | dq.append(i) 24 | 25 | return min_length if min_length != float('inf') else -1 26 | -------------------------------------------------------------------------------- /Algorithms/src/916. Word Subsets/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string[]} words1 3 | * @param {string[]} words2 4 | * @return {string[]} 5 | */ 6 | var wordSubsets = function (words1, words2) { 7 | let maxFreq = new Array(26).fill(0); 8 | 9 | // Precompute the maximum frequency for each character in words2 10 | for (let word of words2) { 11 | let freq = new Array(26).fill(0); 12 | for (let char of word) freq[char.charCodeAt(0) - 97]++; 13 | for (let i = 0; i < 26; i++) { 14 | maxFreq[i] = Math.max(maxFreq[i], freq[i]); 15 | } 16 | } 17 | 18 | let result = []; 19 | // Check each word in words1 20 | for (let word of words1) { 21 | let freq = new Array(26).fill(0); 22 | for (let char of word) freq[char.charCodeAt(0) - 97]++; 23 | let isUniversal = true; 24 | for (let i = 0; i < 26; i++) { 25 | if (freq[i] < maxFreq[i]) { 26 | isUniversal = false; 27 | break; 28 | } 29 | } 30 | if (isUniversal) result.push(word); 31 | } 32 | 33 | return result; 34 | }; 35 | -------------------------------------------------------------------------------- /Algorithms/src/916. Word Subsets/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: 3 | from collections import Counter 4 | 5 | max_freq = Counter() 6 | # Precompute the maximum frequency for each character in words2 7 | for word in words2: 8 | freq = Counter(word) 9 | for char in freq: 10 | max_freq[char] = max(max_freq[char], freq[char]) 11 | 12 | result = [] 13 | # Check each word in words1 14 | for word in words1: 15 | freq = Counter(word) 16 | if all(freq[char] >= max_freq[char] for char in max_freq): 17 | result.append(word) 18 | 19 | return result 20 | -------------------------------------------------------------------------------- /Algorithms/src/962. Maximum Width Ramp/Code/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxWidthRamp(vector& nums) { 4 | int n = nums.size(); 5 | stack s; 6 | 7 | // Step 1: Build a decreasing stack of indices 8 | for (int i = 0; i < n; ++i) { 9 | if (s.empty() || nums[s.top()] > nums[i]) { 10 | s.push(i); 11 | } 12 | } 13 | 14 | int maxWidth = 0; 15 | 16 | // Step 2: Traverse from the end and find maximum width ramp 17 | for (int j = n - 1; j >= 0; --j) { 18 | while (!s.empty() && nums[s.top()] <= nums[j]) { 19 | maxWidth = max(maxWidth, j - s.top()); 20 | s.pop(); 21 | } 22 | } 23 | 24 | return maxWidth; 25 | } 26 | }; -------------------------------------------------------------------------------- /Algorithms/src/962. Maximum Width Ramp/Code/solution.go: -------------------------------------------------------------------------------- 1 | func maxWidthRamp(nums []int) int { 2 | n := len(nums) 3 | stack := []int{} 4 | 5 | // Step 1: Build a decreasing stack of indices 6 | for i := 0; i < n; i++ { 7 | if len(stack) == 0 || nums[stack[len(stack)-1]] > nums[i] { 8 | stack = append(stack, i) 9 | } 10 | } 11 | 12 | maxWidth := 0 13 | 14 | // Step 2: Traverse from the end and find maximum width ramp 15 | for j := n - 1; j >= 0; j-- { 16 | for len(stack) > 0 && nums[stack[len(stack)-1]] <= nums[j] { 17 | i := stack[len(stack)-1] 18 | stack = stack[:len(stack)-1] 19 | if j - i > maxWidth { 20 | maxWidth = j - i 21 | } 22 | } 23 | } 24 | 25 | return maxWidth 26 | } -------------------------------------------------------------------------------- /Algorithms/src/962. Maximum Width Ramp/Code/solution.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxWidthRamp(int[] nums) { 3 | int n = nums.length; 4 | Stack stack = new Stack<>(); 5 | 6 | // Step 1: Build a decreasing stack of indices 7 | for (int i = 0; i < n; ++i) { 8 | if (stack.isEmpty() || nums[stack.peek()] > nums[i]) { 9 | stack.push(i); 10 | } 11 | } 12 | 13 | int maxWidth = 0; 14 | 15 | // Step 2: Traverse from the end and find maximum width ramp 16 | for (int j = n - 1; j >= 0; --j) { 17 | while (!stack.isEmpty() && nums[stack.peek()] <= nums[j]) { 18 | maxWidth = Math.max(maxWidth, j - stack.pop()); 19 | } 20 | } 21 | 22 | return maxWidth; 23 | } 24 | } -------------------------------------------------------------------------------- /Algorithms/src/962. Maximum Width Ramp/Code/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | var maxWidthRamp = function(nums) { 6 | let n = nums.length; 7 | let stack = []; 8 | 9 | // Step 1: Build a decreasing stack of indices 10 | for (let i = 0; i < n; i++) { 11 | if (stack.length === 0 || nums[stack[stack.length - 1]] > nums[i]) { 12 | stack.push(i); 13 | } 14 | } 15 | 16 | let maxWidth = 0; 17 | 18 | // Step 2: Traverse from the end and find maximum width ramp 19 | for (let j = n - 1; j >= 0; j--) { 20 | while (stack.length > 0 && nums[stack[stack.length - 1]] <= nums[j]) { 21 | maxWidth = Math.max(maxWidth, j - stack.pop()); 22 | } 23 | } 24 | 25 | return maxWidth; 26 | }; -------------------------------------------------------------------------------- /Algorithms/src/962. Maximum Width Ramp/Code/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxWidthRamp(self, nums: List[int]) -> int: 3 | n = len(nums) 4 | stack = [] 5 | 6 | # Step 1: Build a decreasing stack of indices 7 | for i in range(n): 8 | if not stack or nums[stack[-1]] > nums[i]: 9 | stack.append(i) 10 | 11 | maxWidth = 0 12 | 13 | # Step 2: Traverse from the end and find maximum width ramp 14 | for j in range(n - 1, -1, -1): 15 | while stack and nums[stack[-1]] <= nums[j]: 16 | maxWidth = max(maxWidth, j - stack.pop()) 17 | 18 | return maxWidth --------------------------------------------------------------------------------