├── C++ ├── 977. SquaresOfASortedArray.cpp ├── 50. Pow-function.cpp ├── 540. SingleElementInASortedArray.cpp ├── 1431. KidsWithTheGreatesNumberOfCandies.cpp ├── 1051. HeightChecker.cpp ├── 905.SortArrayByParity.cpp ├── 75.SortColors.cpp ├── 477. TotalHammingDistance.cpp ├── 319. BulbSwitcher.cpp ├── 7. Reverse_Integer.cpp ├── 121. BestTimetoBuyandSellStock.cpp ├── 1310. XORQueriesOfASubarray.cpp ├── 13. Roman_To_Integer.cpp ├── 1. TwoSum.cpp ├── 124. Binary_Tree_Maximum.cpp ├── 32. LongestValidParenthesis.cpp ├── 414.PartitionEqualSubsetSum.cpp ├── 701. InsertIntoABinarySearchTree.cpp ├── 9. Palindrome Number.cpp ├── 134. GasStation.cpp ├── 42. TrappingRainWater.cpp ├── 532. K-diffPairsInAnArray.cpp ├── 941. ValidMountainArray.cpp ├── 1557.MinimumNumberOfVerticesToReachAllNodes.cpp ├── 151.ReverseWordsInAString.cpp ├── 38. CountAndSay.cpp ├── 72. Edit_Distance.cpp ├── 5. LongestPalindromicSubstring.cpp ├── 4. MedianOfTwoSortedArrays.cpp ├── 198. HouseRobber.cpp ├── 48. RotateImage.cpp ├── 704. BinarySearch.cpp ├── 1304. FindNUniqueIntegersSumUpToZero.cpp ├── 89. GrayCode.cpp ├── 11. ContainerWithMostWater.cpp ├── 67. AddBinary.cpp ├── 23. Merge_k_Sorted_Lists.cpp ├── 152. MaximumProductSubarray.cpp ├── 61. RotateList.cpp ├── 87. ScrambleString.cpp ├── 1288. RemoveCoveredIntervals.cpp ├── 202. HappyNumber.cpp ├── 547. FriendCircles.cpp ├── 78. SubsetsOfAGivenArray.cpp ├── 232. Implement Queue Using Stacks.cpp ├── 733. FloodFill.cpp ├── 41. FirstMissingPositive.cpp ├── 771. JewelsandStones.cpp ├── 1029. TwoCityScheduling.cpp ├── 780. ReachingPoints.cpp ├── 142. LinkedListCycle.cpp ├── 322. CoinChange.cpp ├── 1108. DefangingAnIPAddress.cpp ├── 992. Subarrays with K Different Integers.cpp ├── 54. SpiralMatrix.cpp ├── 326. PowerOfThree.cpp ├── 36. ValidSudoku.cpp ├── 128. LongestConsecutiveSequence.cpp ├── 199. BinaryTreeRightSideView.cpp ├── 49. Group_Anagrams.cpp ├── 543. DiameterOfBinaryTree.cpp ├── 1022. SumofRootToLeafBinaryNumbers.cpp ├── 101. SymmetricTree.cpp ├── 203. RemoveLinkedListElements.cpp ├── 225. Implement Stack Using Queues.cpp ├── 845. LongestMountainInArray.cpp ├── 665. Non-decreasingArray.cpp ├── 297. SerializeAndDeserializeBinaryTree.cpp ├── 189. Rotated_Array.cpp ├── 139. WordBreak.cpp ├── 3. LongestSubstringWithoutRepeatingCharacters.cpp ├── 25. Reverse Nodes in k-group.cpp ├── 127. Word Ladder.cpp └── 730. CountDifferentPalindromicSubsequences.cpp ├── SQL ├── 181. EmployeesEarningMoreThanTheirManagers.sql └── 626. ExchangeSeats.sql ├── Python ├── 122.BestTimeToBuyAndSellStock-II.py ├── 263.UglyNumbers.py ├── 1189. MaximumNumberOfBalloons.py ├── 1.TwoSum.py ├── 905.SortArrayByParity.py ├── 448.FindAllNumbersDisappearedinanArray.py ├── 287. FindTheDuplicateNumber.py ├── 338. CountingBits.py ├── 504. Base7.py ├── 941. ValidMountainArray.py ├── 205.IsomorphicStrings.py ├── 1588. SumofAllOddLengthSubarrays.py ├── 500.KeyboardRow.py ├── 387.FirstUniqueCharInString.py ├── 559. MaximumDepthOfN-aryTree.py ├── 766. ToeplitzMatrix.py ├── 9.Palindrome Number.py ├── 767. ReorganizeString.py ├── 3. LongestSubstringWithoutRepeatingCharacters.py ├── 344. ReverseString.py ├── 136.SingleNumber.py ├── 441. ArrangingCoins.py ├── 7.ReverseInteger.py ├── 771. Jewels and Stone.py ├── 172. FactorialTrailingZeroes.py ├── 977.SquaresOfASortedArray.py ├── 217.ContainsDuplicate.py ├── 169.MajorityNumber.py ├── 1232.CheckIfItIsAStraightLine.py ├── 215.KthLargestElementInAnArray.py ├── 1356.SortIntegersByNumberof1Bits.py ├── 728. SelfDividingNumbers.py ├── 137. SingleNumberII.py ├── 5.LongestPalindromicSubstring.py ├── 485. MaxConsecutiveOnes.py ├── 367.ValidPerfectSquare.py ├── 162.FindPeakElement.py ├── 225.ImplementStackUsingQueues.py ├── 8.PalindromeChecker.py ├── 461.HammingDistance.py ├── 118.PascalsTriangle.py ├── 704. BinarySearch.py ├── 88.MergeSortedArray.py ├── 1289.MatrixSpiral.py ├── 44. WildcardMatching.py ├── 42.TrappingRainWater.py └── 2. AddTwoNumbers.py ├── Java ├── 26. RemoveDuplicatesfromSortedArray.java ├── 1480.RunningSumof1DArray.java ├── 485. Max_Consecutive_ones.java ├── 50. Pow(x, n).java ├── 1089. DuplicateZeros.java ├── 1051.HeightChecker.java ├── 1295. Find_Number_with_even.java ├── 387.First Unique Character in a String.java ├── 1299.ReplaceElementswithGreatestElementonRightSide.java ├── 198. HouseRobber.java ├── 421.MaximumXORofTwoNumbersInAnArray.java ├── 62. UniquePath.java ├── 1346. CheckIfNandItsDoubleExist.java ├── 1.Two Sum.java ├── 88. MergeSortedArrays.java ├── 22. generatePara.java ├── 1041.RobotBoundedInCircle.java ├── 4.MedianOfTwoSortedArrays.java ├── 27. RemoveElement.java ├── 41. First Missing Positive.java ├── 142_linkedlist_cycle_2.java ├── 215.KthElementInAnArray.java ├── 414.ThirdMaximumNumber.java ├── 42. TrappingRainWater.java ├── 1510.StoneGameIV.java ├── 2.Add Two Numbers.java ├── 224.BasicCalculator.java ├── 5.LongestPalindromicSubstring.java ├── 516. Longest Palindromic Subsequence.java ├── 941. ValidMountainArray.java ├── 477. Total Hamming Distance.java ├── 124.BinaryTreeMaxSumPath.java ├── 1395. Count number of teams.java ├── 23. MergeKSortedLists.java ├── 229. MajorityElementII.java ├── 454.4SumII.java ├── 647. Palindromic Substrings.java ├── 35.SearchInsertPosition.java ├── 14. longestCommonPrefix.java ├── 13.RomanToInteger.java ├── 1315. Sum of Nodes with Even-Valued Grandparent.java └── 12.IntegerToRoman.java ├── .github ├── pull_request_template.md └── ISSUE_TEMPLATE │ └── create-an-issue.md ├── LICENSE ├── CONTRIBUTING.md └── README.md /C++/977. SquaresOfASortedArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | class Solution { 3 | public: 4 | vector sortedSquares(vector& A) { 5 | int len=A.size(); 6 | vector B; 7 | for(int i=0;ib.Salary; /* Condition for record selection from joined table */ 5 | -------------------------------------------------------------------------------- /C++/50. Pow-function.cpp: -------------------------------------------------------------------------------- 1 | /*To implement pow(x, n), which calculates x raised to the power n (i.e. xn). 2 | 3 | 4 | For Example: 5 | 6 | Input: x = 2.00000, n = 10 7 | Output: 1024.00000*/ 8 | 9 | class Solution { 10 | public: 11 | 12 | double myPow(double x, int n) 13 | { 14 | double c=n; 15 | return pow(x,c); // using pow function to get x^n 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Python/122.BestTimeToBuyAndSellStock-II.py: -------------------------------------------------------------------------------- 1 | # 122. Best Time To Buy And Sell Stock II 2 | # Language- Python 3.8.5 64-bit 3 | # Author- @PrithirajN 4 | 5 | #Dynamic Programming Approach 6 | 7 | class Sol(object): 8 | def maxProfit(self, prices): 9 | profit = 0 10 | for i in range(len(prices) - 1): 11 | profit += max(0, prices[i + 1] - prices[i]) 12 | return profit -------------------------------------------------------------------------------- /C++/540. SingleElementInASortedArray.cpp: -------------------------------------------------------------------------------- 1 | // The idea is that by, cumulatively, XORing all elements in an array, the result is the single element in the array. 2 | 3 | #include 4 | using namespace std; 5 | 6 | class Solution{ 7 | public: 8 | int singleNonDuplicate(vector & nums){ 9 | int answer = 0; 10 | for(auto e : nums) answer ^= e; 11 | return answer; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Python/263.UglyNumbers.py: -------------------------------------------------------------------------------- 1 | # Having one number num isUgly checks if the only prime divisors of num are 2, 3 and 5. 2 | class Solution(object): 3 | def isUgly(self, num): 4 | if num == 0: 5 | return False 6 | while num % 2 == 0: 7 | num /= 2 8 | while num % 3 == 0: 9 | num /= 3 10 | while num % 5 == 0: 11 | num /= 5 12 | return num == 1 13 | -------------------------------------------------------------------------------- /Java/26. RemoveDuplicatesfromSortedArray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int removeDuplicates(int[] nums) { 3 | int len=nums.length; 4 | int k=0; 5 | 6 | for(int i=1;i List[int]: 7 | hashes = dict() 8 | for i, num in enumerate(nums): 9 | index = target - num 10 | if index not in hashes: 11 | hashes[num] = i 12 | else: 13 | return [hashes[index], i] -------------------------------------------------------------------------------- /Python/905.SortArrayByParity.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortArrayByParity(self, A: List[int]) -> List[int]: 3 | even=0 4 | odd=len(A)-1 5 | 6 | while even 0; i /=2) { 15 | if( (i % 2 == 1) ){ 16 | answer = answer * product; 17 | } 18 | product *= product; 19 | } 20 | 21 | return answer; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Python/448.FindAllNumbersDisappearedinanArray.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findDisappearedNumbers(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[int] 6 | """ 7 | ans=list() 8 | for i in range(0,len(nums)): 9 | tmp=abs(nums[i])-1 10 | if nums[tmp]>=0: 11 | nums[tmp]=-nums[tmp] 12 | for i in range(0,len(nums)): 13 | if nums[i]-1>=0: 14 | ans.append(i+1) 15 | return ans 16 | 17 | -------------------------------------------------------------------------------- /Java/1089. DuplicateZeros.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | void dupli(int arr[], int index, int len){ 4 | for(int i=len-1; i>index;i--){ 5 | arr[i]=arr[i-1]; 6 | } 7 | arr[index]=0; 8 | } 9 | 10 | public void duplicateZeros(int[] arr) { 11 | 12 | int len=arr.length; 13 | 14 | for(int i=0;i 1): 9 | return i 10 | -------------------------------------------------------------------------------- /SQL/626. ExchangeSeats.sql: -------------------------------------------------------------------------------- 1 | #This code gives back every entry from the "seat"-Table but switches the ids in pairs (e.g. 1 <-> 2, 3 <-> 4, ...). The last one (if without a partner) stays itself. 2 | 3 | select 4 | (case 5 | when mod(id, 2) != 0 and id = counts then id 6 | when mod(id, 2) != 0 and id != counts then id+1 7 | else id - 1 8 | end) as id, 9 | student 10 | from 11 | seat, 12 | (select 13 | count(*) as counts 14 | from 15 | seat) 16 | as seatCount 17 | order by 18 | id asc; -------------------------------------------------------------------------------- /Java/1051.HeightChecker.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class Solution { 3 | public int heightChecker(int[] heights) { 4 | int[] sortHeights=new int[heights.length]; 5 | int count=0; 6 | for(int i=0;i List[int]: 14 | # Loop from 0 to num, convert them in binary and use 15 | # `count()` to count the occurances of 1. 16 | 17 | result = [bin(i).count('1') for i in range(num + 1)] 18 | return result 19 | -------------------------------------------------------------------------------- /Python/504. Base7.py: -------------------------------------------------------------------------------- 1 | #Function convertToBase7 converts number num to string representing this number in base 7. 2 | class Solution(object): 3 | def convertToBase7(self, num): 4 | if num == 0: 5 | return "0" 6 | digitsList = [] 7 | sign = num//abs(num) 8 | num = abs(num) 9 | while num > 0: 10 | digitsList += [str(num % 7)] 11 | num //= 7 12 | digitsList.reverse() 13 | numberBase7 = "".join(digitsList) 14 | if sign == -1: 15 | return "-" + numberBase7 16 | return numberBase7 -------------------------------------------------------------------------------- /Java/1295. Find_Number_with_even.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | int findDigit(int n){ 4 | int result=0; 5 | while(n/10 > 0){ 6 | n=n/10; 7 | result++; 8 | } 9 | return result-1; 10 | } 11 | 12 | public int findNumbers(int[] nums) { 13 | 14 | int count=0; 15 | int len=0; 16 | for(int i = 0 ; i < nums.length ; i++){ 17 | len=findDigit(nums[i]); 18 | if(len%2 == 0){ 19 | count++; 20 | } 21 | } 22 | return count; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Java/387.First Unique Character in a String.java: -------------------------------------------------------------------------------- 1 | /**Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1. */ 2 | class Solution { 3 | public int firstUniqChar(String s) { 4 | int[] count = new int [26]; 5 | for (int i = 0; i < s.length(); i++) { 6 | count[s.charAt(i) - 'a']++; 7 | } 8 | for(int i = 0; i < s.length(); i++) { 9 | if (count[s.charAt(i) - 'a'] == 1) { 10 | return i; 11 | } 12 | } 13 | return -1; 14 | 15 | } 16 | } -------------------------------------------------------------------------------- /Python/941. ValidMountainArray.py: -------------------------------------------------------------------------------- 1 | #941. Valid Mountain Array problem is described here : https://leetcode.com/problems/valid-mountain-array/ 2 | 3 | class Solution(object): 4 | def validMountainArray(self, A): 5 | N = len(A) 6 | i = 0 7 | 8 | # walk up 9 | while i+1 < N and A[i] < A[i+1]: 10 | i += 1 11 | 12 | # peak can't be first or last 13 | if i == 0 or i == N-1: 14 | return False 15 | 16 | # walk down 17 | while i+1 < N and A[i] > A[i+1]: 18 | i += 1 19 | 20 | return i == N-1 21 | -------------------------------------------------------------------------------- /Python/205.IsomorphicStrings.py: -------------------------------------------------------------------------------- 1 | # Having 2 strings s1, s2 isIsomorphic checks if s1 can be changed into s2 2 | # by replacing letters of s1 3 | class Solution: 4 | def isIsomorphic(self, s1: str, s2: str) -> bool: 5 | if len(s1) != len(s2): 6 | return False 7 | 8 | mapping = {} 9 | 10 | for letter1, letter2 in zip(s1, s2): 11 | if not letter1 in mapping: 12 | mapping[letter1] = letter2 13 | continue 14 | 15 | if mapping[letter1] != letter2: 16 | return False 17 | 18 | return len(mapping) == len(set(mapping.values())) 19 | -------------------------------------------------------------------------------- /C++/1431. KidsWithTheGreatesNumberOfCandies.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Solution to Kids With the Greatest Number of Candies in CPP 3 | * 4 | * author: ITES7321 5 | * ref:https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/ 6 | */ 7 | 8 | class Solution { 9 | public: 10 | vector kidsWithCandies(vector& candies, int extraCandies) { 11 | int m = *max_element(candies.begin(),candies.end()); 12 | vector v(candies.size()); 13 | for(int i=0;i= m) 16 | v[i] = true; 17 | } 18 | return v; 19 | } 20 | }; -------------------------------------------------------------------------------- /Java/1299.ReplaceElementswithGreatestElementonRightSide.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findGreatest(int[] arr, int key){ 3 | int len=arr.length; 4 | int max=arr[len-1]; 5 | for(int i=len-1;i>key;i--){ 6 | if(arr[i]>max){ 7 | max=arr[i]; 8 | } 9 | } 10 | return max; 11 | } 12 | 13 | public int[] replaceElements(int[] arr) { 14 | int len=arr.length; 15 | 16 | 17 | for(int i=0;i int: 8 | n = len(arr) 9 | res = 0 10 | 11 | for i in range(n): 12 | even_away = ((i // 2) + 1) * ((n - i - 1) // 2 + 1) 13 | odd_away = ((i + 1) // 2) * ((n - i) // 2) 14 | res += arr[i] * (even_away + odd_away) 15 | 16 | return res 17 | -------------------------------------------------------------------------------- /C++/1051. HeightChecker.cpp: -------------------------------------------------------------------------------- 1 | //Return the minimum number of students that must move in order for all students to be standing in non-decreasing order of height. 2 | //Make a copy of the array, sort the copy and comapre it with the actual array 3 | 4 | class Solution { 5 | public: 6 | int heightChecker(vector& heights) { 7 | vectorarr; 8 | int count=0; 9 | int n=heights.size(); 10 | arr.assign(heights.begin(),heights.end()); 11 | sort(heights.begin(),heights.end()); 12 | for(int i=0;i sortArrayByParity(vector& A) { 7 | int n=A.size(); 8 | int i=0,count=0; 9 | while(count int: 6 | counts = {} 7 | 8 | # Iterate through array once, adding counts to dictionary 9 | for char in s: 10 | if char in counts: 11 | counts[char] += 1 12 | else: 13 | counts[char] = 1 14 | 15 | # Iterate through array again, finding the first a letter with a count of 0 16 | for index, char in enumerate(s): 17 | if counts[char] == 1: 18 | return index 19 | return -1 -------------------------------------------------------------------------------- /C++/75.SortColors.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array nums 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. 3 | 4 | Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. 5 | */ 6 | 7 | class Solution { 8 | public: 9 | void sortColors(vector& nums) { 10 | sort(nums.begin(),nums.end()); 11 | } 12 | }; 13 | /* 14 | Sample Tests: 15 | 16 | Input: nums = [2,0,2,1,1,0] 17 | Output: [0,0,1,1,2,2] 18 | 19 | Input: nums = [2,0,1] 20 | Output: [0,1,2] 21 | 22 | Input: nums = [0] 23 | Output: [0] 24 | 25 | Input: nums = [1] 26 | Output: [1] 27 | */ 28 | -------------------------------------------------------------------------------- /C++/477. TotalHammingDistance.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public : 3 | int totalHammingDistance(vector< int >& nums) { 4 | int res = 0 , n = nums.size(); 5 | for ( int i = 0 ; i < 32 ; ++ i) { 6 | int cnt = 0 ; 7 | for ( int num: nums) { // counts set bits at pos i from right 8 | if (num & ( 1 << i)) ++ cnt; 9 | } 10 | res += cnt * (n- cnt); // #setBit * #UnsetBit 11 | } 12 | return res; 13 | } 14 | }; 15 | 16 | //4: 0 1 0 0 17 | 18 | //14: 1 1 1 0 19 | 20 | //2: 0 0 1 0 21 | 22 | //1: 0 0 0 1 23 | 24 | //By observing the above binary form, Imp rule identified here is 25 | //Number of Setbit * number of unsetbit 26 | -------------------------------------------------------------------------------- /Java/198. HouseRobber.java: -------------------------------------------------------------------------------- 1 | /* 2 | Since we are not allowed to rob two adjacent houses, we keep two variables pre and cur. 3 | During the i-th loop, pre records the maximum profit that we do not rob the i - 1-th house and thus the current house (the i-th house) can be robbed 4 | while cur records the profit that we have robbed the i - 1-th house. 5 | 6 | The code is as follows. 7 | 8 | Java 9 | */ 10 | 11 | 12 | class Solution { 13 | public int rob(int[] nums) { 14 | int pre = 0, cur = 0; 15 | for (int num : nums) { 16 | final int temp = Integer.max(pre + num, cur); 17 | pre = cur; 18 | cur = temp; 19 | } 20 | return cur; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Python/559. MaximumDepthOfN-aryTree.py: -------------------------------------------------------------------------------- 1 | """ 2 | # Definition for a Node. 3 | class Node: 4 | def __init__(self, val=None, children=None): 5 | self.val = val 6 | self.children = children 7 | """ 8 | 9 | class Solution: 10 | # calculate n-ary Tree depth 11 | def maxDepth(self, root: 'Node') -> int: 12 | # if root not exist than return 0 13 | if root == None: 14 | return 0 15 | # if root have't children than return 0 16 | if root.children == None: 17 | return 1 18 | # get max depth in root's children 19 | M = 0 20 | for child in root.children: 21 | M = max(M,self.maxDepth(child)) 22 | # add this root 23 | return M+1 -------------------------------------------------------------------------------- /Python/766. ToeplitzMatrix.py: -------------------------------------------------------------------------------- 1 | #A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element. 2 | #Now given an M x N matrix, return True if and only if the matrix is Toeplitz. 3 | 4 | class Solution: 5 | def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: 6 | c = True 7 | rows = len(matrix) 8 | cols = len(matrix[0]) 9 | 10 | for x in range(rows): 11 | for y in range(cols): 12 | if x != 0 and y != 0: 13 | if matrix[x][y] != matrix[x-1][y-1]: 14 | c = False 15 | break 16 | if c == False: 17 | return False 18 | else: 19 | return True 20 | -------------------------------------------------------------------------------- /C++/319. BulbSwitcher.cpp: -------------------------------------------------------------------------------- 1 | // Problem - 319. Bulb Switcher 2 | 3 | // There are n bulbs that are initially off. 4 | // You first turn on all the bulbs. 5 | // Then, you turn off every second bulb. 6 | // On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). 7 | // For the i-th round, you toggle every i bulb. 8 | // For the n-th round, you only toggle the last bulb. 9 | // Find how many bulbs are on after n rounds. 10 | 11 | class Solution { 12 | public: 13 | int bulbSwitch(int n) { 14 | int count=0; 15 | for(int i=1; i*i<=n; i++) { // only bulbs at perfect squares position will remain turned on 16 | count++; 17 | } 18 | return count; 19 | } 20 | }; -------------------------------------------------------------------------------- /Python/9.Palindrome Number.py: -------------------------------------------------------------------------------- 1 | #This program returns true if the number is a palindrome, else it returns false 2 | 3 | class Solution(object): 4 | def isPalindrome(self, x): 5 | """ 6 | :type x: int 7 | :rtype: bool 8 | """ 9 | #All negative numbers reutrn false for Palindrome 10 | if x < 0: 11 | return False 12 | 13 | a = x 14 | sum = 0 15 | while a > 0 : 16 | r = a % 10 17 | sum = sum*10 + r 18 | a = a // 10 19 | #If reversed number is same as orignal, returns True 20 | if sum==x: 21 | return True 22 | 23 | #else returns false 24 | else: 25 | return False 26 | -------------------------------------------------------------------------------- /Python/767. ReorganizeString.py: -------------------------------------------------------------------------------- 1 | #767. Reorganize String problem is described here : https://leetcode.com/problems/reorganize-string/ 2 | 3 | class Solution: 4 | def reorganizeString(self, S: str) -> str: 5 | reorg = [None] * len(S) 6 | letters = [[S.count(c), c] for c in set(S)] 7 | letters.sort(reverse=True) 8 | 9 | i = 0 10 | for count, c in letters: 11 | while count: 12 | reorg[i] = c 13 | i += 2 14 | if i >= len(S): 15 | i = 1 16 | count -= 1 17 | for i in range(len(reorg) - 1): 18 | if reorg[i] == reorg[i + 1]: 19 | return "" 20 | return "".join(reorg) 21 | -------------------------------------------------------------------------------- /Java/421.MaximumXORofTwoNumbersInAnArray.java: -------------------------------------------------------------------------------- 1 | // Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 ≤ i ≤ j < n. 2 | class Solution { 3 | public int findMaximumXOR(int[] nums) { 4 | int max = 0, mask = 0; 5 | for(int i = 31; i >= 0; i--){ 6 | mask = mask | (1 << i); 7 | Set set = new HashSet<>(); 8 | for(int num : nums){ 9 | set.add(num & mask); 10 | } 11 | int tmp = max | (1 << i); 12 | for(int prefix : set){ 13 | if(set.contains(tmp ^ prefix)) { 14 | max = tmp; 15 | break; 16 | } 17 | } 18 | } 19 | return max; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Python/3. LongestSubstringWithoutRepeatingCharacters.py: -------------------------------------------------------------------------------- 1 | # Given a string s, find the length of the longest substring without repeating characters. 2 | 3 | class Solution(object): 4 | def lengthOfLongestSubstring(self, s): 5 | """ 6 | :type s: str 7 | :rtype: int 8 | """ 9 | start = max_length = 0 10 | used_char = {} 11 | 12 | for i in range(len(s)): 13 | if s[i] in used_char and start <= used_char[s[i]]: 14 | start = used_char[s[i]] + 1 15 | else: 16 | max_length = max(max_length, i - start + 1) 17 | 18 | used_char[s[i]] = i 19 | 20 | return max_length 21 | 22 | sol = Solution() 23 | assert 3 == sol.lengthOfLongestSubstring("abcabcbb") 24 | -------------------------------------------------------------------------------- /Java/62. UniquePath.java: -------------------------------------------------------------------------------- 1 | /* 2 | The idea is to use a 2D array to keep track of the total possible ways to enter specific block. 3 | Since we can only go "DOWN" and "RIGHT", therefore each block could be entered from both "ABOVE" and "LEFT", therefore adding up their total ways would give the total ways for current block. 4 | In order to save the hassles in the future, it's easier that we initialize the array 5 | which is why dp[1][0]=1 6 | 7 | Following is the code 8 | 9 | */ 10 | public static int uniquePaths(int m, int n) { 11 | int[][] dp = new int[n + 1][m + 1]; 12 | dp[1][0] = 1; 13 | for (int i = 1; i <= n; i++) { 14 | for (int j = 1; j <= m; j++) { 15 | dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; 16 | } 17 | } 18 | return dp[n][m]; 19 | } 20 | -------------------------------------------------------------------------------- /Java/1346. CheckIfNandItsDoubleExist.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class Solution { 3 | public boolean checkIfExist(int[] arr) { 4 | int len=arr.length; 5 | boolean result=false; 6 | Hashtable keys= new Hashtable<>(); 7 | for(int i=0;i= count): 11 | row += 1 12 | n -= count 13 | count += 1 14 | return row 15 | -------------------------------------------------------------------------------- /Python/7.ReverseInteger.py: -------------------------------------------------------------------------------- 1 | #This program takes in a number, reverses it and then returns it as the output. 2 | 3 | class Solution(object): 4 | def reverse(self, x): 5 | """ 6 | :type x: int 7 | :rtype: int 8 | """ 9 | 10 | #get positive number irrespestive of the original sign 11 | if x>0: 12 | n = x 13 | else: 14 | n = -x 15 | c = 0 16 | 17 | while n>0: 18 | r = n % 10 19 | c = c*10 + r 20 | n = n // 10 21 | 22 | #reset value to 0 if answer exceeds the constraint 23 | if c>((2**31)-1): 24 | c=0 25 | 26 | #return the answer with the original sign 27 | if x>0: 28 | return c 29 | else: 30 | return -c 31 | -------------------------------------------------------------------------------- /Python/771. Jewels and Stone.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You're given strings J representing the types of stones that are jewels, and S representing the stones you have. 3 | 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. 4 | 5 | The letters in J are should be distinct, and all characters in J and S are letters. 6 | Letters are case sensitive, so "a" is considered a different type of stone from "A". 7 | ''' 8 | class Solution(object): 9 | def numJewelsInStones(self, J, S): 10 | jewels = {} 11 | for i in J: 12 | jewels[i] = 1 13 | number = 0 14 | for i in S: 15 | if i in jewels: 16 | number+=1 17 | return number 18 | j=input("Enter Jewels: ") 19 | s=input("Enter Stones: ") 20 | ob1 = Solution() 21 | print(ob1.numJewelsInStones(j,s)) -------------------------------------------------------------------------------- /C++/7. Reverse_Integer.cpp: -------------------------------------------------------------------------------- 1 | /* Program name :- Reverse_Integer.cpp 2 | this program will receive any 3 digit number whether it is positive or negative and convert it into its reversed form or reverse its digits , 3 | and this program also works if the situation overflows. 4 | */ 5 | 6 | 7 | public class Solution { 8 | 9 | public static int reverse(int x) { 10 | int ret = 0; 11 | boolean zero = false; 12 | while (!zero) { 13 | ret = ret * 10 + (x % 10); 14 | x /= 10; 15 | if(x == 0){ 16 | zero = true; 17 | } 18 | } 19 | return ret; 20 | } 21 | 22 | public static void main(String[] args) { 23 | int s = 1000000003; 24 | System.out.println(reverse(s)); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Java/1.Two Sum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 3 | * You may assume that each input would have exactly one solution, and you may not use the same element twice. 4 | * You can return the answer in any order. 5 | */ 6 | class Solution { 7 | public int[] twoSum(int[] nums, int target) { 8 | HashMap map = new HashMap<>(); 9 | int[] res = new int[2]; 10 | for (int i = 0; i < nums.length; i++) { 11 | if (map.containsKey(target - nums[i])) { 12 | res[0] = map.get(target - nums[i]); 13 | res[1] = i; 14 | return res; 15 | } else { 16 | map.put(nums[i], i); 17 | } 18 | } 19 | return res; 20 | } 21 | } -------------------------------------------------------------------------------- /Java/88. MergeSortedArrays.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void merge(int[] nums1, int m, int[] nums2, int n) { 3 | int[] nums3=new int[m+n]; 4 | int k=0; 5 | int i=0,j=0; 6 | while(i int: 21 | if n < 5: 22 | return 0 23 | a = n // 5 24 | return a + self.trailingZeroes(a) 25 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | ## Pull Request Template 2 | 3 | ### What have you Changed(must) 4 | 5 | Write here what you have changed in the codebase 6 | 7 | ### Issue no.(must) - # 8 | 9 | Pr will be close and marked as spam. If issue number not found or issue was assigned to someone else. 10 | Marking as spam can block your account from HacktoberFest. 11 | ### Self Check(Tick After Making pull Request) 12 | 13 | - [ ] This issue was assigned to me if not it will be marked as spam. 14 | - [ ] My file is in the proper folder 15 | - [ ] I am following clean code and Documentation. 16 | - [ ] I have added the title and what program will do first in the file 17 | - [ ] I have named the file as (Problem #). (Problem Title(in Camel Case)).(extension) 18 | ex. 2. AddToNumbers.py 19 | 20 | ### README - [How to Contribute](https://github.com/SSKale1/LeetCode-Solutions/blob/master/CONTRIBUTING.md) 21 | -------------------------------------------------------------------------------- /Java/22. generatePara.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class Solution { 3 | void solve(int open, int close , String op,ArrayList res) 4 | { 5 | if(open==0 && close==0) 6 | { 7 | res.add(op); 8 | return; 9 | } 10 | if(open!=0) 11 | { 12 | String op1=op+"("; 13 | // open--; 14 | solve(open-1,close,op1,res); 15 | } 16 | if(close>open) 17 | { 18 | String op2=op+")"; 19 | // close--; 20 | solve(open,close-1,op2,res); 21 | } 22 | return ; 23 | } 24 | public List generateParenthesis(int n) { 25 | ArrayList res=new ArrayList<>(); 26 | int open = n; 27 | int close = n ; 28 | String op = ""; 29 | solve(open,close,op,res); 30 | 31 | return res; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Python/977.SquaresOfASortedArray.py: -------------------------------------------------------------------------------- 1 | # Having sorted array A of negative and positive integers, sortedSquares 2 | # returns sorted array of squared elements from A 3 | # 4 | # Example: 5 | # A = [-4, -1, 3, 5] 6 | # result = [1, 9, 16, 25] 7 | # 8 | class Solution: 9 | def sortedSquares(self, array: List[int]) -> List[int]: 10 | squared_array = [x*x for x in array] 11 | sorted_array = [] 12 | 13 | left = 0 14 | right = len(squared_array) - 1 15 | 16 | while left <= right: 17 | left_item = squared_array[left] 18 | right_item = squared_array[right] 19 | 20 | if left_item > right_item: 21 | sorted_array.append(left_item) 22 | left += 1 23 | continue 24 | 25 | sorted_array.append(right_item) 26 | right -= 1 27 | 28 | return list(reversed(sorted_array)) 29 | -------------------------------------------------------------------------------- /Python/217.ContainsDuplicate.py: -------------------------------------------------------------------------------- 1 | # Function findPeakElement finds receives an array and checks if 2 | # the array contains a duplicate of two numbers 3 | class Solution(object): 4 | 5 | def ContainsDuplicate(self, arr): 6 | """ 7 | checks if the array contains a duplicate 8 | :param arr: List[int] a list of numbers 9 | :return: True or False if it contains a duplicate 10 | """ 11 | 12 | # a set to contains numbers we have seen 13 | taken_numbers = {} 14 | 15 | # goes through all values in the arr 16 | for i in arr: 17 | # checks if the number has already been seen 18 | if i in taken_numbers: 19 | return True 20 | # adds the number since it hasn't been seen 21 | else: 22 | taken_numbers[i] = i 23 | 24 | # we have not seen any duplicates 25 | return False 26 | -------------------------------------------------------------------------------- /C++/121. BestTimetoBuyandSellStock.cpp: -------------------------------------------------------------------------------- 1 | // Problem: 2 | // Say you have an array for which the ith element is the price of a given stock on day i. 3 | // If you were only permitted to complete at most one transaction 4 | // (i.e., buy one and sell one share of the stock), 5 | // design an algorithm to find the maximum profit. 6 | // Note that you cannot sell a stock before you buy one. 7 | 8 | // Approach: 9 | // Initialize mn variable to first value. Now, find the running difference between current 10 | // value and mn variable, since that would give us the required maximum profit. 11 | 12 | class Solution { 13 | public: 14 | int maxProfit(vector& prices) { 15 | int n = prices.size(); 16 | if (!n) return 0; 17 | int mn = prices[0], ans = 0; 18 | for (int i = 1; i < n; i++) 19 | { 20 | ans = max({0, ans, prices[i] - mn}); 21 | if (prices[i] < mn) 22 | mn = prices[i]; 23 | } 24 | return ans; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Python/169.MajorityNumber.py: -------------------------------------------------------------------------------- 1 | #Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. 2 | class Solution(object): 3 | def majorityElement(self, nums): 4 | tot = len(nums)/2 5 | ls=[] 6 | #First we find the unique element in the list 7 | for i in set(nums): 8 | count = 0 9 | #Then we count the number of occurrences of the element in the list 10 | for j in nums: 11 | if( i == j): 12 | count += 1 13 | #After that we append the unique element and the number of occurences of the element to the list named ls 14 | ls.append([i,count]) 15 | for i in range(len(ls)): 16 | #Here we check occurence of which element is greater than n/2 and return it 17 | if( ls[i][1] > tot): 18 | return ls[i][0] 19 | -------------------------------------------------------------------------------- /C++/1310. XORQueriesOfASubarray.cpp: -------------------------------------------------------------------------------- 1 | // Given the array arr of positive integers and the array queries where queries[i] = [Li, Ri], 2 | // for each query i compute the XOR of elements from Li to Ri (that is, arr[Li] xor arr[Li+1] xor ... xor arr[Ri] ). 3 | // Return an array containing the result for the given queries. 4 | 5 | class Solution { 6 | public: 7 | vector xorQueries(vector& arr, vector>& queries) { 8 | int n = arr.size(); 9 | vector ans; 10 | vector seive(n,0); 11 | seive[0] = arr[0]; 12 | 13 | for(int i = 1;i qry : queries){ 18 | if(qry[0] == 0) ans.push_back(seive[qry[1]]); 19 | else ans.push_back(seive[qry[0]-1]^seive[qry[1]]); 20 | } 21 | return ans; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /C++/13. Roman_To_Integer.cpp: -------------------------------------------------------------------------------- 1 | /* program name:- Roman_To_Integer.cpp 2 | This program converts the entered roman number to integer . 3 | We have used the hash map to ease the input for the desired roman representation of an integer. 4 | */ 5 | 6 | 7 | 8 | int romanToInt(string s) { 9 | 10 | map m = {{'I', 1}, {'V', 5},{'X', 10},{'L', 50}, 11 | {'C', 100},{'D', 500},{'M', 1000}}; 12 | 13 | int total = 0; 14 | for(int i = 0; i < s.length(); i++){ 15 | 16 | //1.The letters are arranged from left to right 17 | in descending order of value to form a number 18 | 19 | if(m[s[i+1]] <= m[s[i]]) total += m[s[i]]; 20 | 21 | //2.when you see a lower value in front of a 22 | higher value (subtract) 23 | else total -= m[s[i]]; 24 | } 25 | return total; 26 | } 27 | -------------------------------------------------------------------------------- /C++/1. TwoSum.cpp: -------------------------------------------------------------------------------- 1 | // Problem - 1. Two Sum 2 | 3 | // Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 4 | // You may assume that each input would have exactly one solution, and you may not use the same element twice. 5 | 6 | class Solution { 7 | public: 8 | vector twoSum(vector& nums, int target) { 9 | 10 | for(int i=0; i size of vector nums 11 | 12 | for(int j=1; j size of vector nums 13 | 14 | if(nums[i]+nums[j]==target && i!=j) 15 | return vector {i,j}; // return vector of i and j if condition satisfies 16 | 17 | } 18 | } 19 | return {}; // return empty vector if condition fails for every element 20 | } 21 | }; -------------------------------------------------------------------------------- /Python/1232.CheckIfItIsAStraightLine.py: -------------------------------------------------------------------------------- 1 | # Given list of (x, y) coordinates checkStraightLine checks if it forms straight line 2 | # 3 | class Solution: 4 | def checkStraightLine(self, coordinates: List[List[int]]) -> bool: 5 | if len(coordinates) <= 2: 6 | # it is always possible to create line through 2 points (and also 1 and 0) 7 | return True 8 | 9 | x0, y0 = coordinates[0] 10 | x1, y1 = coordinates[1] 11 | 12 | if x0 == x1: 13 | # check if this is vertical line (all x are the same) 14 | return all([x == x0 for x, _ in coordinates]) 15 | 16 | # 2 points define line, so find it's equation y = a*x + b 17 | a = (y0 - y1) / (x0 - x1) 18 | b = y0 - a * x0 19 | 20 | line = lambda x: a*x + b 21 | 22 | #check if all points lies on the line defined by (x0, y0) and (x1, y1) 23 | return all([y == line(x) for x, y in coordinates]) 24 | -------------------------------------------------------------------------------- /Python/215.KthLargestElementInAnArray.py: -------------------------------------------------------------------------------- 1 | """ 2 | Goal: Finding the Kth largest element in an array. 3 | 4 | Procedure: 5 | -> Creating a min heap. 6 | -> Finding K number of largest elements 7 | -> Returning the Kth element, that is, the last element from the list found in second step. 8 | 9 | Input: 10 | First entering the array. 11 | Second entering the K value. 12 | 13 | Output: 14 | A single output returning the Kth largest element of the array. 15 | 16 | 17 | Examples: 18 | Input: 3 2 1 5 6 4 19 | 2 20 | 21 | Output: 5 22 | 23 | 24 | Input: 3 2 3 1 2 4 5 5 6 25 | 4 26 | 27 | Output: 4 28 | """ 29 | 30 | import heapq 31 | class Solution: 32 | def findKthLargest(nums, k): 33 | heapq.heapify(nums) 34 | res = heapq.nlargest(k,nums) 35 | return res[len(res)-1] 36 | 37 | arr = [int(w) for w in input().strip().split(',')] 38 | k = int(input()) 39 | print(Solution.findKthLargest(arr, k)) 40 | -------------------------------------------------------------------------------- /C++/124. Binary_Tree_Maximum.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 | int func(TreeNode* root,int &sum){ 15 | if(root==nullptr){ 16 | return 0; 17 | } 18 | int l=max(0,func(root->left,sum)); 19 | int r=max(0,func(root->right,sum)); 20 | sum=max(sum,root->val+l+r); 21 | return root->val+max(l,r); 22 | } 23 | int maxPathSum(TreeNode* root) { 24 | int sum=INT_MIN; 25 | func(root,sum); 26 | return sum; 27 | 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Python/1356.SortIntegersByNumberof1Bits.py: -------------------------------------------------------------------------------- 1 | #Problem Statement 2 | # 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 3 | # and in case of two or more integers have the same number of 1's you have to sort them in ascending order. 4 | # Return the sorted array. 5 | #Input : List of numbers separated by a space (eg. 1 2 3 4) 6 | #Output: Sorted list on basis of 1 bits (eg. 1 2 4 3) 7 | arr = list(map(int,input().split())) 8 | res = {} #dictionary that stores the number as key and number of 1 bits as value 9 | for i in arr: 10 | res[i]=bin(i).count("1") #bin function converts the integer to binary form as a string 11 | res_new = sorted(res.items(), key=lambda res: res[1]) #sort the items according to the value(no. of 1 bits) 12 | for i in res_new: 13 | print(i[0], end= " ") #print according to keys(the given integers) 14 | print() -------------------------------------------------------------------------------- /Python/728. SelfDividingNumbers.py: -------------------------------------------------------------------------------- 1 | #Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible. 2 | class Solution: 3 | def selfDividingNumbers(self, left: int, right: int) -> List[int]: 4 | #initialize an empty list 5 | self_dividing_nos = [] 6 | #check for all the numbers in given range if they are self dividing 7 | for num in range(left, right + 1): 8 | num_original = num 9 | while (num > 0): 10 | digit = num % 10 11 | if digit != 0: 12 | if (num_original % digit == 0): 13 | num = num // 10 14 | else: 15 | break 16 | else: 17 | break 18 | if num == 0: 19 | self_dividing_nos.append(num_original) 20 | return self_dividing_nos 21 | 22 | 23 | -------------------------------------------------------------------------------- /C++/32. LongestValidParenthesis.cpp: -------------------------------------------------------------------------------- 1 | //Given a string containing just the characters 2 | //'(' and ')', find the length of the longest valid (well-formed) parentheses substring. 3 | //We can solve this by using the concept of stack. We will check for the top most closing brace and calculate max length. 4 | 5 | class Solution { 6 | public: 7 | int longestValidParentheses(string s) { 8 | stackst; 9 | st.push(-1); 10 | int l=s.length(); 11 | int ans=0; 12 | for(int i=0;i& nums,int sum,int n) 8 | { 9 | if(n==0)return false; 10 | if(sum==0)return true; 11 | if(dp[n][sum]!=-1)return dp[n][sum]; 12 | if(sum>=nums[n-1]) 13 | return dp[n][sum]=check(nums,sum-nums[n-1],n-1)|| check(nums,sum,n-1); 14 | else 15 | return dp[n][sum]=check(nums,sum,n-1); 16 | } 17 | bool canPartition(vector& nums) { 18 | int n=nums.size(); 19 | memset(dp,-1,sizeof(dp)); 20 | int sum=0; 21 | for(int i=0;i root->val) { 23 | root->right = insertIntoBST(root->right, val); 24 | } 25 | if(val < root->val) { 26 | root->left = insertIntoBST(root->left, val); 27 | } 28 | return root; 29 | } 30 | }; -------------------------------------------------------------------------------- /Java/1041.RobotBoundedInCircle.java: -------------------------------------------------------------------------------- 1 | /* 2 | On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can receive one of three instructions: 3 | 4 | "G": go straight 1 unit; 5 | "L": turn 90 degrees to the left; 6 | "R": turn 90 degress to the right. 7 | The robot performs the instructions given in order, and repeats them forever. 8 | 9 | Return true if and only if there exists a circle in the plane such that the robot never leaves the circle. 10 | */ 11 | 12 | class Solution { 13 | public boolean isRobotBounded(String ins) { 14 | int x = 0, y = 0, i = 0, d[][] = {{0, 1}, {1, 0}, {0, -1}, { -1, 0}}; 15 | for (int j = 0; j < ins.length(); ++j) 16 | if (ins.charAt(j) == 'R') 17 | i = (i + 1) % 4; 18 | else if (ins.charAt(j) == 'L') 19 | i = (i + 3) % 4; 20 | else { 21 | x += d[i][0]; y += d[i][1]; 22 | } 23 | return x == 0 && y == 0 || i > 0; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Python/5.LongestPalindromicSubstring.py: -------------------------------------------------------------------------------- 1 | #check if string is palindrome or not 2 | def isPalindrome(s, x, y): 3 | while x < y: 4 | if s[x] != s[y]: 5 | return False 6 | x += 1 7 | y -= 1 8 | return True 9 | 10 | def longestPalindrome(s): 11 | n = len(s) 12 | max_ = 0 13 | ans = '' 14 | 15 | if n == 1: 16 | return s 17 | 18 | for i in range(n): 19 | #list of all index which is same as s[i] 20 | duplicate = [j for j in range(i+1, n) if s[j] == s[i]] 21 | 22 | #look through all elements in duplicate if the string is palindrome 23 | for j in duplicate: 24 | #if palinfrome update max value and add sub-string to ans 25 | if isPalindrome(s, i, j) and j - i + 1 > max_: 26 | max_ = j - i + 1 27 | ans = ''.join(s[i:j+1]) 28 | 29 | return ans 30 | 31 | s = 'abacddcliril' 32 | 33 | l = longestPalindrome(list(s)) 34 | 35 | print(l) #liril 36 | -------------------------------------------------------------------------------- /C++/9. Palindrome Number.cpp: -------------------------------------------------------------------------------- 1 | /*To determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.*/ 2 | 3 | 4 | class Solution { 5 | public: 6 | bool isPalindrome(int x) { 7 | if(x<0) // to check whether x is negative 8 | return false; 9 | else // for positive x values 10 | { 11 | vector a; // declaration of vector a 12 | while(x!=0) // start of loop to get digits of x 13 | { 14 | a.push_back(x%10); 15 | x=x/10; 16 | } 17 | int c=1; 18 | int n = a.size(); 19 | for(int i=0;i& gas, vector& cost) { 12 | int sumGas = 0; 13 | int sumCost = 0; 14 | int start = 0; 15 | int tank = 0; 16 | for(int i = 0;i=sumCost) return start; 25 | else return -1; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Python/485. MaxConsecutiveOnes.py: -------------------------------------------------------------------------------- 1 | #Given a binary array, find the maximum number of consecutive 1s in this array. 2 | #Taking two variables consecutive and result and assigning them to zero. 3 | #Traversing the list if the value 1 is found in the list we add 1 to consecutive. 4 | #If result is less than consecutive then assigning the value of consecutive to result. 5 | #If the consecutive value is also 1 then we increment consecutive by 1 and assign its value to result if value of result is smaller 6 | #If the consecutive value is not 1 then we assingn 0 to consecutive and start over. 7 | #Fianlly the max consecutive value is returned after traversing the list 8 | class Solution(object): 9 | def findMaxConsecutiveOnes(self, nums): 10 | consecutive=0 11 | result=0 12 | for i in nums: 13 | if(i==1): 14 | consecutive += 1 15 | if(result < consecutive): 16 | result = consecutive 17 | else: 18 | consecutive = 0 19 | return result 20 | -------------------------------------------------------------------------------- /Java/27. RemoveElement.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | void delElement(int[] arr, int key, int len){ 4 | if(arr.length < len) throw new ArrayIndexOutOfBoundsException("Length is longer than array length"); //if input value is less than array lenght, it will throw ArrayIndexOutOfBoundsException exception 5 | if (len - 1 - key >= 0) System.arraycopy(arr, key + 1, arr, key, len - 1 - key); //add elements to array 6 | } 7 | 8 | public int removeElement(int[] nums, int val) { 9 | int i = 0; // declaration variable 10 | int len = nums.length; //declaration array lenght 11 | 12 | for(int j = 0; j < nums.length; j++){ //go through the array elements with the for loop 13 | if(nums[j] != val) { //if statement : actual value of array != input value 14 | nums[i++] = nums[j]; // compare with other elements of array 15 | len--; //decrement lenght 16 | } 17 | } 18 | return nums.length-len; 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /C++/42. TrappingRainWater.cpp: -------------------------------------------------------------------------------- 1 | 2 | /*** 3 | Given n non-negative integers representing an elevation map where the width of each bar is 1, 4 | compute how much water it is able to trap after raining. 5 | 6 | Solution: Dynamic Programming 7 | ***/ 8 | 9 | class Solution { 10 | public: 11 | int trap(vector& height) { 12 | // detect edge case 13 | if (height.size() < 2) return 0; 14 | 15 | int n = height.size(); 16 | int left_max[n]; 17 | int right_max[n]; 18 | 19 | left_max[0] = height[0]; 20 | for (int i = 1; i < n; i ++) { 21 | left_max[i] = max(left_max[i-1], height[i]); 22 | } 23 | right_max[n-1] = height[n-1]; 24 | for (int i = n-2; i >= 0 ; i --) { 25 | right_max[i] = max(right_max[i+1], height[i]); 26 | } 27 | 28 | int ans = 0; 29 | for (int i = 0; i < n; i ++) { 30 | ans += min(left_max[i], right_max[i]) - height[i]; 31 | } 32 | 33 | return ans; 34 | } 35 | }; -------------------------------------------------------------------------------- /C++/532. K-diffPairsInAnArray.cpp: -------------------------------------------------------------------------------- 1 | //If k==0,check how many number of elements are repeated 2 | /*Else for each unique number num in the set of given integers check whether num+k is present.If it is there,then increment finalval*/ 3 | 4 | class Solution { 5 | public: 6 | int findPairs(vector& nums, int k) { 7 | set s; 8 | int n=nums.size(),fval=0; 9 | for(int i=0;i mp; 14 | for(int i=0;i ::iterator it; 25 | for(it=s.begin();it!=s.end();it++) 26 | { 27 | int val=(*it); 28 | 29 | if(s.find(k+val)!=s.end()) 30 | fval++; 31 | 32 | } 33 | return fval; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Java/41. First Missing Positive.java: -------------------------------------------------------------------------------- 1 | /*The problem gives an unsorted integer array 2 | * We have to find the first missing positive integer 3 | * The problem requires that the runtime should be within O(n) and uses constant space. 4 | * 5 | */ 6 | 7 | public class Solution { 8 | public int firstMissingPositive(int[] A) { 9 | if (A == null || A.length == 0) { 10 | return 1; 11 | } 12 | int n = A.length; 13 | int i = 0; 14 | while (i < n) { 15 | if (A[i] != i + 1 && A[i] >= 1 && A[i] <= n && A[i] != A[A[i] - 1]) { 16 | swap(A, i, A[i] - 1); 17 | } else { 18 | i++; 19 | } 20 | } 21 | 22 | for (i = 0; i < n; i++) { 23 | if (A[i] != i + 1) { 24 | return i + 1; 25 | } 26 | } 27 | 28 | return A[n - 1] + 1; 29 | } 30 | 31 | private void swap(int[] A, int i, int j) { 32 | int temp = A[i]; 33 | A[i] = A[j]; 34 | A[j] = temp; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /C++/941. ValidMountainArray.cpp: -------------------------------------------------------------------------------- 1 | //Given an array A of integers, return true if and only if it is a valid mountain array. 2 | //Runtime beats 82.32% of cpp submission 3 | //Find the peak(largest number), check whether it is strictly decreasing/increasing from the peak 4 | 5 | class Solution { 6 | public: 7 | bool validMountainArray(vector& A) { 8 | int j=0,k=0; 9 | int large=0; 10 | if(A.size()<3) 11 | return false; 12 | 13 | for(int i=0;i=A[k+1]) 22 | return false; 23 | k++; 24 | } 25 | j=large; 26 | while(j findSmallestSetOfVertices(int n, vector>& edges) { 10 | bool visited[n]; 11 | for(int i = 0; i < n; i++){ 12 | visited[i] = false; 13 | } 14 | /* All the nodes that are reachable from any other node will be marked as true */ 15 | for(vector i : edges){ 16 | visited[i[1]] = true; 17 | } 18 | /* Nodes with in-degree 0 would be added to the ans vector */ 19 | vectorans; 20 | for(int i = 0; i < n; i++){ 21 | if(visited[i] == false){ 22 | ans.push_back(i); 23 | } 24 | } 25 | return ans; 26 | } 27 | }; -------------------------------------------------------------------------------- /Python/367.ValidPerfectSquare.py: -------------------------------------------------------------------------------- 1 | #Given a positive integer num, write a function which returns True if num is a perfect square else False. 2 | class Solution(object): 3 | def isPerfectSquare(self, num): 4 | low=0 5 | high=num 6 | #Starting from zero till the number we need to check for perfect square 7 | while(low<=high): 8 | #Calulating middle value by using right shift operator 9 | mid=(low+high)>>1 10 | #If the square of the middle value is equal to the number then it is a perfect square else not 11 | if(mid*mid==num): 12 | return True 13 | #If the square of the middle value is less than the number we increment the low variable else the high variable is decremented. 14 | #The loop will continue till the low value becomes more than the high value or the number is a perfect square then True will be 15 | #returned 16 | elif(mid*mid arr[1]: 18 | return 0 19 | else: 20 | return 1 21 | 22 | # peak is at the beginning 23 | if arr[0] > arr[1]: 24 | return 0 25 | 26 | # goes though the array and finds a peak 27 | for i in range(1, len(arr) - 1): 28 | if arr[i] > arr[i - 1] and arr[i] > arr[i + 1]: 29 | return i 30 | 31 | # peak is at the end 32 | return len(arr) - 1 33 | 34 | -------------------------------------------------------------------------------- /Python/225.ImplementStackUsingQueues.py: -------------------------------------------------------------------------------- 1 | # Implementation of stack datastructure (LIFO) using one FIFO queue 2 | 3 | from collections import deque 4 | 5 | class MyStack: 6 | 7 | def __init__(self): 8 | """ 9 | Initialize your data structure here. 10 | """ 11 | self.queue = deque() 12 | 13 | def push(self, x: int) -> None: 14 | """ 15 | Push element x onto stack. 16 | """ 17 | size = len(self.queue) 18 | self.queue.append(x) 19 | for _ in range(size): 20 | item = self.queue.popleft() 21 | self.queue.append(item) 22 | 23 | def pop(self) -> int: 24 | """ 25 | Removes the element on top of the stack and returns that element. 26 | """ 27 | return self.queue.popleft() 28 | 29 | def top(self) -> int: 30 | """ 31 | Get the top element. 32 | """ 33 | return self.queue[0] 34 | 35 | def empty(self) -> bool: 36 | """ 37 | Returns whether the stack is empty. 38 | """ 39 | return len(self.queue) == 0 40 | -------------------------------------------------------------------------------- /Python/8.PalindromeChecker.py: -------------------------------------------------------------------------------- 1 | #Statement: This program takes a string as input, checks whether the string is a palindrome or not and returns, 2 | # True if yes and returns False if no. 3 | 4 | # For example: "AABBCCBBAA" is a palindrome, so True will be returned. 5 | # "122333221" is again a palindrome, so True will be returned. 6 | # But, "I am a good code" is not a palindrome, so False will be returned. 7 | 8 | class Solution(object): 9 | def palindromeChecker(self, str): 10 | """ 11 | :type str: string 12 | :rtype: boolean 13 | """ 14 | strLower = str.lower() # converts the string into lower case 15 | strList = strLower.split("") # converting the string into a list 16 | strReverse = strList.reverse() # reversing the list 17 | finalStr = "".join(strReverse) # getting the final reversed string 18 | 19 | if finalStr == str: # This part checks if the final reversed string is eqaul to the original string or not. 20 | return True 21 | 22 | else: 23 | return False 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/create-an-issue.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Create an Issue 3 | about: 'Template following Contribution Guidelines ' 4 | title: Problem Number | Title | Language 5 | labels: good first issue, hacktoberfest 6 | assignees: '' 7 | 8 | --- 9 | 10 | ## **`Title`** - 11 | 12 | **What will change** - 13 | 14 | ### Type of Issue - 15 | 16 | Please add/delete options that are not relevant. 17 | 18 | - [x] Adding New Code 19 | - [x] Improving Code 20 | - [x] Improving Documentation 21 | - [x] Bug Fix 22 | 23 | ### Programming Language 24 | 25 | Please add/delete options that are not relevant. 26 | 27 | - [x] Python 28 | - [x] C++ 29 | - [x] Java 30 | - [x] SQL 31 | 32 | ### Self Check 33 | 34 | - Ask for issue assignment and wait to get assigned to it before making Pull Request. 35 | - Add your file in the proper folder 36 | - `Clean Code` and `Documentation` for better readability 37 | - Add `Title` and `Description` of the program in the file 38 | 39 | :star2: Star it :fork_and_knife:Fork it :handshake: Contribute to it! 40 | 41 | Discord server ✉️ - https://discord.gg/CXksGdn 42 | 43 | Happy Coding, 44 | -------------------------------------------------------------------------------- /C++/151.ReverseWordsInAString.cpp: -------------------------------------------------------------------------------- 1 | /* Given an input string s, reverse the order of the words. 2 | Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. 3 | Do not include any extra spaces. 4 | 5 | Return a string of the words in reverse order concatenated by a single space. 6 | */ 7 | 8 | /* 9 | Example : 10 | Input: s = "the sky is blue" 11 | Output: "blue is sky the" 12 | 13 | */ 14 | 15 | 16 | class Solution { 17 | public: 18 | string reverseWords(string s) { 19 | string result = ""; 20 | int j = 0; 21 | for(int i=0;i j) 26 | result = s.substr(j,i-j) + " " + result; 27 | j = i+1; 28 | } 29 | else if(i == s.size()-1) 30 | result = s.substr(j,s.size()-j) + " " + result; 31 | } 32 | s=result.substr(0,result.size()-1); 33 | return s; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /C++/38. CountAndSay.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | The count-and-say sequence is the sequence of integers beginning as follows: 3 | 1, 11, 21, 1211, 111221, ... 4 | 1 is read off as one 1 or 11. 5 | 11 is read off as two 1s or 21. 6 | 21 is read off as one 2, then one 1 or 1211. 7 | Given an integer n, generate the nth sequence. 8 | Note: The sequence of integers will be represented as a string. 9 | Example: 10 | if n = 2, 11 | the sequence is 11. 12 | */ 13 | 14 | string Solution::countAndSay(int A) { 15 | string result = ""; 16 | 17 | if(!A) 18 | return result; 19 | 20 | string str = "1"; 21 | int cnt = 1; 22 | 23 | for (int i = 1; i pq = new PriorityQueue<>(); 15 | for(int ele: nums) 16 | { 17 | pq.add(ele); 18 | if(pq.size()>k) 19 | pq.remove(); 20 | } 21 | 22 | return pq.peek(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Java/414.ThirdMaximumNumber.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | class Solution { 3 | public int thirdMax(int[] nums) { 4 | int fmax, smax, tmax; 5 | int len=nums.length; 6 | boolean flag=false; 7 | fmax=Integer.MIN_VALUE; 8 | smax=Integer.MIN_VALUE; 9 | tmax=Integer.MIN_VALUE; 10 | 11 | for(int i=0;ifmax){ 16 | tmax=smax; 17 | smax=fmax; 18 | fmax=nums[i]; 19 | } 20 | else if(nums[i]!=fmax && nums[i]>smax){ 21 | tmax=smax; 22 | smax=nums[i]; 23 | } 24 | else if(nums[i]!=smax && nums[i]tmax){ 25 | tmax=nums[i]; 26 | } 27 | } 28 | 29 | if(smax==tmax){ 30 | return fmax; 31 | }else if(tmax!=Integer.MIN_VALUE || flag){ 32 | return tmax; 33 | }else{ 34 | return fmax; 35 | } 36 | 37 | 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Python/461.HammingDistance.py: -------------------------------------------------------------------------------- 1 | #The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 2 | #we will store the representation in bits of the 2 integers in lists and we'll be comparing element by element 3 | class Solution(object): 4 | def hammingDistance(self, x, y): 5 | a=list(bin(x)[2:]) #bin() transforms an integer into its representation in bits 6 | b=list(bin(y)[2:]) # bin(5) = 0b101 , we'll copy everything starting from third position till the end. that's our number 7 | 8 | # now these next if statements are used to make the lists of equal size because 12 is 1100 and 5 is 101 the number of bits is not equal 9 | 10 | if len(a) > len(b): 11 | b=['0']*(len(a)-len(b))+b 12 | elif len(a) < len(b) : 13 | a= ['0']*(len(b)-len(a))+a 14 | 15 | #continuing from here is easy, we'll just compare element by element and store the number of different bits in d variable 16 | 17 | d=0 18 | for i in range(len(a)): 19 | if a[i] != b[i]: 20 | d+=1 21 | 22 | return d 23 | -------------------------------------------------------------------------------- /C++/5. LongestPalindromicSubstring.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string longestPalindrome(string s) { 4 | const int n = s.size(); 5 | int max{}; 6 | string ans; 7 | if(n == 1) return s; 8 | for(int i = 0; i < n; i++){ 9 | int x = i, y = i; 10 | int count = 1; 11 | while(x > 0 && y < n - 1 && s[x - 1] == s[y + 1]){ 12 | x--; 13 | y++; 14 | count += 2; 15 | } 16 | if(count > max){ 17 | ans = s.substr(x, count); 18 | max = count; 19 | } 20 | if(i < n - 1 && s[i] == s[i + 1]){ 21 | int x = i, y = i + 1; 22 | count = 2; 23 | while (x > 0 && y < n - 1 && s[x - 1] == s[y + 1]){ 24 | x--; 25 | y++; 26 | count += 2; 27 | } 28 | if(count > max) 29 | { 30 | ans = s.substr(x, count); 31 | max = count; 32 | } 33 | } 34 | } 35 | return ans; 36 | } 37 | }; -------------------------------------------------------------------------------- /C++/4. MedianOfTwoSortedArrays.cpp: -------------------------------------------------------------------------------- 1 | //a binary search approach to find the boundaries in both arrays at which the merged array has its middle. 2 | 3 | 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | double findMedianSortedArrays(vector& nums1, vector& nums2) { 10 | int m=nums1.size(); 11 | int n=nums2.size(); 12 | if(m>n) return findMedianSortedArrays(nums2,nums1); 13 | 14 | int start=0; 15 | int end=m; 16 | while(start<=end) { 17 | int i=start+(end-start)/2; 18 | int j=(m+n+1)/2-i; 19 | int min1=(i==m)?INT_MAX:nums1[i]; 20 | int min2=(j==n)?INT_MAX:nums2[j]; 21 | int max1=(i==0)?INT_MIN:nums1[i-1]; 22 | int max2=(j==0)?INT_MIN:nums2[j-1]; 23 | if(max1<=min2 && max2 <=min1) 24 | { 25 | if((m+n)%2==0) return (double)(max(max1,max2)+min(min1,min2))/2; 26 | else return (double)max(max1,max2); 27 | } 28 | else if(max1 > min2) end=i-1; 29 | else start=i+1; 30 | } 31 | return -1; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /C++/198. HouseRobber.cpp: -------------------------------------------------------------------------------- 1 | /*198. House Robber 2 | 3 | You are a professional robber planning to rob houses along a street. 4 | Each house has a certain amount of money stashed, the only constraint stopping 5 | you from robbing each of them is that adjacent houses have security system 6 | connected and it will automatically contact the police if two adjacent houses 7 | were broken into on the same night. 8 | 9 | Given a list of non-negative integers representing the amount of money of each 10 | house, determine the maximum amount of money you can rob tonight without 11 | alerting the police. 12 | 13 | For Example : 14 | 15 | Input: nums = [1,2,3,1] 16 | Output: 4 17 | Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). 18 | Total amount you can rob = 1 + 3 = 4. 19 | */ 20 | 21 | class Solution { 22 | public: 23 | int rob(vector& nums) { 24 | int odds = 0; 25 | int evens = 0; 26 | for (int i = 0; i < std::size(nums); i++) { 27 | if (i % 2) { 28 | evens += nums[i]; 29 | } else { 30 | odds += nums[i]; 31 | } 32 | } 33 | return std::max(odds, evens); 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /C++/48. RotateImage.cpp: -------------------------------------------------------------------------------- 1 | // Leetcode Problem 48 2 | 3 | // You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). 4 | // You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. 5 | // DO NOT allocate another 2D matrix and do the rotation. 6 | 7 | class Solution { 8 | public: 9 | void rotate(vector>& matrix) { 10 | 11 | //transpose of matrix 12 | for(int i=0; i& nums, int target) { 24 | int _size = nums.size(); 25 | int _left = 0; 26 | int _right = _size-1; 27 | 28 | int _middle; 29 | while(_left <= _right) 30 | { 31 | _middle = (_left+_right)/2; 32 | if(target > nums[_middle]) 33 | _left = _middle+1; 34 | else if(target < nums[_middle]) 35 | _right = _middle-1; 36 | else 37 | return _middle; 38 | } 39 | 40 | return -1; 41 | } 42 | }; -------------------------------------------------------------------------------- /C++/1304. FindNUniqueIntegersSumUpToZero.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Finding N Unique Integers Sum Up To Zero- 3 | Given an integer n, return any array containing n unique integers such that they add up to 0. 4 | 5 | Problem link- https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/ 6 | 7 | Approach- 8 | Include integers from 1 to n/2 and -1 to -n/2 into the vector 9 | If n is odd, include 0 into the vector as well. 10 | */ 11 | 12 | #include 13 | using namespace std; 14 | 15 | class Solution { 16 | public: 17 | vector sumZero(int n) { 18 | vector array(n,0); //declaring a vector of integers of sie n, with each element initialised to 0 19 | int counter=0; //counter variable will keep track of where the next element will be added 20 | 21 | for(int i=1;i<=n/2;i++) 22 | { 23 | array[counter]=i; 24 | counter++; 25 | } 26 | for(int i=-1;i>=-n/2;i--) 27 | { 28 | array[counter]=i; 29 | counter++; 30 | } 31 | 32 | return array; //since all elements were originally initialised to zero, the last element will already be 0 if n is odd 33 | } 34 | }; -------------------------------------------------------------------------------- /C++/89. GrayCode.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | The gray code is a binary numeral system where two successive values differ in only one bit. 3 | Given a non-negative integer n representing the total number of bits in the code, 4 | print the sequence of gray code. A gray code sequence must begin with 0. 5 | 6 | Example : 7 | Input: 2 8 | Output: [0,1,3,2] 9 | Explanation: 10 | 00 - 0 11 | 01 - 1 12 | 11 - 3 13 | 10 - 2 14 | 15 | */ 16 | 17 | #include 18 | using namespace std; 19 | 20 | class Solution { 21 | public: 22 | vector grayCode(int n) { 23 | vector ans(pow(2,n)); 24 | ans[0] = 0; 25 | for(int i = 1;i <= n;i++){ 26 | ans[pow(2,i)-1] = pow(2,i-1); 27 | } 28 | 29 | for(int i = 0;i & height) { 17 | int ptr1 = 0, ptr2 = height.size() - 1, maxi = 0; 18 | while(ptr1 < ptr2) { 19 | maxi = max(maxi, min(height[ptr1], height[ptr2]) * (ptr2 - ptr1)); 20 | if(height[ptr1] < height[ptr2]) ptr1++; 21 | else ptr2--; 22 | } 23 | return maxi; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Java/42. TrappingRainWater.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | /* 3 | 42. Trapping Rain Water 4 | 5 | Given n non-negative integers representing an elevation map where the width of each bar is 1, 6 | compute how much water it is able to trap after raining. 7 | 8 | Example: 9 | Input: [0,1,0,2,1,0,1,3,2,1,2,1] 10 | Output: 6 11 | */ 12 | 13 | public int trap(int[] heights) { 14 | int water = 0; 15 | int startMax = 0, endMax = 0; 16 | int start = 0, end = heights.length - 1; 17 | 18 | while(start < end) { 19 | if(heights[start] < heights[end]) { 20 | if(heights[start] > startMax) { 21 | startMax = heights[start]; 22 | } else { 23 | water += startMax - heights[start]; 24 | start++; 25 | } 26 | } 27 | else { 28 | if(heights[end] > endMax) { 29 | endMax = heights[end]; 30 | } else { 31 | water += endMax - heights[end]; 32 | end--; 33 | } 34 | } 35 | } 36 | 37 | return water; 38 | } 39 | } -------------------------------------------------------------------------------- /Python/118.PascalsTriangle.py: -------------------------------------------------------------------------------- 1 | # a function that receives a number a will create 2 | # a pascal triangle of that height 3 | 4 | 5 | class Solution(object): 6 | 7 | def PascalsTriangle(self, num): 8 | """ 9 | creates a two dimensional array holding a pascal triangle of 10 | the desired height 11 | :param num: int the height of the triangle 12 | :return: List[List[int]] a matrix of the pascal triangle 13 | """ 14 | 15 | # the base of the triangle 16 | return_triangle = [[1]] 17 | 18 | # keeps adding a layer 19 | for i in range(1, num): 20 | 21 | # creates a new line 22 | new_line = [] 23 | 24 | # beginning of line is always 1 25 | new_line.append(1) 26 | 27 | # middle of line gets filled by upper level 28 | for j in range(1, i): 29 | new_line.append(return_triangle[i - 1][j] + 30 | return_triangle[i - 1][j - 1]) 31 | 32 | # end of line 33 | new_line.append(1) 34 | 35 | # adds the line 36 | return_triangle.append(new_line) 37 | 38 | # returns the triangle 39 | return return_triangle 40 | -------------------------------------------------------------------------------- /C++/67. AddBinary.cpp: -------------------------------------------------------------------------------- 1 | // Problem - 67 Add Binary 2 | 3 | // Given two binary strings, return their sum (also a binary string). 4 | // The input strings are both non-empty and contains only characters 1 or 0. 5 | 6 | 7 | class Solution { 8 | public: 9 | string addBinary(string a, string b) { 10 | 11 | string answer; 12 | 13 | int i = a.length() - 1; 14 | int j = b.length() - 1; 15 | 16 | int carry = 0; 17 | while(i>=0 || j>=0) { // looping uptill the length of the larger number 18 | int sum = carry; 19 | if(i>=0) 20 | sum += a[i--] - '0'; 21 | if(j>=0) 22 | sum += b[j--] - '0'; 23 | 24 | carry = sum > 1 ? 1 : 0; // if sum > 1 carry is 1 otherwise 0 (because the base is 2) 25 | 26 | answer += to_string(sum%2); // appending the remainder of sum/2 to answer string 27 | } 28 | 29 | if(carry) 30 | answer += to_string(carry); // appending carry if any 31 | 32 | reverse(answer.begin(), answer.end()); // reversing the string to get required answer 33 | return answer; 34 | 35 | } 36 | }; -------------------------------------------------------------------------------- /Python/704. BinarySearch.py: -------------------------------------------------------------------------------- 1 | #Here first mid is calculated and then value at the index is compared with the value to be found. If there is match then the index at which the match occurs is returned. 2 | #If the value at the middle index is smaller than the value to be found we increase the variable low so as to search in the next half of the list. 3 | #If the value at the middle index is larger than the value to be found we decrease the variable high so as to search in the first half of the list. 4 | #This continues till the element is found, then index at which it is present is returned or low becomes more than high i.e value is not found hence -1 is returned 5 | class Solution(object): 6 | def search(self, nums, target): 7 | #Variable low points to first index, high points to the last 8 | low = 0 9 | high = len(nums) - 1 10 | #Loop will run till the low becomes more than high or value found 11 | while( low <= high ): 12 | mid = ( low + high )//2 13 | if( nums[mid] == target ): 14 | return mid 15 | elif( nums[mid] < target ): 16 | low = mid + 1 17 | else: 18 | high = mid - 1 19 | #If value not found return -1 20 | return -1 21 | -------------------------------------------------------------------------------- /Python/88.MergeSortedArray.py: -------------------------------------------------------------------------------- 1 | # Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one 2 | # sorted array. 3 | # 4 | # Note: 5 | # The number of elements initialized in nums1 and nums2 are m and n respectively. 6 | # You may assume that nums1 has enough space (size that is equal to m + n) to 7 | # hold additional elements from nums2. 8 | # Example: 9 | # 10 | # Input: 11 | # nums1 = [1,2,3,0,0,0], m = 3 12 | # nums2 = [2,5,6], n = 3 13 | # 14 | # Output: [1,2,2,3,5,6] 15 | # 16 | # 17 | # Constraints: 18 | # 19 | # -10^9 <= nums1[i], nums2[i] <= 10^9 20 | # nums1.length == m + n 21 | # nums2.length == n 22 | 23 | 24 | class Solution: 25 | def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: 26 | i = 0 27 | j = 0 28 | copy = nums1[:m] 29 | for k in range(m + n): 30 | if i < m and j < n: 31 | if copy[i] < nums2[j]: 32 | nums1[k] = copy[i] 33 | i = i + 1 34 | else: 35 | nums1[k] = nums2[j] 36 | j = j + 1 37 | elif i < m: 38 | nums1[k] = copy[i] 39 | i = i + 1 40 | else: 41 | nums1[k] = nums2[j] 42 | j += 1 43 | -------------------------------------------------------------------------------- /Java/1510.StoneGameIV.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | //In this program we are using dynamic programming 3 | // We are using this approach because we need to remember the outputs for lower cases also. 4 | public boolean winnerSquareGame(int n) { 5 | //Checking for the base cases 6 | if(n<=4){ 7 | if(n==1||n==3||n==4){ 8 | return true; 9 | }else{ 10 | return false; 11 | } 12 | } 13 | //Check if the given number has a perfect square root 14 | if(Math.sqrt(n)-(int)Math.sqrt(n)==0){ 15 | return true; 16 | } 17 | //Array to store values obtained for different cases 18 | //Performing dynamic programming 19 | boolean[] arr=new boolean[n]; 20 | arr[0]=true; 21 | arr[1]=false; 22 | arr[2]=true; 23 | arr[3]=true; 24 | for(int i=4;i &lists) { 19 | if (lists.empty()) { 20 | return nullptr; 21 | } 22 | while (lists.size() > 1) { 23 | lists.push_back(mergeTwoLists(lists[0], lists[1])); 24 | lists.erase(lists.begin()); 25 | lists.erase(lists.begin()); 26 | } 27 | return lists.front(); 28 | } 29 | ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { 30 | if (l1 == nullptr) { 31 | return l2; 32 | } 33 | if (l2 == nullptr) { 34 | return l1; 35 | } 36 | if (l1->val <= l2->val) { 37 | l1->next = mergeTwoLists(l1->next, l2); 38 | return l1; 39 | } 40 | else { 41 | l2->next = mergeTwoLists(l1, l2->next); 42 | return l2; 43 | } 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /C++/152. MaximumProductSubarray.cpp: -------------------------------------------------------------------------------- 1 | // Problem: 2 | // Given an integer array nums, find the contiguous subarray within an array 3 | // (containing at least one number) which has the largest product. 4 | 5 | // Approach: 6 | // Since we have to care about both positive and negative product, we will 7 | // store two running products i.e. max_product and min_product 8 | // containing maximum valued and minimum valued products respectively. 9 | 10 | // Now, if a negative number is encountered, swap both the products, 11 | // since the sign gets changed. Otherwise, find minimum valued and maximum 12 | // valued subarray products ending at that index as per the standard 13 | // Kadane's algorithm and update the "ans" variable accordingly at each index. 14 | 15 | class Solution { 16 | public: 17 | int maxProduct(vector& nums) { 18 | int n = nums.size(); 19 | int min_product, max_product, ans; 20 | min_product = max_product = ans = nums[0]; 21 | for (int i = 1; i < n; i++) 22 | { 23 | if (nums[i] < 0) 24 | swap(min_product, max_product); 25 | min_product = min(nums[i], nums[i] * min_product); 26 | max_product = max(nums[i], nums[i] * max_product); 27 | ans = max(ans, max_product); 28 | } 29 | return ans; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /C++/61. RotateList.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* rotateRight(ListNode* head, int k) { 14 | if(head==NULL) 15 | return NULL; 16 | int length=0; 17 | ListNode* temp=head; 18 | ListNode* lasts;//This is pointer pointing to the last node 19 | while(temp!=NULL) 20 | { 21 | if(temp->next==NULL) 22 | lasts=temp; 23 | length++; 24 | temp=temp->next; 25 | } 26 | k=k%length; 27 | if(k==0) 28 | return head; 29 | ListNode* slow=head; 30 | ListNode* fast=head; 31 | ListNode* rethead;//This is pointer for final head; 32 | for(int i=1;i<=k+1;i++) 33 | fast=fast->next; 34 | while(fast!=NULL) 35 | { 36 | slow=slow->next; 37 | fast=fast->next; 38 | } 39 | rethead=slow->next; 40 | slow->next=NULL; 41 | lasts->next=head; 42 | return rethead;//Returning final pointer 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /C++/87. ScrambleString.cpp: -------------------------------------------------------------------------------- 1 | 2 | //This is a programme to check if 2 strings are scrambled or not. It uses the concept of MCM. 3 | class Solution { 4 | public: 5 | unordered_mapmp; 6 | bool scramble(string s1,string s2) 7 | { 8 | 9 | if(s1==s2) 10 | return true; 11 | if(s1.length()<=1) 12 | return false; 13 | string key=s1+" "+s2; 14 | if(mp.find(key)!=mp.end()) 15 | return mp[key]; 16 | int n=s1.length(); 17 | 18 | bool flag=false; 19 | for(int i=1;i<=n-1;i++) 20 | { 21 | 22 | 23 | if((scramble(s1.substr(0,i),s2.substr(n-i,i)) && 24 | scramble(s1.substr(i,n-i),s2.substr(0,n-i)) )|| 25 | (scramble(s1.substr(0,i),s2.substr(0,i)) && 26 | scramble(s1.substr(i,n-i),s2.substr(i,n-i)) ) 27 | ) 28 | { flag=true; 29 | break; 30 | } 31 | } 32 | return mp[key]=flag; 33 | } 34 | bool isScramble(string s1, string s2) { 35 | if(s1.length()!=s2.length()) 36 | return false; 37 | if(s1.length()==0 && s2.length()==0) 38 | return true; 39 | mp.clear(); 40 | return scramble(s1,s2); 41 | 42 | 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /C++/1288. RemoveCoveredIntervals.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeCoveredIntervals(vector>& intervals) { 4 | //sorting the intervals on the basis of their starting points 5 | sort(intervals.begin(), intervals.end()); 6 | // count will store the number of redundant intervals 7 | int count = 0; 8 | vector curr = {-1, -1}; 9 | for(int i = 0; i < intervals.size(); i++) 10 | { 11 | /* 12 | Three cases now: 13 | 1. intervals[i] lies completely inside curr => count++ 14 | 2. curr lies completely inside intervals[i] => update curr and count++ 15 | 3. intervals[i] and curr overlap partially => update curr 16 | */ 17 | if(intervals[i][0] >= curr[0] && intervals[i][1] <= curr[1]) { 18 | count++; 19 | } 20 | else if(intervals[i][0] <= curr[0] && intervals[i][1] >= curr[1]) { 21 | count++; 22 | curr = {intervals[i][0], intervals[i][1]}; 23 | } 24 | else { 25 | curr = {intervals[i][0], intervals[i][1]}; 26 | } 27 | } 28 | // We have to return the number of non-redundant intervals 29 | return intervals.size() - count; 30 | } 31 | }; -------------------------------------------------------------------------------- /C++/202. HappyNumber.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This problem can be solved in the following steps: 3 | 0- create an empty list called history to hold the generated numbers 4 | 1- separate the number at hand to digits (EX: 439 -> {4,3,9}) 5 | 2- add the squares of the digits obtained from the first step. {EX: 4^2 + 3^2 + 9^2} 6 | 3- If the result in found in "history" return False, else: add it to "history" and return to step 1 7 | */ 8 | 9 | #include 10 | using namespace std; 11 | 12 | 13 | 14 | 15 | class Solution { 16 | public: 17 | vector history; 18 | vector separate(int n){ 19 | vector v; 20 | for(; n; n/=10) v.push_back(n%10); 21 | return v; 22 | } 23 | int add(vector v){ 24 | int result = 0; 25 | for (int a : v) result += (a*a); 26 | return result ; 27 | } 28 | bool check(int n){return n==1;} 29 | bool in_history(int n){ 30 | for(int a : history) if(n==a) return true; 31 | return false; 32 | } 33 | bool isHappy(int n) { 34 | 35 | while(true){ 36 | vector sep = separate(n); 37 | n = add(sep); 38 | if (in_history(n)) return false; 39 | else{ 40 | history.push_back(n); 41 | if(check(n)) return true; 42 | } 43 | } 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /C++/547. FriendCircles.cpp: -------------------------------------------------------------------------------- 1 | // Problem - 547. Friend Circles 2 | 3 | /* 4 | We will do this problem using DFS. So we will have a vector containing the visited friends 5 | with the variable name visited, it will initially contain all 0s and have a size of M. 6 | 7 | When we iterate through M, we check if we have visited that friend yet. If we have not, then we perform 8 | DFS on that friend and mark all of its friend as visited as well. If we have, then we continue iterating. 9 | 10 | Finally we will be able to find out how many friend circles are available in the matrix M. 11 | */ 12 | 13 | class Solution { 14 | public: 15 | void dfs(vector> &M, vector &visited, int currentFriend) { 16 | for (int i = 0; i < M.size(); i++) { 17 | if (M[i][currentFriend] == 1 && visited[i] == 0) { 18 | visited[i] = 1; 19 | dfs(M, visited, i); 20 | } 21 | } 22 | } 23 | 24 | int findCircleNum(vector> &M) { 25 | vector visited(M.size(), 0); 26 | int totalGroup = 0; 27 | for (int i = 0; i < M.size(); i++) { 28 | if (visited[i] == 0) { 29 | visited[i] = 1; 30 | totalGroup++; 31 | dfs(M, visited, i); 32 | } 33 | } 34 | return totalGroup; 35 | } 36 | }; -------------------------------------------------------------------------------- /C++/78. SubsetsOfAGivenArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | //helper will take the input array, the index or the position of the element on which we need to take the decision and the result vector of vectors 4 | void helper(vector&nums, int startIndex, vector>& res){ 5 | int n= nums.size(); 6 | //base case 7 | if (startIndex==n){ 8 | res.push_back({}); 9 | return; 10 | } 11 | //helper(ar,startIndex)= helper(ar,startIndex+1) U {nums[startIndex] U helper(ar.startIndex+1)} 12 | vector> subSol; 13 | helper(nums, startIndex+1, res); 14 | 15 | //exclude the startIndex 16 | subSol= res; 17 | 18 | //include the startIndex 19 | vector temp; 20 | for (int i=0;i> subsets(vector& nums) { 27 | vector> res; 28 | helper(nums,0,res); 29 | return res; 30 | } 31 | }; 32 | 33 | //================================= 34 | //Time complexity for the above algorithm asymptotically: O(2^n) where n is the size of the input array 35 | 36 | //Space complexity: O(n) because of the call stacks 37 | -------------------------------------------------------------------------------- /Java/2.Add Two Numbers.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 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 contains a single digit. Add the two numbers and return the sum as a linked list. 3 | * You may assume the two numbers do not contain any leading zero, except the number 0 itself. 4 | */ 5 | /** 6 | * Definition for singly-linked list. 7 | * public class ListNode { 8 | * int val; 9 | * ListNode next; 10 | * ListNode(int x) { val = x; } 11 | * } 12 | */ 13 | class Solution { 14 | // O(n) O(n) 15 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 16 | ListNode dummy = new ListNode(0); 17 | int sum = 0; 18 | ListNode cur = dummy; 19 | ListNode p1 = l1, p2 = l2; 20 | while (p1 != null || p2 != null) { 21 | if (p1 != null) { 22 | sum += p1.val; 23 | p1 = p1.next; 24 | } 25 | if (p2 != null) { 26 | sum += p2.val; 27 | p2 = p2.next; 28 | } 29 | cur.next = new ListNode(sum % 10); 30 | sum /= 10; 31 | cur = cur.next; 32 | } 33 | if (sum == 1) { 34 | cur.next = new ListNode(1); 35 | } 36 | return dummy.next; 37 | 38 | 39 | } 40 | } -------------------------------------------------------------------------------- /Java/224.BasicCalculator.java: -------------------------------------------------------------------------------- 1 | /** 2 | *Implement a basic calculator to evaluate a simple expression string. 3 | *The expression string may contain open ( and closing parentheses ), the plus + or minus *sign -, non-negative integers and empty spaces . 4 | */ 5 | 6 | class Solution { 7 | // O(n) O(n) 8 | public int calculate(String s) { 9 | if (s == null || s.length() == 0) return 0; 10 | Stack stack = new Stack<>(); 11 | int sign = 1; 12 | int res = 0; 13 | for (int i = 0; i < s.length(); i++) { 14 | if (Character.isDigit(s.charAt(i))) { 15 | int num = s.charAt(i) - '0'; 16 | while (i + 1 < s.length() && Character.isDigit(s.charAt(i + 1))) { 17 | num = num * 10 + s.charAt(++i) - '0'; 18 | } 19 | res += num * sign; 20 | } else if (s.charAt(i) == '+') { 21 | sign = 1; 22 | } else if (s.charAt(i) == '-') { 23 | sign = -1; 24 | } else if (s.charAt(i) == '(') { 25 | stack.push(res); 26 | stack.push(sign); 27 | res = 0; 28 | sign = 1; 29 | } else if (s.charAt(i) == ')') { 30 | res = res * stack.pop() + stack.pop(); 31 | } 32 | } 33 | return res; 34 | } 35 | } -------------------------------------------------------------------------------- /C++/232. Implement Queue Using Stacks.cpp: -------------------------------------------------------------------------------- 1 | /* program name :- Implement Queue Using Stacks.cpp 2 | this program is done by enqueue. 3 | description is given before the functions 4 | */ 5 | 6 | 7 | using namespace std; 8 | 9 | struct Queue { 10 | stack s1, s2; 11 | 12 | void enQueue(int x) 13 | { 14 | // Move all elements from s1 to s2 15 | while (!s1.empty()) { 16 | s2.push(s1.top()); 17 | s1.pop(); 18 | } 19 | 20 | // Push item into s1 21 | s1.push(x); 22 | 23 | // Push everything back to s1 24 | while (!s2.empty()) { 25 | s1.push(s2.top()); 26 | s2.pop(); 27 | } 28 | } 29 | 30 | // Dequeue an item from the queue 31 | int deQueue() 32 | { 33 | // if first stack is empty 34 | if (s1.empty()) { 35 | cout << "Q is Empty"; 36 | exit(0); 37 | } 38 | 39 | // Return top of s1 40 | int x = s1.top(); 41 | s1.pop(); 42 | return x; 43 | } 44 | }; 45 | 46 | // Driver code 47 | int main() 48 | { 49 | Queue q; 50 | q.enQueue(1); 51 | q.enQueue(2); 52 | q.enQueue(3); 53 | 54 | cout << q.deQueue() << '\n'; 55 | cout << q.deQueue() << '\n'; 56 | cout << q.deQueue() << '\n'; 57 | 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /Python/1289.MatrixSpiral.py: -------------------------------------------------------------------------------- 1 | """This program takes a matrix of size mxn as input, and prints the matrix in a spiral format 2 | for example: input ->> [[1,2,3], 3 | [4,5,6], 4 | [7,8,9], 5 | [10,11,12]] 6 | output ->> 1 2 3 6 9 12 11 10 7 4 5 8""" 7 | 8 | 9 | class Solution: 10 | def matrix_spiral(self, matrix): 11 | """ 12 | :type matrix: list[list[]] 13 | """ 14 | 15 | starting_row = 0 16 | ending_row = len(matrix) 17 | starting_col = 0 18 | ending_col = len(matrix[0]) 19 | while starting_row < ending_row and starting_col < ending_col: 20 | for k in range(starting_col, ending_col): 21 | print(matrix[starting_row][k], end=" ") 22 | starting_row += 1 23 | for k in range(starting_row, ending_row): 24 | print(matrix[k][ending_col-1], end=" ") 25 | ending_col -= 1 26 | if starting_row < ending_row: 27 | for k in range(ending_col-1, starting_col-1, -1): 28 | print(matrix[ending_row-1][k], end=" ") 29 | ending_row -= 1 30 | if starting_col < ending_col: 31 | for k in range(ending_row-1, starting_row-1, -1): 32 | print(matrix[k][starting_col], end=" ") 33 | starting_col += 1 34 | -------------------------------------------------------------------------------- /C++/733. FloodFill.cpp: -------------------------------------------------------------------------------- 1 | /*Description of FloodFill algorithm - We are given an image(2d vector) and starting pixel we have to change the colour of the starting pixel, 2 | plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 3 | 4-directionally to those pixels (also with the same color as the starting pixel), and so on to the new colour which is given in the input.*/ 4 | 5 | class Solution { 6 | public: 7 | 8 | bool vis[55][55]; // Visited array 9 | 10 | int dx[4]={-1,0,0,1}; 11 | int dy[4]={0,1,-1,0}; // All the four directions to perform the dfs in the image 12 | 13 | void dfs(int x,int y,int newColor,vector>& image,int c){ 14 | vis[x][y]=1; 15 | int n=image.size(); 16 | int m=image[0].size(); 17 | for(int i=0;i<4;i++){ 18 | int e=x+dx[i]; 19 | int f=y+dy[i]; 20 | if(e>=0 && e=0 && f> floodFill(vector>& image, int sr, int sc, int newColor) { 30 | memset(vis,0,sizeof vis); 31 | dfs(sr,sc,newColor,image,image[sr][sc]); 32 | return image; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /C++/41. FirstMissingPositive.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int firstMissingPositive(vector& nums) { 4 | /* 5 | Our goal is to add every element of nums in its correct place and then find the smallest number that's not present in its place. 6 | eg. nums = [2, 1, 4] 7 | Explanation: 8 | According to the following algorithm, we check for each element of nums: 9 | 2 -> 1st place in the array. Therefore, we swap 2 with 1. 10 | Update: nums = [1, 2, 4] 11 | 2 -> 2nd place in the array 12 | 4 -> 4 > nums.size() (i.e. 3). Therefore, we skip. 13 | Now, we traverse the array again and return the smallest element that is not in its correct place. 14 | */ 15 | 16 | //Base case 17 | if(nums.size() == 0) return 1; 18 | 19 | // Goal: To put each number in its right index. If the number > nums.size(), leave it be. 20 | for(int i = 0; i < nums.size(); i++){ 21 | while(nums[i] > 0 && nums[i] <= nums.size() && nums[nums[i] - 1] != nums[i]) 22 | swap(nums[i], nums[nums[i]-1]); 23 | } 24 | 25 | //Finally, identify the smallest number that is out of place. 26 | for(int i = 0; i < nums.size(); i++){ 27 | if(nums[i] != i+1) return i+1; 28 | } 29 | return nums.size() + 1; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /C++/771. JewelsandStones.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 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. 3 | 4 | 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". 5 | 6 | Example 1: 7 | 8 | Input: J = "aA", S = "aAAbbbb" 9 | Output: 3 10 | Example 2: 11 | 12 | Input: J = "z", S = "ZZ" 13 | Output: 0 14 | 15 | Note: 16 | S and J will consist of letters and have length at most 50. 17 | The characters in J are distinct. 18 | */ 19 | 20 | class Solution { 21 | public: 22 | int numJewelsInStones(string J, string S) { 23 | 24 | // creating an unordered set 25 | unordered_set hash_set; 26 | int count=0; 27 | 28 | //iterating through string J and adding it to the hash_set 29 | for ( int i=0;i 5 | Input: s = "babad" 6 | Output: "bab" 7 | Note: "aba" is also a valid answer. 8 | */ 9 | 10 | class Solution{ 11 | public String longestPalindrome(String s) { 12 | int n = s.length(); 13 | if(n == 0) return ""; 14 | 15 | boolean[][] dp = new boolean[n][n]; 16 | 17 | int maxSoFar = 0; 18 | String ans = ""; 19 | 20 | for(int gap = 0;gap maxSoFar){ 35 | maxSoFar = ep-sp+1; 36 | ans = s.substring(sp,ep+1); 37 | } 38 | } 39 | sp++; ep++; 40 | } 41 | } 42 | return ans; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /C++/1029. TwoCityScheduling.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Two City Scheduling- A company is planning to interview 2n people. Given the array costs where 3 | costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of 4 | flying the ith person to city b is bCosti. 5 | 6 | Return the minimum cost to fly every person to a city such that exactly n people arrive in each city.*/ 7 | 8 | /* 9 | Approach- We will sort the array in the increasing order of differences(v[i][0]-v[i][1]) between the 10 | first element and the second element of the row and then assign first n values(v[i][0]) of the sorted 11 | array to first city and latter n values(v[i][1]) to second city thus this will minimise the total cost.*/ 12 | 13 | class Solution { 14 | public: 15 | 16 | static bool cmp(vector &a,vector &b){ 17 | return (a[0]-a[1])<(b[0]-b[1]); // A comparator to sort according to the differences 18 | } 19 | 20 | int twoCitySchedCost(vector>& costs) { 21 | sort(costs.begin(),costs.end(),cmp); //sorting the costs in increasing order of differences 22 | int sum=0; 23 | for(int i=0;i (1, 2) 13 | (1, 2) -> (3, 2) 14 | (3, 2) -> (3, 5) 15 | 16 | Input: sx = 1, sy = 1, tx = 2, ty = 2 17 | Output: False 18 | 19 | Input: sx = 1, sy = 1, tx = 1, ty = 1 20 | Output: True 21 | 22 | */ 23 | class Solution { 24 | public: 25 | bool reachingPoints(int sx, int sy, int tx, int ty) { 26 | 27 | // if the initial coordinates are equal then the points can be reached 28 | if (tx == ty) return sx == sy && sx == tx; 29 | 30 | // 31 | while (sx != tx || sy != ty) { 32 | 33 | // this cannot be possible if the points can be reached , hence returning false 34 | if (tx < sx || ty < sy) return false; 35 | 36 | // subtracting and traversing ahead 37 | if (tx > ty) tx -= max((tx-sx)/ty, 1) * ty; 38 | else ty -= max((ty-sy)/tx, 1) * tx; 39 | } 40 | 41 | // if the above loop completed , without returning , that means that the points can be reached. Hence , we return true 42 | return true; 43 | 44 | } 45 | }; -------------------------------------------------------------------------------- /Java/516. Longest Palindromic Subsequence.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Question: 3 | * Given a string s, find the longest palindromic subsequence's length in s. 4 | * You may assume that the maximum length of s is 1000. 5 | *

6 | * Example: 7 | * Input: "bbbab" 8 | * Output: 4 9 | * One possible longest palindromic subsequence is "bbbb". 10 | *

11 | * Example: 12 | * Input: "cbbd" 13 | * Output: 2 14 | * One possible longest palindromic subsequence is "bb". 15 | *

16 | * Constraints: 17 | * 1 <= s.length <= 1000 18 | * s consists only of lowercase English letters. 19 | */ 20 | 21 | class Solution { 22 | public int longestPalindromeSubseq(String s) { 23 | // Reverse of the string 24 | String reverseOfString = new StringBuilder(s).reverse().toString(); 25 | int length = s.length(); 26 | // Cost matrix to store cost 27 | int[][] cost = new int[length+1][length+1]; 28 | 29 | // Compare string with its reverse to check for the palindrome 30 | for(int i = 1; i <= length; i++) { 31 | for(int j = 1; j <= length; j++) { 32 | if (reverseOfString.charAt(i-1) == s.charAt(j-1)) { 33 | cost[i][j] = cost[i-1][j-1] + 1; 34 | } else if (cost[i-1][j] >= cost[i][j-1]) { 35 | cost[i][j] = cost[i-1][j]; 36 | } else { 37 | cost[i][j] = cost[i][j-1]; 38 | } 39 | } 40 | } 41 | 42 | return cost[length][length]; 43 | } 44 | } -------------------------------------------------------------------------------- /Java/941. ValidMountainArray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public boolean checkASC(int[] A, int e){ 4 | boolean result=false; 5 | int prev=A[0]; 6 | for(int i=1;i<=e;i++){ 7 | if(prev>=A[i]){ 8 | result=false; 9 | break; 10 | }else{ 11 | result=true; 12 | } 13 | prev=A[i]; 14 | } 15 | return result; 16 | } 17 | 18 | public boolean checkDESC(int[] A, int s, int e){ 19 | boolean result=false; 20 | int prev=A[s]; 21 | if(e-s==1){ 22 | result=true; 23 | } 24 | for(int i=s+1;i=3){ 42 | prev=A[0]; 43 | for(int i=1;iA[i]){ 45 | peak=i-1; 46 | break; 47 | } 48 | prev=A[i]; 49 | } 50 | 51 | isMountain=(checkASC(A,peak) && checkDESC(A,peak+1,len)); 52 | 53 | } 54 | 55 | return isMountain; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /C++/142. LinkedListCycle.cpp: -------------------------------------------------------------------------------- 1 | //Given a linked list, return the node where the cycle begins. If there is no cycle, return null. 2 | //There is a cycle in a linked list if there is some node in the list that can be reached again 3 | //by continuously following the next pointer. 4 | 5 | //C++ code to detect the cycle and find the node where the cycle begins in the linked list 6 | //It uses floyd's cycle finding algorithm 7 | //It contains an O(1) solution to detect cycle in a linked list and return the node where the cycle starts 8 | 9 | //Definition for LinkedList node 10 | struct node 11 | { 12 | int val; 13 | node *next; 14 | node(int x) 15 | { 16 | val=x; 17 | next=nullptr; 18 | } 19 | }; 20 | 21 | class Solution 22 | { 23 | public: 24 | node *detectCycle(node *head) 25 | { 26 | node *slow,*fast; 27 | bool flag=1; 28 | if(head==NULL) 29 | return NULL; 30 | slow=head; 31 | fast=head; 32 | while(slow and fast and fast->next) 33 | { 34 | slow=slow->next; 35 | fast=fast->next->next; 36 | if(slow==fast) 37 | { 38 | flag=0;break; 39 | } 40 | } 41 | if(!flag) 42 | { 43 | slow=head; 44 | while(slow!=fast) 45 | { 46 | slow=slow->next; 47 | fast=fast->next; 48 | } 49 | return slow; 50 | } 51 | else 52 | { 53 | return NULL; 54 | } 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /Java/477. Total Hamming Distance.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Question: 3 | * The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 4 | *

5 | * Now your job is to find the total Hamming distance between all pairs of the given numbers. 6 | *

7 | * Example: 8 | *

9 | * Input: 4, 14, 2 10 | * Output: 6 11 | * Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just 12 | * showing the four bits relevant in this case). So the answer will be: 13 | * HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. 14 | *

15 | * Note: 16 | * 1. Elements of the given array are in the range of 0 to 10^9 17 | * 2. Length of the array will not exceed 10^4. 18 | */ 19 | class Solution { 20 | public int totalHammingDistance(int[] nums) { 21 | int totalHDistance = 0; 22 | int noOfOne; 23 | int noOfZero; 24 | int arrayLength = nums.length; 25 | 26 | // Iterate over each bit 27 | for (int i = 0 ; i < 32 ; ++i) { 28 | noOfOne = 0; 29 | noOfZero = 0; 30 | // Iterate over each array element 31 | for (int j = 0 ; j < arrayLength ; ++j) { 32 | if ((nums[j] & (1 << i)) == (1 << i)) { 33 | ++noOfOne; 34 | } else { 35 | ++noOfZero; 36 | } 37 | } 38 | totalHDistance += noOfOne * noOfZero; 39 | } 40 | return totalHDistance; 41 | } 42 | } -------------------------------------------------------------------------------- /Python/44. WildcardMatching.py: -------------------------------------------------------------------------------- 1 | # Wildcard Matching. 2 | 3 | ''' 4 | Python program to implement Wildcard Matching Algorithm. 5 | ' s ' is the input string and ' p ' is the Wildcard pattern. 6 | 7 | Function matches input string 's' with the given pattern 'p', 8 | and return True if matches otherwise False. 9 | ''' 10 | # Dynamic Programming Approach. 11 | 12 | class Solution(object): 13 | def isMatch(self,s ,p) -> bool: 14 | s_len = len(s) 15 | p_len = len(p) 16 | 17 | if (p_len == 0): 18 | return (s_len == 0) # For empty pattern 19 | 20 | dp = [[False for i in range(p_len + 1)] for j in range(s_len + 1)] # DP matrix for storing results of subproblems 21 | dp[0][0] = True 22 | 23 | for i in range(1,p_len + 1): 24 | if p[i - 1] == '*': 25 | dp[0][i] = dp[0][i-1] 26 | 27 | for i in range(1, s_len + 1): 28 | for j in range(1, p_len + 1): 29 | if s[i - 1] == p[j - 1] or p[j - 1] == '?': 30 | dp[i][j] = dp[i-1][j-1] 31 | 32 | elif p[j - 1] == '*': 33 | dp[i][j] = max(dp[i-1][j], dp[i][j-1]) 34 | 35 | else : 36 | dp[i][j] = False 37 | 38 | return dp[s_len][p_len] 39 | 40 | ''' 41 | s = input('string -> ') 42 | p = input('pattern -> ') 43 | 44 | wildcard_match = Solution() 45 | 46 | print(wildcard_match.isMatch(s,p)) 47 | ''' 48 | -------------------------------------------------------------------------------- /C++/322. CoinChange.cpp: -------------------------------------------------------------------------------- 1 | """ 2 | Problem Statement: 3 | You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. 4 | If that amount of money cannot be made up by any combination of the coins, return -1. 5 | You may assume that you have an infinite number of each kind of coin. 6 | Sample Input: 7 | coins = [1,2,5], amount = 11 8 | Output : 3 9 | Explanation : 11 = 5 + 5 + 1 10 | """ 11 | 12 | class Solution { 13 | public: 14 | int coinChange(vector& coins, int amount) { 15 | int t[coins.size()+1][amount+1]; 16 | for(int i=0;i<=coins.size();i++){ 17 | t[i][0] = 0;//If the amount of money, we require no coin to distribute it. So, the answer is 0. 18 | } 19 | for(int i=0;i<=amount;i++){ 20 | t[0][i] = INT_MAX-1;//If the amount of money is non-zero and we do not have any coins of a particular denomination,we can't partition it, in other words,there will be infinite number of coins required. 21 | } 22 | for(int i=1;i<=coins.size();i++){ 23 | for(int j=1;j<=amount;j++){ 24 | if(coins[i-1]<=j){//If we can use that coin 25 | t[i][j] = min(1+t[i][j-coins[i-1]],t[i-1][j]); 26 | }else{//If we cannot use it 27 | t[i][j] = t[i-1][j]; 28 | } 29 | } 30 | } 31 | return (t[coins.size()][amount] >= 2147483646)?-1:t[coins.size()][amount]; 32 | } 33 | }; -------------------------------------------------------------------------------- /C++/1108. DefangingAnIPAddress.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Defanging an IP Address- 3 | Given a valid (IPv4) IP address, return a defanged version of that IP address. 4 | A defanged IP address replaces every period "." with "[.]". 5 | 6 | Problem link- https://leetcode.com/problems/defanging-an-ip-address/ 7 | 8 | Approach- 9 | Traversing through the string, and adding a [ to the defanged IP Address everytime a . is encountered 10 | A ] is added after adding the . 11 | */ 12 | 13 | #incldue 14 | using namespace std; 15 | 16 | class Solution { 17 | public: 18 | 19 | string defangIPAddress(string IPAddress) 20 | { 21 | string defangedIPAddress; 22 | 23 | int currentPosition=0; //This variable will keep track of the position where the next character has to be added in defangedIPAddress 24 | for(int i=0;IPAddress[i]!='\0';i++) 25 | { 26 | if(IPAddress[i]=='.') //converts . to [.] in the string defangedIPAddress 27 | { 28 | defangedIPAddress[currentPosition]='['; 29 | currentPosition++; 30 | defangedIPAddress[currentPosition]='.'; 31 | currentPosition++; 32 | defangedIPAddress[currentPosition]=']'; 33 | currentPosition++; 34 | } 35 | else 36 | { 37 | defangedIPAddress[currentPosition]=IPAddress[i]; //copies every number from IPAddress to defangedIPAddress 38 | currentPosition++; 39 | } 40 | } 41 | return defangedIPAddress; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /C++/992. Subarrays with K Different Integers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | https://leetcode.com/problems/subarrays-with-k-different-integers/submissions/ 3 | 4 | We use a different problem to solve this. We find the number of substrings with atmost 5 | K unique chars. 6 | substrings with exactly k = atmost unique (K) - atmost unique (K-1) 7 | This diff only leaves the substrings with exactly k unique chars 8 | */ 9 | class Solution { 10 | public: 11 | // Finds the substring with atmost K unique chars 12 | int atmostK(vector& arr, int K) { 13 | int i = 0, j = 0, substrings = 0; 14 | unordered_map freq; 15 | const int N = arr.size(); 16 | 17 | while(i < N) { 18 | // Expand the window 19 | if(K >= 0) { 20 | ++freq[arr[i]]; 21 | if(freq[arr[i]] == 1) 22 | --K; 23 | ++i; 24 | } 25 | // make the window valid 26 | while(K < 0) { 27 | --freq[arr[j]]; 28 | if(freq[arr[j]] == 0) 29 | ++K; 30 | ++j; 31 | } 32 | // Each valid window adds the subarrays which satisfies the condition 33 | // For : 1,2,1, k=2 34 | // 1: [1] 35 | // 2: [2], [1,2] 36 | // 3: [1,2], [2,1], [1,2,1] 37 | substrings += i - j + 1; 38 | } 39 | return substrings; 40 | } 41 | 42 | int subarraysWithKDistinct(vector& arr, int K) { 43 | return atmostK(arr, K) - atmostK(arr, K-1); 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /C++/54. SpiralMatrix.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/spiral-matrix/ 2 | // Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. 3 | 4 | /* Sample input : 5 | [ 6 | [ 1, 2, 3 ], 7 | [ 4, 5, 6 ], 8 | [ 7, 8, 9 ] 9 | ] 10 | 11 | Sample output : 12 | [1,2,3,6,9,8,7,4,5] 13 | */ 14 | 15 | class Solution { 16 | public: 17 | vector spiralOrder(vector>& matrix) { 18 | 19 | //number of rows 20 | int m = matrix.size(); 21 | 22 | vectorv; 23 | 24 | if(m==0)return v; 25 | 26 | //number of cols 27 | int n = matrix[0].size(); 28 | 29 | int i = 0; 30 | int j = 0; 31 | 32 | //loop to print in spiral fashion 33 | while(i= j; l--) 49 | { 50 | v.push_back(matrix[m-1][l]); 51 | } 52 | m--; 53 | 54 | 55 | for(int r = m-1; r >=i; r--) 56 | { 57 | v.push_back(matrix[r][j]); 58 | } 59 | j++; 60 | } 61 | 62 | } 63 | return v; 64 | } 65 | }; -------------------------------------------------------------------------------- /C++/326. PowerOfThree.cpp: -------------------------------------------------------------------------------- 1 | 2 | /*** 3 | Given an integer, write a function to determine if it is a power of three. 4 | 5 | here we write a function for the solution. 6 | ***/ 7 | 8 | class Solution { 9 | 10 | public: 11 | 12 | bool isPowerOfThree(int n) { 13 | return isPowerOfThree03(n); //140ms 14 | return isPowerOfThree02(n);//130ms 15 | return isPowerOfThree01(n); //140ms 16 | return isPowerOfThree_loop(n); //136ms 17 | return isPowerOfThree_recursive(n); //168ms 18 | } 19 | 20 | bool isPowerOfThree03(int n) { 21 | double logRes = log10(n)/log10(3); 22 | return (logRes - int(logRes) == 0); 23 | } 24 | bool isPowerOfThree02(int n) { 25 | return n>0 ? (1162261467%n==0) : false; 26 | } 27 | 28 | void init(unordered_map& power ){ 29 | int p = 1; 30 | power[1]=true; 31 | while(1){ 32 | p *= 3; 33 | power[p] = true; 34 | if (p > INT_MAX/3) break; 35 | 36 | } 37 | } 38 | bool isPowerOfThree01(int n) { 39 | static unordered_map power; 40 | if (power.size()==0) init(power); 41 | return power.find(n) != power.end(); 42 | } 43 | 44 | bool isPowerOfThree_loop(int n) { 45 | for(;n>0;n /= 3){ 46 | if (n==1 || n==3) return true; 47 | if (n%3 != 0) return false; 48 | } 49 | return false; 50 | } 51 | 52 | bool isPowerOfThree_recursive(int n) { 53 | if ( n == 1 || n == 3) return true; 54 | if ( n==0 || n%3 != 0 ) return false; 55 | return isPowerOfThree_recursive(n/3); 56 | } 57 | }; 58 | -------------------------------------------------------------------------------- /C++/36. ValidSudoku.cpp: -------------------------------------------------------------------------------- 1 | // Check whether the given sudoku board is valid or not 2 | 3 | class Solution { 4 | public: 5 | bool isValidSudoku(vector>& board) { 6 | // main function to iterate over the board 7 | 8 | int size=board.size(); 9 | 10 | // iterate over the board 11 | for(int i=0;i>&board,int row,int col,char ch,int size){ 26 | // checking row 27 | for(int k=0;k &nums) { 16 | 17 | // initialising a has_set to store the values that we have already seen 18 | unordered_set hash_set; 19 | 20 | // the final resul that we have to return 21 | int largest_sequence = 0; 22 | 23 | // going through vector and storing the values in the hash set 24 | for (int i = 0; i < nums.size(); i++) 25 | hash_set.insert(nums[i]); 26 | 27 | // going through the vector again and computing the sequence 28 | for (int i = 0; i < nums.size(); i++) { 29 | int current_num = nums[i]; 30 | int short_sequence = 1; 31 | 32 | // finding if the current_num +1 and curent_num -1 are present in the hash set or not 33 | if (hash_set.find(current_num - 1) == hash_set.end()) { 34 | while (hash_set.find(current_num + 1) != hash_set.end()) { 35 | current_num++; 36 | short_sequence++; 37 | } 38 | } 39 | 40 | //finding the maximum between the local sequence and the global sequence 41 | largest_sequence = max(largest_sequence, short_sequence); 42 | 43 | } 44 | 45 | 46 | //returning the largest_sequences 47 | return largest_sequence; 48 | 49 | } 50 | }; -------------------------------------------------------------------------------- /Java/1395. Count number of teams.java: -------------------------------------------------------------------------------- 1 | /** 2 | * The goal is to find the total number of valid teams. A team is valid if the player rating is in either direction ascending. 3 | */ 4 | class Solution { 5 | int totalInc = 0; 6 | int totalDec = 0; 7 | 8 | public void numTeamsInc(int[] rating, int idx, int count) { 9 | for (int i = idx + 1; i < rating.length; i++) { 10 | if (rating[idx] > rating[i]) { 11 | /** 12 | * If we have already have two, we found a third one, which means we found a valid team and don't need to go further. 13 | */ 14 | if (count == 2) { 15 | totalInc++; 16 | } else { 17 | numTeamsInc(rating, i, count + 1); 18 | } 19 | } 20 | } 21 | } 22 | 23 | public void numTeamsDec(int[] rating, int idx, int count) { 24 | for (int i = idx + 1; i < rating.length; i++) { 25 | if (rating[idx] < rating[i]) { 26 | /** 27 | * If we have already have two, we found a third one, which means we found a valid team and don't need to go further. 28 | */ 29 | if (count == 2) { 30 | totalDec++; 31 | } else { 32 | numTeamsDec(rating, i, count + 1); 33 | } 34 | } 35 | } 36 | } 37 | 38 | public int numTeams(int[] rating) { 39 | if (rating == null || rating.length == 0) return 0; 40 | 41 | for (int i = 0; i < rating.length - 1; i++) { 42 | numTeamsInc(rating, i, 1); 43 | numTeamsDec(rating, i, 1); 44 | } 45 | 46 | return totalInc + totalDec; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /C++/199. BinaryTreeRightSideView.cpp: -------------------------------------------------------------------------------- 1 | // Problem - 199. Binary Tree Right Side View 2 | 3 | /* 4 | First we need to know what is the depth of the tree. 5 | Once we know the depth of the tree, we can initialize a vector of that size. 6 | Then we recursively add the rightmost element in every tree to that vector. 7 | Note that it will always change the value in every iteration, but it does not matter 8 | since the last one (rightmost one) will be assigned on top of it all. 9 | Finally return the vector which contains the right side view of the binary tree. 10 | */ 11 | 12 | class Solution { 13 | public: 14 | void checkRight(vector &right, TreeNode *currNode, int curr) { 15 | if (currNode == NULL) { 16 | return; 17 | } 18 | right[curr] = currNode->val; 19 | checkRight(right, currNode->left, curr + 1); 20 | checkRight(right, currNode->right, curr + 1); 21 | } 22 | 23 | int treeSize(TreeNode *node) { 24 | if (node == NULL) { 25 | return 0; 26 | } else { 27 | /* compute the depth of each subtree */ 28 | int lDepth = treeSize(node->left); 29 | int rDepth = treeSize(node->right); 30 | 31 | if (lDepth > rDepth) { 32 | return (lDepth + 1); 33 | } else { 34 | return (rDepth + 1); 35 | } 36 | } 37 | } 38 | 39 | vector rightSideView(TreeNode *root) { 40 | int n = treeSize(root); 41 | vector right(n, 0); 42 | if (root == NULL) { 43 | return right; 44 | } 45 | right[0] = root->val; 46 | checkRight(right, root->left, 1); 47 | checkRight(right, root->right, 1); 48 | return right; 49 | } 50 | }; -------------------------------------------------------------------------------- /Java/23. MergeKSortedLists.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | class Solution { 10 | /* 11 | 23. Merge K Sorted lists 12 | 13 | You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. 14 | Merge all the linked-lists into one sorted linked-list and return it. 15 | 16 | Input: lists = [[1,4,5],[1,3,4],[2,6]] 17 | Output: [1,1,2,3,4,4,5,6] 18 | Explanation: The linked-lists are: 19 | [ 20 | 1->4->5, 21 | 1->3->4, 22 | 2->6 23 | ] 24 | merging them into one sorted list: 25 | 1->1->2->3->4->4->5->6 26 | */ 27 | 28 | /* 29 | This code works by first adding all the values 30 | from the lists to a single list and then sorting 31 | those values and using them to create a new ListNode 32 | with sorted values 33 | 34 | Time complexity: O(nlogn) 35 | Space complexity: O(n) 36 | */ 37 | public ListNode mergeKLists(ListNode[] lists) { 38 | ListNode head = new ListNode(-1); 39 | List list = new ArrayList<>(); 40 | ListNode current = head; 41 | 42 | for(ListNode first : lists){ 43 | while(first != null){ 44 | list.add(first.val); 45 | first = first.next; 46 | } 47 | } 48 | 49 | Collections.sort(list); 50 | int i = 0; 51 | while(i != list.size()){ 52 | current.next = new ListNode(list.get(i)); 53 | current = current.next; 54 | i++; 55 | } 56 | 57 | return head.next; 58 | } 59 | } -------------------------------------------------------------------------------- /Python/42.TrappingRainWater.py: -------------------------------------------------------------------------------- 1 | ''' 2 | LeetCode Link: https://leetcode.com/problems/trapping-rain-water 3 | 4 | Given n non-negative integers representing an elevation map where the width of each bar is 1, 5 | compute how much water it is able to trap after raining. 6 | 7 | The elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. 8 | In this case, 6 units of rain water (blue section) are being trapped. 9 | 10 | Example: 11 | 12 | Input: [0,1,0,2,1,0,1,3,2,1,2,1] 13 | Output: 6 14 | 15 | Solution: 16 | Search from left to right and maintain a max height of left and right separately, 17 | Consider this as one-side wall of partial container. Fix the higher one and flow water from the lower part. 18 | For example, if current height of left is lower, we fill water in the left bin. 19 | We will do this until left meets right or we filled the whole container. 20 | 21 | Time Complexity: O(n) 22 | Space Complexity: O(1) 23 | 24 | ''' 25 | 26 | class Solution: 27 | def trap(self, heights: List[int]) -> int: 28 | water = 0 29 | leftMaxHeight = 0 30 | rightMaxHeight = 0 31 | start = 0 32 | end = len(heights) - 1 33 | 34 | while start < end: 35 | if heights[start] < heights[end]: 36 | if heights[start] > leftMaxHeight: 37 | leftMaxHeight = heights[start] 38 | else: 39 | water += leftMaxHeight - heights[start] 40 | start+=1 41 | else: 42 | if heights[end] > rightMaxHeight: 43 | rightMaxHeight = heights[end] 44 | else: 45 | water += rightMaxHeight - heights[end] 46 | end-=1 47 | return water -------------------------------------------------------------------------------- /C++/49. Group_Anagrams.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | File : Group_Anagrams.cpp 3 | The solution involves 2 steps: 4 | 5 | Sort the element and make it as the key. 6 | Take the value and place it in the key. 7 | */ 8 | 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | vector > groupAnagrams(vector& input_set) 15 | { 16 | // the first value will hold the key, the second vector is used to hold the multiple values. 17 | unordered_map > my_map; 18 | vector > final_set; 19 | 20 | for (int i = 0; i < input_set.size(); i++) 21 | { 22 | // take value at the index as a key 23 | string key = input_set[i]; 24 | 25 | //sort the key 26 | sort(key.begin(), key.end()); 27 | 28 | // add the value to that key 29 | my_map[key].push_back(input_set[i]); 30 | 31 | } 32 | 33 | for (auto n : my_map) 34 | { 35 | // add all the values in the map to the final set 36 | final_set.push_back(n.second); 37 | } 38 | 39 | return final_set; 40 | } 41 | 42 | int main() 43 | { 44 | vector input_set; 45 | input_set.push_back("eat"); 46 | input_set.push_back("tea"); 47 | input_set.push_back("tan"); 48 | input_set.push_back("ate"); 49 | input_set.push_back("nat"); 50 | input_set.push_back("bat"); 51 | 52 | vector > final_set = groupAnagrams(input_set); 53 | 54 | // print the output 55 | for (int i = 0; i < final_set.size(); i++) 56 | { 57 | if (final_set[i].size() > 0) 58 | { 59 | cout << " ( "; 60 | for (int j = 0; j < final_set[i].size(); j++) 61 | cout << final_set[i][j] << " "; 62 | cout << ")"; 63 | } 64 | cout< result is filled with widths from all possible points. 5 | // diameterOfBinaryTree(TreeNode* root) returns the maximum element in vector result as the result 6 | //or 0 if it's empty 7 | 8 | 9 | 10 | #include 11 | using namespace std; 12 | 13 | /** 14 | * Definition for a binary tree node. 15 | * struct TreeNode { 16 | * int val; 17 | * TreeNode *left; 18 | * TreeNode *right; 19 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 20 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 21 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 22 | * }; 23 | */ 24 | 25 | class Solution { 26 | public: 27 | vector results; 28 | 29 | bool is_leaf(TreeNode * node){ 30 | return node->left == nullptr && node->right == nullptr ; 31 | } 32 | 33 | int diameterHelper(TreeNode * node){ 34 | int right=0, left=0; 35 | if(node == nullptr) return 0; 36 | else{ 37 | if (node->right) right = diameterHelper(node->right) + 1; 38 | if (node->left) left = diameterHelper(node->left) + 1; 39 | results.push_back(right+left); 40 | } 41 | return max(right, left); 42 | } 43 | 44 | int diameterOfBinaryTree(TreeNode* root) { 45 | diameterHelper(root); 46 | return results.empty() ? 0 : * max_element(results.begin(), results.end()); 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /C++/1022. SumofRootToLeafBinaryNumbers.cpp: -------------------------------------------------------------------------------- 1 | // Problem: 2 | // You are given the root of a binary tree where each node has a value 0 or 1. 3 | // Each root - to - leaf path represents a binary number starting with the most significant bit. 4 | 5 | // For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13. 6 | 7 | // For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. 8 | // Return the sum of these numbers. The answer is guaranteed to fit in a 32 - bits integer. 9 | 10 | // Approach: 11 | // In the dfs, pass a variable (here, curr) in the parameter, 12 | // which will store binary number from root to leaf. Thus, curr will be nothing but value 13 | // of current value plus previous curr shifted once(or say multiplied by 2). 14 | // Once we reach the leaf node, add it to a variable(here, sum) which will contain sum of 15 | // all those binary values i.e. required answer. 16 | 17 | 18 | /** 19 | * Definition for a binary tree node. 20 | * struct TreeNode { 21 | * int val; 22 | * TreeNode *left; 23 | * TreeNode *right; 24 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 25 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 26 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 27 | * }; 28 | */ 29 | class Solution { 30 | public: 31 | int sum; 32 | void dfs(TreeNode* root, int curr) 33 | { 34 | if (!root) 35 | return; 36 | curr = (curr << 1) + root->val; 37 | if (!root->left and !root->right) 38 | { 39 | sum += curr; 40 | return; 41 | } 42 | dfs(root->left, curr); 43 | dfs(root->right, curr); 44 | } 45 | int sumRootToLeaf(TreeNode* root) { 46 | int curr; 47 | sum = curr = 0; 48 | dfs(root, curr); 49 | return sum; 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /Java/229. MajorityElementII.java: -------------------------------------------------------------------------------- 1 | /* 2 | Majority Element II: Given an integer array of size n, 3 | find all elements that appear more than ⌊ n/3 ⌋ times. 4 | */ 5 | 6 | class Solution { 7 | public List majorityElement(int[] nums) { 8 | List result = new ArrayList<>(); 9 | if (nums == null || nums.length == 0) 10 | return result; 11 | 12 | int cand1 = 0, cand2 = 0; 13 | 14 | int count1 = 0, count2 = 0; 15 | 16 | //Find numbers which are majority or have potential to be majority 17 | 18 | for (int num : nums) { 19 | if (num == cand1) { 20 | count1 ++; 21 | continue; 22 | } 23 | 24 | if (num == cand2) { 25 | count2 ++; 26 | continue; 27 | } 28 | 29 | if (count1 == 0) { 30 | cand1 = num; 31 | count1 = 1; 32 | continue; 33 | } 34 | 35 | if (count2 == 0) { 36 | cand2 = num; 37 | count2 = 1; 38 | continue; 39 | } 40 | 41 | count1 --; 42 | count2 --; 43 | 44 | } 45 | 46 | count1 = 0; 47 | count2 = 0; 48 | 49 | //Check which numbers are majority 50 | 51 | for (int num : nums) { 52 | if (num == cand1) { 53 | count1 ++; 54 | } else if (num == cand2) { 55 | count2 ++; 56 | } 57 | } 58 | 59 | if (count1 > nums.length / 3) 60 | result.add(cand1); 61 | 62 | if (count2 > nums.length / 3) 63 | result.add(cand2); 64 | 65 | return result; 66 | } 67 | } 68 | 69 | /* 70 | Input: nums = [3,2,3] 71 | Output: [3] 72 | 73 | Input: nums = [1,2] 74 | Output: [1,2] 75 | */ 76 | -------------------------------------------------------------------------------- /C++/101. SymmetricTree.cpp: -------------------------------------------------------------------------------- 1 | /*SYMMETRIC TREE*/ 2 | 3 | /*PROBLEM STATEMENT*/ 4 | /* 5 | Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). 6 | */ 7 | 8 | /*EXAMPLES*/ 9 | /* 10 | For example, this binary tree [1,2,2,3,4,4,3] is symmetric: 11 | 12 | 1 13 | / \ 14 | 2 2 15 | / \ / \ 16 | 3 4 4 3 17 | */ 18 | 19 | /* 20 | But the following [1,2,2,null,3,null,3] is not: 21 | 22 | 1 23 | / \ 24 | 2 2 25 | \ \ 26 | 3 3 27 | */ 28 | 29 | /** 30 | * Definition for a binary tree node. 31 | * struct TreeNode { 32 | * int val; 33 | * TreeNode *left; 34 | * TreeNode *right; 35 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 36 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 37 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 38 | * }; 39 | */ 40 | class Solution { 41 | public: 42 | bool isSymmetric(TreeNode* root) { 43 | if(root == NULL) 44 | return true; 45 | 46 | TreeNode *root1 = root->left; 47 | TreeNode *root2 = root->right; 48 | return _isSymmetric(root1, root2); 49 | } 50 | 51 | bool _isSymmetric(TreeNode *root1, TreeNode *root2) 52 | { 53 | if(root1 == root2) 54 | return true; 55 | else 56 | { 57 | if(root1 == NULL || root2 == NULL) 58 | return false; 59 | else 60 | { 61 | if(root1->val == root2->val) 62 | return _isSymmetric(root1->left, root2->right) && 63 | _isSymmetric(root1->right, root2->left); 64 | else 65 | return false; 66 | } 67 | } 68 | } 69 | 70 | }; -------------------------------------------------------------------------------- /C++/203. RemoveLinkedListElements.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ** LeetCode Problem 203. Remove Linked List Elements 3 | ** Url: https://leetcode.com/problems/remove-linked-list-elements/ 4 | ** Statement: 5 | ** Remove all elements from a linked list of integers that have value val. 6 | ** 7 | ** Example: 8 | ** Input: 1->2->6->3->4->5->6, val = 6 9 | ** Output: 1->2->3->4->5 10 | */ 11 | 12 | // Structure for each node 13 | 14 | struct ListNode { 15 | int val; 16 | ListNode* next; 17 | ListNode() : val(0), next(nullptr) {} 18 | ListNode(int x) : val(x), next(nullptr) {} 19 | ListNode(int x, ListNode* next) : val(x), next(next) {} 20 | }; 21 | 22 | class Solution { 23 | public: 24 | ListNode* removeElements(ListNode* head, int val) { 25 | // Return if input list is empty 26 | if (head == nullptr) { 27 | return head; 28 | } 29 | 30 | ListNode* curr = head; 31 | 32 | // Traverse through the list 33 | while (curr->next != nullptr) { 34 | if (curr->next->val == val) { 35 | // If next element has the value to be removed 36 | // take a temporary reference to it to free it 37 | // and prevent memory leak. And, update the 38 | // next pointer of the current node to skip 39 | // the matched value 40 | ListNode* temp = curr->next; 41 | curr->next = curr->next->next; 42 | delete temp; 43 | } else { 44 | curr = curr->next; 45 | } 46 | } 47 | if (head->val == val) { 48 | // If head contains the value to be removed, 49 | // the update the list to remove it. 50 | ListNode* temp = head; 51 | head = head->next; 52 | delete temp; 53 | } 54 | 55 | return head; 56 | } 57 | }; -------------------------------------------------------------------------------- /C++/225. Implement Stack Using Queues.cpp: -------------------------------------------------------------------------------- 1 | /* Implement Stack Using Queues.cpp 2 | So push time is O(1), while push and top takesO(n) time 3 | description is explained in between 4 | */ 5 | 6 | 7 | 8 | using namespace std; 9 | 10 | class Stack { 11 | // Two inbuilt queues 12 | queue q1, q2; 13 | 14 | // To maintain current number of 15 | // elements 16 | int curr_size; 17 | 18 | public: 19 | Stack() 20 | { 21 | curr_size = 0; 22 | } 23 | 24 | void push(int x) 25 | { 26 | curr_size++; 27 | 28 | // Push x first in empty q2 29 | q2.push(x); 30 | 31 | // Push all the remaining 32 | // elements in q1 to q2. 33 | while (!q1.empty()) { 34 | q2.push(q1.front()); 35 | q1.pop(); 36 | } 37 | 38 | // swap the names of two queues 39 | queue q = q1; 40 | q1 = q2; 41 | q2 = q; 42 | } 43 | 44 | void pop() 45 | { 46 | 47 | // if no elements are there in q1 48 | if (q1.empty()) 49 | return; 50 | q1.pop(); 51 | curr_size--; 52 | } 53 | 54 | int top() 55 | { 56 | if (q1.empty()) 57 | return -1; 58 | return q1.front(); 59 | } 60 | 61 | int size() 62 | { 63 | return curr_size; 64 | } 65 | }; 66 | 67 | // Driver code 68 | int main() 69 | { 70 | Stack s; 71 | s.push(1); 72 | s.push(2); 73 | s.push(3); 74 | 75 | cout << "current size: " << s.size() 76 | << endl; 77 | cout << s.top() << endl; 78 | s.pop(); 79 | cout << s.top() << endl; 80 | s.pop(); 81 | cout << s.top() << endl; 82 | 83 | cout << "current size: " << s.size() 84 | << endl; 85 | return 0; 86 | } 87 | -------------------------------------------------------------------------------- /Java/454.4SumII.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | class Solution { 4 | 5 | /** 6 | * The goal is to find the count of all options where A[i] + B[j] + C[k] + D[l] = 0 7 | * 8 | * We can now change this to: 9 | * A[i] + B[j] = - C[k] - D[l] 10 | * 11 | * Which equals: 12 | * A[i] + B[j] = -( C[k] + D[l] ) 13 | * 14 | * or: 15 | * - (A[i] + B[j]) = C[k] + D[l] 16 | * 17 | * Now we need to compute all possible sums of A,B and C,D and count equals. 18 | * 19 | * @param A 20 | * @param B 21 | * @param C 22 | * @param D 23 | * @return 24 | */ 25 | public int fourSumCount(int[] A, int[] B, int[] C, int[] D) { 26 | int length = A.length; 27 | 28 | if (length == 0) 29 | return 0; 30 | 31 | ArrayList sumsAB = new ArrayList(); 32 | ArrayList freqAB = new ArrayList(); 33 | for (int indexA = 0; indexA < length; indexA++) { 34 | for (int indexB = 0; indexB < length; indexB++) { 35 | int tmpSum = A[indexA] + B[indexB]; 36 | 37 | if (!sumsAB.contains(tmpSum)) { 38 | sumsAB.add(0, tmpSum); 39 | freqAB.add(0, 1); 40 | }else{ 41 | int indexFreq = sumsAB.indexOf(tmpSum); 42 | freqAB.set(indexFreq, freqAB.get(indexFreq) + 1); 43 | } 44 | } 45 | } 46 | 47 | int output = 0; 48 | for (int indexC = 0; indexC < length; indexC++) { 49 | for (int indexD = 0; indexD < length; indexD++) { 50 | int tmpSum = C[indexC] + D[indexD]; 51 | 52 | if (sumsAB.contains(-tmpSum)) { 53 | int indexFreq = sumsAB.indexOf(-tmpSum); 54 | output += freqAB.get(indexFreq); 55 | } 56 | } 57 | } 58 | 59 | return output; 60 | } 61 | } -------------------------------------------------------------------------------- /Python/2. AddTwoNumbers.py: -------------------------------------------------------------------------------- 1 | """ 2 | Goal: You are given two non-empty linked lists representing two non-negative integers. 3 | The digits are stored in reverse order, and each of their nodes contains a single digit. 4 | Add the two numbers and return the sum as a linked list. 5 | You may assume the two numbers do not contain any leading zero, except the number 0 itself. 6 | 7 | Procedure: 8 | ==> Idea is to find the sum of two numbers, which has been arranged in reverse order in a linked list. 9 | -> Create a dummy node to start with a new resultant linked list. 10 | -> Get the value from current nodes of the two linked lists if present, otherwise consider default value 0. 11 | -> Add the values along with the carry value. 12 | -> Carry value: Suppose a result of addition is 24, then the ten's place value, here it is 2, is stored in the carry variable. 13 | -> The remaining value, here being 4, is then added as a result to the current sequence of resulting linked list node 14 | -> Create a new next node for further addition. 15 | -> Continue from step 2 as long as there is either values present in the two linked list otherwise if carry is not 0. 16 | """ 17 | 18 | # Definition for singly-linked list. 19 | # class ListNode: 20 | # def __init__(self, val=0, next=None): 21 | # self.val = val 22 | # self.next = next 23 | class Solution: 24 | def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: 25 | rNode = ListNode() 26 | res = rNode 27 | carry = 0 28 | while l1 or l2 or carry: 29 | v1 = l1.val if l1 else 0 30 | v2 = l2.val if l2 else 0 31 | 32 | value = v1 + v2 + carry 33 | carry = value // 10 34 | value %= 10 35 | res.next = ListNode(value) 36 | 37 | res = res.next 38 | l1 = l1.next if l1 else None 39 | l2 = l2.next if l2 else None 40 | 41 | return rNode.next 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /Java/647. Palindromic Substrings.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Question: 3 | * Given a string, your task is to count how many palindromic substrings in this string. 4 | *

5 | * The substrings with different start indexes or end indexes are counted as different substrings even they consist of 6 | * same characters. 7 | *

8 | * Example 1: 9 | * Input: "abc" 10 | * Output: 3 11 | * Explanation: Three palindromic strings: "a", "b", "c". 12 | *

13 | * Example 2: 14 | * Input: "aaa" 15 | * Output: 6 16 | * Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". 17 | *

18 | * Constraints: 19 | * The input string length won't exceed 1000. 20 | */ 21 | class Solution { 22 | public int countSubstrings(String s) { 23 | int stringLength = s.length(); 24 | int count = 0; 25 | boolean[][] isPalindrome = new boolean[stringLength][stringLength]; 26 | 27 | // Resetting matrix 28 | for (int i = 0; i < stringLength; ++i) { 29 | for (int j = 0; j < stringLength; ++j) { 30 | isPalindrome[i][j] = false; 31 | } 32 | } 33 | 34 | // String length 1 35 | for (int i = 0; i < stringLength; ++i) { 36 | ++count; 37 | isPalindrome[i][i] = true; 38 | } 39 | 40 | int end = (stringLength - 1); 41 | 42 | // String length 2 43 | for (int i = 0; i < end; ++i) { 44 | String currentSubstring = s.substring(i, (i + 2)); 45 | if (currentSubstring.charAt(0) == currentSubstring.charAt(1)) { 46 | ++count; 47 | isPalindrome[i][i + 1] = true; 48 | } 49 | } 50 | 51 | // String length more than 3 52 | for (int i = 2; i <= end; ++i) { 53 | for (int j = 0; j < (i - 1); ++j) { 54 | if (s.charAt(j) == s.charAt(i) && isPalindrome[j + 1][i - 1]) { 55 | ++count; 56 | isPalindrome[j][i] = true; 57 | } 58 | } 59 | } 60 | 61 | return count; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /C++/845. LongestMountainInArray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Difficulty: medium 3 | runtime: 36ms 4 | */ 5 | /* 6 | Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:B.length >= 3 7 | There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1] 8 | (Note that B could be any subarray of A, including the entire array A.) 9 | Given an array A of integers, return the length of the longest mountain. Return 0 if there is no mountain. 10 | Note: 11 | 0 <= A.length <= 10000 12 | 0 <= A[i] <= 10000 13 | Example 1: 14 | Input: [2,1,4,7,3,2,5] 15 | Output: 5 16 | Explanation: The largest mountain is [1,4,7,3,2] which has length 5. 17 | Example 2: 18 | Input: [2,2,2] 19 | Output: 0 20 | Explanation: There is no mountain. 21 | Followup: 22 | Can you solve it using only one pass? YES 23 | Can you solve it in O(1) space? YES 24 | ___________________________________________________________________________________________________________________________ 25 | CodeExplain: 26 | while treversing the array..we have to just count increasing and decreasing numbers. 27 | and maximize the addition of increasing and decreasing numbers. 28 | */ 29 | 30 | class Solution { 31 | public: 32 | int longestMountain(vector& A) { 33 | int n=A.size(); 34 | if(n<3) 35 | return 0; 36 | int ans = 0, left = 0, right = 0;// left = increasing, right = decreasing 37 | for(int i=1;iA[i-1]){ //increasing count 40 | if(right){ 41 | left=0; 42 | right=0; 43 | } 44 | left += (1 + (left==0)); 45 | } 46 | else if(A[i]& nums) { 23 | int counter=0; //checks if nums is non-decreasing 24 | int n=nums.size(); 25 | vector case1=nums; 26 | vector case2=nums; 27 | for(int i=0;ival)+" ");//Add value+space,serialize left,then right. 24 | s+=serialize(root->left); 25 | s+=serialize(root->right); 26 | return s; 27 | } 28 | 29 | // Decodes your encoded data to tree. 30 | TreeNode* func(string data,int& ind) 31 | { 32 | if((data[ind]=='X')||(ind>=data.length()))//When value at index ind is 'X' that implies the node in the main tree is NULL 33 | { 34 | ind+=2; 35 | return NULL; 36 | } 37 | string sx=""; 38 | while((indleft=func(data,ind); 47 | nx->right=func(data,ind); 48 | return nx; 49 | } 50 | 51 | TreeNode* deserialize(string data) { 52 | int ind=0; 53 | return func(data,ind); 54 | } 55 | }; 56 | 57 | // Your Codec object will be instantiated and called as such: 58 | // Codec codec; 59 | // codec.deserialize(codec.serialize(root)); 60 | -------------------------------------------------------------------------------- /C++/189. Rotated_Array.cpp: -------------------------------------------------------------------------------- 1 | /*Given an array, we have to rotate the array to the right by k steps, where k is non-negative. 2 | For example: 3 | Input: nums = [1,2,3,4,5,6,7], k = 3 4 | Output: [5,6,7,1,2,3,4] 5 | Explanation: 6 | rotate 1 steps to the right: [7,1,2,3,4,5,6] 7 | rotate 2 steps to the right: [6,7,1,2,3,4,5] 8 | rotate 3 steps to the right: [5,6,7,1,2,3,4] 9 | */ 10 | 11 | class Solution { 12 | public: 13 | void rotate(vector& nums, int k) { 14 | int x = nums.size() - k; //x is the index of first element of vector nums after k rotations 15 | int x1 = x; // stores the initial value of x 16 | 17 | if(k>nums.size()) // condition for k greater than vector nums size 18 | { 19 | x = nums.size() - k%nums.size(); 20 | x1=x; 21 | } 22 | 23 | vector rotated_vector; // resulting vector after k rotations 24 | 25 | if(nums.size()==1||k==0||k==nums.size()) // exception for vector size equal to 1 26 | { 27 | x = 0; 28 | rotated_vector.push_back(nums[x]); //pushing value of nums at x 29 | } 30 | else 31 | { 32 | rotated_vector.push_back(nums[x]); //pushing value of nums at x 33 | 34 | if(x<(nums.size()-1)) //increment of x 35 | { 36 | x++; 37 | } 38 | else 39 | { 40 | x=0; //if x points to last element of array 41 | } 42 | 43 | while(x!=x1&&x In this approach we take map to store if that substring exits in dict or not. At first we pass the whole string and check if that string is present in dic or not. If not then we check with each word in dict, any word matching with the substring of s from first so that we can break that string and recursively check for further substring in the word dict and accordingly set the map. 11 | **/ 12 | 13 | #include 14 | using namespace std; 15 | 16 | class Solution { 17 | public: 18 | unordered_map mp; 19 | 20 | bool startwith(string s,string t){ 21 | int i=0,j=0; 22 | if(t.length()>s.length()) 23 | return false; 24 | 25 | while(j& wordDict){ 37 | if(s=="") 38 | return true; 39 | 40 | if(mp.find(s)!=mp.end()) 41 | return mp[s]; 42 | 43 | for(int i=0;i& wordDict) { 60 | //m.insert(make_pair("",1)); 61 | return wb_utils(s,wordDict); 62 | } 63 | }; -------------------------------------------------------------------------------- /Java/14. longestCommonPrefix.java: -------------------------------------------------------------------------------- 1 | /* Question: 2 | Write a function to find the longest common prefix string amongst an array of strings. 3 | 4 | If there is no common prefix, return an empty string "". 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: strs = ["flower","flow","flight"] 11 | Output: "fl" 12 | Example 2: 13 | 14 | Input: strs = ["dog","racecar","car"] 15 | Output: "" 16 | Explanation: There is no common prefix among the input strings. 17 | 18 | 19 | Constraints: 20 | 21 | 0 <= strs.length <= 200 22 | 0 <= strs[i].length <= 200 23 | strs[i] consists of only lower-case English letters. */ 24 | 25 | //Solution 26 | //The idea is to apply binary search method to find the string with maximum value L, 27 | //which is common prefix of all of the strings. The algorithm searches space is the interval (0…minLen), 28 | //where minLen is minimum string length and the maximum possible common prefix. 29 | //Each time search space is divided in two equal parts, one of them is discarded,because it is sure that it doesn't contain the solution. There are two possible cases: 30 | //(A) S[1...mid] is not a common string. This means that for each j > i S[1..j] is not a common string and we discard the second half of the search space. 31 | //(B) S[1...mid] is common string. This means that for for each i < j S[1..i] is a common string and we discard the first half of the search space, because we try to find longer common prefix. 32 | class Solution { 33 | public String longestCommonPrefix(String[] strs) { 34 | if (strs == null || strs.length == 0) 35 | return ""; 36 | int minLen = Integer.MAX_VALUE; 37 | for (String str : strs) 38 | minLen = Math.min(minLen, str.length()); 39 | int low = 1; 40 | int high = minLen; 41 | while (low <= high) { 42 | int middle = (low + high) / 2; 43 | if (isCommonPrefix(strs, middle)) 44 | low = middle + 1; 45 | else 46 | high = middle - 1; 47 | } 48 | return strs[0].substring(0, (low + high) / 2); 49 | } 50 | 51 | private boolean isCommonPrefix(String[] strs, int len){ 52 | String str1 = strs[0].substring(0,len); 53 | for (int i = 1; i < strs.length; i++) 54 | if (!strs[i].startsWith(str1)) 55 | return false; 56 | return true; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Java/13.RomanToInteger.java: -------------------------------------------------------------------------------- 1 | public class RomanToInteger{ 2 | public static int GetNum(int num) {//gets the number assoicate with a roman character 3 | if (num == 'I' || num == 'i') { 4 | return 1; 5 | } 6 | if (num == 'V' || num == 'v') { 7 | return 5; 8 | } 9 | if (num == 'X' || num == 'x') { 10 | return 10; 11 | } 12 | if (num == 'L' || num == 'l') { 13 | return 50; 14 | } 15 | if (num == 'C' || num == 'c') { 16 | return 100; 17 | } 18 | if (num == 'D' || num == 'd') { 19 | return 500; 20 | } 21 | if (num == 'M' || num == 'm') { 22 | return 1000; 23 | } 24 | 25 | return -1; 26 | } 27 | 28 | public static int romanToNumber(String roman){//Converts a roman numerial into a number 29 | int results = 0; 30 | for (int i = 0; i < roman.length(); i++) {//iterate through all the characters 31 | int cur = GetNum(roman.charAt(i));//Gets the integer of the roman number 32 | if (cur == -1) {//checks if the cur num is -1, if it is -1, it means that it is an invalid character 33 | return -1; 34 | } 35 | if (i + 1 < roman.length()) {//checks if the next index is out of bounds 36 | int next = GetNum(roman.charAt(i + 1));//gets the next character character 37 | if (next == -1) {//checks if the cur num is -1, if it is -1, it means that it is an invalid character 38 | return -1; 39 | } 40 | if (cur >= next) {//compares the current number to the next number 41 | results += cur;//if it is bigger, simply add the current number 42 | } 43 | else {//if the current number is smaller than the next number 44 | results += (next - cur);//subtract the next number by the current number 45 | i++;//increment the index, since the next number has already been used 46 | } 47 | } 48 | else {//only here to add the last number to the results 49 | results += cur;//adds the last character to the results 50 | } 51 | } 52 | return results;//returns the result 53 | } 54 | } -------------------------------------------------------------------------------- /C++/3. LongestSubstringWithoutRepeatingCharacters.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find and print longest 2 | // substring without repeating characters. 3 | #include 4 | 5 | using namespace std; 6 | 7 | // Function to find and print longest 8 | // substring without repeating characters. 9 | string findLongestSubstring(string str) 10 | { 11 | int i; 12 | int n = str.length(); 13 | 14 | // starting point of current substring. 15 | int st = 0; 16 | 17 | // length of current substring. 18 | int currlen; 19 | 20 | // maximum length substring without repeating 21 | // characters. 22 | int maxlen = 0; 23 | 24 | // starting index of maximum length substring. 25 | int start; 26 | 27 | // Hash Map to store last occurrence of each 28 | // already visited character. 29 | unordered_map pos; 30 | 31 | // Last occurrence of first character is index 0; 32 | pos[str[0]] = 0; 33 | 34 | for (i = 1; i < n; i++) { 35 | 36 | // If this character is not present in hash, 37 | // then this is first occurrence of this 38 | // character, store this in hash. 39 | if (pos.find(str[i]) == pos.end()) 40 | pos[str[i]] = i; 41 | 42 | else { 43 | // If this character is present in hash then 44 | // this character has previous occurrence, 45 | // check if that occurrence is before or after 46 | // starting point of current substring. 47 | if (pos[str[i]] >= st) { 48 | 49 | // find length of current substring and 50 | // update maxlen and start accordingly. 51 | currlen = i - st; 52 | if (maxlen < currlen) { 53 | maxlen = currlen; 54 | start = st; 55 | } 56 | 57 | // Next substring will start after the last 58 | // occurrence of current character to avoid 59 | // its repetition. 60 | st = pos[str[i]] + 1; 61 | } 62 | 63 | // Update last occurrence of 64 | // current character. 65 | pos[str[i]] = i; 66 | } 67 | } 68 | 69 | // Compare length of last substring with maxlen and 70 | // update maxlen and start accordingly. 71 | if (maxlen < i - st) { 72 | maxlen = i - st; 73 | start = st; 74 | } 75 | 76 | // The required longest substring without 77 | // repeating characters is from str[start] 78 | // to str[start+maxlen-1]. 79 | return str.substr(start, maxlen); 80 | } 81 | 82 | // Driver function 83 | int main() 84 | { 85 | string str; 86 | getline(cin,str); 87 | cout << findLongestSubstring(str); 88 | return 0; 89 | } 90 | 91 | -------------------------------------------------------------------------------- /C++/25. Reverse Nodes in k-group.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | 12 | /** 13 | First create a reverse funcion which just reverses a segment of linked list and then re assigns the pointers accordingly 14 | so that the reversed list again falls to the place. Then through the driver function just send bits of k segments to the reverse function until 15 | the count variable is lesser than k. Here count is the number of nodes in the input list. 16 | */ 17 | 18 | 19 | int i; //coz its to be declared for every for loop :( 20 | class Solution { 21 | public: 22 | ListNode* reverse(ListNode * head,ListNode *okay,int k) 23 | { 24 | ListNode* x=head; 25 | ListNode*y=nullptr; 26 | ListNode*z=head; 27 | 28 | for(i=0;inext; 30 | if(okay!=nullptr) // this is the last node of the previous part which was sent to this function. 31 | okay->next=x; // this joins all count/k parts into one single list 32 | x=x->next; // now we store the first node of next piece. 33 | for(i=0;inext; 36 | z->next=x; 37 | x=z; 38 | z=y; 39 | } 40 | return head ; // return the last node in reversed list 41 | } 42 | 43 | ListNode* reverseKGroup(ListNode* head, int k) 44 | { 45 | if(k==1) 46 | return head; 47 | ListNode* start=head; 48 | ListNode* nexts=nullptr; ListNode* prev=nullptr;int count=0; ListNode* okay=nullptr; 49 | for(start=head;start!=nullptr;start=start->next) //counting nodes 50 | count++; 51 | start=head; 52 | if(count>=k) 53 | for(i=0;inext; 55 | 56 | while(count-k>=0) 57 | { 58 | count=count-k; 59 | okay=reverse(start,okay,k); // calling reverse for each bit of k nodes and storing the last node of this piece to be used for next call. 60 | 61 | start=start->next; 62 | 63 | } 64 | 65 | 66 | return head; 67 | } 68 | }; 69 | -------------------------------------------------------------------------------- /C++/127. Word Ladder.cpp: -------------------------------------------------------------------------------- 1 | // Word Ladder 2 | /** 3 | Problem - 4 | Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that: 5 | 6 | Only one letter can be changed at a time. 7 | Each transformed word must exist in the word list. 8 | **/ 9 | 10 | /** 11 | Approach: 12 | This is a search problem, the key ide is to make the graph and use bredth first search to find the shortest distance from starting word to required word. 13 | **/ 14 | 15 | class Solution { 16 | public: 17 | int ladderLength(string beginWord, string endWord, vector& wordList) { 18 | unordered_map > l; 19 | 20 | // Preprocessing Step 21 | for(auto word: wordList){ // to make graph 22 | for(int i = 0; i a; 27 | a.push_back(word); 28 | l[temp] = a; 29 | } 30 | else{ 31 | l[temp].push_back(word); 32 | } 33 | } 34 | } 35 | 36 | // Search for shortest path 37 | queue q; 38 | queue dist; 39 | 40 | q.push(beginWord); 41 | dist.push(1); 42 | 43 | unordered_map vis; 44 | 45 | for(auto word: wordList){ 46 | vis[word] = false; 47 | } 48 | 49 | vis[beginWord] = true; 50 | 51 | int ans = 0; 52 | 53 | while(!q.empty()){ 54 | string u = q.front(); q.pop(); 55 | 56 | int d = dist.front(); dist.pop(); 57 | 58 | //cout< 6 | * If there are no nodes with an even-valued grandparent, return 0. 7 | *

8 | * Example: 9 | * Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5] 10 | * Output: 18 11 | * Explanation: ith node is the parent of (i + 1)th (i + 2)th node. 12 | * The nodes [x,x,x,2,7,1,3,x,x,x,x,x,x,x,5] are the nodes with even-value grandparent while the nodes 13 | * [6,x,8,x,x,x,x,x,x,x,x,x,x,x,x] are the even-value grandparents. 14 | *

15 | * Constraints: 16 | * The number of nodes in the tree is between 1 and 10^4. 17 | * The value of nodes is between 1 and 100. 18 | */ 19 | 20 | /** 21 | * Definition for a binary tree node. 22 | * 23 | * ` 24 | * public class TreeNode { 25 | * int val; 26 | * TreeNode left; 27 | * TreeNode right; 28 | * TreeNode(int x) { val = x; } 29 | * } 30 | * ` 31 | */ 32 | class Solution { 33 | public int sumEvenGrandparent(TreeNode root) { 34 | // Stack for DFS 35 | Deque treeStack = new LinkedList<>(); 36 | int sum = 0; 37 | boolean isEven = false; 38 | treeStack.push(root); 39 | 40 | sum = getSum(root, isEven, sum, treeStack); 41 | 42 | return sum; 43 | } 44 | 45 | // Recursive DFS 46 | public int getSum(TreeNode root, boolean isChildrenToBeAdded, int sum, Deque treeStack) { 47 | if (!treeStack.isEmpty()) { 48 | TreeNode currentNode = treeStack.pop(); 49 | 50 | // Add current node's children o sum as current node's parent has even number 51 | if (isChildrenToBeAdded) { 52 | if (currentNode.left != null) { 53 | sum += currentNode.left.val; 54 | } 55 | if (currentNode.right != null) { 56 | sum += currentNode.right.val; 57 | } 58 | } 59 | 60 | // Check if current node has even number so that its grandchildren can be added to sum 61 | if (currentNode.val % 2 == 0) { 62 | isChildrenToBeAdded = true; 63 | } else { 64 | isChildrenToBeAdded = false; 65 | } 66 | 67 | // Traverse Left sub-tre 68 | if (currentNode.left != null) { 69 | treeStack.push(currentNode.left); 70 | sum = getSum(currentNode.left, isChildrenToBeAdded, sum, treeStack); 71 | } 72 | // Traverse Right sub-tre 73 | if (currentNode.right != null) { 74 | treeStack.push(currentNode.right); 75 | sum = getSum(currentNode.right, isChildrenToBeAdded, sum, treeStack); 76 | } 77 | } 78 | 79 | return sum; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Leetcode-Solutions 2 | 3 | We love your input! We want to make contributing to this project as easy and transparent as possible, whether it's: 4 | 5 | - Reporting a bug 6 | - Discussing the current state of the code 7 | - Submitting a fix 8 | - Proposing new features 9 | - Becoming a maintainer 10 | 11 | 12 | ## Steps to contribute 13 | 14 | * Comment on the issue you want to work on. Make sure it's not assigned to someone else. 15 | 16 | * If you think a problem is missing, create an issue. 17 | 18 | ### Making a PR 19 | 20 | > - Make sure you have been assigned the issue to which you are making a PR. 21 | > - If you make PR before being assigned, It will be labelled `invalid` and closed without merging. 22 | 23 | * Fork the repo and clone it on your machine. 24 | * Add an upstream link to the main branch in your cloned repo 25 | ``` 26 | git remote add upstream https://github.com/SSKale1/LeetCode-Solutions.git 27 | ``` 28 | * Keep your cloned repo up to date by pulling from upstream (this will also avoid any merge conflicts while committing new changes) 29 | ``` 30 | git pull upstream master 31 | ``` 32 | * Create your feature branch 33 | ``` 34 | git checkout -b 35 | ``` 36 | * Commit all the changes 37 | ``` 38 | git commit -am "Meaningful commit message" 39 | ``` 40 | * Push the changes for review 41 | ``` 42 | git push origin 43 | ``` 44 | * Create a PR from our repo on Github. 45 | 46 | ### Additional Notes 47 | * Follow the issue creation format. 48 | * Code should be properly commented to ensure it's readability. 49 | * If you've added code that should be tested, add tests as comments. 50 | * Make 1 Issue and PR per problem. 51 | * Make sure your code properly formatted. 52 | * Make sure all filenames follow CamelCase 53 | * Issue that pull request! 54 | 55 | 56 | ## Issue suggestions/Bug reporting 57 | 58 | When you are creating an issue, make sure it's not already present. Furthermore, provide a proper description of the changes. If you are suggesting any code improvements, provide through details about the improvements. 59 | 60 | **Great Issue suggestions** tend to have: 61 | 62 | - A quick summary of the changes. 63 | - In case of any bug provide steps to reproduce 64 | - Be specific! 65 | - Give sample code if you can. 66 | - What you expected would happen 67 | - What actually happens 68 | - Notes (possibly including why you think this might be happening, or stuff you tried that didn't work) 69 | - If you want to submit solutions in a previously unavailable language, create an Issue for it too. 70 | 71 | 72 | ## License 73 | 74 | By contributing, you agree that your contributions will be licensed under its [MIT License](http://choosealicense.com/licenses/mit/). 75 | 76 | 77 | ## References 78 | 79 | This document was adapted from the open-source contribution guidelines for [Facebook's Draft](https://github.com/facebook/draft-js/blob/a9316a723f9e918afde44dea68b5f9f39b7d9b00/CONTRIBUTING.md) 80 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

👉 A Collection of Solutions to Leetcode Problems 👈

4 |

5 | 6 |

7 | 8 | 9 | 10 | 11 |

12 |

13 | 14 | 15 | 16 | 17 |

18 |

19 | 20 |

21 |

22 | 23 |

24 | 25 | ## Introduction 26 | 27 | Leetcode is a Website where programmers practise their Coding Skills. It has over 1500 Problems and growing. Its premium version is fairly popular as it helps to practise coding for interviews of various organizations. 28 | This Repo aims to have the solutions to all the problems on Leetcode and serve as a reference to everyone new to the platform. 29 | 30 | :star2: Star it 31 | :fork_and_knife:Fork it 32 | :handshake: Contribute to it! 33 | 34 | 35 | ## Languages 36 | - Python 37 | - C++ 38 | - Java 39 | - SQL 40 | 41 | ## Support 42 | 43 | Check [Contribution](/CONTRIBUTING.md) Guide Before Contribution. 44 | 45 | 46 | 47 | 48 | 49 |

Code Base Details

50 |
51 | 52 | | Problem # | Title | Remarks | 53 | |---|---|---| 54 | | 1 | Two Sum | | 55 | | 2 | Add Two Numbers | | 56 | | 3 | Longest Substring Without Repeating Characters | | 57 | 58 | 59 | 60 |
61 | 62 | ## Contributing 63 | 64 | Before submitting a bug, please do the following: 65 | Check [Contribution](/CONTRIBUTING.md) Guide Before Contribution. 66 | 67 | - Create separate issues for each problem. 68 | - You can only work on issues that you have been assigned to. 69 | - Join us on [Discord](https://discord.gg/wyrPn9k) 70 | 71 | ## Authors and acknowledgment 72 | 73 | Show your appreciation to those who have contributed to the project. 74 | 75 | ## [License](/LICENSE) 76 | 77 | For open-source projects, Under [MIT License](/LICENSE). 78 | 79 | ## Maintainers 80 | 81 | - [Shantanu Kale](https://github.com/SSKale1) 82 | - [Yashica Sharma](https://github.com/Yashica7) 83 | 84 | -------------------------------------------------------------------------------- /Java/12.IntegerToRoman.java: -------------------------------------------------------------------------------- 1 | public class IntegerToRoman{ 2 | public static String numberToRoman(int number){//Converts a number into a roman numerial 3 | String roman = ""; 4 | while(number != 0){//checks if the number is not equal to 0, if it is not equal then there is more processing to be done 5 | if(number >= 1000){//if the number is larger than 1000, then add an M to the roman string and subtract 1000 from number 6 | roman += "M"; 7 | number -= 1000; 8 | } 9 | else if(number >= 900){//if the number is larger than 900, then add an CM to the roman string and subtract 900 from number 10 | roman += "CM"; 11 | number -= 900; 12 | } 13 | else if(number >= 500){//if the number is larger than 500, then add an D to the roman string and subtract 500 from number 14 | roman += "D"; 15 | number -= 500; 16 | } 17 | else if(number >= 400){//if the number is larger than 400, then add an CD to the roman string and subtract 400 from number 18 | roman += "CD"; 19 | number -= 400; 20 | } 21 | else if(number >= 100){//if the number is larger than 100, then add an C to the roman string and subtract 100 from number 22 | roman += "C"; 23 | number -= 100; 24 | } 25 | else if(number >= 90){//if the number is larger than 90, then add an XC to the roman string and subtract 90 from number 26 | roman += "XC"; 27 | number -= 90; 28 | } 29 | else if(number >= 50){//if the number is larger than 50, then add an L to the roman string and subtract 50 from number 30 | roman += "L"; 31 | number -= 50; 32 | } 33 | else if(number >= 40){//if the number is larger than 40, then add an XL to the roman string and subtract 40 from number 34 | roman += "XL"; 35 | number -= 40; 36 | } 37 | else if(number >= 10){//if the number is larger than 10, then add an X to the roman string and subtract 10 from number 38 | roman += "X"; 39 | number -= 10; 40 | } 41 | else if(number >= 9){//if the number is larger than 9, then add an IX to the roman string and subtract 9 from number 42 | roman += "IX"; 43 | number -= 9; 44 | } 45 | else if(number >= 5){//if the number is larger than 5, then add an V to the roman string and subtract 5 from number 46 | roman += "V"; 47 | number -= 5; 48 | } 49 | else if(number >= 4){//if the number is larger than 4, then add an IV to the roman string and subtract 4 from number 50 | roman += "IV"; 51 | number -= 4; 52 | } 53 | else if(number >= 1){//if the number is larger than 1, then add an I to the roman string and subtract 1 from number 54 | roman += "I"; 55 | number -= 1; 56 | } 57 | } 58 | return roman; 59 | } 60 | } -------------------------------------------------------------------------------- /C++/730. CountDifferentPalindromicSubsequences.cpp: -------------------------------------------------------------------------------- 1 | /*Given a string S, find the number of different non-empty palindromic subsequences in S, and return that number modulo 10^9 + 7. 2 | A subsequence of a string S is obtained by deleting 0 or more characters from S. 3 | A sequence is palindromic if it is equal to the sequence reversed. 4 | Two sequences A_1, A_2, ... and B_1, B_2, ... are different if there is some i for which A_i != B_i. 5 | Example: 6 | Input: 7 | S = 'bccb' 8 | Output: 6 9 | */ 10 | /* 11 | create 2d dp. 12 | dp[i][j] will have the number of palindromes of the input_string[i] to input_string[j]. 13 | for string bccb - 14 | dp: 15 | 1 2 3 6 16 | 0 1 2 3 17 | 0 0 1 2 18 | 0 0 0 1 19 | you will find here..similer logic like finding longest palindromic subsequence.. 20 | */ 21 | 22 | class Solution { 23 | public: 24 | int countPalindromicSubsequences(string s) { 25 | long n=s.size(); 26 | // Created a db and initialize to 0 27 | long dp[n][n]; 28 | for(int i=0;i=0;i--) 37 | { 38 | for(int j=i;ji && s[high]!=s[j]){ 51 | high--; 52 | } 53 | 54 | if(low>high) 55 | { 56 | dp[i][j] = dp[i+1][j-1]*2 + 2; // no other same char is there..between i, j 57 | // in case bccb,i=0,j=3, dp[1][2] = 2(c, cc)...so, dp[0][3] = 2*2+2(b, bcb, bccb, c, cc, bb) 58 | } 59 | else if(low == high) 60 | { 61 | dp[i][j] = dp[i+1][j-1]*2 + 1; // 1 same char is there..between i, j 62 | } // in case bcbb,i=0,j=3, dp[1][2] = 2(c, b)...so, dp[0][3] = 2*2+1(b, bcb, bb, c, bbb) 63 | else 64 | { 65 | dp[i][j] = (dp[i+1][j-1]*2 - dp[low+1][high-1]); // more than 1 same char is there..between i, j 66 | // in case bbbb,i=0,j=3, dp[1][2] = 2(b, bb)...so, dp[0][3] = 2*2 - 0(b, bb, bbb, bbbb) 67 | } 68 | } 69 | else 70 | { 71 | dp[i][j] = dp[i][j-1] + dp[i+1][j] - dp[i+1][j-1]; //edge chars does not mach... 72 | } // in case abcd,i=0,j=3, dp[0][2] = 3, dp[1][3] = 3, dp[1][2] = 2...so, dp[0][3] = 3 + 3 - 2(a, b, c, d) 73 | 74 | // just safe..as we are subtracting..earlier in code 75 | if(dp[i][j]<0) 76 | dp[i][j]+=1000000007; 77 | 78 | dp[i][j]=dp[i][j]%1000000007; // ans could be very big 79 | 80 | } 81 | 82 | } 83 | return dp[0][n-1];//ans 84 | } 85 | }; 86 | --------------------------------------------------------------------------------