├── Other ├── 2025 │ ├── 509. Fibonacci Number.ts │ ├── 405. Convert a Number to Hexadecimal.cs │ ├── 2206. Divide Array Into Equal Pairs.js │ ├── 1672. Richest Customer Wealth.ts │ ├── 2579. Count Total Number of Colored Cells.ts │ ├── 1952. Three Divisors.ts │ ├── 2418. Sort the People.cs │ ├── 2185. Counting Words With a Given Prefix.ts │ ├── 67. Add Binary.py │ ├── 2469. Convert the Temperature.ts │ ├── Special Array I.py │ ├── 2315. Count Asterisks.ts │ ├── 67. Add Binary.js │ ├── 2942. Find Words Containing Character.cs │ ├── 2652. Sum Multiples.py │ ├── 1910. Remove All Occurrences of a Substring.py │ ├── 1952. Three Divisors.py │ ├── 1979. Find Greatest Common Divisor of Array.py │ ├── 3024. Type of Triangle.cs │ ├── CSharp │ │ ├── 1929. Concatenation of Array.cs │ │ └── 20. Valid Parentheses.cs │ ├── 2894. Divisible and Non-divisible Sums Difference.cs │ ├── 136. Single Number.py │ ├── 1512. Number of Good Pairs.cs │ ├── 2180. Count Integers With Even Digit Sum.py │ ├── 1360. Number of Days Between Two Dates.py │ ├── 1790. Check if One String Swap Can Make Strings Equal.py │ ├── 1281. Subtract the Product and Sum of Digits of an Integer.py │ ├── 2129. Capitalize the Title.ts │ ├── 2161. Partition Array According to Given Pivot.ts │ ├── 1979. Find Greatest Common Divisor of Array.ts │ ├── 2427. Number of Common Factors.py │ ├── 2798. Number of Employees Who Met the Target.cs │ ├── 1920. Build Array from Permutation.cs │ ├── 2460. Apply Operations to an Array.ts │ ├── 2185. Counting Words With a Given Prefix.py │ ├── 1422. Maximum Score After Splitting a String.py │ ├── 2367. Number of Arithmetic Triplets.cs │ ├── 3174. Clear Digits.py │ ├── 1295. Find Numbers with Even Number of Digits.cs │ ├── 3042. Count Prefix and Suffix Pairs I.py │ ├── 1534. Count Good Triplets.cs │ ├── 2460. Apply Operations to an Array.cs │ ├── 704. Binary Search.cs │ ├── 1930. Unique Length-3 Palindromic Subsequences.py │ ├── 3169. Count Days Without Meetings.cs │ ├── 2559. Count Vowel Strings in Ranges.py │ ├── 2594. Minimum Time to Repair Cars.js │ ├── 3467. Transform Array by Parity.cs │ ├── 2401. Longest Nice Subarray.js │ ├── 1980. Find Unique Binary String.ts │ ├── 2270. Number of Ways to Split Array.py │ └── 2381. Shifting Letters II.py ├── #2235 - Add Two Integers.js ├── #1929 - Concatenation of Array.js ├── #2413 - Smallest Even Multiple.js ├── #1816 - Truncate Sentence.js ├── #1920 - Build Array from Permutation.js ├── #2678 - Number of Senior Citizens.js ├── #989 - Add to Array-Form of Integer.js ├── #326 - Power of Three.js ├── #1108 - Defanging an IP Address.js ├── #2496 - Maximum Value of a String in an Array.js ├── #342 - Power of Four.js ├── #349_IntersectionOfTwoArrays.js ├── #3174 - Clear Digits.js ├── Python │ ├── 796. Rotate String.py │ ├── Circular Sentence.py │ ├── 1346. Check If N and Its Double Exist.py │ ├── 2275. Largest Combination With Bitwise AND Greater Than Zero.py │ ├── 389. Find the Difference.py │ ├── 217. Contains Duplicate.py │ ├── Delete Characters to Make Fancy String.py │ ├── 3133. Minimum Array End.py │ ├── 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence.py │ ├── 2109. Adding Spaces to a String.py │ ├── 1760. Minimum Limit of Balls in a Bag.py │ ├── 14. Longest Common Prefix.py │ ├── 1829. Maximum XOR for Each Query.py │ ├── Roman to Integer.py │ ├── 2825. Make String a Subsequence Using Cyclic Increments.py │ ├── 3011. Find if Array Can Be Sorted.py │ ├── 2554. Maximum Number of Integers to Choose From a Range I.py │ ├── 3097. Shortest Subarray With OR at Least K II.py │ ├── 3254. Find the Power of K-Size Subarrays I.py │ ├── 2070. Most Beautiful Item for Each Query.py │ ├── 2337. Move Pieces to Obtain a String.py │ └── 2601. Prime Subtraction Operation.py ├── #1662 - Check If Two String Arrays are Equivalent.js ├── #3110_Score of a String.js ├── #2053 - Kth Distinct String in an Array.js ├── #1460 - Make Two Arrays Equal by Reversing Subarrays.js ├── #3190 - Find Minimum Operations to Make All Elements Divisible by Three.js ├── #3016 - Minimum Number of Pushes to Type Word II.js ├── #2540_MinimumCommonValue.js ├── #412 - Fizz Buzz.js ├── #145 - Binary Tree Postorder Traversal.js ├── #2011 - Final Value of Variable After Performing Operations.js ├── #557 - Reverse Words in a String III.js ├── #590 - N-ary Tree Postorder Traversal.js ├── #2108 - Find First Palindromic String in the Array.js ├── #125 - Valid Palindrome.js ├── #1508 - Range Sum of Sorted Subarray Sums.js ├── #2114 - Maximum Number of Words Found in Sentences.js ├── #120_Triangle.js ├── #840 - Magic Squares In Grid.js ├── #1507 - Reformat Date.js └── #273 - Integer to English Words.js ├── README.md └── JavaScript30 ├── #9_Return Length of Arguments Passed.js ├── #1_Create Hello World Function.js ├── #13_Sleep.js ├── #2_Counter.js ├── #12_Add Two Promises.js ├── #5_Apply Transform Over Each Element in Array.js ├── #8_Function Composition.js ├── #10_Allow One Function Call.js ├── #4_Counter II.js ├── #6_Filter Elements from Array.js ├── #3_To Be Or Not To Be.js ├── #7_Array Reduce Transformation.js ├── #11_Memoize.js └── #14_Timeout Cancellation.js /Other/#2235 - Add Two Integers.js: -------------------------------------------------------------------------------- 1 | var sum = function (num1, num2) { 2 | return num1 + num2; 3 | }; 4 | -------------------------------------------------------------------------------- /Other/#1929 - Concatenation of Array.js: -------------------------------------------------------------------------------- 1 | var getConcatenation = function (nums) { 2 | return [...nums, ...nums]; 3 | }; 4 | -------------------------------------------------------------------------------- /Other/#2413 - Smallest Even Multiple.js: -------------------------------------------------------------------------------- 1 | var smallestEvenMultiple = function (n) { 2 | return n % 2 === 0 ? n : n * 2; 3 | }; 4 | -------------------------------------------------------------------------------- /Other/#1816 - Truncate Sentence.js: -------------------------------------------------------------------------------- 1 | var truncateSentence = function (s, k) { 2 | return s.split(" ").slice(0, k).join(" "); 3 | }; 4 | -------------------------------------------------------------------------------- /Other/#1920 - Build Array from Permutation.js: -------------------------------------------------------------------------------- 1 | var buildArray = function (nums) { 2 | return nums.map((value) => nums[value]); 3 | }; 4 | -------------------------------------------------------------------------------- /Other/2025/509. Fibonacci Number.ts: -------------------------------------------------------------------------------- 1 | function fib(n: number): number { 2 | if (n < 2) return n; 3 | return fib(n - 1) + fib(n - 2); 4 | } 5 | -------------------------------------------------------------------------------- /Other/#2678 - Number of Senior Citizens.js: -------------------------------------------------------------------------------- 1 | var countSeniors = function (details) { 2 | return details.filter((value) => value.slice(11, 13) > 60).length; 3 | }; -------------------------------------------------------------------------------- /Other/#989 - Add to Array-Form of Integer.js: -------------------------------------------------------------------------------- 1 | let addToArrayForm = function (num, k) { 2 | return [...(BigInt(num.join("")) + BigInt(k)).toString()]; 3 | }; 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Leetcode 2 | 3 | --- 4 | 5 | [![Leetcode Stats](https://leetcard.jacoblin.cool/usmonovshohruxmirzo)](https://leetcode.com/usmonovshohruxmirzo) 6 | -------------------------------------------------------------------------------- /Other/#326 - Power of Three.js: -------------------------------------------------------------------------------- 1 | var isPowerOfThree = function (n) { 2 | if (n === 0) return false; 3 | while (n % 3 === 0) n /= 3; 4 | return n === 1; 5 | }; 6 | -------------------------------------------------------------------------------- /Other/2025/405. Convert a Number to Hexadecimal.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public string ToHex(int num) { 3 | return num.ToString("x"); 4 | } 5 | } -------------------------------------------------------------------------------- /Other/2025/2206. Divide Array Into Equal Pairs.js: -------------------------------------------------------------------------------- 1 | const divideArray = (nums) => { 2 | return nums.reduce((a, v) => ((a[v] = a[v] ^ 1), a), []).every((v) => !v); 3 | }; 4 | -------------------------------------------------------------------------------- /Other/#1108 - Defanging an IP Address.js: -------------------------------------------------------------------------------- 1 | var defangIPaddr = function (address) { 2 | return address.split(".").join("[.]"); 3 | }; 4 | console.log(defangIPaddr("1.1.1.1")); 5 | -------------------------------------------------------------------------------- /Other/#2496 - Maximum Value of a String in an Array.js: -------------------------------------------------------------------------------- 1 | var maximumValue = function (strs) { 2 | return Math.max(...strs.map((s) => (Number.isInteger(+s) ? +s : s.length))); 3 | }; 4 | -------------------------------------------------------------------------------- /Other/2025/1672. Richest Customer Wealth.ts: -------------------------------------------------------------------------------- 1 | function maximumWealth(accounts: number[][]): number { 2 | return Math.max(...accounts.map((c) => c.reduce((a, b) => a + b, 0))); 3 | } 4 | -------------------------------------------------------------------------------- /Other/#342 - Power of Four.js: -------------------------------------------------------------------------------- 1 | var isPowerOfFour = function (n) { 2 | if (n === 0) return false; 3 | while (n % 4 === 0) n /= 4; 4 | return n === 1; 5 | }; 6 | console.log(isPowerOfFour(16)); 7 | -------------------------------------------------------------------------------- /Other/#349_IntersectionOfTwoArrays.js: -------------------------------------------------------------------------------- 1 | let intersection = function(nums1, nums2) { 2 | return nums1.reduce((acc,curr) => (nums2.includes(curr) && !acc.includes(curr) ? [...acc, curr] : acc), []) 3 | }; 4 | -------------------------------------------------------------------------------- /Other/#3174 - Clear Digits.js: -------------------------------------------------------------------------------- 1 | var clearDigits = function (s) { 2 | let regex = /[a-zA-z][0-9]/g; 3 | while (regex.test(s)) s = s.replace(regex, ""); 4 | return s; 5 | }; 6 | console.log(clearDigits("ag3")); 7 | -------------------------------------------------------------------------------- /Other/2025/2579. Count Total Number of Colored Cells.ts: -------------------------------------------------------------------------------- 1 | // Formula: C(n) = 2n^2 - 2n + 1 2 | function coloredCells(n: number): number { 3 | return 2 * n ** 2 - 2 * n + 1; 4 | } 5 | console.log(coloredCells(2)); 6 | -------------------------------------------------------------------------------- /Other/Python/796. Rotate String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotateString(self, s: str, goal: str) -> bool: 3 | if len(s) != len(goal): 4 | return False 5 | return goal in s + s 6 | -------------------------------------------------------------------------------- /Other/#1662 - Check If Two String Arrays are Equivalent.js: -------------------------------------------------------------------------------- 1 | var arrayStringsAreEqual = function (word1, word2) { 2 | let w1 = word1.join(""); 3 | let w2 = word2.join(""); 4 | return w1 === w2 ? true : false; 5 | }; 6 | -------------------------------------------------------------------------------- /Other/2025/1952. Three Divisors.ts: -------------------------------------------------------------------------------- 1 | function isThree(n: number): boolean { 2 | let divisors: number = 0; 3 | for (let i = 1; i <= n; i++) if (n % i == 0) divisors++; 4 | return divisors === 3 ? true : false; 5 | } 6 | -------------------------------------------------------------------------------- /Other/2025/2418. Sort the People.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public string[] SortPeople(string[] names, int[] heights) { 3 | Array.Sort(heights, names); 4 | return names.Reverse().ToArray();; 5 | } 6 | } -------------------------------------------------------------------------------- /Other/#3110_Score of a String.js: -------------------------------------------------------------------------------- 1 | var scoreOfString = function (s) { 2 | let sum = 0; 3 | for (let i = 0; i < s.length - 1; i++) { 4 | sum += Math.abs(s.charCodeAt(i) - s.charCodeAt(i + 1)); 5 | } 6 | return sum; 7 | }; 8 | -------------------------------------------------------------------------------- /Other/#2053 - Kth Distinct String in an Array.js: -------------------------------------------------------------------------------- 1 | var kthDistinct = function (arr, k) { 2 | return ( 3 | arr.filter( 4 | (value, index, array) => array.indexOf(value) === array.lastIndexOf(value) 5 | )[k - 1] || "" 6 | ); 7 | }; 8 | -------------------------------------------------------------------------------- /Other/#1460 - Make Two Arrays Equal by Reversing Subarrays.js: -------------------------------------------------------------------------------- 1 | var canBeEqual = function (target, arr) { 2 | let targetArray = target.sort(); 3 | let array = arr.sort(); 4 | return targetArray.every((value, index) => value === array[index]); 5 | }; 6 | -------------------------------------------------------------------------------- /Other/2025/2185. Counting Words With a Given Prefix.ts: -------------------------------------------------------------------------------- 1 | function prefixCount(words: string[], pref: string): number { 2 | let count: number = 0; 3 | for (let i = 0; i < words.length; i++) if (words[i].startsWith(pref)) count++; 4 | return count; 5 | } 6 | -------------------------------------------------------------------------------- /JavaScript30/#9_Return Length of Arguments Passed.js: -------------------------------------------------------------------------------- 1 | // Write a function argumentsLength that returns the count of arguments passed to it. 2 | 3 | let argumentsLength = function (...args) { 4 | return args.length; 5 | }; 6 | console.log(argumentsLength(1, 2, 3)); 7 | -------------------------------------------------------------------------------- /Other/2025/67. Add Binary.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addBinary(self, a: str, b: str) -> str: 3 | return bin(int(a, 2) + int(b, 2))[2:] 4 | 5 | # Test cases 6 | print(Solution().addBinary("11", "1")) # 100 7 | print(Solution().addBinary("1010", "1011")) # 10101 -------------------------------------------------------------------------------- /JavaScript30/#1_Create Hello World Function.js: -------------------------------------------------------------------------------- 1 | // Write a function createHelloWorld. It should return a new function that always returns "Hello World". 2 | 3 | let createHelloWorld = function () { 4 | return function (...args) { 5 | return "Hello World"; 6 | }; 7 | }; 8 | -------------------------------------------------------------------------------- /Other/2025/2469. Convert the Temperature.ts: -------------------------------------------------------------------------------- 1 | function convertTemperature(celsius: number): number[] { 2 | const answer: number[] = [] 3 | const k: number = celsius + 273.15 4 | const f: number = celsius * 1.80 + 32.00 5 | answer.push(k, f) 6 | return answer 7 | }; -------------------------------------------------------------------------------- /Other/2025/Special Array I.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def isArraySpecial(self, nums: List[int]) -> bool: 5 | for i in range(len(nums) - 1): 6 | if nums[i] % 2 == nums[i + 1] % 2: 7 | return False 8 | return True -------------------------------------------------------------------------------- /Other/#3190 - Find Minimum Operations to Make All Elements Divisible by Three.js: -------------------------------------------------------------------------------- 1 | var minimumOperations = function (nums) { 2 | let count = 0; 3 | for (let i = 0; i < nums.length; i++) { 4 | if (nums[i] % 3 !== 0) { 5 | count++; 6 | } 7 | } 8 | return count; 9 | }; 10 | -------------------------------------------------------------------------------- /Other/2025/2315. Count Asterisks.ts: -------------------------------------------------------------------------------- 1 | function countAsterisks(s: string): number { 2 | let count: number = 0; 3 | let flag: boolean = true; 4 | for (const char of s) { 5 | if (flag && char === "*") count++; 6 | if (char === "|") flag = !flag; 7 | } 8 | return count; 9 | } 10 | -------------------------------------------------------------------------------- /Other/2025/67. Add Binary.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} a 3 | * @param {string} b 4 | * @return {string} 5 | */ 6 | var addBinary = function (a, b) { 7 | return (BigInt(`0b${a}`) + BigInt(`0b${b}`)).toString(2); 8 | }; 9 | 10 | // Test cases 11 | console.log(addBinary("11", "1")); 12 | -------------------------------------------------------------------------------- /Other/#3016 - Minimum Number of Pushes to Type Word II.js: -------------------------------------------------------------------------------- 1 | var minimumPushes = function(word) { 2 | let freq = Array(123).fill(0); 3 | for (let i = 0, n = word.length; i < n; i++) freq[word.charCodeAt(i)]++; 4 | return freq.sort((a ,b) => b - a).reduce((acc, f, i) => acc + Math.floor(i / 8 + 1) * f, 0); 5 | }; -------------------------------------------------------------------------------- /Other/#2540_MinimumCommonValue.js: -------------------------------------------------------------------------------- 1 | let getCommon = function (nums1, nums2) { 2 | let i = 0, 3 | j = 0; 4 | 5 | while (i < nums1.length && j < nums2.length) { 6 | if (nums1[i] === nums2[j]) return nums1[i]; 7 | else if (nums1[i] > nums2[j]) j++; 8 | else i++; 9 | } 10 | return -1; 11 | }; 12 | -------------------------------------------------------------------------------- /Other/2025/2942. Find Words Containing Character.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public IList FindWordsContaining(string[] words, char x) { 3 | List answer = new List(); 4 | for (int i = 0; i < words.Length; i++) if (words[i].Contains(x)) answer.Add(i); 5 | return answer; 6 | } 7 | } -------------------------------------------------------------------------------- /Other/#412 - Fizz Buzz.js: -------------------------------------------------------------------------------- 1 | var fizzBuzz = function (n) { 2 | let result = []; 3 | for (let i = 1; i <= n; i++) { 4 | let str = ""; 5 | if (i % 3 === 0) str += "Fizz"; 6 | if (i % 5 === 0) str += "Buzz"; 7 | 8 | if (str === "") str += i; 9 | result.push(str); 10 | } 11 | return result; 12 | }; 13 | -------------------------------------------------------------------------------- /Other/Python/Circular Sentence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isCircularSentence(self, sentence: str) -> bool: 3 | word = sentence.split() 4 | for i in range(len(word) - 1): 5 | if word[i][-1] == word[i + 1][0]: pass 6 | else: return False 7 | return True if word[0][0] == word[-1][-1] else False -------------------------------------------------------------------------------- /Other/2025/2652. Sum Multiples.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sumOfMultiples(self, n: int) -> int: 3 | result = 0 4 | for i in range(1, n + 1): 5 | if i % 3 == 0 or i % 5 == 0 or i % 7 == 0: 6 | result += i 7 | return result 8 | 9 | # Test cases 10 | print(Solution().sumOfMultiples(7)) -------------------------------------------------------------------------------- /Other/2025/1910. Remove All Occurrences of a Substring.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeOccurrences(self, s: str, part: str) -> str: 3 | while part in s: 4 | s = s.replace(part, "", 1) 5 | return s 6 | 7 | print(Solution().removeOccurrences("daabcbaabcbc", "abc")) 8 | print(Solution().removeOccurrences("axxxxyyyyb", "xy")) -------------------------------------------------------------------------------- /Other/Python/1346. Check If N and Its Double Exist.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def checkIfExist(self, arr: List[int]) -> bool: 5 | seen = set() 6 | for num in arr: 7 | if num * 2 in seen or num / 2 in seen: 8 | return True 9 | seen.add(num) 10 | return False -------------------------------------------------------------------------------- /Other/#145 - Binary Tree Postorder Traversal.js: -------------------------------------------------------------------------------- 1 | var postorderTraversal = function (root) { 2 | const result = []; 3 | function treverse(node) { 4 | if (!node) return; 5 | if (node.left) treverse(node.left); 6 | if (node.right) treverse(node.right); 7 | result.push(node.val); 8 | } 9 | treverse(root); 10 | return result; 11 | }; 12 | -------------------------------------------------------------------------------- /Other/#2011 - Final Value of Variable After Performing Operations.js: -------------------------------------------------------------------------------- 1 | var finalValueAfterOperations = function (operations) { 2 | let count = 0; 3 | let i = 0; 4 | while (i < operations.length) { 5 | if (operations[i].includes("+")) { 6 | count++; 7 | } else { 8 | count--; 9 | } 10 | i++; 11 | } 12 | return count; 13 | }; 14 | -------------------------------------------------------------------------------- /Other/2025/1952. Three Divisors.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isThree(self, n: int) -> bool: 3 | divisors = 0 4 | for num in range(1, n + 1): 5 | if n % num == 0: 6 | divisors += 1 7 | return True if divisors == 3 else False 8 | 9 | # Test cases 10 | print(Solution().isThree(2)) 11 | print(Solution().isThree(4)) -------------------------------------------------------------------------------- /Other/Python/2275. Largest Combination With Bitwise AND Greater Than Zero.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | class Solution: 3 | def largestCombination(self, candidates: List[int]) -> int: 4 | answer = 0 5 | for i in range(32): 6 | cnt = sum(1 for candidate in candidates if candidate & (1 << i)) 7 | answer = max(answer, cnt) 8 | return answer -------------------------------------------------------------------------------- /Other/2025/1979. Find Greatest Common Divisor of Array.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | import math 3 | 4 | class Solution: 5 | def findGCD(self, nums: List[int]) -> int: 6 | return math.gcd(min(nums), max(nums)) 7 | 8 | # Test cases 9 | print(Solution().findGCD([2,5,6,9,10])) 10 | print(Solution().findGCD([7,5,6,8,3])) 11 | print(Solution().findGCD([3,3])) 12 | -------------------------------------------------------------------------------- /Other/2025/3024. Type of Triangle.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public string TriangleType(int[] nums) { 3 | Array.Sort(nums); 4 | if (nums[0] + nums[1] <= nums[2]) return "none"; 5 | else if (nums[0] == nums[2]) return "equilateral"; 6 | else if (nums[0] == nums[1] || nums[1] == nums[2]) return "isosceles"; 7 | else return "scalene"; 8 | } 9 | } -------------------------------------------------------------------------------- /Other/2025/CSharp/1929. Concatenation of Array.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] GetConcatenation(int[] nums) { 3 | int n = nums.Length; 4 | int[] ans = new int[2 * n]; 5 | 6 | for (int i = 0; i < n; i++) { 7 | ans[i] = nums[i]; 8 | ans[i + n] = nums[i]; 9 | } 10 | 11 | return ans; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Other/Python/389. Find the Difference.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findTheDifference(self, s: str, t: str) -> str: 3 | for n in t: 4 | if n in s: 5 | s = s.replace(n, "", 1) 6 | else: 7 | return n 8 | 9 | # Test 10 | solution = Solution() 11 | print(solution.findTheDifference("abcd", "abcde")) 12 | 13 | -------------------------------------------------------------------------------- /JavaScript30/#13_Sleep.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a positive integer millis, write an asynchronous function that sleeps for millis milliseconds. It can resolve any value. 3 | */ 4 | 5 | 6 | async function sleep(millis) { 7 | return new Promise(resolve => setTimeout(resolve, millis)) 8 | } 9 | 10 | /** 11 | * let t = Date.now() 12 | * sleep(100).then(() => console.log(Date.now() - t)) // 100 13 | */ -------------------------------------------------------------------------------- /Other/2025/2894. Divisible and Non-divisible Sums Difference.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int DifferenceOfSums(int n, int m) { 3 | int ans = 0; 4 | for (int i = 1; i <= n; i++) { 5 | if (i % m == 0) { 6 | ans -= i; 7 | } else { 8 | ans += i; 9 | } 10 | } 11 | return ans; 12 | } 13 | } -------------------------------------------------------------------------------- /Other/2025/136. Single Number.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def singleNumber(self, nums: List[int]) -> int: 5 | single = 0 6 | for i in range(len(nums)): 7 | single ^= nums[i] 8 | return single 9 | 10 | # Test cases 11 | print(Solution().singleNumber([2,2,1])) 12 | print(Solution().singleNumber([4,1,2,1,2])) 13 | print(Solution().singleNumber([1])) -------------------------------------------------------------------------------- /Other/Python/217. Contains Duplicate.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def containsDuplicate(self, nums: List[int]) -> bool: 5 | return len(set(nums)) != len(nums) 6 | 7 | solution = Solution() 8 | 9 | # Test Cases 10 | print(solution.containsDuplicate([1,2,3,1])) 11 | print(solution.containsDuplicate([1,2,3,4])) 12 | print(solution.containsDuplicate([1,1,1,3,3,4,3,2,4,2])) -------------------------------------------------------------------------------- /Other/2025/1512. Number of Good Pairs.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int NumIdenticalPairs(int[] nums) { 3 | int count = 0; 4 | for (int i = 0; i < nums.Length; i++) 5 | { 6 | for (int j = i + 1; j < nums.Length; j++) 7 | { 8 | if (nums[i] == nums[j] && i < j) count++; 9 | } 10 | } 11 | return count; 12 | } 13 | } -------------------------------------------------------------------------------- /JavaScript30/#2_Counter.js: -------------------------------------------------------------------------------- 1 | // Given an integer n, return a counter function. This counter function initially returns n and then returns 1 more than the previous value every subsequent time it is called (n, n + 1, n + 2, etc). 2 | 3 | let createCounter = function (n) { 4 | return function () { 5 | return n++; 6 | }; 7 | }; 8 | 9 | const counter = createCounter(10); 10 | counter(); 11 | counter(); 12 | counter(); 13 | -------------------------------------------------------------------------------- /Other/Python/Delete Characters to Make Fancy String.py: -------------------------------------------------------------------------------- 1 | def makeFancyString(s: str) -> str: 2 | answer = s[0] 3 | cnt = 1 4 | for i in range(1, len(s)): 5 | if s[i] == answer[-1]: 6 | cnt += 1 7 | if cnt < 3: 8 | answer += s[i] 9 | else: 10 | cnt = 1 11 | answer += s[i] 12 | return answer 13 | 14 | print(makeFancyString("leetcode")) -------------------------------------------------------------------------------- /Other/2025/2180. Count Integers With Even Digit Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countEven(self, num: int) -> int: 3 | count = 0 4 | for i in range(1, num + 1): 5 | digit_sum = sum(int(d) for d in str(i)) 6 | if digit_sum % 2 == 0: 7 | count += 1 8 | return count 9 | 10 | # Test cases 11 | print(Solution().countEven(4)) 12 | print(Solution().countEven(30)) -------------------------------------------------------------------------------- /Other/#557 - Reverse Words in a String III.js: -------------------------------------------------------------------------------- 1 | var reverseWords = function (s) { 2 | let strToArr = s.split(" "); 3 | let result = []; 4 | for (let i = 0; i < strToArr.length; i++) { 5 | result.push(strToArr[i].split("").reverse().join("")); 6 | } 7 | return result.join(" "); 8 | }; 9 | 10 | let testCase1 = "Let's take LeetCode contest"; 11 | let testCase2 = "Mr Ding"; 12 | 13 | console.log(reverseWords(testCase1)); 14 | -------------------------------------------------------------------------------- /Other/2025/1360. Number of Days Between Two Dates.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | class Solution: 4 | def daysBetweenDates(self, date1: str, date2: str) -> int: 5 | d1 = datetime.strptime(date1, "%Y-%m-%d") 6 | d2 = datetime.strptime(date2, "%Y-%m-%d") 7 | return abs((d1 - d2).days) 8 | 9 | # Test Cases 10 | solution = Solution() 11 | print(solution.daysBetweenDates("2019-06-29", "2019-06-30")) -------------------------------------------------------------------------------- /Other/#590 - N-ary Tree Postorder Traversal.js: -------------------------------------------------------------------------------- 1 | var postorder = function (root) { 2 | let results = []; 3 | 4 | function treverse(currentNode) { 5 | if (currentNode) { 6 | if (currentNode.children) { 7 | for (let node of currentNode.children) { 8 | treverse(node); 9 | } 10 | } 11 | results.push(currentNode.val); 12 | } 13 | } 14 | treverse(root); 15 | return results; 16 | }; 17 | -------------------------------------------------------------------------------- /Other/Python/3133. Minimum Array End.py: -------------------------------------------------------------------------------- 1 | # Should Review 2 | class Solution: 3 | def minEnd(self, n: int, x: int) -> int: 4 | result = x 5 | remaining = n - 1 6 | position = 1 7 | 8 | while remaining: 9 | if not (x & position): 10 | result |= (remaining & 1) * position 11 | remaining >>= 1 12 | position <<= 1 13 | 14 | return result -------------------------------------------------------------------------------- /Other/2025/1790. Check if One String Swap Can Make Strings Equal.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def areAlmostEqual(self, s1: str, s2: str) -> bool: 3 | if s1 == s2: return True 4 | diff = [i for i in range(len(s1)) if s1[i] != s2[i]] 5 | return len(diff) == 2 and s1[diff[0]] == s2[diff[1]] and s1[diff[1]] == s2[diff[0]] 6 | 7 | # Test 8 | s1 = "bank" 9 | s2 = "kanb" 10 | print(Solution().areAlmostEqual(s1, s2)) -------------------------------------------------------------------------------- /Other/2025/1281. Subtract the Product and Sum of Digits of an Integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subtractProductAndSum(self, n: int) -> int: 3 | nums = list(map(int, str(n))) 4 | a = 1 5 | b = 0 6 | 7 | for num in nums: 8 | a *= num 9 | 10 | for num in nums: 11 | b += num 12 | 13 | return a - b 14 | 15 | 16 | print(Solution().subtractProductAndSum(234)) -------------------------------------------------------------------------------- /Other/2025/2129. Capitalize the Title.ts: -------------------------------------------------------------------------------- 1 | function capitalizeTitle(title: string): string { 2 | const words: string[] = title.toLowerCase().split(" "); 3 | for (let i = 0; i < words.length; i++) { 4 | if (words[i].length >= 3) { 5 | words[i] = words[i][0].toUpperCase() + words[i].slice(1); 6 | } 7 | } 8 | return words.join(" "); 9 | } 10 | 11 | // Test cases 12 | console.log(capitalizeTitle("capiTalIze t1He titLe of")); 13 | -------------------------------------------------------------------------------- /Other/2025/2161. Partition Array According to Given Pivot.ts: -------------------------------------------------------------------------------- 1 | function pivotArray(nums: number[], pivot: number): number[] { 2 | const less: number[] = []; 3 | const equal: number[] = []; 4 | const greater: number[] = []; 5 | 6 | for (const num of nums) { 7 | if (num < pivot) less.push(num); 8 | else if (num == pivot) equal.push(num); 9 | else greater.push(num); 10 | } 11 | 12 | return [...less, ...equal, ...greater]; 13 | } 14 | -------------------------------------------------------------------------------- /Other/Python/1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPrefixOfWord(self, sentence: str, searchWord: str) -> int: 3 | words = sentence.split(" ") 4 | for i, word in enumerate(words): 5 | if word.startswith(searchWord): 6 | return i + 1 7 | return -1 8 | 9 | answer = Solution() 10 | print(answer.isPrefixOfWord("i love eating burger", "burg")) 11 | -------------------------------------------------------------------------------- /Other/Python/2109. Adding Spaces to a String.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | def addSpaces(s: str, spaces: List[int]) -> str: 4 | words = [] 5 | space_index = 0 6 | 7 | for i in range(len(s)): 8 | if space_index < len(spaces) and i == spaces[space_index]: 9 | words.append(" ") 10 | space_index += 1 11 | 12 | words.append(s[i]) 13 | 14 | # test 15 | print(addSpaces("LeetcodeHelpsMeLearn", [8,13,15])) -------------------------------------------------------------------------------- /Other/#2108 - Find First Palindromic String in the Array.js: -------------------------------------------------------------------------------- 1 | var firstPalindrome = function (words) { 2 | let result = []; 3 | let fPalindrome = []; 4 | 5 | for (let i = 0; i < words.length; i++) { 6 | let rwords = words[i].split("").reverse().join(""); 7 | result.push(rwords); 8 | 9 | if (result[i] === words[i]) { 10 | fPalindrome.push(result[i]); 11 | return fPalindrome[0]; 12 | } 13 | } 14 | 15 | return ""; 16 | }; 17 | -------------------------------------------------------------------------------- /Other/2025/1979. Find Greatest Common Divisor of Array.ts: -------------------------------------------------------------------------------- 1 | function findGCD(nums: number[]): number { 2 | let a: number = Math.min(...nums); 3 | let b: number = Math.max(...nums); 4 | 5 | const euclidean = (a: number, b: number) => { 6 | if (b === 0) return a; 7 | return euclidean(b, a % b); 8 | }; 9 | 10 | return euclidean(b, a); 11 | } 12 | 13 | // Test cases 14 | console.log(findGCD([7, 5, 6, 8, 3])); 15 | console.log(findGCD([3, 3])); 16 | -------------------------------------------------------------------------------- /Other/2025/2427. Number of Common Factors.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def commonFactors(self, a: int, b: int) -> int: 3 | common_factors = 0 4 | min_value = min(a, b) 5 | 6 | for i in range(1, min_value + 1): 7 | if a % i == 0 and b % i == 0: 8 | common_factors += 1 9 | 10 | return common_factors 11 | 12 | # Test cases 13 | print(Solution().commonFactors(12, 6)) 14 | print(Solution().commonFactors(35, 25)) -------------------------------------------------------------------------------- /Other/2025/2798. Number of Employees Who Met the Target.cs: -------------------------------------------------------------------------------- 1 | // public class Solution { 2 | // public int NumberOfEmployeesWhoMetTarget(int[] hours, int target) { 3 | // return hours.Count(x => x >= target); 4 | // } 5 | // } 6 | 7 | public class Solution { 8 | public int NumberOfEmployeesWhoMetTarget(int[] hours, int target) { 9 | int count = 0; 10 | foreach (int hour in hours) if (hour >= target) count++; 11 | return count; 12 | } 13 | } -------------------------------------------------------------------------------- /Other/2025/1920. Build Array from Permutation.cs: -------------------------------------------------------------------------------- 1 | // public class Solution { 2 | // public int[] BuildArray(int[] nums) { 3 | // return nums.Select(i => nums[i]).ToArray(); 4 | // } 5 | // } 6 | 7 | public class Solution { 8 | public int[] BuildArray(int[] nums) { 9 | int[] result = new int[nums.Length]; 10 | for (int i = 0; i < nums.Length; i++) { 11 | result[i] = nums[nums[i]]; 12 | } 13 | return result; 14 | } 15 | } -------------------------------------------------------------------------------- /Other/2025/2460. Apply Operations to an Array.ts: -------------------------------------------------------------------------------- 1 | function applyOperations(nums: number[]): number[] { 2 | for (let i = 0; i < nums.length - 1; i++) { 3 | if (nums[i] === nums[i + 1]) { 4 | nums[i] *= 2; 5 | nums[i + 1] = 0; 6 | } 7 | } 8 | 9 | let index: number = 0; 10 | for (let i = 0; i < nums.length; i++) { 11 | if (nums[i] !== 0) { 12 | [nums[index], nums[i]] = [nums[i], nums[index]]; 13 | index++; 14 | } 15 | } 16 | 17 | return nums; 18 | } 19 | -------------------------------------------------------------------------------- /Other/#125 - Valid Palindrome.js: -------------------------------------------------------------------------------- 1 | var isPalindrome = function (s) { 2 | let word = s.replace(/[^a-z0-9]/gi, "").toLowerCase(); 3 | let rword = word.split("").reverse().join(""); 4 | if (word === rword) return true; 5 | else return false; 6 | }; 7 | 8 | let testCase1 = "A man, a plan, a canal: Panama"; 9 | let testCase2 = "race a car"; 10 | let testCase3 = " "; 11 | 12 | console.log(isPalindrome(testCase1)); 13 | console.log(isPalindrome(testCase2)); 14 | console.log(isPalindrome(testCase3)); 15 | -------------------------------------------------------------------------------- /JavaScript30/#12_Add Two Promises.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given two promises promise1 and promise2, return a new promise. promise1 and promise2 will both resolve with a number. 3 | The returned promise should resolve with the sum of the two numbers. 4 | */ 5 | 6 | var addTwoPromises = async function (promise1, promise2) { 7 | const [val1, val2] = await Promise.all([promise1, promise2]); 8 | return val1 + val2; 9 | }; 10 | 11 | addTwoPromises(Promise.resolve(2), Promise.resolve(2)).then(console.log); // 4 12 | -------------------------------------------------------------------------------- /Other/2025/2185. Counting Words With a Given Prefix.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def prefixCount(self, words: List[str], pref: str) -> int: 5 | count = 0 6 | for i in range(len(words)): 7 | if words[i].startswith(pref): 8 | count += 1 9 | return count 10 | 11 | # Test cases 12 | print(Solution().prefixCount(["pay","attention","practice","attend"], "at")) 13 | print(Solution().prefixCount(["leetcode","win","loops","success"], "code")) -------------------------------------------------------------------------------- /Other/Python/1760. Minimum Limit of Balls in a Bag.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def minimumSize(self, nums: List[int], maxOperations: int) -> int: 5 | low, high = 1, max(nums) 6 | while low < high: 7 | mid = (low + high) // 2 8 | if sum((n - 1) // mid for n in nums) <= maxOperations: 9 | high = mid 10 | else: 11 | low = mid + 1 12 | return high 13 | 14 | solution = Solution() 15 | print(solution.minimumSize([9], 3)) -------------------------------------------------------------------------------- /Other/#1508 - Range Sum of Sorted Subarray Sums.js: -------------------------------------------------------------------------------- 1 | var rangeSum = function (nums, n, left, right) { 2 | const MOD = 1000000007; 3 | let arr = []; 4 | 5 | for (let i = 0; i < n; i++) { 6 | for (let j = i; j < n; j++) { 7 | let sum = nums.slice(i, j + 1).reduce((acc, total) => (acc += total), 0); 8 | arr.push(sum); 9 | } 10 | } 11 | arr = arr.sort((a, b) => a - b); 12 | let res = arr 13 | .slice(left - 1, right) 14 | .reduce((acc, total) => (acc += total), 0); 15 | 16 | return res % MOD; 17 | }; 18 | -------------------------------------------------------------------------------- /Other/Python/14. Longest Common Prefix.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def longestCommonPrefix(self, strs: List[str]) -> str: 5 | if not strs: return "" 6 | 7 | prefix = strs[0] 8 | 9 | for s in strs[1:]: 10 | while not s.startswith(prefix): 11 | prefix = prefix[:-1] 12 | if not prefix: return "" 13 | 14 | return prefix 15 | 16 | solution = Solution() 17 | print(solution.longestCommonPrefix(["flower","flow","flight"])) -------------------------------------------------------------------------------- /Other/#2114 - Maximum Number of Words Found in Sentences.js: -------------------------------------------------------------------------------- 1 | var mostWordsFound = function (sentences) { 2 | const maxWords = []; 3 | for (let i = 0; i < sentences.length; i++) { 4 | maxWords.push(sentences[i].split(" ").length); 5 | } 6 | return Math.max(...maxWords); 7 | }; 8 | let testCase1 = [ 9 | "alice and bob love leetcode", 10 | "i think so too", 11 | "this is great thanks very much", 12 | ]; 13 | let testCase2 = ["please wait", "continue to fight", "continue to win"]; 14 | 15 | console.log(mostWordsFound(testCase1)); 16 | -------------------------------------------------------------------------------- /Other/Python/1829. Maximum XOR for Each Query.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]: 5 | n = len(nums) 6 | xorr = nums[0] 7 | max_xor = (1 << maximumBit) - 1 8 | 9 | for i in range(1, n): 10 | xorr ^= nums[i] 11 | 12 | ans = [] 13 | for i in range(n): 14 | ans.append(xorr ^ max_xor) 15 | xorr ^= nums[n - 1 - i] 16 | 17 | return ans 18 | 19 | -------------------------------------------------------------------------------- /Other/Python/Roman to Integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def romanToInt(self, s: str) -> int: 3 | m = { 4 | 'I': 1, 5 | 'V': 5, 6 | 'X': 10, 7 | 'L': 50, 8 | 'C': 100, 9 | 'D': 500, 10 | 'M': 1000 11 | } 12 | 13 | answer = 0 14 | 15 | for i in range(len(s)): 16 | if i < len(s) - 1 and m[s[i]] < m[s[i + 1]]: 17 | answer -= m[s[i]] 18 | else: 19 | answer += m[s[i]] 20 | return answer 21 | -------------------------------------------------------------------------------- /Other/#120_Triangle.js: -------------------------------------------------------------------------------- 1 | let Triangle = function (triangle) { 2 | for (let i = 0; i < triangle.length; i++) { 3 | for (let j = 0; j < triangle[i].length; j++) { 4 | if (triangle[i - 1]) 5 | triangle[i][j] = 6 | Math.min( 7 | ...[triangle?.[i - 1]?.[j - 1], triangle?.[i - 1]?.[j]].filter( 8 | (num) => num !== undefined 9 | ) 10 | ) + triangle[i][j]; 11 | } 12 | } 13 | return Math.min(...triangle[triangle.length - 1]); 14 | }; 15 | 16 | console.log(Triangle([[2], [3, 4], [6, 5, 7], [4, 1, 8, 3]])); 17 | -------------------------------------------------------------------------------- /Other/Python/2825. Make String a Subsequence Using Cyclic Increments.py: -------------------------------------------------------------------------------- 1 | def canMakeSubsequence(str1: str, str2: str) -> bool: 2 | index, n = 0, len(str2) 3 | print(index, n) 4 | 5 | for char in str1: 6 | if index == n: 7 | break 8 | 9 | if char == str2[index]: 10 | index += 1 11 | continue 12 | 13 | next_char = "a" if char == "z" else chr(ord(char) + 1) 14 | if next_char == str2[index]: 15 | index += 1 16 | 17 | return index == n 18 | 19 | print(canMakeSubsequence("abc", "ad")) -------------------------------------------------------------------------------- /JavaScript30/#5_Apply Transform Over Each Element in Array.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer array arr and a mapping function fn, return a new array with a transformation applied to each element. 3 | 4 | The returned array should be created such that returnedArray[i] = fn(arr[i], i). 5 | 6 | Please solve it without the built-in Array.map method. 7 | */ 8 | 9 | var map = function (arr, fn) { 10 | let array = []; 11 | for (let i = 0; i < arr.length; i++) { 12 | array[i] = fn(arr[i], i); 13 | } 14 | return array; 15 | }; 16 | 17 | console.log(map([10, 20, 30], (n, i) => n + i)); 18 | -------------------------------------------------------------------------------- /Other/Python/3011. Find if Array Can Be Sorted.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def canSortArray(self, nums: List[int]) -> bool: 5 | pmax = cmin = cmax = pcnt = 0 6 | for v in nums: 7 | ccnt = v.bit_count() 8 | if pcnt == ccnt: 9 | cmin = min(cmin, v) 10 | cmax = max(cmax, v) 11 | elif cmin < pmax: 12 | return False 13 | else: 14 | pmax = cmax 15 | cmin = cmax = v 16 | pcnt = ccnt 17 | return cmin >= pmax -------------------------------------------------------------------------------- /Other/Python/2554. Maximum Number of Integers to Choose From a Range I.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def maxCount(self, banned: List[int], n: int, maxSum: int) -> int: 5 | banned_set = set(banned) 6 | total_sum = 0 7 | count = 0 8 | 9 | for i in range(1, n + 1): 10 | if i in banned_set: 11 | continue 12 | total_sum += i 13 | if total_sum > maxSum: 14 | break 15 | count += 1 16 | 17 | return count 18 | 19 | solution = Solution() 20 | 21 | print(solution.maxCount([1, 6, 5], 5, 6)) -------------------------------------------------------------------------------- /Other/2025/1422. Maximum Score After Splitting a String.py: -------------------------------------------------------------------------------- 1 | from numpy import inf 2 | 3 | class Solution: 4 | def maxScore(self, s: str) -> int: 5 | ones = 0 6 | zeros = 0 7 | best = -inf 8 | 9 | for i in range(len(s) - 1): 10 | if s[i] == "1": ones += 1 11 | else: zeros += 1 12 | 13 | best = max(best, zeros - ones) 14 | 15 | if s[-1] == "1": ones += 1 16 | 17 | return best + ones 18 | 19 | # Test cases 20 | solution = Solution() 21 | print(solution.maxScore("011101")) 22 | print(solution.maxScore("00111")) 23 | print(solution.maxScore("1111")) -------------------------------------------------------------------------------- /Other/2025/2367. Number of Arithmetic Triplets.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int ArithmeticTriplets(int[] nums, int diff) { 3 | int count = 0; 4 | for (int i = 0; i < nums.Length; i++) 5 | { 6 | for (int j = i + 1; j < nums.Length; j++) 7 | { 8 | for (int k = j + 1; k < nums.Length; k++) 9 | { 10 | if (nums[j] - nums[i] == diff && nums[k] - nums[j] == diff) 11 | { 12 | count++; 13 | } 14 | } 15 | } 16 | } 17 | return count; 18 | } 19 | } -------------------------------------------------------------------------------- /Other/2025/3174. Clear Digits.py: -------------------------------------------------------------------------------- 1 | import re 2 | # Solution with re 3 | # class Solution: 4 | # def clearDigits(self, s: str) -> str: 5 | # regex = re.compile(r"[a-zA-Z][0-9]") 6 | # while regex.search(s): 7 | # s = regex.sub("", s) 8 | # return s 9 | 10 | # Solution without re 11 | class Solution: 12 | def clearDigits(self, s: str) -> str: 13 | answer = [] 14 | for char in s: 15 | if(char.isalpha()): 16 | answer.append(char) 17 | else: 18 | answer.pop() 19 | return ''.join(answer) 20 | 21 | print(Solution().clearDigits("a8f")) -------------------------------------------------------------------------------- /Other/Python/3097. Shortest Subarray With OR at Least K II.py: -------------------------------------------------------------------------------- 1 | # Should review 2 | 3 | from typing import List 4 | from math import inf 5 | 6 | class Solution: 7 | def minimumSubarrayLength(self, nums: List[int], k: int) -> int: 8 | answer = inf 9 | d = {} 10 | 11 | for i, x in enumerate(nums): 12 | d = {or_val | x: left for or_val, left in d.items()} 13 | d[x] = i 14 | 15 | for or_val, left in d.items(): 16 | if or_val >= k: 17 | answer = min(answer, i - left + 1) 18 | 19 | return answer if answer < inf else -1 20 | -------------------------------------------------------------------------------- /Other/2025/1295. Find Numbers with Even Number of Digits.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int FindNumbers(int[] nums) { 3 | int count = 0; 4 | for (int i = 0; i < nums.Length; i++) 5 | { 6 | int num = Math.Abs(nums[i]).ToString().Length; 7 | if ((num & 1) == 0) 8 | { 9 | count++; 10 | } 11 | } 12 | return count; 13 | } 14 | } 15 | 16 | // LINQ Version 17 | // public class Solution { 18 | // public int FindNumbers(int[] nums) { 19 | // return nums.Count(n => (Math.Abs(n).ToString().Length & 1) == 0); 20 | // } 21 | // } -------------------------------------------------------------------------------- /Other/2025/3042. Count Prefix and Suffix Pairs I.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def countPrefixSuffixPairs(self, words: List[str]) -> int: 5 | n = len(words) 6 | count = 0 7 | for i in range(n): 8 | for j in range(i + 1, n): 9 | if words[j].startswith(words[i]) and words[j].endswith(words[i]): 10 | count += 1 11 | return count 12 | 13 | # Test cases 14 | print(Solution().countPrefixSuffixPairs(["a","aba","ababa","aa"])) 15 | print(Solution().countPrefixSuffixPairs(["pa","papa","ma","mama"])) 16 | print(Solution().countPrefixSuffixPairs(["abab","ab"])) -------------------------------------------------------------------------------- /Other/Python/3254. Find the Power of K-Size Subarrays I.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def resultsArray(self, nums: List[int], k: int) -> List[int]: 5 | res = [] 6 | l = 0 7 | consec_cnt = 1 8 | for r in range(len(nums)): 9 | if r > 0 and nums[r - 1] + 1 == nums[r]: 10 | consec_cnt += 1 11 | 12 | if r - l + 1 > k: 13 | if nums[l] + 1 == nums[l + 1]: 14 | consec_cnt -= 1 15 | l += 1 16 | 17 | if r - l + 1 == k: 18 | res.append(nums[r] if consec_cnt == k else -1) 19 | 20 | return res -------------------------------------------------------------------------------- /Other/2025/1534. Count Good Triplets.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int CountGoodTriplets(int[] arr, int a, int b, int c) { 3 | int x = 0; 4 | for (int i = 0; i < arr.Length; i++) { 5 | for (int j = i + 1; j < arr.Length; j++) { 6 | for (int k = j + 1; k < arr.Length; k++) { 7 | if ( 8 | Math.Abs(arr[i] - arr[j]) <= a && 9 | Math.Abs(arr[j] - arr[k]) <= b && 10 | Math.Abs(arr[i] - arr[k]) <= c 11 | ) { 12 | x++; 13 | } 14 | } 15 | } 16 | } 17 | return x; 18 | } 19 | } -------------------------------------------------------------------------------- /Other/2025/2460. Apply Operations to an Array.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] ApplyOperations(int[] nums) { 3 | for (int i = 0; i < nums.Length - 1; i++) { 4 | if (nums[i] == nums[i + 1]) { 5 | nums[i] *= 2; 6 | nums[i + 1] = 0; 7 | } 8 | } 9 | 10 | int index = 0; 11 | for (int i = 0; i < nums.Length; i++) { 12 | if (nums[i] != 0) { 13 | int temp = nums[index]; 14 | nums[index] = nums[i]; 15 | nums[i] = temp; 16 | index++; 17 | } 18 | } 19 | 20 | return nums; 21 | } 22 | } -------------------------------------------------------------------------------- /Other/2025/CSharp/20. Valid Parentheses.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public bool IsValid(string s) { 3 | Stack stack = new Stack(); 4 | 5 | foreach (char c in s) 6 | { 7 | if (c == '(' || c == '{' || c == '[') stack.Push(c); 8 | else 9 | { 10 | if (stack.Count == 0) return false; 11 | char top = stack.Pop(); 12 | if (c == ')' && top != '(') return false; 13 | if (c == '}' && top != '{') return false; 14 | if (c == ']' && top != '[') return false; 15 | } 16 | } 17 | 18 | return stack.Count == 0; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /JavaScript30/#8_Function Composition.js: -------------------------------------------------------------------------------- 1 | /** 2 | Given an array of functions [f1, f2, f3, ..., fn], return a new function fn that is the function composition of the array of functions. 3 | 4 | The function composition of [f(x), g(x), h(x)] is fn(x) = f(g(h(x))). 5 | 6 | The function composition of an empty list of functions is the identity function f(x) = x. 7 | 8 | You may assume each function in the array accepts one integer as input and returns one integer as output. 9 | */ 10 | 11 | let compose = function (functions) { 12 | return (n) => functions.reduceRight((acc, f) => f(acc), n); 13 | }; 14 | 15 | const fn = compose([(n) => n + 1, (n) => 2 * n, (n) => n + 5]); 16 | console.log(fn(4)); 17 | -------------------------------------------------------------------------------- /Other/2025/704. Binary Search.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int Search(int[] nums, int target) { 3 | int left = 0; 4 | int right = nums.Length - 1; 5 | 6 | while (left <= right) 7 | { 8 | int mid = (left + right) / 2; 9 | 10 | if (nums[mid] == target) 11 | { 12 | return mid; 13 | } 14 | else if (nums[mid] < target) 15 | { 16 | left = mid + 1; 17 | } 18 | else 19 | { 20 | right = mid - 1; 21 | } 22 | } 23 | 24 | return -1; 25 | } 26 | } 27 | 28 | 29 | // nums = [-1,0,3,5,9,12] 30 | // targer = 9 -------------------------------------------------------------------------------- /Other/#840 - Magic Squares In Grid.js: -------------------------------------------------------------------------------- 1 | var numMagicSquaresInside = (g, p, q, s = 0) => ( 2 | g.forEach( 3 | (r, i) => ( 4 | (p = g[i + 1]), 5 | (q = g[i - 1]), 6 | p && 7 | q && 8 | r.forEach( 9 | (c, j) => 10 | c == 5 && 11 | p[j] % 5 && 12 | r[j - 1] % 5 && 13 | q[j + 1] % 5 && 14 | p[j] + q[j] == 10 && 15 | r[j - 1] + r[j + 1] == 10 && 16 | p[j - 1] + q[j + 1] == 10 && 17 | p[j + 1] + q[j - 1] == 10 && 18 | p[j - 1] + p[j] + p[j + 1] == 15 && 19 | p[j - 1] + r[j - 1] + q[j - 1] == 15 && 20 | ++s 21 | ) 22 | ) 23 | ), 24 | s 25 | ); 26 | -------------------------------------------------------------------------------- /JavaScript30/#10_Allow One Function Call.js: -------------------------------------------------------------------------------- 1 | /** 2 | Given a function fn, return a new function that is identical to the original function except that it ensures fn is called at most once. 3 | 4 | The first time the returned function is called, it should return the same result as fn. 5 | Every subsequent time it is called, it should return undefined. 6 | 7 | */ 8 | 9 | let once = function (fn) { 10 | let called = false; 11 | return function (...args) { 12 | if (!called) { 13 | called = true; 14 | return fn(...args); 15 | } 16 | }; 17 | }; 18 | 19 | let fn = (a, b, c) => a + b + c; 20 | let onceFn = once(fn); 21 | console.log(onceFn(1, 2, 3)); // 6 22 | console.log(onceFn(5, 5, 5)); // undefined 23 | -------------------------------------------------------------------------------- /Other/Python/2070. Most Beautiful Item for Each Query.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]: 5 | sorted_items = sorted(items, key = lambda x: x[1], reverse = True) 6 | answer = [] 7 | 8 | for query in queries: 9 | for item in sorted_items: 10 | if item[0] <= query: 11 | answer.append(item[1]) 12 | break 13 | else: 14 | answer.append(0) 15 | return answer 16 | 17 | # solution = Solution() 18 | # print(solution.maximumBeauty( 19 | # [[1,2], [3,2], [2,4], [5,6], [3,5]], 20 | # [1, 2, 3, 4, 5, 6] 21 | # )) -------------------------------------------------------------------------------- /Other/2025/1930. Unique Length-3 Palindromic Subsequences.py: -------------------------------------------------------------------------------- 1 | # Should Review 2 | class Solution: 3 | def countPalindromicSubsequence(self, s: str) -> int: 4 | letters = set(s) 5 | count = 0 6 | 7 | for letter in letters: 8 | i, j = s.index(letter), s.rindex(letter) 9 | between = set() 10 | 11 | for k in range(i + 1, j): 12 | between.add(s[k]) 13 | print(between) 14 | 15 | count += len(between) 16 | 17 | return count 18 | # Test Cases 19 | solution = Solution() 20 | print(solution.countPalindromicSubsequence("aabca")) 21 | print(solution.countPalindromicSubsequence("abc")) 22 | print(solution.countPalindromicSubsequence("bbcbaba")) -------------------------------------------------------------------------------- /JavaScript30/#4_Counter II.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function createCounter. It should accept an initial integer init. It should return an object with three functions. 3 | 4 | The three functions are: 5 | 6 | increment() increases the current value by 1 and then returns it. 7 | decrement() reduces the current value by 1 and then returns it. 8 | reset() sets the current value to init and then returns it. 9 | 10 | */ 11 | 12 | let createCounter = function (init) { 13 | let value = init; 14 | 15 | return { 16 | increment: () => ++value, 17 | decrement: () => --value, 18 | reset: () => (value = init), 19 | }; 20 | }; 21 | 22 | /** 23 | * const counter = createCounter(5) 24 | * counter.increment(); // 6 25 | * counter.reset(); // 5 26 | * counter.decrement(); // 4 27 | */ 28 | -------------------------------------------------------------------------------- /Other/2025/3169. Count Days Without Meetings.cs: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int CountDays(int days, int[][] meetings) { 3 | Array.Sort(meetings, (a, b) => a[0].CompareTo(b[0])); 4 | 5 | int totalCovered = 0; 6 | int start = meetings[0][0]; 7 | int end = meetings[0][1]; 8 | 9 | for (int i = 1; i < meetings.Length; i++) { 10 | if (end >= meetings[i][0]) { 11 | end = Math.Max(end, meetings[i][1]); 12 | } else { 13 | totalCovered += end - start + 1; 14 | start = meetings[i][0]; 15 | end = meetings[i][1]; 16 | } 17 | } 18 | 19 | totalCovered += end - start + 1; 20 | 21 | return days - totalCovered; 22 | } 23 | } -------------------------------------------------------------------------------- /Other/#1507 - Reformat Date.js: -------------------------------------------------------------------------------- 1 | var reformatDate = function (date) { 2 | let result; 3 | const months = [ 4 | "January", 5 | "February", 6 | "March", 7 | "April", 8 | "May", 9 | "June", 10 | "July", 11 | "August", 12 | "September", 13 | "October", 14 | "November", 15 | "December", 16 | ]; 17 | 18 | function withZero(n) { 19 | if (n < 10) n = "0" + n; 20 | return n; 21 | } 22 | 23 | for (let i = 0; i < months.length; i++) { 24 | let d = date.split(" ")[0].replace(/[a-zA-Z]/g, ""); 25 | let m = date.split(" ")[1]; 26 | let y = date.split(" ")[2]; 27 | if (months[i].substring(0, 3) === m) { 28 | result = `${withZero(d)} ${withZero(i + 1)} ${y}`; 29 | } 30 | } 31 | return result.split(" ").reverse().join("-"); 32 | }; 33 | -------------------------------------------------------------------------------- /Other/2025/2559. Count Vowel Strings in Ranges.py: -------------------------------------------------------------------------------- 1 | # Should Review 2 | 3 | from typing import List 4 | 5 | class Solution: 6 | def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]: 7 | n = len(words) 8 | prefix = [0] * (n + 1) 9 | vowels = {"a", "e", "i", "o", "u"} 10 | 11 | for i in range(n): 12 | prefix[i + 1] = prefix[i] 13 | if words[i][0] in vowels and words[i][-1] in vowels: 14 | prefix[i + 1] += 1 15 | 16 | result = [] 17 | for query in queries: 18 | result.append(prefix[query[1] + 1] - prefix[query[0]]) 19 | 20 | return result 21 | 22 | # Test cases 23 | solution = Solution() 24 | print(solution.vowelStrings(["aba","bcb","ece","aa","e"], [[0,2],[1,4],[1,1]])) -------------------------------------------------------------------------------- /Other/2025/2594. Minimum Time to Repair Cars.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} ranks 3 | * @param {number} cars 4 | * @return {number} 5 | */ 6 | var repairCars = function (ranks, cars) { 7 | let left = 1; 8 | let right = Math.min(...ranks) * cars * cars; // 100 9 | 10 | const canRepairAll = (time) => { 11 | let totalCarRepaired = 0; 12 | for (rank of ranks) { 13 | totalCarRepaired += Math.floor(Math.sqrt(time / rank)); 14 | if (totalCarRepaired >= cars) return true; 15 | } 16 | return false; 17 | }; 18 | 19 | while (left < right) { 20 | let mid = Math.floor((left + right) / 2); 21 | if (canRepairAll(mid)) right = mid; 22 | else left = mid + 1; 23 | } 24 | 25 | return left; 26 | }; 27 | 28 | // test case 29 | console.log(repairCars([4, 2, 3, 1], 10)); 30 | -------------------------------------------------------------------------------- /JavaScript30/#6_Filter Elements from Array.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer array arr and a filtering function fn, return a filtered array filteredArr. 3 | 4 | The fn function takes one or two arguments: 5 | 6 | arr[i] - number from the arr 7 | i - index of arr[i] 8 | 9 | filteredArr should only contain the elements from the arr for which the expression fn(arr[i], i) evaluates to a truthy value. A truthy value is a value where Boolean(value) returns true. 10 | 11 | Please solve it without the built-in Array.filter method. 12 | */ 13 | 14 | const filter = (array, callback) => { 15 | const filteredArray = []; 16 | for (let i = 0; i < array.length; i++) { 17 | if (callback(array[i], i, array)) { 18 | filteredArray.push(array[i]); 19 | } 20 | } 21 | return filteredArray; 22 | }; 23 | 24 | let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]; 25 | console.log(filter(numbers, (value) => value <= 5)); 26 | -------------------------------------------------------------------------------- /Other/Python/2337. Move Pieces to Obtain a String.py: -------------------------------------------------------------------------------- 1 | # Should Review 2 | 3 | def canChange(start: str, target: str) -> bool: 4 | if start == target: 5 | return True 6 | waitL = 0 7 | waitR = 0 8 | 9 | for curr, goal in zip(start, target): 10 | print(curr, goal) 11 | if curr == "R": 12 | if waitL > 0: return False 13 | waitR += 1 14 | if goal == "L": 15 | if waitR > 0: return False 16 | waitL += 1 17 | if goal == "R": 18 | if waitR == 0: return False 19 | waitR -= 1 20 | if curr == "L": 21 | if waitL == 0: return False 22 | waitL -= 1 23 | return waitL == 0 and waitR == 0 24 | 25 | # Test cases 26 | # print(list(zip("abc", "123", "#$%"))) 27 | 28 | print(canChange("_L__R__R_", "L______RR")) 29 | print(canChange("R_L_", "__LR")) 30 | print(canChange("_R", "R_")) -------------------------------------------------------------------------------- /Other/2025/3467. Transform Array by Parity.cs: -------------------------------------------------------------------------------- 1 | // public class Solution { 2 | // public int[] TransformArray(int[] nums) { 3 | // List answer = new List(); 4 | // for (int i = 0; i < nums.Length; i++) 5 | // { 6 | // if ((nums[i] & 1) == 1) answer.Add(1); 7 | // else answer.Add(0); 8 | // } 9 | // return answer.OrderBy(x => x).ToArray(); 10 | // } 11 | // } 12 | 13 | // public class Solution { 14 | // public int[] TransformArray(int[] nums) { 15 | // List answer = new List(); 16 | // for (int i = 0; i < nums.Length; i++) answer.Add((nums[i] & 1) == 1 ? 1 : 0); 17 | // return answer.OrderBy(x => x).ToArray(); 18 | // } 19 | // } 20 | 21 | public class Solution { 22 | public int[] TransformArray(int[] nums) { 23 | return nums.Select(n => (n & 1) == 1 ? 1 : 0).OrderBy(x => x).ToArray(); 24 | } 25 | } -------------------------------------------------------------------------------- /JavaScript30/#3_To Be Or Not To Be.js: -------------------------------------------------------------------------------- 1 | /* 2 | Write a function expect that helps developers test their code. It should take in any value val and return an object with the following two functions. 3 | 4 | toBe(val) accepts another value and returns true if the two values === each other. If they are not equal, it should throw an error "Not Equal". 5 | notToBe(val) accepts another value and returns true if the two values !== each other. If they are equal, it should throw an error "Equal". 6 | 7 | */ 8 | 9 | let expect = function (val) { 10 | return { 11 | toBe: (val2) => { 12 | if (val !== val2) throw new Error("Not Equal"); 13 | else return true; 14 | }, 15 | notToBe: (val2) => { 16 | if (val === val2) throw new Error("Equal"); 17 | else return true; 18 | }, 19 | }; 20 | }; 21 | 22 | /** 23 | * expect(5).toBe(5); // true 24 | * expect(5).notToBe(5); // throws "Equal" 25 | */ 26 | -------------------------------------------------------------------------------- /Other/2025/2401. Longest Nice Subarray.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @return {number} 4 | */ 5 | // var longestNiceSubarray = function (nums) { 6 | // let left = 0; 7 | // let bits = new Set(); 8 | // let max = 0; 9 | // for (let right = 0; right < nums.length; right++) { 10 | // while ([...bits].some((num) => num & nums[right])) { 11 | // bits.delete(nums[left]); 12 | // left++; 13 | // } 14 | // bits.add(nums[right]); 15 | // max = Math.max(max, right - left + 1); 16 | // } 17 | // return max; 18 | // }; 19 | 20 | var longestNiceSubarray = function (nums) { 21 | let l = 0, 22 | bitmask = 0, 23 | max = 0; 24 | for (let r = 0; r < nums.length; r++) { 25 | while (bitmask & nums[r]) bitmask ^= nums[l++]; 26 | bitmask |= nums[r]; 27 | max = Math.max(max, r - l + 1); 28 | } 29 | return max; 30 | }; 31 | 32 | console.log(longestNiceSubarray([1, 3, 8, 48, 10])); 33 | -------------------------------------------------------------------------------- /JavaScript30/#7_Array Reduce Transformation.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer array nums, a reducer function fn, and an initial value init, return the final result obtained by executing the fn function on each element of the array, sequentially, passing in the return value from the calculation on the preceding element. 3 | 4 | This result is achieved through the following operations: val = fn(init, nums[0]), val = fn(val, nums[1]), val = fn(val, nums[2]), ... until every element in the array has been processed. The ultimate value of val is then returned. 5 | 6 | If the length of the array is 0, the function should return init. 7 | 8 | Please solve it without using the built-in Array.reduce method. 9 | */ 10 | 11 | let reduce = function (nums, fn, init) { 12 | let val = init; 13 | for (let i = 0; i < nums.length; i++) { 14 | val = fn(val, nums[i]); 15 | } 16 | return val; 17 | }; 18 | 19 | console.log(reduce([1, 2, 3, 4, 5], (acc, curr) => acc + curr, 0)); 20 | -------------------------------------------------------------------------------- /Other/2025/1980. Find Unique Binary String.ts: -------------------------------------------------------------------------------- 1 | // Solution 1 2 | // function findDifferentBinaryString(nums: string[]): string { 3 | // const answer: string[] = []; 4 | // for (let i = 0; i < nums.length; i++) { 5 | // if (nums[i][i] == "0") answer.push("1"); 6 | // else answer.push("0"); 7 | // } 8 | // return answer.join(""); 9 | // } 10 | 11 | // Solution 2 12 | // function findDifferentBinaryString(nums: string[]): string { 13 | // let answer = ""; 14 | // for (let i = 0; i < nums.length; i++) { 15 | // answer += nums[i][i] === "0" ? "1" : "0"; 16 | // } 17 | // return answer; 18 | // } 19 | 20 | // Solution 3 21 | function findDifferentBinaryString(nums: string[]): string { 22 | return nums.map((num, i) => (num[i] === "0" ? "1" : "0")).join(""); 23 | } 24 | 25 | // Test Cases 26 | console.log(findDifferentBinaryString(["01", "10"])); 27 | console.log(findDifferentBinaryString(["00", "01"])); 28 | console.log(findDifferentBinaryString(["111", "011", "001"])); 29 | -------------------------------------------------------------------------------- /Other/Python/2601. Prime Subtraction Operation.py: -------------------------------------------------------------------------------- 1 | # Should Review 2 | 3 | from typing import List 4 | 5 | class Solution: 6 | def primeSubOperation(self, nums: List[int]) -> bool: 7 | def getMaxElement(nums): 8 | return max(nums) 9 | 10 | maxElement = getMaxElement(nums) 11 | sieve = [True] * (maxElement + 1) 12 | sieve[1] = False 13 | 14 | for i in range(2, int((maxElement + 1) ** 0.5) + 1): 15 | if sieve[i]: 16 | for j in range(i + i, maxElement + 1, i): 17 | sieve[j] = False 18 | 19 | currValue = 1 20 | i = 0 21 | while i < len(nums): 22 | difference = nums[i] - currValue 23 | 24 | if difference < 0: return False 25 | 26 | if sieve[difference] == True or difference == 0: 27 | i += 1 28 | currValue += 1 29 | else: 30 | currValue += 1 31 | 32 | return True -------------------------------------------------------------------------------- /JavaScript30/#11_Memoize.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a function fn, return a memoized version of that function. 3 | 4 | A memoized function is a function that will never be called twice with the same inputs. Instead it will return a cached value. 5 | 6 | You can assume there are 3 possible input functions: sum, fib, and factorial. 7 | 8 | sum accepts two integers a and b and returns a + b. 9 | fib accepts a single integer n and returns 1 if n <= 1 or fib(n - 1) + fib(n - 2) otherwise. 10 | factorial accepts a single integer n and returns 1 if n <= 1 or factorial(n - 1) * n otherwise. 11 | 12 | */ 13 | 14 | function memoize(fn) { 15 | let map = {}; 16 | return function (...args) { 17 | const s = args.toString(); 18 | if (s in map) { 19 | return map[s]; 20 | } else { 21 | let res = fn(...args); 22 | map[s] = res; 23 | return res; 24 | } 25 | }; 26 | } 27 | 28 | let callCount = 0; 29 | const memoizedFn = memoize(function (a, b) { 30 | callCount += 1; 31 | return a + b; 32 | }); 33 | memoizedFn(2, 3); // 5 34 | memoizedFn(2, 3); // 5 35 | console.log(callCount); // 1 36 | -------------------------------------------------------------------------------- /Other/2025/2270. Number of Ways to Split Array.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def waysToSplitArray(self, nums: List[int]) -> int: 5 | total_sum = sum(nums) 6 | left_sum = 0 7 | valid_splits = 0 8 | print(total_sum) 9 | 10 | for i in range(len(nums) - 1): 11 | left_sum += nums[i] 12 | right_sum = total_sum - left_sum 13 | if left_sum >= right_sum: 14 | valid_splits += 1 15 | 16 | return valid_splits 17 | 18 | # Test Cases 19 | solution = Solution() 20 | print(solution.waysToSplitArray([10, 4, -8, 7])) 21 | # print(solution.waysToSplitArray([2, 3, 1, 0])) 22 | 23 | 24 | # Solution 2: Prefix Sum Array 25 | class Solution: 26 | def waysToSplitArray(self, nums: list[int]) -> int: 27 | n = len(nums) 28 | prefix_sum = [0] * n 29 | prefix_sum[0] = nums[0] 30 | 31 | for i in range(1, n): 32 | prefix_sum[i] = prefix_sum[i - 1] + nums[i] 33 | 34 | count = sum(1 for i in range(n - 1) if prefix_sum[i] >= prefix_sum[-1] - prefix_sum[i]) 35 | 36 | return count -------------------------------------------------------------------------------- /JavaScript30/#14_Timeout Cancellation.js: -------------------------------------------------------------------------------- 1 | /* 2 | Given a function fn, an array of arguments args, and a timeout t in milliseconds, return a cancel function cancelFn. 3 | 4 | After a delay of cancelTimeMs, the returned cancel function cancelFn will be invoked. 5 | 6 | setTimeout(cancelFn, cancelTimeMs) 7 | 8 | Initially, the execution of the function fn should be delayed by t milliseconds. 9 | 10 | If, before the delay of t milliseconds, the function cancelFn is invoked, it should cancel the delayed execution of fn. Otherwise, if cancelFn is not invoked within the specified delay t, fn should be executed with the provided args as arguments. 11 | */ 12 | 13 | var cancellable = function (fn, args, t) { 14 | const timeoutHandle = setTimeout(() => fn(...args), t); 15 | return () => clearTimeout(timeoutHandle); 16 | }; 17 | 18 | /** 19 | * const result = []; 20 | * 21 | * const fn = (x) => x * 5; 22 | * const args = [2], t = 20, cancelTimeMs = 50; 23 | * 24 | * const start = performance.now(); 25 | * 26 | * const log = (...argsArr) => { 27 | * const diff = Math.floor(performance.now() - start); 28 | * result.push({"time": diff, "returned": fn(...argsArr)}); 29 | * } 30 | * 31 | * const cancel = cancellable(log, args, t); 32 | * 33 | * const maxT = Math.max(t, cancelTimeMs); 34 | * 35 | * setTimeout(cancel, cancelTimeMs); 36 | * 37 | * setTimeout(() => { 38 | * console.log(result); // [{"time":20,"returned":10}] 39 | * }, maxT + 15) 40 | */ 41 | -------------------------------------------------------------------------------- /Other/2025/2381. Shifting Letters II.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | class Solution: 4 | def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str: 5 | n = len(s) 6 | shift_diff = [0] * (n + 1) 7 | 8 | for shift in shifts: 9 | start, end, direction = shift 10 | 11 | if direction == 1: 12 | shift_diff[start] += 1 13 | if end + 1 < n: 14 | shift_diff[end + 1] -= 1 15 | else: 16 | shift_diff[start] -= 1 17 | if end + 1 < n: 18 | shift_diff[end + 1] += 1 19 | 20 | shift = 0 21 | s_list = list(s) 22 | for i in range(n): 23 | shift += shift_diff[i] 24 | current_char = s_list[i] 25 | new_char = chr((ord(current_char) - ord("a") + shift) % 26 + ord("a")) 26 | """ 27 | 1. ord("a") = 97 28 | 2. ord("a") - ord("a") = 97 - 97 = 0 29 | 3. 0 + 1 = 1 (we shift forward by 1). 30 | 4. (1) % 26 = 1 (no wrapping needed). 31 | 5. 1 + ord("a") = 1 + 97 = 98. 32 | 6. chr(98) = "b". 33 | So, "a" shifted forward by 1 becomes "b". 34 | """ 35 | s_list[i] = new_char 36 | 37 | return "".join(s_list) 38 | 39 | # Test cases 40 | print(Solution().shiftingLetters("abc", [[0,1,0],[1,2,1],[0,2,1]])) 41 | print(Solution().shiftingLetters("dztz", [[0,0,0],[1,1,1]])) -------------------------------------------------------------------------------- /Other/#273 - Integer to English Words.js: -------------------------------------------------------------------------------- 1 | var numberToWords = function (num) { 2 | if (num === 0) { 3 | return "Zero"; 4 | } 5 | 6 | if (num <= 20) { 7 | return translations.get(num); 8 | } 9 | 10 | let result = []; 11 | 12 | for (let [value, translation] of translations) { 13 | const times = Math.floor(num / value); 14 | 15 | if (times === 0) { 16 | continue; 17 | } 18 | 19 | num -= times * value; 20 | 21 | if (times === 1 && value >= 100) { 22 | result.push("One", translation); 23 | continue; 24 | } 25 | 26 | if (times === 1) { 27 | result.push(translation); 28 | continue; 29 | } 30 | 31 | result.push(numberToWords(times), translation); 32 | } 33 | 34 | return result.join(" "); 35 | }; 36 | 37 | const translations = new Map([ 38 | [1000000000, "Billion"], 39 | [1000000, "Million"], 40 | [1000, "Thousand"], 41 | [100, "Hundred"], 42 | [90, "Ninety"], 43 | [80, "Eighty"], 44 | [70, "Seventy"], 45 | [60, "Sixty"], 46 | [50, "Fifty"], 47 | [40, "Forty"], 48 | [30, "Thirty"], 49 | [20, "Twenty"], 50 | [19, "Nineteen"], 51 | [18, "Eighteen"], 52 | [17, "Seventeen"], 53 | [16, "Sixteen"], 54 | [15, "Fifteen"], 55 | [14, "Fourteen"], 56 | [13, "Thirteen"], 57 | [12, "Twelve"], 58 | [11, "Eleven"], 59 | [10, "Ten"], 60 | [9, "Nine"], 61 | [8, "Eight"], 62 | [7, "Seven"], 63 | [6, "Six"], 64 | [5, "Five"], 65 | [4, "Four"], 66 | [3, "Three"], 67 | [2, "Two"], 68 | [1, "One"], 69 | ]); 70 | --------------------------------------------------------------------------------