├── 977 ├── CodeChef ├── Normal │ └── 1.c └── Easy │ ├── a.out │ ├── .7.coin_flip.c.swp │ ├── 7.coin_flip.c │ ├── 3.ciel_and_ab.c │ ├── 6.uncle_johny.py │ ├── 1.life_universe_everything.c │ ├── 4.racing_horses.py │ ├── 2.factorial.c │ └── 5.cleaning_up.py ├── LeetCode ├── cpp │ ├── 977.squarensort.cpp │ ├── 1480.runningsum.cpp │ ├── 1299.greatelementonright.cpp │ ├── 1464.productof2max.cpp │ ├── 561.arraypartition.cpp │ ├── 1304.uniquesum.cpp │ ├── 832.flippingarr.cpp │ ├── 1450.querytime.cpp │ ├── 1502.ap.cpp │ ├── 657.robot.cpp │ ├── 1309.converttochar.cpp │ ├── 1475.discount.cpp │ ├── 709.tolower.cpp │ ├── 1.twosum.cpp │ ├── 589.preorder.cpp │ ├── 590.postorder.cpp │ ├── 1337.kweakestrows.cpp │ ├── 1106.defangingip.cpp │ ├── 905.sortbyparity.cpp │ ├── 700.searchtree.cpp │ ├── 1281.sumandproduct.cpp │ ├── 617.merge2trees.cpp │ ├── 771.jewelsandstones.cpp │ ├── 1470.shufflearray.cpp │ ├── 1374.strwithoddcount.cpp │ ├── 1512.goodpairs.cpp │ ├── 1351.noofnegatives.cpp │ ├── 1486.findxor.cpp │ ├── 1295.numswithevenlen.cpp │ ├── 728.selfdividingnums.cpp │ ├── 1323.max69num.cpp │ ├── 1313.decompress.cpp │ ├── 1221.balancestr.cpp │ ├── 1528.shufflestr.cpp │ ├── 938.rangesumtree.cpp │ ├── 1266.mintime.cpp │ ├── 1460.equalsubarr.cpp │ ├── 1290.listtobin.cpp │ ├── 1432.noofstepsto0.cpp │ ├── 1389.insertatindex.cpp │ ├── 1252.cellswithoddval.cpp │ ├── 804.uniquemorsecode.cpp │ ├── 1431.kidswithcandies.cpp │ └── 1365.prefixsum.cpp ├── Readme.md └── python │ ├── 1491.avgsalary.py │ ├── 169.majorelem.py │ ├── 81.searchinarr2.py │ ├── 33.searchinarr.py │ ├── 41firstnlast.py │ ├── 53.maxsubarray.py │ ├── 557.reversestr.py │ ├── 219..py │ ├── 1550.consequitive3odds.py │ ├── 1441.arraynstack.py │ ├── 121.buynsellstocks.py │ ├── 1403.maxsum.py │ ├── 47.perm2.py │ ├── 922.sortarrbyparity.py │ ├── 496.nextgreatestnum.py │ ├── 217.dup.py │ ├── 503.nextgreatelem.py │ ├── 709.tolower.py │ ├── 1354.triplets.py │ ├── 897.increasingBST.py │ ├── 1.twosum.py │ ├── 69.sqrt.py │ ├── 977.squareandsort.py │ ├── 31.nextperm.py │ ├── 58.lenoflastword.py │ ├── 767.reorgstr.py │ ├── 1237.customfn.py │ ├── 9.palindromenum.py │ ├── 961.repeatntimes.py │ ├── 14.longestprefix.py │ ├── 1299.replacearray.py │ ├── 125.checkpalindrome.py │ ├── 905.sortarrbyparity.py │ ├── 441.arrangingcoins.py │ ├── 1304.uniquesum.py │ ├── 561.arraypartition.py │ ├── 1207.counter.py │ ├── 171.excelcolumnno.py │ ├── 56.mergeintervals.py │ ├── 1281.productandsum.py │ ├── 1108.defrangingip.py │ ├── 164.maxgap.py │ ├── 1470.shufflearray.py │ ├── 896.monotonic.py │ ├── 1464.maxproductinarr.py │ ├── 771.jewelsandstones.py │ ├── 1480.runningsum.py │ ├── 3.long_substr.py │ ├── 101.symtree.py │ ├── 5.longestsubpalindrome.py │ ├── 1295.evenlengths.py │ ├── 516.longestpalindrome.py │ ├── 17.lettercombos.py │ ├── 665.nondecreasingarr.py │ ├── 468.xorops.py │ ├── 538.treedfs.py │ ├── 7.rev.py │ ├── 57.insertinterval.py │ ├── 1502.checkap.py │ ├── 104.depthoftree.py │ ├── 1512.noofgoodpairs.py │ ├── 1374.strwithoddcounts.py │ ├── 16.3sumclosest.py │ ├── 942.DIstrmatch.py │ ├── 938.btreesum.py │ ├── 2.add2num.py │ ├── 461.hammingdistance.py │ ├── 728.selfdividingnumbers.py │ ├── 589.narytreepreorder.py │ ├── 6.zigzag.py │ ├── 20.validparenthesis.py │ ├── 1323.max69num.py │ ├── 1313.decompresslist.py │ ├── 1432.stepstozero.py │ ├── 700.searchbinarytree.py │ ├── 1051.heightchecker.py │ ├── 100.sametre.py │ ├── 559.maxdpth.py │ ├── 1356.sortintbyparity.py │ ├── 590.narytreepostorder.py │ ├── 657.robotturns.py │ ├── 1309.decryptstring.py │ ├── 1266.minvisitingtime.py │ ├── 1290.bintointlinkedlist.py │ ├── 832.flippingimage.py │ ├── 11.watercontainer.py │ ├── 1221.splittingstrings.py │ ├── 1528.shufflestring.py │ ├── 75.sortcolor.py │ ├── 15.3sum.py │ ├── 1038.btree.py │ ├── 617.merge2trees.py │ ├── 1460.canbeequal.py │ ├── 1436.destinationcity.py │ ├── 1252.arrwithoddvalues.py │ ├── 1389.insertinorder.py │ ├── 38.countandsay.py │ ├── 1365.largenumbers.py │ ├── 997.judgetrust.py │ ├── 155.designminstack.py │ ├── 26.remduplicates.py │ ├── 1337.weakrow.py │ ├── 18.4sum.py │ ├── 1380.luckynum.py │ ├── 27.remelement.py │ ├── 804.uniquemorsecode.py │ ├── 1475.finalprices.py │ ├── 1450.studentsdoingwork.py │ ├── 12.inttoroman.py │ ├── 13.romtoint.py │ ├── 1431.kids&candies.py │ └── 1021.remoutparenthesis.py ├── projecteuler ├── a.out ├── coded_triangle_no.py ├── power_digit_sum.py ├── factorial_digit_sum.py ├── multiples_of_3and_5.c ├── powerful_digit_sum.py ├── even_fibbonaci_num.py ├── double_base_palin.py ├── largest_prime_factor.c ├── Nth_Prime.c └── Nth_Fibonacci.c ├── HackerRank ├── Python │ ├── Easy │ │ ├── .vscode │ │ │ └── settings.json │ │ ├── reshape.py │ │ ├── transpose_flatten.py │ │ ├── list.py │ │ ├── array.py │ │ ├── findpercent.py │ │ ├── swapcase.py │ │ ├── hash.py │ │ ├── join.py │ │ └── nestedlist.py │ └── Medium │ │ └── mergetools.py └── CPP │ ├── 2Darraydesign.cpp │ └── newyearchaos.cpp ├── HackerEarth ├── codearena │ ├── a.out │ └── fibonacci.cpp ├── practice │ ├── tier0 │ │ ├── a.out │ │ ├── .vscode │ │ │ └── settings.json │ │ └── terribleChandu.cpp │ └── tier1 │ │ ├── sorting │ │ ├── a.out │ │ ├── chanduNgirlfriend.cpp │ │ ├── puchiNluggage.cpp │ │ └── chanduNgirlfriendret.cpp │ │ └── searching │ │ ├── a.out │ │ └── discoverthemonk.cpp └── monthly_circuits │ └── sep │ └── taxi.cpp ├── CodeForces └── practice │ ├── 4a.watermelon.py │ └── 1a.theatre.py ├── LeetCode2025 └── 1.TwoSum.py ├── CodeJam ├── foregone_solutions.py ├── foregone_solutions.py.save └── foregone.cpp ├── 942.strmatch.cpp ├── README.md └── GeeksForGeeks ├── longest_parenthesis.py ├── max_index.py ├── subarray.py └── decodingstrings.py /977: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /CodeChef/Normal/1.c: -------------------------------------------------------------------------------- 1 | Helo 2 | -------------------------------------------------------------------------------- /LeetCode/cpp/977.squarensort.cpp: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /LeetCode/Readme.md: -------------------------------------------------------------------------------- 1 | All questions can be found at https://leetcode.com/problemset/all/ 2 | -------------------------------------------------------------------------------- /projecteuler/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nikhil713/Algorithms/HEAD/projecteuler/a.out -------------------------------------------------------------------------------- /CodeChef/Easy/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nikhil713/Algorithms/HEAD/CodeChef/Easy/a.out -------------------------------------------------------------------------------- /HackerRank/Python/Easy/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "/usr/bin/python3" 3 | } -------------------------------------------------------------------------------- /HackerEarth/codearena/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nikhil713/Algorithms/HEAD/HackerEarth/codearena/a.out -------------------------------------------------------------------------------- /CodeChef/Easy/.7.coin_flip.c.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nikhil713/Algorithms/HEAD/CodeChef/Easy/.7.coin_flip.c.swp -------------------------------------------------------------------------------- /HackerEarth/practice/tier0/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nikhil713/Algorithms/HEAD/HackerEarth/practice/tier0/a.out -------------------------------------------------------------------------------- /HackerEarth/practice/tier0/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "iostream": "cpp" 4 | } 5 | } -------------------------------------------------------------------------------- /CodeForces/practice/4a.watermelon.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | if n % 2 ==0 and n > 2: 3 | print('YES') 4 | else: 5 | print('NO') -------------------------------------------------------------------------------- /HackerEarth/practice/tier1/sorting/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nikhil713/Algorithms/HEAD/HackerEarth/practice/tier1/sorting/a.out -------------------------------------------------------------------------------- /HackerEarth/practice/tier1/searching/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nikhil713/Algorithms/HEAD/HackerEarth/practice/tier1/searching/a.out -------------------------------------------------------------------------------- /LeetCode/python/1491.avgsalary.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def average(self, salary: List[int]) -> float: 3 | return mean(sorted(salary)[1:-1]) -------------------------------------------------------------------------------- /LeetCode/python/169.majorelem.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def majorityElement(self, nums: List[int]) -> int: 3 | nums.sort() 4 | return nums[len(nums)//2] -------------------------------------------------------------------------------- /LeetCode/python/81.searchinarr2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def search(self, nums: List[int], target: int) -> bool: 3 | if target in nums: 4 | return True 5 | return False -------------------------------------------------------------------------------- /HackerRank/Python/Easy/reshape.py: -------------------------------------------------------------------------------- 1 | import numpy 2 | 3 | 4 | arr=input().split() 5 | for _ in range(len(arr)): 6 | arr[_]=int(arr[_]) 7 | array1=numpy.array(arr) 8 | print(numpy.reshape(array1,(3,3))) -------------------------------------------------------------------------------- /HackerRank/Python/Easy/transpose_flatten.py: -------------------------------------------------------------------------------- 1 | import numpy 2 | 3 | narr = numpy.array([input().split() for _ in range(int(input().split()[0]))],int) 4 | print(narr.transpose()) 5 | print(narr.flatten()) -------------------------------------------------------------------------------- /LeetCode/python/33.searchinarr.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def search(self, nums: List[int], target: int) -> int: 3 | if target in nums: 4 | return nums.index(target) 5 | else: 6 | return -1 -------------------------------------------------------------------------------- /CodeChef/Easy/7.coin_flip.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void main() 4 | { 5 | int tcase; 6 | scanf("%d",&tcase); 7 | 8 | scanf("%d",&nogames); 9 | scanf("%d",&instate); 10 | scanf("%d",&nocoins); 11 | scanf("%d",&quest); 12 | 13 | -------------------------------------------------------------------------------- /projecteuler/coded_triangle_no.py: -------------------------------------------------------------------------------- 1 | import math 2 | T=int(input().strip()) 3 | for i in range(1,T+1): 4 | t=int(input().strip()) 5 | k=(-1+math.sqrt(1+8*t)) 6 | if(k%2==0): 7 | print(int(k/2)) 8 | else: 9 | print(-1) 10 | 11 | -------------------------------------------------------------------------------- /projecteuler/power_digit_sum.py: -------------------------------------------------------------------------------- 1 | T=int(input()) 2 | for i in range(T): 3 | N=int(input()) 4 | power=2**N 5 | S=0 6 | while(power!=0): 7 | d=power%10 8 | power=power//10 9 | S=S+d 10 | print(S) 11 | -------------------------------------------------------------------------------- /CodeChef/Easy/3.ciel_and_ab.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int a,b; 6 | scanf("%d",&a); 7 | scanf("%d",&b); 8 | if((a-b)%10==9) 9 | printf("%d",a-b-1); 10 | else 11 | printf("%d",a-b+1); 12 | return(0); 13 | } 14 | 15 | -------------------------------------------------------------------------------- /LeetCode/python/41firstnlast.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchRange(self, nums: List[int], target: int) -> List[int]: 3 | if target in nums: 4 | return [nums.index(target),len(nums) - 1 - nums[::-1].index(target)] 5 | return [-1,-1] -------------------------------------------------------------------------------- /HackerRank/Python/Easy/list.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | x = int(input()) 3 | y = int(input()) 4 | z = int(input()) 5 | n = int(input()) 6 | print([[a,b,c] for a in range(0,x+1) for b in range(0,y+1) for c in range(0,z+1) if(a+b+c)!=n]) 7 | -------------------------------------------------------------------------------- /LeetCode/python/53.maxsubarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSubArray(self, nums: List[int]) -> int: 3 | res = temp = nums[0] 4 | for i in nums[1:]: 5 | temp = max(i,temp + i) 6 | res = max(res,temp) 7 | return res -------------------------------------------------------------------------------- /LeetCode/python/557.reversestr.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseWords(self, s: str) -> str: 3 | 4 | arr = s.split() 5 | for i in range(len(arr)): 6 | arr[i] = arr[i][::-1] 7 | res = ' '.join(arr) 8 | return res 9 | -------------------------------------------------------------------------------- /HackerEarth/monthly_circuits/sep/taxi.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | int dist,on_firstpay,on_first,on_rest,cl_speed,cl_base,cl_min,cl_dist,onpay,clpay; 9 | 10 | scanf("%d",&dist); 11 | 12 | 13 | } -------------------------------------------------------------------------------- /HackerRank/Python/Easy/array.py: -------------------------------------------------------------------------------- 1 | import numpy 2 | 3 | def arrays(arr): 4 | # complete this function 5 | # use numpy.array 6 | a=numpy.array(arr[::-1],float) 7 | return(a) 8 | 9 | 10 | arr = input().strip().split(' ') 11 | result = arrays(arr) 12 | print(result) -------------------------------------------------------------------------------- /LeetCode2025/1.TwoSum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums: List[int], target: int) -> List[int]: 3 | for i in range(len(nums)): 4 | for j in range(i + 1, len(nums)): 5 | if nums[i] + nums[j] == target: 6 | return [i, j] -------------------------------------------------------------------------------- /CodeChef/Easy/6.uncle_johny.py: -------------------------------------------------------------------------------- 1 | tcase=int(input()) 2 | num1=0 3 | for i in range(tcase): 4 | no=int(input()) 5 | numbers=input().split() 6 | num=int(input()) 7 | num1=numbers[num-1] 8 | numbers.sort(key=int) 9 | for j in range(no): 10 | if(numbers[j]==num1): 11 | print(j+1) 12 | -------------------------------------------------------------------------------- /CodeChef/Easy/1.life_universe_everything.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int x,j,c=0,i=0,a[100]; 6 | while(c!=42) 7 | { 8 | scanf("%d",&x); 9 | c=x; 10 | a[i]=x; 11 | i++; 12 | } 13 | for(j=0;j bool: 3 | hashmap = {} 4 | for i,v in enumerate(nums): 5 | if v in hashmap and i - hashmap[v] <= k: 6 | return True 7 | hashmap[v] = i 8 | return False -------------------------------------------------------------------------------- /CodeChef/Easy/4.racing_horses.py: -------------------------------------------------------------------------------- 1 | tcase=int(input()) 2 | for i in range(tcase): 3 | num=int(input()) 4 | arr=input().split() 5 | for i in range(num): 6 | arr[i]=int(arr[i]) 7 | arr.sort() 8 | small=arr[1]-arr[0] 9 | for i in range(num-1): 10 | if(arr[i+1]-arr[i] runningSum(vector& nums) { 4 | int sum = 0; 5 | vectorarr; 6 | for(int i=0;i< nums.size();i++){ 7 | sum += nums[i]; 8 | arr.push_back(sum); 9 | } 10 | return arr; 11 | } 12 | }; -------------------------------------------------------------------------------- /CodeChef/Easy/2.factorial.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int i,no,a,c5; 6 | scanf("%d",&no); 7 | int b[no]; 8 | for(i=0;i=5) 13 | { 14 | c5+=a/5; 15 | a/=5; 16 | } 17 | b[i]=c5; 18 | } 19 | for(i=0;i replaceElements(vector& arr) { 4 | vector res = arr; 5 | int g = -1; 6 | for(int i = arr.size()-1;i >= 0;i--){ 7 | res[i] = g; 8 | g = max(g,arr[i]); 9 | } 10 | return res; 11 | } 12 | }; -------------------------------------------------------------------------------- /LeetCode/cpp/1464.productof2max.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProduct(vector& nums) { 4 | vector nums1 = nums; 5 | sort(nums1.begin(),nums1.end(),greater()); 6 | int last = nums1[0]; 7 | int seclast = nums1[1]; 8 | 9 | return ((last-1 ) * (seclast - 1)) ; 10 | } 11 | }; -------------------------------------------------------------------------------- /LeetCode/python/1550.consequitive3odds.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def threeConsecutiveOdds(self, arr: List[int]) -> bool: 3 | count = 0 4 | for i in arr: 5 | if i % 2==1: 6 | count+=1 7 | else: 8 | count = 0 9 | if count == 3: 10 | return True 11 | return False -------------------------------------------------------------------------------- /LeetCode/python/1441.arraynstack.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def buildArray(self, target: List[int], n: int) -> List[str]: 3 | res = [] 4 | for i in range(1,n+1): 5 | res.append('Push') 6 | if i not in target: 7 | res.append('Pop') 8 | if i == target[-1]: 9 | break 10 | return res -------------------------------------------------------------------------------- /HackerEarth/codearena/fibonacci.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void fib(int end) 6 | { 7 | string str = "a"; 8 | string str1 ="A"; 9 | str1.append(str); 10 | cout<>start>>end; 18 | fib(end); 19 | return 0; 20 | } -------------------------------------------------------------------------------- /LeetCode/cpp/561.arraypartition.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int arrayPairSum(vector& nums) { 4 | sort(nums.begin(),nums.end()); 5 | int sum = 0; 6 | for(int i = 0; i sumZero(int n) { 4 | int i; 5 | vector res; 6 | for(i = 1 ; i < n/2 + 1; i++){ 7 | res.push_back(i); 8 | res.push_back(-i); 9 | } 10 | if( n % 2 == 1){ 11 | res.push_back(0); 12 | } 13 | return res; 14 | } 15 | }; -------------------------------------------------------------------------------- /LeetCode/cpp/832.flippingarr.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> flipAndInvertImage(vector>& A) { 4 | for( auto &i : A){ 5 | reverse(i.begin(),i.end()); 6 | } 7 | for( auto &i :A){ 8 | for( auto &j : i){ 9 | j = j^1; 10 | } 11 | } 12 | return A; 13 | } 14 | }; -------------------------------------------------------------------------------- /LeetCode/cpp/1450.querytime.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int busyStudent(vector& startTime, vector& endTime, int queryTime) { 4 | int res=0; 5 | for(int i =0 ;i < startTime.size();i++){ 6 | if (queryTime>=startTime[i] && queryTime <= endTime[i]){ 7 | res++; 8 | } 9 | } 10 | return res; 11 | } 12 | }; -------------------------------------------------------------------------------- /LeetCode/cpp/1502.ap.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canMakeArithmeticProgression(vector& arr) { 4 | sort(arr.begin(),arr.end()); 5 | int dif = arr[1] - arr[0]; 6 | for(int i = 0; i < arr.size() - 1;i++){ 7 | if(arr[i+1] -arr[i] != dif){ 8 | return false; 9 | } 10 | } 11 | return true; 12 | } 13 | }; -------------------------------------------------------------------------------- /LeetCode/python/121.buynsellstocks.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices: List[int]) -> int: 3 | if len(prices) <= 1: 4 | return 0 5 | lowest = prices[0] 6 | profit = 0 7 | 8 | for i in range(len(prices)): 9 | lowest = min(lowest,prices[i]) 10 | profit = max(profit,prices[i] - lowest) 11 | return profit -------------------------------------------------------------------------------- /projecteuler/multiples_of_3and_5.c: -------------------------------------------------------------------------------- 1 | //Project Euler Problem :1 2 | 3 | 4 | #include 5 | 6 | ///sum of multiples of 3 and 5 7 | 8 | void main() 9 | { 10 | int n,Sum=0; 11 | printf("enter the number\n"); 12 | scanf("%d",&n); 13 | for(int i=1;i 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | int i,tcase; 10 | cin>>tcase; 11 | for(i=0;i<=tcase;i++) 12 | { 13 | string str; 14 | getline(cin,str); 15 | reverse(str.begin(),str.end()); 16 | cout< List[int]: 3 | totsum = sum(nums) 4 | nums.sort(reverse = True) 5 | res = [] 6 | temp = 0 7 | for i in range(len(nums)): 8 | temp += nums[i] 9 | res.append(nums[i]) 10 | if temp > totsum - temp: 11 | break 12 | return res 13 | -------------------------------------------------------------------------------- /LeetCode/python/47.perm2.py: -------------------------------------------------------------------------------- 1 | # Given a collection of numbers that might contain duplicates, return all possible unique permutations. 2 | 3 | # Example: 4 | 5 | # Input: [1,1,2] 6 | # Output: 7 | # [ 8 | # [1,1,2], 9 | # [1,2,1], 10 | # [2,1,1] 11 | # ] 12 | 13 | 14 | class Solution: 15 | def permuteUnique(self, nums: List[int]) -> List[List[int]]: 16 | nums = permutations(nums) 17 | return set(nums) -------------------------------------------------------------------------------- /LeetCode/python/922.sortarrbyparity.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortArrayByParityII(self, A: List[int]) -> List[int]: 3 | odd = [] 4 | even = [] 5 | for i in A: 6 | if i%2 == 0: 7 | even.append(i) 8 | else: 9 | odd.append(i) 10 | for i in range(len(A)//2): 11 | A[2*i] = even[i] 12 | A[2*i+1] = odd[i] 13 | return A -------------------------------------------------------------------------------- /HackerRank/Python/Easy/findpercent.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | n = int(input()) 3 | student_marks = {} 4 | for _ in range(n): 5 | name, *line = input().split() 6 | scores = list(map(float, line)) 7 | student_marks[name] = scores 8 | query_name = input() 9 | avg=0 10 | i=0 11 | for i in range(3): 12 | avg=avg+student_marks[query_name][i] 13 | print("{0:.2f}".format(avg/3)) 14 | -------------------------------------------------------------------------------- /HackerRank/Python/Medium/mergetools.py: -------------------------------------------------------------------------------- 1 | def merge_the_tools(string, k): 2 | # your code goes here 3 | res = [] 4 | for i in range(len(string)): 5 | if string[i] not in res: 6 | res.append(string[i]) 7 | if (i+1)%k == 0: 8 | print(''.join(res)) 9 | res = [] 10 | 11 | 12 | if __name__ == '__main__': 13 | string, k = raw_input(), int(raw_input()) 14 | merge_the_tools(string, k) -------------------------------------------------------------------------------- /LeetCode/python/496.nextgreatestnum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: 3 | res = [] 4 | for i in nums1: 5 | temp = -1 6 | start = nums2.index(i) 7 | for j in nums2[start:]: 8 | if i < j: 9 | temp = j 10 | break 11 | res.append(temp) 12 | return res -------------------------------------------------------------------------------- /CodeJam/foregone_solutions.py.save: -------------------------------------------------------------------------------- 1 | # Question: https://codingcompetitions.withgoogle.com/codejam/round/000000000005170 2 | tcase=int(input()) 3 | for i in range(tcase): 4 | arr=list(map(int,str(input()))) 5 | print(arr) 6 | b=0 7 | arr.reverse() 8 | for j in range(len(arr)): 9 | if arr[j]==4: 10 | arr[j]-=1 11 | 12 | b+=10**j 13 | arr.reverse() 14 | 15 | "".join(str(arr)) 16 | print(int(arr)) 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /projecteuler/even_fibbonaci_num.py: -------------------------------------------------------------------------------- 1 | #Project Euler Problem: 2 2 | 3 | #!/bin/python3 4 | 5 | import sys 6 | 7 | 8 | t = int(input().strip()) 9 | for a0 in range(t): 10 | n = int(input().strip()) 11 | i,k,s=1,2,0 12 | while(i bool: 3 | arr = [] 4 | nums.sort() 5 | for i in range(len(nums) - 1): 6 | if nums[i] == nums[i+1]: 7 | return True 8 | return False 9 | 10 | class Solution: 11 | def containsDuplicate(self, nums: List[int]) -> bool: 12 | if len(nums) == len(set(nums)): 13 | return False 14 | return True -------------------------------------------------------------------------------- /LeetCode/python/503.nextgreatelem.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def nextGreaterElements(self, nums: List[int]) -> List[int]: 3 | nums1 = nums[:] 4 | nums += nums 5 | res = [] 6 | for i in range(len(nums1)): 7 | temp = -1 8 | for j in range(i,len(nums)): 9 | if nums[j] > nums1[i]: 10 | temp = nums[j] 11 | break 12 | res.append(temp) 13 | return res -------------------------------------------------------------------------------- /LeetCode/python/709.tolower.py: -------------------------------------------------------------------------------- 1 | # Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase. 2 | 3 | 4 | 5 | # Example 1: 6 | 7 | # Input: "Hello" 8 | # Output: "hello" 9 | 10 | # Example 2: 11 | 12 | # Input: "here" 13 | # Output: "here" 14 | 15 | # Example 3: 16 | 17 | # Input: "LOVELY" 18 | # Output: "lovely" 19 | 20 | 21 | class Solution: 22 | def toLowerCase(self, str: str) -> str: 23 | return(str.lower()) -------------------------------------------------------------------------------- /LeetCode/cpp/657.robot.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool judgeCircle(string moves) { 4 | int cU,cD,cL,cR; 5 | cU = count(moves.begin(),moves.end(),'U'); 6 | cD = count(moves.begin(),moves.end(),'D'); 7 | cL = count(moves.begin(),moves.end(),'L'); 8 | cR = count(moves.begin(),moves.end(),'R'); 9 | if( cU == cD && cL == cR){ 10 | return true; 11 | } 12 | else{ 13 | return false; 14 | } 15 | } 16 | }; -------------------------------------------------------------------------------- /LeetCode/cpp/1309.converttochar.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string freqAlphabets(string s) { 4 | int i=0; 5 | string res; 6 | while( i < s.size()){ 7 | if (i < s.size() - 2 && s[i+2] == '#'){ 8 | res += 'a' - 1 + (s[i] - '0')*10 + (s[i+1] - '0'); 9 | i+=3; 10 | } 11 | else{ 12 | res += 'a'- 1 + (s[i] - '0'); 13 | i++; 14 | } 15 | } 16 | return res; 17 | } 18 | }; -------------------------------------------------------------------------------- /LeetCode/python/1354.triplets.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int: 3 | res = 0 4 | for i in range(len(arr)): 5 | for j in range(i+1,len(arr)): 6 | for k in range(j+1,len(arr)): 7 | if( abs(arr[i] - arr[j]) <= a): 8 | if( abs( arr[j] - arr[k]) <= b): 9 | if( abs(arr[i] - arr[k]) <= c): 10 | res += 1 11 | return res -------------------------------------------------------------------------------- /CodeChef/Easy/5.cleaning_up.py: -------------------------------------------------------------------------------- 1 | 2 | tcase=int(input()) 3 | for i in range(tcase): 4 | count=0 5 | chef='' 6 | assistant='' 7 | jobs=input().split() 8 | total=int(jobs[0]) 9 | completed_no=int(jobs[1]) 10 | completed=input().split() 11 | for j in range(completed_no): 12 | completed[j]=int(completed[j]) 13 | completed.sort() 14 | for j in range(1,total+1): 15 | if j not in completed: 16 | if(count%2==0): 17 | chef+=str(j)+' ' 18 | else: 19 | assistant+=str(j)+' ' 20 | count+=1 21 | print(chef) 22 | print(assistant) 23 | -------------------------------------------------------------------------------- /942.strmatch.cpp: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def diStringMatch(self, S: str) -> List[int]: 3 | arr = [] 4 | low = 0 5 | high = len(S) 6 | i = 0 7 | while ( i < len(S)): 8 | if S[i] == 'I': 9 | arr.append(low) 10 | low += 1 11 | if S[i] == 'D': 12 | arr.append(high) 13 | high -= 1 14 | i += 1 15 | if S[-1] == 'D': 16 | arr.append(high) 17 | else: 18 | arr.append(low) 19 | return arr -------------------------------------------------------------------------------- /LeetCode/python/897.increasingBST.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 increasingBST(self, root: TreeNode, tail = None) -> TreeNode: 9 | if not root: 10 | return tail 11 | res = self.increasingBST(root.left,root) 12 | root.left = None 13 | root.right = self.increasingBST(root.right,tail) 14 | return res -------------------------------------------------------------------------------- /LeetCode/cpp/1475.discount.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector finalPrices(vector& prices) { 4 | vector res; 5 | int i,j,temp; 6 | for( i = 0 ; iCompetitive Coding 2 |

3 | Solutions to some questions in the online coding platforms 4 |
5 | Links to the coding platforms mentioned above: 6 | 7 | CodeChef: https://www.codechef.com/ 8 |
9 | HackerEarth: https://www.hackerearth.com/challenges/ 10 |
11 | HackerRank: https://www.hackerrank.com/challenges/ 12 |
13 | CodeJam: https://codingcompetitions.withgoogle.com/codejam 14 |
15 | Project Euler : https://www.projecteuler.net/ 16 |
17 | LeetCode : https://leetcode.com/problemset/all/ 18 |
19 | GeeksForGeeks : https://www.geeksforgeeks.org/ -------------------------------------------------------------------------------- /LeetCode/cpp/1.twosum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class Solution { 5 | public: 6 | vector twoSum(vector& nums, int target) { 7 | int flag,i,j; 8 | for (i=0;i List[int]: 15 | for i in range(len(nums)): 16 | if target - nums[i] in nums[i+1:]: 17 | return(i, nums.index(target - nums[i],i+1)) -------------------------------------------------------------------------------- /GeeksForGeeks/longest_parenthesis.py: -------------------------------------------------------------------------------- 1 | #code 2 | 3 | tcase = int(input()) 4 | 5 | for i in range(tcase): 6 | 7 | arr = list(input()) 8 | 9 | stack = [] 10 | maxdiff = 0 11 | size = len(arr) 12 | j=0 13 | 14 | print (arr) 15 | for i in range(size): 16 | 17 | if (arr[i] == '('): 18 | stack.push('(') 19 | j+=1 20 | if (arr[i] == ')') and stack.empty() != 0: 21 | stack.pop() 22 | j+=1 23 | if (len(stack) == 0): 24 | maxdiff = j 25 | j=0 26 | print (stack , j ,maxdiff) 27 | 28 | print(maxdiff) -------------------------------------------------------------------------------- /HackerRank/Python/Easy/swapcase.py: -------------------------------------------------------------------------------- 1 | You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa. 2 | 3 | For Example: 4 | 5 | Www.HackerRank.com → wWW.hACKERrANK.COM 6 | Pythonist 2 → pYTHONIST 2 7 | 8 | Input Format 9 | 10 | A single line containing a string 11 | 12 | . 13 | 14 | Constraints 15 | 16 | Output Format 17 | 18 | Print the modified string 19 | 20 | . 21 | 22 | Sample Input 0 23 | 24 | HackerRank.com presents "Pythonist 2". 25 | 26 | Sample Output 0 27 | 28 | hACKERrANK.COM PRESENTS "pYTHONIST 2". 29 | 30 | def swap_case(s): 31 | return s.swapcase() 32 | 33 | -------------------------------------------------------------------------------- /LeetCode/python/69.sqrt.py: -------------------------------------------------------------------------------- 1 | # Implement int sqrt(int x). 2 | 3 | # Compute and return the square root of x, where x is guaranteed to be a non-negative integer. 4 | 5 | # Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. 6 | 7 | # Example 1: 8 | 9 | # Input: 4 10 | # Output: 2 11 | 12 | # Example 2: 13 | 14 | # Input: 8 15 | # Output: 2 16 | # Explanation: The square root of 8 is 2.82842..., and since 17 | # the decimal part is truncated, 2 is returned. 18 | 19 | 20 | 21 | class Solution: 22 | def mySqrt(self, x: int) -> int: 23 | return(int(sqrt(x))) 24 | -------------------------------------------------------------------------------- /LeetCode/cpp/589.preorder.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | // Definition for a Node. 3 | class Node { 4 | public: 5 | int val; 6 | vector children; 7 | 8 | Node() {} 9 | 10 | Node(int _val) { 11 | val = _val; 12 | } 13 | 14 | Node(int _val, vector _children) { 15 | val = _val; 16 | children = _children; 17 | } 18 | }; 19 | */ 20 | 21 | class Solution { 22 | public: 23 | vector res; 24 | vector preorder(Node* root) { 25 | if(root){ 26 | res.push_back(root->val); 27 | for(auto i : root->children){ 28 | preorder(i); 29 | } 30 | } 31 | return res; 32 | } 33 | }; -------------------------------------------------------------------------------- /LeetCode/python/977.squareandsort.py: -------------------------------------------------------------------------------- 1 | # Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. 2 | 3 | 4 | 5 | # Example 1: 6 | 7 | # Input: [-4,-1,0,3,10] 8 | # Output: [0,1,9,16,100] 9 | 10 | # Example 2: 11 | 12 | # Input: [-7,-3,2,3,11] 13 | # Output: [4,9,9,49,121] 14 | 15 | 16 | 17 | # Note: 18 | 19 | # 1 <= A.length <= 10000 20 | # -10000 <= A[i] <= 10000 21 | # A is sorted in non-decreasing order. 22 | 23 | class Solution: 24 | def sortedSquares(self, A: List[int]) -> List[int]: 25 | for i in range(len(A)): 26 | A[i] *= A[i] 27 | return sorted(A) -------------------------------------------------------------------------------- /LeetCode/cpp/590.postorder.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | // Definition for a Node. 3 | class Node { 4 | public: 5 | int val; 6 | vector children; 7 | 8 | Node() {} 9 | 10 | Node(int _val) { 11 | val = _val; 12 | } 13 | 14 | Node(int _val, vector _children) { 15 | val = _val; 16 | children = _children; 17 | } 18 | }; 19 | */ 20 | 21 | class Solution { 22 | public: 23 | vector res; 24 | vector postorder(Node* root) { 25 | if(root){ 26 | for(auto i: root->children){ 27 | postorder(i); 28 | } 29 | res.push_back(root->val); 30 | } 31 | return res; 32 | } 33 | }; -------------------------------------------------------------------------------- /LeetCode/python/31.nextperm.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def nextPermutation(self, nums: List[int]) -> None: 3 | """ 4 | Do not return anything, modify nums in-place instead. 5 | """ 6 | index = len(nums) - 2 7 | while(index >= 0): 8 | if nums[index] < nums[index+1]: 9 | break 10 | index-=1 11 | 12 | if index < 0: 13 | nums.sort() 14 | return nums 15 | 16 | nindex = index + 1 17 | while nindex < len(nums) and nums[nindex] > nums[index]: 18 | nindex += 1 19 | nums[nindex-1],nums[index] = nums[index], nums[nindex-1] 20 | nums[index+1:] = nums[index+1:][::-1] -------------------------------------------------------------------------------- /HackerEarth/practice/tier1/sorting/chanduNgirlfriend.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | // #include 4 | 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | int tcase,i; 10 | int j,array_size; 11 | scanf("%d",&tcase); 12 | 13 | for(i=0;i()); 24 | for(j=0;j int: 14 | if not s: 15 | return 0 16 | elif s.strip()== "": 17 | return 0 18 | else: 19 | arr=s.split() 20 | return(len(arr[-1])) -------------------------------------------------------------------------------- /LeetCode/python/767.reorgstr.py: -------------------------------------------------------------------------------- 1 | # Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same. 2 | 3 | # If possible, output any possible result. If not possible, return the empty string. 4 | 5 | # Example 1: 6 | 7 | # Input: S = "aab" 8 | # Output: "aba" 9 | 10 | # Example 2: 11 | 12 | # Input: S = "aaab" 13 | # Output: "" 14 | 15 | # Note: 16 | 17 | # S will consist of lowercase letters and have length in range [1, 500]. 18 | 19 | class Solution: 20 | def reorganizeString(self, S: str) -> str: 21 | a = sorted(sorted(S),key = S.count) 22 | l = len(a)//2 23 | a[1::2],a[::2] = a[:l],a[l:] 24 | return ''.join(a) * (a[-1:] != a[-2:-1]) -------------------------------------------------------------------------------- /LeetCode/cpp/1337.kweakestrows.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector kWeakestRows(vector>& mat, int k) { 4 | vector> mat2 = mat; 5 | sort(mat2.begin(),mat2.end()); 6 | vector res; 7 | vector temp(mat2[0].size(),-1); 8 | int ind,j=0; 9 | for (int i = 0; i List[List[int]]: 14 | res = [] 15 | for i in range(1,z+1): 16 | for j in range(1,z+1): 17 | if customfunction.f(i,j) == z: 18 | res.append([i,j]) 19 | return res -------------------------------------------------------------------------------- /LeetCode/python/9.palindromenum.py: -------------------------------------------------------------------------------- 1 | # Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. 2 | 3 | # Example 1: 4 | 5 | # Input: 121 6 | # Output: true 7 | 8 | # Example 2: 9 | 10 | # Input: -121 11 | # Output: false 12 | # Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. 13 | 14 | # Example 3: 15 | 16 | # Input: 10 17 | # Output: false 18 | # Explanation: Reads 01 from right to left. Therefore it is not a palindrome. 19 | 20 | class Solution: 21 | def isPalindrome(self, x: int) -> bool: 22 | s = str(x) 23 | s1 = s[::-1] 24 | if s == s1: 25 | return True 26 | else: 27 | return False -------------------------------------------------------------------------------- /projecteuler/largest_prime_factor.c: -------------------------------------------------------------------------------- 1 | /* This program is used to find 2 | the largest prime factor of a number */ 3 | 4 | 5 | #include 6 | #include 7 | 8 | int Lprime(int num) 9 | { 10 | int big; 11 | while(num%2==0) 12 | {big=2; 13 | num/=2; 14 | } 15 | for(int i=3;i<=num/2;i+=2) 16 | { 17 | while(num%i==0) 18 | {big=i; 19 | num/=i; 20 | } 21 | } 22 | if(num>2) 23 | big=num; 24 | 25 | return big; 26 | } 27 | 28 | 29 | 30 | 31 | 32 | void main() 33 | { 34 | int T,N,i,maxprime; 35 | printf("Enter the no of test cases\n"); 36 | scanf("%d",&T); 37 | for(i=1;i<=T;i++) 38 | {printf("\nEnter the number\n"); 39 | scanf("%d",&N); 40 | maxprime=Lprime(N); 41 | printf("the largest prime is %d \n",maxprime); 42 | } 43 | 44 | 45 | } 46 | 47 | -------------------------------------------------------------------------------- /LeetCode/python/961.repeatntimes.py: -------------------------------------------------------------------------------- 1 | # In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times. 2 | 3 | # Return the element repeated N times. 4 | 5 | 6 | 7 | # Example 1: 8 | 9 | # Input: [1,2,3,3] 10 | # Output: 3 11 | 12 | # Example 2: 13 | 14 | # Input: [2,1,2,5,3,2] 15 | # Output: 2 16 | 17 | # Example 3: 18 | 19 | # Input: [5,1,5,2,5,3,5,4] 20 | # Output: 5 21 | 22 | 23 | 24 | # Note: 25 | 26 | # 4 <= A.length <= 10000 27 | # 0 <= A[i] < 10000 28 | # A.length is even 29 | 30 | class Solution: 31 | def repeatedNTimes(self, A: List[int]) -> int: 32 | for i in range(2,len(A)): 33 | if A[i] == A[i-1] or A[i] == A[i-2]: 34 | return A[i] 35 | return A[0] -------------------------------------------------------------------------------- /LeetCode/python/14.longestprefix.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/longest-common-prefix/ 2 | 3 | # Write a function to find the longest common prefix string amongst an array of strings. 4 | 5 | # If there is no common prefix, return an empty string "". 6 | 7 | # Example 1: 8 | 9 | # Input: ["flower","flow","flight"] 10 | # Output: "fl" 11 | 12 | # Example 2: 13 | 14 | # Input: ["dog","racecar","car"] 15 | # Output: "" 16 | # Explanation: There is no common prefix among the input strings. 17 | 18 | 19 | class Solution: 20 | def longestCommonPrefix(self, m): 21 | if not m: 22 | return '' 23 | 24 | s1 = min(m) 25 | s2 = max(m) 26 | 27 | for i, c in enumerate(s1): 28 | if c != s2[i]: 29 | return s1[:i] 30 | return s1 -------------------------------------------------------------------------------- /projecteuler/Nth_Prime.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include //To find the nth Prime number 3 | #define MAX 10000 4 | 5 | int isPrime(int num) 6 | { 7 | int m,flag=1; 8 | double n=num; 9 | for(m=2;m<(n/2)+1;m++) 10 | { 11 | if(num%m==0) 12 | { 13 | flag=0; 14 | break; 15 | } 16 | } 17 | return(flag); 18 | } 19 | 20 | 21 | 22 | void main() 23 | { 24 | int lim,N,i,arr[MAX]; 25 | printf("No of test cases:"); 26 | scanf("%d",&lim); 27 | for(i=0;i List[int]: 22 | 23 | res = [-1] 24 | greatest = 0 25 | for i in range(len(arr) - 1 , 0 , -1): 26 | if arr[i] > greatest: 27 | greatest = arr[i] 28 | res.append(greatest) 29 | 30 | return res[::-1] -------------------------------------------------------------------------------- /HackerEarth/practice/tier1/searching/discoverthemonk.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int query,i,j,querysize,arraysize,flag=0; 8 | scanf("%d %d",&arraysize,&querysize); 9 | int array[arraysize]; 10 | for(i=0;i bool: 19 | s = s.lower() 20 | s1='' 21 | for i in range(len(s)): 22 | if s[i].isalpha() or s[i].isdigit(): 23 | s1+=s[i] 24 | if s1 == s1[::-1]: 25 | return True 26 | else: 27 | return False 28 | -------------------------------------------------------------------------------- /HackerRank/Python/Easy/hash.py: -------------------------------------------------------------------------------- 1 | Task 2 | Given an integer, , and space-separated integers as input, create a tuple, , of those integers. Then compute and print the result of 3 | 4 | . 5 | 6 | Note: hash() is one of the functions in the __builtins__ module, so it need not be imported. 7 | 8 | Input Format 9 | 10 | The first line contains an integer, 11 | , denoting the number of elements in the tuple. 12 | The second line contains space-separated integers describing the elements in tuple 13 | 14 | . 15 | 16 | Output Format 17 | 18 | Print the result of 19 | 20 | . 21 | 22 | Sample Input 0 23 | 24 | 2 25 | 1 2 26 | 27 | Sample Output 0 28 | 29 | 3713081631934410656 30 | 31 | if __name__ == '__main__': 32 | n = int(input()) 33 | integer_list = map(int, input().split()) 34 | ntup = tuple(integer_list) 35 | print(hash(ntup)) -------------------------------------------------------------------------------- /LeetCode/python/905.sortarrbyparity.py: -------------------------------------------------------------------------------- 1 | # Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A. 2 | 3 | # You may return any answer array that satisfies this condition. 4 | 5 | 6 | 7 | # Example 1: 8 | 9 | # Input: [3,1,2,4] 10 | # Output: [2,4,3,1] 11 | # The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. 12 | 13 | 14 | 15 | # Note: 16 | 17 | # 1 <= A.length <= 5000 18 | # 0 <= A[i] <= 5000 19 | 20 | class Solution: 21 | def sortArrayByParity(self, A: List[int]) -> List[int]: 22 | odd = [] 23 | even = [] 24 | for i in range(len(A)): 25 | if A[i] % 2 == 0: 26 | odd.append(A[i]) 27 | else: 28 | even.append(A[i]) 29 | return(odd + even) -------------------------------------------------------------------------------- /CodeJam/foregone.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | typedef long long ll; 3 | using namespace std; 4 | ll A,B; 5 | void digits(ll Num,vector &Digits){ 6 | ll digit; 7 | while(Num!=0){ 8 | digit= Num%10; 9 | Digits.push_back(digit); 10 | Num = Num/10; 11 | } 12 | } 13 | 14 | void findAB(vector &Digits){ 15 | ll len = Digits.size(),i; 16 | for(i=0;i>T; 29 | for(i=1;i<=T;i++){ 30 | cin>>N; 31 | A= 0; 32 | B = 0; 33 | vector Digits; 34 | digits(N,Digits); 35 | findAB(Digits); 36 | cout<<"Case #"< 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int tcase; 8 | int i,j,k; 9 | int nooffrnds; 10 | scanf("%d",&tcase); 11 | for(i=0;iweights[k]) 25 | { 26 | count++; 27 | } 28 | } 29 | printf("%d ",count); 30 | } 31 | printf("\n"); 32 | } 33 | return 0; 34 | } -------------------------------------------------------------------------------- /LeetCode/python/441.arrangingcoins.py: -------------------------------------------------------------------------------- 1 | # You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins. 2 | 3 | # Given n, find the total number of full staircase rows that can be formed. 4 | 5 | # n is a non-negative integer and fits within the range of a 32-bit signed integer. 6 | 7 | # Example 1: 8 | 9 | # n = 5 10 | 11 | # The coins can form the following rows: 12 | # ¤ 13 | # ¤ ¤ 14 | # ¤ ¤ 15 | 16 | # Because the 3rd row is incomplete, we return 2. 17 | 18 | # Example 2: 19 | 20 | # n = 8 21 | 22 | # The coins can form the following rows: 23 | # ¤ 24 | # ¤ ¤ 25 | # ¤ ¤ ¤ 26 | # ¤ ¤ 27 | 28 | # Because the 4th row is incomplete, we return 3. 29 | 30 | 31 | class Solution: 32 | def arrangeCoins(self, n: int) -> int: 33 | res = (-1 + (1+8*n)**(1/2))/2 34 | return(int(res)) -------------------------------------------------------------------------------- /LeetCode/python/1304.uniquesum.py: -------------------------------------------------------------------------------- 1 | # Given an integer n, return any array containing n unique integers such that they add up to 0. 2 | 3 | 4 | 5 | # Example 1: 6 | 7 | # Input: n = 5 8 | # Output: [-7,-1,1,3,4] 9 | # Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4]. 10 | 11 | # Example 2: 12 | 13 | # Input: n = 3 14 | # Output: [-1,0,1] 15 | 16 | # Example 3: 17 | 18 | # Input: n = 1 19 | # Output: [0] 20 | 21 | 22 | 23 | # Constraints: 24 | 25 | # 1 <= n <= 1000 26 | 27 | class Solution: 28 | def sumZero(self, n: int) -> List[int]: 29 | # arr = [] 30 | # j = 0 31 | # for i in range(n//2): 32 | # j+=1 33 | # arr.append(j) 34 | # arr.append(-1*j) 35 | # if n%2 != 0: 36 | # arr.append(0) 37 | # return arr 38 | return(range(1-n,n,2)) -------------------------------------------------------------------------------- /HackerRank/Python/Easy/join.py: -------------------------------------------------------------------------------- 1 | In Python, a string can be split on a delimiter. 2 | 3 | Example: 4 | 5 | >>> a = "this is a string" 6 | >>> a = a.split(" ") # a is converted to a list of strings. 7 | >>> print a 8 | ['this', 'is', 'a', 'string'] 9 | 10 | Joining a string is simple: 11 | 12 | >>> a = "-".join(a) 13 | >>> print a 14 | this-is-a-string 15 | 16 | Task 17 | You are given a string. Split the string on a " " (space) delimiter and join using a - hyphen. 18 | 19 | Input Format 20 | The first line contains a string consisting of space separated words. 21 | 22 | Output Format 23 | Print the formatted string as explained above. 24 | 25 | Sample Input 26 | 27 | this is a string 28 | 29 | Sample Output 30 | 31 | this-is-a-string 32 | 33 | def split_and_join(line): 34 | # write your code here 35 | line = line.split() 36 | return "-".join(line) -------------------------------------------------------------------------------- /LeetCode/python/561.arraypartition.py: -------------------------------------------------------------------------------- 1 | # Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. 2 | 3 | # Example 1: 4 | 5 | # Input: [1,4,3,2] 6 | 7 | # Output: 4 8 | # Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4). 9 | 10 | # Note: 11 | 12 | # n is a positive integer, which is in the range of [1, 10000]. 13 | # All the integers in the array will be in the range of [-10000, 10000]. 14 | 15 | class Solution: 16 | def arrayPairSum(self, nums: List[int]) -> int: 17 | # sumlast = 0 18 | # nums.sort() 19 | # for i in range(0,len(nums),2): 20 | # sumlast += min(nums[i],nums[i+1]) 21 | # return sumlast 22 | return sum(sorted(nums)[::2]) -------------------------------------------------------------------------------- /LeetCode/python/1207.counter.py: -------------------------------------------------------------------------------- 1 | # Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique. 2 | 3 | 4 | 5 | # Example 1: 6 | 7 | # Input: arr = [1,2,2,1,1,3] 8 | # Output: true 9 | # Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. 10 | 11 | # Example 2: 12 | 13 | # Input: arr = [1,2] 14 | # Output: false 15 | 16 | # Example 3: 17 | 18 | # Input: arr = [-3,0,1,-3,1,1,1,-3,10,0] 19 | # Output: true 20 | 21 | 22 | 23 | # Constraints: 24 | 25 | # 1 <= arr.length <= 1000 26 | # -1000 <= arr[i] <= 1000 27 | 28 | class Solution: 29 | def uniqueOccurrences(self, arr: List[int]) -> bool: 30 | newset = set(arr) 31 | res = [] 32 | for i in newset: 33 | res.append(arr.count(i)) 34 | return len(res) == len(set(res)) -------------------------------------------------------------------------------- /LeetCode/python/171.excelcolumnno.py: -------------------------------------------------------------------------------- 1 | # Given a column title as appear in an Excel sheet, return its corresponding column number. 2 | 3 | # For example: 4 | 5 | # A -> 1 6 | # B -> 2 7 | # C -> 3 8 | # ... 9 | # Z -> 26 10 | # AA -> 27 11 | # AB -> 28 12 | # ... 13 | 14 | # Example 1: 15 | 16 | # Input: "A" 17 | # Output: 1 18 | 19 | # Example 2: 20 | 21 | # Input: "AB" 22 | # Output: 28 23 | 24 | # Example 3: 25 | 26 | # Input: "ZY" 27 | # Output: 701 28 | 29 | 30 | 31 | # Constraints: 32 | 33 | # 1 <= s.length <= 7 34 | # s consists only of uppercase English letters. 35 | # s is between "A" and "FXSHRXW". 36 | 37 | 38 | class Solution: 39 | def titleToNumber(self, s: str) -> int: 40 | count = 0 41 | # print(int('A')) 42 | for i in range(len(s)): 43 | count += (ord(s[i]) - 64) * (26 ** (len(s) - i - 1)) 44 | return count -------------------------------------------------------------------------------- /LeetCode/python/56.mergeintervals.py: -------------------------------------------------------------------------------- 1 | # Given a collection of intervals, merge all overlapping intervals. 2 | 3 | # Example 1: 4 | 5 | # Input: [[1,3],[2,6],[8,10],[15,18]] 6 | # Output: [[1,6],[8,10],[15,18]] 7 | # Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. 8 | 9 | # Example 2: 10 | 11 | # Input: [[1,4],[4,5]] 12 | # Output: [[1,5]] 13 | # Explanation: Intervals [1,4] and [4,5] are considered overlapping. 14 | 15 | class Solution: 16 | def merge(self, intervals: List[List[int]]) -> List[List[int]]: 17 | intervals = sorted(intervals, key=lambda x:x[0]) 18 | i=0 19 | while (i< len(intervals) - 1): 20 | # print(i, intervals) 21 | if(intervals[i][1] >= intervals[i+1][0]): 22 | intervals[i][1]=max(intervals[i][1],intervals[i+1][1]) 23 | del intervals[i+1] 24 | else: 25 | i+=1 26 | return intervals -------------------------------------------------------------------------------- /LeetCode/python/1281.productandsum.py: -------------------------------------------------------------------------------- 1 | # Given an integer number n, return the difference between the product of its digits and the sum of its digits. 2 | 3 | 4 | 5 | # Example 1: 6 | 7 | # Input: n = 234 8 | # Output: 15 9 | # Explanation: 10 | # Product of digits = 2 * 3 * 4 = 24 11 | # Sum of digits = 2 + 3 + 4 = 9 12 | # Result = 24 - 9 = 15 13 | 14 | # Example 2: 15 | 16 | # Input: n = 4421 17 | # Output: 21 18 | # Explanation: 19 | # Product of digits = 4 * 4 * 2 * 1 = 32 20 | # Sum of digits = 4 + 4 + 2 + 1 = 11 21 | # Result = 32 - 11 = 21 22 | 23 | 24 | 25 | # Constraints: 26 | 27 | # 1 <= n <= 10^5 28 | 29 | class Solution: 30 | def subtractProductAndSum(self, n: int) -> int: 31 | s = str(n) 32 | arr = list(s) 33 | sum = 0 34 | product = 1 35 | for i in range(len(arr)): 36 | sum += int(arr[i]) 37 | product *= int(arr[i]) 38 | return( product - sum ) -------------------------------------------------------------------------------- /LeetCode/python/1108.defrangingip.py: -------------------------------------------------------------------------------- 1 | # Given a valid (IPv4) IP address, return a defanged version of that IP address. 2 | 3 | # A defanged IP address replaces every period "." with "[.]". 4 | 5 | 6 | 7 | # Example 1: 8 | 9 | # Input: address = "1.1.1.1" 10 | # Output: "1[.]1[.]1[.]1" 11 | 12 | # Example 2: 13 | 14 | # Input: address = "255.100.50.0" 15 | # Output: "255[.]100[.]50[.]0" 16 | 17 | 18 | 19 | # Constraints: 20 | 21 | # The given address is a valid IPv4 address. 22 | 23 | 24 | class Solution: 25 | def defangIPaddr(self, address: str) -> str: 26 | i = 0 27 | while(i < len(address)): 28 | if address[i] == '.': 29 | address = address[:i]+'[.]'+address[i+1:] 30 | i+=2 31 | else: 32 | i+=1 33 | return address 34 | 35 | class Solution: 36 | def defangIPaddr(self, address: str) -> str: 37 | return address.replace('.','[.]') -------------------------------------------------------------------------------- /LeetCode/python/164.maxgap.py: -------------------------------------------------------------------------------- 1 | # Given an unsorted array, find the maximum difference between the successive elements in its sorted form. 2 | 3 | # Return 0 if the array contains less than 2 elements. 4 | 5 | # Example 1: 6 | 7 | # Input: [3,6,9,1] 8 | # Output: 3 9 | # Explanation: The sorted form of the array is [1,3,6,9], either 10 | # (3,6) or (6,9) has the maximum difference 3. 11 | 12 | # Example 2: 13 | 14 | # Input: [10] 15 | # Output: 0 16 | # Explanation: The array contains less than 2 elements, therefore return 0. 17 | 18 | class Solution: 19 | def maximumGap(self, nums: List[int]) -> int: 20 | if len(nums) < 2: 21 | return 0 22 | nums.sort() 23 | maxdiff=0 24 | i=0 25 | while(i< len(nums) - 1): 26 | diff = nums[i+1] - nums[i] 27 | if diff > maxdiff: 28 | maxdiff = diff 29 | i+=1 30 | return maxdiff 31 | -------------------------------------------------------------------------------- /LeetCode/cpp/905.sortbyparity.cpp: -------------------------------------------------------------------------------- 1 | // Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A. 2 | 3 | // You may return any answer array that satisfies this condition. 4 | 5 | 6 | 7 | // Example 1: 8 | 9 | // Input: [3,1,2,4] 10 | // Output: [2,4,3,1] 11 | // The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. 12 | 13 | 14 | 15 | // Note: 16 | 17 | // 1 <= A.length <= 5000 18 | // 0 <= A[i] <= 5000 19 | 20 | class Solution { 21 | public: 22 | vector sortArrayByParity(vector& A) { 23 | vector odd,even; 24 | for(auto i:A){ 25 | if(i%2 == 1){ 26 | odd.push_back(i); 27 | } 28 | else{ 29 | even.push_back(i); 30 | } 31 | } 32 | even.insert(even.end(),odd.begin(),odd.end()); 33 | return(even); 34 | } 35 | }; -------------------------------------------------------------------------------- /LeetCode/python/1470.shufflearray.py: -------------------------------------------------------------------------------- 1 | # Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn]. 2 | 3 | # Return the array in the form [x1,y1,x2,y2,...,xn,yn]. 4 | 5 | 6 | 7 | # Example 1: 8 | 9 | # Input: nums = [2,5,1,3,4,7], n = 3 10 | # Output: [2,3,5,4,1,7] 11 | # Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7]. 12 | 13 | # Example 2: 14 | 15 | # Input: nums = [1,2,3,4,4,3,2,1], n = 4 16 | # Output: [1,4,2,3,3,2,4,1] 17 | 18 | # Example 3: 19 | 20 | # Input: nums = [1,1,2,2], n = 2 21 | # Output: [1,2,1,2] 22 | 23 | 24 | 25 | # Constraints: 26 | 27 | # 1 <= n <= 500 28 | # nums.length == 2n 29 | # 1 <= nums[i] <= 10^3 30 | 31 | 32 | class Solution: 33 | def shuffle(self, nums: List[int], n: int) -> List[int]: 34 | arr = [] 35 | for i in range(n): 36 | arr.append(nums[i]) 37 | arr.append(nums[i+n]) 38 | return arr -------------------------------------------------------------------------------- /LeetCode/cpp/700.searchtree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* searchBST(TreeNode* root, int val) { 15 | while(root){ 16 | if (root == NULL){ 17 | break; 18 | } 19 | else if(root->val > val){ 20 | root = root->left; 21 | } 22 | else if(root->val < val){ 23 | root = root->right; 24 | } 25 | else if (root->val == val){ 26 | return root; 27 | } 28 | } 29 | return NULL; 30 | } 31 | }; -------------------------------------------------------------------------------- /HackerEarth/practice/tier1/sorting/chanduNgirlfriendret.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int tcase,i,j; 8 | scanf("%d",&tcase); 9 | for(i=0;i()); 29 | 30 | for(j=0;j= A[j]. 4 | 5 | # Return true if and only if the given array A is monotonic. 6 | 7 | 8 | 9 | # Example 1: 10 | 11 | # Input: [1,2,2,3] 12 | # Output: true 13 | 14 | # Example 2: 15 | 16 | # Input: [6,5,4,4] 17 | # Output: true 18 | 19 | # Example 3: 20 | 21 | # Input: [1,3,2] 22 | # Output: false 23 | 24 | # Example 4: 25 | 26 | # Input: [1,2,4,5] 27 | # Output: true 28 | 29 | # Example 5: 30 | 31 | # Input: [1,1,1] 32 | # Output: true 33 | 34 | class Solution: 35 | def isMonotonic(self, A: List[int]) -> bool: 36 | if not A: 37 | return True 38 | if A == sorted(A) or A == sorted(A , reverse = True) : 39 | return True 40 | else: 41 | return False 42 | -------------------------------------------------------------------------------- /LeetCode/python/1464.maxproductinarr.py: -------------------------------------------------------------------------------- 1 | # Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1). 2 | 3 | 4 | 5 | # Example 1: 6 | 7 | # Input: nums = [3,4,5,2] 8 | # Output: 12 9 | # Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. 10 | 11 | # Example 2: 12 | 13 | # Input: nums = [1,5,4,5] 14 | # Output: 16 15 | # Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16. 16 | 17 | # Example 3: 18 | 19 | # Input: nums = [3,7] 20 | # Output: 12 21 | 22 | 23 | 24 | # Constraints: 25 | 26 | # 2 <= nums.length <= 500 27 | # 1 <= nums[i] <= 10^3 28 | 29 | 30 | class Solution: 31 | def maxProduct(self, nums: List[int]) -> int: 32 | nums.sort(reverse = True) 33 | return((nums[0] -1) *(nums[1] - 1) ) -------------------------------------------------------------------------------- /LeetCode/python/771.jewelsandstones.py: -------------------------------------------------------------------------------- 1 | # You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels. 2 | 3 | # The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A". 4 | 5 | # Example 1: 6 | 7 | # Input: J = "aA", S = "aAAbbbb" 8 | # Output: 3 9 | 10 | # Example 2: 11 | 12 | # Input: J = "z", S = "ZZ" 13 | # Output: 0 14 | 15 | # Note: 16 | 17 | # S and J will consist of letters and have length at most 50. 18 | # The characters in J are distinct. 19 | 20 | class Solution:1 21 | def numJewelsInStones(self, J: str, S: str) -> int: 22 | count = 0 23 | for i in range(len(S)): 24 | if S[i] in J: 25 | count += 1 26 | 27 | return count -------------------------------------------------------------------------------- /LeetCode/cpp/1281.sumandproduct.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer number n, return the difference between the product of its digits and the sum of its digits. 2 | 3 | 4 | 5 | // Example 1: 6 | 7 | // Input: n = 234 8 | // Output: 15 9 | // Explanation: 10 | // Product of digits = 2 * 3 * 4 = 24 11 | // Sum of digits = 2 + 3 + 4 = 9 12 | // Result = 24 - 9 = 15 13 | 14 | // Example 2: 15 | 16 | // Input: n = 4421 17 | // Output: 21 18 | // Explanation: 19 | // Product of digits = 4 * 4 * 2 * 1 = 32 20 | // Sum of digits = 4 + 4 + 2 + 1 = 11 21 | // Result = 32 - 11 = 21 22 | 23 | 24 | 25 | // Constraints: 26 | 27 | // 1 <= n <= 10^5 28 | 29 | 30 | class Solution { 31 | public: 32 | 33 | int subtractProductAndSum(int n) { 34 | string s = to_string(n); 35 | int sum = 0; 36 | int product = 1; 37 | int temp; 38 | for (auto i: s){ 39 | sum+= (i - 48); 40 | product*= (i - 48); 41 | } 42 | return(product - sum); 43 | } 44 | }; -------------------------------------------------------------------------------- /LeetCode/cpp/617.merge2trees.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* dfs(TreeNode* t1,TreeNode* t2){ 15 | 16 | if(t1 && t2){ 17 | t1->val = t1->val+t2->val; 18 | t1->left = dfs(t1->left,t2->left); 19 | t1->right = dfs(t1->right,t2->right); 20 | return t1; 21 | } 22 | else{ 23 | if(t1){ 24 | return t1; 25 | } 26 | return t2; 27 | } 28 | 29 | } 30 | TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { 31 | t1 = dfs(t1,t2); 32 | return t1; 33 | } 34 | }; -------------------------------------------------------------------------------- /LeetCode/python/1480.runningsum.py: -------------------------------------------------------------------------------- 1 | # Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). 2 | 3 | # Return the running sum of nums. 4 | 5 | 6 | 7 | # Example 1: 8 | 9 | # Input: nums = [1,2,3,4] 10 | # Output: [1,3,6,10] 11 | # Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4]. 12 | 13 | # Example 2: 14 | 15 | # Input: nums = [1,1,1,1,1] 16 | # Output: [1,2,3,4,5] 17 | # Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1]. 18 | 19 | # Example 3: 20 | 21 | # Input: nums = [3,1,2,10,1] 22 | # Output: [3,4,6,16,17] 23 | 24 | 25 | 26 | # Constraints: 27 | 28 | # 1 <= nums.length <= 1000 29 | # -10^6 <= nums[i] <= 10^6 30 | 31 | 32 | class Solution: 33 | def runningSum(self, nums: List[int]) -> List[int]: 34 | if not nums: 35 | return 36 | arr = [] 37 | sum = 0 38 | for i in range(len(nums)): 39 | sum+=nums[i] 40 | arr.append(sum) 41 | return arr -------------------------------------------------------------------------------- /projecteuler/Nth_Fibonacci.c: -------------------------------------------------------------------------------- 1 | /* This program is used to find the 2 | first N digit Fibonacci Number */ 3 | 4 | 5 | #include 6 | 7 | int digits(int num) 8 | { 9 | int digit=0; 10 | while(num!=0) 11 | {digit+=1; 12 | num/=10; 13 | } 14 | return digit; 15 | 16 | } 17 | 18 | 19 | int main() 20 | { 21 | int X0,Y1,count,T,N,i; 22 | printf("enter the test cases\n"); 23 | scanf("%d", &T); 24 | for(i=1;i<=T;i++) 25 | {printf("\nEnter the Number\n"); 26 | scanf("%d", &N); 27 | X0=1; 28 | Y1=1; 29 | count=2; 30 | while(N!=1) 31 | {if(count%2==0) 32 | {X0=X0+Y1; 33 | if(digits(X0)==N) 34 | {printf("The first fibonaci with %d digit is %d \n",N,X0); 35 | break;} 36 | } 37 | 38 | else 39 | {Y1=X0+Y1; 40 | if(digits(Y1)==N) 41 | {printf("The first fibonaci with %d digit is %d \n",N,Y1); 42 | break;} 43 | } 44 | 45 | count+=1; 46 | 47 | 48 | } 49 | if(N==1) 50 | 51 | printf("The first fibonacci with %d digit is 1\n",N); 52 | 53 | } 54 | 55 | 56 | 57 | } 58 | 59 | -------------------------------------------------------------------------------- /LeetCode/cpp/771.jewelsandstones.cpp: -------------------------------------------------------------------------------- 1 | // You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels. 2 | 3 | // The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A". 4 | 5 | // Example 1: 6 | 7 | // Input: J = "aA", S = "aAAbbbb" 8 | // Output: 3 9 | 10 | // Example 2: 11 | 12 | // Input: J = "z", S = "ZZ" 13 | // Output: 0 14 | 15 | // Note: 16 | 17 | // S and J will consist of letters and have length at most 50. 18 | // The characters in J are distinct. 19 | 20 | 21 | class Solution { 22 | public: 23 | int numJewelsInStones(string J, string S) { 24 | int res = 0; 25 | for(auto i : S){ 26 | if (J.find(i) != string::npos){ 27 | res++; 28 | } 29 | } 30 | return res; 31 | } 32 | }; -------------------------------------------------------------------------------- /LeetCode/python/3.long_substr.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLongestSubstring(self, s: str) -> int: 3 | if len(s)==0: 4 | return(0) 5 | maxlen = 1 6 | size = len(s) 7 | dup = [] 8 | temp = 1 9 | dup.append(s[0]) 10 | i=1 11 | ind=0 12 | while(i maxlen : 19 | maxlen = temp 20 | if(len(dup)>maxlen): 21 | maxlen=len(dup) 22 | duplen=len(dup) 23 | if i shuffle(vector& nums, int n) { 34 | vector first; 35 | for (int i = 0;i < nums.size()/2;i++){ 36 | first.push_back(nums[i]); 37 | first.push_back(nums[i+n]); 38 | } 39 | return first; 40 | } 41 | }; -------------------------------------------------------------------------------- /LeetCode/python/101.symtree.py: -------------------------------------------------------------------------------- 1 | # Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 2 | 3 | # For example, this binary tree [1,2,2,3,4,4,3] is symmetric: 4 | 5 | # 1 6 | # / \ 7 | # 2 2 8 | # / \ / \ 9 | # 3 4 4 3 10 | 11 | 12 | 13 | # But the following [1,2,2,null,3,null,3] is not: 14 | 15 | # 1 16 | # / \ 17 | # 2 2 18 | # \ \ 19 | # 3 3 20 | 21 | # Definition for a binary tree node. 22 | # class TreeNode: 23 | # def __init__(self, val=0, left=None, right=None): 24 | # self.val = val 25 | # self.left = left 26 | # self.right = right 27 | class Solution: 28 | def isSymmetric(self, root: TreeNode) -> bool: 29 | if not root: 30 | return True 31 | def dfs(l,r): 32 | if not l and not r: 33 | return True 34 | if l and r and l.val == r.val: 35 | return dfs(l.left,r.right) and dfs(l.right,r.left) 36 | return False 37 | return dfs(root.left,root.right) -------------------------------------------------------------------------------- /HackerRank/CPP/2Darraydesign.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | // Complete the hourglassSum function below. 6 | int hourglassSum(vector> a) { 7 | vector Sum; 8 | int s; 9 | for(int i=0;i<4;i++){ 10 | for(int j=0;j<4;j++) 11 | { 12 | s=a[i][j]+a[i][j+1]+a[i][j+2]+a[i+1][j+1]+a[i+2][j]+a[i+2][j+1]+a[i+2][j+2]; 13 | Sum.push_back(s); 14 | } 15 | } 16 | sort(Sum.begin(),Sum.end()); 17 | int ans = Sum[Sum.size() - 1]; 18 | return ans; 19 | 20 | } 21 | 22 | int main() 23 | { 24 | ofstream fout(getenv("OUTPUT_PATH")); 25 | 26 | vector> arr(6); 27 | for (int i = 0; i < 6; i++) { 28 | arr[i].resize(6); 29 | 30 | for (int j = 0; j < 6; j++) { 31 | cin >> arr[i][j]; 32 | } 33 | 34 | cin.ignore(numeric_limits::max(), '\n'); 35 | } 36 | 37 | int result = hourglassSum(arr); 38 | 39 | fout << result << "\n"; 40 | 41 | fout.close(); 42 | 43 | return 0; 44 | } 45 | 46 | -------------------------------------------------------------------------------- /LeetCode/python/5.longestsubpalindrome.py: -------------------------------------------------------------------------------- 1 | # Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. 2 | 3 | # Example 1: 4 | 5 | # Input: "babad" 6 | # Output: "bab" 7 | # Note: "aba" is also a valid answer. 8 | 9 | # Example 2: 10 | 11 | # Input: "cbbd" 12 | # Output: "bb" 13 | 14 | 15 | class Solution: 16 | 17 | def longestPalindrome(self, s: str) -> str: 18 | newstr = "" 19 | if ( len (s) == 1): 20 | return s 21 | i=0 22 | while ( i < len(s) - 1 ): 23 | sub1 = helper(s,i,i) 24 | if ( len(sub1) > len (newstr)): 25 | newstr = sub1 26 | sub2 = helper(s,i,i+1) 27 | if ( len(sub2) > len (newstr)): 28 | newstr = sub2 29 | i+=1 30 | return newstr 31 | 32 | 33 | 34 | def helper (s , left , right): 35 | while ( left >=0 and right < len(s) and s[left] == s[right]): 36 | left-=1 37 | right+=1 38 | return s[left + 1:right] -------------------------------------------------------------------------------- /LeetCode/cpp/1374.strwithoddcount.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times. 2 | 3 | // The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them. 4 | 5 | 6 | 7 | // Example 1: 8 | 9 | // Input: n = 4 10 | // Output: "pppz" 11 | // Explanation: "pppz" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as "ohhh" and "love". 12 | 13 | // Example 2: 14 | 15 | // Input: n = 2 16 | // Output: "xy" 17 | // Explanation: "xy" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as "ag" and "ur". 18 | 19 | // Example 3: 20 | 21 | // Input: n = 7 22 | // Output: "holasss" 23 | 24 | 25 | 26 | // Constraints: 27 | 28 | // 1 <= n <= 500 29 | 30 | class Solution { 31 | public: 32 | string generateTheString(int n) { 33 | return "b" + string(n-1, 'a' + n%2); 34 | } 35 | }; -------------------------------------------------------------------------------- /LeetCode/cpp/1512.goodpairs.cpp: -------------------------------------------------------------------------------- 1 | // Given an array of integers nums. 2 | 3 | // A pair (i,j) is called good if nums[i] == nums[j] and i < j. 4 | 5 | // Return the number of good pairs. 6 | 7 | 8 | 9 | // Example 1: 10 | 11 | // Input: nums = [1,2,3,1,1,3] 12 | // Output: 4 13 | // Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. 14 | 15 | // Example 2: 16 | 17 | // Input: nums = [1,1,1,1] 18 | // Output: 6 19 | // Explanation: Each pair in the array are good. 20 | 21 | // Example 3: 22 | 23 | // Input: nums = [1,2,3] 24 | // Output: 0 25 | 26 | 27 | 28 | // Constraints: 29 | 30 | // 1 <= nums.length <= 100 31 | // 1 <= nums[i] <= 100 32 | 33 | class Solution { 34 | public: 35 | int numIdenticalPairs(vector& nums) { 36 | int res = 0; 37 | // vector arr; 38 | for(int i = 0;i< nums.size();i++){ 39 | for(int j = i+1; j int: 33 | count = 0 34 | for i in range(len(nums)): 35 | if (len(str(nums[i])) % 2 == 0): 36 | count += 1 37 | 38 | return count -------------------------------------------------------------------------------- /LeetCode/python/516.longestpalindrome.py: -------------------------------------------------------------------------------- 1 | # Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000. 2 | 3 | # Example 1: 4 | # Input: 5 | 6 | # "bbbab" 7 | 8 | # Output: 9 | 10 | # 4 11 | 12 | # One possible longest palindromic subsequence is "bbbb". 13 | 14 | 15 | 16 | # Example 2: 17 | # Input: 18 | 19 | # "cbbd" 20 | 21 | # Output: 22 | 23 | # 2 24 | 25 | # One possible longest palindromic subsequence is "bb". 26 | 27 | 28 | 29 | # Constraints: 30 | 31 | # 1 <= s.length <= 1000 32 | # s consists only of lowercase English letters. 33 | 34 | 35 | class Solution: 36 | def longestPalindromeSubseq(self, s: str) -> int: 37 | @lru_cache(None) 38 | def recursion(i,j): 39 | if i == j: 40 | return 1 41 | elif i > j: 42 | return 0 43 | if s[i] == s[j]: 44 | return 2 + recursion(i+1,j-1) 45 | else: 46 | return max(recursion(i+1,j),recursion(i,j-1)) 47 | return recursion(0,len(s)-1) -------------------------------------------------------------------------------- /LeetCode/python/17.lettercombos.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/letter-combinations-of-a-phone-number/ 2 | 3 | # Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. 4 | 5 | # A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. 6 | 7 | # Example: 8 | 9 | # Input: "23" 10 | # Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 11 | 12 | class Solution: 13 | def letterCombinations(self, digits: str) -> List[str]: 14 | d = {'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'} 15 | if not digits: 16 | return [] 17 | ret = [] 18 | def helper(ret,cur,index): 19 | if (index == len(digits)): 20 | ret.append(''.join(cur[:])) 21 | return 22 | for c in d[digits[index]]: 23 | cur.append(c) 24 | helper(ret,cur,index+1) 25 | cur.pop() 26 | helper(ret,[],0) 27 | return ret -------------------------------------------------------------------------------- /LeetCode/python/665.nondecreasingarr.py: -------------------------------------------------------------------------------- 1 | # Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element. 2 | 3 | # We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2). 4 | 5 | 6 | 7 | # Example 1: 8 | 9 | # Input: nums = [4,2,3] 10 | # Output: true 11 | # Explanation: You could modify the first 4 to 1 to get a non-decreasing array. 12 | 13 | # Example 2: 14 | 15 | # Input: nums = [4,2,1] 16 | # Output: false 17 | # Explanation: You can't get a non-decreasing array by modify at most one element. 18 | 19 | 20 | 21 | # Constraints: 22 | 23 | # 1 <= n <= 10 ^ 4 24 | # - 10 ^ 5 <= nums[i] <= 10 ^ 5 25 | 26 | class Solution: 27 | def checkPossibility(self, nums: List[int]) -> bool: 28 | one, two = nums[:],nums[:] 29 | for i in range(len(nums) - 1): 30 | if nums[i] > nums[i+1]: 31 | one[i] = nums[i+1] 32 | two[i+1] = nums[i] 33 | break 34 | return one == sorted(one) or two == sorted(two) -------------------------------------------------------------------------------- /LeetCode/python/468.xorops.py: -------------------------------------------------------------------------------- 1 | # Given an integer n and an integer start. 2 | 3 | # Define an array nums where nums[i] = start + 2*i (0-indexed) and n == nums.length. 4 | 5 | # Return the bitwise XOR of all elements of nums. 6 | 7 | 8 | 9 | # Example 1: 10 | 11 | # Input: n = 5, start = 0 12 | # Output: 8 13 | # Explanation: Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8. 14 | # Where "^" corresponds to bitwise XOR operator. 15 | 16 | # Example 2: 17 | 18 | # Input: n = 4, start = 3 19 | # Output: 8 20 | # Explanation: Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8. 21 | 22 | # Example 3: 23 | 24 | # Input: n = 1, start = 7 25 | # Output: 7 26 | 27 | # Example 4: 28 | 29 | # Input: n = 10, start = 5 30 | # Output: 2 31 | 32 | 33 | 34 | # Constraints: 35 | 36 | # 1 <= n <= 1000 37 | # 0 <= start <= 1000 38 | # n == nums.length 39 | 40 | 41 | class Solution: 42 | def xorOperation(self, n: int, start: int) -> int: 43 | res = start 44 | for i in range(1,n): 45 | temp = start + 2*i 46 | res^=temp 47 | return res -------------------------------------------------------------------------------- /LeetCode/python/538.treedfs.py: -------------------------------------------------------------------------------- 1 | # Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST. 2 | 3 | # Example: 4 | 5 | # Input: The root of a Binary Search Tree like this: 6 | # 5 7 | # / \ 8 | # 2 13 9 | 10 | # Output: The root of a Greater Tree like this: 11 | # 18 12 | # / \ 13 | # 20 13 14 | 15 | 16 | # Definition for a binary tree node. 17 | # class TreeNode: 18 | # def __init__(self, val=0, left=None, right=None): 19 | # self.val = val 20 | # self.left = left 21 | # self.right = right 22 | class Solution: 23 | def convertBST(self, root: TreeNode) -> TreeNode: 24 | self.temp = 0 25 | def dfs(node): 26 | if not node: 27 | return 28 | dfs(node.right) 29 | self.temp+= node.val 30 | node.val = self.temp 31 | dfs(node.left) 32 | 33 | dfs(root) 34 | return root -------------------------------------------------------------------------------- /LeetCode/python/7.rev.py: -------------------------------------------------------------------------------- 1 | # Given a 32-bit signed integer, reverse digits of an integer. 2 | 3 | # Example 1: 4 | 5 | # Input: 123 6 | # Output: 321 7 | 8 | # Example 2: 9 | 10 | # Input: -123 11 | # Output: -321 12 | 13 | # Example 3: 14 | 15 | # Input: 120 16 | # Output: 21 17 | 18 | # Note: 19 | # Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. 20 | 21 | 22 | 23 | class Solution: 24 | def reverse(self, x: int) -> int: 25 | arr = [num for num in str(x)] 26 | size = len(arr)-1 27 | flag=0 28 | while(arr[size] == 0): 29 | size-=1 30 | if(arr[0]=='-'): 31 | newarr= arr[1:size+1] 32 | flag = 1 33 | else: 34 | newarr= arr[:size+1] 35 | newarr = newarr[::-1] 36 | num=int("".join(map(str,newarr))) 37 | if flag == 1: 38 | num*=-1 39 | if(abs(num) > 2**31 -1): 40 | return 0 41 | return num -------------------------------------------------------------------------------- /LeetCode/python/57.insertinterval.py: -------------------------------------------------------------------------------- 1 | # Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). 2 | 3 | # You may assume that the intervals were initially sorted according to their start times. 4 | 5 | # Example 1: 6 | 7 | # Input: intervals = [[1,3],[6,9]], newInterval = [2,5] 8 | # Output: [[1,5],[6,9]] 9 | 10 | # Example 2: 11 | 12 | # Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] 13 | # Output: [[1,2],[3,10],[12,16]] 14 | # Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]. 15 | 16 | 17 | class Solution: 18 | def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: 19 | intervals.append(newInterval) 20 | intervals = sorted(intervals, key = lambda x:x[0]) 21 | print(intervals) 22 | i=0 23 | while(i < len(intervals) - 1): 24 | if(intervals[i][1] >= intervals[i+1][0]): 25 | intervals[i][1]= max(intervals[i][1],intervals[i+1][1]) 26 | del intervals[i+1] 27 | else: 28 | i+=1 29 | return intervals -------------------------------------------------------------------------------- /LeetCode/python/1502.checkap.py: -------------------------------------------------------------------------------- 1 | # Given an array of numbers arr. A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same. 2 | 3 | # Return true if the array can be rearranged to form an arithmetic progression, otherwise, return false. 4 | 5 | 6 | 7 | # Example 1: 8 | 9 | # Input: arr = [3,5,1] 10 | # Output: true 11 | # Explanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements. 12 | 13 | # Example 2: 14 | 15 | # Input: arr = [1,2,4] 16 | # Output: false 17 | # Explanation: There is no way to reorder the elements to obtain an arithmetic progression. 18 | 19 | 20 | 21 | # Constraints: 22 | 23 | # 2 <= arr.length <= 1000 24 | # -10^6 <= arr[i] <= 10^6 25 | 26 | class Solution: 27 | def canMakeArithmeticProgression(self, arr: List[int]) -> bool: 28 | arr.sort() 29 | if len(arr) < 3: 30 | return True 31 | diff = arr[1] - arr[0] 32 | for i in range(len(arr) - 1 ): 33 | if arr[i+1] - arr[i] != diff: 34 | return False 35 | return True -------------------------------------------------------------------------------- /LeetCode/python/104.depthoftree.py: -------------------------------------------------------------------------------- 1 | # Given a binary tree, find its maximum depth. 2 | 3 | # The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 4 | 5 | # Note: A leaf is a node with no children. 6 | 7 | # Example: 8 | 9 | # Given binary tree [3,9,20,null,null,15,7], 10 | 11 | # 3 12 | # / \ 13 | # 9 20 14 | # / \ 15 | # 15 7 16 | 17 | # return its depth = 3. 18 | 19 | 20 | # Definition for a binary tree node. 21 | # class TreeNode: 22 | # def __init__(self, val=0, left=None, right=None): 23 | # self.val = val 24 | # self.left = left 25 | # self.right = right 26 | class Solution: 27 | def maxDepth(self, root: TreeNode) -> int: 28 | if not root: 29 | return 0 30 | self.maxcount = 0 31 | def dfs(root,count): 32 | if not root: 33 | return 34 | print(root.val,count) 35 | if count > self.maxcount: 36 | self.maxcount = count 37 | dfs(root.left,count+1) 38 | dfs(root.right,count+1) 39 | dfs(root,1) 40 | return self.maxcount -------------------------------------------------------------------------------- /LeetCode/python/1512.noofgoodpairs.py: -------------------------------------------------------------------------------- 1 | # Given an array of integers nums. 2 | 3 | # A pair (i,j) is called good if nums[i] == nums[j] and i < j. 4 | 5 | # Return the number of good pairs. 6 | 7 | 8 | 9 | # Example 1: 10 | 11 | # Input: nums = [1,2,3,1,1,3] 12 | # Output: 4 13 | # Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. 14 | 15 | # Example 2: 16 | 17 | # Input: nums = [1,1,1,1] 18 | # Output: 6 19 | # Explanation: Each pair in the array are good. 20 | 21 | # Example 3: 22 | 23 | # Input: nums = [1,2,3] 24 | # Output: 0 25 | 26 | 27 | 28 | # Constraints: 29 | 30 | # 1 <= nums.length <= 100 31 | # 1 <= nums[i] <= 100 32 | 33 | 34 | class Solution: 35 | def numIdenticalPairs(self, nums: List[int]) -> int: 36 | if not nums: 37 | return 0 38 | arr = [] 39 | for i in range(len(nums)): 40 | for j in range(i+1,len(nums)): 41 | if nums[i] == nums[j]: 42 | temp = [] 43 | temp.append(i) 44 | temp.append(j) 45 | arr.append(temp) 46 | print(arr) 47 | return len(arr) 48 | 49 | -------------------------------------------------------------------------------- /LeetCode/python/1374.strwithoddcounts.py: -------------------------------------------------------------------------------- 1 | # Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times. 2 | 3 | # The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them. 4 | 5 | 6 | 7 | # Example 1: 8 | 9 | # Input: n = 4 10 | # Output: "pppz" 11 | # Explanation: "pppz" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as "ohhh" and "love". 12 | 13 | # Example 2: 14 | 15 | # Input: n = 2 16 | # Output: "xy" 17 | # Explanation: "xy" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as "ag" and "ur". 18 | 19 | # Example 3: 20 | 21 | # Input: n = 7 22 | # Output: "holasss" 23 | 24 | 25 | 26 | # Constraints: 27 | 28 | # 1 <= n <= 500 29 | 30 | class Solution: 31 | def generateTheString(self, n: int) -> str: 32 | res = '' 33 | if n%2 == 1: 34 | res = 'a' * n 35 | else: 36 | res = 'a' * (n-1) 37 | res += 'b' 38 | return res -------------------------------------------------------------------------------- /LeetCode/python/16.3sumclosest.py: -------------------------------------------------------------------------------- 1 | # Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. 2 | 3 | 4 | 5 | # Example 1: 6 | 7 | # Input: nums = [-1,2,1,-4], target = 1 8 | # Output: 2 9 | # Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). 10 | 11 | class Solution: 12 | def threeSumClosest(self, nums: List[int], target: int) -> int: 13 | nums.sort() 14 | res = nums[0] + nums[1] +nums[2] 15 | for i in range(len(nums) - 2): 16 | left = i + 1 17 | right = len(nums) - 1 18 | while (left < right): 19 | tempsum = nums[i] + nums[left] +nums[right] 20 | if tempsum == target: 21 | return target 22 | if abs(tempsum - target) < abs(res - target): 23 | res = tempsum 24 | if tempsum < target: 25 | left+=1 26 | if tempsum > target: 27 | right-=1 28 | 29 | return res -------------------------------------------------------------------------------- /LeetCode/cpp/1351.noofnegatives.cpp: -------------------------------------------------------------------------------- 1 | // Given a m * n matrix grid which is sorted in non-increasing order both row-wise and column-wise. 2 | 3 | // Return the number of negative numbers in grid. 4 | 5 | 6 | 7 | // Example 1: 8 | 9 | // Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]] 10 | // Output: 8 11 | // Explanation: There are 8 negatives number in the matrix. 12 | 13 | // Example 2: 14 | 15 | // Input: grid = [[3,2],[1,0]] 16 | // Output: 0 17 | 18 | // Example 3: 19 | 20 | // Input: grid = [[1,-1],[-1,-1]] 21 | // Output: 3 22 | 23 | // Example 4: 24 | 25 | // Input: grid = [[-1]] 26 | // Output: 1 27 | 28 | 29 | 30 | // Constraints: 31 | 32 | // m == grid.length 33 | // n == grid[i].length 34 | // 1 <= m, n <= 100 35 | // -100 <= grid[i][j] <= 100 36 | 37 | class Solution { 38 | public: 39 | int countNegatives(vector>& grid) { 40 | int res = 0; 41 | for (int i = 0; i< grid.size();i++){ 42 | for(int j = 0; j A[i+1] 7 | 8 | 9 | 10 | # Example 1: 11 | 12 | # Input: "IDID" 13 | # Output: [0,4,1,3,2] 14 | 15 | # Example 2: 16 | 17 | # Input: "III" 18 | # Output: [0,1,2,3] 19 | 20 | # Example 3: 21 | 22 | # Input: "DDI" 23 | # Output: [3,2,0,1] 24 | 25 | 26 | 27 | # Note: 28 | 29 | # 1 <= S.length <= 10000 30 | # S only contains characters "I" or "D" 31 | 32 | class Solution: 33 | def diStringMatch(self, S: str) -> List[int]: 34 | arr = [] 35 | low = 0 36 | high = len(S) 37 | i = 0 38 | while ( i < len(S)): 39 | if S[i] == 'I': 40 | arr.append(low) 41 | low += 1 42 | if S[i] == 'D': 43 | arr.append(high) 44 | high -= 1 45 | i += 1 46 | if S[-1] == 'D': 47 | arr.append(high) 48 | else: 49 | arr.append(low) 50 | return arr -------------------------------------------------------------------------------- /LeetCode/cpp/1486.findxor.cpp: -------------------------------------------------------------------------------- 1 | // Given an integer n and an integer start. 2 | 3 | // Define an array nums where nums[i] = start + 2*i (0-indexed) and n == nums.length. 4 | 5 | // Return the bitwise XOR of all elements of nums. 6 | 7 | 8 | 9 | // Example 1: 10 | 11 | // Input: n = 5, start = 0 12 | // Output: 8 13 | // Explanation: Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8. 14 | // Where "^" corresponds to bitwise XOR operator. 15 | 16 | // Example 2: 17 | 18 | // Input: n = 4, start = 3 19 | // Output: 8 20 | // Explanation: Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8. 21 | 22 | // Example 3: 23 | 24 | // Input: n = 1, start = 7 25 | // Output: 7 26 | 27 | // Example 4: 28 | 29 | // Input: n = 10, start = 5 30 | // Output: 2 31 | 32 | 33 | 34 | // Constraints: 35 | 36 | // 1 <= n <= 1000 37 | // 0 <= start <= 1000 38 | // n == nums.length 39 | 40 | class Solution { 41 | public: 42 | int xorOperation(int n, int start) { 43 | int res = start; 44 | int temp,i = 1; 45 | while(i < n){ 46 | temp = start + 2*i; 47 | res^=temp; 48 | i++; 49 | } 50 | return res; 51 | } 52 | }; -------------------------------------------------------------------------------- /LeetCode/python/938.btreesum.py: -------------------------------------------------------------------------------- 1 | # Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive). 2 | 3 | # The binary search tree is guaranteed to have unique values. 4 | 5 | 6 | 7 | # Example 1: 8 | 9 | # Input: root = [10,5,15,3,7,null,18], L = 7, R = 15 10 | # Output: 32 11 | # Example 2: 12 | 13 | # Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10 14 | # Output: 23 15 | 16 | 17 | # Note: 18 | 19 | # The number of nodes in the tree is at most 10000. 20 | # The final answer is guaranteed to be less than 2^31. 21 | 22 | # Definition for a binary tree node. 23 | # class TreeNode: 24 | # def __init__(self, val=0, left=None, right=None): 25 | # self.val = val 26 | # self.left = left 27 | # self.right = right 28 | 29 | class Solution: 30 | def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int: 31 | self.sum1 = 0 32 | def dfs(root): 33 | if not root: 34 | return 35 | if root.val >= L and root.val <= R: 36 | self.sum1+=root.val 37 | dfs(root.left) 38 | dfs(root.right) 39 | dfs(root) 40 | return self.sum1 -------------------------------------------------------------------------------- /LeetCode/python/2.add2num.py: -------------------------------------------------------------------------------- 1 | # You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. 2 | 3 | # You may assume the two numbers do not contain any leading zero, except the number 0 itself. 4 | 5 | # Example: 6 | 7 | # Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 8 | # Output: 7 -> 0 -> 8 9 | # Explanation: 342 + 465 = 807. 10 | 11 | # Definition for singly-linked list. 12 | # class ListNode: 13 | # def __init__(self, val=0, next=None): 14 | # self.val = val 15 | # self.next = next 16 | class Solution: 17 | def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: 18 | result = ListNode(0) 19 | result2 = result 20 | carry=0 21 | while(l1 or l2 or carry !=0): 22 | val1 = (l1.val if l1 else 0) 23 | val2 = (l2.val if l2 else 0) 24 | carry,temp = divmod(val1+val2+carry,10) 25 | result2.next = ListNode(temp) 26 | result2 = result2.next 27 | l1 = (l1.next if l1 else None) 28 | l2 = (l2.next if l2 else None) 29 | return result.next -------------------------------------------------------------------------------- /LeetCode/cpp/1295.numswithevenlen.cpp: -------------------------------------------------------------------------------- 1 | // Given an array nums of integers, return how many of them contain an even number of digits. 2 | 3 | 4 | 5 | // Example 1: 6 | 7 | // Input: nums = [12,345,2,6,7896] 8 | // Output: 2 9 | // Explanation: 10 | // 12 contains 2 digits (even number of digits). 11 | // 345 contains 3 digits (odd number of digits). 12 | // 2 contains 1 digit (odd number of digits). 13 | // 6 contains 1 digit (odd number of digits). 14 | // 7896 contains 4 digits (even number of digits). 15 | // Therefore only 12 and 7896 contain an even number of digits. 16 | 17 | // Example 2: 18 | 19 | // Input: nums = [555,901,482,1771] 20 | // Output: 1 21 | // Explanation: 22 | // Only 1771 contains an even number of digits. 23 | 24 | 25 | 26 | // Constraints: 27 | 28 | // 1 <= nums.length <= 500 29 | // 1 <= nums[i] <= 10^5 30 | 31 | class Solution { 32 | public: 33 | int findNumbers(vector& nums) { 34 | int i,res = 0; 35 | string temp; 36 | for ( i = 0; i selfDividingNumbers(int left, int right) { 18 | vector res; 19 | int i,j; 20 | string temp; 21 | int flag = 0; 22 | for (i = left ; i <= right ; i++){ 23 | flag = 0; 24 | temp = to_string(i); 25 | for(auto c:temp){ 26 | if(int(c)-48 == 0 || i % (int(c)-48)){ 27 | flag = 1; 28 | break; 29 | } 30 | } 31 | if (flag == 0){ 32 | res.push_back(i); 33 | } 34 | } 35 | return res; 36 | } 37 | }; -------------------------------------------------------------------------------- /LeetCode/python/461.hammingdistance.py: -------------------------------------------------------------------------------- 1 | # The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 2 | 3 | # Given two integers x and y, calculate the Hamming distance. 4 | 5 | # Note: 6 | # 0 ≤ x, y < 231. 7 | 8 | # Example: 9 | 10 | # Input: x = 1, y = 4 11 | 12 | # Output: 2 13 | 14 | # Explanation: 15 | # 1 (0 0 0 1) 16 | # 4 (0 1 0 0) 17 | # ↑ ↑ 18 | 19 | # The above arrows point to positions where the corresponding bits are different. 20 | 21 | class Solution: 22 | def hammingDistance(self, x: int, y: int) -> int: 23 | # xbin = str(bin(x)).replace("0b","") 24 | # ybin = str(bin(y)).replace("0b","") 25 | # count = 0 26 | # xlen = len(xbin) 27 | # ylen = len(ybin) 28 | # maxlen = max(xlen,ylen) 29 | # if xlen > ylen: 30 | # ybin = '0' * (xlen - ylen) + ybin 31 | # if ylen > xlen: 32 | # xbin = '0' * (ylen - xlen) + xbin 33 | # for i in range(len(xbin)): 34 | # if xbin[i] != ybin[i]: 35 | # count+=1 36 | # return count 37 | 38 | x = x^y 39 | res = str(bin(x)).replace("0b","") 40 | return (res.count('1')) -------------------------------------------------------------------------------- /LeetCode/python/728.selfdividingnumbers.py: -------------------------------------------------------------------------------- 1 | # A self-dividing number is a number that is divisible by every digit it contains. 2 | 3 | # For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. 4 | 5 | # Also, a self-dividing number is not allowed to contain the digit zero. 6 | 7 | # Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible. 8 | 9 | # Example 1: 10 | 11 | # Input: 12 | # left = 1, right = 22 13 | # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22] 14 | 15 | # Note: 16 | # The boundaries of each input argument are 1 <= left <= right <= 10000. 17 | 18 | class Solution: 19 | def selfDividingNumbers(self, left: int, right: int) -> List[int]: 20 | def works(n) -> bool: 21 | s = str(n) 22 | if '0' in s: 23 | return False 24 | for i in range(len(s)): 25 | num = int(s[i]) 26 | if n % num != 0: 27 | return False 28 | return True 29 | res = [] 30 | for j in range(left,right+1): 31 | if works(j) == True: 32 | res.append(j) 33 | return res 34 | -------------------------------------------------------------------------------- /LeetCode/python/589.narytreepreorder.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/n-ary-tree-preorder-traversal/ 2 | 3 | # Given an n-ary tree, return the preorder traversal of its nodes' values. 4 | 5 | # Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples). 6 | 7 | 8 | 9 | # Follow up: 10 | 11 | # Recursive solution is trivial, could you do it iteratively? 12 | 13 | 14 | 15 | # Example 1: 16 | 17 | # Input: root = [1,null,3,2,4,null,5,6] 18 | # Output: [1,3,5,6,2,4] 19 | 20 | # Example 2: 21 | 22 | # Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] 23 | # Output: [1,2,3,6,7,11,14,4,8,12,5,9,13,10] 24 | 25 | 26 | """ 27 | # Definition for a Node. 28 | class Node: 29 | def __init__(self, val=None, children=None): 30 | self.val = val 31 | self.children = children 32 | """ 33 | 34 | class Solution: 35 | def preorder(self, root: 'Node') -> List[int]: 36 | res = [] 37 | def dfs(root): 38 | if not root: 39 | return 40 | res.append(root.val) 41 | for i in root.children: 42 | dfs(i) 43 | dfs(root) 44 | return res -------------------------------------------------------------------------------- /LeetCode/cpp/1323.max69num.cpp: -------------------------------------------------------------------------------- 1 | // Given a positive integer num consisting only of digits 6 and 9. 2 | 3 | // Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6). 4 | 5 | 6 | 7 | // Example 1: 8 | 9 | // Input: num = 9669 10 | // Output: 9969 11 | // Explanation: 12 | // Changing the first digit results in 6669. 13 | // Changing the second digit results in 9969. 14 | // Changing the third digit results in 9699. 15 | // Changing the fourth digit results in 9666. 16 | // The maximum number is 9969. 17 | 18 | // Example 2: 19 | 20 | // Input: num = 9996 21 | // Output: 9999 22 | // Explanation: Changing the last digit 6 to 9 results in the maximum number. 23 | 24 | // Example 3: 25 | 26 | // Input: num = 9999 27 | // Output: 9999 28 | // Explanation: It is better not to apply any change. 29 | 30 | 31 | 32 | // Constraints: 33 | 34 | // 1 <= num <= 10^4 35 | // num's digits are 6 or 9. 36 | 37 | class Solution { 38 | public: 39 | int maximum69Number (int num) { 40 | string s = to_string(num); 41 | for(int i =0;i < s.size(); i++){ 42 | if (s[i] == '6'){ 43 | s[i] = '9'; 44 | break; 45 | } 46 | } 47 | return stoi(s); 48 | } 49 | }; -------------------------------------------------------------------------------- /LeetCode/python/6.zigzag.py: -------------------------------------------------------------------------------- 1 | # The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) 2 | 3 | # P A H N 4 | # A P L S I I G 5 | # Y I R 6 | 7 | # And then read line by line: "PAHNAPLSIIGYIR" 8 | 9 | # Write the code that will take a string and make this conversion given a number of rows: 10 | 11 | # string convert(string s, int numRows); 12 | 13 | # Example 1: 14 | 15 | # Input: s = "PAYPALISHIRING", numRows = 3 16 | # Output: "PAHNAPLSIIGYIR" 17 | 18 | # Example 2: 19 | 20 | # Input: s = "PAYPALISHIRING", numRows = 4 21 | # Output: "PINALSIGYAHRPI" 22 | # Explanation: 23 | 24 | # P I N 25 | # A L S I G 26 | # Y A H R 27 | # P I 28 | 29 | class Solution: 30 | def convert(self, s: str, numRows: int) -> str: 31 | if numRows == 1 or len(s) < numRows : 32 | return s 33 | res = [''] * numRows 34 | i = 0 35 | step = 0 36 | for c in s: 37 | res[i]+= c 38 | if i == 0: 39 | step = 1 40 | if i == numRows - 1: 41 | step = -1 42 | i += step 43 | new = ''.join(res) 44 | return new 45 | 46 | -------------------------------------------------------------------------------- /LeetCode/python/20.validparenthesis.py: -------------------------------------------------------------------------------- 1 | # Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 2 | 3 | # An input string is valid if: 4 | 5 | # Open brackets must be closed by the same type of brackets. 6 | # Open brackets must be closed in the correct order. 7 | 8 | # Note that an empty string is also considered valid. 9 | 10 | # Example 1: 11 | 12 | # Input: "()" 13 | # Output: true 14 | 15 | # Example 2: 16 | 17 | # Input: "()[]{}" 18 | # Output: true 19 | 20 | # Example 3: 21 | 22 | # Input: "(]" 23 | # Output: false 24 | 25 | # Example 4: 26 | 27 | # Input: "([)]" 28 | # Output: false 29 | 30 | # Example 5: 31 | 32 | # Input: "{[]}" 33 | # Output: true 34 | 35 | class Solution: 36 | def isValid(self, s: str) -> bool: 37 | if not s: 38 | return True 39 | stack = [] 40 | dict1 = {']':'[' , '}':'{' , ')':'('} 41 | for c in s: 42 | if c in dict1.values(): 43 | stack.append(c) 44 | elif c in dict1.keys(): 45 | if stack == [] or dict1[c] != stack.pop(): 46 | return False 47 | else: 48 | return False 49 | return stack == [] 50 | 51 | -------------------------------------------------------------------------------- /LeetCode/python/1323.max69num.py: -------------------------------------------------------------------------------- 1 | # Given a positive integer num consisting only of digits 6 and 9. 2 | 3 | # Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6). 4 | 5 | 6 | 7 | # Example 1: 8 | 9 | # Input: num = 9669 10 | # Output: 9969 11 | # Explanation: 12 | # Changing the first digit results in 6669. 13 | # Changing the second digit results in 9969. 14 | # Changing the third digit results in 9699. 15 | # Changing the fourth digit results in 9666. 16 | # The maximum number is 9969. 17 | 18 | # Example 2: 19 | 20 | # Input: num = 9996 21 | # Output: 9999 22 | # Explanation: Changing the last digit 6 to 9 results in the maximum number. 23 | 24 | # Example 3: 25 | 26 | # Input: num = 9999 27 | # Output: 9999 28 | # Explanation: It is better not to apply any change. 29 | 30 | 31 | 32 | # Constraints: 33 | 34 | # 1 <= num <= 10^4 35 | # num's digits are 6 or 9. 36 | 37 | 38 | class Solution: 39 | def maximum69Number (self, num: int) -> int: 40 | s = str(num) 41 | # for i in range(len(s)): 42 | # if s[i] == '6': 43 | # s = s[:i]+'9'+s[i+1:] 44 | # break 45 | if '6' in s: 46 | i = s.index('6') 47 | s = s[:i] + '9' + s[i+1:] 48 | return(int(s)) -------------------------------------------------------------------------------- /LeetCode/python/1313.decompresslist.py: -------------------------------------------------------------------------------- 1 | # We are given a list nums of integers representing a list compressed with run-length encoding. 2 | 3 | # Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0). For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list. 4 | 5 | # Return the decompressed list. 6 | 7 | 8 | 9 | # Example 1: 10 | 11 | # Input: nums = [1,2,3,4] 12 | # Output: [2,4,4,4] 13 | # Explanation: The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2]. 14 | # The second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4]. 15 | # At the end the concatenation [2] + [4,4,4] is [2,4,4,4]. 16 | 17 | # Example 2: 18 | 19 | # Input: nums = [1,1,2,3] 20 | # Output: [1,3,3] 21 | 22 | 23 | 24 | # Constraints: 25 | 26 | # 2 <= nums.length <= 100 27 | # nums.length % 2 == 0 28 | # 1 <= nums[i] <= 100 29 | 30 | class Solution: 31 | def decompressRLElist(self, nums: List[int]) -> List[int]: 32 | arr = [] 33 | i = 0 34 | while( i < len(nums) ): 35 | for j in range(nums[i]): 36 | arr.append(nums[i+1]) 37 | i+=2 38 | return arr 39 | -------------------------------------------------------------------------------- /LeetCode/python/1432.stepstozero.py: -------------------------------------------------------------------------------- 1 | # Given a non-negative integer num, return the number of steps to reduce it to zero. If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it. 2 | 3 | 4 | 5 | # Example 1: 6 | 7 | # Input: num = 14 8 | # Output: 6 9 | # Explanation: 10 | # Step 1) 14 is even; divide by 2 and obtain 7. 11 | # Step 2) 7 is odd; subtract 1 and obtain 6. 12 | # Step 3) 6 is even; divide by 2 and obtain 3. 13 | # Step 4) 3 is odd; subtract 1 and obtain 2. 14 | # Step 5) 2 is even; divide by 2 and obtain 1. 15 | # Step 6) 1 is odd; subtract 1 and obtain 0. 16 | 17 | # Example 2: 18 | 19 | # Input: num = 8 20 | # Output: 4 21 | # Explanation: 22 | # Step 1) 8 is even; divide by 2 and obtain 4. 23 | # Step 2) 4 is even; divide by 2 and obtain 2. 24 | # Step 3) 2 is even; divide by 2 and obtain 1. 25 | # Step 4) 1 is odd; subtract 1 and obtain 0. 26 | 27 | # Example 3: 28 | 29 | # Input: num = 123 30 | # Output: 12 31 | 32 | 33 | 34 | # Constraints: 35 | 36 | # 0 <= num <= 10^6 37 | 38 | class Solution: 39 | def numberOfSteps (self, num: int) -> int: 40 | count = 0 41 | while(num != 0): 42 | if num%2 == 0: 43 | num/=2 44 | else: 45 | num-=1 46 | count+=1 47 | return count -------------------------------------------------------------------------------- /LeetCode/cpp/1313.decompress.cpp: -------------------------------------------------------------------------------- 1 | // We are given a list nums of integers representing a list compressed with run-length encoding. 2 | 3 | // Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0). For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list. 4 | 5 | // Return the decompressed list. 6 | 7 | 8 | 9 | // Example 1: 10 | 11 | // Input: nums = [1,2,3,4] 12 | // Output: [2,4,4,4] 13 | // Explanation: The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2]. 14 | // The second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4]. 15 | // At the end the concatenation [2] + [4,4,4] is [2,4,4,4]. 16 | 17 | // Example 2: 18 | 19 | // Input: nums = [1,1,2,3] 20 | // Output: [1,3,3] 21 | 22 | 23 | 24 | // Constraints: 25 | 26 | // 2 <= nums.length <= 100 27 | // nums.length % 2 == 0 28 | // 1 <= nums[i] <= 100 29 | 30 | 31 | class Solution { 32 | public: 33 | vector decompressRLElist(vector& nums) { 34 | vectorres; 35 | for (int i = 0; i TreeNode: 32 | while(root != None): 33 | if val < root.val: 34 | root = root.left 35 | elif val > root.val: 36 | root = root.right 37 | elif val == root.val: 38 | return root 39 | return None -------------------------------------------------------------------------------- /LeetCode/python/1051.heightchecker.py: -------------------------------------------------------------------------------- 1 | # Students are asked to stand in non-decreasing order of heights for an annual photo. 2 | 3 | # Return the minimum number of students that must move in order for all students to be standing in non-decreasing order of height. 4 | 5 | # Notice that when a group of students is selected they can reorder in any possible way between themselves and the non selected students remain on their seats. 6 | 7 | 8 | 9 | # Example 1: 10 | 11 | # Input: heights = [1,1,4,2,1,3] 12 | # Output: 3 13 | # Explanation: 14 | # Current array : [1,1,4,2,1,3] 15 | # Target array : [1,1,1,2,3,4] 16 | # On index 2 (0-based) we have 4 vs 1 so we have to move this student. 17 | # On index 4 (0-based) we have 1 vs 3 so we have to move this student. 18 | # On index 5 (0-based) we have 3 vs 4 so we have to move this student. 19 | 20 | # Example 2: 21 | 22 | # Input: heights = [5,1,2,3,4] 23 | # Output: 5 24 | 25 | # Example 3: 26 | 27 | # Input: heights = [1,2,3,4,5] 28 | # Output: 0 29 | 30 | 31 | 32 | # Constraints: 33 | 34 | # 1 <= heights.length <= 100 35 | # 1 <= heights[i] <= 100 36 | 37 | 38 | class Solution: 39 | def heightChecker(self, heights: List[int]) -> int: 40 | new_heights = sorted(heights) 41 | count = 0 42 | for i in range(len(heights)): 43 | if heights[i] != new_heights[i]: 44 | count += 1 45 | return count -------------------------------------------------------------------------------- /LeetCode/python/100.sametre.py: -------------------------------------------------------------------------------- 1 | # Given two binary trees, write a function to check if they are the same or not. 2 | 3 | # Two binary trees are considered the same if they are structurally identical and the nodes have the same value. 4 | 5 | # Example 1: 6 | 7 | # Input: 1 1 8 | # / \ / \ 9 | # 2 3 2 3 10 | 11 | # [1,2,3], [1,2,3] 12 | 13 | # Output: true 14 | 15 | # Example 2: 16 | 17 | # Input: 1 1 18 | # / \ 19 | # 2 2 20 | 21 | # [1,2], [1,null,2] 22 | 23 | # Output: false 24 | 25 | # Example 3: 26 | 27 | # Input: 1 1 28 | # / \ / \ 29 | # 2 1 1 2 30 | 31 | # [1,2,1], [1,1,2] 32 | 33 | # Output: false 34 | 35 | # Definition for a binary tree node. 36 | # class TreeNode: 37 | # def __init__(self, val=0, left=None, right=None): 38 | # self.val = val 39 | # self.left = left 40 | # self.right = right 41 | class Solution: 42 | def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: 43 | if not p and not q: 44 | return True 45 | elif not p or not q: 46 | return False 47 | elif(p.val != q.val): 48 | return False 49 | else: 50 | return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right) 51 | 52 | -------------------------------------------------------------------------------- /LeetCode/python/559.maxdpth.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/maximum-depth-of-n-ary-tree/ 2 | 3 | # Given a n-ary tree, find its maximum depth. 4 | 5 | # The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 6 | 7 | # Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples). 8 | 9 | 10 | 11 | # Example 1: 12 | 13 | # Input: root = [1,null,3,2,4,null,5,6] 14 | # Output: 3 15 | 16 | # Example 2: 17 | 18 | # Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] 19 | # Output: 5 20 | 21 | 22 | 23 | # Constraints: 24 | 25 | # The depth of the n-ary tree is less than or equal to 1000. 26 | # The total number of nodes is between [0, 10^4]. 27 | 28 | """ 29 | # Definition for a Node. 30 | class Node: 31 | def __init__(self, val=None, children=None): 32 | self.val = val 33 | self.children = children 34 | """ 35 | 36 | class Solution: 37 | def maxDepth(self, root: 'Node') -> int: 38 | self.res = 0 39 | def dfs(root,count): 40 | if root == None: 41 | return 42 | for i in root.children: 43 | dfs(i,count+1) 44 | if self.res < count: 45 | self.res = count 46 | dfs(root,1) 47 | return self.res -------------------------------------------------------------------------------- /LeetCode/python/1356.sortintbyparity.py: -------------------------------------------------------------------------------- 1 | # Given an integer array arr. You have to sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order. 2 | 3 | # Return the sorted array. 4 | 5 | 6 | 7 | # Example 1: 8 | 9 | # Input: arr = [0,1,2,3,4,5,6,7,8] 10 | # Output: [0,1,2,4,8,3,5,6,7] 11 | # Explantion: [0] is the only integer with 0 bits. 12 | # [1,2,4,8] all have 1 bit. 13 | # [3,5,6] have 2 bits. 14 | # [7] has 3 bits. 15 | # The sorted array by bits is [0,1,2,4,8,3,5,6,7] 16 | 17 | # Example 2: 18 | 19 | # Input: arr = [1024,512,256,128,64,32,16,8,4,2,1] 20 | # Output: [1,2,4,8,16,32,64,128,256,512,1024] 21 | # Explantion: All integers have 1 bit in the binary representation, you should just sort them in ascending order. 22 | 23 | # Example 3: 24 | 25 | # Input: arr = [10000,10000] 26 | # Output: [10000,10000] 27 | 28 | # Example 4: 29 | 30 | # Input: arr = [2,3,5,7,11,13,17,19] 31 | # Output: [2,3,5,17,7,11,13,19] 32 | 33 | # Example 5: 34 | 35 | # Input: arr = [10,100,1000,10000] 36 | # Output: [10,100,10000,1000] 37 | 38 | 39 | 40 | # Constraints: 41 | 42 | # 1 <= arr.length <= 500 43 | # 0 <= arr[i] <= 10^4 44 | 45 | 46 | 47 | class Solution: 48 | def sortByBits(self, arr: List[int]) -> List[int]: 49 | return sorted(arr , key = lambda x : [(bin(x)).count('1'),x]) -------------------------------------------------------------------------------- /LeetCode/python/590.narytreepostorder.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/n-ary-tree-postorder-traversal/ 2 | 3 | # Given an n-ary tree, return the postorder traversal of its nodes' values. 4 | 5 | # Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples). 6 | 7 | 8 | 9 | # Follow up: 10 | 11 | # Recursive solution is trivial, could you do it iteratively? 12 | 13 | 14 | 15 | # Example 1: 16 | 17 | # Input: root = [1,null,3,2,4,null,5,6] 18 | # Output: [5,6,3,2,4,1] 19 | 20 | # Example 2: 21 | 22 | # Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] 23 | # Output: [2,6,14,11,7,3,12,8,4,13,9,10,5,1] 24 | 25 | 26 | 27 | # Constraints: 28 | 29 | # The height of the n-ary tree is less than or equal to 1000 30 | # The total number of nodes is between [0, 10^4] 31 | 32 | 33 | """ 34 | # Definition for a Node. 35 | class Node: 36 | def __init__(self, val=None, children=None): 37 | self.val = val 38 | self.children = children 39 | """ 40 | 41 | class Solution: 42 | def postorder(self, root: 'Node') -> List[int]: 43 | res = [] 44 | def dfs(root): 45 | if not root: 46 | return 47 | for i in root.children: 48 | dfs(i) 49 | res.append(root.val) 50 | dfs(root) 51 | return res -------------------------------------------------------------------------------- /LeetCode/cpp/1221.balancestr.cpp: -------------------------------------------------------------------------------- 1 | // Balanced strings are those who have equal quantity of 'L' and 'R' characters. 2 | 3 | // Given a balanced string s split it in the maximum amount of balanced strings. 4 | 5 | // Return the maximum amount of splitted balanced strings. 6 | 7 | 8 | 9 | // Example 1: 10 | 11 | // Input: s = "RLRRLLRLRL" 12 | // Output: 4 13 | // Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'. 14 | 15 | // Example 2: 16 | 17 | // Input: s = "RLLLLRRRLR" 18 | // Output: 3 19 | // Explanation: s can be split into "RL", "LLLRRR", "LR", each substring contains same number of 'L' and 'R'. 20 | 21 | // Example 3: 22 | 23 | // Input: s = "LLLLRRRR" 24 | // Output: 1 25 | // Explanation: s can be split into "LLLLRRRR". 26 | 27 | // Example 4: 28 | 29 | // Input: s = "RLRRRLLRLL" 30 | // Output: 2 31 | // Explanation: s can be split into "RL", "RRRLLRLL", since each substring contains an equal number of 'L' and 'R' 32 | 33 | class Solution { 34 | public: 35 | int balancedStringSplit(string s) { 36 | int i,j,rcount=0,lcount=0; 37 | int res = 0; 38 | string temp; 39 | for(i = 0;i < s.length(); i++){ 40 | if (s[i] == 'R') 41 | rcount += 1; 42 | if (s[i] == 'L') 43 | lcount += 1; 44 | if (rcount == lcount) 45 | res += 1; 46 | } 47 | return res; 48 | } 49 | }; -------------------------------------------------------------------------------- /LeetCode/python/657.robotturns.py: -------------------------------------------------------------------------------- 1 | # There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves. 2 | 3 | # The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves are R (right), L (left), U (up), and D (down). If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false. 4 | 5 | # Note: The way that the robot is "facing" is irrelevant. "R" will always make the robot move to the right once, "L" will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move. 6 | 7 | # Example 1: 8 | 9 | # Input: "UD" 10 | # Output: true 11 | # Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true. 12 | 13 | 14 | 15 | # Example 2: 16 | 17 | # Input: "LL" 18 | # Output: false 19 | # Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves. 20 | 21 | # Accepted 22 | # 238,875 23 | # Submissions 24 | # 325,023 25 | 26 | class Solution: 27 | def judgeCircle(self, moves: str) -> bool: 28 | if moves.count('U') == moves.count('D') and moves.count('L') == moves.count('R'): 29 | return True 30 | else: 31 | return False -------------------------------------------------------------------------------- /LeetCode/python/1309.decryptstring.py: -------------------------------------------------------------------------------- 1 | # Given a string s formed by digits ('0' - '9') and '#' . We want to map s to English lowercase characters as follows: 2 | 3 | # Characters ('a' to 'i') are represented by ('1' to '9') respectively. 4 | # Characters ('j' to 'z') are represented by ('10#' to '26#') respectively. 5 | 6 | # Return the string formed after mapping. 7 | 8 | # It's guaranteed that a unique mapping will always exist. 9 | 10 | 11 | 12 | # Example 1: 13 | 14 | # Input: s = "10#11#12" 15 | # Output: "jkab" 16 | # Explanation: "j" -> "10#" , "k" -> "11#" , "a" -> "1" , "b" -> "2". 17 | 18 | # Example 2: 19 | 20 | # Input: s = "1326#" 21 | # Output: "acz" 22 | 23 | # Example 3: 24 | 25 | # Input: s = "25#" 26 | # Output: "y" 27 | 28 | # Example 4: 29 | 30 | # Input: s = "12345678910#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#" 31 | # Output: "abcdefghijklmnopqrstuvwxyz" 32 | 33 | 34 | 35 | # Constraints: 36 | 37 | # 1 <= s.length <= 1000 38 | # s[i] only contains digits letters ('0'-'9') and '#' letter. 39 | # s will be valid string such that mapping is always possible. 40 | 41 | class Solution: 42 | def freqAlphabets(self, s: str) -> str: 43 | res = '' 44 | i = 0 45 | while ( i < len(s)): 46 | temp = s[i:i+3] 47 | if '#' in temp: 48 | res += chr(int(temp[:2]) + 96) 49 | i += 3 50 | else: 51 | res+=chr(int(temp[0]) + 96) 52 | i += 1 53 | return res -------------------------------------------------------------------------------- /LeetCode/python/1266.minvisitingtime.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/minimum-time-visiting-all-points/ 2 | 3 | # On a plane there are n points with integer coordinates points[i] = [xi, yi]. Your task is to find the minimum time in seconds to visit all points. 4 | 5 | # You can move according to the next rules: 6 | 7 | # In one second always you can either move vertically, horizontally by one unit or diagonally (it means to move one unit vertically and one unit horizontally in one second). 8 | # You have to visit the points in the same order as they appear in the array. 9 | 10 | 11 | 12 | # Example 1: 13 | 14 | # Input: points = [[1,1],[3,4],[-1,0]] 15 | # Output: 7 16 | # Explanation: One optimal path is [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0] 17 | # Time from [1,1] to [3,4] = 3 seconds 18 | # Time from [3,4] to [-1,0] = 4 seconds 19 | # Total time = 7 seconds 20 | 21 | # Example 2: 22 | 23 | # Input: points = [[3,2],[-2,2]] 24 | # Output: 5 25 | 26 | 27 | 28 | # Constraints: 29 | 30 | # points.length == n 31 | # 1 <= n <= 100 32 | # points[i].length == 2 33 | # -1000 <= points[i][0], points[i][1] <= 1000 34 | 35 | class Solution: 36 | def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int: 37 | res = 0 38 | # x1,y1 = points[0][0] 39 | i= 0 40 | while(i < len(points) - 1): 41 | res += max(abs(points[i][0] - points[i+1][0]),abs(points[i][1] - points[i+1][1])) 42 | i+=1 43 | return res -------------------------------------------------------------------------------- /LeetCode/python/1290.bintointlinkedlist.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/ 2 | 3 | # Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number. 4 | 5 | # Return the decimal value of the number in the linked list. 6 | 7 | 8 | 9 | # Example 1: 10 | 11 | 12 | # Input: head = [1,0,1] 13 | # Output: 5 14 | # Explanation: (101) in base 2 = (5) in base 10 15 | # Example 2: 16 | 17 | # Input: head = [0] 18 | # Output: 0 19 | # Example 3: 20 | 21 | # Input: head = [1] 22 | # Output: 1 23 | # Example 4: 24 | 25 | # Input: head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0] 26 | # Output: 18880 27 | # Example 5: 28 | 29 | # Input: head = [0,0] 30 | # Output: 0 31 | 32 | 33 | # Constraints: 34 | 35 | # The Linked List is not empty. 36 | # Number of nodes will not exceed 30. 37 | # Each node's value is either 0 or 1. 38 | 39 | # Definition for singly-linked list. 40 | # class ListNode: 41 | # def __init__(self, val=0, next=None): 42 | # self.val = val 43 | # self.next = next 44 | 45 | class Solution: 46 | 47 | def getDecimalValue(self, head: ListNode) -> int: 48 | 49 | arr = [] 50 | while (head != None): 51 | arr.append(head.val) 52 | head = head.next 53 | n = 0 54 | size = len(arr) 55 | for i in range(size): 56 | n += arr[len(arr) - i - 1] * 2**i 57 | return n -------------------------------------------------------------------------------- /LeetCode/python/832.flippingimage.py: -------------------------------------------------------------------------------- 1 | # Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image. 2 | 3 | # To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0] horizontally results in [0, 1, 1]. 4 | 5 | # To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [0, 1, 1] results in [1, 0, 0]. 6 | 7 | # Example 1: 8 | 9 | # Input: [[1,1,0],[1,0,1],[0,0,0]] 10 | # Output: [[1,0,0],[0,1,0],[1,1,1]] 11 | # Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]]. 12 | # Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]] 13 | 14 | # Example 2: 15 | 16 | # Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] 17 | # Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] 18 | # Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]]. 19 | # Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] 20 | 21 | # Notes: 22 | 23 | # 1 <= A.length = A[0].length <= 20 24 | # 0 <= A[i][j] <= 1 25 | 26 | class Solution: 27 | def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]: 28 | arr = [] 29 | for i in range(len(A)): 30 | arr.append(A[i][::-1]) 31 | for i in range(len(arr)): 32 | for j in range(len(arr[0])): 33 | if arr[i][j] == 0: 34 | arr[i][j] = 1 35 | else: 36 | arr[i][j] = 0 37 | return arr 38 | -------------------------------------------------------------------------------- /LeetCode/cpp/1528.shufflestr.cpp: -------------------------------------------------------------------------------- 1 | // Given a string s and an integer array indices of the same length. 2 | 3 | // The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string. 4 | 5 | // Return the shuffled string. 6 | 7 | 8 | 9 | // Example 1: 10 | 11 | // Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3] 12 | // Output: "leetcode" 13 | // Explanation: As shown, "codeleet" becomes "leetcode" after shuffling. 14 | 15 | // Example 2: 16 | 17 | // Input: s = "abc", indices = [0,1,2] 18 | // Output: "abc" 19 | // Explanation: After shuffling, each character remains in its position. 20 | 21 | // Example 3: 22 | 23 | // Input: s = "aiohn", indices = [3,1,4,2,0] 24 | // Output: "nihao" 25 | 26 | // Example 4: 27 | 28 | // Input: s = "aaiougrt", indices = [4,0,2,6,7,3,1,5] 29 | // Output: "arigatou" 30 | 31 | // Example 5: 32 | 33 | // Input: s = "art", indices = [1,0,2] 34 | // Output: "rat" 35 | 36 | 37 | 38 | // Constraints: 39 | 40 | // s.length == indices.length == n 41 | // 1 <= n <= 100 42 | // s contains only lower-case English letters. 43 | // 0 <= indices[i] < n 44 | // All values of indices are unique (i.e. indices is a permutation of the integers from 0 to n - 1). 45 | 46 | class Solution { 47 | public: 48 | string restoreString(string s, vector& indices) { 49 | string res = s; 50 | for(int i = 0; i < indices.size(); i++){ 51 | res[indices[i]] = s[i] ; 52 | } 53 | return res; 54 | } 55 | }; -------------------------------------------------------------------------------- /LeetCode/cpp/938.rangesumtree.cpp: -------------------------------------------------------------------------------- 1 | // Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive). 2 | 3 | // The binary search tree is guaranteed to have unique values. 4 | 5 | 6 | 7 | // Example 1: 8 | 9 | // Input: root = [10,5,15,3,7,null,18], L = 7, R = 15 10 | // Output: 32 11 | 12 | // Example 2: 13 | 14 | // Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10 15 | // Output: 23 16 | 17 | 18 | 19 | // Note: 20 | 21 | // The number of nodes in the tree is at most 10000. 22 | // The final answer is guaranteed to be less than 2^31. 23 | 24 | 25 | /** 26 | * Definition for a binary tree node. 27 | * struct TreeNode { 28 | * int val; 29 | * TreeNode *left; 30 | * TreeNode *right; 31 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 32 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 33 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 34 | * }; 35 | */ 36 | class Solution { 37 | public: 38 | int sum = 0; 39 | void dfs(TreeNode* root,int L, int R){ 40 | if(root){ 41 | // cout<val< left,L,R); 43 | dfs(root -> right,L,R); 44 | if ((root -> val >= L) && (root -> val <= R)){ 45 | sum+= root -> val; 46 | } 47 | } 48 | return; 49 | } 50 | int rangeSumBST(TreeNode* root, int L, int R) { 51 | 52 | dfs(root,L,R); 53 | return sum; 54 | } 55 | }; -------------------------------------------------------------------------------- /LeetCode/python/11.watercontainer.py: -------------------------------------------------------------------------------- 1 | # Link: https://leetcode.com/problems/container-with-most-water/ 2 | 3 | # Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. 4 | 5 | # Note: You may not slant the container and n is at least 2. 6 | 7 | 8 | 9 | # The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. 10 | 11 | 12 | 13 | # Example: 14 | 15 | # Input: [1,8,6,2,5,4,8,3,7] 16 | # Output: 49 17 | 18 | class Solution: 19 | def maxArea(self, height: List[int]) -> int: 20 | if not height: 21 | return 0 22 | left = 0 23 | right = len(height) - 1 24 | print(height[left],height[right]) 25 | vol = 0 26 | while ( left < right): 27 | width = right - left 28 | temp = width * (min(height[left],height[right])) 29 | if temp > vol: 30 | vol = temp 31 | if height[left] > height[right]: 32 | right-=1 33 | else: 34 | if height[left] < height[right]: 35 | left+=1 36 | else: 37 | if height[left] == height[right]: 38 | left+=1 39 | right-=1 40 | 41 | return(vol) -------------------------------------------------------------------------------- /LeetCode/python/1221.splittingstrings.py: -------------------------------------------------------------------------------- 1 | # Balanced strings are those who have equal quantity of 'L' and 'R' characters. 2 | 3 | # Given a balanced string s split it in the maximum amount of balanced strings. 4 | 5 | # Return the maximum amount of splitted balanced strings. 6 | 7 | 8 | 9 | # Example 1: 10 | 11 | # Input: s = "RLRRLLRLRL" 12 | # Output: 4 13 | # Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'. 14 | 15 | # Example 2: 16 | 17 | # Input: s = "RLLLLRRRLR" 18 | # Output: 3 19 | # Explanation: s can be split into "RL", "LLLRRR", "LR", each substring contains same number of 'L' and 'R'. 20 | 21 | # Example 3: 22 | 23 | # Input: s = "LLLLRRRR" 24 | # Output: 1 25 | # Explanation: s can be split into "LLLLRRRR". 26 | 27 | # Example 4: 28 | 29 | # Input: s = "RLRRRLLRLL" 30 | # Output: 2 31 | # Explanation: s can be split into "RL", "RRRLLRLL", since each substring contains an equal number of 'L' and 'R' 32 | 33 | 34 | 35 | # Constraints: 36 | 37 | # 1 <= s.length <= 1000 38 | # s[i] = 'L' or 'R' 39 | 40 | class Solution: 41 | def balancedStringSplit(self, s: str) -> int: 42 | lcount = 0 43 | rcount = 0 44 | i = 0 45 | tcount = 0 46 | while ( i < len(s)): 47 | if s[i] == 'R': 48 | rcount += 1 49 | if s[i] == 'L': 50 | lcount +=1 51 | if lcount == rcount: 52 | tcount+=1 53 | rcount = 0 54 | lcount = 0 55 | i+=1 56 | return tcount -------------------------------------------------------------------------------- /LeetCode/cpp/1266.mintime.cpp: -------------------------------------------------------------------------------- 1 | // On a plane there are n points with integer coordinates points[i] = [xi, yi]. Your task is to find the minimum time in seconds to visit all points. 2 | 3 | // You can move according to the next rules: 4 | 5 | // In one second always you can either move vertically, horizontally by one unit or diagonally (it means to move one unit vertically and one unit horizontally in one second). 6 | // You have to visit the points in the same order as they appear in the array. 7 | 8 | 9 | 10 | // Example 1: 11 | 12 | // Input: points = [[1,1],[3,4],[-1,0]] 13 | // Output: 7 14 | // Explanation: One optimal path is [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0] 15 | // Time from [1,1] to [3,4] = 3 seconds 16 | // Time from [3,4] to [-1,0] = 4 seconds 17 | // Total time = 7 seconds 18 | 19 | // Example 2: 20 | 21 | // Input: points = [[3,2],[-2,2]] 22 | // Output: 5 23 | 24 | 25 | 26 | // Constraints: 27 | 28 | // points.length == n 29 | // 1 <= n <= 100 30 | // points[i].length == 2 31 | // -1000 <= points[i][0], points[i][1] <= 1000 32 | 33 | 34 | class Solution { 35 | public: 36 | int minTimeToVisitAllPoints(vector>& points) { 37 | int res = 0; 38 | int i = 0; 39 | while(i < points.size() - 1){ 40 | res += max(abs(points[i+1][0] - points[i][0]),abs(points[i+1][1] - points[i][1])); 41 | // cout << points[i+1][1] <<" "<< points[i][1] < str: 49 | res = {} 50 | for i in range(len(s)): 51 | res[indices[i]] = s[i] 52 | res = sorted(res.items(),key = lambda x:x[0]) 53 | ress = '' 54 | for i in range(len(s)): 55 | ress += res[i][1] 56 | return ress -------------------------------------------------------------------------------- /LeetCode/python/75.sortcolor.py: -------------------------------------------------------------------------------- 1 | # Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. 2 | 3 | # Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. 4 | 5 | # Note: You are not suppose to use the library's sort function for this problem. 6 | 7 | # Example: 8 | 9 | # Input: [2,0,2,1,1,0] 10 | # Output: [0,0,1,1,2,2] 11 | 12 | # Follow up: 13 | 14 | # A rather straight forward solution is a two-pass algorithm using counting sort. 15 | # First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's. 16 | # Could you come up with a one-pass algorithm using only constant space? 17 | 18 | class Solution: 19 | def sortColors(self, nums: List[int]) -> None: 20 | """ 21 | Do not return anything, modify nums in-place instead. 22 | """ 23 | 24 | red=0 25 | white=0 26 | blue=0 27 | 28 | for i in range(len(nums)): 29 | if nums[i]==0: 30 | red+=1 31 | if nums[i]==1: 32 | white+=1 33 | if nums[i]==2: 34 | blue+=1 35 | 36 | i=0 37 | for j in range(red): 38 | nums[i]=0 39 | i+=1 40 | for j in range(white): 41 | nums[i]=1 42 | i+=1 43 | for j in range(blue): 44 | nums[i]=2 45 | i+=1 46 | print(nums) -------------------------------------------------------------------------------- /LeetCode/python/15.3sum.py: -------------------------------------------------------------------------------- 1 | # Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. 2 | 3 | # Note: 4 | 5 | # The solution set must not contain duplicate triplets. 6 | 7 | # Example: 8 | 9 | # Given array nums = [-1, 0, 1, 2, -1, -4], 10 | 11 | # A solution set is: 12 | # [ 13 | # [-1, 0, 1], 14 | # [-1, -1, 2] 15 | # ] 16 | 17 | class Solution: 18 | def threeSum(self, nums: List[int]) -> List[List[int]]: 19 | res = [] 20 | nums.sort() 21 | for i in range(len(nums) - 2 ): 22 | if i > 0 and nums[i] == nums[i-1]: 23 | continue 24 | left = i + 1 25 | right = len(nums) - 1 26 | while (left < right): 27 | sum = nums[i] + nums [left] + nums[right] 28 | if sum < 0: 29 | left += 1 30 | elif sum > 0: 31 | right -=1 32 | else: 33 | temp = [] 34 | temp.append(nums[i]) 35 | temp.append(nums[left]) 36 | temp.append(nums[right]) 37 | res.append(temp) 38 | while ( left < right and nums[left] == nums[left+1] ): 39 | left+=1 40 | while ( left < right and nums[right] == nums[right-1] ): 41 | right-=1 42 | left+=1 43 | right-=1 44 | 45 | 46 | return(res) 47 | 48 | -------------------------------------------------------------------------------- /GeeksForGeeks/max_index.py: -------------------------------------------------------------------------------- 1 | Given an array A[] of N positive integers. The task is to find the maximum of j - i subjected to the constraint of A[i] <= A[j]. 2 | 3 | Input: 4 | The first line contains an integer T, depicting total number of test cases. Then T test case follows. First line of each test case contains an integer N denoting the size of the array. Next line contains N space separated integeres denoting the elements of the array. 5 | 6 | Output: 7 | Print the maximum difference of the indexes i and j in a separtate line. 8 | 9 | Constraints: 10 | 1 ≤ T ≤ 1000 11 | 1 ≤ N ≤ 107 12 | 0 ≤ A[i] ≤ 1018 13 | 14 | Example: 15 | Input: 16 | 1 17 | 9 18 | 34 8 10 3 2 80 30 33 1 19 | 20 | Output: 21 | 6 22 | 23 | Explanation: 24 | Testcase 1: In the given array A[1] < A[7] satisfying the required condition(A[i] <= A[j]) thus giving the maximum difference of j - i which is 6(7-1). 25 | #code 26 | 27 | tcase = int(input()) 28 | 29 | for i in range(tcase): 30 | 31 | size = int(input()) 32 | arr = list(map(int,input().split())) 33 | maxdiff = 0 34 | 35 | start = 0 36 | 37 | while (start <= size): 38 | end = size - 1 39 | 40 | if(maxdiff > end - start): 41 | break 42 | 43 | while (start <= end): 44 | 45 | if (arr[start] <= arr[end]): 46 | if (end - start > maxdiff): 47 | maxdiff = end - start 48 | break 49 | 50 | if (arr[start] > arr[end]): 51 | end-=1 52 | 53 | start+=1 54 | 55 | 56 | print(maxdiff) -------------------------------------------------------------------------------- /LeetCode/python/1038.btree.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/ 2 | # Given the root of a binary search tree with distinct values, modify it so that every node has a new value equal to the sum of the values of the original tree that are greater than or equal to node.val. 3 | 4 | # As a reminder, a binary search tree is a tree that satisfies these constraints: 5 | 6 | # The left subtree of a node contains only nodes with keys less than the node's key. 7 | # The right subtree of a node contains only nodes with keys greater than the node's key. 8 | # Both the left and right subtrees must also be binary search trees. 9 | 10 | 11 | 12 | # Example 1: 13 | 14 | # Input: [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8] 15 | # Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8] 16 | 17 | 18 | 19 | # Constraints: 20 | 21 | # The number of nodes in the tree is between 1 and 100. 22 | # Each node will have value between 0 and 100. 23 | # The given tree is a binary search tree. 24 | 25 | 26 | # Definition for a binary tree node. 27 | # class TreeNode: 28 | # def __init__(self, val=0, left=None, right=None): 29 | # self.val = val 30 | # self.left = left 31 | # self.right = right 32 | class Solution: 33 | def bstToGst(self, root: TreeNode) -> TreeNode: 34 | self.cur = 0 35 | def dfs(node): 36 | if not node: 37 | return 38 | dfs(node.right) 39 | self.cur += node.val 40 | node.val = self.cur 41 | dfs(node.left) 42 | dfs(root) 43 | return root -------------------------------------------------------------------------------- /LeetCode/python/617.merge2trees.py: -------------------------------------------------------------------------------- 1 | # Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. 2 | 3 | # You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree. 4 | 5 | # Example 1: 6 | 7 | # Input: 8 | # Tree 1 Tree 2 9 | # 1 2 10 | # / \ / \ 11 | # 3 2 1 3 12 | # / \ \ 13 | # 5 4 7 14 | # Output: 15 | # Merged tree: 16 | # 3 17 | # / \ 18 | # 4 5 19 | # / \ \ 20 | # 5 4 7 21 | 22 | 23 | 24 | # Note: The merging process must start from the root nodes of both trees. 25 | 26 | 27 | # Definition for a binary tree node. 28 | # class TreeNode: 29 | # def __init__(self, val=0, left=None, right=None): 30 | # self.val = val 31 | # self.left = left 32 | # self.right = right 33 | class Solution: 34 | def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: 35 | if t1 and t2: 36 | res = TreeNode(t1.val + t2.val) 37 | res.left = self.mergeTrees(t1.left,t2.left) 38 | res.right = self.mergeTrees(t1.right,t2.right) 39 | else: 40 | return t1 or t2 41 | return res -------------------------------------------------------------------------------- /LeetCode/python/1460.canbeequal.py: -------------------------------------------------------------------------------- 1 | # Given two integer arrays of equal length target and arr. 2 | 3 | # In one step, you can select any non-empty sub-array of arr and reverse it. You are allowed to make any number of steps. 4 | 5 | # Return True if you can make arr equal to target, or False otherwise. 6 | 7 | 8 | 9 | # Example 1: 10 | 11 | # Input: target = [1,2,3,4], arr = [2,4,1,3] 12 | # Output: true 13 | # Explanation: You can follow the next steps to convert arr to target: 14 | # 1- Reverse sub-array [2,4,1], arr becomes [1,4,2,3] 15 | # 2- Reverse sub-array [4,2], arr becomes [1,2,4,3] 16 | # 3- Reverse sub-array [4,3], arr becomes [1,2,3,4] 17 | # There are multiple ways to convert arr to target, this is not the only way to do so. 18 | 19 | # Example 2: 20 | 21 | # Input: target = [7], arr = [7] 22 | # Output: true 23 | # Explanation: arr is equal to target without any reverses. 24 | 25 | # Example 3: 26 | 27 | # Input: target = [1,12], arr = [12,1] 28 | # Output: true 29 | 30 | # Example 4: 31 | 32 | # Input: target = [3,7,9], arr = [3,7,11] 33 | # Output: false 34 | # Explanation: arr doesn't have value 9 and it can never be converted to target. 35 | 36 | # Example 5: 37 | 38 | # Input: target = [1,1,1,1,1], arr = [1,1,1,1,1] 39 | # Output: true 40 | 41 | 42 | 43 | # Constraints: 44 | 45 | # target.length == arr.length 46 | # 1 <= target.length <= 1000 47 | # 1 <= target[i] <= 1000 48 | # 1 <= arr[i] <= 1000 49 | 50 | class Solution: 51 | def canBeEqual(self, target: List[int], arr: List[int]) -> bool: 52 | if sorted(target) == sorted(arr): 53 | return True 54 | else: 55 | return False -------------------------------------------------------------------------------- /LeetCode/python/1436.destinationcity.py: -------------------------------------------------------------------------------- 1 | # You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city. 2 | 3 | # It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city. 4 | 5 | 6 | 7 | # Example 1: 8 | 9 | # Input: paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]] 10 | # Output: "Sao Paulo" 11 | # Explanation: Starting at "London" city you will reach "Sao Paulo" city which is the destination city. Your trip consist of: "London" -> "New York" -> "Lima" -> "Sao Paulo". 12 | 13 | # Example 2: 14 | 15 | # Input: paths = [["B","C"],["D","B"],["C","A"]] 16 | # Output: "A" 17 | # Explanation: All possible trips are: 18 | # "D" -> "B" -> "C" -> "A". 19 | # "B" -> "C" -> "A". 20 | # "C" -> "A". 21 | # "A". 22 | # Clearly the destination city is "A". 23 | 24 | # Example 3: 25 | 26 | # Input: paths = [["A","Z"]] 27 | # Output: "Z" 28 | 29 | 30 | 31 | # Constraints: 32 | 33 | # 1 <= paths.length <= 100 34 | # paths[i].length == 2 35 | # 1 <= cityAi.length, cityBi.length <= 10 36 | # cityAi != cityBi 37 | # All strings consist of lowercase and uppercase English letters and the space character. 38 | 39 | class Solution: 40 | def destCity(self, paths: List[List[str]]) -> str: 41 | start = [] 42 | end = [] 43 | for i,j in paths: 44 | start.append(i) 45 | end.append(j) 46 | for i in end: 47 | if i not in start: 48 | return i 49 | return -------------------------------------------------------------------------------- /LeetCode/python/1252.arrwithoddvalues.py: -------------------------------------------------------------------------------- 1 | # Given n and m which are the dimensions of a matrix initialized by zeros and given an array indices where indices[i] = [ri, ci]. For each pair of [ri, ci] you have to increment all cells in row ri and column ci by 1. 2 | 3 | # Return the number of cells with odd values in the matrix after applying the increment to all indices. 4 | 5 | 6 | 7 | # Example 1: 8 | 9 | # Input: n = 2, m = 3, indices = [[0,1],[1,1]] 10 | # Output: 6 11 | # Explanation: Initial matrix = [[0,0,0],[0,0,0]]. 12 | # After applying first increment it becomes [[1,2,1],[0,1,0]]. 13 | # The final matrix will be [[1,3,1],[1,3,1]] which contains 6 odd numbers. 14 | 15 | # Example 2: 16 | 17 | # Input: n = 2, m = 2, indices = [[1,1],[0,0]] 18 | # Output: 0 19 | # Explanation: Final matrix = [[2,2],[2,2]]. There is no odd number in the final matrix. 20 | 21 | 22 | 23 | # Constraints: 24 | 25 | # 1 <= n <= 50 26 | # 1 <= m <= 50 27 | # 1 <= indices.length <= 100 28 | # 0 <= indices[i][0] < n 29 | # 0 <= indices[i][1] < m 30 | 31 | class Solution: 32 | def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int: 33 | arr = [[0 for i in range(m)] for j in range(n)] 34 | 35 | def inc(row,column): 36 | for i in range(m): 37 | arr[row][i] += 1 38 | for i in range(n): 39 | arr[i][column] += 1 40 | 41 | for i,j in indices: 42 | inc(i,j) 43 | 44 | res = 0 45 | print(arr) 46 | for i in range(n): 47 | for j in range(m): 48 | if (arr[i][j] % 2 == 1): 49 | res += 1 50 | return(res) -------------------------------------------------------------------------------- /LeetCode/python/1389.insertinorder.py: -------------------------------------------------------------------------------- 1 | # Given two arrays of integers nums and index. Your task is to create target array under the following rules: 2 | 3 | # Initially target array is empty. 4 | # From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array. 5 | # Repeat the previous step until there are no elements to read in nums and index. 6 | 7 | # Return the target array. 8 | 9 | # It is guaranteed that the insertion operations will be valid. 10 | 11 | 12 | 13 | # Example 1: 14 | 15 | # Input: nums = [0,1,2,3,4], index = [0,1,2,2,1] 16 | # Output: [0,4,1,3,2] 17 | # Explanation: 18 | # nums index target 19 | # 0 0 [0] 20 | # 1 1 [0,1] 21 | # 2 2 [0,1,2] 22 | # 3 2 [0,1,3,2] 23 | # 4 1 [0,4,1,3,2] 24 | 25 | # Example 2: 26 | 27 | # Input: nums = [1,2,3,4,0], index = [0,1,2,3,0] 28 | # Output: [0,1,2,3,4] 29 | # Explanation: 30 | # nums index target 31 | # 1 0 [1] 32 | # 2 1 [1,2] 33 | # 3 2 [1,2,3] 34 | # 4 3 [1,2,3,4] 35 | # 0 0 [0,1,2,3,4] 36 | 37 | # Example 3: 38 | 39 | # Input: nums = [1], index = [0] 40 | # Output: [1] 41 | 42 | 43 | 44 | # Constraints: 45 | 46 | # 1 <= nums.length, index.length <= 100 47 | # nums.length == index.length 48 | # 0 <= nums[i] <= 100 49 | # 0 <= index[i] <= i 50 | 51 | class Solution: 52 | def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]: 53 | arr = [] 54 | for i in range(len(nums)): 55 | arr.insert(index[i],nums[i]) 56 | return arr -------------------------------------------------------------------------------- /LeetCode/cpp/1460.equalsubarr.cpp: -------------------------------------------------------------------------------- 1 | // Given two integer arrays of equal length target and arr. 2 | 3 | // In one step, you can select any non-empty sub-array of arr and reverse it. You are allowed to make any number of steps. 4 | 5 | // Return True if you can make arr equal to target, or False otherwise. 6 | 7 | 8 | 9 | // Example 1: 10 | 11 | // Input: target = [1,2,3,4], arr = [2,4,1,3] 12 | // Output: true 13 | // Explanation: You can follow the next steps to convert arr to target: 14 | // 1- Reverse sub-array [2,4,1], arr becomes [1,4,2,3] 15 | // 2- Reverse sub-array [4,2], arr becomes [1,2,4,3] 16 | // 3- Reverse sub-array [4,3], arr becomes [1,2,3,4] 17 | // There are multiple ways to convert arr to target, this is not the only way to do so. 18 | 19 | // Example 2: 20 | 21 | // Input: target = [7], arr = [7] 22 | // Output: true 23 | // Explanation: arr is equal to target without any reverses. 24 | 25 | // Example 3: 26 | 27 | // Input: target = [1,12], arr = [12,1] 28 | // Output: true 29 | 30 | // Example 4: 31 | 32 | // Input: target = [3,7,9], arr = [3,7,11] 33 | // Output: false 34 | // Explanation: arr doesn't have value 9 and it can never be converted to target. 35 | 36 | // Example 5: 37 | 38 | // Input: target = [1,1,1,1,1], arr = [1,1,1,1,1] 39 | // Output: true 40 | 41 | 42 | 43 | // Constraints: 44 | 45 | // target.length == arr.length 46 | // 1 <= target.length <= 1000 47 | // 1 <= target[i] <= 1000 48 | // 1 <= arr[i] <= 1000 49 | 50 | class Solution { 51 | public: 52 | bool canBeEqual(vector& target, vector& arr) { 53 | sort(target.begin(),target.end()); 54 | sort(arr.begin(),arr.end()); 55 | 56 | return arr==target; 57 | } 58 | }; -------------------------------------------------------------------------------- /LeetCode/python/38.countandsay.py: -------------------------------------------------------------------------------- 1 | # The count-and-say sequence is the sequence of integers with the first five terms as following: 2 | 3 | # 1. 1 4 | # 2. 11 5 | # 3. 21 6 | # 4. 1211 7 | # 5. 111221 8 | 9 | # 1 is read off as "one 1" or 11. 10 | # 11 is read off as "two 1s" or 21. 11 | # 21 is read off as "one 2, then one 1" or 1211. 12 | 13 | # Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit. 14 | 15 | # Note: Each term of the sequence of integers will be represented as a string. 16 | 17 | 18 | 19 | # Example 1: 20 | 21 | # Input: 1 22 | # Output: "1" 23 | # Explanation: This is the base case. 24 | 25 | # Example 2: 26 | 27 | # Input: 4 28 | # Output: "1211" 29 | # Explanation: For n = 3 the term was "21" in which we have two groups "2" and "1", "2" can be read as "12" which means frequency = 1 and value = 2, the same way "1" is read as "11", so the answer is the concatenation of "12" and "11" which is "1211". 30 | 31 | class Solution: 32 | def countAndSay(self, n: int) -> str: 33 | s = '1' 34 | for i in range(n-1): 35 | temp = [] 36 | count = 1 37 | for j in range(1,len(s)): 38 | if s[j] == s[j-1]: 39 | count += 1 40 | else: 41 | temp.append(str(count)) 42 | temp.append(s[j-1]) 43 | count = 1 44 | temp.append(str(count)) 45 | temp.append(s[-1]) 46 | s = ''.join(temp) 47 | return s 48 | -------------------------------------------------------------------------------- /GeeksForGeeks/subarray.py: -------------------------------------------------------------------------------- 1 | # Given an unsorted array A of size N of non-negative integers, find a continuous sub-array which adds to a given number S. 2 | 3 | # Input: 4 | # The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case consists of two lines. The first line of each test case is N and S, where N is the size of array and S is the sum. The second line of each test case contains N space separated integers denoting the array elements. 5 | 6 | # Output: 7 | # For each testcase, in a new line, print the starting and ending positions(1 indexing) of first such occuring subarray from the left if sum equals to subarray, else print -1. 8 | 9 | # Constraints: 10 | # 1 <= T <= 100 11 | # 1 <= N <= 107 12 | # 1 <= Ai <= 1010 13 | 14 | # Example: 15 | # Input: 16 | # 2 17 | # 5 12 18 | # 1 2 3 7 5 19 | # 10 15 20 | # 1 2 3 4 5 6 7 8 9 10 21 | # Output: 22 | # 2 4 23 | # 1 5 24 | 25 | # Explanation : 26 | # Testcase1: sum of elements from 2nd position to 4th position is 12 27 | # Testcase2: sum of elements from 1st position to 5th position is 15 28 | 29 | tcase = int(input()) 30 | for i in range(tcase): 31 | size,sum = map(int,input().split()) 32 | arr = list(map(int,input().split())) 33 | temp=0 34 | start,end,cursum,flag = 0,size,0,0 35 | while(start <= end and temp < end): 36 | cursum+=arr[temp] 37 | 38 | while(cursum >= sum): 39 | if(cursum==sum): 40 | print(start+1,temp+1) 41 | flag=1 42 | break 43 | cursum-=arr[start] 44 | start+=1 45 | temp+=1 46 | if(flag==1): 47 | break 48 | if(flag == 0): 49 | print(-1) -------------------------------------------------------------------------------- /LeetCode/cpp/1290.listtobin.cpp: -------------------------------------------------------------------------------- 1 | // Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number. 2 | 3 | // Return the decimal value of the number in the linked list. 4 | 5 | 6 | 7 | // Example 1: 8 | 9 | // Input: head = [1,0,1] 10 | // Output: 5 11 | // Explanation: (101) in base 2 = (5) in base 10 12 | 13 | // Example 2: 14 | 15 | // Input: head = [0] 16 | // Output: 0 17 | 18 | // Example 3: 19 | 20 | // Input: head = [1] 21 | // Output: 1 22 | 23 | // Example 4: 24 | 25 | // Input: head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0] 26 | // Output: 18880 27 | 28 | // Example 5: 29 | 30 | // Input: head = [0,0] 31 | // Output: 0 32 | 33 | 34 | 35 | // Constraints: 36 | 37 | // The Linked List is not empty. 38 | // Number of nodes will not exceed 30. 39 | // Each node's value is either 0 or 1. 40 | 41 | /** 42 | * Definition for singly-linked list. 43 | * struct ListNode { 44 | * int val; 45 | * ListNode *next; 46 | * ListNode() : val(0), next(nullptr) {} 47 | * ListNode(int x) : val(x), next(nullptr) {} 48 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 49 | * }; 50 | */ 51 | class Solution { 52 | public: 53 | int getDecimalValue(ListNode* head) { 54 | vector res; 55 | while(head){ 56 | res.push_back(head->val); 57 | head = head ->next; 58 | } 59 | int finalres = 0; 60 | reverse(res.begin(),res.end()); 61 | for(auto i = 0;i < res.size();i++){ 62 | if(res[i] == 1){ 63 | finalres = finalres + pow(2,i); 64 | } 65 | } 66 | return finalres; 67 | } 68 | }; -------------------------------------------------------------------------------- /LeetCode/cpp/1432.noofstepsto0.cpp: -------------------------------------------------------------------------------- 1 | // Given a non-negative integer num, return the number of steps to reduce it to zero. If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it. 2 | 3 | 4 | 5 | // Example 1: 6 | 7 | // Input: num = 14 8 | // Output: 6 9 | // Explanation: 10 | // Step 1) 14 is even; divide by 2 and obtain 7. 11 | // Step 2) 7 is odd; subtract 1 and obtain 6. 12 | // Step 3) 6 is even; divide by 2 and obtain 3. 13 | // Step 4) 3 is odd; subtract 1 and obtain 2. 14 | // Step 5) 2 is even; divide by 2 and obtain 1. 15 | // Step 6) 1 is odd; subtract 1 and obtain 0. 16 | 17 | // Example 2: 18 | 19 | // Input: num = 8 20 | // Output: 4 21 | // Explanation: 22 | // Step 1) 8 is even; divide by 2 and obtain 4. 23 | // Step 2) 4 is even; divide by 2 and obtain 2. 24 | // Step 3) 2 is even; divide by 2 and obtain 1. 25 | // Step 4) 1 is odd; subtract 1 and obtain 0. 26 | 27 | // Example 3: 28 | 29 | // Input: num = 123 30 | // Output: 12 31 | 32 | 33 | 34 | // Constraints: 35 | 36 | // 0 <= num <= 10^6 37 | 38 | class Solution { 39 | public: 40 | int numberOfSteps (int num) { 41 | int i = 0; 42 | while(num != 0){ 43 | if(num%2 == 0){ 44 | num = num/2; 45 | } 46 | else{ 47 | num = num -1; 48 | } 49 | i+=1; 50 | } 51 | return i; 52 | } 53 | }; 54 | 55 | class Solution { 56 | public: 57 | int numberOfSteps (int num) { 58 | int res = 0; 59 | if(!num){ 60 | return 0; 61 | } 62 | while(num){ 63 | res += (num & 1) ? 2 : 1; 64 | num >>= 1; 65 | } 66 | return res-1; 67 | } 68 | }; 69 | -------------------------------------------------------------------------------- /LeetCode/python/1365.largenumbers.py: -------------------------------------------------------------------------------- 1 | # Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i]. 2 | 3 | # Return the answer in an array. 4 | 5 | 6 | 7 | # Example 1: 8 | 9 | # Input: nums = [8,1,2,2,3] 10 | # Output: [4,0,1,1,3] 11 | # Explanation: 12 | # For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). 13 | # For nums[1]=1 does not exist any smaller number than it. 14 | # For nums[2]=2 there exist one smaller number than it (1). 15 | # For nums[3]=2 there exist one smaller number than it (1). 16 | # For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2). 17 | 18 | # Example 2: 19 | 20 | # Input: nums = [6,5,4,8] 21 | # Output: [2,1,0,3] 22 | 23 | # Example 3: 24 | 25 | # Input: nums = [7,7,7,7] 26 | # Output: [0,0,0,0] 27 | 28 | 29 | 30 | # Constraints: 31 | 32 | # 2 <= nums.length <= 500 33 | # 0 <= nums[i] <= 100 34 | 35 | 36 | class Solution: 37 | def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: 38 | arr = [] 39 | for i in range(len(nums)): 40 | count = 0 41 | for j in range(len(nums)): 42 | if nums[i] > nums[j]: 43 | count+=1 44 | arr.append(count) 45 | return arr 46 | 47 | 48 | class Solution: 49 | def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: 50 | arr = [] 51 | nums1 = [] 52 | for i in range(len(nums)): 53 | nums1.append(nums[i]) 54 | nums1.sort() 55 | for i in range(len(nums)): 56 | arr.append(nums1.index(nums[i])) 57 | return arr 58 | 59 | 60 | -------------------------------------------------------------------------------- /LeetCode/python/997.judgetrust.py: -------------------------------------------------------------------------------- 1 | # In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge. 2 | 3 | # If the town judge exists, then: 4 | 5 | # The town judge trusts nobody. 6 | # Everybody (except for the town judge) trusts the town judge. 7 | # There is exactly one person that satisfies properties 1 and 2. 8 | 9 | # You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b. 10 | 11 | # If the town judge exists and can be identified, return the label of the town judge. Otherwise, return -1. 12 | 13 | 14 | 15 | # Example 1: 16 | 17 | # Input: N = 2, trust = [[1,2]] 18 | # Output: 2 19 | 20 | # Example 2: 21 | 22 | # Input: N = 3, trust = [[1,3],[2,3]] 23 | # Output: 3 24 | 25 | # Example 3: 26 | 27 | # Input: N = 3, trust = [[1,3],[2,3],[3,1]] 28 | # Output: -1 29 | 30 | # Example 4: 31 | 32 | # Input: N = 3, trust = [[1,2],[2,3]] 33 | # Output: -1 34 | 35 | # Example 5: 36 | 37 | # Input: N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]] 38 | # Output: 3 39 | 40 | 41 | 42 | # Constraints: 43 | 44 | # 1 <= N <= 1000 45 | # 0 <= trust.length <= 10^4 46 | # trust[i].length == 2 47 | # trust[i] are all different 48 | # trust[i][0] != trust[i][1] 49 | # 1 <= trust[i][0], trust[i][1] <= N 50 | 51 | ## finding in degree and out degree. judge will be the one with indegree N-1 52 | 53 | class Solution: 54 | def findJudge(self, N: int, trust: List[List[int]]) -> int: 55 | count = [0] * (N + 1) 56 | for i,j in trust: 57 | count[i] -= 1 58 | count[j] += 1 59 | for i in range(1,N+1): 60 | if count[i] == N-1: 61 | return i 62 | return -1 -------------------------------------------------------------------------------- /LeetCode/python/155.designminstack.py: -------------------------------------------------------------------------------- 1 | # Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. 2 | 3 | # push(x) -- Push element x onto stack. 4 | # pop() -- Removes the element on top of the stack. 5 | # top() -- Get the top element. 6 | # getMin() -- Retrieve the minimum element in the stack. 7 | 8 | 9 | 10 | # Example 1: 11 | 12 | # Input 13 | # ["MinStack","push","push","push","getMin","pop","top","getMin"] 14 | # [[],[-2],[0],[-3],[],[],[],[]] 15 | 16 | # Output 17 | # [null,null,null,null,-3,null,0,-2] 18 | 19 | # Explanation 20 | # MinStack minStack = new MinStack(); 21 | # minStack.push(-2); 22 | # minStack.push(0); 23 | # minStack.push(-3); 24 | # minStack.getMin(); // return -3 25 | # minStack.pop(); 26 | # minStack.top(); // return 0 27 | # minStack.getMin(); // return -2 28 | 29 | 30 | 31 | # Constraints: 32 | 33 | # Methods pop, top and getMin operations will always be called on non-empty stacks. 34 | 35 | class MinStack: 36 | # s = [] 37 | def __init__(self): 38 | """ 39 | initialize your data structure here. 40 | """ 41 | self.s = [] 42 | 43 | def push(self, x: int) -> None: 44 | self.s.append(x) 45 | return 46 | 47 | def pop(self) -> None: 48 | self.s.pop() 49 | 50 | def top(self) -> int: 51 | return self.s[len(self.s) - 1] 52 | 53 | def getMin(self) -> int: 54 | low = self.s[0] 55 | for i in range(len(self.s)): 56 | if low > self.s[i]: 57 | low = self.s[i] 58 | return low 59 | 60 | 61 | # Your MinStack object will be instantiated and called as such: 62 | # obj = MinStack() 63 | # obj.push(x) 64 | # obj.pop() 65 | # param_3 = obj.top() 66 | # param_4 = obj.getMin() -------------------------------------------------------------------------------- /LeetCode/cpp/1389.insertatindex.cpp: -------------------------------------------------------------------------------- 1 | // Given two arrays of integers nums and index. Your task is to create target array under the following rules: 2 | 3 | // Initially target array is empty. 4 | // From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array. 5 | // Repeat the previous step until there are no elements to read in nums and index. 6 | 7 | // Return the target array. 8 | 9 | // It is guaranteed that the insertion operations will be valid. 10 | 11 | 12 | 13 | // Example 1: 14 | 15 | // Input: nums = [0,1,2,3,4], index = [0,1,2,2,1] 16 | // Output: [0,4,1,3,2] 17 | // Explanation: 18 | // nums index target 19 | // 0 0 [0] 20 | // 1 1 [0,1] 21 | // 2 2 [0,1,2] 22 | // 3 2 [0,1,3,2] 23 | // 4 1 [0,4,1,3,2] 24 | 25 | // Example 2: 26 | 27 | // Input: nums = [1,2,3,4,0], index = [0,1,2,3,0] 28 | // Output: [0,1,2,3,4] 29 | // Explanation: 30 | // nums index target 31 | // 1 0 [1] 32 | // 2 1 [1,2] 33 | // 3 2 [1,2,3] 34 | // 4 3 [1,2,3,4] 35 | // 0 0 [0,1,2,3,4] 36 | 37 | // Example 3: 38 | 39 | // Input: nums = [1], index = [0] 40 | // Output: [1] 41 | 42 | 43 | 44 | // Constraints: 45 | 46 | // 1 <= nums.length, index.length <= 100 47 | // nums.length == index.length 48 | // 0 <= nums[i] <= 100 49 | // 0 <= index[i] <= i 50 | 51 | class Solution { 52 | public: 53 | vector createTargetArray(vector& nums, vector& index) { 54 | vector res; 55 | for(int i = 0;i int: 40 | length = 0 41 | if not nums: 42 | return 0 43 | for i in range(1, len(nums)): 44 | if (nums[length] < nums[i]): 45 | length+=1 46 | nums[length] = nums[i] 47 | return length + 1 -------------------------------------------------------------------------------- /LeetCode/python/1337.weakrow.py: -------------------------------------------------------------------------------- 1 | # Given a m * n matrix mat of ones (representing soldiers) and zeros (representing civilians), return the indexes of the k weakest rows in the matrix ordered from the weakest to the strongest. 2 | 3 | # A row i is weaker than row j, if the number of soldiers in row i is less than the number of soldiers in row j, or they have the same number of soldiers but i is less than j. Soldiers are always stand in the frontier of a row, that is, always ones may appear first and then zeros. 4 | 5 | 6 | 7 | # Example 1: 8 | 9 | # Input: mat = 10 | # [[1,1,0,0,0], 11 | # [1,1,1,1,0], 12 | # [1,0,0,0,0], 13 | # [1,1,0,0,0], 14 | # [1,1,1,1,1]], 15 | # k = 3 16 | # Output: [2,0,3] 17 | # Explanation: 18 | # The number of soldiers for each row is: 19 | # row 0 -> 2 20 | # row 1 -> 4 21 | # row 2 -> 1 22 | # row 3 -> 2 23 | # row 4 -> 5 24 | # Rows ordered from the weakest to the strongest are [2,0,3,1,4] 25 | 26 | # Example 2: 27 | 28 | # Input: mat = 29 | # [[1,0,0,0], 30 | # [1,1,1,1], 31 | # [1,0,0,0], 32 | # [1,0,0,0]], 33 | # k = 2 34 | # Output: [0,2] 35 | # Explanation: 36 | # The number of soldiers for each row is: 37 | # row 0 -> 1 38 | # row 1 -> 4 39 | # row 2 -> 1 40 | # row 3 -> 1 41 | # Rows ordered from the weakest to the strongest are [0,2,3,1] 42 | 43 | class Solution: 44 | def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]: 45 | res = {} 46 | m = len(mat[0]) 47 | n = len(mat) 48 | for i in range(n): 49 | temp = 0 50 | for j in range(m): 51 | temp += mat[i][j] 52 | res[i] = temp 53 | result = sorted(res.items(),key = lambda x : x[1]) 54 | newres = [] 55 | for i in range(k): 56 | newres.append(result[i][0]) 57 | return(newres) -------------------------------------------------------------------------------- /LeetCode/python/18.4sum.py: -------------------------------------------------------------------------------- 1 | # Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. 2 | 3 | # Note: 4 | 5 | # The solution set must not contain duplicate quadruplets. 6 | 7 | # Example: 8 | 9 | # Given array nums = [1, 0, -1, 0, -2, 2], and target = 0. 10 | 11 | # A solution set is: 12 | # [ 13 | # [-1, 0, 0, 1], 14 | # [-2, -1, 1, 2], 15 | # [-2, 0, 0, 2] 16 | # ] 17 | 18 | 19 | class Solution: 20 | def fourSum(self, nums: List[int], target: int) -> List[List[int]]: 21 | res = [] 22 | if not nums or len(nums)<4: 23 | return [] 24 | nums.sort() 25 | i=0 26 | while ( i List[int]: 44 | minrow = {min(r) for r in matrix} 45 | maxcol = {max(c) for c in zip(*matrix)} # it is like iterating through column values 46 | return list(minrow & maxcol) 47 | 48 | class Solution: 49 | def luckyNumbers (self, matrix: List[List[int]]) -> List[int]: 50 | row,col = [],[] 51 | for i in matrix: 52 | row.append(min(i)) 53 | for i in range(len(matrix[0])): 54 | temp = matrix[0][i] 55 | for j in range(len(matrix)): 56 | temp = max(temp,matrix[j][i]) 57 | col.append(temp) 58 | res = [] 59 | for i in row: 60 | if i in col: 61 | res.append(i) 62 | return res 63 | -------------------------------------------------------------------------------- /LeetCode/python/27.remelement.py: -------------------------------------------------------------------------------- 1 | # Given an array nums and a value val, remove all instances of that value in-place and return the new length. 2 | 3 | # Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 4 | 5 | # The order of elements can be changed. It doesn't matter what you leave beyond the new length. 6 | 7 | # Example 1: 8 | 9 | # Given nums = [3,2,2,3], val = 3, 10 | 11 | # Your function should return length = 2, with the first two elements of nums being 2. 12 | 13 | # It doesn't matter what you leave beyond the returned length. 14 | 15 | # Example 2: 16 | 17 | # Given nums = [0,1,2,2,3,0,4,2], val = 2, 18 | 19 | # Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. 20 | 21 | # Note that the order of those five elements can be arbitrary. 22 | 23 | # It doesn't matter what values are set beyond the returned length. 24 | 25 | # Clarification: 26 | 27 | # Confused why the returned value is an integer but your answer is an array? 28 | 29 | # Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well. 30 | 31 | # Internally you can think of this: 32 | 33 | # // nums is passed in by reference. (i.e., without making a copy) 34 | # int len = removeElement(nums, val); 35 | 36 | # // any modification to nums in your function would be known by the caller. 37 | # // using the length returned by your function, it prints the first len elements. 38 | # for (int i = 0; i < len; i++) { 39 | # print(nums[i]); 40 | # } 41 | 42 | class Solution: 43 | def removeElement(self, nums: List[int], val: int) -> int: 44 | i = 0 45 | while( i < len(nums)): 46 | if nums[i] == val: 47 | del(nums[i]) 48 | else: 49 | i+=1 50 | return(len(nums)) -------------------------------------------------------------------------------- /HackerRank/Python/Easy/nestedlist.py: -------------------------------------------------------------------------------- 1 | Given the names and grades for each student in a Physics class of 2 | 3 | students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade. 4 | 5 | Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line. 6 | 7 | Input Format 8 | 9 | The first line contains an integer, 10 | , the number of students. 11 | The subsequent lines describe each student over 12 | 13 | lines; the first line contains a student's name, and the second line contains their grade. 14 | 15 | Constraints 16 | 17 | There will always be one or more students having the second lowest grade. 18 | 19 | Output Format 20 | 21 | Print the name(s) of any student(s) having the second lowest grade in Physics; if there are multiple students, order their names alphabetically and print each one on a new line. 22 | 23 | Sample Input 0 24 | 25 | 5 26 | Harry 27 | 37.21 28 | Berry 29 | 37.21 30 | Tina 31 | 37.2 32 | Akriti 33 | 41 34 | Harsh 35 | 39 36 | 37 | Sample Output 0 38 | 39 | Berry 40 | Harry 41 | 42 | Explanation 0 43 | 44 | There are 45 | 46 | students in this class whose names and grades are assembled to build the following list: 47 | 48 | python students = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]] 49 | 50 | The lowest grade of 51 | belongs to Tina. The second lowest grade of belongs to both Harry and Berry, so we order their names alphabetically and print each name on a new line. 52 | 53 | 54 | if __name__ == '__main__': 55 | names = [] 56 | scores = [] 57 | for _ in range(int(input())): 58 | name = input() 59 | score = float(input()) 60 | 61 | names.append([name,score]) 62 | scores.append(score) 63 | 64 | sec_low = sorted(set(scores))[1] 65 | names.sort() 66 | for i in range(len(names)): 67 | if names[i][1] == sec_low: 68 | print(names[i][0]) 69 | -------------------------------------------------------------------------------- /LeetCode/python/804.uniquemorsecode.py: -------------------------------------------------------------------------------- 1 | # International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on. 2 | 3 | # For convenience, the full table for the 26 letters of the English alphabet is given below: 4 | 5 | # [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] 6 | 7 | # Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter. For example, "cab" can be written as "-.-..--...", (which is the concatenation "-.-." + ".-" + "-..."). We'll call such a concatenation, the transformation of a word. 8 | 9 | # Return the number of different transformations among all words we have. 10 | 11 | # Example: 12 | # Input: words = ["gin", "zen", "gig", "msg"] 13 | # Output: 2 14 | # Explanation: 15 | # The transformation of each word is: 16 | # "gin" -> "--...-." 17 | # "zen" -> "--...-." 18 | # "gig" -> "--...--." 19 | # "msg" -> "--...--." 20 | 21 | # There are 2 different transformations, "--...-." and "--...--.". 22 | 23 | # Note: 24 | 25 | # The length of words will be at most 100. 26 | # Each words[i] will have length in range [1, 12]. 27 | # words[i] will only consist of lowercase letters. 28 | 29 | 30 | class Solution: 31 | def uniqueMorseRepresentations(self, words: List[str]) -> int: 32 | morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] 33 | arr = [] 34 | count = 0 35 | for i in words: 36 | temp = [] 37 | for j in i: 38 | temp.append(morse[ord(j)-97]) 39 | s = ''.join(temp) 40 | if s not in arr: 41 | arr.append(s) 42 | count += 1 43 | return count -------------------------------------------------------------------------------- /LeetCode/cpp/1252.cellswithoddval.cpp: -------------------------------------------------------------------------------- 1 | // Given n and m which are the dimensions of a matrix initialized by zeros and given an array indices where indices[i] = [ri, ci]. For each pair of [ri, ci] you have to increment all cells in row ri and column ci by 1. 2 | 3 | // Return the number of cells with odd values in the matrix after applying the increment to all indices. 4 | 5 | 6 | 7 | // Example 1: 8 | 9 | // Input: n = 2, m = 3, indices = [[0,1],[1,1]] 10 | // Output: 6 11 | // Explanation: Initial matrix = [[0,0,0],[0,0,0]]. 12 | // After applying first increment it becomes [[1,2,1],[0,1,0]]. 13 | // The final matrix will be [[1,3,1],[1,3,1]] which contains 6 odd numbers. 14 | 15 | // Example 2: 16 | 17 | // Input: n = 2, m = 2, indices = [[1,1],[0,0]] 18 | // Output: 0 19 | // Explanation: Final matrix = [[2,2],[2,2]]. There is no odd number in the final matrix. 20 | 21 | 22 | 23 | // Constraints: 24 | 25 | // 1 <= n <= 50 26 | // 1 <= m <= 50 27 | // 1 <= indices.length <= 100 28 | // 0 <= indices[i][0] < n 29 | // 0 <= indices[i][1] < m 30 | 31 | 32 | class Solution { 33 | public: 34 | int arr[100][100]; 35 | void incrow(int r, int m){ 36 | for(int i =0;i>& indices) { 46 | int i,j; 47 | int fin = 0; 48 | for (i = 0; i< n; i++){ 49 | for(j =0; j i and prices[j] <= prices[i], otherwise, you will not receive any discount at all. 2 | 3 | # Return an array where the ith element is the final price you will pay for the ith item of the shop considering the special discount. 4 | 5 | 6 | 7 | # Example 1: 8 | 9 | # Input: prices = [8,4,6,2,3] 10 | # Output: [4,2,4,2,3] 11 | # Explanation: 12 | # For item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4. 13 | # For item 1 with price[1]=4 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 4 - 2 = 2. 14 | # For item 2 with price[2]=6 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 6 - 2 = 4. 15 | # For items 3 and 4 you will not receive any discount at all. 16 | 17 | # Example 2: 18 | 19 | # Input: prices = [1,2,3,4,5] 20 | # Output: [1,2,3,4,5] 21 | # Explanation: In this case, for all items, you will not receive any discount at all. 22 | 23 | # Example 3: 24 | 25 | # Input: prices = [10,1,1,6] 26 | # Output: [9,0,1,6] 27 | 28 | 29 | class Solution: 30 | def finalPrices(self, prices: List[int]) -> List[int]: 31 | res = [] 32 | def findprice(high,arr) -> int: 33 | m = 2**31 - 1 34 | for i in arr: 35 | if i < m and i <= high: 36 | m = i 37 | break 38 | if m == 2**31 - 1: 39 | return 0 40 | return m 41 | 42 | for i in range(len(prices)): 43 | finalprice = findprice(prices[i],prices[i+1:]) 44 | prices[i] -= finalprice 45 | return prices 46 | 47 | -------------------------------------------------------------------------------- /LeetCode/python/1450.studentsdoingwork.py: -------------------------------------------------------------------------------- 1 | # Given two integer arrays startTime and endTime and given an integer queryTime. 2 | 3 | # The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i]. 4 | 5 | # Return the number of students doing their homework at time queryTime. More formally, return the number of students where queryTime lays in the interval [startTime[i], endTime[i]] inclusive. 6 | 7 | 8 | 9 | # Example 1: 10 | 11 | # Input: startTime = [1,2,3], endTime = [3,2,7], queryTime = 4 12 | # Output: 1 13 | # Explanation: We have 3 students where: 14 | # The first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4. 15 | # The second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4. 16 | # The third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4. 17 | 18 | # Example 2: 19 | 20 | # Input: startTime = [4], endTime = [4], queryTime = 4 21 | # Output: 1 22 | # Explanation: The only student was doing their homework at the queryTime. 23 | 24 | # Example 3: 25 | 26 | # Input: startTime = [4], endTime = [4], queryTime = 5 27 | # Output: 0 28 | 29 | # Example 4: 30 | 31 | # Input: startTime = [1,1,1,1], endTime = [1,3,2,4], queryTime = 7 32 | # Output: 0 33 | 34 | # Example 5: 35 | 36 | # Input: startTime = [9,8,7,6,5,4,3,2,1], endTime = [10,10,10,10,10,10,10,10,10], queryTime = 5 37 | # Output: 5 38 | 39 | 40 | 41 | # Constraints: 42 | 43 | # startTime.length == endTime.length 44 | # 1 <= startTime.length <= 100 45 | # 1 <= startTime[i] <= endTime[i] <= 1000 46 | # 1 <= queryTime <= 1000 47 | 48 | class Solution: 49 | def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int: 50 | res = 0 51 | for i in range(len(startTime)): 52 | if queryTime >= startTime[i] and queryTime <= endTime[i]: 53 | res += 1 54 | return res -------------------------------------------------------------------------------- /LeetCode/python/12.inttoroman.py: -------------------------------------------------------------------------------- 1 | # Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. 2 | 3 | # Symbol Value 4 | # I 1 5 | # V 5 6 | # X 10 7 | # L 50 8 | # C 100 9 | # D 500 10 | # M 1000 11 | 12 | # For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II. 13 | 14 | # Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used: 15 | 16 | # I can be placed before V (5) and X (10) to make 4 and 9. 17 | # X can be placed before L (50) and C (100) to make 40 and 90. 18 | # C can be placed before D (500) and M (1000) to make 400 and 900. 19 | 20 | # Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. 21 | 22 | # Example 1: 23 | 24 | # Input: 3 25 | # Output: "III" 26 | 27 | # Example 2: 28 | 29 | # Input: 4 30 | # Output: "IV" 31 | 32 | # Example 3: 33 | 34 | # Input: 9 35 | # Output: "IX" 36 | 37 | # Example 4: 38 | 39 | # Input: 58 40 | # Output: "LVIII" 41 | # Explanation: L = 50, V = 5, III = 3. 42 | 43 | # Example 5: 44 | 45 | # Input: 1994 46 | # Output: "MCMXCIV" 47 | # Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. 48 | 49 | 50 | class Solution: 51 | def intToRoman(self, num: int) -> str: 52 | s = ['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I'] 53 | n = [1000,900,500,400,100,90,50,40,10,9,5,4,1] 54 | res = '' 55 | i=0 56 | while(num > 0 ): 57 | if num >= n[i]: 58 | res += s[i] 59 | num -= n[i] 60 | else: 61 | i+=1 62 | return res -------------------------------------------------------------------------------- /LeetCode/cpp/804.uniquemorsecode.cpp: -------------------------------------------------------------------------------- 1 | // International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on. 2 | 3 | // For convenience, the full table for the 26 letters of the English alphabet is given below: 4 | 5 | // [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] 6 | 7 | // Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter. For example, "cab" can be written as "-.-..--...", (which is the concatenation "-.-." + ".-" + "-..."). We'll call such a concatenation, the transformation of a word. 8 | 9 | // Return the number of different transformations among all words we have. 10 | 11 | // Example: 12 | // Input: words = ["gin", "zen", "gig", "msg"] 13 | // Output: 2 14 | // Explanation: 15 | // The transformation of each word is: 16 | // "gin" -> "--...-." 17 | // "zen" -> "--...-." 18 | // "gig" -> "--...--." 19 | // "msg" -> "--...--." 20 | 21 | // There are 2 different transformations, "--...-." and "--...--.". 22 | 23 | // Note: 24 | 25 | // The length of words will be at most 100. 26 | // Each words[i] will have length in range [1, 12]. 27 | // words[i] will only consist of lowercase letters. 28 | 29 | class Solution { 30 | public: 31 | int uniqueMorseRepresentations(vector& words) { 32 | vector sign = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}; 33 | string temp,temp1; 34 | set res; 35 | int i,j; 36 | for (i=0 ; i kidsWithCandies(vector& candies, int extraCandies) { 32 | vector res; 33 | int max = *max_element(candies.begin(),candies.end()); 34 | for(auto i:candies){ 35 | if(i+extraCandies>=max){ 36 | res.push_back(true); 37 | cout< int: 53 | d = {'I':1,'IV':4,'V':5,'IX':9,'X':10,'XL':40,'L':50,'LC':90,'C':100,'CD':400,'D':500,'DM':900,'M':1000} 54 | temp = 0 55 | ret = 0 56 | for c in reversed(s): 57 | if temp <= d[c]: 58 | ret+=d[c] 59 | temp = d[c] 60 | else: 61 | ret-=d[c] 62 | return(ret) 63 | -------------------------------------------------------------------------------- /LeetCode/cpp/1365.prefixsum.cpp: -------------------------------------------------------------------------------- 1 | // Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i]. 2 | 3 | // Return the answer in an array. 4 | 5 | 6 | 7 | // Example 1: 8 | 9 | // Input: nums = [8,1,2,2,3] 10 | // Output: [4,0,1,1,3] 11 | // Explanation: 12 | // For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). 13 | // For nums[1]=1 does not exist any smaller number than it. 14 | // For nums[2]=2 there exist one smaller number than it (1). 15 | // For nums[3]=2 there exist one smaller number than it (1). 16 | // For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2). 17 | 18 | // Example 2: 19 | 20 | // Input: nums = [6,5,4,8] 21 | // Output: [2,1,0,3] 22 | 23 | // Example 3: 24 | 25 | // Input: nums = [7,7,7,7] 26 | // Output: [0,0,0,0] 27 | 28 | 29 | 30 | // Constraints: 31 | 32 | // 2 <= nums.length <= 500 33 | // 0 <= nums[i] <= 100 34 | 35 | class Solution { 36 | public: 37 | vector smallerNumbersThanCurrent(vector& nums) { 38 | vector res; 39 | int temp = 0; 40 | for (int i = 0;i smallerNumbersThanCurrent(vector& nums) { 56 | vector res; 57 | int prefix[101] = {0}; 58 | int n,sum = 0; 59 | for(auto i:nums){ 60 | prefix[i]++; 61 | } 62 | int i; 63 | for(i = 0;i < 101 ;i++){ 64 | n = prefix[i]; 65 | prefix[i] = sum; 66 | sum += n; 67 | } 68 | for(i = 0;i 1 4 | 'B' -> 2 5 | ... 6 | 'Z' -> 26 7 | 8 | You are an FBI agent. You have to determine the total number of ways that message can be decoded. 9 | Note: An empty digit sequence is considered to have one decoding. It may be assumed that the input contains valid digits from 0 to 9 and If there are leading 0’s, extra trailing 0’s and two or more consecutive 0’s then it is an invalid string. 10 | 11 | Example : 12 | Given encoded message "123", it could be decoded as "ABC" (1 2 3) or "LC" (12 3) or "AW"(1 23). 13 | So total ways are 3. 14 | 15 | Input: 16 | First line contains the test cases T. 1<=T<=1000 17 | Each test case have two lines 18 | First is length of string N. 1<=N<=40 19 | Second line is string S of digits from '0' to '9' of N length. 20 | 21 | Example: 22 | Input: 23 | 2 24 | 3 25 | 123 26 | 4 27 | 2563 28 | Output: 29 | 3 30 | 2 31 | 32 | #code 33 | 34 | def helper(data,k,mem): 35 | 36 | 37 | s = len(data) - k 38 | 39 | if k == 0: 40 | return(1) 41 | 42 | if data[s] == 0: 43 | return(0) 44 | 45 | if (mem[k] != None): 46 | return(mem[k]) 47 | 48 | result = helper(data,k-1,mem) 49 | 50 | 51 | if (k >= 2 and int(data[s:s+2]) <=26 ): 52 | result += helper(data,k-2,mem) 53 | 54 | mem[k] = result 55 | print (result ,k) 56 | return result 57 | 58 | 59 | def num_ways(data,k): 60 | mem = [None]*(k+1) 61 | count = helper(data,k,mem) 62 | return count 63 | 64 | 65 | 66 | tcase = int(input()) 67 | 68 | for i in range(tcase): 69 | 70 | size = int(input()) 71 | data = input() 72 | 73 | count = 0 74 | count = num_ways(data,len(data)) 75 | 76 | for j in range(data.count('0')): 77 | n= data.index('0') 78 | if int(data[n-1]) >= 3: 79 | count = 0 80 | break 81 | data = data[n+1:] 82 | # print(data) 83 | print(count) 84 | 85 | -------------------------------------------------------------------------------- /HackerRank/CPP/newyearchaos.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | vector split_string(string); 6 | 7 | // Complete the minimumBribes function below. 8 | void minimumBribes(vector q) { 9 | int ans = 0; 10 | for (int i = q.size() - 1; i >= 0; i--) { 11 | if (q[i] - (i + 1) > 2) { 12 | cout << "Too chaotic" << endl; 13 | return; 14 | } 15 | for (int j = max(0, q[i] - 2); j < i; j++) 16 | if (q[j] > q[i]) ans++; 17 | } 18 | cout << ans << endl; 19 | } 20 | 21 | int main() 22 | { 23 | int t; 24 | cin >> t; 25 | cin.ignore(numeric_limits::max(), '\n'); 26 | 27 | for (int t_itr = 0; t_itr < t; t_itr++) { 28 | int n; 29 | cin >> n; 30 | cin.ignore(numeric_limits::max(), '\n'); 31 | 32 | string q_temp_temp; 33 | getline(cin, q_temp_temp); 34 | 35 | vector q_temp = split_string(q_temp_temp); 36 | 37 | vector q(n); 38 | 39 | for (int i = 0; i < n; i++) { 40 | int q_item = stoi(q_temp[i]); 41 | 42 | q[i] = q_item; 43 | } 44 | 45 | minimumBribes(q); 46 | } 47 | 48 | return 0; 49 | } 50 | 51 | vector split_string(string input_string) { 52 | string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { 53 | return x == y and x == ' '; 54 | }); 55 | 56 | input_string.erase(new_end, input_string.end()); 57 | 58 | while (input_string[input_string.length() - 1] == ' ') { 59 | input_string.pop_back(); 60 | } 61 | 62 | vector splits; 63 | char delimiter = ' '; 64 | 65 | size_t i = 0; 66 | size_t pos = input_string.find(delimiter); 67 | 68 | while (pos != string::npos) { 69 | splits.push_back(input_string.substr(i, pos - i)); 70 | 71 | i = pos + 1; 72 | pos = input_string.find(delimiter, i); 73 | } 74 | 75 | splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); 76 | 77 | return splits; 78 | } 79 | 80 | -------------------------------------------------------------------------------- /LeetCode/python/1431.kids&candies.py: -------------------------------------------------------------------------------- 1 | # Given the array candies and the integer extraCandies, where candies[i] represents the number of candies that the ith kid has. 2 | 3 | # For each kid check if there is a way to distribute extraCandies among the kids such that he or she can have the greatest number of candies among them. Notice that multiple kids can have the greatest number of candies. 4 | 5 | 6 | 7 | # Example 1: 8 | 9 | # Input: candies = [2,3,5,1,3], extraCandies = 3 10 | # Output: [true,true,true,false,true] 11 | # Explanation: 12 | # Kid 1 has 2 candies and if he or she receives all extra candies (3) will have 5 candies --- the greatest number of candies among the kids. 13 | # Kid 2 has 3 candies and if he or she receives at least 2 extra candies will have the greatest number of candies among the kids. 14 | # Kid 3 has 5 candies and this is already the greatest number of candies among the kids. 15 | # Kid 4 has 1 candy and even if he or she receives all extra candies will only have 4 candies. 16 | # Kid 5 has 3 candies and if he or she receives at least 2 extra candies will have the greatest number of candies among the kids. 17 | 18 | # Example 2: 19 | 20 | # Input: candies = [4,2,1,1,2], extraCandies = 1 21 | # Output: [true,false,false,false,false] 22 | # Explanation: There is only 1 extra candy, therefore only kid 1 will have the greatest number of candies among the kids regardless of who takes the extra candy. 23 | 24 | # Example 3: 25 | 26 | # Input: candies = [12,1,12], extraCandies = 10 27 | # Output: [true,false,true] 28 | 29 | 30 | 31 | # Constraints: 32 | 33 | # 2 <= candies.length <= 100 34 | # 1 <= candies[i] <= 100 35 | # 1 <= extraCandies <= 50 36 | 37 | 38 | class Solution: 39 | def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]: 40 | maxi = 0 41 | arr = [] 42 | for i in range(len(candies)): 43 | if candies[i] > maxi: 44 | maxi = candies[i] 45 | for i in range(len(candies)): 46 | if candies[i] + extraCandies >= maxi: 47 | arr.append(True) 48 | else: 49 | arr.append(False) 50 | return arr -------------------------------------------------------------------------------- /LeetCode/python/1021.remoutparenthesis.py: -------------------------------------------------------------------------------- 1 | # A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation. For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings. 2 | 3 | # A valid parentheses string S is primitive if it is nonempty, and there does not exist a way to split it into S = A+B, with A and B nonempty valid parentheses strings. 4 | 5 | # Given a valid parentheses string S, consider its primitive decomposition: S = P_1 + P_2 + ... + P_k, where P_i are primitive valid parentheses strings. 6 | 7 | # Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S. 8 | 9 | 10 | 11 | # Example 1: 12 | 13 | # Input: "(()())(())" 14 | # Output: "()()()" 15 | # Explanation: 16 | # The input string is "(()())(())", with primitive decomposition "(()())" + "(())". 17 | # After removing outer parentheses of each part, this is "()()" + "()" = "()()()". 18 | 19 | # Example 2: 20 | 21 | # Input: "(()())(())(()(()))" 22 | # Output: "()()()()(())" 23 | # Explanation: 24 | # The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))". 25 | # After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())". 26 | 27 | # Example 3: 28 | 29 | # Input: "()()" 30 | # Output: "" 31 | # Explanation: 32 | # The input string is "()()", with primitive decomposition "()" + "()". 33 | # After removing outer parentheses of each part, this is "" + "" = "". 34 | 35 | 36 | 37 | # Note: 38 | 39 | # S.length <= 10000 40 | # S[i] is "(" or ")" 41 | # S is a valid parentheses string 42 | 43 | class Solution: 44 | def removeOuterParentheses(self, S: str) -> str: 45 | index = 0 46 | res = [] 47 | j = 0 48 | balance = 0 49 | while(index < len(S) and j < len(S)): 50 | if S[j] == '(': 51 | balance += 1 52 | if S[j] == ')': 53 | balance -= 1 54 | if balance == 0: 55 | res.append(S[index + 1:j]) 56 | index = j+1 57 | j+=1 58 | return("".join(res)) --------------------------------------------------------------------------------