├── Rotate Image ├── javaSolutionRoateImage.java ├── PythonSolutionRotateImage.py ├── CppSolutionRotateImage .cpp └── CSolutionRotateImage.c ├── Java Program to remove duplicate element in an Array ├── Reverse Integer ├── PythonSolutionReverseInteger.py ├── javaSolutionReverseInteger.java ├── CppSolutionReverseInteger.cpp └── cppSolutionReverseInteger.cpp ├── Power of Two └── JavaSolutionPowerofTwo.java ├── Median of Two Sorted Arrays ├── 2LinerPython.py ├── CppSolutionMedianOfSortedArrays.cpp └── CSolutionMedianOfSortedArray.cpp ├── Missing Number ├── PythonSolutionMissingNumber.py ├── CppSolutionMissingNumberSolution.cpp ├── cppSolution[Missing Number].cpp └── JavaSolutionMissingNumber.java ├── Reducing Dishes └── pySolutionReducingDishes.py ├── Factorial Trailing Zeroes ├── CppSolutionFactorialTrailingZeroes.cpp └── Readme.md ├── Count of Smaller Numbers After Self └── pySolutionCountOfSmallerNumbersAfterSelf.py ├── Delete Node In Linked List └── cppSolutionDeleteNodeInLinkedList.cpp ├── Find Peak Element ├── PythonSolutionFindPeakElement.py └── javaSolutionFindPeakElement.java ├── Word Break II └── pySoultionWordBreak2.py ├── N-Queens II └── pySolutionNQueens2.py ├── Bag of Tokens ├── pythonSolutionBagofTokens.py ├── JavaSolutionBagOfTokens.java ├── CppSolutionBagofTokens.cpp └── README.md ├── Generate-Parentheses ├── JavaScriptSolutionGenerateParentheses.js ├── CppSolutionGenerateParentheses.cpp ├── PythonSolutionGenerateParentheses.py └── JavaSolutionGenerateParentheses.java ├── Jump Game 3 └── jump-game-3.java ├── N-Queens └── NQueens1.py ├── Decode String ├── JavaSolutionDecodeString.java ├── PythonSolutionDecodeString.py └── CppSolutionDecodeString.cpp ├── Reverse Linked List └── cppSolutionReverseLinkedList.cpp ├── Largest Rectangle in Histogram ├── PythonSolutionLargestRectangleInHistogram.py ├── CppSolutionLargestRectangleInHistogram.cpp └── JavaSolutionLargestRectangleInHistogram.java ├── Two Sum ├── JavaSolutionTwoSum.java └── CppSolutionTwoSum.cpp ├── Remove Node From End └── JavaSolutionRemoveNthFromEnd.java ├── Sieve Of Eratosthenes ├── cppSolution_Sieve of Erathosthenes.cpp └── JavaSolutionSieveOfEratosthenes.java ├── Maximum Sum BST in Binary Tree └── pySoultionMaximumSumBSTInBinaryTree.py ├── Product of Array Except Self └── JavaSolutionProductofArrayExceptSelf.java ├── Trapping Rain Water ├── pySolutionTrappingRainWater.py ├── cppSolutionTrappingRainWater.cpp └── javaSolutionTrappingRainWater.java ├── Longest Palindromic Substring ├── Readme.md └── CppSolutionLongestPalindromicSubstring.cpp ├── House Robber └── javaSolutionHouseRobber.java ├── Frequency of the Most Frequent Element ├── PySolutionFrequencyoftheMostFrequentElement.py └── CppSolutionFrequencyoftheMostFrequentElement.cpp ├── Count and Say └── JavaSolutionCountandSay.java ├── Jump Game 1 └── javaSolutionJumpGame1.java ├── 3 Sum ├── README.md ├── javasolution3Sum.java └── CppSolution3Sum.cpp ├── pySoultionLongestIncreasingPathInAMatrix.py ├── Squares Of A Sorted Array ├── README.md ├── CppSolutionSquaresofAsortedArray.cpp └── JavaSolutionSquaresofASortedArray.java ├── Merge k Sorted Lists └── usingHeapPython.py ├── Jump Game 2 └── javaSolutionJumpGame2.java ├── First Bad Version └── CppSolutionFirstBadVersion.cpp ├── Best Time to Buy and Sell Stocks ├── JavaSoltionBestTimetoBuyandSellStocks.java └── javaSolutionBestTimeToBuyAndSellStockFour.java ├── First Missing positive Integer └── JavaSolutionFirstMissingPositiveInteger.java ├── House Robber-ii └── javaSolutionHouseRobberTwo.java ├── Sort Array By Parity └── JavaSolutionSortArrayByParity.java ├── Search in Rotated Sorted Array ├── javaSolutionSearchInRotatedSortedArray.java └── CppSolutionSearchInRotatedSortedArray.cpp ├── Lowest Common Ancestor of a Binary Tree └── CppSolutionLowestCommonAncestorOfABinaryTree.cpp ├── Cells-With-Odd-Values-In-A-Matrix └── javasolutionCellsWithOddValuesInAMatrix.java ├── Fizz-buzz └── cppsolutionfizzbuzz.java ├── Coin Change 2 └── javaSolutionCoinChange2.java ├── Genetrate-Triplets-Threesum └── PythonSolutionGenerateTriplets.py ├── SlidingWindowMaximum └── JavaSolutionSlidingWindowMaximum.java ├── Game of Life └── CppSolutionGameOfLife.cpp ├── Valid Sudoku └── JavaSolutionValidSudoku.java ├── Max Points on a Line └── pySolutionMaxPointsOnALine.py ├── ReverseNodesInKGroup └── CppSolutionReverseKNodes.cpp ├── Spiral Matrix └── javaSolutionSpiralMatrix.java ├── BestTimeToBuyAndSellStock-iii └── javaSolutionBestTimeToBuyAndSellStockThree.java ├── BestTimeToBuyAndSellStock-iv └── javaSolutionBestTimeToBuyAndSellStockFour.java ├── Trapping Rainwater └── trapping_rainwater.cpp ├── README.md └── interLeavingString └── interLeavingString.cpp /Rotate Image/javaSolutionRoateImage.java: -------------------------------------------------------------------------------- 1 | // Rotate Image code (dummy for hacktober fest video) 2 | -------------------------------------------------------------------------------- /Java Program to remove duplicate element in an Array: -------------------------------------------------------------------------------- 1 | I Want Create a new file Java Program to remove duplicate element in an Array. please Assing to me @KhushbooGoel01 2 | -------------------------------------------------------------------------------- /Reverse Integer/PythonSolutionReverseInteger.py: -------------------------------------------------------------------------------- 1 | n = 569 2 | rev = 0 3 | 4 | while(n > 0): 5 | a = n % 10 6 | rev = rev * 10 + a 7 | n = n // 10 8 | 9 | print(rev) 10 | -------------------------------------------------------------------------------- /Power of Two/JavaSolutionPowerofTwo.java: -------------------------------------------------------------------------------- 1 | // Question: https://leetcode.com/problems/power-of-two/ 2 | 3 | class Solution { 4 | public boolean isPowerOfTwo(int n) { 5 | return (n>0 && ((n & (n-1)) == 0)); 6 | } 7 | } -------------------------------------------------------------------------------- /Median of Two Sorted Arrays/2LinerPython.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: 3 | v = sorted(nums1+nums2) 4 | return v[len(v)//2] if len(v)&1 else (v[len(v)//2-1]+v[len(v)//2])/2 5 | -------------------------------------------------------------------------------- /Missing Number/PythonSolutionMissingNumber.py: -------------------------------------------------------------------------------- 1 | def getMissingNo(A): 2 | n = len(A) 3 | total = (n + 1)*(n + 2)/2 4 | sum_of_A = sum(A) 5 | return total - sum_of_A 6 | 7 | A = [1, 2, 3, 4, 5, 6, 8, 9] 8 | miss = getMissingNo(A) 9 | print(miss) 10 | -------------------------------------------------------------------------------- /Reducing Dishes/pySolutionReducingDishes.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSatisfaction(self, data: List[int]) -> int: 3 | data = sorted(data, reverse=True) 4 | ans = s = 0 5 | for i in data: 6 | s+=i 7 | if s>=0: ans+=s 8 | else: break 9 | return ans 10 | -------------------------------------------------------------------------------- /Factorial Trailing Zeroes/CppSolutionFactorialTrailingZeroes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int trailingZeroes(int n) { 4 | 5 | int num = 5, ans = 0; 6 | 7 | while(n/num) { 8 | 9 | ans += n/num; 10 | num *= 5; 11 | } 12 | return ans; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Missing Number/CppSolutionMissingNumberSolution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int missingNumber(vector& nums) { 4 | int result = nums.size(); 5 | int i=0; 6 | 7 | for(int num:nums){ 8 | result ^= num; 9 | result ^= i; 10 | i++; 11 | } 12 | 13 | return result; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Count of Smaller Numbers After Self/pySolutionCountOfSmallerNumbersAfterSelf.py: -------------------------------------------------------------------------------- 1 | from bisect import bisect_left, insort 2 | 3 | class Solution: 4 | def countSmaller(self, nums: List[int]) -> List[int]: 5 | ans = [ ] 6 | lnums = [] 7 | for i in nums[::-1]: 8 | ans.append(bisect_left(lnums,i)) 9 | insort(lnums,i) 10 | return ans[::-1] 11 | -------------------------------------------------------------------------------- /Reverse Integer/javaSolutionReverseInteger.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int reverse(int x) { 3 | int rev = 0; 4 | while(x != 0){ 5 | int r = x % 10; 6 | x /= 10; 7 | if(rev < Integer.MIN_VALUE/10) return 0; 8 | if(rev > Integer.MAX_VALUE/10) return 0; 9 | rev = rev * 10 + r; 10 | } 11 | return rev; 12 | } 13 | } -------------------------------------------------------------------------------- /Delete Node In Linked List/cppSolutionDeleteNodeInLinkedList.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | void deleteNode(ListNode* node) { 12 | node->val=node->next->val; 13 | node->next=node->next->next; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Find Peak Element/PythonSolutionFindPeakElement.py: -------------------------------------------------------------------------------- 1 | // Question link : https://leetcode.com/problems/find-peak-element/submissions/ 2 | 3 | class Solution: 4 | def findPeakElement(self, nums: List[int]) -> int: 5 | b = 0 6 | e = len(nums)-1 7 | while(b None: 5 | 6 | for i in range(len(matrix)): 7 | for j in range(i,len(matrix)): 8 | matrix[i][j],matrix[j][i]=matrix[j][i],matrix[i][j] 9 | #this is to transpose matrix 10 | for l in matrix: 11 | l.reverse() 12 | -------------------------------------------------------------------------------- /Reverse Integer/CppSolutionReverseInteger.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int reverse(int x) { 4 | int rev = 0; 5 | while (x != 0) { 6 | int pop = x % 10; 7 | x /= 10; 8 | if (rev > INT_MAX/10 || (rev == INT_MAX / 10 && pop > 7)) return 0; 9 | if (rev < INT_MIN/10 || (rev == INT_MIN / 10 && pop < -8)) return 0; 10 | rev = rev * 10 + pop; 11 | } 12 | return rev; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Reverse Integer/cppSolutionReverseInteger.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int reverse(int x) { 4 | int rev = 0; 5 | while (x != 0) { 6 | int pop = x % 10; 7 | x /= 10; 8 | if (rev > INT_MAX/10 || (rev == INT_MAX / 10 && pop > 7)) return 0; 9 | if (rev < INT_MIN/10 || (rev == INT_MIN / 10 && pop < -8)) return 0; 10 | rev = rev * 10 + pop; 11 | } 12 | return rev; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Word Break II/pySoultionWordBreak2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def wordBreak(self, s: str, words: List[str]) -> List[str]: 3 | def bt(s, i, ans=[]): 4 | if i==len(s): 5 | return [ ans ] 6 | 7 | toReturn = [] 8 | for word in words: 9 | if s.startswith(word,i): 10 | toReturn += bt(s, i+len(word), ans+[word]) 11 | return toReturn 12 | return [ " ".join(line) for line in bt(s, 0) ] 13 | -------------------------------------------------------------------------------- /N-Queens II/pySolutionNQueens2.py: -------------------------------------------------------------------------------- 1 | def is_valid(pos, y): 2 | isValid = y not in pos 3 | for i,j in enumerate(pos): 4 | if abs(i-len(pos)) == abs(j-y): 5 | isValid = False 6 | return isValid 7 | 8 | def nqueens(pos, size): 9 | if len(pos)==size: return [pos] 10 | 11 | ans = [] 12 | for i in range(size): 13 | if is_valid(pos, i): 14 | ans += nqueens(pos+[i], size) 15 | return ans 16 | 17 | class Solution: 18 | def totalNQueens(self, n: int) -> int: 19 | return len(nqueens([], n)) 20 | -------------------------------------------------------------------------------- /Rotate Image/CppSolutionRotateImage .cpp: -------------------------------------------------------------------------------- 1 | // Question Link: https://leetcode.com/problems/rotate-image/ 2 | 3 | 4 | class Solution { 5 | public: 6 | void rotate(vector>& image) { 7 | // transpose matrix 8 | for (int i = 0; i < image.size(); ++i) { 9 | for (int j = i; j < image.size(); ++j) { 10 | swap(image[i][j], image[j][i]); 11 | } 12 | } 13 | // reverse rows 14 | for (auto& row : image) reverse(row.begin(), row.end()); 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /Bag of Tokens/pythonSolutionBagofTokens.py: -------------------------------------------------------------------------------- 1 | #Question link: https://leetcode.com/problems/bag-of-tokens/ 2 | 3 | def bagOfTokensScore(self, tokens, P): 4 | res = cur = 0 5 | d = collections.deque(sorted(tokens)) 6 | 7 | while d and (d[0] <= P or cur): 8 | if d[0] <= P: 9 | P -= d.popleft() 10 | cur += 1 11 | else: 12 | P += d.pop() 13 | cur -= 1 14 | res = max(res, cur) 15 | 16 | return res 17 | -------------------------------------------------------------------------------- /Missing Number/cppSolution[Missing Number].cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int getMissingNo(int a[] , 5 | int n) 6 | { 7 | int n_elements_sum = n * (n + 1) / 2 ; 8 | int sum = 0; 9 | 10 | for(int i = 0; i < n - 1; i++) 11 | sum += a[i]; 12 | return n_elements_sum-sum; 13 | } 14 | 15 | int main() 16 | { 17 | int a[] = {1, 2, 4, 5, 6}; 18 | int n = sizeof(a) / 19 | sizeof(a[0]) + 1; 20 | int miss = getMissingNo(a, n); 21 | cout << (miss); 22 | return 0; 23 | } 24 | 25 | -------------------------------------------------------------------------------- /Generate-Parentheses/JavaScriptSolutionGenerateParentheses.js: -------------------------------------------------------------------------------- 1 | const generateParenthesis = (n) => { 2 | const solution = []; 3 | 4 | const generateCombo = (leftPCount, rightPCount, partial) => { 5 | if(leftPCount > rightPCount) return; 6 | if(!leftPCount && !rightPCount) solution.push(partial); 7 | if(leftPCount > 0)generateCombo (leftPCount -1, rightPCount, partial +'('); 8 | if(rightPCount> 0)generateCombo (leftPCount, rightPCount -1,partial +')'); 9 | } 10 | generateCombo(n,n,''); 11 | return solution; 12 | }; 13 | -------------------------------------------------------------------------------- /Jump Game 3/jump-game-3.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canReach(int[] arr, int start) { 3 | boolean vis[]=new boolean[arr.length]; 4 | return check(arr,start,vis); 5 | } 6 | static boolean check(int arr[],int s, boolean vis[]){ 7 | if(s<0 || s>=arr.length) return false; 8 | if(arr[s]==0) return true; 9 | if(vis[s]) return false; 10 | vis[s]=true; 11 | 12 | boolean l=check(arr,s+arr[s],vis); 13 | 14 | boolean r=check(arr,s-arr[s],vis); 15 | return l || r; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Find Peak Element/javaSolutionFindPeakElement.java: -------------------------------------------------------------------------------- 1 | Problem Link: https://leetcode.com/problems/find-peak-element/ 2 | 3 | public int findPeakElement(int[] nums) { 4 | int n=nums.length; 5 | int start=0; 6 | int end=n-1; 7 | int mid; 8 | 9 | while(start List[List[str]]: 19 | solutions = nqueens([], n) 20 | return [[ "."*(i)+"Q"+"."*(n-i-1) for i in s] for s in solutions] 21 | -------------------------------------------------------------------------------- /Decode String/JavaSolutionDecodeString.java: -------------------------------------------------------------------------------- 1 | public static String decodeString (String input) { 2 | String output = input; 3 | Pattern pattern = Pattern.compile("(\\d+)\\[([a-z]+)\\]"); 4 | Matcher matcher = pattern.matcher(input); 5 | while (matcher.find()) { 6 | output = output.replace(matcher.group(0), new String(new char[Integer.valueOf(matcher.group(1))]).replace("\0", matcher.group(2))); 7 | } 8 | if (output.contains("[")) { 9 | output = decodeString(output); 10 | } 11 | return output; 12 | } 13 | -------------------------------------------------------------------------------- /Reverse Linked List/cppSolutionReverseLinkedList.cpp: -------------------------------------------------------------------------------- 1 | #Reverse Linked List Problem Leetcode link : https://leetcode.com/problems/reverse-linked-list 2 | 3 | ListNode* reverseList(ListNode* head) { 4 | ListNode* prevptr = NULL; 5 | ListNode* currptr = head; 6 | ListNode* nextptr ; 7 | 8 | while(currptr != NULL){ 9 | nextptr = currptr->next; 10 | currptr->next = prevptr; 11 | 12 | prevptr = currptr; 13 | currptr = nextptr; 14 | } 15 | 16 | return prevptr; 17 | } 18 | -------------------------------------------------------------------------------- /Largest Rectangle in Histogram/PythonSolutionLargestRectangleInHistogram.py: -------------------------------------------------------------------------------- 1 | #Question : https://leetcode.com/problems/largest-rectangle-in-histogram/ 2 | 3 | class Solution: 4 | def largestRectangleArea(self, height: List[int]) -> int: 5 | height.append(0) 6 | stack = [0] 7 | r = 0 8 | for i in range(1, len(height)): 9 | while stack and height[i] < height[stack[-1]]: 10 | h = height[stack.pop()] 11 | w = i if not stack else i - stack[-1] -1 12 | r = max(r, w*h) 13 | stack.append(i) 14 | return r 15 | -------------------------------------------------------------------------------- /Two Sum/JavaSolutionTwoSum.java: -------------------------------------------------------------------------------- 1 | // Question Link :- https://leetcode.com/problems/two-sum/ 2 | 3 | // Below is Solution 4 | class Solution { 5 | public int[] twoSum(int[] nums, int target) { 6 | int[] ansArray = new int[2]; 7 | for(int i = 0; i < nums.length; i++){ 8 | for(int j = 0; j < nums.length; j++){ 9 | if((nums[i] + nums[j] == target) && (i!=j)){ 10 | ansArray[0] = i; 11 | ansArray[1] = j; 12 | } 13 | } 14 | } 15 | return ansArray; 16 | } 17 | } 18 | // Time Complexity :- O(n^2) -------------------------------------------------------------------------------- /Factorial Trailing Zeroes/Readme.md: -------------------------------------------------------------------------------- 1 | # [Question Link](https://leetcode.com/problems/factorial-trailing-zeroes/) 2 | Given an integer `n`, return the number of trailing zeroes in `n!`. 3 | 4 | Note that `n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1`. 5 | 6 | 7 | Example 1: 8 | ``` 9 | Input: n = 3 10 | Output: 0 11 | Explanation: 3! = 6, no trailing zero. 12 | ``` 13 | 14 | Example 2: 15 | ``` 16 | Input: n = 5 17 | Output: 1 18 | Explanation: 5! = 120, one trailing zero. 19 | ``` 20 | 21 | Example 3: 22 | ``` 23 | Input: n = 0 24 | Output: 0 25 | ``` 26 | 27 | 28 | Constraints: 29 | ``` 30 | 0 <= n <= 10^4 31 | ``` 32 | -------------------------------------------------------------------------------- /Generate-Parentheses/CppSolutionGenerateParentheses.cpp: -------------------------------------------------------------------------------- 1 | //Question link: https://leetcode.com/problems/generate-parentheses/ 2 | 3 | class Solution { 4 | public: 5 | vector generateParenthesis(int n) { 6 | vector res; 7 | addingpar(res, "", n, 0); 8 | return res; 9 | } 10 | void addingpar(vector &v, string str, int n, int m){ 11 | if(n==0 && m==0) { 12 | v.push_back(str); 13 | return; 14 | } 15 | if(m > 0){ addingpar(v, str+")", n, m-1); } 16 | if(n > 0){ addingpar(v, str+"(", n-1, m+1); } 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Remove Node From End/JavaSolutionRemoveNthFromEnd.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ListNode removeNthFromEnd(ListNode head, int n) { 3 | ListNode start = new ListNode(); 4 | start.next = head; 5 | ListNode fast = start; 6 | ListNode slow = start; 7 | 8 | for(int i = 1; i <= n; ++i) 9 | fast = fast.next; 10 | 11 | while(fast.next != null) 12 | { 13 | fast = fast.next; 14 | slow = slow.next; 15 | } 16 | 17 | slow.next = slow.next.next; 18 | 19 | return start.next; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Sieve Of Eratosthenes/cppSolution_Sieve of Erathosthenes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void Sieve(int n){ 5 | int n; 6 | vector is_prime(n+1, true); 7 | is_prime[0] = is_prime[1] = false; 8 | for (int i = 2; i <= n; i++) { 9 | if (is_prime[i] && (long long)i * i <= n) { 10 | for (int j = i * i; j <= n; j += i) 11 | is_prime[j] = false; 12 | } 13 | } 14 | } 15 | 16 | int main(){ 17 | ios::sync_with_stdio(0); 18 | cin.tie(0); 19 | int T; 20 | cin >> T; 21 | while (T--) { 22 | Sieve(); 23 | } 24 | return 0; 25 | } 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /Maximum Sum BST in Binary Tree/pySoultionMaximumSumBSTInBinaryTree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSumBST(self, root: TreeNode) -> int: 3 | self.MAX = 0 4 | self.mbst(root) 5 | return self.MAX 6 | 7 | def mbst(self, root): 8 | if not root: return (True, 0, float('-inf'), float('inf')) 9 | lv, ls, ll, lr = self.mbst(root.left) 10 | rv, rs, rl, rr = self.mbst(root.right) 11 | isBst = lv and rv and ll < root.val < rr 12 | sBst = (ls+rs+root.val) 13 | if isBst: 14 | self.MAX = max(self.MAX, sBst) 15 | return (isBst, sBst, max(rl, root.val), min(lr, root.val)) 16 | -------------------------------------------------------------------------------- /Product of Array Except Self/JavaSolutionProductofArrayExceptSelf.java: -------------------------------------------------------------------------------- 1 | //Question: https://leetcode.com/problems/product-of-array-except-self 2 | 3 | class Solution { 4 | public int[] productExceptSelf(int[] nums) { 5 | int prodExcept[]=new int[nums.length]; 6 | int product=1; 7 | for(int i=0; i=0; i--) 14 | { 15 | prodExcept[i]*=product; 16 | product*=nums[i]; 17 | } 18 | return prodExcept; 19 | } 20 | } -------------------------------------------------------------------------------- /Trapping Rain Water/pySolutionTrappingRainWater.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def trap(self, height: List[int]) -> int: 3 | lheights = [] 4 | maxi = 0 5 | for h in height: 6 | maxi = max(maxi, h) 7 | lheights.append(maxi) 8 | 9 | rheights = [] 10 | maxi = 0 11 | for h in height[::-1]: 12 | maxi = max(maxi, h) 13 | rheights.append(maxi) 14 | rheights = rheights[::-1] 15 | 16 | result = 0 17 | for i in range(len(height)): 18 | result += min(lheights[i], rheights[i]) - height[i] 19 | return result 20 | -------------------------------------------------------------------------------- /Generate-Parentheses/PythonSolutionGenerateParentheses.py: -------------------------------------------------------------------------------- 1 | # Question Link: https://leetcode.com/problems/generate-parentheses/ 2 | 3 | def generateParenthesis(self, n): 4 | if n == 0: 5 | return [""] 6 | self.result = [] 7 | self.helper("", n, 0) 8 | return self.result 9 | 10 | def helper(self, pattern, remain_left, remain_right): 11 | if remain_left == 0 and remain_right == 0: 12 | self.result.append(pattern) 13 | return 14 | if remain_left: 15 | self.helper(pattern + "(", remain_left - 1, remain_right + 1) 16 | if remain_right: 17 | self.helper(pattern + ")", remain_left, remain_right - 1) 18 | -------------------------------------------------------------------------------- /Longest Palindromic Substring/Readme.md: -------------------------------------------------------------------------------- 1 | # [Question Link](https://leetcode.com/problems/longest-palindromic-substring/) 2 | Given a string` s`, return the longest palindromic substring in `s`. 3 | 4 | 5 | Example 1: 6 | ``` 7 | Input: s = "babad" 8 | Output: "bab" 9 | Note: "aba" is also a valid answer. 10 | ``` 11 | 12 | Example 2: 13 | ``` 14 | Input: s = "cbbd" 15 | Output: "bb" 16 | ``` 17 | 18 | Example 3: 19 | ``` 20 | Input: s = "a" 21 | Output: "a" 22 | ``` 23 | Example 4: 24 | ``` 25 | Input: s = "ac" 26 | Output: "a" 27 | ``` 28 | 29 | Constraints: 30 | ``` 31 | 1 <= s.length <= 1000 32 | s consist of only digits and English letters. 33 | 34 | ``` 35 | -------------------------------------------------------------------------------- /House Robber/javaSolutionHouseRobber.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int rob(int[] arr) 4 | { 5 | 6 | int dp[]=new int[1000]; 7 | 8 | for(int i=0;i<1000;i++) dp[i]=-1; 9 | 10 | return solve(arr,0,dp); 11 | } 12 | public static int solve(int arr[],int i,int dp[]){ 13 | 14 | if(i>=arr.length) return 0; 15 | 16 | if(dp[i]!=-1){ 17 | return dp[i]; 18 | } 19 | 20 | int robbed=arr[i]+solve(arr,i+2,dp); 21 | int notRobbed=solve(arr,i+1,dp); 22 | 23 | return dp[i]=Math.max(robbed,notRobbed); 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Frequency of the Most Frequent Element/PySolutionFrequencyoftheMostFrequentElement.py: -------------------------------------------------------------------------------- 1 | # Problem link: https://leetcode.com/problems/frequency-of-the-most-frequent-element 2 | 3 | # Solution: 4 | 5 | class Solution: 6 | def maxFrequency(self, nums: List[int], k: int) -> int: 7 | nums.sort() 8 | 9 | l, r = 0, 0 10 | res, total = 0, 0 11 | 12 | while r < len(nums): 13 | total += nums[r] 14 | while nums[r] * (r - l + 1) > total + k: 15 | total -= nums[l] 16 | l += 1 17 | res = max(res, r - l + 1) 18 | r += 1 19 | 20 | return res -------------------------------------------------------------------------------- /Count and Say/JavaSolutionCountandSay.java: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/count-and-say/ 2 | 3 | class Solution { 4 | public String countAndSay(int n) { 5 | if(n==1) 6 | return "1"; 7 | String prev=countAndSay(n-1); 8 | StringBuilder str=new StringBuilder(); 9 | int i=0; 10 | while(i=nums.length-1){ 16 | return true; 17 | } 18 | } 19 | return false; 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /3 Sum/README.md: -------------------------------------------------------------------------------- 1 | # [Question Link](https://leetcode.com/problems/3sum/) 2 | Given an integer array nums, return all the triplets `[nums[i], nums[j], nums[k]]` such that `i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0`. 3 | 4 | Notice that the solution set must not contain duplicate triplets. 5 | 6 | 7 | 8 | Example 1: 9 | ``` 10 | Input: nums = [-1,0,1,2,-1,-4] 11 | Output: [[-1,-1,2],[-1,0,1]] 12 | ``` 13 | 14 | Example 2: 15 | ``` 16 | Input: nums = [] 17 | Output: [] 18 | ``` 19 | 20 | Example 3: 21 | ``` 22 | Input: nums = [0] 23 | Output: [] 24 | ``` 25 | 26 | 27 | Constraints: 28 | ``` 29 | 0 <= nums.length <= 3000 30 | -105 <= nums[i] <= 105 31 | ``` 32 | -------------------------------------------------------------------------------- /pySoultionLongestIncreasingPathInAMatrix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestIncreasingPath(self, matrix: List[List[int]]) -> int: 3 | m,n = len(matrix), len(matrix[0]) 4 | path = [ [0]*m for _ in range(n)] 5 | d = [(0,1), (1,0), (0, -1), (-1,0)] 6 | dp={} 7 | def abc(x,y): 8 | if (x,y) not in dp: 9 | dp[(x,y)]= 1+max([abc(x+i,y+j) for i,j in d if 0<=x+i str: 5 | stack = [] 6 | 7 | for c in s: 8 | if c != "]": 9 | stack.append(c) 10 | 11 | else: 12 | substr = "" 13 | while stack[-1] != "[": 14 | substr = stack.pop() + substr 15 | stack.pop() 16 | 17 | k = "" 18 | while stack and stack[-1].isdigit(): 19 | k = stack.pop() + k 20 | 21 | stack.append(substr * int(k)) 22 | 23 | return "".join(stack) 24 | -------------------------------------------------------------------------------- /Largest Rectangle in Histogram/CppSolutionLargestRectangleInHistogram.cpp: -------------------------------------------------------------------------------- 1 | //Question Link: https://leetcode.com/problems/largest-rectangle-in-histogram/ 2 | 3 | class Solution { 4 | public: 5 | int largestRectangleArea(vector& height) { 6 | int n = height.size(), area = 0, h, l; 7 | stack indexes; 8 | for (int i = 0; i <= n; i++) { 9 | while (i == n || (!indexes.empty() && height[indexes.top()] > height[i])) { 10 | if (i == n && indexes.empty()) h = 0, i++; 11 | else h = height[indexes.top()], indexes.pop(); 12 | l = indexes.empty() ? -1 : indexes.top(); 13 | area = max(area, h * (i - l - 1)); 14 | } 15 | indexes.push(i); 16 | } 17 | return area; 18 | 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Squares Of A Sorted Array/CppSolutionSquaresofAsortedArray.cpp: -------------------------------------------------------------------------------- 1 | // Problem link -: https://leetcode.com/problems/squares-of-a-sorted-array/ 2 | 3 | class Solution { 4 | public: 5 | vector sortedSquares(vector& nums) { 6 | vector res(nums.size(), 0); 7 | int i=0, j=nums.size()-1, k=nums.size()-1; 8 | while(i<=j) 9 | { 10 | if(abs(nums[i])>abs(nums[j])) 11 | { 12 | res[k--] = abs(nums[i])*abs(nums[i]); 13 | i++; 14 | } 15 | else 16 | { 17 | res[k--] = abs(nums[j])*abs(nums[j]); 18 | j--; 19 | } 20 | } 21 | return res; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Trapping Rain Water/cppSolutionTrappingRainWater.cpp: -------------------------------------------------------------------------------- 1 | # Question Link: https://leetcode.com/problems/trapping-rain-water 2 | 3 | int trap(vector& height) 4 | { 5 | int ans = 0, current = 0; 6 | stack st; 7 | while (current < height.size()) { 8 | while (!st.empty() && height[current] > height[st.top()]) { 9 | int top = st.top(); 10 | st.pop(); 11 | if (st.empty()) 12 | break; 13 | int distance = current - st.top() - 1; 14 | int bounded_height = min(height[current], height[st.top()]) - height[top]; 15 | ans += distance * bounded_height; 16 | } 17 | st.push(current++); 18 | } 19 | return ans; 20 | } 21 | -------------------------------------------------------------------------------- /Merge k Sorted Lists/usingHeapPython.py: -------------------------------------------------------------------------------- 1 | from heapq import * 2 | class Solution: 3 | def mergeKLists(self, lists: List[ListNode]) -> ListNode: 4 | n=len(lists) 5 | heap = [] 6 | for i in range(n): 7 | if lists[i] != None: 8 | heappush(heap, (lists[i].val, i)) 9 | 10 | ans = root = None 11 | while(heap): 12 | v, i = heappop(heap) 13 | if ans == None: ans = root = ListNode(v) 14 | else: 15 | ans.next = ListNode(v) 16 | ans=ans.next 17 | lists[i] = lists[i].next 18 | if lists[i] != None: 19 | heappush(heap, (lists[i].val, i)) 20 | 21 | return root 22 | -------------------------------------------------------------------------------- /Bag of Tokens/JavaSolutionBagOfTokens.java: -------------------------------------------------------------------------------- 1 | //Java Solution for Bag of tokens problem Leetcode. 2 | //Question can be found at- https://leetcode.com/problems/bag-of-tokens/ 3 | Time complexity- Time O(sort) 4 | Space O(sort) 5 | 6 | public int bagOfTokensScore(int[] A, int P) { 7 | Arrays.sort(A); 8 | int res = 0, points = 0, i = 0, j = A.length - 1; 9 | while (i <= j) { 10 | if (P >= A[i]) { 11 | P -= A[i++]; 12 | res = Math.max(res, ++points); 13 | } else if (points > 0) { 14 | points--; 15 | P += A[j--]; 16 | } else { 17 | break; 18 | } 19 | } 20 | return res; 21 | } 22 | -------------------------------------------------------------------------------- /Frequency of the Most Frequent Element/CppSolutionFrequencyoftheMostFrequentElement.cpp: -------------------------------------------------------------------------------- 1 | //PROBLEM LINK: https://leetcode.com/problems/frequency-of-the-most-frequent-element 2 | 3 | //PROBLEM SOLUTION: 4 | 5 | class Solution { 6 | public: 7 | int maxFrequency(vector &nums, long long int k) 8 | { 9 | int n = nums.size(); 10 | sort(nums.begin(), nums.end()); 11 | int i = 0; 12 | int ans = 0; 13 | for (int j = 0; j < n; j++) 14 | { 15 | k += nums[j]; 16 | while (k < (long)nums[j] * (j - i + 1)) 17 | { 18 | k -= nums[i]; 19 | i++; 20 | } 21 | ans = max(ans, j - i + 1); 22 | } 23 | return ans; 24 | } 25 | }; -------------------------------------------------------------------------------- /Two Sum/CppSolutionTwoSum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& nums, int target) { 4 | unordered_map hash; // Use as a hash table, instead of creating one 5 | vector result; 6 | for (int i = 0; i < nums.size(); i++) 7 | if (hash.count(target - nums[i])) // If the partner of this value to reach the target sum has been saved already 8 | { 9 | result.push_back(hash[target - nums[i]]); // Get index of other value 10 | result.push_back(i); 11 | return result; 12 | } 13 | else // Pair has not yet been found, so save value to hash table 14 | hash[nums[i]] = i; 15 | return result; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Bag of Tokens/CppSolutionBagofTokens.cpp: -------------------------------------------------------------------------------- 1 | # Question Link: https://leetcode.com/problems/bag-of-tokens/ 2 | 3 | int bagOfTokensScore(vector& tokens, int P) { 4 | sort(tokens.begin(), tokens.end()); 5 | 6 | int res = 0, points = 0, i = 0, j = tokens.size() - 1; 7 | 8 | while (i <= j) { 9 | if (P >= tokens[i]) { 10 | P -= tokens[i]; 11 | i++; 12 | res = max(res, ++points); 13 | 14 | } 15 | else if (points > 0) { 16 | points--; 17 | P += tokens[j]; 18 | j--; 19 | } 20 | else { 21 | break; 22 | } 23 | } 24 | return res; 25 | } 26 | -------------------------------------------------------------------------------- /Jump Game 2/javaSolutionJumpGame2.java: -------------------------------------------------------------------------------- 1 | //QUESTION'S LINK=== 2 | // https://leetcode.com/problems/jump-game-ii/ 3 | class Solution { 4 | public int jump(int[] nums) { 5 | int n=nums.length; 6 | int dp[]=new int[n]; 7 | for(int i=0;i=nums.length-1) return 0; 15 | int min=100000; 16 | if(dp[idx]!=min){ 17 | return dp[idx]; 18 | } 19 | for(int i=1;i<=nums[idx];i++){ 20 | min=Math.min(min,1+solve(nums,idx+i,dp)); 21 | } 22 | 23 | return dp[idx]=min; 24 | } 25 | } 26 | © 2021 GitHub, Inc. 27 | Ter 28 | -------------------------------------------------------------------------------- /First Bad Version/CppSolutionFirstBadVersion.cpp: -------------------------------------------------------------------------------- 1 | // Problem link: https://leetcode.com/problems/first-bad-version/ 2 | 3 | //Approch: Binary Search 4 | 5 | // Time: O(logn) 6 | // Space: O(1) 7 | 8 | // Forward declaration of isBadVersion API. 9 | bool isBadVersion(int version); 10 | 11 | class Solution { 12 | public: 13 | int firstBadVersion(int n) { 14 | long long int beg,last,mid; 15 | beg = 1 , last = n; 16 | long int pos = 1; 17 | while(beg<=last){ 18 | mid = beg + (last-beg)/2; 19 | bool x = isBadVersion(mid); 20 | if(x == true){ 21 | pos = mid; 22 | last = mid-1; 23 | } 24 | else 25 | beg = mid+1; 26 | } 27 | return pos; 28 | } 29 | }; -------------------------------------------------------------------------------- /Best Time to Buy and Sell Stocks/JavaSoltionBestTimetoBuyandSellStocks.java: -------------------------------------------------------------------------------- 1 | //Java Solution for Best Time to Buy and Sell Stock problem Leetcode. 2 | //Question can be found at- https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 3 | 4 | class Solution { 5 | public int maxProfit(int[] prices) { 6 | if(prices.length<2) 7 | return 0; 8 | int minPrice=prices[0]; 9 | int maxProfit=prices[1]-prices[0]; 10 | 11 | for(int i=1; i n) { 8 | nums[i] = n + 1; 9 | } 10 | } 11 | 12 | for (int i = 0; i < n; i++) { 13 | int val = Math.abs(nums[i]); 14 | if (val != n + 1 && nums[val - 1] > 0) { 15 | nums[val - 1] = - nums[val - 1]; 16 | } 17 | } 18 | 19 | for (int i = 0; i < n; i++) { 20 | if (nums[i] > 0) { 21 | return i + 1; 22 | } 23 | } 24 | 25 | return n + 1; 26 | } 27 | } -------------------------------------------------------------------------------- /House Robber-ii/javaSolutionHouseRobberTwo.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public int rob(int[] arr) 4 | { 5 | if(arr.length==1) return arr[0]; 6 | int dp1[]=new int[101]; 7 | int dp2[]=new int[101]; 8 | Arrays.fill(dp1,-1); 9 | Arrays.fill(dp2,-1); 10 | 11 | int x=solve(arr,0,arr.length-1,dp1); 12 | int y=solve(arr,1,arr.length,dp2); 13 | 14 | return Math.max(x,y); 15 | 16 | } 17 | public static int solve(int arr[],int i,int n,int dp[]){ 18 | if(i>=n) return 0; 19 | 20 | if(dp[i]!=-1){ 21 | return dp[i]; 22 | } 23 | 24 | int rob=arr[i]+solve(arr,i+2,n,dp); 25 | int not=solve(arr,i+1,n,dp); 26 | 27 | return dp[i]=Math.max(rob,not); 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Squares Of A Sorted Array/JavaSolutionSquaresofASortedArray.java: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/squares-of-a-sorted-array/ 2 | 3 | class Solution { 4 | public int[] sortedSquares(int[] nums) { 5 | int [] res = new int [nums.length]; 6 | int left = 0; 7 | int right = nums.length - 1; 8 | int index = nums.length - 1; 9 | while(left <= right){ 10 | int val1 = nums[left] * nums[left]; 11 | int val2 = nums[right] * nums[right]; 12 | if(val1 > val2){ 13 | res[index] = val1; 14 | left++; 15 | } 16 | else{ 17 | res[index] = val2; 18 | --right; 19 | } 20 | index--; 21 | } 22 | return res; 23 | } 24 | } -------------------------------------------------------------------------------- /Sort Array By Parity/JavaSolutionSortArrayByParity.java: -------------------------------------------------------------------------------- 1 | // Question Link :- https://leetcode.com/problems/sort-array-by-parity/ 2 | 3 | // Below is Solution 4 | class Solution { 5 | public int[] sortArrayByParity(int[] nums) { 6 | int start = 0; 7 | int last = nums.length - 1; 8 | int i = 0; 9 | int temp; 10 | while(i<=last){ 11 | if(nums[i]==0){ 12 | temp = nums[i]; 13 | nums[i] = nums[start]; 14 | nums[start] = temp; 15 | i++; 16 | start++; 17 | }else if(nums[i] % 2 == 0){ 18 | i++; 19 | }else{ 20 | temp = nums[i]; 21 | nums[i] = nums[last]; 22 | nums[last] = temp; 23 | last--; 24 | } 25 | } 26 | return nums; 27 | } 28 | } -------------------------------------------------------------------------------- /Generate-Parentheses/JavaSolutionGenerateParentheses.java: -------------------------------------------------------------------------------- 1 | //#Question : https://leetcode.com/problems/generate-parentheses/ 2 | 3 | class Solution { 4 | public List generateParenthesis(int n) { 5 | ArrayList list = new ArrayList(); 6 | 7 | for (int i = (int)Math.pow(2, 2*n-1); i < (int)(Math.pow(2, 2*n)-1); i = i + 2) { 8 | Stack s = new Stack(); 9 | StringBuffer b = new StringBuffer(); 10 | int tmp = i; 11 | while (tmp > 0) { 12 | if (tmp % 2 == 1) { 13 | b.append(')'); 14 | if (s.isEmpty() || s.pop() != ')') { 15 | break; 16 | } 17 | } 18 | else { 19 | b.append('('); 20 | s.push(')'); 21 | } 22 | tmp = tmp / 2; 23 | } 24 | if (s.isEmpty() && b.length() == 2 * n) { 25 | list.add(b.toString()); 26 | } 27 | } 28 | 29 | return list; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Search in Rotated Sorted Array/javaSolutionSearchInRotatedSortedArray.java: -------------------------------------------------------------------------------- 1 | Problem Link: https://leetcode.com/problems/search-in-rotated-sorted-array/ 2 | 3 | public int search(int[] nums, int target) { 4 | int n=nums.length; 5 | int start=0; 6 | int end=n-1; 7 | int mid; 8 | 9 | while(start<=end){ 10 | mid =start+(end-start)/2; 11 | if(nums[mid]==target) 12 | return mid; 13 | if(nums[start]<=nums[mid]){ 14 | 15 | if(target>=nums[start] && targetnums[mid] && target<=nums[end]) 23 | start=mid+1; 24 | else 25 | end=mid-1; 26 | } 27 | 28 | } 29 | return -1; 30 | } 31 | -------------------------------------------------------------------------------- /Lowest Common Ancestor of a Binary Tree/CppSolutionLowestCommonAncestorOfABinaryTree.cpp: -------------------------------------------------------------------------------- 1 | //Question Link : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 15 | if(root == NULL || p == root || q == root) 16 | return root; 17 | 18 | TreeNode *left = lowestCommonAncestor(root -> left, p, q); 19 | TreeNode *right = lowestCommonAncestor(root -> right, p, q); 20 | 21 | if(left == NULL) 22 | return right; 23 | else if(right == NULL) 24 | return left; 25 | else 26 | return root; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Cells-With-Odd-Values-In-A-Matrix/javasolutionCellsWithOddValuesInAMatrix.java: -------------------------------------------------------------------------------- 1 | // Question Link : https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/ 2 | package com.shrey; 3 | 4 | public class oddCells { 5 | public int oddCells(int m, int n, int[][] indices) { 6 | int[][] ar = new int[m][n]; 7 | int count = 0; 8 | int r = 0; 9 | int c = 0; 10 | for(int i=0; i=maxLeft) 14 | maxLeft=height[left]; 15 | else 16 | water+=maxLeft-height[left]; 17 | left+=1; 18 | } 19 | else{ 20 | if(height[right]>maxRight) 21 | maxRight=height[right]; 22 | else 23 | water+=maxRight-height[right]; 24 | right-=1; 25 | } 26 | } 27 | return water; 28 | } 29 | -------------------------------------------------------------------------------- /Decode String/CppSolutionDecodeString.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/decode-string/ 2 | 3 | class Solution { 4 | public: 5 | string decode(string s,int &index){ 6 | string str; 7 | while(index='a'&&s[index]<='z'){ 10 | str+=s[index]; 11 | index++; 12 | } 13 | if(s[index]>'0'&&s[index]<='9'){ 14 | int n=0; 15 | while(s[index]!='['){ 16 | n=n*10+(s[index]-'0'); 17 | index++; 18 | } 19 | index++; 20 | string q=decode(s,index); 21 | index++; 22 | while(n--) {str+=q;} 23 | } 24 | } 25 | return str; 26 | } 27 | string decodeString(string s) { 28 | int index=0; 29 | return decode(s,index); 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /Fizz-buzz/cppsolutionfizzbuzz.java: -------------------------------------------------------------------------------- 1 | //Question can be found at : https://leetcode.com/explore/interview/card/top-interview-questions-easy/102/math/743/ 2 | class Solution { 3 | public List fizzBuzz(int n) { 4 | 5 | // ans list 6 | List ans = new ArrayList(); 7 | 8 | for (int num = 1; num <= n; num++) { 9 | 10 | boolean divisibleBy3 = (num % 3 == 0); 11 | boolean divisibleBy5 = (num % 5 == 0); 12 | 13 | if (divisibleBy3 && divisibleBy5) { 14 | // Divides by both 3 and 5, add FizzBuzz 15 | ans.add("FizzBuzz"); 16 | } else if (divisibleBy3) { 17 | // Divides by 3, add Fizz 18 | ans.add("Fizz"); 19 | } else if (divisibleBy5) { 20 | // Divides by 5, add Buzz 21 | ans.add("Buzz"); 22 | } else { 23 | // Not divisible by 3 or 5, add the number 24 | ans.add(Integer.toString(num)); 25 | } 26 | } 27 | 28 | return ans; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Coin Change 2/javaSolutionCoinChange2.java: -------------------------------------------------------------------------------- 1 | //QUESTION'S LINK==== 2 | //https://leetcode.com/problems/coin-change-2/ 3 | 4 | class Solution { 5 | public int change(int amount, int[] coins) { 6 | 7 | int dp[][]=new int[coins.length+1][amount+1]; 8 | 9 | for(int i=0;i=coins.length) return 0; 21 | 22 | if(dp[i][val]!=-1) return dp[i][val]; 23 | 24 | int taken=0; 25 | 26 | if(coins[i]<=val){ 27 | taken=solve(val-coins[i],coins,i,dp); 28 | } 29 | 30 | int nottaken=solve(val,coins,i+1,dp); 31 | 32 | return dp[i][val]=taken+nottaken; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Genetrate-Triplets-Threesum/PythonSolutionGenerateTriplets.py: -------------------------------------------------------------------------------- 1 | # Question Link: https://leetcode.com/problems/3sum/ 2 | # run it in leetcode code runner. 3 | 4 | class Solution: 5 | def threeSum(self, nums: List[int]) -> List[List[int]]: 6 | if not nums: 7 | return [] 8 | elif len(nums) < 3: 9 | return [] 10 | 11 | temp = {} 12 | for i in range(len(nums)): 13 | temp[nums[i]] = i 14 | 15 | ans = {} 16 | 17 | for i in range(len(nums)): 18 | for k in range(len(nums)): 19 | if i != k: 20 | target = 0 - nums[i] 21 | sum_ = target - nums[k] 22 | if sum_ in temp and i != temp[sum_] and i != k and temp[sum_] != k: 23 | to_append = tuple(sorted((sum_, nums[i], nums[k]))) 24 | if not to_append in ans: 25 | ans[to_append] = 0 26 | 27 | return ans 28 | -------------------------------------------------------------------------------- /Missing Number/JavaSolutionMissingNumber.java: -------------------------------------------------------------------------------- 1 | // Question Link :- https://leetcode.com/problems/missing-number/ 2 | 3 | // Below is Solution 4 | class Solution { 5 | public int missingNumber(int[] nums) { 6 | int i = 0; 7 | while(i < nums.length){ 8 | int correct = nums[i]; 9 | if(nums[i] != nums.length && nums[i] != nums[correct]){ 10 | swap(nums, i, correct); 11 | }else{ 12 | i++; 13 | } 14 | } 15 | // search for first missing number 16 | for(int index = 0; index < nums.length; index++){ 17 | if(nums[index] != index){ 18 | return index; 19 | } 20 | } 21 | // case 2 22 | // return number 23 | return nums.length; 24 | } 25 | // swap 26 | void swap(int[] arr, int first, int second){ 27 | int temp = arr[first]; 28 | arr[first] = arr[second]; 29 | arr[second] = temp; 30 | } 31 | } -------------------------------------------------------------------------------- /SlidingWindowMaximum/JavaSolutionSlidingWindowMaximum.java: -------------------------------------------------------------------------------- 1 | # Question Link: https://leetcode.com/problems/sliding-window-maximum/ 2 | 3 | public int[] maxSlidingWindow(int[] nums, int k) { 4 | int n=nums.length; 5 | int[] res=new int[n-k+1]; 6 | int i=0,j=0; 7 | int K=0; 8 | ArrayDeque q=new ArrayDeque<>(); 9 | while(j>board; 6 | int r,c; 7 | int getl(int i,int j){ 8 | int l=0; 9 | if(i+1=0 && board[i-1][j])l++; 13 | if(i-1>=0 && j-1>=0 && board[i-1][j-1])l++; 14 | if(j-1>=0 && board[i][j-1])l++; 15 | if(i+1=0 && board[i+1][j-1])l++; 16 | if(i-1>=0 && j+1>& t) { 20 | board=t; 21 | r=board.size();c=board[0].size(); 22 | for(int i=0;i2 && i<6) box+=3; 18 | else if(i>=6) box+=6; 19 | if(countBox[box][value]==1) return false; 20 | else countBox[box][value]++; 21 | // System.out.println(i+" "+j+" "+box+" "+value); 22 | } 23 | } 24 | return true; 25 | } 26 | } -------------------------------------------------------------------------------- /Max Points on a Line/pySolutionMaxPointsOnALine.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxPoints(self, points: List[List[int]]) -> int: 3 | 4 | primes = [2] 5 | for i in range(3, 101): 6 | for j in primes: 7 | if j*j>i: 8 | primes += [i] 9 | break 10 | if i%j==0: 11 | break 12 | 13 | ans=0 14 | for i in range(len(points)): 15 | slopes = {} 16 | for j in range(len(points)): 17 | if i==j: continue 18 | x1,y1 = points[i] 19 | x2,y2 = points[j] 20 | y,x = y2-y1, x2-x1 21 | #print(x,y) 22 | for p in primes: 23 | if p>abs(y) and p>abs(x): break 24 | while x%p==0 and y%p==0: 25 | x//=p 26 | y//=p 27 | 28 | slopes[(x,y)] = slopes.get((x,y), 0) + 1 29 | ans = max(ans, max(list(slopes.values())+[0])+1) 30 | return ans 31 | -------------------------------------------------------------------------------- /3 Sum/javasolution3Sum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> threeSum(int[] num) { 3 | 4 | Arrays.sort(num); 5 | 6 | List> res = new LinkedList<>(); 7 | 8 | for (int i = 0; i < num.length-2; i++) { 9 | 10 | if (i == 0 || (i > 0 && num[i] != num[i-1])) { 11 | 12 | int lo = i+1, hi = num.length-1, sum = 0 - num[i]; 13 | 14 | while (lo < hi) { 15 | if (num[lo] + num[hi] == sum) { 16 | 17 | res.add(Arrays.asList(num[i], num[lo], num[hi])); 18 | 19 | while (lo < hi && num[lo] == num[lo+1]) lo++; 20 | while (lo < hi && num[hi] == num[hi-1]) hi--; 21 | 22 | lo++; hi--; 23 | } 24 | else if (num[lo] + num[hi] < sum) lo++; 25 | 26 | else hi--; 27 | } 28 | } 29 | } 30 | return res; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /ReverseNodesInKGroup/CppSolutionReverseKNodes.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* reverseKGroup(ListNode* head, int k) { 14 | if(head==NULL || k==1) return head; 15 | 16 | ListNode* dummy=new ListNode(0); 17 | dummy->next=head; 18 | ListNode *cur=dummy,*nex=dummy,*pre=dummy; 19 | int count=0; 20 | while(cur->next!=NULL){ 21 | cur=cur->next; 22 | count++; 23 | } 24 | while(count>=k){ 25 | cur=pre->next; 26 | nex=cur->next; 27 | for(int i=1;inext=nex->next; 29 | nex->next=pre->next; 30 | pre->next=nex; 31 | nex=cur->next; 32 | } 33 | pre=cur; 34 | count-=k; 35 | } 36 | return dummy->next; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Search in Rotated Sorted Array/CppSolutionSearchInRotatedSortedArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int search(vector& nums, int target) { 4 | 5 | int low = 0, high = nums.size()-1; 6 | while(low <= high) { 7 | 8 | int mid = (low+high)/2; 9 | 10 | if(nums[mid] == target) { 11 | 12 | return mid; 13 | } 14 | if(nums[low] <= nums[mid]) { 15 | 16 | if(target >= nums[low] && target <= nums[mid]) { 17 | 18 | high = mid - 1; 19 | } 20 | else { 21 | 22 | low = mid + 1; 23 | } 24 | } 25 | else { 26 | 27 | if(target >= nums[mid] && target <= nums[high]) { 28 | 29 | low = mid + 1; 30 | } 31 | else { 32 | 33 | high = mid-1; 34 | } 35 | } 36 | } 37 | 38 | return -1; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /Largest Rectangle in Histogram/JavaSolutionLargestRectangleInHistogram.java: -------------------------------------------------------------------------------- 1 | // Question link : https://leetcode.com/problems/largest-rectangle-in-histogram/ 2 | 3 | public static int largestRectangleArea(int[] height) { 4 | if (height == null || height.length == 0) { 5 | return 0; 6 | } 7 | int[] lessFromLeft = new int[height.length]; // idx of the first bar the left that is lower than current 8 | int[] lessFromRight = new int[height.length]; // idx of the first bar the right that is lower than current 9 | lessFromRight[height.length - 1] = height.length; 10 | lessFromLeft[0] = -1; 11 | 12 | for (int i = 1; i < height.length; i++) { 13 | int p = i - 1; 14 | 15 | while (p >= 0 && height[p] >= height[i]) { 16 | p = lessFromLeft[p]; 17 | } 18 | lessFromLeft[i] = p; 19 | } 20 | 21 | for (int i = height.length - 2; i >= 0; i--) { 22 | int p = i + 1; 23 | 24 | while (p < height.length && height[p] >= height[i]) { 25 | p = lessFromRight[p]; 26 | } 27 | lessFromRight[i] = p; 28 | } 29 | 30 | int maxArea = 0; 31 | for (int i = 0; i < height.length; i++) { 32 | maxArea = Math.max(maxArea, height[i] * (lessFromRight[i] - lessFromLeft[i] - 1)); 33 | } 34 | 35 | return maxArea; 36 | } 37 | -------------------------------------------------------------------------------- /Median of Two Sorted Arrays/CppSolutionMedianOfSortedArrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double findMedianSortedArrays(vector& nums1, vector& nums2) { 4 | if(nums2.size() < nums1.size()) return findMedianSortedArrays(nums2, nums1); 5 | int n1 = nums1.size(); 6 | int n2 = nums2.size(); 7 | int low = 0, high = n1; 8 | 9 | while(low <= high) { 10 | int cut1 = (low+high) >> 1; 11 | int cut2 = (n1 + n2 + 1) / 2 - cut1; 12 | 13 | 14 | int left1 = cut1 == 0 ? INT_MIN : nums1[cut1-1]; 15 | int left2 = cut2 == 0 ? INT_MIN : nums2[cut2-1]; 16 | 17 | int right1 = cut1 == n1 ? INT_MAX : nums1[cut1]; 18 | int right2 = cut2 == n2 ? INT_MAX : nums2[cut2]; 19 | 20 | 21 | if(left1 <= right2 && left2 <= right1) { 22 | if( (n1 + n2) % 2 == 0 ) 23 | return (max(left1, left2) + min(right1, right2)) / 2.0; 24 | else 25 | return max(left1, left2); 26 | } 27 | else if(left1 > right2) { 28 | high = cut1 - 1; 29 | } 30 | else { 31 | low = cut1 + 1; 32 | } 33 | } 34 | return 0.0; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /3 Sum/CppSolution3Sum.cpp: -------------------------------------------------------------------------------- 1 | //Problem Link: https://leetcode.com/problems/3sum/ 2 | 3 | //Approach : 2 Pointers 4 | 5 | //TC = O(N^2) 6 | //SC = O(M)[for storage for answers] 7 | 8 | #include 9 | using namespace std; 10 | 11 | class Solution { 12 | public: 13 | vector> threeSum(vector nums) { 14 | vector> ans; 15 | if(nums.size() < 3) return ans; 16 | 17 | sort(nums.begin(), nums.end()); 18 | for(int i = 0; i < nums.size()-2; i++){ 19 | if(i == 0 || ( i > 0 && nums[i] != nums[i-1])){ 20 | int lo = i+1, hi = nums.size()-1, sum = 0 - nums[i]; 21 | 22 | while(lo < hi){ 23 | if(nums[lo] + nums[hi] == sum){ 24 | ans.push_back({nums[i],nums[lo],nums[hi]}); 25 | 26 | while(lo < hi && nums[lo] == nums[lo+1]) lo++; 27 | while(lo < hi && nums[hi] == nums[hi-1]) hi--; 28 | 29 | lo++; 30 | hi--; 31 | } 32 | else if(nums[lo] + nums[hi] < sum) lo++; 33 | else hi--; 34 | } 35 | } 36 | } 37 | return ans; 38 | } 39 | }; -------------------------------------------------------------------------------- /Spiral Matrix/javaSolutionSpiralMatrix.java: -------------------------------------------------------------------------------- 1 | Problem Link: https://leetcode.com/problems/spiral-matrix/ 2 | 3 | public List spiralOrder(int[][] matrix) { 4 | int minR=0,minC=0; 5 | int maxR=matrix.length-1; 6 | int maxC=matrix[0].length-1; 7 | int count=0; 8 | int total=matrix.length*matrix[0].length; 9 | List spiralTraversal=new ArrayList<>(); 10 | 11 | while(count=minC && count=minR && count mp=new HashMap<>(); 16 | return solve(prices,0,true,2,mp); 17 | } 18 | 19 | public static int solve(int price[],int i,boolean canBuy,int count,Map mp){ 20 | 21 | if(i>=price.length || count<=0) return 0; 22 | 23 | String key=i+"!"+canBuy+"!"+count; 24 | 25 | if(mp.containsKey(key)) return mp.get(key); 26 | 27 | if(canBuy){ 28 | 29 | int idle=solve(price,i+1,canBuy,count,mp); 30 | int buying=(-1*price[i])+solve(price,i+1,false,count,mp); 31 | mp.put(key,Math.max(idle,buying)); 32 | return mp.get(key); 33 | 34 | }else{ 35 | 36 | int idle=solve(price,i+1,canBuy,count,mp); 37 | int selling=price[i]+solve(price,i+1,true,count-1,mp); 38 | mp.put(key,Math.max(idle,selling)); 39 | return mp.get(key); 40 | 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /BestTimeToBuyAndSellStock-iv/javaSolutionBestTimeToBuyAndSellStockFour.java: -------------------------------------------------------------------------------- 1 | //Question Link= https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/ 2 | 3 | 4 | import java.util.*; 5 | 6 | public class BestTimeToBuyAndSellStockFour{ 7 | 8 | public static void main(String[] args) throws Exception { 9 | int k=3; 10 | int prices[]={1,3,4,2,6,1,6}; 11 | System.out.println(maxProfit(prices,k)); 12 | } 13 | 14 | 15 | public static int maxProfit(int[] prices,int k) { 16 | Map mp=new HashMap<>(); 17 | return solve(prices,0,true,k,mp); 18 | } 19 | 20 | public static int solve(int price[],int i,boolean canBuy,int count,Map mp){ 21 | 22 | if(i>=price.length || count<=0) return 0; 23 | 24 | String key=i+"!"+canBuy+"!"+count; 25 | 26 | if(mp.containsKey(key)) return mp.get(key); 27 | 28 | if(canBuy){ 29 | 30 | int idle=solve(price,i+1,canBuy,count,mp); 31 | int buying=(-1*price[i])+solve(price,i+1,false,count,mp); 32 | mp.put(key,Math.max(idle,buying)); 33 | return mp.get(key); 34 | 35 | }else{ 36 | 37 | int idle=solve(price,i+1,canBuy,count,mp); 38 | int selling=price[i]+solve(price,i+1,true,count-1,mp); 39 | mp.put(key,Math.max(idle,selling)); 40 | return mp.get(key); 41 | 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Best Time to Buy and Sell Stocks/javaSolutionBestTimeToBuyAndSellStockFour.java: -------------------------------------------------------------------------------- 1 | //Question Link= https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/ 2 | 3 | 4 | import java.util.*; 5 | 6 | public class BestTimeToBuyAndSellStockFour{ 7 | 8 | public static void main(String[] args) throws Exception { 9 | int k=3; 10 | int prices[]={1,3,4,2,6,1,6}; 11 | System.out.println(maxProfit(prices,k)); 12 | } 13 | 14 | 15 | public static int maxProfit(int[] prices,int k) { 16 | Map mp=new HashMap<>(); 17 | return solve(prices,0,true,k,mp); 18 | } 19 | 20 | public static int solve(int price[],int i,boolean canBuy,int count,Map mp){ 21 | 22 | if(i>=price.length || count<=0) return 0; 23 | 24 | String key=i+"!"+canBuy+"!"+count; 25 | 26 | if(mp.containsKey(key)) return mp.get(key); 27 | 28 | if(canBuy){ 29 | 30 | int idle=solve(price,i+1,canBuy,count,mp); 31 | int buying=(-1*price[i])+solve(price,i+1,false,count,mp); 32 | mp.put(key,Math.max(idle,buying)); 33 | return mp.get(key); 34 | 35 | }else{ 36 | 37 | int idle=solve(price,i+1,canBuy,count,mp); 38 | int selling=price[i]+solve(price,i+1,true,count-1,mp); 39 | mp.put(key,Math.max(idle,selling)); 40 | return mp.get(key); 41 | 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Sieve Of Eratosthenes/JavaSolutionSieveOfEratosthenes.java: -------------------------------------------------------------------------------- 1 | /* 2 | Question link: https://leetcode.com/problems/count-primes/ 3 | Question: Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number. 4 | For ex: 5 | input: n = 50 6 | output: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47. 7 | */ 8 | 9 | import java.util.*; 10 | //to print all primes upto n 11 | public class SieveOfEratosthenes{ 12 | public static void main(String[] args){ 13 | Scanner sc = new Scanner(System.in); 14 | 15 | int n = sc.nextInt(); //to store the limit 16 | 17 | boolean[] check = new boolean[n+1]; 18 | Arrays.fill(check,true); //It will first assign all the indexes in the array with true 19 | 20 | for(int i = 2;i*i r2) { 34 | 35 | high = mid-1; 36 | } 37 | else { 38 | 39 | low = mid+1; 40 | } 41 | } 42 | 43 | return 0.0; 44 | } 45 | -------------------------------------------------------------------------------- /Trapping Rainwater/trapping_rainwater.cpp: -------------------------------------------------------------------------------- 1 | //Trapping rainwater problem 2 | // Efficient solution 3 | // Expected Time Complexity: O(N). 4 | // Expected Auxiliary Space: O(N). 5 | // Asked in Amazon Microsoft Google Flipkart 6 | #include 7 | 8 | using namespace std; 9 | 10 | int main() 11 | { 12 | int t, n; 13 | //test cases 14 | cin >> t; 15 | while (t--) 16 | { 17 | //size of array 18 | cin >> n; 19 | long long arr[n]; 20 | //adding elements 21 | for (int i = 0; i < n; i++) 22 | { 23 | cin >> arr[i]; 24 | } 25 | 26 | long long result = 0; 27 | 28 | // maximum element on left and right 29 | int left_max = 0, right_max = 0; 30 | 31 | // indices to traverse the array 32 | int lo = 0, hi = n - 1; 33 | 34 | while (lo <= hi) 35 | { 36 | if (arr[lo] < arr[hi]) 37 | { 38 | if (arr[lo] > left_max) 39 | // update max in left 40 | left_max = arr[lo]; 41 | else 42 | // water on curr element = max - curr 43 | result += left_max - arr[lo]; 44 | lo++; 45 | } 46 | else 47 | { 48 | if (arr[hi] > right_max) 49 | // update right maximum 50 | right_max = arr[hi]; 51 | else 52 | result += right_max - arr[hi]; 53 | hi--; 54 | } 55 | } 56 | 57 | cout << result; 58 | } 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /Rotate Image/CSolutionRotateImage.c: -------------------------------------------------------------------------------- 1 | // C program to turn an 2 | // image by 90 Degree 3 | #include 4 | #include 5 | 6 | void displayMatrix(unsigned int const *p, 7 | unsigned int row, 8 | unsigned int col); 9 | 10 | void rotate(unsigned int *pS, 11 | unsigned int *pD, 12 | unsigned int row, 13 | unsigned int col); 14 | 15 | void displayMatrix(unsigned int const *p, 16 | unsigned int r, 17 | unsigned int c) 18 | { 19 | unsigned int row, col; 20 | printf("\n\n"); 21 | 22 | for (row = 0; row < r; row++) 23 | { 24 | for (col = 0; col < c; col++) 25 | printf("%d\t", * (p + row * c + col)); 26 | printf("\n"); 27 | } 28 | 29 | printf("\n\n"); 30 | } 31 | 32 | void rotate(unsigned int *pS, 33 | unsigned int *pD, 34 | unsigned int row, 35 | unsigned int col) 36 | { 37 | unsigned int r, c; 38 | for (r = 0; r < row; r++) 39 | { 40 | for (c = 0; c < col; c++) 41 | { 42 | *(pD + c * row + (row - r - 1)) = 43 | *(pS + r * col + c); 44 | } 45 | } 46 | } 47 | 48 | // Driver Code 49 | int main() 50 | { 51 | 52 | // declarations 53 | unsigned int image[][4] = {{1,2,3,4}, 54 | {5,6,7,8}, 55 | {9,10,11,12}}; 56 | unsigned int *pSource; 57 | unsigned int *pDestination; 58 | unsigned int m, n; 59 | 60 | // setting initial values 61 | // and memory allocation 62 | m = 3, n = 4, pSource = (unsigned int *)image; 63 | pDestination = 64 | (unsigned int *)malloc 65 | (sizeof(int) * m * n); 66 | 67 | // process each buffer 68 | displayMatrix(pSource, m, n); 69 | 70 | rotate(pSource, pDestination, m, n); 71 | 72 | displayMatrix(pDestination, n, m); 73 | 74 | free(pDestination); 75 | 76 | getchar(); 77 | return 0; 78 | } 79 | -------------------------------------------------------------------------------- /Bag of Tokens/README.md: -------------------------------------------------------------------------------- 1 | # [Question Link](https://leetcode.com/problems/bag-of-tokens/) 2 | 3 | You have an initial power of power, an initial score of 0, and a bag of tokens where tokens[i] is the value of the ith token (0-indexed). 4 | 5 | Your goal is to maximize your total score by potentially playing each token in one of two ways: 6 | 7 | - If your current power is at least tokens[i], you may play the ith token face up, losing tokens[i] power and gaining 1 score. 8 | - If your current score is at least 1, you may play the ith token face down, gaining tokens[i] power and losing 1 score. 9 | - Each token may be played at most once and in any order. You do not have to play all the tokens. 10 | 11 | Return the largest possible score you can achieve after playing any number of tokens. 12 | 13 | 14 | 15 | Example 1: 16 | ``` 17 | Input: tokens = [100], power = 50 18 | Output: 0 19 | Explanation: Playing the only token in the bag is impossible because you either have too little power or too little score. 20 | ``` 21 | 22 | 23 | Example 2: 24 | ``` 25 | Input: tokens = [100,200], power = 150 26 | Output: 1 27 | Explanation: Play the 0th token (100) face up, your power becomes 50 and score becomes 1. 28 | There is no need to play the 1st token since you cannot play it face up to add to your score. 29 | ``` 30 | 31 | Example 3: 32 | ``` 33 | Input: tokens = [100,200,300,400], power = 200 34 | Output: 2 35 | Explanation: Play the tokens in this order to get a score of 2: 36 | 1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1. 37 | 2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0. 38 | 3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1. 39 | 4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2. 40 | ``` 41 | 42 | Constraints: 43 | ``` 44 | 0 <= tokens.length <= 1000 45 | 0 <= tokens[i], power < 104 46 | ``` 47 | -------------------------------------------------------------------------------- /Longest Palindromic Substring/CppSolutionLongestPalindromicSubstring.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string findSub(int i, int j, string s) { 4 | 5 | string ans = ""; 6 | while(i <= j) { 7 | 8 | ans += s[i]; 9 | i++; 10 | } 11 | 12 | return ans; 13 | } 14 | string longestPalindrome(string s) { 15 | 16 | int dp[s.length()][s.length()]; 17 | int max = 0; 18 | string ans=""; 19 | 20 | for(int i = 0; i < s.length(); ++i) { 21 | 22 | int st = 0, end = i; 23 | 24 | for(int j = 0; j < s.length()-i; ++j) { 25 | 26 | if(i > 1) { 27 | 28 | dp[st][end] = 0; 29 | 30 | if(s[st] == s[end] && dp[st+1][end-1]) { 31 | 32 | dp[st][end] = 1; 33 | 34 | if(end-st > max) { 35 | 36 | ans = findSub(st, end, s); 37 | max = end-st; 38 | } 39 | } 40 | } 41 | else { 42 | 43 | if(i) { 44 | 45 | dp[st][end] = 0; 46 | 47 | if(s[st] == s[end]) { 48 | 49 | dp[st][end] = 1; 50 | 51 | if(end-st > max) { 52 | 53 | ans = findSub(st, end, s); 54 | max = end-st; 55 | } 56 | } 57 | } 58 | else { 59 | 60 | dp[st][end] = 1; 61 | ans = s[st]; 62 | max = 0; 63 | } 64 | } 65 | 66 | st++; 67 | end++; 68 | } 69 | } 70 | return ans; 71 | } 72 | }; 73 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Do not make a PR without getting the issues assigned. Read Rules Carefully! 2 | 3 | [![MasterHead](https://user-images.githubusercontent.com/64991656/135403993-8436cfd2-5314-4c03-8509-d33e51c565b2.png)](https://hacktoberfest.digitalocean.com) 4 |

Kickstart your Open-Source Journey!!

5 |

Read It Carefully.

6 | 7 | 8 | # Top-Interview-Questions--Leetcode 9 | These are solutions in Cpp, Java, Python for problems in [Top Interview Questions from Leetcode](https://leetcode.com/explore/interview/card/top-interview-questions-hard/). 10 | 11 | To understand and get an overview of Hacktoberfest, Check out [this video](https://youtu.be/QfPY3346TpI) 12 | 13 | # Here's a [DEMO video](https://youtu.be/VCUZK-o5eFg) of how to contribute. 14 | 15 | ## Rules To Contribute To This Repo 16 | 17 | - You can write solutions in C/C++/Java/Python for a particular Question. 18 | - check your code twice before PR, only correct codes are going to be considered. 19 | - Follow the file naming convention for all your pull requests. 20 | - While adding any content it should be inside its appropriate folder. 21 | - if there is any problem with an inaccurate solution create an issue! 22 | - Do not create duplicate issues, firstly check if that issue has been created already or not. 23 | - Do not make a PR without getting issues assigned to you! ( they will not be merged ). 24 | - Link your PR with the Issue number. 25 | - if you don't work on the issue within 4 days, It will be assigned to another interested member. 26 | - make sure you read these rules twice. 27 | 28 | 29 | ## file naming convention 30 | 31 | | use | file type | comments | 32 | | ------------------ | ------------------------------ | ----------------------------------------------------------------------------------------------------------- | 33 | | new question | **[question name]** (folder) | All solution files for this question should be under this folder 34 | | c++ solutions | **cppSolution[question name].cpp** | also comment the question link on the top 35 | 36 | ## Steps For Contribution 37 | 38 | 1. Fork this repo. 39 | 2. Star this repo. 40 | 3. Get an issue assigned. 41 | 3. Work on the issue, add a file ( txt/cpp ) inside the appropriate folder. 42 | 4. Commit the code. 43 | 5. Make a pull request. 44 | 45 | --- 46 | 47 | 48 | ## Ideas for contribution 49 | 50 | - Repo contains folders of Top-Interview-Questions by Leetcode. You can **add a solution** to an unanswered question. 51 | - You can **update the existing solution** with a better one ( better complexity). 52 | - You can **add new questions** and solutions in diff. languages. 53 | - **solve issues** raised by other people or yourself. 54 | - make a webpage ( hosted from GitHub readme ) more appealing and updated. 55 | - You can add question link along with descrption to each folder. 56 | 57 | 58 | 59 | ##

Connect with me:

60 |

61 | 62 | khushboogoel01 63 | _khushboo.goel 64 | khushboo goel 65 |

66 | 67 | If you post about it on social media, Don't forget to tag me ;) 68 | -------------------------------------------------------------------------------- /interLeavingString/interLeavingString.cpp: -------------------------------------------------------------------------------- 1 | // Source : https://oj.leetcode.com/problems/interleaving-string/ 2 | 3 | /********************************************************************************** 4 | * 5 | * Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. 6 | * 7 | * For example, 8 | * Given: 9 | * s1 = "aabcc", 10 | * s2 = "dbbca", 11 | * 12 | * When s3 = "aadbbcbcac", return true. 13 | * When s3 = "aadbbbaccc", return false. 14 | * 15 | * 16 | **********************************************************************************/ 17 | 18 | #include 19 | #include 20 | #include 21 | using namespace std; 22 | 23 | /* 24 | Considering: 25 | s1 = a1, a2 ........a(i-1), ai 26 | s2 = b1, b2, .......b(j-1), bj 27 | s3 = c1, c3, .......c(i+j-1), c(i+j) 28 | Defined 29 | 30 | match[i][j] means s1[0..i] and s2[0..j] is matched S3[0..i+j] 31 | So, if ai == c(i+j), then match[i][j] = match[i-1][j], which means 32 | s1 = a1, a2 ........a(i-1) 33 | s2 = b1, b2, .......b(j-1), bj 34 | s3 = c1, c3, .......c(i+j-1) 35 | Same, if bj = c(i+j), then match[i][j] = match[i][j-1]; 36 | Formula: 37 | Match[i][j] = 38 | (s3[i+j-1] == s1[i]) && match[i-1][j] || 39 | (s3[i+j-1] == s2[j]) && match[i][j-1] 40 | Initialization: 41 | i=0 && j=0, match[0][0] = true; 42 | i=0, s3[j] == s2[j], match[0][j] |= match[0][j-1] 43 | s3[j] != s2[j], match[0][j] = false; 44 | j=0, s3[i] == s1[i], match[i][0] |= match[i-1][0] 45 | s3[i] != s1[i], Match[i][0] = false; 46 | */ 47 | 48 | 49 | 50 | 51 | //Dynamic Programming 52 | bool isInterleave(string s1, string s2, string s3) { 53 | 54 | if (s1.size() + s2.size() != s3.size()) { 55 | return false; 56 | } 57 | 58 | vector< vector > match(s1.size()+1, vector(s2.size()+1, false) ); 59 | 60 | match[0][0] = true; 61 | for(int i=1; i<=s1.size(); i++) { 62 | if (s1[i-1] == s3[i-1] ) { 63 | match[i][0] = true; 64 | }else{ 65 | break; 66 | } 67 | } 68 | for(int i=1; i<=s2.size(); i++) { 69 | if (s2[i-1] == s3[i-1] ) { 70 | match[0][i] = true; 71 | }else{ 72 | break; 73 | } 74 | } 75 | 76 | 77 | for(int i=1; i<=s1.size(); i++) { 78 | for(int j=1; j<=s2.size(); j++) { 79 | if (s1[i-1] == s3[i+j-1]) { 80 | match[i][j] = match[i-1][j] || match[i][j]; 81 | } 82 | if (s2[j-1] == s3[i+j-1]) { 83 | match[i][j] = match[i][j-1] || match[i][j]; 84 | } 85 | } 86 | } 87 | return match[s1.size()][s2.size()]; 88 | } 89 | 90 | //Time Limit Exceeded 91 | bool isInterleave_dfs(string s1, string s2, string s3) { 92 | if (s1.size() + s2.size() != s3.size()) { 93 | return false; 94 | } 95 | 96 | const char *p1 = s1.c_str(), *p2 = s2.c_str(), *p3 = s3.c_str(); 97 | for (; *p3 != '\0'; p3++){ 98 | if (*p3 == *p1 && *p3!=*p2) { 99 | p1++; 100 | }else if ( *p3 == *p2 && *p3 != *p1) { 101 | p2++; 102 | }else if (*p3==*p1 && *p3 ==*p2) { 103 | if (isInterleave(p1+1, p2, p3+1) == false){ 104 | return isInterleave(p1, p2+1, p3+1); 105 | } 106 | return true; 107 | }else{ 108 | return false; 109 | } 110 | } 111 | return ( *p1 =='\0' && *p2 =='\0' && *p3 =='\0' ); 112 | } 113 | 114 | #define TEST(s1, s2, s3) cout << s1 << ", " << s2 << " = " << s3 << " : " << isInterleave(s1,s2,s3) << endl; 115 | int main(int argc, char**argv) 116 | { 117 | string s1= "aabcc", s2 = "dbbca"; 118 | TEST(s1,s2, "aadbbcbcac"); 119 | TEST(s1,s2, "aadbbbaccc"); 120 | 121 | s1="c"; s2="ca"; 122 | TEST(s1, s2, "cca"); 123 | TEST(s1, s2, "cac"); 124 | 125 | s1 = "bbbbbabbbbabaababaaaabbababbaaabbabbaaabaaaaababbbababbbbbabbbbababbabaabababbbaabababababbbaaababaa"; 126 | s2 = "babaaaabbababbbabbbbaabaabbaabbbbaabaaabaababaaaabaaabbaaabaaaabaabaabbbbbbbbbbbabaaabbababbabbabaab"; 127 | string s3 = "babbbabbbaaabbababbbbababaabbabaabaaabbbbabbbaaabbbaaaaabbbbaabbaaabababbaaaaaabababbababaababbababbbababbbbaaaabaabbabbaaaaabbabbaaaabbbaabaaabaababaababbaaabbbbbabbbbaabbabaabbbbabaaabbababbabbabbab"; 128 | TEST(s1, s2, s3); 129 | 130 | return 0; 131 | } 132 | --------------------------------------------------------------------------------