├── 001-500 ├── 206.py ├── 292.py ├── 476.py ├── 191.py ├── 263.py ├── 326.py ├── 172.py ├── 338.py ├── 190.py ├── 342.py ├── 014.py ├── 055.py ├── 122.py ├── 55.py ├── 119.py ├── 205.py ├── 001.py ├── 058.py ├── 492.py ├── 448.py ├── 451.py ├── 045.py ├── 198.py ├── 349.py ├── 080.py ├── 455.py ├── 268.py ├── 344.py ├── 392.py ├── 078.py ├── 048.py ├── 452.py ├── 036.py ├── 121.py ├── 071.py ├── 162.py ├── 125.py ├── 167.py ├── 461.py ├── 070.py ├── 300.py ├── 219.py ├── 050.py ├── 128.py ├── 056.py ├── 151.py ├── 077.py ├── 104.py ├── 441.py ├── 011.py ├── 022.py ├── 209.py ├── 234.py ├── 412.py ├── 046.py ├── 134.py ├── 275.py ├── 278.py ├── 90.py ├── 090.py ├── 160.py ├── 003.py ├── 009.py ├── 013.py ├── 215.py ├── 020.py ├── 026.py ├── 083.py ├── 027.py ├── 189.py ├── 028.py ├── 383.py ├── 389.py ├── 171.py ├── 228.py ├── 350.py ├── 226.py ├── 446.py ├── 035.py ├── 202.py ├── 053.py ├── 118.py ├── 135.py ├── 367.py ├── 258.py ├── 024.py ├── 073.py ├── 017.py ├── 203.py ├── 230.py ├── 033.py ├── 098.py ├── 404.py ├── 016.py ├── 049.py ├── 105.py ├── 106.py ├── 405.py ├── 100.py ├── 108.py ├── 112.py ├── 034.py ├── 110.py ├── 225.py ├── 222.py ├── 021.py ├── 155.py ├── 232.py ├── 257.py ├── 238.py ├── 145.py ├── 002.py ├── 005.py ├── 168.py ├── 494.py ├── 242.py ├── 141.py ├── 217.py ├── 054.py ├── 142.py ├── 148.py ├── 059.py ├── 200.py ├── 042.py ├── 169.py ├── 088.py ├── 150.py ├── 004.py ├── 433.py ├── 062.py ├── 072.py ├── 229.py ├── 097.py ├── 322.py ├── 120.py ├── 146.py ├── 067.py ├── 063.py ├── 064.py ├── 015.py ├── 019.py └── 380.py ├── 1001-1500 ├── 1025.py ├── 1356.py ├── 1491.py ├── 1207.py ├── 1374.py ├── 1309.py ├── 1486.py ├── 1137.py ├── 1281.py ├── 1323.py ├── 1342.py ├── 1221.py ├── 1480.py ├── 1492.py ├── 1071.py ├── 1047.py ├── 1394.py ├── 1331.py ├── 1436.py ├── 1389.py ├── 1470.py ├── 1313.py ├── 1347.py ├── 1002.py ├── 1291.py ├── 1365.py ├── 1464.py ├── 1370.py ├── 1239.py ├── 1431.py ├── 1108.py ├── 1304.py ├── 1379.py ├── 1235.py ├── 1457.py ├── 1290.py ├── 1022.py ├── 1325.py ├── 1074.py ├── 1115.py ├── 1472.py ├── 1302.py ├── 1026.py ├── 1381.py ├── 1143.py └── 1114.py ├── 1501-2000 ├── 1689.py ├── 1551.py ├── 1929.py ├── 1816.py ├── 1859.py ├── 1641.py ├── 1913.py ├── 1662.py ├── 1646.py ├── 1920.py ├── 1732.py ├── 1614.py ├── 1844.py ├── 1941.py ├── 1720.py ├── 1768.py ├── 1791.py ├── 1572.py ├── 2000.py ├── 1748.py ├── 1828.py ├── 1822.py ├── 1672.py ├── 1678.py ├── 1657.py ├── 1603.py ├── 1656.py ├── 1528.py ├── 1721.py ├── 1544.py ├── 1704.py ├── 1971.py └── 1512.py ├── 2001-2500 ├── 2396.py ├── 2220.py ├── 2053.py ├── 2235.py ├── 2469.py ├── 2215.py ├── 2351.py ├── 2433.py ├── 2089.py ├── 2037.py ├── 2125.py ├── 2390.py ├── 2011.py ├── 2367.py ├── 2439.py ├── 2221.py ├── 2160.py ├── 2169.py ├── 2148.py ├── 2236.py ├── 2185.py ├── 2278.py ├── 2413.py ├── 2485.py ├── 2103.py ├── 2225.py ├── 2404.py ├── 2325.py ├── 2255.py ├── 2418.py ├── 2315.py ├── 2006.py ├── 2424.py ├── 2497.py ├── 2331.py ├── 2442.py ├── 2405.py ├── 2283.py ├── 2114.py ├── 2341.py ├── 2500.py ├── 2181.py └── 2385.py ├── 501-1000 ├── 509.py ├── 557.py ├── 771.py ├── 594.py ├── 561.py ├── 680.py ├── 637.py ├── 709.py ├── 704.py ├── 645.py ├── 832.py ├── 643.py ├── 739.py ├── 629.py ├── 682.py ├── 797.py ├── 559.py ├── 907.py ├── 868.py ├── 693.py ├── 933.py ├── 997.py ├── 918.py ├── 944.py ├── 896.py ├── 931.py ├── 844.py ├── 876.py ├── 589.py ├── 841.py ├── 705.py ├── 804.py ├── 700.py ├── 563.py ├── 938.py ├── 543.py ├── 617.py ├── 658.py ├── 530.py ├── 599.py ├── 606.py ├── 567.py ├── 989.py ├── 909.py ├── 872.py └── 576.py ├── 2501-3000 ├── 2864.py ├── 2652.py ├── 2678.py ├── 2942.py ├── 2520.py ├── 2506.py ├── 2529.py ├── 2894.py ├── 2586.py ├── 2744.py ├── 2544.py ├── 2870.py ├── 2535.py ├── 2903.py ├── 2859.py ├── 2574.py ├── 2610.py ├── 2807.py ├── 2966.py ├── 2824.py └── 2816.py └── README.md /001-500/206.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /001-500/292.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canWinNim(self, n: int) -> bool: 3 | return n%4!=0 4 | -------------------------------------------------------------------------------- /1001-1500/1025.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def divisorGame(self, n: int) -> bool: 3 | return n%2==0 4 | -------------------------------------------------------------------------------- /1501-2000/1689.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minPartitions(self, n: str) -> int: 3 | return int(max(n)) 4 | -------------------------------------------------------------------------------- /2001-2500/2396.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isStrictlyPalindromic(self, n: int) -> bool: 3 | return False 4 | -------------------------------------------------------------------------------- /1501-2000/1551.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minOperations(self, n: int) -> int: 3 | return n*n >> 2 4 | 5 | -------------------------------------------------------------------------------- /001-500/476.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findComplement(self, num: int) -> int: 3 | return ((1 << num.bit_length())-1) ^ num 4 | -------------------------------------------------------------------------------- /2001-2500/2220.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minBitFlips(self, start: int, goal: int) -> int: 3 | return bin(start^goal).count("1") 4 | -------------------------------------------------------------------------------- /1001-1500/1356.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortByBits(self, arr: List[int]) -> List[int]: 3 | arr.sort(key= lambda x: (bin(x).count("1"),x)) 4 | return arr 5 | -------------------------------------------------------------------------------- /1001-1500/1491.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def average(self, salary: List[int]) -> float: 3 | s = sum(salary) - max(salary) - min(salary) 4 | return s/(len(salary)-2) 5 | -------------------------------------------------------------------------------- /501-1000/509.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fib(self, n: int) -> int: 3 | a,b=0,1 4 | for _ in range(n-1): 5 | a,b=b,a+b 6 | return b if n!=0 else 0 7 | -------------------------------------------------------------------------------- /501-1000/557.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseWords(self, s: str) -> str: 3 | l = s.split(" ") 4 | l = [word[::-1] for word in l] 5 | return " ".join(l) 6 | -------------------------------------------------------------------------------- /001-500/191.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hammingWeight(self, n: int) -> int: 3 | c = 0 4 | while n: 5 | c += 1 6 | n &= (n-1) 7 | return c 8 | -------------------------------------------------------------------------------- /001-500/263.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isUgly(self, n: int) -> bool: 3 | for x in 2,3,5: 4 | while n and n%x==0: 5 | n/=x 6 | return n==1 7 | -------------------------------------------------------------------------------- /001-500/326.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPowerOfThree(self, n: int) -> bool: 3 | while n>1: 4 | if (n%3!=0): return False 5 | n /= 3 6 | return n==1 7 | -------------------------------------------------------------------------------- /1001-1500/1207.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def uniqueOccurrences(self, arr: List[int]) -> bool: 3 | c = Counter(arr) 4 | return len(c.values())==len(set(c.values())) 5 | 6 | -------------------------------------------------------------------------------- /1001-1500/1374.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generateTheString(self, n: int) -> str: 3 | if n%2==0: 4 | return "a"*(n-1) + "b" 5 | else: 6 | return "a"*n 7 | -------------------------------------------------------------------------------- /2001-2500/2053.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kthDistinct(self, arr: List[str], k: int) -> str: 3 | d = [x for x in arr if arr.count(x)==1] 4 | return "" if k>len(d) else d[k-1] 5 | -------------------------------------------------------------------------------- /1001-1500/1309.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def freqAlphabets(self, s: str) -> str: 3 | for i in range(26,0,-1): 4 | s = s.replace(str(i)+"#"*(i>9),chr(96+i)) 5 | return s 6 | -------------------------------------------------------------------------------- /1001-1500/1486.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def xorOperation(self, n: int, start: int) -> int: 3 | x = 0 4 | for i in range(n): 5 | x ^= (start+2*i) 6 | return x 7 | -------------------------------------------------------------------------------- /001-500/172.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def trailingZeroes(self, n: int) -> int: 3 | count = 0 4 | while n>=5: 5 | count += (n//5) 6 | n = n//5 7 | return count 8 | -------------------------------------------------------------------------------- /001-500/338.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countBits(self, n: int) -> List[int]: 3 | res = [0]*(n+1) 4 | for i in range(1,n+1): 5 | res[i] = res[i&(i-1)] + 1 6 | return res 7 | -------------------------------------------------------------------------------- /1001-1500/1137.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def tribonacci(self, n: int) -> int: 3 | t = [0,1,1] 4 | for i in range(3,n+1): 5 | t.append(t[i-1]+t[i-2]+t[i-3]) 6 | return t[n] 7 | -------------------------------------------------------------------------------- /1501-2000/1929.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def getConcatenation(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[int] 6 | """ 7 | return nums+nums 8 | -------------------------------------------------------------------------------- /001-500/190.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseBits(self, n: int) -> int: 3 | ans = 0 4 | for _ in range(32): 5 | ans = (ans<<1) + (n&1) 6 | n >>= 1 7 | return ans 8 | -------------------------------------------------------------------------------- /501-1000/771.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numJewelsInStones(self, jewels: str, stones: str) -> int: 3 | c = 0 4 | for stone in stones: 5 | c += stone in jewels 6 | return c 7 | -------------------------------------------------------------------------------- /2001-2500/2235.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def sum(self, num1, num2): 3 | """ 4 | :type num1: int 5 | :type num2: int 6 | :rtype: int 7 | """ 8 | return num1+num2 9 | -------------------------------------------------------------------------------- /2001-2500/2469.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def convertTemperature(self, c): 3 | """ 4 | :type celsius: float 5 | :rtype: List[float] 6 | """ 7 | return [c+273.15, c*1.8+32] 8 | -------------------------------------------------------------------------------- /2501-3000/2864.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximumOddBinaryNumber(self, s: str) -> str: 3 | n = s.count("1")-1 4 | ans = "1"*n 5 | ans += "0"*(len(s)-n-1) 6 | ans += "1" 7 | return ans 8 | -------------------------------------------------------------------------------- /1501-2000/1816.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def truncateSentence(self, s, k): 3 | """ 4 | :type s: str 5 | :type k: int 6 | :rtype: str 7 | """ 8 | return " ".join(s.split()[:k]) 9 | -------------------------------------------------------------------------------- /001-500/342.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPowerOfFour(self, n: int) -> bool: 3 | if n==1: return True 4 | if n<=0: return False 5 | logb4 = math.log(n)/math.log(4) 6 | return logb4==int(logb4) 7 | 8 | -------------------------------------------------------------------------------- /2001-2500/2215.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]: 3 | x = set(nums1) - set(nums2) 4 | y = set(nums2) - set(nums1) 5 | return [list(x), list(y)] 6 | -------------------------------------------------------------------------------- /2501-3000/2652.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sumOfMultiples(self, n: int) -> int: 3 | sum = 0 4 | for i in range(1,n+1): 5 | if i%3 == 0 or i%5 == 0 or i%7 == 0: 6 | sum += i 7 | return sum 8 | -------------------------------------------------------------------------------- /2501-3000/2678.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countSeniors(self, details: List[str]) -> int: 3 | ans = 0 4 | for d in details: 5 | if (int(d[11:13])>60): 6 | ans+=1 7 | return ans 8 | 9 | -------------------------------------------------------------------------------- /001-500/014.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestCommonPrefix(self, strs: List[str]) -> str: 3 | for i, c in enumerate(min(strs)): 4 | if c != max(strs)[i]: 5 | return max(strs)[:i] 6 | return min(strs) 7 | -------------------------------------------------------------------------------- /1501-2000/1859.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortSentence(self, s: str) -> str: 3 | l = s.split() 4 | l.sort(key=lambda x: x[-1]) 5 | for i in range(len(l)): 6 | l[i] = l[i][:-1] 7 | return " ".join(l) 8 | -------------------------------------------------------------------------------- /2001-2500/2351.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def repeatedCharacter(self, s: str) -> str: 3 | seen = [] 4 | for c in s: 5 | if c in seen: 6 | return c 7 | else: 8 | seen.append(c) 9 | -------------------------------------------------------------------------------- /501-1000/594.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findLHS(self, nums: List[int]) -> int: 3 | c = collections.Counter(nums) 4 | res = 0 5 | for x in c: 6 | if x+1 in c: 7 | res = max(res, c[x]+c[x+1]) 8 | return res 9 | -------------------------------------------------------------------------------- /001-500/055.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canJump(self, nums: List[int]) -> bool: 3 | goal = len(nums)-1 4 | for i in reversed(range(len(nums)-1)): 5 | if i+nums[i]>=goal: 6 | goal = i 7 | return goal==0 8 | -------------------------------------------------------------------------------- /001-500/122.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices: List[int]) -> int: 3 | mp = 0 4 | for i in range(len(prices)-1): 5 | if prices[i+1]>prices[i]: 6 | mp += prices[i+1]-prices[i] 7 | return mp 8 | -------------------------------------------------------------------------------- /001-500/55.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canJump(self, nums: List[int]) -> bool: 3 | goal = len(nums)-1 4 | for i in reversed(range(len(nums)-1)): 5 | if i+nums[i]>=goal: 6 | goal = i 7 | return goal==0 8 | -------------------------------------------------------------------------------- /1501-2000/1641.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countVowelStrings(self, n: int) -> int: 3 | dp = [1]*5 4 | while n>0: 5 | for i in reversed(range(0,4)): 6 | dp[i]+=dp[i+1] 7 | n-=1 8 | return dp[0] 9 | -------------------------------------------------------------------------------- /1501-2000/1913.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxProductDifference(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | nums.sort() 8 | return (nums[-1]*nums[-2])-(nums[0]*nums[1]) 9 | -------------------------------------------------------------------------------- /2001-2500/2433.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findArray(self, pref: List[int]) -> List[int]: 3 | prev = pref[0] 4 | for i in range(1,len(pref)): 5 | pref[i]^=prev 6 | prev^=pref[i] 7 | return pref 8 | 9 | -------------------------------------------------------------------------------- /001-500/119.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getRow(self, rowIndex: int) -> List[int]: 3 | res = [[1]] 4 | for _ in range(rowIndex): 5 | x = res.pop() 6 | res.append(list(map(add, x+[0], [0]+x))) 7 | 8 | return res[0] 9 | -------------------------------------------------------------------------------- /2501-3000/2942.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findWordsContaining(self, words: List[str], x: str) -> List[int]: 3 | res = [] 4 | for i in range(len(words)): 5 | if x in words[i]: 6 | res.append(i) 7 | return res 8 | -------------------------------------------------------------------------------- /2501-3000/2520.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countDigits(self, num: int) -> int: 3 | str_num, count = str(num), 0 4 | for digit in str_num: 5 | if num % int(digit) == 0: 6 | count += 1 7 | return count 8 | 9 | -------------------------------------------------------------------------------- /1501-2000/1662.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def arrayStringsAreEqual(self, word1, word2): 3 | """ 4 | :type word1: List[str] 5 | :type word2: List[str] 6 | :rtype: bool 7 | """ 8 | return "".join(word1)=="".join(word2) 9 | -------------------------------------------------------------------------------- /1001-1500/1281.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subtractProductAndSum(self, n: int) -> int: 3 | s = 0 4 | p = 1 5 | while n>0: 6 | i = n%10 7 | n //= 10 8 | s += i 9 | p *= i 10 | return p-s 11 | -------------------------------------------------------------------------------- /1001-1500/1323.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximum69Number (self, num: int) -> int: 3 | nl = list(str(num)) 4 | for i in range(len(nl)): 5 | if nl[i]=='6': 6 | nl[i]= '9' 7 | break 8 | return int(''.join(nl)) 9 | 10 | -------------------------------------------------------------------------------- /1001-1500/1342.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numberOfSteps(self, num: int) -> int: 3 | c = 0 4 | while num>0: 5 | c+=1 6 | if num%2==0: 7 | num/=2 8 | else: 9 | num-=1 10 | return c 11 | -------------------------------------------------------------------------------- /501-1000/561.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def arrayPairSum(self, nums: List[int]) -> int: 3 | nums.sort() 4 | i = 0 5 | ans = 0 6 | while i bool: 3 | l1 = [] 4 | l2 = [] 5 | for c in s: 6 | l1.append(s.index(c)) 7 | for c in t: 8 | l2.append(t.index(c)) 9 | return l1==l2 10 | -------------------------------------------------------------------------------- /1001-1500/1221.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def balancedStringSplit(self, s: str) -> int: 3 | c = res = 0 4 | for i in s: 5 | if i=="L": c+=1 6 | else: c-=1 7 | if c==0: 8 | res+=1 9 | 10 | return res 11 | -------------------------------------------------------------------------------- /1001-1500/1480.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def runningSum(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[int] 6 | """ 7 | for i in range(1,len(nums)): 8 | nums[i]+=nums[i-1] 9 | 10 | return nums 11 | -------------------------------------------------------------------------------- /1001-1500/1492.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kthFactor(self, n: int, k: int) -> int: 3 | i = 1 4 | while k>0: 5 | if i>n: 6 | return -1 7 | if n%i==0: 8 | k-=1 9 | i+=1 10 | return i-1 11 | -------------------------------------------------------------------------------- /2001-2500/2089.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def targetIndices(self, nums: List[int], target: int) -> List[int]: 3 | nums.sort() 4 | res = [] 5 | for i in range(len(nums)): 6 | if nums[i]==target: 7 | res.append(i) 8 | return res 9 | -------------------------------------------------------------------------------- /2001-2500/2037.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minMovesToSeat(self, seats: List[int], students: List[int]) -> int: 3 | seats.sort() 4 | students.sort() 5 | x = 0 6 | for i in range(len(seats)): 7 | x += abs(seats[i]-students[i]) 8 | return x 9 | -------------------------------------------------------------------------------- /2001-2500/2125.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numberOfBeams(self, bank: List[str]) -> int: 3 | arr = [row.count("1") for row in bank if "1" in row] 4 | res = 0 5 | for i in range(len(arr)-1): 6 | res+=(arr[i]*arr[i+1]) 7 | return res 8 | 9 | -------------------------------------------------------------------------------- /2001-2500/2390.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeStars(self, s: str) -> str: 3 | stack = [] 4 | for c in s: 5 | if c=="*": 6 | stack.pop() 7 | else: 8 | stack.append(c) 9 | 10 | return "".join(stack) 11 | -------------------------------------------------------------------------------- /2501-3000/2506.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def similarPairs(self, words: List[str]) -> int: 3 | count = 0 4 | for i in range(len(words)-1): 5 | for j in range(i+1,len(words)): 6 | count += set(words[i]) == set(words[j]) 7 | 8 | return count 9 | -------------------------------------------------------------------------------- /2501-3000/2529.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximumCount(self, nums: List[int]) -> int: 3 | pos=neg=0 4 | for num in nums: 5 | if num<0: 6 | neg+=1 7 | elif num>0: 8 | pos+=1 9 | return max(pos,neg) 10 | -------------------------------------------------------------------------------- /1001-1500/1071.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def gcdOfStrings(self, str1: str, str2: str) -> str: 3 | if str1 + str2 != str2 + str1: 4 | return "" 5 | 6 | max_length = gcd(len(str1), len(str2)) 7 | return str1[:max_length] 8 | 9 | 10 | -------------------------------------------------------------------------------- /2001-2500/2011.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def finalValueAfterOperations(self, operations: List[str]) -> int: 3 | x = 0 4 | for o in operations: 5 | if "+" in o: 6 | x += 1 7 | else: 8 | x -= 1 9 | return x 10 | -------------------------------------------------------------------------------- /2501-3000/2894.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def differenceOfSums(self, n: int, m: int) -> int: 3 | ans = 0 4 | for i in range(1,n+1): 5 | if i%m==0: 6 | ans-=i 7 | else: 8 | ans+=i 9 | return ans 10 | 11 | -------------------------------------------------------------------------------- /001-500/001.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums: List[int], target: int) -> List[int]: 3 | d = {} 4 | for i in range(len(nums)): 5 | r = target - nums[i] 6 | if r in d: return [d[r],i] 7 | d[nums[i]]=i 8 | 9 | 10 | -------------------------------------------------------------------------------- /001-500/058.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLastWord(self, s: str) -> int: 3 | i = len(s)-1 4 | while s[i]==" ": 5 | i -= 1 6 | count = 0 7 | while i!=-1 and s[i]!=" ": 8 | i -= 1 9 | count += 1 10 | return count 11 | -------------------------------------------------------------------------------- /001-500/492.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def constructRectangle(self, area: int) -> List[int]: 3 | import math 4 | mid = int(math.sqrt(area)) 5 | while mid>0: 6 | if area%mid==0: 7 | return [int(area/mid),mid] 8 | mid-=1 9 | 10 | -------------------------------------------------------------------------------- /1001-1500/1047.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeDuplicates(self, s: str) -> str: 3 | stack = ["#"] 4 | for c in s: 5 | if c==stack[-1]: 6 | stack.pop() 7 | else: 8 | stack.append(c) 9 | return "".join(stack[1:]) 10 | -------------------------------------------------------------------------------- /1501-2000/1646.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getMaximumGenerated(self, n: int) -> int: 3 | nums = [0]*(n+2) 4 | nums[1] = 1 5 | for i in range(2,n+1): 6 | nums[i] = nums[i//2] + nums[(i//2)+1]*(i%2) 7 | 8 | return max(nums[:n+1]) 9 | 10 | -------------------------------------------------------------------------------- /2501-3000/2586.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def vowelStrings(self, words: List[str], left: int, right: int) -> int: 3 | v = "aeiouAEIOU" 4 | c = 0 5 | for i in range(left,right+1): 6 | if words[i][0] in v and words[i][-1] in v: 7 | c += 1 8 | return c 9 | -------------------------------------------------------------------------------- /2001-2500/2367.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def arithmeticTriplets(self, nums: List[int], diff: int) -> int: 3 | ans = 0 4 | s = set(nums) 5 | for num in nums: 6 | if num+diff in s and num+2*diff in s: 7 | ans += 1 8 | return ans 9 | 10 | -------------------------------------------------------------------------------- /2001-2500/2439.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimizeArrayValue(self, nums: List[int]) -> int: 3 | s = 0 4 | maxv = float('-inf') 5 | for i in range(len(nums)): 6 | s += nums[i] 7 | maxv = max(maxv, math.ceil(s/(i+1))) 8 | return maxv 9 | 10 | -------------------------------------------------------------------------------- /001-500/448.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDisappearedNumbers(self, nums: List[int]) -> List[int]: 3 | for num in nums: 4 | val = abs(num)-1 5 | nums[val] = -abs(nums[val]) 6 | return [i+1 for i in range(len(nums)) if nums[i]>0] 7 | 8 | -------------------------------------------------------------------------------- /1501-2000/1920.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def buildArray(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[int] 6 | """ 7 | ans=[] 8 | 9 | for i in range(len(nums)): 10 | ans.append(nums[nums[i]]) 11 | 12 | return ans 13 | -------------------------------------------------------------------------------- /001-500/451.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def frequencySort(self, s: str) -> str: 3 | m = Counter(s) 4 | l = sorted(m.items(), key = lambda x: x[1], reverse=True) 5 | ans = "" 6 | for c,count in l: 7 | ans += c*count 8 | return ans 9 | 10 | 11 | -------------------------------------------------------------------------------- /1001-1500/1394.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findLucky(self, arr: List[int]) -> int: 3 | d = defaultdict(int) 4 | for num in arr: 5 | d[num]+=1 6 | for key,val in sorted(d.items(), reverse=True): 7 | if key==val: 8 | return key 9 | return -1 10 | -------------------------------------------------------------------------------- /001-500/045.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def jump(self, nums: List[int]) -> int: 3 | reach, last, count = 0,0,0 4 | for i in range(len(nums)-1): 5 | reach = max(reach,i+nums[i]) 6 | if i==last: 7 | last=reach 8 | count += 1 9 | return count 10 | -------------------------------------------------------------------------------- /001-500/198.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rob(self, nums: List[int]) -> int: 3 | if len(nums)<=2: 4 | return max(nums) 5 | dp = [0]*len(nums) 6 | 7 | for i in range(len(nums)): 8 | dp[i] = max(dp[i-2]+nums[i], dp[i-1]) 9 | 10 | return dp[-1] 11 | 12 | -------------------------------------------------------------------------------- /001-500/349.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: 3 | return list(set(nums1) & set(nums2)) 4 | 5 | 6 | class Solution: 7 | def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: 8 | return set(nums1).intersection(nums2) 9 | -------------------------------------------------------------------------------- /001-500/080.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeDuplicates(self, nums: List[int]) -> int: 3 | fast=slow=0 4 | while fast int: 3 | s.sort() 4 | g.sort() 5 | i,j=0,0 6 | while i=g[i]: 8 | i+=1 9 | j+=1 10 | return i 11 | 12 | -------------------------------------------------------------------------------- /2001-2500/2221.py: -------------------------------------------------------------------------------- 1 | from itertools import accumulate 2 | class Solution: 3 | def triangularSum(self, nums: List[int]) -> int: 4 | n = len(nums) 5 | while n>0: 6 | for i in range(n-1): 7 | nums[i] = (nums[i] + nums[i+1]) % 10 8 | n -= 1 9 | return nums[0] 10 | -------------------------------------------------------------------------------- /001-500/268.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def missingNumber(self, nums: List[int]) -> int: 3 | return int(len(nums)*(len(nums)+1)/2 - sum(nums)) 4 | 5 | 6 | class Solution: 7 | def missingNumber(self, nums: List[int]) -> int: 8 | s = sum(nums) 9 | n = len(nums) 10 | return int(n*(n+1)/2 - s) 11 | -------------------------------------------------------------------------------- /001-500/344.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseString(self, s: List[str]) -> None: 3 | """ 4 | Do not return anything, modify s in-place instead. 5 | """ 6 | i = 0 7 | j = len(s)-1 8 | while i bool: 3 | if not s: 4 | return True 5 | i = 0 6 | for c in t: 7 | if s[i]==c: 8 | i+=1 9 | if i==len(s): 10 | break 11 | 12 | return i==len(s) 13 | -------------------------------------------------------------------------------- /2001-2500/2160.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumSum(self, num: int) -> int: 3 | n = sorted(str(num)) 4 | return int(n[0] + n[2]) + int(n[1] + n[3]) 5 | 6 | 7 | class Solution: 8 | def minimumSum(self, num: int) -> int: 9 | a,b,c,d = sorted(str(num)) 10 | return int(a+c) + int(b+d) 11 | -------------------------------------------------------------------------------- /2001-2500/2169.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countOperations(self, num1: int, num2: int) -> int: 3 | c = 0 4 | while num1!=0 and num2!=0: 5 | if num1>=num2: 6 | num1-=num2 7 | else: 8 | num2-=num1 9 | c+=1 10 | return c 11 | 12 | -------------------------------------------------------------------------------- /2501-3000/2744.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maximumNumberOfStringPairs(self, words: List[str]) -> int: 3 | strings = set() 4 | ans = 0 5 | for w in words: 6 | if w in strings: 7 | ans += 1 8 | else: 9 | strings.add(w[::-1]) 10 | return ans 11 | -------------------------------------------------------------------------------- /2001-2500/2148.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countElements(self, nums: List[int]) -> int: 3 | if len(nums)<3: 4 | return 0 5 | nums.sort() 6 | ans = len(nums) - nums.count(nums[0]) 7 | if nums[0]!=nums[-1]: 8 | ans -= nums.count(nums[-1]) 9 | return ans 10 | 11 | -------------------------------------------------------------------------------- /2501-3000/2544.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def alternateDigitSum(self, n: int) -> int: 3 | res = 0 4 | sign = 1 5 | for sn in str(n): 6 | res += (int(sn)*sign) 7 | if sign==1: 8 | sign = -1 9 | else: 10 | sign = 1 11 | return res 12 | 13 | -------------------------------------------------------------------------------- /1501-2000/1732.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def largestAltitude(self, gain): 3 | """ 4 | :type gain: List[int] 5 | :rtype: int 6 | """ 7 | m = 0 8 | x = 0 9 | for i in range(0, len(gain)): 10 | x += gain[i] 11 | m = max(m,x) 12 | 13 | return m 14 | -------------------------------------------------------------------------------- /501-1000/680.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def validPalindrome(self, s: str) -> bool: 3 | l,r = 0,len(s)-1 4 | flag = 0 5 | while l int: 3 | stack = [] 4 | ans = -1 5 | for c in s: 6 | if c=="(": 7 | stack.append("(") 8 | ans = max(ans,len(stack)) 9 | elif c==")": 10 | stack.pop() 11 | return ans 12 | -------------------------------------------------------------------------------- /2501-3000/2870.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minOperations(self, nums: List[int]) -> int: 3 | d = defaultdict(int) 4 | for num in nums: 5 | d[num] += 1 6 | 7 | if min(d.values()) == 1: 8 | return -1 9 | 10 | return sum(c // 3 + (c % 3 > 0) for c in d.values()) 11 | 12 | 13 | -------------------------------------------------------------------------------- /1001-1500/1331.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def arrayRankTransform(self, arr: List[int]) -> List[int]: 3 | arrSorted = sorted(set(arr)) 4 | d = {} 5 | for i in range(len(arrSorted)): 6 | d[arrSorted[i]] = i+1 7 | res = [] 8 | for num in arr: 9 | res.append(d[num]) 10 | return res 11 | -------------------------------------------------------------------------------- /1001-1500/1436.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def destCity(self, paths: List[List[str]]) -> str: 3 | cities_with_outgoing_path = set() 4 | for ca,cb in paths: 5 | cities_with_outgoing_path.add(ca) 6 | for ca,cb in paths: 7 | if cb not in cities_with_outgoing_path: 8 | return cb 9 | 10 | -------------------------------------------------------------------------------- /001-500/078.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subsets(self, nums: List[int]) -> List[List[int]]: 3 | res = [] 4 | self.backtrack(nums,[], res) 5 | return res 6 | 7 | def backtrack(self,nums,path,res): 8 | res.append(path) 9 | for i in range(len(nums)): 10 | self.backtrack(nums[i+1:], path+[nums[i]], res) 11 | -------------------------------------------------------------------------------- /001-500/048.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotate(self, m: List[List[int]]) -> None: 3 | """ 4 | Do not return anything, modify matrix in-place instead. 5 | """ 6 | m.reverse() 7 | #transposing 8 | for i in range(len(m)): 9 | for j in range(i): 10 | m[i][j], m[j][i] = m[j][i], m[i][j] 11 | -------------------------------------------------------------------------------- /1501-2000/1844.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def replaceDigits(self, s: str) -> str: 3 | def shift(x, n): 4 | return chr(ord(x)+n) 5 | res = "" 6 | for i in range(len(s)): 7 | if i%2==0: 8 | res += s[i] 9 | else: 10 | res += shift(s[i-1],int(s[i])) 11 | return res 12 | -------------------------------------------------------------------------------- /001-500/452.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMinArrowShots(self, points: List[List[int]]) -> int: 3 | points.sort(key=lambda x:x[1]) 4 | arrows=0 5 | end = float('-inf') 6 | for balloon in points: 7 | if balloon[0]>end: 8 | end = balloon[1] 9 | arrows += 1 10 | 11 | return arrows 12 | -------------------------------------------------------------------------------- /501-1000/637.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMinArrowShots(self, points: List[List[int]]) -> int: 3 | points.sort(key=lambda x:x[1]) 4 | arrows=0 5 | end = float('-inf') 6 | for balloon in points: 7 | if balloon[0]>end: 8 | end = balloon[1] 9 | arrows += 1 10 | 11 | return arrows 12 | -------------------------------------------------------------------------------- /1001-1500/1389.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def createTargetArray(self, nums, index): 3 | """ 4 | :type nums: List[int] 5 | :type index: List[int] 6 | :rtype: List[int] 7 | """ 8 | target = [] 9 | 10 | for i in range(len(nums)): 11 | target.insert(index[i], nums[i]) 12 | 13 | return target 14 | -------------------------------------------------------------------------------- /2001-2500/2236.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def checkTree(self, root: Optional[TreeNode]) -> bool: 9 | return root.val == root.left.val + root.right.val 10 | -------------------------------------------------------------------------------- /2501-3000/2535.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def differenceOfSum(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | es = sum(nums) 8 | ds = 0 9 | for num in nums: 10 | while num>0: 11 | ds+=num%10 12 | num//=10 13 | return abs(es-ds) 14 | -------------------------------------------------------------------------------- /001-500/036.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isValidSudoku(self, board: List[List[str]]) -> bool: 3 | res = [] 4 | for i in range(9): 5 | for j in range(9): 6 | ele = board[i][j] 7 | if ele != ".": 8 | res += [(i,ele), (ele,j), (i//3,j//3,ele)] 9 | return len(res)==len(set(res)) 10 | 11 | -------------------------------------------------------------------------------- /001-500/121.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices: List[int]) -> int: 3 | maxProfit = 0 4 | l,r = 0,1 5 | while r < len(prices): 6 | if prices[r]>prices[l]: 7 | maxProfit = max(maxProfit,prices[r]-prices[l]) 8 | else: 9 | l = r 10 | r += 1 11 | return maxProfit 12 | -------------------------------------------------------------------------------- /1501-2000/1941.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def areOccurrencesEqual(self, s: str) -> bool: 3 | d = {} 4 | for c in s: 5 | if c in d: 6 | d[c]+=1 7 | else: 8 | d[c]=1 9 | x = d[s[0]] 10 | for k,v in d.items(): 11 | if v!=x: 12 | return False 13 | return True 14 | -------------------------------------------------------------------------------- /1001-1500/1470.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def shuffle(self, nums, n): 3 | """ 4 | :type nums: List[int] 5 | :type n: int 6 | :rtype: List[int] 7 | """ 8 | res = [] 9 | for i in range(n): 10 | res.append(nums[i]) 11 | res.append(nums[i+n]) 12 | 13 | return res 14 | 15 | 16 | -------------------------------------------------------------------------------- /001-500/071.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def simplifyPath(self, path: str) -> str: 3 | dirOrFiles = [] 4 | path = path.split("/") 5 | for x in path: 6 | if dirOrFiles and x=="..": 7 | dirOrFiles.pop() 8 | elif x not in [".","..",""]: 9 | dirOrFiles.append(x) 10 | 11 | return "/"+"/".join(dirOrFiles) 12 | -------------------------------------------------------------------------------- /001-500/162.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findPeakElement(self, nums: List[int]) -> int: 3 | l,h=0,len(nums)-1 4 | while l<=h: 5 | m = (l+h)>>1 6 | if m>0 and nums[m] int: 3 | ds, dt = defaultdict(int), defaultdict(int) 4 | for c in s: 5 | ds[c]+=1 6 | for c in t: 7 | dt[c]+=1 8 | ans = 0 9 | for k in ds.keys(): 10 | ans += (ds[k]-dt[k]) if ds[k]>dt[k] else 0 11 | return ans 12 | 13 | -------------------------------------------------------------------------------- /001-500/125.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPalindrome(self, s: str) -> bool: 3 | l,r = 0,len(s)-1 4 | while l List[int]: 3 | i,j=0,len(nums)-1 4 | while i target: 8 | j -= 1 9 | else: 10 | i += 1 11 | return [] 12 | 13 | -------------------------------------------------------------------------------- /001-500/461.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hammingDistance(self, x: int, y: int) -> int: 3 | hd = 0 4 | z = x^y 5 | while z: 6 | if z%2==1: 7 | hd += 1 8 | z = z>>1 9 | return hd 10 | 11 | 12 | class Solution: 13 | def hammingDistance(self, x: int, y: int) -> int: 14 | return bin(x^y).count('1') 15 | -------------------------------------------------------------------------------- /1501-2000/1720.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def decode(self, encoded, first): 3 | """ 4 | :type encoded: List[int] 5 | :type first: int 6 | :rtype: List[int] 7 | """ 8 | arr = [] 9 | arr.append(first) 10 | 11 | for e in encoded: 12 | first ^= e 13 | arr.append(first) 14 | 15 | return arr 16 | -------------------------------------------------------------------------------- /2001-2500/2185.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def prefixCount(self, words, pref): 3 | """ 4 | :type words: List[str] 5 | :type pref: str 6 | :rtype: int 7 | """ 8 | count = 0 9 | pl = len(pref) 10 | for word in words: 11 | if word.startswith(pref): 12 | count+=1 13 | 14 | return count 15 | -------------------------------------------------------------------------------- /2001-2500/2278.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def percentageLetter(self, s: str, letter: str) -> int: 3 | d = {} 4 | for c in s: 5 | if c in d: 6 | d[c]+=1 7 | else: 8 | d[c]=1 9 | try: 10 | count = d[letter] 11 | return int((count/len(s))*100) 12 | except: 13 | return 0 14 | -------------------------------------------------------------------------------- /501-1000/709.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def toLowerCase(self, s: str) -> str: 3 | res = "" 4 | for c in s: 5 | if c.isupper(): 6 | res += chr(ord(c)+32) 7 | else: 8 | res += c 9 | return res 10 | 11 | 12 | class Solution: 13 | def toLowerCase(self, s: str) -> str: 14 | return s.lower() 15 | -------------------------------------------------------------------------------- /001-500/070.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def climbStairs(self, n: int) -> int: 3 | fib = [0,1] 4 | for i in range(2,n+2): 5 | fib.append(fib[i-1]+fib[i-2]) 6 | return fib[n+1] 7 | 8 | class Solution: 9 | def climbStairs(self, n: int) -> int: 10 | a,b=1,1 11 | while n>0: 12 | a,b = b,a+b 13 | n-=1 14 | return a 15 | -------------------------------------------------------------------------------- /1001-1500/1002.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def commonChars(self, words: List[str]) -> List[str]: 3 | res = list(words[0]) 4 | for word in words: 5 | newRes = [] 6 | for c in word: 7 | if c in res: 8 | newRes.append(c) 9 | res.remove(c) 10 | res = newRes 11 | return res 12 | 13 | -------------------------------------------------------------------------------- /501-1000/704.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def search(self, nums: List[int], target: int) -> int: 3 | l,h = 0, len(nums)-1 4 | while l<=h: 5 | mid = (l+h)//2 6 | if nums[mid]==target: 7 | return mid 8 | elif nums[mid]>target: 9 | h = mid-1 10 | else: 11 | l = mid+1 12 | return -1 13 | -------------------------------------------------------------------------------- /001-500/300.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLIS(self, nums: List[int]) -> int: 3 | packs = [] 4 | 5 | for num in nums: 6 | if not packs or num > packs[-1]: 7 | packs.append(num) 8 | else: 9 | i = bisect.bisect_left(packs, num) 10 | packs[i] = num 11 | 12 | return len(packs) 13 | 14 | -------------------------------------------------------------------------------- /1001-1500/1291.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sequentialDigits(self, low: int, high: int) -> List[int]: 3 | x = "123456789" 4 | ans = [] 5 | 6 | for i in range(len(x)): 7 | for j in range(i + 1, len(x) + 1): 8 | curr = int(x[i:j]) 9 | if low <= curr <= high: 10 | ans.append(curr) 11 | return sorted(ans) 12 | -------------------------------------------------------------------------------- /501-1000/645.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findErrorNums(self, nums: List[int]) -> List[int]: 3 | return [sum(nums)-sum(set(nums)), int(len(nums)*(len(nums)+1)/2-sum(set(nums)))] 4 | 5 | class Solution: 6 | def findErrorNums(self, nums: List[int]) -> List[int]: 7 | x = (len(nums)*(len(nums)+1))//2 8 | s = sum(set(nums)) 9 | return [sum(nums)-s, x-s] 10 | 11 | -------------------------------------------------------------------------------- /001-500/219.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: 3 | d = {} 4 | for i in range(len(nums)): 5 | if nums[i] not in d: 6 | d[nums[i]] = i 7 | else: 8 | if abs(i-d[nums[i]])<=k: 9 | return True 10 | d[nums[i]]=i 11 | 12 | return False 13 | -------------------------------------------------------------------------------- /1501-2000/1768.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def mergeAlternately(self, word1: str, word2: str) -> str: 3 | i = j =0 4 | res = "" 5 | while i int: 5 | g = defaultdict(list) 6 | for edge in edges: 7 | g[edge[0]].append(edge[1]) 8 | g[edge[1]].append(edge[0]) 9 | for s,dlist in g.items(): 10 | if len(dlist)==len(g.keys())-1: 11 | return s 12 | -------------------------------------------------------------------------------- /501-1000/832.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def flipAndInvertImage(self, image): 3 | """ 4 | :type image: List[List[int]] 5 | :rtype: List[List[int]] 6 | """ 7 | for i in range(len(image)): 8 | image[i].reverse() 9 | for j in range(len(image[i])): 10 | image[i][j]=1 if image[i][j]==0 else 0 11 | 12 | return image 13 | -------------------------------------------------------------------------------- /001-500/050.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def myPow(self, x: float, n: int) -> float: 3 | def solve(x,n): 4 | if x==0: 5 | return 0 6 | if n==0: 7 | return 1 8 | res = solve(x,n//2) 9 | res *= res 10 | return res*x if n%2!=0 else res 11 | 12 | res = solve(x,abs(n)) 13 | return res if n>0 else 1/res 14 | -------------------------------------------------------------------------------- /001-500/128.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestConsecutive(self, nums: List[int]) -> int: 3 | numSet = set(nums) 4 | ans = 0 5 | 6 | for num in nums: 7 | if (num-1) not in numSet: 8 | length = 1 9 | while (num+length) in numSet: 10 | length += 1 11 | ans = max(ans,length) 12 | 13 | return ans 14 | -------------------------------------------------------------------------------- /501-1000/643.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMaxAverage(self, nums: List[int], k: int) -> float: 3 | l,r=0,k-1 4 | curSum = sum(nums[:k]) 5 | maxSum = curSum 6 | while r List[List[int]]: 3 | res = [] 4 | intervals.sort(key=lambda x: x[0]) 5 | for interval in intervals: 6 | if not res or res[-1][-1] < interval[0]: 7 | res.append(interval) 8 | else: 9 | res[-1][-1]=max(res[-1][-1],interval[-1]) 10 | return res 11 | -------------------------------------------------------------------------------- /501-1000/739.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def dailyTemperatures(self, T: List[int]) -> List[int]: 3 | ans = [0]*len(T) 4 | stack = [] 5 | 6 | for i,v in enumerate(T): 7 | while stack and stack[-1][1] < v: 8 | index,value = stack.pop() 9 | ans[index] = i - index 10 | stack.append([i,v]) 11 | 12 | return ans 13 | -------------------------------------------------------------------------------- /1001-1500/1365.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def smallerNumbersThanCurrent(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[int] 6 | """ 7 | m = {} 8 | numsSorted = sorted(nums) 9 | for i in range(len(numsSorted)): 10 | if numsSorted[i] not in m.keys(): 11 | m[numsSorted[i]]=i 12 | return [m[x] for x in nums] 13 | -------------------------------------------------------------------------------- /2001-2500/2413.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def smallestEvenMultiple(self, n: int) -> int: 3 | if n%2==0: 4 | return n 5 | return n*2 6 | 7 | 8 | class Solution: 9 | def smallestEvenMultiple(self, n: int) -> int: 10 | return n << (n & 1) 11 | 12 | 13 | class Solution: 14 | def smallestEvenMultiple(self, n: int) -> int: 15 | return n*2 if n%2!=0 else n 16 | -------------------------------------------------------------------------------- /1501-2000/1572.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def diagonalSum(self, mat): 3 | """ 4 | :type mat: List[List[int]] 5 | :rtype: int 6 | """ 7 | n = len(mat) 8 | mid = n//2 9 | s = 0 10 | for i in range(n): 11 | s+=mat[i][i] 12 | s+=mat[n-i-1][i] 13 | 14 | if n%2!=0: 15 | s-=mat[mid][mid] 16 | 17 | return s 18 | -------------------------------------------------------------------------------- /1501-2000/2000.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reversePrefix(self, w: str, ch: str) -> str: 3 | j = -1 4 | word = list(w) 5 | for i in range(len(word)): 6 | if word[i]==ch: 7 | j = i 8 | break 9 | i = 0 10 | while i str: 3 | res = [] 4 | temp = "" 5 | for c in s: 6 | if c!=" ": 7 | temp += c 8 | else: 9 | if temp!="": 10 | res.append(temp) 11 | temp = "" 12 | if temp!="": 13 | res.append(temp) 14 | return " ".join(res[::-1]) 15 | -------------------------------------------------------------------------------- /2001-2500/2485.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def pivotInteger(self, n: int) -> int: 3 | tsum = n*(n+1) // 2 4 | l,r = 1,n+1 5 | while l List[List[int]]: 3 | res = [] 4 | self.backtrack(range(1,n+1), k, [], res) 5 | return res 6 | 7 | def backtrack(self, nums, k, path, res): 8 | if len(path)==k: 9 | res.append(path) 10 | return 11 | for i in range(len(nums)): 12 | self.backtrack(nums[i+1:], k, path+[nums[i]], res) 13 | -------------------------------------------------------------------------------- /001-500/104.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def maxDepth(self, root: Optional[TreeNode]) -> int: 9 | if not root: 10 | return 0 11 | return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 12 | -------------------------------------------------------------------------------- /001-500/441.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def arrangeCoins(self, n: int) -> int: 3 | l = 0 4 | r = n 5 | while l<=r: 6 | m = (l+r)>>1 7 | coins_until_m = (m*(m+1))>>1 8 | if coins_until_m == n: 9 | return m 10 | elif n < coins_until_m: 11 | r = m-1 12 | else: 13 | l = m+1 14 | return r 15 | 16 | -------------------------------------------------------------------------------- /001-500/011.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxArea(self, height: List[int]) -> int: 3 | maxVol = 0 4 | i,j=0,len(height)-1 5 | while iheight[j]: 11 | j-=1 12 | else: 13 | i+=1 14 | return maxVol 15 | -------------------------------------------------------------------------------- /001-500/022.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generateParenthesis(self, n: int) -> List[str]: 3 | def dfs(l,r,s): 4 | if len(s)==n*2: 5 | res.append(s) 6 | return 7 | 8 | if l int: 3 | l,r,total=0,0,0 4 | ans = float('inf') 5 | 6 | while r=target: 9 | ans = min(ans,r-l+1) 10 | total-=nums[l] 11 | l+=1 12 | r+=1 13 | 14 | return 0 if ans==float('inf') else ans 15 | -------------------------------------------------------------------------------- /001-500/234.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def isPalindrome(self, head: Optional[ListNode]) -> bool: 8 | temp = head 9 | arr = [] 10 | while temp: 11 | arr.append(temp.val) 12 | temp = temp.next 13 | return arr == arr[::-1] 14 | -------------------------------------------------------------------------------- /001-500/412.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fizzBuzz(self, n: int) -> List[str]: 3 | res = [] 4 | for i in range(1,n+1): 5 | if i%3==0 and i%5==0: 6 | res.append("FizzBuzz") 7 | elif i%3==0: 8 | res.append("Fizz") 9 | elif i%5==0: 10 | res.append("Buzz") 11 | else: 12 | res.append(str(i)) 13 | 14 | return res 15 | -------------------------------------------------------------------------------- /501-1000/629.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kInversePairs(self, n: int, k: int) -> int: 3 | M = 10**9 + 7 4 | d = [0] + [1] * (k + 1) 5 | for n in range(2, n+1): 6 | new = [0] 7 | for k in range(k+1): 8 | v = d[k+1] 9 | v -= d[k-n+1] if k >= n else 0 10 | new.append( (new[-1] + v) % M ) 11 | d = new 12 | return (d[k+1] - d[k]) % M 13 | -------------------------------------------------------------------------------- /501-1000/682.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def calPoints(self, operations: List[str]) -> int: 3 | l = [] 4 | for i in operations: 5 | if i=="C": 6 | l.pop() 7 | elif i=="D": 8 | l.append(l[-1]*2) 9 | elif i=="+": 10 | l.append(l[-1]+l[-2]) 11 | else: 12 | l.append(int(i)) 13 | print(l) 14 | return sum(l) 15 | -------------------------------------------------------------------------------- /001-500/046.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def permute(self, nums: List[int]) -> List[List[int]]: 3 | res = [] 4 | n = len(nums) 5 | self.backtrack(nums,[],res) 6 | return res 7 | 8 | def backtrack(self, nums, path, res): 9 | if len(nums)==0: 10 | res.append(path) 11 | return 12 | for i in range(len(nums)): 13 | self.backtrack(nums[:i]+nums[i+1:], path+[nums[i]], res) 14 | -------------------------------------------------------------------------------- /001-500/134.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: 3 | if sum(gas) int: 3 | l,h=0,len(citations)-1 4 | while l<=h: 5 | m = (l+h)>>1 6 | if citations[m]==len(citations)-m: 7 | return len(citations)-m 8 | elif citations[m] bool: 3 | 4 | class Solution: 5 | def firstBadVersion(self, n: int) -> int: 6 | l,h=1,n 7 | ans = 1 8 | while l<=h: 9 | m = (l+h)>>1 10 | if isBadVersion(m)==False: 11 | l = m+1 12 | else: 13 | h = m-1 14 | ans = m 15 | return ans 16 | -------------------------------------------------------------------------------- /2001-2500/2103.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countPoints(self, rings: str) -> int: 3 | rods = [set() for _ in range(10)] 4 | i = 0 5 | ans = 0 6 | alreadyCounted = set() 7 | while i List[int]: 3 | ans = [-1,-1] 4 | for i in range(len(nums)): 5 | for j in range(i, len(nums)): 6 | if abs(i-j)>=indexDifference and abs(nums[i]-nums[j]) >= valueDifference: 7 | ans[0], ans[1] = i,j 8 | break 9 | return ans 10 | 11 | -------------------------------------------------------------------------------- /001-500/90.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: 3 | res = [] 4 | nums.sort() 5 | self.backtrack(nums,[],res) 6 | return res 7 | def backtrack(self, nums, path, res): 8 | res.append(path) 9 | for i in range(len(nums)): 10 | if i>0 and nums[i]==nums[i-1]: 11 | continue 12 | self.backtrack(nums[i+1:], path+[nums[i]], res) 13 | -------------------------------------------------------------------------------- /2001-2500/2225.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findWinners(self, matches: List[List[int]]) -> List[List[int]]: 3 | d = defaultdict(int) 4 | players = set() 5 | for w,l in matches: 6 | d[l] += 1 7 | players.add(w) 8 | players.add(l) 9 | ans = [[],[]] 10 | for p in sorted(players): 11 | if d[p]==0 or d[p]==1: 12 | ans[d[p]].append(p) 13 | return ans 14 | -------------------------------------------------------------------------------- /2001-2500/2404.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | class Solution: 3 | def mostFrequentEven(self, nums: List[int]) -> int: 4 | d = defaultdict(lambda: 0) 5 | val,freq=-1,-float('inf') 6 | for num in nums: 7 | if num%2==0: 8 | d[num]+=1 9 | if d[num]>freq or (d[num]==freq and num int: 3 | res = 0 4 | for i in range(len(nums)): 5 | if str(bin(i)).count("1")==k: 6 | res+=nums[i] 7 | return res 8 | 9 | 10 | class Solution: 11 | def sumIndicesWithKSetBits(self, nums: List[int], k: int) -> int: 12 | return sum([nums[i] for i in range(len(nums)) if bin(i)[2:].count('1')==k]) 13 | -------------------------------------------------------------------------------- /501-1000/797.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: 3 | n = len(graph) 4 | stack = [(0,[0])] 5 | res = [] 6 | 7 | while stack: 8 | node, path = stack.pop() 9 | if node==n-1: 10 | res.append(path) 11 | for child in graph[node]: 12 | stack.append((child,path+[child])) 13 | 14 | return res 15 | -------------------------------------------------------------------------------- /001-500/090.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: 3 | res = [] 4 | nums.sort() 5 | self.backtrack(nums,[],res) 6 | return res 7 | def backtrack(self, nums, path, res): 8 | res.append(path) 9 | for i in range(len(nums)): 10 | if i>0 and nums[i]==nums[i-1]: 11 | continue 12 | self.backtrack(nums[i+1:], path+[nums[i]], res) 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Leetcode Solutions in Python 2 | 3 | This is a personal repository where I store my solutions to algorithmic problems from LeetCode, a popular platform for practicing coding interviews. The repository includes solutions in Python and the files are named according to the question no. on Leetcode. The project is intended to serve as a record of my progress in problem-solving skills, and also as a reference for future coding interviews and technical discussions. 4 | -------------------------------------------------------------------------------- /001-500/160.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: 9 | a = headA 10 | b = headB 11 | while a!=b: 12 | a = headB if not a else a.next 13 | b = headA if not b else b.next 14 | return a 15 | -------------------------------------------------------------------------------- /1001-1500/1464.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProduct(self, nums: List[int]) -> int: 3 | maxval = max(nums) 4 | nums.remove(maxval) 5 | return (maxval-1)*(max(nums)-1) 6 | 7 | 8 | class Solution: 9 | def maxProduct(self, nums: List[int]) -> int: 10 | ans = 0 11 | for i in range(len(nums)): 12 | for j in range(i+1,len(nums)): 13 | ans = max(ans, (nums[i]-1)*(nums[j]-1)) 14 | return ans 15 | -------------------------------------------------------------------------------- /1001-1500/1370.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortString(self, s: str) -> str: 3 | cntlist = collections.Counter(s) 4 | asc = True 5 | ans = "" 6 | while cntlist: 7 | for c in sorted(cntlist) if asc else reversed(sorted(cntlist)): 8 | ans += c 9 | cntlist[c]-=1 10 | if cntlist[c]==0: 11 | del cntlist[c] 12 | asc = not asc 13 | 14 | return ans 15 | -------------------------------------------------------------------------------- /501-1000/559.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Definition for a Node. 3 | class Node: 4 | def __init__(self, val=None, children=None): 5 | self.val = val 6 | self.children = children 7 | """ 8 | 9 | class Solution: 10 | def maxDepth(self, root: 'Node') -> int: 11 | if not root: 12 | return 0 13 | d = 1 14 | if root.children: 15 | d += max(self.maxDepth(child) for child in root.children) 16 | return d 17 | 18 | -------------------------------------------------------------------------------- /501-1000/907.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sumSubarrayMins(self, arr: List[int]) -> int: 3 | ans = 0 4 | stack = [] 5 | arr = [float('-inf')] + arr + [float('-inf')] 6 | for i, n in enumerate(arr): 7 | while stack and arr[stack[-1]] > n: 8 | cur = stack.pop() 9 | ans += arr[cur] * (i - cur) * (cur - stack[-1]) 10 | stack.append(i) 11 | return ans % (10**9 + 7) 12 | 13 | -------------------------------------------------------------------------------- /001-500/003.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLongestSubstring(self, s: str) -> int: 3 | start = 0 4 | maxVal = 0 5 | charHistory = {} 6 | 7 | for i in range(len(s)): 8 | if s[i] in charHistory and start<=charHistory[s[i]]: 9 | start = charHistory[s[i]]+1 10 | else: 11 | maxVal = max(maxVal,i-start+1) 12 | charHistory[s[i]]=i 13 | 14 | return maxVal 15 | -------------------------------------------------------------------------------- /001-500/009.py: -------------------------------------------------------------------------------- 1 | #Without conversion to string 2 | class Solution: 3 | def isPalindrome(self, x: int) -> bool: 4 | revx = 0 5 | temp = x 6 | while temp>0: 7 | revx = revx*10 + (temp%10) 8 | temp = temp//10 9 | if (x==revx): return True 10 | 11 | 12 | #Converting to string and then checking 13 | class Solution: 14 | def isPalindrome(self, x: int) -> bool: 15 | xstr = str(x) 16 | return xstr==xstr[::-1] 17 | -------------------------------------------------------------------------------- /1001-1500/1239.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxLength(self, arr: List[str]) -> int: 3 | def is_unique(s): 4 | return len(s)==len(set(s)) 5 | def bt(start, cur_s): 6 | nonlocal max_len 7 | if is_unique(cur_s): 8 | max_len = max(max_len, len(cur_s)) 9 | for i in range(start, len(arr)): 10 | bt(i+1, cur_s+arr[i]) 11 | max_len = 0 12 | bt(0,"") 13 | return max_len 14 | -------------------------------------------------------------------------------- /001-500/013.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def romanToInt(self, s: str) -> int: 3 | smap = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000} 4 | res = 0 5 | i = 0 6 | while i int: 5 | h = [] 6 | res = 0 7 | for num in nums: 8 | heappush(h,num) 9 | if len(h)>k: 10 | heappop(h) 11 | return heappop(h) 12 | 13 | 14 | class Solution: 15 | def findKthLargest(self, nums: List[int], k: int) -> int: 16 | heapify(nums) 17 | return nlargest(k,nums)[-1] 18 | -------------------------------------------------------------------------------- /1001-1500/1431.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def kidsWithCandies(self, candies, extraCandies): 3 | """ 4 | :type candies: List[int] 5 | :type extraCandies: int 6 | :rtype: List[bool] 7 | """ 8 | res = [] 9 | m = max(candies) 10 | for i in candies: 11 | if i+extraCandies >= m: 12 | res.append(True) 13 | else: 14 | res.append(False) 15 | 16 | return res 17 | -------------------------------------------------------------------------------- /1501-2000/1748.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def sumOfUnique(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | m = {} 8 | 9 | for num in nums: 10 | if num in m: 11 | m[num]+=1 12 | else: 13 | m[num]=1 14 | 15 | count = 0 16 | for num in nums: 17 | if m[num]==1: 18 | count+=num 19 | 20 | return count 21 | -------------------------------------------------------------------------------- /501-1000/868.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def binaryGap(self, n: int) -> int: 3 | count = 0 4 | temp = -1 5 | 6 | while n: 7 | if n&1: 8 | if temp==-1: 9 | temp = 1 10 | else: 11 | count = max(count,temp) 12 | temp = 1 13 | else: 14 | if temp!=-1: 15 | temp += 1 16 | n >>= 1 17 | return count 18 | -------------------------------------------------------------------------------- /001-500/020.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isValid(self, s): 3 | """ 4 | :type s: str 5 | :rtype: bool 6 | """ 7 | d = {'(':')', '[':']', '{':'}'} 8 | stk = [] 9 | 10 | for c in s: 11 | if c in d: 12 | stk.append(c) 13 | elif len(stk)>0 and c==d[stk[-1]]: 14 | stk.pop() 15 | else: 16 | return False 17 | 18 | return not bool(len(stk)) 19 | -------------------------------------------------------------------------------- /001-500/026.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def removeDuplicates(self, arr): 3 | """ 4 | :type nums: List[int] 5 | :rtype: int 6 | """ 7 | fast = slow = count = 0 8 | while fast Optional[ListNode]: 8 | cur = head 9 | while cur: 10 | while cur.next and cur.val==cur.next.val: 11 | cur.next = cur.next.next 12 | cur = cur.next 13 | return head 14 | -------------------------------------------------------------------------------- /2001-2500/2325.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def decodeMessage(self, key: str, message: str) -> str: 3 | d = {} 4 | ans = "" 5 | n = 0 6 | for i in key: 7 | if i not in d and i != " ": 8 | d[i]=chr(ord('a')+n) 9 | n += 1 10 | for i in message: 11 | if i in d: 12 | ans += d[i] 13 | elif i == " ": 14 | ans += " " 15 | 16 | return ans 17 | 18 | -------------------------------------------------------------------------------- /501-1000/693.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hasAlternatingBits(self, n: int) -> bool: 3 | x = n&1 4 | n >>= 1 5 | while n!=0: 6 | if x^(n&1): 7 | x = n&1 8 | n >>= 1 9 | else: 10 | return False 11 | return True 12 | 13 | 14 | class Solution: 15 | def hasAlternatingBits(self, n: int) -> bool: 16 | bits = bin(n) 17 | return "00" not in bits and "11" not in bits 18 | -------------------------------------------------------------------------------- /501-1000/933.py: -------------------------------------------------------------------------------- 1 | class RecentCounter: 2 | 3 | def __init__(self): 4 | self.requests = deque() 5 | 6 | def ping(self, t: int) -> int: 7 | start = t - 3000 8 | self.requests.append(t) 9 | while self.requests and self.requests[0] int: 3 | ans = 0 4 | for word in words: 5 | if s.find(word)==0: 6 | ans += 1 7 | return ans 8 | 9 | class Solution: 10 | def countPrefixes(self, words: List[str], s: str) -> int: 11 | ans = 0 12 | for word in words: 13 | if s[:len(word)]==word: 14 | ans += 1 15 | return ans 16 | 17 | -------------------------------------------------------------------------------- /2001-2500/2418.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are given an array of strings names, and an array heights that consists of distinct positive integers. Both arrays are of length n. 3 | 4 | For each index i, names[i] and heights[i] denote the name and height of the ith person. 5 | 6 | Return names sorted in descending order by the people's heights. 7 | ''' 8 | 9 | 10 | class Solution(object): 11 | def sortPeople(self, names, heights): 12 | return [c for _, c in sorted(zip(heights, names), reverse=True)] 13 | -------------------------------------------------------------------------------- /501-1000/997.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findJudge(self, n: int, trust: List[List[int]]) -> int: 3 | g = {} 4 | x = defaultdict(list) 5 | for i in range(1,n+1): 6 | g[i] = [] 7 | 8 | for s,d in trust: 9 | g[s].append(d) 10 | x[d].append(s) 11 | 12 | for s,d in g.items(): 13 | if len(d)==0: 14 | if len(x[s])==n-1: 15 | return s 16 | 17 | return -1 18 | -------------------------------------------------------------------------------- /001-500/027.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def removeElement(self, nums, val): 3 | """ 4 | :type nums: List[int] 5 | :type val: int 6 | :rtype: int 7 | """ 8 | fast=slow=count=0 9 | while fast None: 3 | """ 4 | Do not return anything, modify nums in-place instead. 5 | """ 6 | def rev(arr, l, r): 7 | while l List[int]: 3 | res = [nums[0]] 4 | total = nums[-1] 5 | for i in range(1,len(nums)): 6 | res.append(res[i-1]+nums[i]) 7 | 8 | i = len(nums)-1 9 | while i>=0: 10 | if i!=len(nums)-1: 11 | total+=nums[i] 12 | res[i] = abs(res[i]-total) 13 | i-=1 14 | 15 | 16 | return res 17 | 18 | 19 | -------------------------------------------------------------------------------- /001-500/028.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def strStr(self, haystack: str, needle: str) -> int: 3 | for i in range(len(haystack)-len(needle)+1): 4 | flag = True 5 | for j in range(len(needle)): 6 | if haystack[i+j]!=needle[j]: 7 | flag = False 8 | if flag: return i 9 | return -1 10 | 11 | 12 | class Solution: 13 | def strStr(self, haystack: str, needle: str) -> int: 14 | return haystack.find(needle) 15 | -------------------------------------------------------------------------------- /501-1000/918.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSubarraySumCircular(self, nums: List[int]) -> int: 3 | maxSum,minSum = nums[0],nums[0] 4 | curMax,curMin = 0,0 5 | totalSum = 0 6 | for num in nums: 7 | curMax = max(curMax+num,num) 8 | curMin = min(curMin+num,num) 9 | totalSum += num 10 | maxSum = max(maxSum,curMax) 11 | minSum = min(minSum,curMin) 12 | return max(totalSum-minSum,maxSum) if maxSum>0 else maxSum 13 | -------------------------------------------------------------------------------- /001-500/383.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canConstruct(self, ransomNote: str, magazine: str) -> bool: 3 | d = defaultdict(int) 4 | 5 | i = 0 6 | while i List[int]: 3 | res = [] 4 | count = 0 5 | for i in queries: 6 | x1,y1,r=i[0],i[1],i[2] 7 | for j in points: 8 | x2=j[0] 9 | y2=j[1] 10 | if (((x2 - x1)**2 + (y2 - y1)**2)**0.5) <= r : 11 | count+=1 12 | res.append(count) 13 | count = 0 14 | return res 15 | -------------------------------------------------------------------------------- /2001-2500/2315.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countAsterisks(self, s: str) -> int: 3 | res = 0 4 | nt = 0 5 | for c in s: 6 | if c=="|": 7 | nt+=1 8 | elif nt%2==0: 9 | res += c=="*" 10 | return res 11 | 12 | 13 | 14 | class Solution: 15 | def countAsterisks(self, s: str) -> int: 16 | l = s.split("|") 17 | res = 0 18 | for a in l[0::2]: 19 | res += a.count("*") 20 | return res 21 | -------------------------------------------------------------------------------- /501-1000/944.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Delete Columns to Make Sorted 3 | ''' 4 | 5 | class Solution(object): 6 | def minDeletionSize(self, arr): 7 | """ 8 | :type strs: List[str] 9 | :rtype: int 10 | """ 11 | count = 0 12 | for i in range(len(arr[0])): 13 | j = 0 14 | while j arr[j+1][i]: 16 | count+=1 17 | break 18 | j+=1 19 | return count 20 | -------------------------------------------------------------------------------- /001-500/389.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findTheDifference(self, s: str, t: str) -> str: 3 | x = 0 4 | for c in s: 5 | x += ord(c) 6 | y = 0 7 | for c in t: 8 | y += ord(c) 9 | 10 | return chr(abs(x-y)) 11 | 12 | 13 | 14 | class Solution: 15 | def findTheDifference(self, s: str, t: str) -> str: 16 | x = 0 17 | for c in s: 18 | x ^= ord(c) 19 | for c in t: 20 | x ^= ord(c) 21 | return chr(x) 22 | -------------------------------------------------------------------------------- /501-1000/896.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isMonotonic(self, nums: List[int]) -> bool: 3 | if len(nums)<=2: 4 | return True 5 | 6 | isGreat = False 7 | isLess = False 8 | for i in range(1,len(nums)): 9 | if nums[i]nums[i-1]: 12 | isLess = True 13 | if isGreat and isLess: 14 | return False 15 | 16 | return True 17 | 18 | -------------------------------------------------------------------------------- /001-500/171.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def titleToNumber(self, columnTitle: str) -> int: 3 | res = 0 4 | for i,c in enumerate(reversed(columnTitle)): 5 | res += (26**i) * (ord(c) - ord('A') + 1) 6 | return res 7 | 8 | 9 | class Solution: 10 | def titleToNumber(self, columnTitle: str) -> int: 11 | res,count = 0,len(columnTitle)-1 12 | for c in columnTitle: 13 | res += (26**count) * (ord(c) - ord('A') + 1) 14 | count-=1 15 | return res 16 | -------------------------------------------------------------------------------- /2001-2500/2006.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def countKDifference(self, nums, k): 3 | """ 4 | :type nums: List[int] 5 | :type k: int 6 | :rtype: int 7 | """ 8 | count=0 9 | m = {} 10 | 11 | for num in nums: 12 | if num in m: 13 | m[num]+=1 14 | else: 15 | m[num]=1 16 | 17 | for num in nums: 18 | if num+k in nums: 19 | count+=m[num+k] 20 | 21 | return count 22 | -------------------------------------------------------------------------------- /2001-2500/2424.py: -------------------------------------------------------------------------------- 1 | class LUPrefix: 2 | 3 | def __init__(self, n: int): 4 | self.l = 0 5 | self.videos = set() 6 | 7 | def upload(self, video: int) -> None: 8 | self.videos.add(video) 9 | while self.l+1 in self.videos: 10 | self.l += 1 11 | 12 | def longest(self) -> int: 13 | return self.l 14 | 15 | 16 | 17 | # Your LUPrefix object will be instantiated and called as such: 18 | # obj = LUPrefix(n) 19 | # obj.upload(video) 20 | # param_2 = obj.longest() 21 | -------------------------------------------------------------------------------- /001-500/228.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def summaryRanges(self, nums: List[int]) -> List[str]: 3 | res = [] 4 | i = 0 5 | while i" + str(end)) 17 | i+=1 18 | 19 | return res 20 | -------------------------------------------------------------------------------- /001-500/350.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: 3 | nums1.sort() 4 | nums2.sort() 5 | res = [] 6 | i = j = 0 7 | while i nums2[j]: 11 | j+=1 12 | else: 13 | res.append(nums1[i]) 14 | i+=1 15 | j+=1 16 | return res 17 | 18 | -------------------------------------------------------------------------------- /001-500/226.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: 9 | if not root: 10 | return None 11 | self.invertTree(root.left) 12 | self.invertTree(root.right) 13 | root.left,root.right = root.right,root.left 14 | return root 15 | -------------------------------------------------------------------------------- /1501-2000/1822.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def arraySign(self, nums: List[int]) -> int: 3 | c = 0 4 | for num in nums: 5 | if num==0: return 0 6 | elif num<0: c+=1 7 | return 1 if not c%2 else -1 8 | 9 | 10 | class Solution: 11 | def arraySign(self, nums: List[int]) -> int: 12 | p = 1 13 | for num in nums: 14 | p *= num 15 | if p>0: 16 | return 1 17 | elif p<0: 18 | return -1 19 | else: 20 | return 0 21 | -------------------------------------------------------------------------------- /501-1000/931.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minFallingPathSum(self, arr: List[List[int]]) -> int: 3 | for i in range(1,len(arr)): 4 | for j in range(len(arr[0])): 5 | if j==0: 6 | arr[i][j] += min([arr[i-1][j+1], arr[i-1][j]]) 7 | elif j==len(arr[0])-1: 8 | arr[i][j] += min([arr[i-1][j-1], arr[i-1][j]]) 9 | else: 10 | arr[i][j] += min([arr[i-1][j-1], arr[i-1][j], arr[i-1][j+1]]) 11 | return min(arr[-1]) 12 | -------------------------------------------------------------------------------- /001-500/446.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numberOfArithmeticSlices(self, nums: List[int]) -> int: 3 | n = len(nums) 4 | total_count = 0 5 | dp = [defaultdict(int) for _ in range(n)] 6 | 7 | for i in range(1, n): 8 | for j in range(i): 9 | diff = nums[i] - nums[j] 10 | dp[i][diff] += 1 11 | if diff in dp[j]: 12 | dp[i][diff] += dp[j][diff] 13 | total_count += dp[j][diff] 14 | 15 | return total_count 16 | -------------------------------------------------------------------------------- /501-1000/844.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def backspaceCompare(self, s: str, t: str) -> bool: 3 | stk1 = [] 4 | stk2 = [] 5 | 6 | for c in s: 7 | if c=="#": 8 | if len(stk1): 9 | stk1.pop() 10 | else: 11 | stk1.append(c) 12 | 13 | for c in t: 14 | if c=="#": 15 | if len(stk2): 16 | stk2.pop() 17 | else: 18 | stk2.append(c) 19 | 20 | return stk1==stk2 21 | -------------------------------------------------------------------------------- /1501-2000/1672.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maximumWealth(self, accounts): 3 | """ 4 | :type accounts: List[List[int]] 5 | :rtype: int 6 | """ 7 | m = 0 8 | for i in accounts: 9 | m = max(m,sum(i)) 10 | 11 | return m 12 | 13 | 14 | 15 | class Solution(object): 16 | def maximumWealth(self, accounts): 17 | """ 18 | :type accounts: List[List[int]] 19 | :rtype: int 20 | """ 21 | return max(map(sum,accounts)) 22 | -------------------------------------------------------------------------------- /1501-2000/1678.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def interpret(self, command: str) -> str: 3 | d = {"G":"G","()":"o","(al)":"al"} 4 | 5 | t = "" 6 | res = "" 7 | 8 | for i in range(len(command)): 9 | t += command[i] 10 | if t in d: 11 | res += d[t] 12 | t = "" 13 | 14 | return res 15 | 16 | 17 | class Solution: 18 | def interpret(self, command: str) -> str: 19 | return command.replace("()","o").replace("(al)","al") 20 | 21 | -------------------------------------------------------------------------------- /001-500/035.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def searchInsert(self, nums, target): 3 | """ 4 | :type nums: List[int] 5 | :type target: int 6 | :rtype: int 7 | """ 8 | low = 0 9 | high = len(nums)-1 10 | 11 | while low<=high: 12 | mid = (high+low)//2 13 | if nums[mid]==target: 14 | return mid 15 | elif nums[mid]>target: 16 | high = mid-1 17 | else: 18 | low = mid+1 19 | 20 | return low 21 | -------------------------------------------------------------------------------- /2001-2500/2497.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maximumValue(self, strs): 3 | """ 4 | :type strs: List[str] 5 | :rtype: int 6 | """ 7 | m = 0 8 | 9 | for x in strs: 10 | if x.isdigit(): 11 | if int(x)>m: 12 | m = int(x) 13 | 14 | elif x.isalpha(): 15 | if len(x)>m: 16 | m=len(x) 17 | 18 | else: 19 | if len(x)>m: 20 | m=len(x) 21 | 22 | return m 23 | -------------------------------------------------------------------------------- /001-500/202.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isHappy(self, n: int) -> bool: 3 | seen = set() 4 | while n!=1: 5 | n = sum(int(x)**2 for x in str(n)) 6 | if n in seen: 7 | return False 8 | seen.add(n) 9 | 10 | return True 11 | 12 | 13 | class Solution: 14 | def isHappy(self, n: int) -> bool: 15 | seen = set() 16 | while n not in seen: 17 | seen.add(n) 18 | n = sum(int(x)**2 for x in str(n)) 19 | 20 | return n==1 21 | -------------------------------------------------------------------------------- /1001-1500/1108.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def defangIPaddr(self, address: str) -> str: 3 | res = "" 4 | for i in address: 5 | if i==".": 6 | res += "[.]" 7 | else: 8 | res += i 9 | return res 10 | 11 | 12 | class Solution: 13 | def defangIPaddr(self, address: str) -> str: 14 | return "[.]".join(address.split(".")) 15 | 16 | 17 | class Solution: 18 | def defangIPaddr(self, address: str) -> str: 19 | l = address.split(".") 20 | return "[.]".join(l) 21 | -------------------------------------------------------------------------------- /501-1000/876.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: 8 | temp = head 9 | count=0 10 | while temp: 11 | temp=temp.next 12 | count+=1 13 | count//=2 14 | temp = head 15 | while count!=0: 16 | temp=temp.next 17 | count-=1 18 | return temp 19 | -------------------------------------------------------------------------------- /001-500/053.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSubArray(self, nums: List[int]) -> int: 3 | dp = [0]*len(nums) 4 | for idx,num in enumerate(nums): 5 | dp[idx] = max(dp[idx-1]+num, num) 6 | return max(dp) 7 | 8 | 9 | class Solution: 10 | def maxSubArray(self, nums: List[int]) -> int: 11 | curSum = 0 12 | maxSum = nums[0] 13 | for num in nums: 14 | if curSum<0: 15 | curSum = 0 16 | curSum+=num 17 | maxSum = max(curSum,maxSum) 18 | return maxSum 19 | -------------------------------------------------------------------------------- /001-500/118.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generate(self, numRows: int) -> List[List[int]]: 3 | res = [[1]*i for i in range(1,numRows+1)] 4 | 5 | for i in range(2,numRows): 6 | for j in range(1,i): 7 | res[i][j]=res[i-1][j]+res[i-1][j-1] 8 | 9 | return res 10 | 11 | 12 | class Solution: 13 | def generate(self, numRows: int) -> List[List[int]]: 14 | res = [[1]] 15 | for _ in range(numRows): 16 | res.append(list(map(add, res[-1]+[0], [0]+res[-1]))) 17 | return res[:numRows] 18 | -------------------------------------------------------------------------------- /001-500/135.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def candy(self, ratings: List[int]) -> int: 3 | rtl = [1]*len(ratings) 4 | ltr = [1]*len(ratings) 5 | 6 | for i in range(1,len(ratings)): 7 | if ratings[i-1] bool: 3 | left, right = 1, num 4 | while left <= right: 5 | mid = (left + right) // 2 6 | if mid * mid == num: 7 | return True 8 | elif mid * mid < num: 9 | left = mid + 1 10 | else: 11 | right = mid - 1 12 | return False 13 | 14 | 15 | 16 | class Solution: 17 | def isPerfectSquare(self, num: int) -> bool: 18 | return (int(num**0.5) * int(num**0.5)) == num 19 | -------------------------------------------------------------------------------- /2501-3000/2610.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | class Solution: 4 | def findMatrix(self, nums: List[int]) -> List[List[int]]: 5 | d = defaultdict(int) 6 | for num in nums: 7 | d[num]+=1 8 | res = [] 9 | while d: 10 | row = [] 11 | keys = list(d.keys()) 12 | for k in keys: 13 | row.append(k) 14 | d[k]-=1 15 | if d[k]==0: 16 | del d[k] 17 | res.append(row) 18 | return res 19 | 20 | -------------------------------------------------------------------------------- /001-500/258.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addDigits(self, num: int) -> int: 3 | while len(str(num))!=1: 4 | res = 0 5 | while num!=0: 6 | num,c=divmod(num,10) 7 | res+=c 8 | num = res 9 | return num 10 | 11 | 12 | 13 | class Solution: 14 | def addDigits(self, num: int) -> int: 15 | s = str(num) 16 | while len(s)!=1: 17 | res = 0 18 | for n in s: 19 | res+=int(n) 20 | s = str(res) 21 | return int(s) 22 | -------------------------------------------------------------------------------- /501-1000/589.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Definition for a Node. 3 | class Node: 4 | def __init__(self, val=None, children=None): 5 | self.val = val 6 | self.children = children 7 | """ 8 | 9 | class Solution: 10 | def preorder(self, root: 'Node') -> List[int]: 11 | def dfs(root,res): 12 | if not root: 13 | return 14 | res.append(root.val) 15 | for child in root.children: 16 | dfs(child, res) 17 | res = [] 18 | dfs(root, res) 19 | return res 20 | 21 | 22 | -------------------------------------------------------------------------------- /501-1000/841.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: 3 | n = len(rooms) 4 | visited = set() 5 | 6 | stack = [0] 7 | while stack: 8 | node = stack.pop() 9 | if node in visited: continue 10 | 11 | visited.add(node) 12 | if len(visited)==n: 13 | return True 14 | 15 | for child in rooms[node]: 16 | if child not in visited: 17 | stack.append(child) 18 | 19 | return False 20 | -------------------------------------------------------------------------------- /501-1000/705.py: -------------------------------------------------------------------------------- 1 | class MyHashSet: 2 | 3 | def __init__(self): 4 | self.hashset = set() 5 | 6 | def add(self, key: int) -> None: 7 | self.hashset.add(key) 8 | 9 | def remove(self, key: int) -> None: 10 | if key in self.hashset: 11 | self.hashset.remove(key) 12 | 13 | def contains(self, key: int) -> bool: 14 | return key in self.hashset 15 | 16 | 17 | # Your MyHashSet object will be instantiated and called as such: 18 | # obj = MyHashSet() 19 | # obj.add(key) 20 | # obj.remove(key) 21 | # param_3 = obj.contains(key) 22 | -------------------------------------------------------------------------------- /001-500/024.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: 8 | dummy = ListNode(-1) 9 | dummy.next = head 10 | pre = dummy 11 | while pre.next and pre.next.next: 12 | a = pre.next 13 | b = pre.next.next 14 | pre.next,b.next,a.next=b,a,b.next 15 | pre = a 16 | return dummy.next 17 | -------------------------------------------------------------------------------- /001-500/073.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def setZeroes(self, matrix: List[List[int]]) -> None: 3 | """ 4 | Do not return anything, modify matrix in-place instead. 5 | """ 6 | m = set() 7 | for i in range(len(matrix)): 8 | for j in range(len(matrix[0])): 9 | if matrix[i][j]==0: 10 | m.add((i,j)) 11 | for r,c in m: 12 | for i in range(len(matrix[0])): 13 | matrix[r][i]=0 14 | for j in range(len(matrix)): 15 | matrix[j][c]=0 16 | 17 | -------------------------------------------------------------------------------- /1001-1500/1304.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def sumZero(self, n): 3 | """ 4 | :type n: int 5 | :rtype: List[int] 6 | """ 7 | res = [0 for _ in range(n)] 8 | 9 | l,h=0,n-1 10 | while l TreeNode: 10 | if not original: 11 | return None 12 | if original is target: 13 | return cloned 14 | return self.getTargetCopy(original.left,cloned.left,target) or self.getTargetCopy(original.right,cloned.right,target) 15 | 16 | -------------------------------------------------------------------------------- /501-1000/804.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def uniqueMorseRepresentations(self, words): 3 | """ 4 | :type words: List[str] 5 | :rtype: int 6 | """ 7 | l = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] 8 | o = [] 9 | for word in words: 10 | for char in word: 11 | word = word.replace(char,l[ord(char)-97]) 12 | o.append(word) 13 | return set(o).__len__() 14 | 15 | -------------------------------------------------------------------------------- /001-500/017.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def letterCombinations(self, digits: str) -> List[str]: 3 | dic = { "2": "abc", "3": "def", "4":"ghi", "5":"jkl", "6":"mno", "7":"pqrs", "8":"tuv", "9":"wxyz"} 4 | res = [] 5 | if len(digits)==0: 6 | return res 7 | self.dfs(digits,0,dic,'', res) 8 | return res 9 | 10 | def dfs(self,digits,index,dic,path,res): 11 | if index>=len(digits): 12 | res.append(path) 13 | return 14 | s = dic[digits[index]] 15 | for c in s: 16 | self.dfs(digits,index+1,dic,path+c,res) 17 | -------------------------------------------------------------------------------- /1001-1500/1235.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: 3 | ind = 0 4 | for e, s, p in sorted(zip(endTime, startTime, profit)): 5 | startTime[ind] = s 6 | endTime[ind] = e 7 | profit[ind] = p 8 | ind += 1 9 | 10 | for i in range(1, len(profit)): 11 | 12 | index = bisect_right(endTime, startTime[i]) - 1 13 | profit[i] = max(profit[i - 1], (profit[index] if index >= 0 else 0) + profit[i]) 14 | 15 | return profit[-1] 16 | -------------------------------------------------------------------------------- /501-1000/700.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: 9 | if not root: 10 | return None 11 | if root.val==val: 12 | return root 13 | elif root.val<=val: 14 | return self.searchBST(root.right, val) 15 | else: 16 | return self.searchBST(root.left,val) 17 | -------------------------------------------------------------------------------- /001-500/203.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]: 8 | dummy = ListNode(-1) 9 | dummy.next = head 10 | cur = dummy 11 | prev = None 12 | while cur: 13 | if cur.val==val: 14 | prev.next = cur.next 15 | else: 16 | prev = cur 17 | cur = cur.next 18 | return dummy.next 19 | -------------------------------------------------------------------------------- /1501-2000/1657.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def closeStrings(self, word1: str, word2: str) -> bool: 3 | if set(word1)!=set(word2): 4 | return False 5 | d1, d2 = defaultdict(int), defaultdict(int) 6 | for c in word1: 7 | d1[c]+=1 8 | for c in word2: 9 | d2[c]+=1 10 | return sorted(d1.values())==sorted(d2.values()) 11 | 12 | class Solution: 13 | def closeStrings(self, word1: str, word2: str) -> bool: 14 | return set(word1) == set(word2) and Counter(Counter(word1).values()) == Counter(Counter(word2).values()) 15 | 16 | -------------------------------------------------------------------------------- /1001-1500/1457.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def pseudoPalindromicPaths (self, root: Optional[TreeNode], cnt=0) -> int: 9 | if not root: return 0 10 | cnt ^= 1<<(root.val-1) 11 | if root.left is None and root.right is None: 12 | return 1 if cnt & (cnt-1) == 0 else 0 13 | return self.pseudoPalindromicPaths(root.left, cnt) + self.pseudoPalindromicPaths(root.right, cnt) 14 | -------------------------------------------------------------------------------- /501-1000/563.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def findTilt(self, root: Optional[TreeNode]) -> int: 9 | def helper(root): 10 | if not root: 11 | return 0 12 | l,r = helper(root.left),helper(root.right) 13 | self.ans += abs(l-r) 14 | return root.val + l + r 15 | self.ans = 0 16 | helper(root) 17 | return self.ans 18 | 19 | -------------------------------------------------------------------------------- /001-500/230.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: 9 | res = [] 10 | def inorder(node): 11 | if not node: return 12 | inorder(node.left) 13 | if len(res)==k: 14 | return 15 | res.append(node.val) 16 | inorder(node.right) 17 | inorder(root) 18 | return res[-1] 19 | -------------------------------------------------------------------------------- /1501-2000/1603.py: -------------------------------------------------------------------------------- 1 | class ParkingSystem: 2 | 3 | def __init__(self, big: int, medium: int, small: int): 4 | self.big = big 5 | self.small = small 6 | self.medium = medium 7 | self.arr = [self.big, self.medium, self.small] 8 | 9 | def addCar(self, carType: int) -> bool: 10 | if self.arr[carType-1]>0: 11 | self.arr[carType-1]-=1 12 | return True 13 | else: 14 | return False 15 | 16 | 17 | # Your ParkingSystem object will be instantiated and called as such: 18 | # obj = ParkingSystem(big, medium, small) 19 | # param_1 = obj.addCar(carType) 20 | -------------------------------------------------------------------------------- /1001-1500/1290.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def getDecimalValue(self, head: ListNode) -> int: 8 | temp = head 9 | count = 0 10 | while temp: 11 | temp=temp.next 12 | count+=1 13 | temp = head 14 | count-=1 15 | val = 0 16 | while count>=0: 17 | if temp.val==1: 18 | val += (2**count) 19 | count-=1 20 | temp=temp.next 21 | return val 22 | -------------------------------------------------------------------------------- /1501-2000/1656.py: -------------------------------------------------------------------------------- 1 | class OrderedStream: 2 | 3 | def __init__(self, n: int): 4 | self.data = [None]*n 5 | self.ptr = 0 6 | 7 | def insert(self, idKey: int, value: str) -> List[str]: 8 | idKey-=1 9 | self.data[idKey]=value 10 | 11 | if idKey>self.ptr: 12 | return [] 13 | 14 | while self.ptr < len(self.data) and self.data[self.ptr]: 15 | self.ptr+=1 16 | return self.data[idKey:self.ptr] 17 | 18 | 19 | # Your OrderedStream object will be instantiated and called as such: 20 | # obj = OrderedStream(n) 21 | # param_1 = obj.insert(idKey,value) 22 | -------------------------------------------------------------------------------- /2001-2500/2331.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def evaluateTree(self, root: Optional[TreeNode]) -> bool: 9 | if root.val==0 or root.val==1: 10 | return root.val 11 | elif root.val==2: 12 | return self.evaluateTree(root.left) or self.evaluateTree(root.right) 13 | elif root.val==3: 14 | return self.evaluateTree(root.left) and self.evaluateTree(root.right) 15 | 16 | -------------------------------------------------------------------------------- /2001-2500/2442.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countDistinctIntegers(self, nums: List[int]) -> int: 3 | def reverseInteger(n): 4 | r = 0 5 | while n>0: 6 | r = 10*r + n%10 7 | n //= 10 8 | return r 9 | s = set(nums) 10 | for n in nums: 11 | s.add(reverseInteger(n)) 12 | return len(s) 13 | 14 | 15 | class Solution: 16 | def countDistinctIntegers(self, nums: List[int]) -> int: 17 | s = set(nums) 18 | for n in nums: 19 | s.add(int(str(n)[::-1])) 20 | return len(s) 21 | 22 | -------------------------------------------------------------------------------- /001-500/033.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def search(self, nums: List[int], target: int) -> int: 3 | l,r = 0,len(nums)-1 4 | while l<=r: 5 | m = (l+r)>>1 6 | if nums[m]==target: 7 | return m 8 | 9 | if nums[l]<=nums[m]: 10 | if target>nums[m] or targetnums[r]: 16 | r = m - 1 17 | else: 18 | l = m + 1 19 | return -1 20 | -------------------------------------------------------------------------------- /001-500/098.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def isValidBST(self, root: Optional[TreeNode]) -> bool: 9 | 10 | def inorder(root): 11 | return inorder(root.left) + [root.val] + inorder(root.right) if root else [] 12 | 13 | arr = inorder(root) 14 | 15 | for i in range(1,len(arr)): 16 | if arr[i-1]>=arr[i]: 17 | return False 18 | 19 | return True 20 | 21 | 22 | -------------------------------------------------------------------------------- /001-500/404.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int: 9 | if not root: 10 | return 0 11 | if root.left and not root.left.left and not root.left.right: 12 | return root.left.val + self.sumOfLeftLeaves(root.right) 13 | else: 14 | return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right) 15 | 16 | 17 | -------------------------------------------------------------------------------- /001-500/016.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def threeSumClosest(self, nums: List[int], target: int) -> int: 3 | nums.sort() 4 | res = nums[0]+nums[1]+nums[2] 5 | for i in range(len(nums)): 6 | s,e=i+1,len(nums)-1 7 | while starget: 16 | e-=1 17 | 18 | return res 19 | -------------------------------------------------------------------------------- /001-500/049.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | class Solution: 3 | def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 4 | ans = defaultdict(list) 5 | for s in strs: 6 | ans[tuple(sorted(s))].append(s) 7 | return list(ans.values()) 8 | 9 | 10 | class Solution: 11 | def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 12 | ans = {} 13 | 14 | for s in strs: 15 | if tuple(sorted(s)) in ans: 16 | ans[tuple(sorted(s))].append(s) 17 | else: 18 | ans[tuple(sorted(s))] = [s] 19 | return list(ans.values()) 20 | -------------------------------------------------------------------------------- /001-500/105.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: 9 | if not inorder: 10 | return None 11 | root = TreeNode(preorder[0]) 12 | mid = inorder.index(root.val) 13 | root.left = self.buildTree(preorder[1:mid+1], inorder[:mid]) 14 | root.right = self.buildTree(preorder[mid+1:], inorder[mid+1:]) 15 | return root 16 | -------------------------------------------------------------------------------- /001-500/106.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]: 9 | if not inorder: 10 | return None 11 | root = TreeNode(postorder.pop()) 12 | mid = inorder.index(root.val) 13 | root.left = self.buildTree(inorder[:mid], postorder[:mid]) 14 | root.right = self.buildTree(inorder[mid+1:], postorder[mid:]) 15 | return root 16 | -------------------------------------------------------------------------------- /001-500/405.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def toHex(self, num: int) -> str: 3 | if num==0: return '0' 4 | mp = '0123456789abcdef' 5 | ans = '' 6 | for i in range(8): 7 | n = num & 15 8 | c = mp[n] 9 | ans = c + ans 10 | num = num >> 4 11 | return ans.lstrip('0') 12 | 13 | 14 | class Solution: 15 | def toHex(self, num: int) -> str: 16 | s, res, num = '0123456789abcdef', '', num & 0xFFFFFFFF 17 | while num: 18 | res += s[num % 16] 19 | num >>= 4 20 | return res[::-1] or '0' 21 | 22 | 23 | -------------------------------------------------------------------------------- /1001-1500/1022.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def sumRootToLeaf(self, root: Optional[TreeNode]) -> int: 9 | def dfs(node,path): 10 | if not node: 11 | return 0 12 | path = (path<<1)+node.val 13 | if not node.left and not node.right: 14 | return path 15 | else: 16 | return dfs(node.left, path) + dfs(node.right, path) 17 | return dfs(root,0) 18 | -------------------------------------------------------------------------------- /1501-2000/1528.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def restoreString(self, s, indices): 3 | """ 4 | :type s: str 5 | :type indices: List[int] 6 | :rtype: str 7 | """ 8 | return "".join([x for (_,x) in sorted(zip(indices,s))]) 9 | 10 | 11 | class Solution(object): 12 | def restoreString(self, s, indices): 13 | """ 14 | :type s: str 15 | :type indices: List[int] 16 | :rtype: str 17 | """ 18 | l = [0 for _ in range(len(s))] 19 | 20 | for i in range(len(indices)): 21 | l[indices[i]]=s[i] 22 | 23 | return "".join(l) 24 | -------------------------------------------------------------------------------- /1001-1500/1325.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]: 9 | if not root: 10 | return None 11 | root.left = self.removeLeafNodes(root.left, target) 12 | root.right = self.removeLeafNodes(root.right, target) 13 | if not root.left and not root.right and root.val==target: 14 | root = None 15 | return root 16 | 17 | -------------------------------------------------------------------------------- /001-500/100.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: 9 | if p is None and q is None: 10 | return True 11 | elif p is None or q is None: 12 | return False 13 | else: 14 | if p.val==q.val: 15 | return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right) 16 | else: 17 | return False 18 | -------------------------------------------------------------------------------- /001-500/108.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]: 9 | def recf(nums,start,end): 10 | while start<=end: 11 | mid = (start+end)>>1 12 | node = TreeNode(nums[mid]) 13 | node.left = recf(nums, start, mid-1) 14 | node.right = recf(nums, mid+1, end) 15 | return node 16 | return recf(nums,0,len(nums)-1) 17 | -------------------------------------------------------------------------------- /2001-2500/2405.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def partitionString(self, s: str) -> int: 3 | seen = "" 4 | res = 1 5 | for c in s: 6 | if c in seen: 7 | res += 1 8 | seen = "" 9 | seen += c 10 | 11 | return res 12 | 13 | 14 | 15 | class Solution: 16 | def partitionString(self, s: str) -> int: 17 | i = 0 18 | seen = "" 19 | c = 0 20 | while i bool: 9 | def dfs(root,curSum): 10 | if not root: 11 | return False 12 | 13 | curSum+=root.val 14 | if not root.right and not root.left: 15 | return curSum==targetSum 16 | 17 | return dfs(root.left,curSum) or dfs(root.right,curSum) 18 | 19 | return dfs(root,0) 20 | -------------------------------------------------------------------------------- /2001-2500/2283.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def digitCount(self, num: str) -> bool: 3 | d = {} 4 | for i in range(len(num)): 5 | d[str(i)] = 0 6 | 7 | for i in range(len(num)): 8 | if num[i] in d: 9 | d[num[i]]+=1 10 | 11 | for i in range(len(num)): 12 | if int(num[i])!= d[str(i)]: 13 | return False 14 | 15 | return True 16 | 17 | 18 | class Solution: 19 | def digitCount(self, num: str) -> bool: 20 | for i in range(len(num)): 21 | if num.count(str(i))!=int(num[i]): 22 | return False 23 | return True 24 | -------------------------------------------------------------------------------- /501-1000/938.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int: 9 | if not root: 10 | return 0 11 | elif root.valhigh: 14 | return self.rangeSumBST(root.left,low,high) 15 | else: 16 | return root.val+self.rangeSumBST(root.left,low,high)+self.rangeSumBST(root.right,low,high) 17 | -------------------------------------------------------------------------------- /001-500/034.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchRange(self, nums: List[int], target: int) -> List[int]: 3 | def binSearch(leftBias): 4 | l,h=0,len(nums)-1 5 | index = -1 6 | while l<=h: 7 | m = (l+h)>>1 8 | if nums[m]target: 11 | h = m-1 12 | else: 13 | index = m 14 | if leftBias: 15 | h = m-1 16 | else: 17 | l = m+1 18 | return index 19 | return [binSearch(True), binSearch(False)] 20 | -------------------------------------------------------------------------------- /501-1000/543.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def diameterOfBinaryTree(self, root: TreeNode) -> int: 10 | self.diameter = 0 11 | self.dfs(root) 12 | return self.diameter 13 | 14 | def dfs(self, node): 15 | if node == None: 16 | return 0 17 | left_height = self.dfs(node.left) 18 | right_height = self.dfs(node.right) 19 | self.diameter = max(self.diameter,left_height + right_height ) 20 | return max(left_height,right_height) + 1 21 | -------------------------------------------------------------------------------- /501-1000/617.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]: 9 | if not root1: 10 | return root2 11 | elif not root2: 12 | return root1 13 | else: 14 | ans = TreeNode(root1.val+root2.val) 15 | ans.left = self.mergeTrees(root1.left, root2.left) 16 | ans.right = self.mergeTrees(root1.right, root2.right) 17 | return ans 18 | -------------------------------------------------------------------------------- /001-500/110.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def isBalanced(self, root: Optional[TreeNode]) -> bool: 9 | def helper(root): 10 | if not root: 11 | return True 12 | 13 | left = helper(root.left) 14 | right = helper(root.right) 15 | 16 | if right<0 or left<0 or abs(left-right)>1: 17 | return -1 18 | 19 | return max(left,right)+1 20 | 21 | return helper(root)>=0 22 | 23 | -------------------------------------------------------------------------------- /2001-2500/2114.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def mostWordsFound(self, sentences): 3 | """ 4 | :type sentences: List[str] 5 | :rtype: int 6 | """ 7 | mx = 0 8 | for sentence in sentences: 9 | nw = len(sentence.split()) 10 | if nw>mx: 11 | mx = nw 12 | 13 | return mx 14 | 15 | 16 | 17 | class Solution(object): 18 | def mostWordsFound(self, sentences): 19 | """ 20 | :type sentences: List[str] 21 | :rtype: int 22 | """ 23 | m = 0 24 | for sentence in sentences: 25 | m = max(m,sentence.count(" ")+1) 26 | 27 | return m 28 | -------------------------------------------------------------------------------- /501-1000/658.py: -------------------------------------------------------------------------------- 1 | # Efficient 2 | class Solution: 3 | def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: 4 | left, right = 0, len(arr)-k 5 | while left < right: 6 | mid = (left+right)//2 7 | if x-arr[mid] > arr[mid+k] - x: 8 | left = mid+1 # search right side 9 | else: right = mid # search left side 10 | return arr[left:left+k] 11 | 12 | # Easy 13 | class Solution: 14 | def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: 15 | l = [] 16 | for num in arr: 17 | l.append((abs(num-x), num)) 18 | l.sort() 19 | return sorted([i[1] for i in l[:k]]) 20 | -------------------------------------------------------------------------------- /501-1000/530.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def getMinimumDifference(self, root: Optional[TreeNode]) -> int: 9 | prev,res = None,float('inf') 10 | 11 | def dfs(root): 12 | if not root: 13 | return None 14 | 15 | dfs(root.left) 16 | 17 | nonlocal prev,res 18 | if prev: 19 | res = min(res,root.val-prev.val) 20 | prev = root 21 | 22 | dfs(root.right) 23 | 24 | dfs(root) 25 | return res 26 | -------------------------------------------------------------------------------- /001-500/225.py: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | class MyStack: 4 | 5 | def __init__(self): 6 | self.queue = collections.deque() 7 | 8 | def push(self, x: int) -> None: 9 | q = self.queue 10 | q.append(x) 11 | for _ in range(len(q)-1): 12 | q.append(q.popleft()) 13 | 14 | def pop(self) -> int: 15 | return self.queue.popleft() 16 | 17 | def top(self) -> int: 18 | return self.queue[0] 19 | 20 | def empty(self) -> bool: 21 | return (not len(self.queue)) 22 | 23 | 24 | # Your MyStack object will be instantiated and called as such: 25 | # obj = MyStack() 26 | # obj.push(x) 27 | # param_2 = obj.pop() 28 | # param_3 = obj.top() 29 | # param_4 = obj.empty() 30 | -------------------------------------------------------------------------------- /001-500/222.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def countNodes(self, root: Optional[TreeNode]) -> int: 9 | if not root: 10 | return 0 11 | 12 | l=root 13 | r=root 14 | hl=0 15 | hr=0 16 | 17 | while l: 18 | hl+=1 19 | l=l.left 20 | 21 | while r: 22 | hr+=1 23 | r=r.right 24 | 25 | if hl==hr: 26 | return 2**hl-1 27 | else: 28 | return 1 + self.countNodes(root.left)+self.countNodes(root.right) 29 | -------------------------------------------------------------------------------- /001-500/021.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution(object): 7 | def mergeTwoLists(self, a, b): 8 | """ 9 | :type list1: Optional[ListNode] 10 | :type list2: Optional[ListNode] 11 | :rtype: Optional[ListNode] 12 | """ 13 | dummy = temp = ListNode() 14 | while a and b: 15 | if a.val Optional[ListNode]: 8 | temp = head 9 | c = 1 10 | left,right=None,None 11 | n = 0 12 | while temp: 13 | if n==k-1: 14 | left = temp 15 | temp=temp.next 16 | n+=1 17 | temp = head 18 | while temp: 19 | if c==n-k+1: 20 | right = temp 21 | temp = temp.next 22 | c+=1 23 | left.val,right.val=right.val,left.val 24 | return head 25 | -------------------------------------------------------------------------------- /2001-2500/2341.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numberOfPairs(self, nums: List[int]) -> List[int]: 3 | counter=collections.Counter(nums) 4 | ans1=ans2=0 5 | for k,v in counter.items(): 6 | ans1+=v//2 7 | ans2+=v%2 8 | return [ans1, ans2] 9 | 10 | 11 | class Solution: 12 | def numberOfPairs(self, nums: List[int]) -> List[int]: 13 | d = {} 14 | ans = [0,0] 15 | for num in nums: 16 | if num in d: 17 | d[num]+=1 18 | if d[num]>1: 19 | ans[0]+=d[num]//2 20 | d[num]%=2 21 | else: 22 | d[num]=1 23 | for k,v in d.items(): 24 | ans[1]+=v 25 | return ans 26 | -------------------------------------------------------------------------------- /2001-2500/2500.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def deleteGreatestValue(self, grid: List[List[int]]) -> int: 3 | i,res,curMax=0,0,0 4 | while True: 5 | if len(grid[i])==0: 6 | break 7 | grid[i].sort() 8 | curMax = max(curMax,grid[i][-1]) 9 | grid[i].pop() 10 | i+=1 11 | if i==len(grid): 12 | res+=curMax 13 | curMax,i=0,0 14 | return res 15 | 16 | 17 | class Solution: 18 | def deleteGreatestValue(self, grid: List[List[int]]) -> int: 19 | for i in range(len(grid)): 20 | grid[i].sort() 21 | 22 | grid = list(zip(*grid)) 23 | 24 | return sum(max(row) for row in grid) 25 | 26 | -------------------------------------------------------------------------------- /501-1000/599.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findRestaurant(self, list1, list2): 3 | """ 4 | :type list1: List[str] 5 | :type list2: List[str] 6 | :rtype: List[str] 7 | """ 8 | res = [] 9 | small = float("inf") 10 | d = {} 11 | 12 | for i in range(len(list1)): 13 | if list1[i] in list2: 14 | d[list1[i]] = i 15 | 16 | for i in range(len(list2)): 17 | if list2[i] in d.keys(): 18 | d[list2[i]]+=i 19 | if d[list2[i]] str: 9 | if root is None: 10 | return '' 11 | s = str(root.val) 12 | if root.left is None and root.right is None: 13 | s += '' 14 | if root.left: 15 | s += '({})'.format(self.tree2str(root.left)) 16 | if root.left is None and root.right: 17 | s += '()' 18 | if root.right: 19 | s+= '({})'.format(self.tree2str(root.right)) 20 | return s 21 | 22 | -------------------------------------------------------------------------------- /001-500/155.py: -------------------------------------------------------------------------------- 1 | class MinStack: 2 | 3 | def __init__(self): 4 | self.minStack = [] 5 | self.stack = [] 6 | 7 | def push(self, val: int) -> None: 8 | self.stack.append(val) 9 | if self.minStack: 10 | val = min(self.minStack[-1],val) 11 | self.minStack.append(val) 12 | 13 | def pop(self) -> None: 14 | self.stack.pop() 15 | self.minStack.pop() 16 | 17 | 18 | def top(self) -> int: 19 | return self.stack[-1] 20 | 21 | def getMin(self) -> int: 22 | return self.minStack[-1] 23 | 24 | 25 | # Your MinStack object will be instantiated and called as such: 26 | # obj = MinStack() 27 | # obj.push(val) 28 | # obj.pop() 29 | # param_3 = obj.top() 30 | # param_4 = obj.getMin() 31 | -------------------------------------------------------------------------------- /1501-2000/1544.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def makeGood(self, s: str) -> str: 3 | stk = [] 4 | for c in s: 5 | if stk: 6 | if abs(ord(stk[-1])-ord(c))==32: 7 | stk.pop() 8 | else: 9 | stk.append(c) 10 | else: 11 | stk.append(c) 12 | 13 | return "".join(stk) 14 | 15 | 16 | class Solution: 17 | def makeGood(self, s: str) -> str: 18 | stk = [] 19 | for c in s: 20 | if c.isupper() and stk and stk[-1]==c.lower(): 21 | stk.pop() 22 | elif c.islower() and stk and stk[-1]==c.upper(): 23 | stk.pop() 24 | else: 25 | stk.append(c) 26 | 27 | return "".join(stk) 28 | -------------------------------------------------------------------------------- /2501-3000/2807.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def insertGreatestCommonDivisors(self, head: Optional[ListNode]) -> Optional[ListNode]: 8 | def gcd(a,b): 9 | if b==0: 10 | return a 11 | return gcd(b,a%b) 12 | 13 | dummy = ListNode(next=head) 14 | prev = dummy 15 | cur = dummy.next 16 | 17 | while cur: 18 | midNode = ListNode(val=math.gcd(prev.val,cur.val), next=prev.next) 19 | prev.next = midNode 20 | prev = cur 21 | cur = cur.next 22 | 23 | return dummy.next.next 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /001-500/232.py: -------------------------------------------------------------------------------- 1 | class MyQueue: 2 | 3 | def __init__(self): 4 | self.inStack, self.outStack = [], [] 5 | 6 | def push(self, x: int) -> None: 7 | self.inStack.append(x) 8 | 9 | def pop(self) -> int: 10 | self.peek() 11 | return self.outStack.pop() 12 | 13 | def peek(self) -> int: 14 | if not self.outStack: 15 | while self.inStack: 16 | self.outStack.append(self.inStack.pop()) 17 | return self.outStack[-1] 18 | 19 | def empty(self) -> bool: 20 | return (not self.inStack) and (not self.outStack) 21 | 22 | 23 | # Your MyQueue object will be instantiated and called as such: 24 | # obj = MyQueue() 25 | # obj.push(x) 26 | # param_2 = obj.pop() 27 | # param_3 = obj.peek() 28 | # param_4 = obj.empty() 29 | -------------------------------------------------------------------------------- /1001-1500/1074.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int: 3 | m, n = len(matrix), len(matrix[0]) 4 | for row in range(m): 5 | for col in range(1, n): 6 | matrix[row][col] += matrix[row][col - 1] 7 | 8 | count = 0 9 | for c1 in range(n): 10 | for c2 in range(c1, n): 11 | prefix_sum_map = {0: 1} 12 | sum_val = 0 13 | 14 | for row in range(m): 15 | sum_val += matrix[row][c2] - (matrix[row][c1 - 1] if c1 > 0 else 0) 16 | count += prefix_sum_map.get(sum_val - target, 0) 17 | prefix_sum_map[sum_val] = prefix_sum_map.get(sum_val, 0) + 1 18 | 19 | return count 20 | -------------------------------------------------------------------------------- /1501-2000/1704.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def halvesAreAlike(self, s: str) -> bool: 3 | v = "aeiouAEIOU" 4 | count = 0 5 | for i in range(len(s)): 6 | if s[i] in v: 7 | if i<=len(s)//2-1: 8 | count += 1 9 | else: 10 | count -= 1 11 | 12 | return count==0 13 | 14 | 15 | class Solution: 16 | def halvesAreAlike(self, s: str) -> bool: 17 | def is_vowel(x): 18 | v = "aeiouAEIOU" 19 | return x in v 20 | 21 | c = 0 22 | for i in range(len(s)//2): 23 | if is_vowel(s[i]): 24 | c+=1 25 | if is_vowel(s[len(s)-i-1]): 26 | c-=1 27 | 28 | return c==0 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /501-1000/567.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | class Solution: 4 | def checkInclusion(self, s1: str, s2: str) -> bool: 5 | d1 = defaultdict(int) 6 | d2 = defaultdict(int) 7 | for c in s1: 8 | d1[c]+=1 9 | 10 | for c in s2[:len(s1)]: 11 | d2[c]+=1 12 | 13 | left = 0 14 | for right in range(len(s1),len(s2)): 15 | if d1.items()==d2.items(): 16 | return True 17 | if d2[s2[left]]==1: 18 | del d2[s2[left]] 19 | else: 20 | d2[s2[left]]-=1 21 | d2[s2[right]]+=1 22 | left += 1 23 | 24 | if d1.items()==d2.items(): 25 | return True 26 | 27 | return False 28 | 29 | -------------------------------------------------------------------------------- /001-500/257.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]: 9 | res = [] 10 | def dfs(root, path): 11 | if not root: 12 | return [] 13 | 14 | path+=str(root.val) + "->" 15 | if not root.right and not root.left: 16 | if len(path)==1: 17 | res.append(path) 18 | else: 19 | res.append(path[:-2]) 20 | 21 | dfs(root.left,path) 22 | dfs(root.right,path) 23 | 24 | dfs(root,"") 25 | return res 26 | -------------------------------------------------------------------------------- /1001-1500/1115.py: -------------------------------------------------------------------------------- 1 | from threading import Lock 2 | 3 | 4 | class FooBar: 5 | def __init__(self, n): 6 | self.n = n 7 | self.fl = Lock() 8 | self.bl = Lock() 9 | self.bl.acquire() 10 | 11 | 12 | def foo(self, printFoo: 'Callable[[], None]') -> None: 13 | 14 | for i in range(self.n): 15 | self.fl.acquire() 16 | # printFoo() outputs "foo". Do not change or remove this line. 17 | printFoo() 18 | self.bl.release() 19 | 20 | 21 | def bar(self, printBar: 'Callable[[], None]') -> None: 22 | 23 | for i in range(self.n): 24 | self.bl.acquire() 25 | # printBar() outputs "bar". Do not change or remove this line. 26 | printBar() 27 | self.fl.release() 28 | -------------------------------------------------------------------------------- /001-500/238.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def productExceptSelf(self, nums: List[int]) -> List[int]: 3 | res = [1]*len(nums) 4 | 5 | pre = 1 6 | for i in range(len(nums)): 7 | res[i] = pre 8 | pre *= nums[i] 9 | 10 | post = 1 11 | for i in reversed(range(len(nums))): 12 | res[i] *= post 13 | post *= nums[i] 14 | 15 | return res 16 | 17 | 18 | 19 | class Solution: 20 | def productExceptSelf(self, nums: List[int]) -> List[int]: 21 | res = [1]*len(nums) 22 | pre = 1 23 | post = 1 24 | 25 | for i in range(len(nums)): 26 | res[i] *= pre 27 | pre *= nums[i] 28 | res[len(nums)-i-1] *= post 29 | post *= nums[len(nums)-i-1] 30 | 31 | return res 32 | -------------------------------------------------------------------------------- /001-500/145.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def __init__(self): 9 | self.ans = [] 10 | 11 | def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: 12 | if not root: 13 | return [] 14 | self.postorderTraversal(root.left) 15 | self.postorderTraversal(root.right) 16 | self.ans.append(root.val) 17 | return self.ans 18 | 19 | 20 | class Solution: 21 | def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]: 22 | return self.postorderTraversal(root.left)+self.postorderTraversal(root.right)+[root.val] if root else [] 23 | 24 | -------------------------------------------------------------------------------- /1001-1500/1472.py: -------------------------------------------------------------------------------- 1 | class BrowserHistory: 2 | 3 | def __init__(self, homepage: str): 4 | self.history = [homepage] 5 | self.curPage = 0 6 | 7 | 8 | def visit(self, url: str) -> None: 9 | self.history = self.history[:self.curPage+1] + [url] 10 | self.curPage += 1 11 | 12 | def back(self, steps: int) -> str: 13 | self.curPage = max(0,self.curPage-steps) 14 | return self.history[self.curPage] 15 | 16 | def forward(self, steps: int) -> str: 17 | self.curPage = min(len(self.history)-1,self.curPage+steps) 18 | return self.history[self.curPage] 19 | 20 | 21 | # Your BrowserHistory object will be instantiated and called as such: 22 | # obj = BrowserHistory(homepage) 23 | # obj.visit(url) 24 | # param_2 = obj.back(steps) 25 | # param_3 = obj.forward(steps) 26 | -------------------------------------------------------------------------------- /001-500/002.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: 8 | temp = ListNode() 9 | cur = temp 10 | carry=0 11 | 12 | while l1!=None or l2!=None or carry!=0: 13 | num1 = l1.val if l1 else 0 14 | num2 = l2.val if l2 else 0 15 | colSum = num1+num2+carry 16 | carry = colSum//10 17 | newNode = ListNode(colSum%10) 18 | cur.next = newNode 19 | cur = newNode 20 | l1 = l1.next if l1 else None 21 | l2 = l2.next if l2 else None 22 | 23 | return temp.next 24 | 25 | -------------------------------------------------------------------------------- /1501-2000/1971.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool: 3 | def dfs(graph,node): 4 | stack = [node] 5 | visited = set() 6 | while stack: 7 | node = stack.pop() 8 | if node==destination: 9 | return True 10 | if node not in visited: 11 | visited.add(node) 12 | for child in graph[node]: 13 | if child not in visited: 14 | stack.append(child) 15 | return False 16 | 17 | graph = defaultdict(list) 18 | 19 | for s,d in edges: 20 | graph[s].append(d) 21 | graph[d].append(s) 22 | 23 | return dfs(graph,source) 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /1001-1500/1302.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def __init__(self): 9 | self.deepest = float('-inf') 10 | self.res = 0 11 | 12 | def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: 13 | def dfs(root, level): 14 | if not root: 15 | return 16 | if level>self.deepest: 17 | self.res = root.val 18 | self.deepest = level 19 | elif level ==self.deepest: 20 | self.res += root.val 21 | dfs(root.left,level+1) 22 | dfs(root.right,level+1) 23 | 24 | dfs(root,0) 25 | return self.res 26 | 27 | -------------------------------------------------------------------------------- /1001-1500/1026.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def maxAncestorDiff(self, root: Optional[TreeNode]) -> int: 9 | maxVal = 0 10 | 11 | queue = deque([(root, root.val, root.val)]) 12 | while queue: 13 | curr, high, low = queue.popleft() 14 | currVal = curr.val 15 | diff1, diff2 = currVal - low, high - currVal 16 | maxVal = max(maxVal, diff1, diff2) 17 | 18 | if curr.left: 19 | queue.append((curr.left, max(currVal, high), min(currVal, low))) 20 | if curr.right: 21 | queue.append((curr.right, max(currVal, high), min(currVal, low))) 22 | return maxVal 23 | -------------------------------------------------------------------------------- /001-500/005.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def longestPalindrome(self, s): 3 | """ 4 | :type s: str 5 | :rtype: str 6 | """ 7 | start = 0 8 | end = 0 9 | m = 0 10 | 11 | for i in range(len(s)): 12 | 13 | #odd palindromes 14 | l,r=i,i 15 | while l>=0 and rm: 17 | start = l 18 | end = r 19 | m = r-l+1 20 | l-=1 21 | r+=1 22 | 23 | #even palindromes 24 | l,r=i,i+1 25 | while l>=0 and rm: 27 | start = l 28 | end = r 29 | m = r-l+1 30 | l-=1 31 | r+=1 32 | 33 | return s[start:end+1] 34 | -------------------------------------------------------------------------------- /2501-3000/2966.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def divideArray(self, nums: List[int], k: int) -> List[List[int]]: 3 | n = len(nums) 4 | if n % 3 != 0: 5 | return [] 6 | 7 | nums.sort() 8 | 9 | result = [] 10 | group_index = 0 11 | for i in range(0, n, 3): 12 | if i + 2 < n and nums[i + 2] - nums[i] <= k: 13 | result.append([nums[i], nums[i + 1], nums[i + 2]]) 14 | group_index += 1 15 | else: 16 | return [] 17 | return result 18 | 19 | 20 | class Solution: 21 | def divideArray(self, nums: List[int], k: int) -> List[List[int]]: 22 | nums.sort() 23 | ans=[] 24 | n=len(nums)//3 25 | for i in range(n): 26 | if nums[3*i+2]-nums[3*i]> k: 27 | return [] 28 | ans.append(nums[3*i:3*i+3]) 29 | return ans 30 | 31 | -------------------------------------------------------------------------------- /501-1000/989.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addToArrayForm(self, num: List[int], k: int) -> List[int]: 3 | i = len(num)-1 4 | num[i] += k 5 | 6 | while i>0 or num[i]>9: 7 | c,num[i] = divmod(num[i],10) 8 | if i>0: 9 | num[i-1]+=c 10 | i -= 1 11 | else: 12 | num.insert(0,c) 13 | i =0 14 | 15 | return num 16 | 17 | 18 | 19 | 20 | class Solution: 21 | def addToArrayForm(self, num: List[int], k: int) -> List[int]: 22 | i = len(num)-1 23 | num[i] += k 24 | 25 | while i>0: 26 | if num[i]>9: 27 | c,num[i] = divmod(num[i],10) 28 | num[i-1]+=c 29 | i-=1 30 | 31 | while num[i]>9: 32 | c,num[i] = divmod(num[i],10) 33 | num.insert(0,c) 34 | 35 | 36 | return num 37 | -------------------------------------------------------------------------------- /001-500/168.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def convertToTitle(self, c: int) -> str: 3 | a = [chr(x) for x in range(ord("A"), ord("Z")+2)] 4 | res = "" 5 | while c>0: 6 | c -= 1 7 | res += a[c%26] 8 | c //= 26 9 | 10 | return res[::-1] 11 | 12 | 13 | 14 | class Solution: 15 | def convertToTitle(self, c: int) -> str: 16 | res = "" 17 | while c>0: 18 | c -= 1 19 | res += chr(ord("A") + c%26) 20 | c //= 26 21 | 22 | return res[::-1] 23 | 24 | 25 | 26 | class Solution: 27 | def convertToTitle(self, c: int) -> str: 28 | a = ['0','A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] 29 | res = "" 30 | while c>0: 31 | c -= 1 32 | res += a[c%26+1] 33 | c //= 26 34 | 35 | return res[::-1] 36 | -------------------------------------------------------------------------------- /1001-1500/1381.py: -------------------------------------------------------------------------------- 1 | class CustomStack: 2 | 3 | def __init__(self, maxSize: int): 4 | self.maxSize = maxSize 5 | self.stack = [] 6 | 7 | def push(self, x: int) -> None: 8 | if len(self.stack)!=self.maxSize: 9 | self.stack.append(x) 10 | 11 | def pop(self) -> int: 12 | if len(self.stack)==0: 13 | return -1 14 | else: 15 | return self.stack.pop() 16 | 17 | def increment(self, k: int, val: int) -> None: 18 | tempStack = [] 19 | while len(self.stack)!=0: 20 | tempStack.append(self.stack.pop()) 21 | while len(tempStack) and k!=0: 22 | self.stack.append(tempStack.pop()+val) 23 | k-=1 24 | while len(tempStack)!=0: 25 | self.stack.append(tempStack.pop()) 26 | 27 | 28 | # Your CustomStack object will be instantiated and called as such: 29 | # obj = CustomStack(maxSize) 30 | # obj.push(x) 31 | # param_2 = obj.pop() 32 | # obj.increment(k,val) 33 | -------------------------------------------------------------------------------- /1501-2000/1512.py: -------------------------------------------------------------------------------- 1 | # Hashmap Approach 2 | class Solution(object): 3 | def numIdenticalPairs(self, nums): 4 | """ 5 | :type nums: List[int] 6 | :rtype: int 7 | """ 8 | memory = {} 9 | count = 0 10 | 11 | for num in nums: 12 | if num in memory: 13 | if memory[num]==1: 14 | count+=1 15 | else: 16 | count+=memory[num] 17 | memory[num]+=1 18 | else: 19 | memory[num]=1 20 | 21 | return count 22 | 23 | 24 | 25 | # Bruteforce approach 26 | class Solution(object): 27 | def numIdenticalPairs(self, nums): 28 | """ 29 | :type nums: List[int] 30 | :rtype: int 31 | """ 32 | count = 0 33 | for i in range(len(nums)): 34 | for j in range(i+1,len(nums)): 35 | if nums[i]==nums[j]: 36 | count+=1 37 | 38 | return count 39 | -------------------------------------------------------------------------------- /501-1000/909.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def snakesAndLadders(self, board: List[List[int]]) -> int: 3 | n = len(board) 4 | board.reverse() 5 | 6 | def squarePos(square): 7 | r = (square-1) // n 8 | c = (square-1) % n 9 | if r%2==1: 10 | c = n-c-1 11 | return (r,c) 12 | 13 | q = deque() 14 | q.append((1,0)) 15 | visited = set() 16 | while q: 17 | square, moves = q.popleft() 18 | 19 | for i in range(1,7): 20 | nextSquare = square + i 21 | r,c = squarePos(nextSquare) 22 | if board[r][c]!=-1: 23 | nextSquare = board[r][c] 24 | if nextSquare==n**2: 25 | return moves+1 26 | if nextSquare not in visited: 27 | visited.add(nextSquare) 28 | q.append((nextSquare, moves+1)) 29 | 30 | return -1 31 | -------------------------------------------------------------------------------- /001-500/494.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findTargetSumWays(self, nums: List[int], target: int) -> int: 3 | memo = {} 4 | 5 | def helper(i, t): 6 | if i==-1: 7 | if t==0: 8 | return 1 9 | return 0 10 | if (i,t) in memo: 11 | return memo.get((i,t)) 12 | pos = helper(i-1,t-nums[i]) 13 | neg = helper(i-1,t+nums[i]) 14 | memo[(i,t)] = pos+neg 15 | return memo[(i,t)] 16 | 17 | return helper(len(nums)-1,target) 18 | 19 | 20 | 21 | class Solution: 22 | def findTargetSumWays(self, nums: List[int], target: int) -> int: 23 | def helper(i, t): 24 | if i==-1: 25 | if t==0: 26 | return 1 27 | return 0 28 | pos = helper(i-1,t-nums[i]) 29 | neg = helper(i-1,t+nums[i]) 30 | return pos+neg 31 | return helper(len(nums)-1,target) 32 | 33 | 34 | -------------------------------------------------------------------------------- /001-500/242.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isAnagram(self, s: str, t: str) -> bool: 3 | if len(s)!=len(t): 4 | return False 5 | 6 | d = defaultdict(int) 7 | for c in s: 8 | d[c]+=1 9 | for c in t: 10 | d[c]-=1 11 | 12 | for i in d.values(): 13 | if i!=0: 14 | return False 15 | 16 | return True 17 | 18 | 19 | 20 | class Solution: 21 | def isAnagram(self, s: str, t: str) -> bool: 22 | if len(s)!=len(t): 23 | return False 24 | 25 | d = {} 26 | 27 | for i in range(len(s)): 28 | if s[i] in d: 29 | d[s[i]] += 1 30 | else: 31 | d[s[i]] = 1 32 | 33 | for i in range(len(t)): 34 | if t[i] in d: 35 | d[t[i]] -= 1 36 | else: 37 | return False 38 | 39 | for v in d.values(): 40 | if v>0: 41 | return False 42 | return True 43 | -------------------------------------------------------------------------------- /001-500/141.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def hasCycle(self, head: Optional[ListNode]) -> bool: 9 | try: 10 | s = head 11 | f = s.next 12 | 13 | while s is not f: 14 | s = s.next 15 | f = f.next.next 16 | 17 | return True 18 | except: 19 | return False 20 | 21 | 22 | 23 | class Solution: 24 | def hasCycle(self, head: Optional[ListNode]) -> bool: 25 | if not head or not head.next: 26 | return False 27 | s = head 28 | f = head.next 29 | 30 | if s==f: 31 | return True 32 | 33 | while s is not f and f and f.next and f.next.next: 34 | s = s.next 35 | f = f.next.next 36 | if s==f: 37 | return True 38 | 39 | return False 40 | 41 | 42 | -------------------------------------------------------------------------------- /001-500/217.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def containsDuplicate(self, nums: List[int]) -> bool: 3 | nums.sort() 4 | for i in range(len(nums)-1): 5 | if nums[i]==nums[i+1]: 6 | return True 7 | return False 8 | 9 | 10 | 11 | 12 | class Solution: 13 | def containsDuplicate(self, nums: List[int]) -> bool: 14 | return sorted(nums)!=sorted(list(set(nums))) 15 | 16 | 17 | 18 | 19 | class Solution: 20 | def containsDuplicate(self, nums: List[int]) -> bool: 21 | d = {} 22 | for num in nums: 23 | if num in d: 24 | return True 25 | else: 26 | d[num]=1 27 | return False 28 | 29 | 30 | 31 | 32 | class Solution: 33 | def containsDuplicate(self, nums: List[int]) -> bool: 34 | s = set() 35 | for num in nums: 36 | if num in s: 37 | return True 38 | else: 39 | s.add(num) 40 | return False 41 | -------------------------------------------------------------------------------- /2501-3000/2824.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countPairs(self, nums: List[int], target: int) -> int: 3 | nums.sort() 4 | count = 0 5 | left = 0 6 | right = len(nums)-1 7 | while left int: 18 | count = 0 19 | for i in range(len(nums)): 20 | for j in range(i+1,len(nums)): 21 | count += nums[i]+nums[j] int: 27 | count = 0 28 | for i in range(len(nums)): 29 | for j in range(i+1,len(nums)): 30 | if nums[i]+nums[j] bool: 9 | def findLeaf(root): 10 | if not root: 11 | return [] 12 | if not (root.left or root.right): 13 | return [root.val] 14 | return findLeaf(root.left) + findLeaf(root.right) 15 | return findLeaf(root1)==findLeaf(root2) 16 | 17 | 18 | 19 | class Solution: 20 | def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool: 21 | def dfs(root): 22 | if not root: 23 | return [] 24 | if not root.left and not root.right: 25 | return [root.val] 26 | return dfs(root.left) + dfs(root.right) 27 | return dfs(root2)==dfs(root1) 28 | 29 | -------------------------------------------------------------------------------- /2501-3000/2816.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def doubleIt(self, head: Optional[ListNode]) -> Optional[ListNode]: 8 | def reverse(head): 9 | temp = head 10 | prev = None 11 | while temp: 12 | x = temp.next 13 | temp.next = prev 14 | prev = temp 15 | temp = x 16 | return prev 17 | 18 | head = reverse(head) 19 | 20 | temp = head 21 | carry = 0 22 | while temp: 23 | curVal = (temp.val*2)+carry 24 | temp.val = curVal%10 25 | carry = curVal//10 26 | temp = temp.next 27 | 28 | head = reverse(head) 29 | 30 | if carry>0: 31 | temp = ListNode(carry) 32 | temp.next = head 33 | return temp 34 | 35 | return head 36 | -------------------------------------------------------------------------------- /001-500/054.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def spiralOrder(self, matrix: List[List[int]]) -> List[int]: 3 | m = len(matrix) 4 | n = len(matrix[0]) 5 | top = left = 0 6 | down = m-1 7 | right = n-1 8 | d = 0 #direction 9 | ans = [] 10 | 11 | while (top<=down and left<=right): 12 | if (d==0): 13 | for i in range(top,right+1): 14 | ans.append(matrix[top][i]) 15 | top += 1 16 | elif (d==1): 17 | for i in range(top,down+1): 18 | ans.append(matrix[i][right]) 19 | right -= 1 20 | elif (d==2): 21 | for i in reversed(range(left, right+1)): 22 | ans.append(matrix[down][i]) 23 | down -= 1 24 | elif (d==3): 25 | for i in reversed(range(top, down+1)): 26 | ans.append(matrix[i][left]) 27 | left += 1 28 | 29 | d = (d+1)%4 30 | 31 | return ans 32 | -------------------------------------------------------------------------------- /001-500/142.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: 9 | try: 10 | slow = head 11 | fast = head.next 12 | while slow is not fast: 13 | slow = slow.next 14 | fast = fast.next.next 15 | except: 16 | return None 17 | 18 | slow = slow.next 19 | temp = head 20 | while temp is not slow: 21 | slow = slow.next 22 | temp = temp.next 23 | 24 | return temp 25 | 26 | 27 | 28 | class Solution: 29 | def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: 30 | temp = head 31 | seen = [] 32 | while temp: 33 | if temp in seen: 34 | return temp 35 | seen.append(temp) 36 | temp = temp.next 37 | return None 38 | 39 | -------------------------------------------------------------------------------- /001-500/148.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: 8 | if not head or not head.next: 9 | return head 10 | 11 | slow,fast = head,head.next 12 | while fast and fast.next: 13 | slow = slow.next 14 | fast = fast.next.next 15 | 16 | mid = slow.next 17 | slow.next = None 18 | 19 | left = self.sortList(head) 20 | right = self.sortList(mid) 21 | 22 | dummy = ListNode(0) 23 | cur = dummy 24 | while left and right: 25 | if left.val List[List[int]]: 3 | m = [[0]*n for _ in range(n)] 4 | top = left = 0 5 | down = right = n-1 6 | d = 0 #direction 7 | ele = 1 8 | 9 | while (top<=down and left<=right): 10 | if d==0: 11 | for i in range(left,right+1): 12 | m[top][i] = ele 13 | ele += 1 14 | top += 1 15 | 16 | if d==1: 17 | for i in range(top,down+1): 18 | m[i][right] = ele 19 | ele += 1 20 | right -= 1 21 | 22 | if d==2: 23 | for i in reversed(range(left,right+1)): 24 | m[down][i] = ele 25 | ele += 1 26 | down -= 1 27 | 28 | if d==3: 29 | for i in reversed(range(top,down+1)): 30 | m[i][left] = ele 31 | ele += 1 32 | left += 1 33 | 34 | d = (d+1)%4 35 | 36 | return m 37 | 38 | 39 | -------------------------------------------------------------------------------- /001-500/200.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | class Solution: 4 | def numIslands(self, grid: List[List[str]]) -> int: 5 | if not grid: 6 | return 0 7 | rows,cols = len(grid),len(grid[0]) 8 | visited = set() 9 | islands = 0 10 | 11 | def bfs(r,c): 12 | q = deque() 13 | q.append((r,c)) 14 | visited.add((r,c)) 15 | while q: 16 | row,col = q.popleft() 17 | directions = [[0,1],[1,0],[-1,0],[0,-1]] 18 | for dr,dc in directions: 19 | r,c=row+dr,col+dc 20 | if (r in range(rows) and 21 | c in range(cols) and 22 | grid[r][c]=="1" and 23 | (r,c) not in visited): 24 | q.append((r,c)) 25 | visited.add((r,c)) 26 | 27 | for r in range(rows): 28 | for c in range(cols): 29 | if grid[r][c]=="1" and (r,c) not in visited: 30 | bfs(r,c) 31 | islands += 1 32 | 33 | return islands 34 | -------------------------------------------------------------------------------- /001-500/042.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def trap(self, height: List[int]) -> int: 3 | water = 0 4 | maxLeftArr = [0]*len(height) 5 | maxRightArr = [0]*len(height) 6 | 7 | maxLeft = height[0] 8 | for i in range(1,len(height)): 9 | maxLeftArr[i] = maxLeft 10 | if height[i]>maxLeft: 11 | maxLeft=height[i] 12 | 13 | maxRight = height[-1] 14 | for i in reversed(range(len(height)-1)): 15 | maxRightArr[i] = maxRight 16 | if height[i]>maxRight: 17 | maxRight=height[i] 18 | 19 | for i in range(1,len(height)-1): 20 | bar_height = min(maxLeftArr[i], maxRightArr[i]) 21 | if bar_height>height[i]: 22 | water += bar_height-height[i] 23 | return water 24 | 25 | 26 | 27 | # Exceeds Time Limit 28 | class Solution: 29 | def trap(self, height: List[int]) -> int: 30 | water = 0 31 | for i in range(1,len(height)-1): 32 | bar_height = min(max(height[:i]), max(height[i+1:])) 33 | if bar_height>height[i]: 34 | water += bar_height-height[i] 35 | return water 36 | -------------------------------------------------------------------------------- /001-500/169.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def majorityElement(self, nums: List[int]) -> int: 3 | count = 0 4 | maj = None 5 | for num in nums: 6 | if count==0: 7 | maj = num 8 | count += 1 if num==maj else -1 9 | return maj 10 | 11 | 12 | 13 | class Solution: 14 | def majorityElement(self, nums: List[int]) -> int: 15 | n2 = len(nums)//2 16 | d = {} 17 | for i in nums: 18 | if i in d: 19 | d[i]+=1 20 | else: 21 | d[i]=1 22 | for i,j in d.items(): 23 | if j>n2: 24 | return i 25 | 26 | 27 | 28 | from collections import defaultdict 29 | class Solution: 30 | def majorityElement(self, nums: List[int]) -> int: 31 | n2 = len(nums)//2 32 | d = defaultdict(int) 33 | for i in nums: 34 | d[i]+=1 35 | for i,j in d.items(): 36 | if j>n2: 37 | return i 38 | 39 | 40 | 41 | class Solution: 42 | def majorityElement(self, nums: List[int]) -> int: 43 | return sorted(nums)[len(nums)//2] 44 | 45 | 46 | -------------------------------------------------------------------------------- /2001-2500/2181.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]: 8 | p1 = head 9 | p2 = head.next 10 | c = 0 11 | while p2: 12 | if p2.val==0: 13 | p1 = p1.next 14 | p1.val = c 15 | c = 0 16 | else: 17 | c+=p2.val 18 | p2 = p2.next 19 | p1.next = None 20 | return head.next 21 | 22 | 23 | 24 | class Solution: 25 | def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]: 26 | temp = head 27 | res = [] 28 | while temp: 29 | c = 0 30 | while temp.val!=0: 31 | c += temp.val 32 | temp = temp.next 33 | if c!=0: 34 | res.append(c) 35 | temp = temp.next 36 | 37 | z = ListNode(res[0]) 38 | x = z 39 | for i in res[1:]: 40 | x.next = ListNode() 41 | x = x.next 42 | x.val = i 43 | 44 | 45 | return z 46 | -------------------------------------------------------------------------------- /001-500/088.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: 3 | """ 4 | Do not return anything, modify nums1 in-place instead. 5 | """ 6 | k = m+n-1 7 | i = m-1 8 | j = n-1 9 | 10 | while j>=0: 11 | if i>=0 and nums1[i]>nums2[j]: 12 | nums1[k]=nums1[i] 13 | i-=1 14 | k-=1 15 | else: 16 | nums1[k]=nums2[j] 17 | j-=1 18 | k-=1 19 | 20 | 21 | 22 | class Solution(object): 23 | def merge(self, nums1, m, nums2, n): 24 | """ 25 | :type nums1: List[int] 26 | :type m: int 27 | :type nums2: List[int] 28 | :type n: int 29 | :rtype: None Do not return anything, modify nums1 in-place instead. 30 | """ 31 | i = m+n-1 32 | j = n-1 33 | k = m-1 34 | 35 | while j>=0 and k>=0: 36 | if nums2[j] > nums1[k]: 37 | nums1[i]=nums2[j] 38 | j-=1 39 | else: 40 | nums1[i]=nums1[k] 41 | k-=1 42 | i-=1 43 | 44 | while i>=0 and j>=0: 45 | nums1[i]=nums2[j] 46 | j-=1 47 | i-=1 48 | -------------------------------------------------------------------------------- /001-500/150.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def evalRPN(self, tokens: List[str]) -> int: 3 | stack = [] 4 | for token in tokens: 5 | if token not in "+-*/": 6 | stack.append(int(token)) 7 | else: 8 | b = stack.pop() 9 | a = stack.pop() 10 | if token=="+": 11 | c = a+b 12 | elif token=="-": 13 | c = a-b 14 | elif token=="/": 15 | c = int(a/b) 16 | elif token=="*": 17 | c = a*b 18 | stack.append(c) 19 | 20 | return stack[-1] 21 | 22 | 23 | class Solution: 24 | def evalRPN(self, tokens: List[str]) -> int: 25 | s = [] 26 | x = "+-*/" 27 | for token in tokens: 28 | if token not in x: 29 | s.append(int(token)) 30 | else: 31 | a = s.pop() 32 | b = s.pop() 33 | if token=="+": 34 | s.append(a+b) 35 | elif token=="-": 36 | s.append(b-a) 37 | elif token=="*": 38 | s.append(a*b) 39 | else: 40 | s.append(int(b/a)) 41 | return s[0] 42 | -------------------------------------------------------------------------------- /001-500/004.py: -------------------------------------------------------------------------------- 1 | #Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. 2 | 3 | #The overall run time complexity should be O(log (m+n)). 4 | 5 | 6 | #Approach 1 7 | class Solution: 8 | def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: 9 | nums1 += nums2 10 | nums1.sort() 11 | n = len(nums1) 12 | if n%2==0: 13 | return (nums1[n//2-1]+nums1[n//2])/2 14 | else: 15 | return nums1[n//2] 16 | 17 | 18 | #Approach 2 19 | class Solution: 20 | def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: 21 | arr = [] 22 | i=j=0 23 | n1 = len(nums1) 24 | n2 = len(nums2) 25 | n = n1+n2 26 | while i int: 3 | q = deque() 4 | q.append((startGene,0)) 5 | visited = {startGene} 6 | while q: 7 | node, steps = q.popleft() 8 | if node==endGene: 9 | return steps 10 | for c in 'ATGC': 11 | for i in range(len(node)): 12 | x = node[:i] + c + node[i+1:] 13 | if x not in visited and x in bank: 14 | q.append((x,steps+1)) 15 | visited.add(x) 16 | 17 | return -1 18 | 19 | 20 | 21 | class Solution: 22 | def minMutation(self, startGene: str, endGene: str, bank: List[str]) -> int: 23 | stack = [] 24 | stack.append((startGene,0)) 25 | visited = {startGene} 26 | while stack: 27 | node, steps = stack.pop() 28 | if node==endGene: 29 | return steps 30 | for c in 'ATGC': 31 | for i in range(len(node)): 32 | x = node[:i] + c + node[i+1:] 33 | if x not in visited and x in bank: 34 | stack.append((x,steps+1)) 35 | visited.add(x) 36 | 37 | return -1 38 | -------------------------------------------------------------------------------- /2001-2500/2385.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def amountOfTime(self, root: Optional[TreeNode], start: int) -> int: 9 | def dfs(node): 10 | if node is None: 11 | return 12 | if node.left: 13 | graph[node.val].append(node.left.val) 14 | graph[node.left.val].append(node.val) 15 | if node.right: 16 | graph[node.val].append(node.right.val) 17 | graph[node.right.val].append(node.val) 18 | dfs(node.left) 19 | dfs(node.right) 20 | 21 | graph = defaultdict(list) 22 | dfs(root) 23 | visited = set() 24 | queue = deque([start]) 25 | time = -1 26 | 27 | while queue: 28 | time += 1 29 | for _ in range(len(queue)): 30 | current_node = queue.popleft() 31 | visited.add(current_node) 32 | for neighbor in graph[current_node]: 33 | if neighbor not in visited: 34 | queue.append(neighbor) 35 | 36 | return time 37 | 38 | -------------------------------------------------------------------------------- /001-500/062.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def uniquePaths(self, m: int, n: int) -> int: 3 | dp = [[0]*m for _ in range(n)] 4 | for i in range(m): 5 | dp[0][i]=1 6 | for j in range(n): 7 | dp[j][0]=1 8 | 9 | for i in range(1,n): 10 | for j in range(1,m): 11 | dp[i][j] = dp[i-1][j] + dp[i][j-1] 12 | 13 | return dp[n-1][m-1] 14 | 15 | class Solution: 16 | def uniquePaths(self, m: int, n: int) -> int: 17 | def helper(i,j,dp): 18 | if i==0 and j==0: 19 | return 1 20 | elif i<0 or j<0: 21 | return 0 22 | elif dp[i][j]!=-1: 23 | return dp[i][j] 24 | l = helper(i-1,j,dp) 25 | r = helper(i,j-1,dp) 26 | dp[i][j] = l+r 27 | return dp[i][j] 28 | 29 | dp = [[-1]*m for _ in range(n)] 30 | return helper(n-1,m-1,dp) 31 | 32 | class Solution: 33 | def uniquePaths(self, m: int, n: int) -> int: 34 | def helper(i,j): 35 | if i==0 and j==0: 36 | return 1 37 | elif i<0 or j<0: 38 | return 0 39 | l = helper(i-1,j) 40 | r = helper(i,j-1) 41 | return l+r 42 | 43 | return helper(n-1,m-1) 44 | -------------------------------------------------------------------------------- /001-500/072.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minDistance(self, word1: str, word2: str) -> int: 3 | def helper(i,j,dp): 4 | if i==0: 5 | return j 6 | if j==0: 7 | return i 8 | if dp[i][j]!=-1: 9 | return dp[i][j] 10 | if word1[i-1]==word2[j-1]: 11 | dp[i][j] = helper(i-1,j-1,dp) 12 | else: 13 | insertOp = helper(i-1,j,dp) 14 | deleteOp = helper(i,j-1,dp) 15 | swapOp = helper(i-1,j-1,dp) 16 | dp[i][j] = min(insertOp,deleteOp,swapOp) + 1 17 | return dp[i][j] 18 | 19 | dp = [[-1]*(len(word2)+1) for _ in range(len(word1)+1)] 20 | return helper(len(word1),len(word2),dp) 21 | 22 | 23 | 24 | class Solution: 25 | def minDistance(self, word1: str, word2: str) -> int: 26 | def helper(i,j): 27 | if i==0: 28 | return j 29 | if j==0: 30 | return i 31 | if word1[i-1]==word2[j-1]: 32 | return helper(i-1,j-1) 33 | else: 34 | insertOp = helper(i-1,j) 35 | deleteOp = helper(i,j-1) 36 | swapOp = helper(i-1,j-1) 37 | return min(insertOp,deleteOp,swapOp) + 1 38 | 39 | return helper(len(word1),len(word2)) 40 | 41 | 42 | -------------------------------------------------------------------------------- /001-500/229.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def majorityElement(self, nums: List[int]) -> List[int]: 3 | c1,c2,cd1,cd2=0,0,0,1 4 | for num in nums: 5 | if num==cd1: 6 | c1+=1 7 | elif num==cd2: 8 | c2+=1 9 | elif c1==0: 10 | c1,cd1=1,num 11 | elif c2==0: 12 | c2,cd2=1,num 13 | else: 14 | c1-=1 15 | c2-=1 16 | if cd1==cd2: 17 | return [cd1] 18 | return [n for n in (cd1,cd2) if nums.count(n)>len(nums)//3] 19 | 20 | 21 | from collections import defaultdict 22 | class Solution: 23 | def majorityElement(self, nums: List[int]) -> List[int]: 24 | d = defaultdict(int) 25 | n = len(nums)//3 26 | res = [] 27 | for num in nums: 28 | d[num]+=1 29 | for i,j in d.items(): 30 | if j>n: 31 | res.append(i) 32 | 33 | return res 34 | 35 | 36 | class Solution: 37 | def majorityElement(self, nums: List[int]) -> List[int]: 38 | d = {} 39 | n = len(nums)//3 40 | res = [] 41 | for num in nums: 42 | if num not in d: 43 | d[num]=1 44 | else: 45 | d[num]+=1 46 | for i,j in d.items(): 47 | if j>n: 48 | res.append(i) 49 | 50 | return res 51 | -------------------------------------------------------------------------------- /001-500/097.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isInterleave(self, s1: str, s2: str, s3: str) -> bool: 3 | l1,l2,l3 = len(s1),len(s2),len(s3) 4 | if l1+l2!=l3: 5 | return False 6 | 7 | dp = [[-1]*(l2+1) for _ in range(l1+1)] 8 | 9 | def helper(i,j,k): 10 | if k==l3: 11 | return True 12 | 13 | if dp[i][j]!=-1: 14 | return dp[i][j] 15 | 16 | ans = False 17 | if i bool: 32 | l1,l2,l3 = len(s1),len(s2),len(s3) 33 | if l1+l2!=l3: 34 | return False 35 | 36 | def helper(i,j,k): 37 | if k==l3: 38 | return True 39 | 40 | ans = False 41 | if i int: 3 | def helper(i,amt,dp): 4 | if i==0: 5 | if amt%coins[0]==0: 6 | return amt//coins[0] 7 | else: 8 | return float('inf') 9 | if dp[i][amt]!=-1: 10 | return dp[i][amt] 11 | not_pick = helper(i-1,amt,dp) 12 | if coins[i]<=amt: 13 | pick = 1 + helper(i,amt-coins[i],dp) 14 | else: 15 | pick = float('inf') 16 | dp[i][amt] = min(pick,not_pick) 17 | return dp[i][amt] 18 | 19 | dp = [[-1]*(amount+1) for _ in range(len(coins))] 20 | res = helper(len(coins)-1, amount, dp) 21 | return res if res!=float('inf') else -1 22 | 23 | 24 | class Solution: 25 | def coinChange(self, coins: List[int], amount: int) -> int: 26 | def helper(i,amt): 27 | if i==0: 28 | if amt%coins[0]==0: 29 | return amt//coins[0] 30 | else: 31 | return float('inf') 32 | not_pick = helper(i-1,amt) 33 | if coins[i]<=amt: 34 | pick = 1 + helper(i,amt-coins[i]) 35 | else: 36 | pick = float('inf') 37 | return min(pick,not_pick) 38 | 39 | res = helper(len(coins)-1, amount) 40 | return res if res!=float('inf') else -1 41 | -------------------------------------------------------------------------------- /501-1000/576.py: -------------------------------------------------------------------------------- 1 | # Memoization 2 | class Solution: 3 | def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int: 4 | R = m 5 | C = n 6 | M = 10**9 + 7 7 | mem = {} 8 | 9 | def dfs(r,c,maxMove): 10 | if (r<0 or r==R or c<0 or c==C): 11 | return 1 12 | if maxMove==0: 13 | return 0 14 | if (r,c,maxMove) in mem: 15 | return mem[(r,c,maxMove)] 16 | mem[(r,c,maxMove)] = ( 17 | (dfs(r+1,c,maxMove-1) + dfs(r-1,c,maxMove-1)) % M 18 | + 19 | (dfs(r,c+1,maxMove-1) + dfs(r,c-1,maxMove-1)) % M 20 | ) % M 21 | return mem[(r,c,maxMove)] 22 | 23 | return dfs(startRow, startColumn, maxMove) 24 | 25 | # Recursive - TLE 26 | class Solution: 27 | def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int: 28 | R = m 29 | C = n 30 | M = 10**9 + 7 31 | 32 | def dfs(r,c,maxMove): 33 | if (r<0 or r==R or c<0 or c==C): 34 | return 1 35 | if maxMove==0: 36 | return 0 37 | return ( 38 | (dfs(r+1,c,maxMove-1) + dfs(r-1,c,maxMove-1)) % M 39 | + 40 | (dfs(r,c+1,maxMove-1) + dfs(r,c-1,maxMove-1)) % M 41 | ) % M 42 | 43 | return dfs(startRow, startColumn, maxMove) 44 | -------------------------------------------------------------------------------- /1001-1500/1143.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestCommonSubsequence(self, text1: str, text2: str) -> int: 3 | dp = [[0]*(len(text2)+1) for _ in range(len(text1)+1)] 4 | for i in range(len(text1)): 5 | for j in range(len(text2)): 6 | if text1[i]==text2[j]: 7 | dp[i][j] = 1 + dp[i-1][j-1] 8 | else: 9 | dp[i][j] = max(dp[i-1][j],dp[i][j-1]) 10 | 11 | return dp[len(text1)-1][len(text2)-1] 12 | 13 | 14 | class Solution: 15 | def longestCommonSubsequence(self, text1: str, text2: str) -> int: 16 | def helper(i,j, dp): 17 | if i<0 or j<0: 18 | return 0 19 | 20 | if dp[i][j]!=-1: 21 | return dp[i][j] 22 | 23 | if text1[i]==text2[j]: 24 | return 1 + helper(i-1,j-1,dp) 25 | 26 | dp[i][j] = max(helper(i-1,j,dp),helper(i,j-1,dp)) 27 | return dp[i][j] 28 | 29 | dp = [[-1]*len(text2) for _ in range(len(text1))] 30 | return helper(len(text1)-1,len(text2)-1,dp) 31 | 32 | 33 | class Solution: 34 | def longestCommonSubsequence(self, text1: str, text2: str) -> int: 35 | def helper(i,j): 36 | if i<0 or j<0: 37 | return 0 38 | 39 | if text1[i]==text2[j]: 40 | return 1 + helper(i-1,j-1) 41 | 42 | return max(helper(i-1,j),helper(i,j-1)) 43 | 44 | return helper(len(text1)-1,len(text2)-1) 45 | -------------------------------------------------------------------------------- /001-500/120.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumTotal(self, triangle: List[List[int]]) -> int: 3 | n = len(triangle) 4 | dp = [[0]*(n+1) for _ in range(n+1)] 5 | 6 | for i in range(n): 7 | dp[n-1][i] = triangle[n-1][i] 8 | 9 | for i in range(n-1,-1,-1): 10 | for j in range(i,-1,-1): 11 | down = triangle[i][j] + dp[i+1][j] 12 | diagonal = triangle[i][j] + dp[i+1][j+1] 13 | dp[i][j] = min(down,diagonal) 14 | 15 | return dp[0][0] 16 | 17 | 18 | 19 | class Solution: 20 | def minimumTotal(self, triangle: List[List[int]]) -> int: 21 | n = len(triangle) 22 | def f(i,j,dp): 23 | if i==n-1: 24 | return triangle[i][j] 25 | if dp[i][j]!=-1: 26 | return dp[i][j] 27 | down = triangle[i][j] + f(i+1,j,dp) 28 | diagonal = triangle[i][j] + f(i+1,j+1,dp) 29 | dp[i][j] = min(down,diagonal) 30 | return dp[i][j] 31 | 32 | dp = [[-1]*n for _ in range(n)] 33 | return f(0,0,dp) 34 | 35 | 36 | class Solution: 37 | def minimumTotal(self, triangle: List[List[int]]) -> int: 38 | n = len(triangle) 39 | def f(i,j): 40 | if i==n-1: 41 | return triangle[i][j] 42 | down = triangle[i][j] + f(i+1,j) 43 | diagonal = triangle[i][j] + f(i+1,j+1) 44 | return min(down,diagonal) 45 | return f(0,0) 46 | -------------------------------------------------------------------------------- /001-500/146.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self,key,val): 3 | self.key = key 4 | self.val = val 5 | self.next = None 6 | self.prev = None 7 | 8 | 9 | class LRUCache: 10 | 11 | def __init__(self, capacity: int): 12 | self.capacity = capacity 13 | self.dic = {} 14 | self.head = ListNode(0,0) 15 | self.tail = ListNode(0,0) 16 | self.head.next = self.tail 17 | self.tail.prev = self.head 18 | 19 | 20 | def get(self, key: int) -> int: 21 | if key not in self.dic: 22 | return -1 23 | node = self.dic[key] 24 | self.remove(node) 25 | self.add(node) 26 | return node.val 27 | 28 | def put(self, key: int, value: int) -> None: 29 | if key in self.dic: 30 | oldNode = self.dic[key] 31 | self.remove(oldNode) 32 | node = ListNode(key,value) 33 | self.dic[key] = node 34 | self.add(node) 35 | 36 | if len(self.dic)>self.capacity: 37 | lru_node = self.head.next 38 | self.remove(lru_node) 39 | del self.dic[lru_node.key] 40 | 41 | def add(self, newNode): 42 | prev_node = self.tail.prev 43 | newNode.next = self.tail 44 | newNode.prev = prev_node 45 | prev_node.next = newNode 46 | self.tail.prev = newNode 47 | 48 | def remove(self, node): 49 | node.next.prev = node.prev 50 | node.prev.next = node.next 51 | 52 | # Your LRUCache object will be instantiated and called as such: 53 | # obj = LRUCache(capacity) 54 | # param_1 = obj.get(key) 55 | # obj.put(key,value) 56 | -------------------------------------------------------------------------------- /001-500/067.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addBinary(self, a: str, b: str) -> str: 3 | c = 0 4 | la = len(a)-1 5 | lb = len(b)-1 6 | res = "" 7 | 8 | while la>=0 or lb>=0: 9 | s = c 10 | if la>=0 : s += ord(a[la]) - ord('0') 11 | if lb>=0 : s += ord(b[lb]) - ord('0') 12 | la,lb = la-1, lb-1 13 | c = 1 if s>1 else 0 14 | res += str(s%2) 15 | 16 | if c==1: 17 | res+="1" 18 | 19 | return res[::-1] 20 | 21 | 22 | 23 | class Solution: 24 | def addBinary(self, a: str, b: str) -> str: 25 | res = "" 26 | i,j,c = len(a)-1,len(b)-1,0 27 | while i>=0 or j>=0: 28 | sum = c 29 | if i>=0: 30 | sum+=int(a[i]) 31 | if j>=0: 32 | sum+=int(b[j]) 33 | i,j = i-1,j-1 34 | c = 1 if sum>1 else 0 35 | res = str(sum%2) + res 36 | 37 | if c: res = "1"+res 38 | return res 39 | 40 | 41 | 42 | 43 | class Solution: 44 | def addBinary(self, a: str, b: str) -> str: 45 | c = 0 46 | la = len(a)-1 47 | lb = len(b)-1 48 | res = "" 49 | 50 | while la>=0 or lb>=0: 51 | s = c 52 | if la>=0 : s += int(a[la]) 53 | if lb>=0 : s += int(b[lb]) 54 | la,lb = la-1, lb-1 55 | c = 1 if s>1 else 0 56 | res += str(s%2) 57 | 58 | if c==1: 59 | res+="1" 60 | 61 | return res[::-1] 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /001-500/063.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int: 3 | n = len(obstacleGrid) 4 | m = len(obstacleGrid[0]) 5 | dp = [[0]*m for _ in range(n)] 6 | 7 | for i in range(m): 8 | if obstacleGrid[0][i]==1: 9 | break 10 | dp[0][i]=1 11 | for j in range(n): 12 | if obstacleGrid[j][0]==1: 13 | break 14 | dp[j][0]=1 15 | 16 | for i in range(1,n): 17 | for j in range(1,m): 18 | if obstacleGrid[i][j]==1: 19 | dp[i][j] = 0 20 | elif i==0 and j==0: 21 | dp[i][j] = 1 22 | else: 23 | left,up = 0,0 24 | if i>0: 25 | up = dp[i-1][j] 26 | if j>0: 27 | left = dp[i][j-1] 28 | dp[i][j] = up + left 29 | 30 | return dp[n-1][m-1] 31 | 32 | 33 | class Solution: 34 | def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int: 35 | def helper(i,j,dp): 36 | if obstacleGrid[i][j]==1: 37 | return 0 38 | elif i==0 and j==0: 39 | return 1 40 | elif i<0 or j<0: 41 | return 0 42 | l = helper(i-1,j,dp) 43 | r = helper(i,j-1,dp) 44 | dp[i][j] = l+r 45 | return dp[i][j] 46 | 47 | n = len(obstacleGrid) 48 | m = len(obstacleGrid[0]) 49 | dp = [[-1]*m for _ in range(n)] 50 | return helper(n-1,m-1,dp) 51 | -------------------------------------------------------------------------------- /001-500/064.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minPathSum(self, grid: List[List[int]]) -> int: 3 | n = len(grid) 4 | m = len(grid[0]) 5 | 6 | dp = [[0]*(m+1) for _ in range(n+1)] 7 | for i in range(n): 8 | for j in range(m): 9 | if i==0 and j==0: 10 | dp[i][j]=grid[0][0] 11 | else: 12 | up = grid[i][j] + dp[i-1][j] if i>0 else 99999 13 | left = grid[i][j] + dp[i][j-1] if j>0 else 99999 14 | dp[i][j] = min(up,left) 15 | return dp[n-1][m-1] 16 | 17 | 18 | class Solution: 19 | def minPathSum(self, grid: List[List[int]]) -> int: 20 | n = len(grid) 21 | m = len(grid[0]) 22 | def f(i,j, dp): 23 | if i==0 and j==0: 24 | return grid[0][0] 25 | elif i<0 or j<0: 26 | return 9999999 27 | elif dp[i][j]!=-1: 28 | return dp[i][j] 29 | up = grid[i][j] + f(i-1,j,dp) 30 | left = grid[i][j] + f(i,j-1,dp) 31 | dp[i][j] = min(up,left) 32 | return dp[i][j] 33 | 34 | dp = [[-1]*m for _ in range(n)] 35 | return f(n-1,m-1,dp) 36 | 37 | class Solution: 38 | def minPathSum(self, grid: List[List[int]]) -> int: 39 | n = len(grid) 40 | m = len(grid[0]) 41 | def f(i,j): 42 | if i==0 and j==0: 43 | return grid[0][0] 44 | elif i<0 or j<0: 45 | return 9999999 46 | up = grid[i][j] + f(i-1,j) 47 | left = grid[i][j] + f(i,j-1) 48 | return min(up,left) 49 | 50 | return f(n-1,m-1) 51 | -------------------------------------------------------------------------------- /1001-1500/1114.py: -------------------------------------------------------------------------------- 1 | class Foo: 2 | def __init__(self): 3 | self.s = 1 4 | 5 | 6 | def first(self, printFirst: 'Callable[[], None]') -> None: 7 | while self.s!=1: 8 | continue 9 | # printFirst() outputs "first". Do not change or remove this line. 10 | printFirst() 11 | self.s+=1 12 | 13 | 14 | def second(self, printSecond: 'Callable[[], None]') -> None: 15 | while self.s!=2: 16 | continue 17 | # printSecond() outputs "second". Do not change or remove this line. 18 | printSecond() 19 | self.s+=1 20 | 21 | 22 | def third(self, printThird: 'Callable[[], None]') -> None: 23 | while self.s!=3: 24 | continue 25 | # printThird() outputs "third". Do not change or remove this line. 26 | printThird() 27 | 28 | 29 | 30 | from threading import Barrier 31 | 32 | class Foo: 33 | def __init__(self): 34 | self.first_barrier = Barrier(2) 35 | self.second_barrier = Barrier(2) 36 | 37 | 38 | def first(self, printFirst: 'Callable[[], None]') -> None: 39 | # printFirst() outputs "first". Do not change or remove this line. 40 | printFirst() 41 | self.first_barrier.wait() 42 | 43 | 44 | def second(self, printSecond: 'Callable[[], None]') -> None: 45 | self.first_barrier.wait() 46 | # printSecond() outputs "second". Do not change or remove this line. 47 | printSecond() 48 | self.second_barrier.wait() 49 | 50 | 51 | def third(self, printThird: 'Callable[[], None]') -> None: 52 | self.second_barrier.wait() 53 | # printThird() outputs "third". Do not change or remove this line. 54 | printThird() 55 | -------------------------------------------------------------------------------- /001-500/015.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def threeSum(self, nums: List[int]) -> List[List[int]]: 3 | n,p,z = [],[],[] 4 | res = set() 5 | 6 | for num in nums: 7 | if num==0: 8 | z.append(num) 9 | elif num>0: 10 | p.append(num) 11 | else: 12 | n.append(num) 13 | 14 | N,P = set(n), set(p) 15 | 16 | if z: 17 | for num in P: 18 | if -num in N: 19 | res.add((num,-num,0)) 20 | 21 | if len(z)>=3: 22 | res.add((0,0,0)) 23 | 24 | for i in range(len(p)): 25 | for j in range(i+1,len(p)): 26 | target = -(p[i]+p[j]) 27 | if target in N: 28 | res.add(tuple(sorted([target, p[i], p[j]]))) 29 | 30 | for i in range(len(n)): 31 | for j in range(i+1,len(n)): 32 | target = -(n[i]+n[j]) 33 | if target in P: 34 | res.add(tuple(sorted([target, n[i], n[j]]))) 35 | 36 | return res 37 | 38 | 39 | 40 | 41 | class Solution: 42 | def threeSum(self, nums: List[int]) -> List[List[int]]: 43 | nums.sort() 44 | ans = [] 45 | 46 | for i in range(len(nums)-2): 47 | if i>0 and nums[i]==nums[i-1]: 48 | continue 49 | target = nums[i]*-1 50 | l,r=i+1,len(nums)-1 51 | 52 | while l Optional[ListNode]: 8 | if head.next == None: 9 | return None 10 | 11 | temp = ListNode() 12 | temp.next = head 13 | fast = head 14 | slow = temp 15 | 16 | while n>0 and fast!=None: 17 | fast = fast.next 18 | n-=1 19 | 20 | while fast!=None: 21 | slow = slow.next; 22 | fast = fast.next 23 | 24 | slow.next = slow.next.next 25 | 26 | return temp.next 27 | 28 | 29 | # Definition for singly-linked list. 30 | # class ListNode: 31 | # def __init__(self, val=0, next=None): 32 | # self.val = val 33 | # self.next = next 34 | class Solution: 35 | def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: 36 | slow = fast = head 37 | for _ in range(n): 38 | fast = fast.next 39 | if not fast: 40 | return head.next 41 | while fast.next: 42 | fast = fast.next 43 | slow = slow.next 44 | slow.next = slow.next.next 45 | return head 46 | 47 | class Solution: 48 | def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: 49 | 50 | t = head 51 | nodes = 0 52 | 53 | while t: 54 | nodes+=1 55 | t = t.next 56 | 57 | dummy = ListNode() 58 | dummy.next = head 59 | t = dummy 60 | p = None 61 | for i in range(nodes-n+1): 62 | p = t 63 | t = t.next 64 | p.next=t.next 65 | return dummy.next 66 | -------------------------------------------------------------------------------- /001-500/380.py: -------------------------------------------------------------------------------- 1 | class RandomizedSet: 2 | 3 | def __init__(self): 4 | self.m = {} 5 | self.data = [] 6 | 7 | def insert(self, val: int) -> bool: 8 | if val in self.m: 9 | return False 10 | else: 11 | self.m[val]=len(self.data) 12 | self.data.append(val) 13 | return True 14 | 15 | def remove(self, val: int) -> bool: 16 | if val not in self.m: 17 | return False 18 | else: 19 | val_pos= self.m[val] 20 | self.m[self.data[-1]] = val_pos 21 | self.data[val_pos], self.data[-1] = self.data[-1], self.data[val_pos] 22 | self.m.pop(val) 23 | self.data.pop() 24 | return True 25 | 26 | def getRandom(self) -> int: 27 | return random.choice(self.data) 28 | 29 | 30 | class RandomizedSet: 31 | 32 | def __init__(self): 33 | self.memory = {} 34 | self.values = [] 35 | 36 | 37 | def insert(self, val: int) -> bool: 38 | if val in self.memory: 39 | return False 40 | else: 41 | self.values.append(val) 42 | self.memory[val]=len(self.values)-1 43 | return True 44 | 45 | 46 | def remove(self, val: int) -> bool: 47 | if val not in self.memory: 48 | return False 49 | else: 50 | val_pos = self.memory[val] 51 | self.memory[self.values[-1]] = val_pos 52 | self.values[val_pos], self.values[-1] = self.values[-1], self.values[val_pos] 53 | self.values.pop() 54 | del self.memory[val] 55 | return True 56 | 57 | 58 | def getRandom(self) -> int: 59 | return random.choice(self.values) 60 | 61 | 62 | # Your RandomizedSet object will be instantiated and called as such: 63 | # obj = RandomizedSet() 64 | # param_1 = obj.insert(val) 65 | # param_2 = obj.remove(val) 66 | # param_3 = obj.getRandom() 67 | --------------------------------------------------------------------------------