├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Contains Duplicate.py ├── Easy ├── 101. Symmetric_Tree.py ├── 69. Sqrt(x).py ├── 94. Binary_Tree_Inorder_Traversal.py ├── A.cpp ├── A_Restoring_numbers.cpp ├── A_SUM_OF_Round_Numbers.cpp ├── Add_Binary.cpp ├── ArrangingCoins441.java ├── BestTimeToBuyStock.py ├── Best_Time_to_Buy_and_Sell_Stock.cpp ├── Best_Time_to_Buy_and_Sell_Stock.java ├── BinarySearch.java ├── BubbleSort ├── Build-Array-From-Permutation.cpp ├── Can-make-arithmetic-progression-from-sequence.py ├── CommanFactors.cpp ├── Count Asterisks.cpp ├── CountNegGrid.java ├── Create Maximum sum subarray of size k.cpp ├── DisBetweenTwoArrayLeetcode1385.java ├── EvenOddNumber.java ├── Factorial.java ├── FizzBuzz.js ├── Inheritance.java ├── IsSubSequence.cpp ├── Largest Perimeter Triangle.cpp ├── Length_of_last_word.cpp ├── LinkedList_Cycle.py ├── Long_sharing_chef.cpp ├── LongestPrefix.java ├── MajorityElement.java ├── Maximum Product of Three Numbers.cpp ├── MaximumDepthOfBinaryTree.java ├── MaximumElementAfterDecreasingAndRearranging.cpp ├── MergeArray.java ├── Merge_Strings_Alternately1768.java ├── Middle of the Linked List.py ├── MiddleNodeLinkedList.java ├── Move Zeroes.py ├── Number of Arithmetic Triplets.cpp ├── NumsNotInArrayLeetcode448.java ├── Palindrome Number(LC).cpp ├── PalindromeNumber.ts ├── Problem_69.Sqrt(x).cpp ├── Ransom Note.cpp ├── Remove Duplicates from Sorted Array.cpp ├── RichestCustomerWealthSolution.java ├── Roman_to_Integer.cpp ├── Roman_to_Integer13.java ├── ShuffleTheArray.js ├── SmallestLetter.java ├── Sqrt.java ├── Symmetric Tree.cpp ├── Two_Sum.py ├── Two_sum.cpp ├── Valid_ParenthesesLC.cpp ├── Valid_anagram.java ├── check_distance_between_same_letters.java ├── count-no-of-pairs.cpp ├── count_items_matching_a_rule.cpp ├── kthSmallestInMatrix.java ├── longestCommanPrefix.cpp ├── main (3).cpp ├── plus one.py ├── plusOne.js ├── primeNumber.java ├── quick_sort.cpp ├── richest-customer-wealth.cpp ├── twoSum.java └── validParentheses.java ├── Hacktoberfest2022.png ├── Hard ├── 140. Word Break II.py ├── 25.Reverse_Nodes_in_K_Groups.cpp ├── 336. Palindrome Pairs.cpp ├── 37. Sudoku Solver.py ├── 4. Median of Two Sorted Arrays.py ├── 44. Wildcard Matching.py ├── AggressiveCows.cpp ├── Array_Divisible.cpp ├── BubbleSort.java ├── Count Subarrays.cpp ├── FindMountainArraySolution.java ├── Fraction_class.cpp ├── Frog_Position_After_T_Seconds.java ├── Maximum Deletions on a String.cpp ├── MedianFinder.java ├── MedianOfTwoSortedArrays.java ├── Median_from_DataStream.cpp ├── Median_of_ Two_Sorted_Arrays.cpp ├── Merge_k_Sorted_Lists.py ├── Merge_k_sorted_list.cpp ├── Minimum Weighted Subgraph With the Required Paths.cpp ├── N-Queens.cpp ├── Number_of_Pairs_Satisfying_Inequality.cpp ├── Scramble_String.cpp ├── Sliding Window Maximum.cpp ├── Subset_Sum_Problem.cpp ├── Substring_with_catenation_of_All_words.cpp ├── TopoLogical-Sort.cpp ├── Word Ladder.cpp ├── closestKvalues.java ├── countSmaller.java ├── findMin.java ├── first_missing_positive.cpp ├── ladderLength.java ├── largest_Rectangle_in_Histogram.cpp ├── lineartree.cpp ├── numberToWords.java ├── skyline.java ├── splitArr.java ├── trap1.java └── trapping_rain_water.cpp ├── LICENSE ├── Medium ├── 91 │ └── Decode Way │ │ └── Solution.py ├── 1155 │ └── Number of Dice Rolls With Target Sum │ │ └── Solution.py ├── word-break.cpp ├── 240. Search a 2D Matrix II │ └── Rotate Image │ │ └── rotate_image_48.java ├── 4sum.cpp ├── 78 Subsets.py ├── 99-Recovery-Binary-searchTree.py ├── AddTwoNumbersLinkedList.java ├── Add_One_Row_to_Tree.cpp ├── Armstrongnumber.java ├── Bitwise XOR of All Pairings.cpp ├── Combination_Sum.java ├── Container With Most Water │ ├── Container With Most Water.java │ └── Container With Most Water.py ├── Count Number Bad Pairs │ ├── leet_code2364.cpp │ └── leetcode23.java ├── Decode Way │ └── Solution.java ├── DecodeWays.cpp ├── DecodeWays.java ├── DeleteNodeLinkedList.java ├── Design Linked List ├── Divide_Two_Integers.cpp ├── Fair_play.cpp ├── Find All Good Indices │ └── Find-All-Good-Indices.cpp ├── Find First and Last Position of Element in Sorted Array.java ├── Find Peak Element.cpp ├── First_And_Last_Occurence_of_an_Element.cpp ├── Fruit Into Baskets.py ├── House_robber.java ├── IIISearch a 2D Matrix II │ └── Rotate Image │ │ └── rotate_image_48.java ├── IntersectionOfTwoArrays.java ├── Jump_Game.java ├── KClosestElement.java ├── KadaneAlgo.java ├── KoKoEatingBanana.java ├── LargestnumberofArray.java ├── Letter_Combinations_of_a_Phone_Number.java ├── Letter_Combinations_of_a_Phone_Number.py ├── LinkedListCycleII.java ├── Longest Subarray With Maximum Bitwise AND │ └── Longest-Subarray-With-Maximum-Bitwise-AND.cpp ├── Longest Substring Without Repeating Characters.cpp ├── Longest Substring Without Repeating Characters │ ├── solution.js │ └── solution.py ├── Longest Uploaded Prefix │ └── Longest-Uploaded-Prefix.cpp ├── Longest-Consecutive-sequence.cpp ├── Lru-cache.cpp ├── MCLV │ └── Number of Dice Rolls With Target Sum │ │ └── Solution.py ├── Max Area of Island.cpp ├── MaxSubArraySum.java ├── Max_Bitwise_And.cpp ├── Maximal-square.cpp ├── Maximum Sum of an Hourglass.cpp ├── Minimize XOR.cpp ├── Minimum time to make Rope Colourful.cpp ├── Minimum_Absolute_Sum_Difference.cpp ├── Multiply_Strings.java ├── Number of Dice Rolls With Target SumSolution.java ├── PeakIndexMountainArraySolution.java ├── Peakindex.cpp ├── Problem7.java ├── Pseudo-Palindromic Paths in a Binary Tree.cpp ├── Recovery-Binary-searchTree ├── Remove Duplicates from Sorted Array │ ├── Remove Nth Node From End of List.java │ └── solution.cpp ├── Remove Duplicates from sorted linked list (82) │ └── leetcode82.java ├── RemoveNthNodeFromEnd.cpp ├── Remove_Duplicates.cpp ├── RotateArraySolution.java ├── Rotate_List.py ├── RotatedBSDuplicates.java ├── Search a 2D Matrix II │ └── Search2DMatrix.cpp ├── SearchRotatedSortedArray.java ├── Search_in_rotated_SortedArray.cpp ├── SetMatrixZero.java ├── ShipCapacity.java ├── Simplify_Path.java ├── SolutionForSpiralMatrix_54_leetcode.java ├── Spiral_Matrix.cpp ├── Spiral_Matrix.java ├── String_to_integer(atoi).cpp ├── Subarray Sum Equals K.cpp ├── Subsets ├── Subsets II │ └── M#1(Recursion CPP) ├── Sum_Closest.java ├── Sum_of_two_integers.cpp ├── Swap Nodes In Pairs.java ├── ThreeSum.swift ├── Triangle.java ├── Ugly_number_2.cpp ├── Unique_Paths.java ├── Unique_paths.cpp ├── ValidSudoko.cpp ├── XCI │ └── 91 │ │ └── Solution.py ├── findDuplicate.java ├── flattenBTtoLL.cpp ├── good_pair.cpp ├── linkedlist.c ├── min_in_sorted_rotated_sorted_array.py ├── nextPermutation.cpp ├── numRollsToTarget.py ├── pattern.cpp ├── powXN.java ├── setMatrixZeroes.cpp ├── stringCompression.cpp ├── subsets.CPP ├── sum.cpp └── zigzag_traversal_binary_tree.cpp ├── README.md └── twitter.png /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # HOW TO CONTRIBUTE 2 |

LEETCODE

3 | 4 | ### It has three folder EASY, MEDIUM, HARD, solve the question of LEETCODE and make a PR according to its level 5 | 6 | 1. fork repository. 7 | 2. clone repository. 8 | 3. now code. 9 | 10 | ### after coding in folders--------------------------------------------------------------------------- 11 | git add . 12 |
13 | git commit -m"a meaningful message!" 14 |
15 | git push origin main 16 | 17 | ### . Then make PR!! 18 | ### . Add question link also in your code 19 | BACK TO [README.md](https://github.com/Vanshika2063/Leetcode-Questions/blob/main/README.md) 20 |
21 |
22 |
23 | 24 | # Please share it on social media and tag me on twitter 25 | 26 | ### Here is my twitter account:- 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /Contains Duplicate.py: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/contains-duplicate/ 2 | 3 | 4 | class Solution: 5 | def containsDuplicate(self, nums: List[int]) -> bool: 6 | d = {} 7 | 8 | for i in nums: 9 | if i in d: 10 | return True 11 | d[i] = None 12 | 13 | return False 14 | -------------------------------------------------------------------------------- /Easy/101. Symmetric_Tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isSymmetric(self, root: Optional[TreeNode]) -> bool: 3 | def sp(node1, node2): 4 | if node1 is None: 5 | return node2 is None 6 | if node2 is None: 7 | return False 8 | return node1.val == node2.val and sp(node1.left, node2.right) and sp(node1.right, node2.left) 9 | 10 | if root is None: 11 | return True 12 | return sp(root.left, root.right) 13 | -------------------------------------------------------------------------------- /Easy/69. Sqrt(x).py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def mySqrt(self, x: int) -> int: 3 | return int(sqrt(x)) 4 | -------------------------------------------------------------------------------- /Easy/94. Binary_Tree_Inorder_Traversal.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: 3 | ans=[root] 4 | fi=[] 5 | def trv(root,fi): 6 | if root: 7 | trv(root.left,fi) 8 | fi.append(root.val) 9 | trv(root.right,fi) 10 | 11 | trv(root,fi) 12 | 13 | return fi 14 | -------------------------------------------------------------------------------- /Easy/A.cpp: -------------------------------------------------------------------------------- 1 | // Code By- Romijul Laskar 2 | #include 3 | using namespace std; 4 | #define ll long long 5 | int main() 6 | { 7 | ll x; 8 | int X; 9 | ll crime = 0; 10 | ll police = 0; 11 | vector c; 12 | cin >> x; 13 | while (x--) 14 | { 15 | cin >> X; 16 | c.push_back(X); 17 | } 18 | for (int i = 0; i < c.size(); i++) 19 | { 20 | if (c[i] >= 1) 21 | { 22 | police+=c[i]; 23 | } 24 | else 25 | { 26 | if (police != 0) 27 | { 28 | police--; 29 | } 30 | else 31 | { 32 | crime++; 33 | } 34 | } 35 | } 36 | cout << crime; 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /Easy/A_Restoring_numbers.cpp: -------------------------------------------------------------------------------- 1 | //Code By- Romijul Laskar 2 | #include 3 | using namespace std; 4 | #define ll long long 5 | #define deb(x) cout<<#x<>a>>b>>c>>d; 16 | int m=max(a,max(b,max(c,d))); 17 | int n=min(a,min(b,min(c,d))); 18 | vector v; 19 | v.push_back(n); 20 | int l=m-n; 21 | v.push_back(l-1); 22 | v.push_back(abs((l-1)-l)); 23 | // for (auto &k:v) 24 | // { 25 | // cout< 3 | using namespace std; 4 | #define ll long long 5 | int main() 6 | { 7 | int t; 8 | cin >> t; 9 | while (t--) 10 | { 11 | int oc = -1; 12 | string s; 13 | cin >> s; 14 | int z = s.size(); 15 | for (int i = 0; i < s.size(); i++) 16 | { 17 | if (s[i] != 0) 18 | { 19 | oc++; 20 | } 21 | } //1352/A 22 | cout << oc << "\n"; 23 | for (int i = 0; i < z; i++) 24 | { 25 | if (s[i] > 0) 26 | { 27 | cout << s[i]; 28 | for (int j = i; j < oc; j++) 29 | { 30 | cout << 0; 31 | } 32 | cout << " "; 33 | } 34 | } 35 | cout<<"\n"; 36 | } 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /Easy/Add_Binary.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Statement: Given two binary strings a and b, return their sum as a binary string. 3 | 4 | Example: 5 | Input: a = "1010", b = "1011" 6 | Output: "10101" 7 | 8 | */ 9 | 10 | class Solution { 11 | public: 12 | string addBinary(string a, string b) { 13 | string res; 14 | int i = a.length()-1; 15 | int j = b.length()-1; 16 | int carry = 0; 17 | 18 | while(i>=0 || j>=0){ 19 | int sum = carry; 20 | if(i >= 0) sum += a[i--] - '0'; 21 | if(j >= 0) sum += b[j--] - '0'; 22 | carry = sum > 1 ? 1 : 0; 23 | res += to_string(sum % 2); 24 | } 25 | 26 | if(carry) res += to_string(carry); 27 | reverse(res.begin(), res.end()); 28 | return res; 29 | 30 | } 31 | }; -------------------------------------------------------------------------------- /Easy/ArrangingCoins441.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class ArrangingCoins441 { 4 | public static void main(String[] args) { 5 | Scanner in = new Scanner(System.in); 6 | //int a = in.nextInt(); 7 | System.out.println(arrangeCoins(2147483643)); 8 | } 9 | static int arrangeCoins(int n) { 10 | int start = 1, end = n; 11 | while (start <= end) { 12 | int mid = start + (end - start) / 2; 13 | long coins = ((long) mid * (mid + 1)) / 2; 14 | if (coins == n) 15 | return mid; 16 | else if (coins < n) 17 | start = mid + 1; 18 | if (coins > n) { 19 | if (start == end) 20 | return mid - 1; 21 | else 22 | end = mid - 1; 23 | } 24 | } 25 | return end; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Easy/BestTimeToBuyStock.py: -------------------------------------------------------------------------------- 1 | #You are given an array prices where prices[i] is the price of a given stock on the ith day. 2 | #You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. 3 | 4 | class Solution(object): 5 | def maxProfit(self, prices): 6 | maxProf = 0 7 | buy = 0 8 | sell = 1 9 | while sell < len(prices): 10 | curProfit = prices[sell] - prices[buy] 11 | if prices[buy] < prices[sell]: 12 | maxProf = max(curProfit,maxProf) 13 | else: 14 | buy = sell 15 | sell += 1 16 | return maxProf -------------------------------------------------------------------------------- /Easy/Best_Time_to_Buy_and_Sell_Stock.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an array prices where prices[i] is the price of a given stock on the ith day. 3 | You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. 4 | Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. 5 | 6 | Example: 7 | Input: prices = [7,1,5,3,6,4] 8 | Output: 5 9 | 10 | Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. 11 | 12 | Input: prices = [7,6,4,3,1] 13 | Output: 0 14 | 15 | Explanation: In this case, no transactions are done and the max profit = 0. 16 | */ 17 | 18 | /* 19 | Approach: We just have to find the minimum price of the stock on any given day 20 | and selling it on any day after the minimum price day and compute the maximum profit. 21 | */ 22 | 23 | 24 | // Time Complexity: O(N) & Space Complexity: O(1) 25 | class Solution { 26 | public: 27 | int maxProfit(vector& prices) { 28 | 29 | int mini = INT_MAX; 30 | int maxP = 0; 31 | 32 | for(auto x: prices) 33 | { 34 | mini = min(mini, x); 35 | maxP = max(maxP, x-mini); 36 | } 37 | 38 | return maxP; 39 | } 40 | }; -------------------------------------------------------------------------------- /Easy/Best_Time_to_Buy_and_Sell_Stock.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | int arr[] = {7,1,5,3,6,4}; 7 | 8 | int maxPro = maxProfit(arr); 9 | System.out.println("Max profit is: " + maxPro); 10 | 11 | } 12 | static int maxProfit(int[] arr) { 13 | int maxPro = 0; 14 | int minPrice = Integer.MAX_VALUE; 15 | for (int i = 0; i < arr.length; i++) { 16 | minPrice = Math.min(minPrice, arr[i]); 17 | maxPro = Math.max(maxPro, arr[i] - minPrice); 18 | } 19 | return maxPro; 20 | } 21 | } -------------------------------------------------------------------------------- /Easy/BinarySearch.java: -------------------------------------------------------------------------------- 1 | // Java implementation of recursive Binary Search 2 | class BinarySearch { 3 | // Returns index of x if it is present in arr[l.. 4 | // r], else return -1 5 | int binarySearch(int arr[], int l, int r, int x) 6 | { 7 | if (r >= l) { 8 | int mid = l + (r - l) / 2; 9 | 10 | // If the element is present at the 11 | // middle itself 12 | if (arr[mid] == x) 13 | return mid; 14 | 15 | // If element is smaller than mid, then 16 | // it can only be present in left subarray 17 | if (arr[mid] > x) 18 | return binarySearch(arr, l, mid - 1, x); 19 | 20 | // Else the element can only be present 21 | // in right subarray 22 | return binarySearch(arr, mid + 1, r, x); 23 | } 24 | 25 | // We reach here when element is not present 26 | // in array 27 | return -1; 28 | } 29 | 30 | // Driver method to test above 31 | public static void main(String args[]) 32 | { 33 | BinarySearch ob = new BinarySearch(); 34 | int arr[] = { 2, 3, 4, 10, 40 }; 35 | int n = arr.length; 36 | int x = 10; 37 | int result = ob.binarySearch(arr, 0, n - 1, x); 38 | if (result == -1) 39 | System.out.println("Element not present"); 40 | else 41 | System.out.println("Element found at index " + result); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Easy/BubbleSort: -------------------------------------------------------------------------------- 1 | // C program for implementation of Bubble sort 2 | #include 3 | 4 | void swap(int *xp, int *yp) 5 | { 6 | int temp = *xp; 7 | *xp = *yp; 8 | *yp = temp; 9 | } 10 | 11 | // A function to implement bubble sort 12 | void bubbleSort(int arr[], int n) 13 | { 14 | int i, j; 15 | for (i = 0; i < n-1; i++) 16 | 17 | // Last i elements are already in place 18 | for (j = 0; j < n-i-1; j++) 19 | if (arr[j] > arr[j+1]) 20 | swap(&arr[j], &arr[j+1]); 21 | } 22 | 23 | /* Function to print an array */ 24 | void printArray(int arr[], int size) 25 | { 26 | int i; 27 | for (i=0; i < size; i++) 28 | printf("%d ", arr[i]); 29 | printf("\n"); 30 | } 31 | 32 | // Driver program to test above functions 33 | int main() 34 | { 35 | int arr[] = {64, 34, 25, 12, 22, 11, 90}; 36 | int n = sizeof(arr)/sizeof(arr[0]); 37 | bubbleSort(arr, n); 38 | printf("Sorted array: \n"); 39 | printArray(arr, n); 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /Easy/Build-Array-From-Permutation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector buildArray(vector& nums) { 4 | unordered_map m; 5 | for(int i=0; i ans; 10 | for(int i=0; i= 0){ 12 | if(grid[s][e] < 0){ 13 | count += grid.length - s; 14 | e--; 15 | } else{ 16 | s++; 17 | } 18 | } 19 | return count; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Easy/Create Maximum sum subarray of size k.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int maxsumsubarr(int arr[],int n,int k){ 4 | int i=0,j=0,sum=0,maxi=0; 5 | while(j0) 37 | { 38 | Scanner meet = new Scanner(System.in); 39 | 40 | System.out.print("Enter Bowler Player Type (Fast / Spin / Medium) : "); 41 | role = meet.next(); 42 | } 43 | 44 | } 45 | } 46 | 47 | class batsman extends CricketPlayer 48 | { 49 | void getCar() 50 | { 51 | Scanner meet = new Scanner(System.in); 52 | 53 | System.out.print("Enter Player Carrer Total Match : "); 54 | total = meet.nextInt(); 55 | 56 | } 57 | 58 | void print1() 59 | { 60 | System.out.println("Player Type : " + type); 61 | System.out.println("Carrer Total Match : " + total); 62 | } 63 | 64 | } 65 | 66 | class Bowler extends CricketPlayer 67 | { 68 | 69 | void print() 70 | { 71 | System.out.println("Player Name : " + name); 72 | System.out.println("Player Age : " + age); 73 | 74 | if(c == 1) 75 | 76 | -------------------------------------------------------------------------------- /Easy/IsSubSequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isSubsequence(string s, string t) { 4 | //we have to find whether string s can be made from string t 5 | // in which we don't have to change the relative positions of the characters 6 | // we can delete characters one or more characters. 7 | 8 | //case 1 : delete all the characters 9 | if(s.size() == 0) return true; 10 | 11 | //case 2: Two pointer approach to look all the characters present in the string s 12 | int s_point = 0; 13 | int t_point = 0; 14 | 15 | while(t_point < t.size()) { 16 | if(t[t_point] == s[s_point]) { 17 | s_point++; 18 | 19 | if(s_point == s.size()) return true; 20 | } 21 | 22 | t_point++; 23 | } 24 | 25 | return false; 26 | 27 | } 28 | }; -------------------------------------------------------------------------------- /Easy/Largest Perimeter Triangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int largestPerimeter(vector& nums) { 4 | int end=nums.size()-1; 5 | sort(nums.begin(),nums.end()); 6 | while(1 nums[end - 2] && nums[end] + nums[end - 2] > nums[end - 1] && nums[end - 1] + nums[end - 2] > nums[end]){ 8 | return nums[end] + nums[end - 1] + nums[end - 2]; 9 | } 10 | end--; 11 | } 12 | return 0; 13 | 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Easy/Length_of_last_word.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLastWord(string s) { 4 | int t=s.length(); 5 | int c=0; 6 | for(int i=t-1;i>=0;i--) 7 | { 8 | if(s[i]==' '&&c!=0) 9 | return c; 10 | else if((c==0)&&(s[i]==' ')) 11 | continue; 12 | else 13 | c++; 14 | } 15 | return c; 16 | } 17 | }; -------------------------------------------------------------------------------- /Easy/LinkedList_Cycle.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def hasCycle(self, head: Optional[ListNode]) -> bool: 9 | slow, fast = head, head 10 | 11 | while fast and fast.next: 12 | slow = slow.next 13 | fast = fast.next.next 14 | if slow == fast: 15 | return true 16 | 17 | return False -------------------------------------------------------------------------------- /Easy/Long_sharing_chef.cpp: -------------------------------------------------------------------------------- 1 | // Code By Romijul Laskar 2 | #include 3 | using namespace std; 4 | #define fast ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0) 5 | #define fn < n; k < n ? i += 1 : i -= 1) 8 | #define ll long long 9 | #define deb(x) cout << #x << "=" << x << endl 10 | #define debg(x) cout << x << endl 11 | #define deb2(x, y) cout << #x << "=" << x << "," << #y << "=" << y << endl 12 | #define pb push_back 13 | #define mp make_pair 14 | #define tr(it, a) for(auto it = a.begin(); it != a.end(); it++) 15 | #define F first 16 | #define S second 17 | #define PI 3.1415926535897932384626 18 | typedef pair pii; 19 | typedef pair pl; 20 | typedef vector vi; 21 | typedef vector vl; 22 | #define a *max_element(v.begin(),v.end()) 23 | #define b *min_element(v.begin(),v.end()) 24 | #define fe(i) for(i=0; i!='\n'; i++) 25 | 26 | 27 | void solve() 28 | { 29 | string str; 30 | cin>>str; 31 | int GG=0; 32 | int RR=0; 33 | for (int i = 0; i < str.size(); i++) 34 | { 35 | if(str[i]==str[i+1]) 36 | { 37 | if(str[i]=='R'){RR++;} 38 | else{GG++;} 39 | } 40 | } 41 | if(str[str.size()-1]==str[0]){ 42 | if(str[0]=='R'){RR++;} 43 | else{GG++;} 44 | } 45 | if((RR==GG)&&RR<=1&&GG<=1){cout<<"yes" fn} 46 | else{cout<<"no" fn} 47 | return; 48 | } 49 | int main() 50 | { 51 | fast; 52 | srand(chrono::high_resolution_clock::now().time_since_epoch().count()); 53 | 54 | int t; 55 | cin >> t; 56 | while (t--) 57 | { 58 | solve(); 59 | } 60 | return 0; 61 | } 62 | -------------------------------------------------------------------------------- /Easy/LongestPrefix.java: -------------------------------------------------------------------------------- 1 | package LeetCode; 2 | 3 | import java.util.*; 4 | import java.lang.*; 5 | import java.io.*; 6 | 7 | class Main { 8 | public String longestCommonPrefix(String[] S) { 9 | if (S.length == 0) return ""; 10 | String prefix = S[0]; 11 | for (int i = 1; i < S.length; i++) 12 | while (S[i].indexOf(prefix) != 0) { 13 | prefix = prefix.substring(0, prefix.length() - 1); 14 | if (prefix.isEmpty()) return ""; 15 | } 16 | return prefix; 17 | } 18 | public static void main(String args[]) { 19 | // Your code goes here 20 | Main ob = new Main(); 21 | String s[] = {"flower", "flow", "flight"}; 22 | System.out.println(ob.longestCommonPrefix(s)); 23 | } 24 | } -------------------------------------------------------------------------------- /Easy/MajorityElement.java: -------------------------------------------------------------------------------- 1 | int elem = 0, cnt = 0; 2 | 3 | for (int i=0;i& nums) { 29 | 30 | sort(nums.begin(),nums.end()); 31 | int i=0; int j=nums.size()-1; int ans=1; 32 | ans=nums[j]; j--; 33 | int a= (ans*nums[j]*nums[j-1]); 34 | int b= (ans*nums[i]*nums[i+1]); 35 | return max(a,b); 36 | } 37 | }; -------------------------------------------------------------------------------- /Easy/MaximumDepthOfBinaryTree.java: -------------------------------------------------------------------------------- 1 | package net.kenyang.algorithm; 2 | 3 | /** 4 | * Given a binary tree, find its maximum depth.
5 | * The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 6 | * @author Ken Yang 7 | * 8 | */ 9 | public class MaximumDepthOfBinaryTree { 10 | public class TreeNode { 11 | int val; 12 | TreeNode left; 13 | TreeNode right; 14 | TreeNode(int x) { 15 | val = x; 16 | } 17 | } 18 | 19 | public int maxDepth(TreeNode root) { 20 | 21 | if (root == null) { 22 | return 0; 23 | } 24 | 25 | int iRightDepth = maxDepth(root.right); 26 | int iLefttDepth = maxDepth(root.left); 27 | return (iRightDepth > iLefttDepth) ? iRightDepth + 1 : iLefttDepth + 1; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Easy/MergeArray.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class MergeArray 3 | { 4 | public static void main(String args[]) 5 | { 6 | Scanner sc = new Scanner(System.in); 7 | 8 | // Input size of array 1 9 | System.out.println("Enter the number of elements in array 1 : "); 10 | int len1=sc.nextInt(); 11 | 12 | // Input size of array 2 13 | System.out.println("Enter the number of elements in array 2 : "); 14 | int len2=sc.nextInt(); 15 | 16 | //Declaring arrays 17 | int arr1[]=new int[len1+len2]; 18 | int arr2[]=new int[len2]; 19 | 20 | //Input elements of array 1 21 | System.out.println("Enter array 1 values using spaces : "); 22 | for(int i =0;iw2.length()){ 21 | str=w1; 22 | } 23 | else{ 24 | str=w2; 25 | } 26 | for (int i = l; i Optional[ListNode]: 8 | slow = head 9 | fast = head 10 | while fast and fast.next: 11 | slow = slow.next 12 | fast = fast.next.next 13 | return slow 14 | -------------------------------------------------------------------------------- /Easy/MiddleNodeLinkedList.java: -------------------------------------------------------------------------------- 1 | public class MiddleNodeLinkedList { 2 | 3 | public static class ListNode { 4 | int val; 5 | ListNode next; 6 | ListNode() {} 7 | ListNode(int val) { 8 | this.val = val; 9 | } 10 | ListNode(int val, ListNode next) { 11 | this.val = val; this.next = next; 12 | } 13 | } 14 | 15 | public static ListNode middleNode(ListNode head) { 16 | 17 | if(head == null) 18 | return null; 19 | 20 | ListNode fast = head, slow = head; 21 | 22 | while(fast != null && fast.next != null){ 23 | fast = fast.next.next; 24 | slow = slow.next; 25 | } 26 | 27 | return slow; 28 | } 29 | 30 | private static void printList(ListNode head){ 31 | while(head != null){ 32 | System.out.print(head.val + " "); 33 | head = head.next; 34 | } 35 | System.out.println(""); 36 | } 37 | 38 | public static void main(String[] args) { 39 | 40 | ListNode head = new ListNode(1, null); 41 | head.next = new ListNode(2); 42 | head.next.next = new ListNode(3); 43 | head.next.next.next = new ListNode(4); 44 | head.next.next.next.next = new ListNode(5); 45 | 46 | System.out.print("Given Linked List: "); 47 | printList(head); 48 | 49 | ListNode mid = middleNode(head); 50 | 51 | System.out.print("Middle elements: "); 52 | printList(mid); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Easy/Move Zeroes.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def moveZeroes(self, nums: List[int]) -> None: 3 | right=left=len(nums) 4 | for i in range(len(nums)): 5 | if nums[i]==0: 6 | right=left=i 7 | break 8 | while right 2 | using namespace std; 3 | 4 | class Solution 5 | { 6 | public: 7 | int arithmeticTriplets(vector &nums, int diff) 8 | { 9 | int res = 0; 10 | unordered_map m; 11 | for (auto &i : nums) 12 | { 13 | m[i] = true; 14 | } 15 | for (int i = 0; i < nums.size() - 2; i++) 16 | { 17 | if (m[nums[i] + diff] and m[nums[i] + (2 * diff)]) // find element present in hash map 18 | res++; 19 | } 20 | return res; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Easy/NumsNotInArrayLeetcode448.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class NumsNotInArrayLeetcode448 { 5 | public static void main(String[] args) { 6 | int[] arr = {4,3,2,7,8,2,3,1}; 7 | System.out.println(findDisappearedNumbers(arr)); 8 | } 9 | static List findDisappearedNumbers(int[] arr) { 10 | List ans = new ArrayList(); 11 | int i = 0; 12 | while(i < arr.length) 13 | { 14 | int actual = arr[i]-1; 15 | if(arr[i] != arr[actual]) 16 | swap(arr, i, actual); 17 | else 18 | i++; 19 | } 20 | for(int j = 0; j < arr.length; j++) 21 | { 22 | if(arr[j] != j+1) 23 | ans.add(j+1); 24 | 25 | } 26 | return ans; 27 | } 28 | 29 | static void swap(int[] arr, int first, int second) 30 | { 31 | int temp = arr[first]; 32 | arr[first] = arr[second]; 33 | arr[second] = temp; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Easy/Palindrome Number(LC).cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPalindrome(int x) { 4 | if(x<0) 5 | return false; 6 | 7 | long reverse = 0; 8 | long temp = x; 9 | while (temp != 0) { 10 | reverse = (reverse * 10) + (temp % 10); 11 | temp = temp / 10; 12 | } 13 | return (reverse 14 | == x); 15 | } 16 | }; -------------------------------------------------------------------------------- /Easy/PalindromeNumber.ts: -------------------------------------------------------------------------------- 1 | /* 2 | Given an integer x, return true if x is palindrome integer. 3 | 4 | An integer is a palindrome when it reads the same backward as forward. 5 | */ 6 | 7 | 8 | function isPalindrome(x: number): boolean { 9 | if (x < 0)return false; 10 | return x.toString() == x.toString().split("").reverse().join("") 11 | }; -------------------------------------------------------------------------------- /Easy/Problem_69.Sqrt(x).cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int mySqrt(int x) { 4 | long int i; 5 | if(x<=4) 6 | { 7 | if(x==4) 8 | return 2; 9 | else if(x>=1) 10 | return 1; 11 | else 12 | return 0; 13 | } 14 | else if(x>4) 15 | { 16 | for(i=2;ix)) 19 | { 20 | int j=i; 21 | return j; 22 | } 23 | 24 | } 25 | } 26 | return i; 27 | 28 | } 29 | }; -------------------------------------------------------------------------------- /Easy/Ransom Note.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Solution { 4 | public: 5 | bool canConstruct(string ransomNote, string magazine) { 6 | unordered_mapm1; 7 | unordered_mapm2; 8 | 9 | for(int i=0;im2[it.first]) 18 | return false; 19 | 20 | } 21 | 22 | return true ; 23 | 24 | } 25 | }; 26 | int main() 27 | { 28 | string ransomNote,magazine; 29 | cin>>ransomNote>>magazine; 30 | Solution result; 31 | if(result.canConstruct(ransomNote,magazine)) 32 | cout<<"True"<max){ 17 | max = sum; 18 | } 19 | } 20 | return max; 21 | } 22 | } -------------------------------------------------------------------------------- /Easy/Roman_to_Integer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int romanToInt(string S) { 9 | int ans = 0, num = 0; 10 | for (int i = S.size()-1; ~i; i--) { 11 | switch(S[i]) { 12 | case 'I': num = 1; break; 13 | case 'V': num = 5; break; 14 | case 'X': num = 10; break; 15 | case 'L': num = 50; break; 16 | case 'C': num = 100; break; 17 | case 'D': num = 500; break; 18 | case 'M': num = 1000; break; 19 | } 20 | if (4 * num < ans) ans -= num; 21 | else ans += num; 22 | } 23 | return ans; 24 | } 25 | }; 26 | 27 | 28 | 29 | int main() 30 | { string s("III"); 31 | Solution PUSS; 32 | cout< letters[letters.length-1] then return 0 and here just return s 22 | } 23 | 24 | static char nextGreatestLetter2(char[] letters, char target){ 25 | if(target >= letters[letters.length-1]){ 26 | return letters[0]; 27 | } 28 | 29 | int s = 0; 30 | int e = letters.length-1; 31 | 32 | while(s < e){ 33 | int m = s + (e-s)/2; 34 | 35 | if(target < letters[m]){ 36 | e = m-1; 37 | } else{ 38 | s = m+1; 39 | } 40 | } 41 | return letters[s] > target ? letters[s] : letters[s+1]; 42 | } 43 | 44 | 45 | 46 | } 47 | -------------------------------------------------------------------------------- /Easy/Sqrt.java: -------------------------------------------------------------------------------- 1 | public class Sqrt { 2 | public static void main(String[] args) { 3 | int n = 8; 4 | System.out.println(sqrt2(n)); 5 | } 6 | 7 | static int sqrt(int n){ 8 | long s = 1; 9 | long e = n; 10 | 11 | while(s <= e){ 12 | long m = s + (e-s)/2; 13 | 14 | if(m * m <= n){ 15 | s = m +1; 16 | } else{ 17 | e = m -1; 18 | } 19 | } 20 | return (int)e; //e will always point to the greatest value satisfying the condition in this s <= e wala case doosre tarike se abhi dekhte h 21 | } 22 | 23 | static int sqrt2(int n){ 24 | long s = 1; 25 | long e = n; 26 | 27 | while(s < e){ 28 | long m = s + (e-s)/2; 29 | 30 | if(m * m <= n){ 31 | s = m+1; 32 | } else{ 33 | e = m; 34 | } 35 | } 36 | return s*s <= n ? (int)s: (int)s-1; 37 | //idhr s-1 hoti h vo max value jo staisfy kregi condition ko lekin maano 1 ka sqrt to s or e dono hi 1 ko point krenge to is case mai loop run hi nhi hoga to kya krna h ki s-1 se pehle s ko dekhna h or agr ye satisfy krta h to yu hi bta s bda ya s-1 ? s hi na to bss use ho return nhi to simple s-1. 38 | } 39 | 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Easy/Symmetric Tree.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 | bool isSymmetric(TreeNode* root) { 15 | return (root==NULL)||(syshelp(root->left,root->right)); 16 | 17 | } 18 | bool syshelp(TreeNode* lef,TreeNode* rig) 19 | { 20 | if(lef==NULL || rig==NULL) 21 | return lef==rig; 22 | if(lef->val!=rig->val) return false; 23 | 24 | return ((syshelp(lef->left,rig->right))&&(syshelp(lef->right,rig->left))); 25 |       26 |  } 27 |    28 | }; 29 | -------------------------------------------------------------------------------- /Easy/Two_Sum.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Coded by TSG 3 | ''' 4 | 5 | class Solution(object): 6 | def twoSum(self, nums, target): 7 | for idx , num in enumerate(nums): 8 | if (target - num) in nums: 9 | if nums.index(target - num) != idx: 10 | return [idx , nums.index(target - num)] 11 | -------------------------------------------------------------------------------- /Easy/Two_sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | vector twoSum(vector& nums, int target) { 7 | unordered_map numToIndex; 8 | 9 | for (int i = 0; i < nums.size(); ++i) { 10 | if (numToIndex.count(target - nums[i])) 11 | return {numToIndex[target - nums[i]], i}; 12 | numToIndex[nums[i]] = i; 13 | } 14 | 15 | throw; 16 | }; 17 | }; -------------------------------------------------------------------------------- /Easy/Valid_ParenthesesLC.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std ; 5 | 6 | 7 | class Solution { 8 | public: 9 | bool isValid(string s) { 10 | 11 | stack bass; 12 | int i=0; 13 | if(s.size()%2!=0) 14 | return false; 15 | while(i map = new HashMap<>(); 4 | for (int i = 0; i < s.length(); i++) { 5 | char c = s.charAt(i); 6 | if (map.containsKey(c)) { 7 | if (i - map.get(c) - 1 != distance[c - 'a']) 8 | return false; 9 | } else { 10 | map.put(c, i); 11 | } 12 | } 13 | return true; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Easy/count-no-of-pairs.cpp: -------------------------------------------------------------------------------- 1 | /* LEETCODE PROBLEM: 2006 2 | Count Number of Pairs With Absolute Difference K 3 | 4 | https://leetcode.com/problems/count-number-of-pairs-with-absolute-difference-k/ 5 | 6 | Given an integer array nums and an integer k, return the number of pairs (i, j) where i < j such that |nums[i] - nums[j]| == k. 7 | The value of |x| is defined as: 8 | x if x >= 0. 9 | -x if x < 0. 10 | 11 | Example 1: 12 | Input: nums = [1,2,2,1], k = 1 13 | Output: 4 14 | Explanation: The pairs with an absolute difference of 1 are: 15 | - [1,2,2,1] 16 | - [1,2,2,1] 17 | - [1,2,2,1] 18 | - [1,2,2,1] 19 | */ 20 | class Solution { 21 | public: 22 | int countKDifference(vector& nums, int k) { 23 | int count=0; 24 | 25 | for(int i=0;i>& items, string ruleKey, string ruleValue) { 18 | int type=0, ctr=0; 19 | if(ruleKey == "type") 20 | type=0; 21 | else if(ruleKey == "color") 22 | type=1; 23 | else 24 | type=2; 25 | 26 | for(int i=0; i < items.size(); i++) { 27 | if(items[i][type] == ruleValue) 28 | ctr++; 29 | } 30 | return ctr; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Easy/kthSmallestInMatrix.java: -------------------------------------------------------------------------------- 1 | public class kthSmallestInMatrix { 2 | public static void main(String[] args) { 3 | int[][] matrix = { 4 | {1,5,9}, 5 | {10,11,13}, 6 | {12,13,15}, 7 | }; 8 | int k = 8; 9 | System.out.println(kthSmallest(matrix, k)); 10 | } 11 | 12 | static int kthSmallest(int[][] matrix, int k) { 13 | int s = matrix[0][0]; 14 | int e = matrix[ matrix.length-1 ][ matrix[0].length-1 ]; //wow 15 | 16 | while(s < e){ 17 | int m = s + (e-s)/2; 18 | 19 | if( isPotentialK(matrix, m, k) ){ 20 | e = m; 21 | } else { 22 | s = m+1; 23 | } 24 | } 25 | return s; //or e as they are pointing to the same elm 26 | } 27 | 28 | static boolean isPotentialK(int[][] matrix, int m, int k) { 29 | int count = 0; 30 | 31 | int r = 0; 32 | int c = matrix[0].length-1; 33 | 34 | while(r < matrix.length && c >= 0){ 35 | if(matrix[r][c] <= m){ 36 | count += c+1; 37 | r++; 38 | } else{ 39 | c--; 40 | } 41 | } 42 | return count >= k; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Easy/longestCommanPrefix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string longestCommonPrefix(vector& strs) { 4 | int n=strs.size(); 5 | if(n==0) return ""; 6 | if(n==1) return strs[0]; 7 | sort(strs.begin(),strs.end()); 8 | 9 | string s=strs[0]; 10 | string t=strs[n-1]; 11 | int k= s.size(); 12 | int l= t.size(); 13 | int count =l; 14 | 15 | if(k>l) count=k; 16 | string ans=""; 17 | for(int i=0;i& nums) { 4 | sort(nums.begin(),nums.end()); 5 | int n = nums.size(); 6 | return max(nums[n-1]*nums[n-2]*nums[n-3],nums[0]*nums[1]*nums[n-1]); 7 | } 8 | }; 9 | -------------------------------------------------------------------------------- /Easy/plus one.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def plusOne(self, l: List[int]) -> List[int]: 3 | if l[-1]==9: 4 | s=''.join(map(str,l)) 5 | a=str(int(s)+1) 6 | return list(map(int,a)) 7 | else: 8 | l[-1]+=1 9 | return l 10 | -------------------------------------------------------------------------------- /Easy/plusOne.js: -------------------------------------------------------------------------------- 1 | /* You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's. 2 | 3 | Increment the large integer by one and return the resulting array of digits. */ 4 | 5 | /** 6 | * @param {number[]} digits 7 | * @return {number[]} 8 | */ 9 | 10 | var plusOne = (digits) => { 11 | for (let digit = digits.length - 1; 0 <= digit; digit--) { 12 | /* Time O(N) */ 13 | const canCarry = digits[digit] === 9; 14 | if (canCarry) { 15 | digits[digit] = 0; 16 | continue; 17 | } 18 | 19 | digits[digit]++; 20 | 21 | return digits; 22 | } 23 | 24 | digits.unshift(1); /* Time O(N) | Space O(N) */ 25 | 26 | return digits; 27 | }; 28 | console.log(plusOne([1, 2, 3])); //returns [1,2,4] 29 | /*Explanation: The array represents the integer 123. 30 | Incrementing by one gives 123 + 1 = 124. 31 | Thus, the result should be [1,2,4]. */ 32 | 33 | console.log(plusOne([9])); //returns [1,0] 34 | -------------------------------------------------------------------------------- /Easy/primeNumber.java: -------------------------------------------------------------------------------- 1 | public class primeNumber { 2 | public static void main(String args[]) { 3 | int i, m = 0, flag = 0; 4 | int n = 3;// it is the number to be checked 5 | m = n / 2; 6 | if (n == 0 || n == 1) { 7 | System.out.println(n + " is not prime number"); 8 | } else { 9 | for (i = 2; i <= m; i++) { 10 | if (n % i == 0) { 11 | System.out.println(n + " is not prime number"); 12 | flag = 1; 13 | break; 14 | } 15 | } 16 | if (flag == 0) { 17 | System.out.println(n + " is prime number"); 18 | } 19 | } // end of else 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Easy/quick_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int partition(int arr[], int s, int e) 5 | { 6 | int pivot = arr[s]; 7 | int cnt = 0; 8 | for(int i=s+1;i<=e;i++) 9 | { 10 | if(arr[i] <= pivot) { 11 | cnt++; 12 | } 13 | } 14 | //place pivot at right position 15 | int pivotIndex = s+cnt; 16 | swap(arr[pivotIndex],arr[s]); 17 | //left and right wala part 18 | int i=s,j=e; 19 | while(ipivotIndex) 20 | { 21 | while(arr[i]<= pivot) { 22 | i++; 23 | } 24 | while(arr[j]>pivot){ 25 | j--; 26 | } 27 | if(ipivotIndex){ 28 | swap(arr[i++], arr[j--]); 29 | } 30 | } 31 | return pivotIndex; 32 | } 33 | 34 | void quickSort(int arr[], int s, int e) 35 | { //base case 36 | if(s>=e) 37 | return ; 38 | 39 | //partition karenge 40 | int p = partition(arr,s,e); 41 | 42 | //left part sort karo 43 | quickSort(arr,s,p-1); 44 | 45 | //right wala part sort karo 46 | quickSort(arr,p+1,e); 47 | } 48 | 49 | int main() 50 | { 51 | int arr[5] = {2,4,1,6,9}; 52 | int n = 5; 53 | 54 | quickSort(arr,0,n-1); 55 | 56 | for(int i=0; i>& accounts) { 27 | 28 | int maxwlth=0; 29 | int sum=0; 30 | int n=accounts.size(); 31 | for(int i=0;i numMap = new HashMap<>(); 12 | for (int i = 0; i < arr.length; i++) { 13 | int complement = target - arr[i]; 14 | if (numMap.containsKey(complement)) { 15 | return new int[] { numMap.get(complement), i }; 16 | } else { 17 | numMap.put(arr[i], i); 18 | } 19 | } 20 | return new int[] {}; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Easy/validParentheses.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | public class validParentheses { 4 | public static void main(String[] args) { 5 | String s= "()"; 6 | // {}, [] 7 | System.out.println(isValid(s)); 8 | } 9 | static boolean isValid(String s) { 10 | if (s.length() % 2 == 1) { 11 | return false; 12 | } 13 | 14 | Stack stack = new Stack(); 15 | 16 | for (int i = 0; i < s.length(); i++) { 17 | if (s.charAt(i) == '(') { 18 | stack.push(')'); 19 | } else if (s.charAt(i) == '{') { 20 | stack.push('}'); 21 | } else if (s.charAt(i) == '[') { 22 | stack.push(']'); 23 | } else if (stack.isEmpty() || stack.pop() != s.charAt(i)) 24 | return false; 25 | } 26 | return stack.isEmpty(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Hacktoberfest2022.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vanshika2063/Leetcode-Questions/6ac1ef53044340cec9592fb4eab47d80f5440f31/Hacktoberfest2022.png -------------------------------------------------------------------------------- /Hard/140. Word Break II.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def wordBreak(self, s, wordDict): 3 | """ 4 | :type s: str 5 | :type wordDict: List[str] 6 | :rtype: List[str] 7 | """ 8 | out = [] 9 | 10 | def check(wrd,s): 11 | n = len(s) 12 | for i in range(n+1): 13 | if s[:i] == wrd: 14 | return [True,s[i:]] 15 | return [False,s] 16 | 17 | 18 | 19 | def recur(st,words): 20 | if st == "": 21 | out.append(words[1:]) 22 | return 23 | for wrd in wordDict: 24 | cond,val = check(wrd,st) 25 | if cond: 26 | news = val 27 | recur(news,words +" " + wrd) 28 | 29 | recur(s,"") 30 | 31 | return out 32 | -------------------------------------------------------------------------------- /Hard/25.Reverse_Nodes_in_K_Groups.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Intuition: Better be understood with an exmaple 3 | 4 | 1->2->3->4->5->6->7->8, and k = 3 5 | 6 | 1) First we will traverse the list till k nodes and reverse the first k nodes.Meanwhile we will also 7 | store the k+1 node in a variable tempNext. 8 | 9 | Let's take temp node as a dummy node and store the head node in it. 10 | after forloop temp->next will point to 4 and temp will point to 3. 11 | 12 | 2) Now we will break the link between the kth node and the k+1th node and make the kth node point to NULL. 13 | tempNext = temp->next; 14 | temp->next = NULL; 15 | 16 | 3) We will reverse the first k nodes and store the new head in a variable newHead and connect previous head to the tempNext node. 17 | newHead = reverseList(head); 18 | 19 | 3->2->1->4->5->6->7->8 20 | 4) Now we will call the recursion to make the remaining list. 21 | 3->2->1->6->5->4->7->8 22 | */ 23 | 24 | 25 | class Solution { 26 | // a function to reverse the node and return the head of the reversed list 27 | ListNode* rev(ListNode* root) 28 | { 29 | ListNode* curr = root, *prev = NULL, *currNext = NULL; 30 | 31 | while(curr) 32 | { 33 | currNext = curr->next; 34 | curr->next = prev; 35 | prev = curr; 36 | curr = currNext; 37 | } 38 | 39 | return prev; 40 | } 41 | 42 | public: 43 | ListNode* reverseKGroup(ListNode* head, int k) { 44 | if(!head) 45 | return head; 46 | 47 | ListNode* temp = head; 48 | 49 | // Note: (inext; 52 | 53 | if(!temp) 54 | return head; 55 | 56 | ListNode* tempNext = temp->next; 57 | temp->next = NULL; 58 | 59 | ListNode* h = rev(head); 60 | head->next = reverseKGroup(tempNext, k); 61 | 62 | return h; 63 | } 64 | }; 65 | -------------------------------------------------------------------------------- /Hard/336. Palindrome Pairs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution 5 | { 6 | public: 7 | vector> palindromePairs(vector &words) 8 | { 9 | unordered_map wmap; 10 | vector> ans; 11 | for (int i = 0; i < words.size(); i++) 12 | wmap[words[i]] = i; 13 | for (int i = 0; i < words.size(); i++) 14 | { 15 | if (words[i] == "") 16 | { 17 | for (int j = 0; j < words.size(); j++) 18 | { 19 | string &w = words[j]; 20 | if (isPal(w, 0, w.size() - 1) && j != i) 21 | { 22 | ans.push_back(vector{i,j}); 23 | ans.push_back(vector{j,i}); 24 | } 25 | } 26 | continue; 27 | } 28 | string bw = words[i]; 29 | reverse(bw.begin(), bw.end()); 30 | if (wmap.find(bw) != wmap.end()) 31 | { 32 | int res = wmap[bw]; 33 | if (res != i) 34 | ans.push_back(vector{i,res}); 35 | } 36 | for (int j = 1; j < bw.size(); j++) 37 | { 38 | if (isPal(bw, 0, j - 1)) 39 | { 40 | string s = bw.substr(j, bw.size() - j); 41 | if (wmap.find(s) != wmap.end()) 42 | ans.push_back(vector{i,wmap[s]}); 43 | } 44 | if (isPal(bw, j, bw.size() - 1)) 45 | { 46 | string s = bw.substr(0, j); 47 | if (wmap.find(s) != wmap.end()) 48 | ans.push_back(vector{wmap[s], i}); 49 | } 50 | } 51 | } 52 | return ans; 53 | } 54 | 55 | private: 56 | bool isPal(string &word, int i, int j) 57 | { 58 | while (i < j) 59 | if (word[i++] != word[j--]) 60 | return false; 61 | return true; 62 | } 63 | }; -------------------------------------------------------------------------------- /Hard/4. Median of Two Sorted Arrays.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findMedianSortedArrays(self, nums1, nums2): 3 | """ 4 | :type nums1: List[int] 5 | :type nums2: List[int] 6 | :rtype: float 7 | """ 8 | 9 | # median is an element which is half way btw the full array 10 | # if there are even numbe of elements , median will be half of the values 11 | 12 | # for a given list only one median exists 13 | 14 | 15 | # we will find median by binary search over the sorted arrays.... 16 | # anyone of them, 17 | # actually the smmaller one !! 18 | 19 | if len(nums1) > len(nums2): 20 | return self.findMedianSortedArrays(nums2,nums1) 21 | 22 | # smaller one 23 | n = len(nums1) 24 | # larger one 25 | m = len(nums2) 26 | 27 | l = 0 28 | h = n 29 | fullLen = n + m + 1 30 | halfCount = fullLen / 2 31 | while l <= h: 32 | cut1 = (l+h) //2 33 | cut2 = halfCount - cut1 34 | 35 | l1,r1 = -1e9,1e9 36 | l2,r2 = -1e9,1e9 37 | 38 | if cut1 > 0: 39 | l1 = nums1[cut1-1] 40 | if cut1 <= n-1 : 41 | r1 = nums1[cut1] 42 | if cut2 > 0: 43 | l2 = nums2[cut2-1] 44 | if cut2 <= m-1 : 45 | r2 = nums2[cut2] 46 | 47 | # median found 48 | if l1 <= r2 and l2 <= r1: 49 | if (fullLen-1) & 1: 50 | return max(l1,l2) 51 | else: 52 | return (max(l1,l2) + min(r1,r2)) / 2.0 53 | elif l1 > r2: 54 | h = cut1 - 1 55 | else: 56 | l = cut1 + 1 57 | return 0 58 | -------------------------------------------------------------------------------- /Hard/44. Wildcard Matching.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isMatch(self, s: str, p: str) -> bool: 3 | n = len(s) 4 | m = len(p) 5 | memo = [[-1 for i in range(m+1)] for j in range(n+1)] 6 | def solve(i,j): 7 | # base condition 8 | if i == 0: 9 | if j == 0 : return True 10 | else: 11 | for temp in range(j): 12 | if p[temp] != "*": 13 | return False 14 | return True 15 | elif j == 0: 16 | return False 17 | 18 | 19 | if memo[i][j] != -1: 20 | return memo[i][j] 21 | 22 | 23 | ans = False 24 | if s[i-1] == p[j-1] or p[j-1] == "?": 25 | ans = solve(i-1,j-1) 26 | 27 | elif p[j-1] == "*": 28 | ans = solve(i-1,j-1) or solve(i-1,j) or solve(i,j-1) 29 | else: 30 | return False 31 | memo[i][j] = ans 32 | return ans 33 | res = solve(n,m) 34 | # print(memo) 35 | return res 36 | 37 | -------------------------------------------------------------------------------- /Hard/AggressiveCows.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool isPossible(vector& stalls , int n , int k , int mid) 5 | { 6 | int cowsCount = 1; 7 | int cowsDistance = stalls[0]; 8 | for(int i= 0 ; i< n ;i++) 9 | { 10 | if(stalls[i] - cowsDistance >= mid) 11 | { 12 | cowsCount++; 13 | if(cowsCount == k) 14 | { 15 | return true; 16 | } 17 | cowsDistance = stalls[i]; 18 | } 19 | 20 | } 21 | return false; 22 | } 23 | 24 | int aggresiveCows(vector &stalls , int n , int k) 25 | { 26 | sort(stalls.begin() , stalls.end()); 27 | int start = 0; 28 | int maxi = -1; 29 | for(int i=0 ; i> n >> k; 53 | vector arr; 54 | for(int i=0 ;i> x; 57 | arr.push_back(x); 58 | } 59 | int ans = aggresiveCows(arr , n , k); 60 | cout << ans; 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /Hard/BubbleSort.java: -------------------------------------------------------------------------------- 1 | public class BubbleSort { 2 | static void bubbleSort(int[] arr) { 3 | int n = arr.length; 4 | int temp = 0; 5 | for(int i=0; i < n; i++){ 6 | for(int j=1; j < (n-i); j++){ 7 | if(arr[j-1] > arr[j]){ 8 | //swap elements 9 | temp = arr[j-1]; 10 | arr[j-1] = arr[j]; 11 | arr[j] = temp; 12 | } 13 | 14 | } 15 | } 16 | 17 | } 18 | public static void main(String[] args) { 19 | int arr[] ={3,60,35,2,45,320,5}; 20 | 21 | System.out.println("Array Before Bubble Sort"); 22 | for(int i=0; i < arr.length; i++){ 23 | System.out.print(arr[i] + " "); 24 | } 25 | System.out.println(); 26 | 27 | bubbleSort(arr);//sorting array elements using bubble sort 28 | 29 | System.out.println("Array After Bubble Sort"); 30 | for(int i=0; i < arr.length; i++){ 31 | System.out.print(arr[i] + " "); 32 | } 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Hard/Count Subarrays.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 2302. Count Subarrays With Score Less Than K 3 | 4 | The score of an array is defined as the product of its sum and its length. 5 | 6 | For example, the score of [1, 2, 3, 4, 5] is (1 + 2 + 3 + 4 + 5) * 5 = 75. 7 | 8 | Given a positive integer array nums and an integer k, return the number of non-empty subarrays of nums whose score is strictly less than k. 9 | 10 | A subarray is a contiguous sequence of elements within an array. 11 | 12 | Example 1: 13 | 14 | Input: nums = [2,1,4,3,5], k = 10 15 | Output: 6 16 | Explanation: 17 | The 6 subarrays having scores less than 10 are: 18 | - [2] with score 2 * 1 = 2. 19 | - [1] with score 1 * 1 = 1. 20 | - [4] with score 4 * 1 = 4. 21 | - [3] with score 3 * 1 = 3. 22 | - [5] with score 5 * 1 = 5. 23 | - [2,1] with score (2 + 1) * 2 = 6. 24 | Note that subarrays such as [1,4] and [4,3,5] are not considered because their scores are 10 and 36 respectively, while we need scores strictly less than 10. 25 | 26 | Example 2: 27 | 28 | Input: nums = [1,1,1], k = 5 29 | Output: 5 30 | Explanation: 31 | Every subarray except [1,1,1] has a score less than 5. 32 | [1,1,1] has a score (1 + 1 + 1) * 3 = 9, which is greater than 5. 33 | Thus, there are 5 subarrays having scores less than 5. 34 | 35 | 36 | 37 | Constraints: 38 | 39 | 1 <= nums.length <= 10^5 40 | 1 <= nums[i] <= 10^5 41 | 1 <= k <= 10^15 42 | 43 | */ 44 | 45 | class Solution { 46 | public: 47 | long long countSubarrays(vector& a, long long k) { 48 | long long n = a.size(); 49 | long long cnt = 0; 50 | long long sum = 0; 51 | for(int i = 0, j = 0;j < n;j++) 52 | { 53 | sum += a[j]; 54 | while(i < j and sum * (j - i + 1) >= k) 55 | { 56 | sum -= a[i++]; 57 | } 58 | if(sum * (j - i + 1) < k) 59 | { 60 | cnt += j - i + 1; 61 | } 62 | } 63 | return cnt; 64 | } 65 | }; -------------------------------------------------------------------------------- /Hard/MedianFinder.java: -------------------------------------------------------------------------------- 1 | class MedianFinder { 2 | 3 | PriorityQueue low = new PriorityQueue((a,b) -> (b-a)); 4 | PriorityQueue hi = new PriorityQueue(); 5 | /** initialize your data structure here. */ 6 | public MedianFinder() { 7 | 8 | } 9 | 10 | public void addNum(int num) { 11 | low.offer(num); 12 | 13 | hi.offer(low.poll()); 14 | 15 | if(low.size() < hi.size()) 16 | { 17 | low.offer(hi.poll()); 18 | } 19 | 20 | } 21 | 22 | public double findMedian() { 23 | 24 | return low.size() > hi.size() ? low.peek() : (low.peek() + hi.peek())/2.0; 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Hard/MedianOfTwoSortedArrays.java: -------------------------------------------------------------------------------- 1 | public class MedianOfTwoSortedArrays { 2 | public static void main(String[] args) { 3 | 4 | } 5 | 6 | static double findMedianSortedArrays(int[] nums1, int[] nums2) { 7 | if(nums2.length < nums1.length){ 8 | return findMedianSortedArrays(nums2, nums1); 9 | } 10 | 11 | int s = 0; 12 | int e = nums1.length; 13 | 14 | while(s <= e){ 15 | int cut1 = s + (e-s)/2; 16 | int cut2 = (nums1.length + nums2.length) /2 - cut1; 17 | 18 | int l1 = cut1 <= 0 ? Integer.MIN_VALUE : nums1[cut1 - 1]; 19 | int l2 = cut2 <= 0 ? Integer.MIN_VALUE : nums2[cut2 - 1]; 20 | 21 | int r1 = cut1 >= nums1.length ? Integer.MAX_VALUE : nums1[cut1]; 22 | int r2 = cut2 >= nums2.length ? Integer.MAX_VALUE : nums2[cut2]; 23 | 24 | if( l1 > r2 ){ 25 | e = cut1 - 1; 26 | } else if( l2 > r1 ){ 27 | s = cut1 + 1; 28 | } else{ 29 | return (nums1.length + nums2.length) % 2 == 0 ? 30 | (float) ( Math.max(l1, l2) + Math.min(r1, r2) ) / 2 : 31 | Math.min(r1, r2); 32 | } 33 | 34 | } 35 | return -1; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Hard/Median_of_ Two_Sorted_Arrays.cpp: -------------------------------------------------------------------------------- 1 | // Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. 2 | 3 | // The overall run time complexity should be O(log (m+n)). 4 | 5 | 6 | 7 | // Example 1: 8 | 9 | // Input: nums1 = [1,3], nums2 = [2] 10 | // Output: 2.00000 11 | // Explanation: merged array = [1,2,3] and median is 2. 12 | // Example 2: 13 | 14 | // Input: nums1 = [1,2], nums2 = [3,4] 15 | // Output: 2.50000 16 | // Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. 17 | 18 | 19 | // Constraints: 20 | 21 | // nums1.length == m 22 | // nums2.length == n 23 | // 0 <= m <= 1000 24 | // 0 <= n <= 1000 25 | // 1 <= m + n <= 2000 26 | // -106 <= nums1[i], nums2[i] <= 106 27 | 28 | 29 | 30 | //solution 31 | class Solution { 32 | public: 33 | double findMedianSortedArrays(vector& nums1, vector& nums2) { 34 | int n = nums1.size() + nums2.size(); 35 | vectorv(n); 36 | merge(nums1.begin(), nums1.end(), nums2.begin(), 37 | nums2.end(), v.begin()); 38 | int mid = 0; 39 | double median =0; 40 | cout< Optional[ListNode]: 3 | fi=[] 4 | for i in lists: 5 | t=i 6 | while t!=None: 7 | fi.append(t.val) 8 | t=t.next 9 | fi=sorted(fi) 10 | if len(fi)==0: 11 | return None 12 | p=ListNode(fi.pop(0)) 13 | t=p 14 | while len(fi)>0: 15 | p.next=ListNode(fi.pop(0)) 16 | p=p.next 17 | return t 18 | 19 | -------------------------------------------------------------------------------- /Hard/Merge_k_sorted_list.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* mergeKLists(vector& lists) { 14 | priority_queue,greater > pq; 15 | int k=lists.size(); 16 | ListNode *result=new ListNode(0); 17 | ListNode *ptr=result; 18 | if(!k) 19 | return NULL; 20 | for(int i=0;ival); 26 | head=head->next; 27 | } 28 | } 29 | while(!pq.empty()) 30 | { 31 | ListNode *temp=new ListNode(pq.top()); 32 | ptr->next=temp; 33 | ptr=temp; 34 | pq.pop(); 35 | } 36 | return result->next; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Hard/Minimum Weighted Subgraph With the Required Paths.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Topic: Graph (Dijkstra) 3 | Difficulty: H 4 | Time: O(n+elog(n)) 5 | Space: O(n) 6 | */ 7 | 8 | 9 | typedef long long ll; 10 | class Solution { 11 | vector dijkstra(int n, vector> *graph, int src) { 12 | vector distance(n, -1); 13 | set> q; 14 | distance[src] = 0; 15 | q.insert({0, src}); 16 | while (!q.empty()) { 17 | ll dist = q.begin()->first; 18 | int node = q.begin()->second; 19 | q.erase(q.begin()); 20 | for (auto nbr : graph[node]) { 21 | if (distance[nbr.first] == -1) { 22 | distance[nbr.first] = dist + nbr.second; 23 | q.insert({distance[nbr.first], nbr.first}); 24 | } else if (distance[nbr.first] > dist + nbr.second) { 25 | q.erase({distance[nbr.first], nbr.first}); 26 | distance[nbr.first] = dist + nbr.second; 27 | q.insert({distance[nbr.first], nbr.first}); 28 | } 29 | } 30 | } 31 | 32 | return distance; 33 | } 34 | 35 | public: 36 | long long minimumWeight(int n, vector> &edges, int src1, int src2, int dest) { 37 | vector> graph[n]; 38 | vector> revGraph[n]; 39 | for (auto edge : edges) { 40 | graph[edge[0]].push_back({edge[1], edge[2]}); 41 | revGraph[edge[1]].push_back({edge[0], edge[2]}); 42 | } 43 | auto src1ToAll = dijkstra(n, graph, src1); 44 | auto src2ToAll = dijkstra(n, graph, src2); 45 | auto destToAll = dijkstra(n, revGraph, dest); 46 | if (destToAll[src1] == -1 || destToAll[src2] == -1) return -1; 47 | ll dist = LLONG_MAX; 48 | for (int common = 0; common < n; common++) { 49 | if (destToAll[common] != -1 && src1ToAll[common] != -1 && src2ToAll[common] != -1) 50 | dist = min(dist, destToAll[common] + src1ToAll[common] + src2ToAll[common]); 51 | } 52 | return dist; 53 | } 54 | }; 55 | -------------------------------------------------------------------------------- /Hard/Number_of_Pairs_Satisfying_Inequality.cpp: -------------------------------------------------------------------------------- 1 | // You are given two 0-indexed integer arrays nums1 and nums2, each of size n, and an integer diff. Find the number of pairs (i, j) such that: 2 | 3 | // 0 <= i < j <= n - 1 and 4 | // nums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff. 5 | 6 | // Return the number of pairs that satisfy the conditions. 7 | 8 | 9 | // Solution 10 | 11 | #include 12 | #include 13 | using namespace __gnu_pbds; 14 | 15 | #define order_set tree, null_type,less>, rb_tree_tag,tree_order_statistics_node_update> 16 | class Solution { 17 | public: 18 | long long numberOfPairs(vector& nums1, vector& nums2, int diff) { 19 | 20 | int n=nums1.size(); 21 | long long ans=0; 22 | vector t1; 23 | 24 | for(int i=0;i>>>>>>>>> 3 | 4 | /* 5 | Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false. 6 | 7 | Example 1: 8 | 9 | Input: s1 = "abcde", s2 = "caebd" 10 | Output: false 11 | 12 | Example 2: 13 | 14 | Input: s1 = "a", s2 = "a" 15 | Output: true 16 | 17 | */ 18 | 19 | class Solution { 20 | public: 21 | 22 | unordered_map m; 23 | 24 | bool isScramble(string s1, string s2) { 25 | 26 | string key = s1 + " " + s2; 27 | 28 | // precheck the key ,whether it's available in map or not 29 | 30 | if (m.find(key) != m.end()) 31 | return m[key]; 32 | 33 | if (s1.compare(s2) == 0) { 34 | 35 | return m[key] = true; 36 | 37 | } 38 | 39 | if (s1.length() <= 1) { 40 | 41 | // equal to is used also becasue if it was single character and was same with s2 then it 42 | // would alrady has been returned true by above if statement 43 | 44 | m[key] = false; 45 | return false; 46 | } 47 | 48 | int n = s1.length(); 49 | int flag = false; 50 | for (int i = 1; i <= n - 1; i++) { 51 | if ((isScramble(s1.substr(0, i), s2.substr(n - i, i)) && isScramble(s1.substr(i), s2.substr(0, n - i))) || 52 | (isScramble(s1.substr(0, i), s2.substr(0, i)) && isScramble(s1.substr(i), s2.substr(i)))) { 53 | flag = true; 54 | break; 55 | } 56 | } 57 | 58 | return m[key] = flag; 59 | 60 | 61 | } 62 | }; 63 | 64 | -------------------------------------------------------------------------------- /Hard/Sliding Window Maximum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector maxSlidingWindow(vector& nums, int k) { 4 | 5 | deque maxi(k); 6 | vector ans; 7 | 8 | for(int i = 0; i < k; i++) { 9 | 10 | while(!maxi.empty() && nums[maxi.back()] <= nums[i]) { 11 | maxi.pop_back(); 12 | } 13 | maxi.push_back(i); 14 | } 15 | ans.push_back(nums[maxi.front()]); 16 | 17 | for(int i = k; i < nums.size(); i++) { 18 | 19 | //removal 20 | while(!maxi.empty() && i-maxi.front() >= k) { 21 | maxi.pop_front(); 22 | } 23 | 24 | //addition 25 | while(!maxi.empty() && nums[maxi.back()] <= nums[i]) { 26 | maxi.pop_back(); 27 | } 28 | 29 | maxi.push_back(i); 30 | 31 | ans.push_back(nums[maxi.front()]); 32 | } 33 | return ans; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /Hard/Subset_Sum_Problem.cpp: -------------------------------------------------------------------------------- 1 | // A Dynamic Programming solution for subset sum problem 2 | #include 3 | 4 | // Returns true if there is a subset of set[] with sun equal to given sum 5 | bool isSubsetSum(int set[], int n, int sum) 6 | { 7 | // The value of subset[i][j] will be true if there is a 8 | // subset of set[0..j-1] with sum equal to i 9 | bool subset[n+1][sum+1]; 10 | 11 | // If sum is 0, then answer is true 12 | for (int i = 0; i <= n; i++) 13 | subset[i][0] = true; 14 | 15 | // If sum is not 0 and set is empty, then answer is false 16 | for (int i = 1; i <= sum; i++) 17 | subset[0][i] = false; 18 | 19 | // Fill the subset table in botton up manner 20 | for (int i = 1; i <= n; i++) 21 | { 22 | for (int j = 1; j <= sum; j++) 23 | { 24 | if(j= set[i-1]) 27 | subset[i][j] = subset[i-1][j] || 28 | subset[i - 1][j-set[i-1]]; 29 | } 30 | } 31 | 32 | /* // uncomment this code to print table 33 | for (int i = 0; i <= n; i++) 34 | { 35 | for (int j = 0; j <= sum; j++) 36 | printf ("%4d", subset[i][j]); 37 | printf("\n"); 38 | }*/ 39 | 40 | return subset[n][sum]; 41 | } 42 | 43 | // Driver program to test above function 44 | int main() 45 | { 46 | int set[] = {3, 34, 4, 12, 5, 2}; 47 | int sum = 9; 48 | int n = sizeof(set)/sizeof(set[0]); 49 | if (isSubsetSum(set, n, sum) == true) 50 | printf("Found a subset with given sum"); 51 | else 52 | printf("No subset with given sum"); 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /Hard/Substring_with_catenation_of_All_words.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPossible(string &s,int i,int j , unordered_map &hm,int len){ 4 | 5 | unordered_map freq; // map frequency of each word occuring in this window 6 | int k = i; 7 | while(k findSubstring(string s, vector& words) { 22 | 23 | 24 | 25 | unordered_map hm; 26 | for(int k = 0;k ans; // ans vector 34 | 35 | while(j s1 -> s2 -> ... -> sk such that: 4 | 5 | // Every adjacent pair of words differs by a single letter. 6 | // Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList. 7 | // sk == endWord 8 | // Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists. 9 | 10 | class Solution { 11 | public: 12 | int ladderLength(string beginWord, string endWord, vector& wordList) { 13 | queue> q; 14 | unordered_set st(wordList.begin(), wordList.end()); 15 | unordered_set vis; 16 | 17 | q.push({beginWord, 1}); 18 | vis.insert(beginWord); 19 | while(!q.empty()){ 20 | string w = q.front().first; 21 | int lvl = q.front().second; 22 | q.pop(); 23 | if(w == endWord) return lvl; 24 | for(int i = 0; i < w.size(); i++){ 25 | string temp = w; 26 | for(char ch = 'a'; ch <= 'z'; ch++){ 27 | temp[i] = ch; 28 | if(st.find(temp) != st.end() && vis.find(temp) == vis.end()){ 29 | q.push({temp, lvl+1}); 30 | vis.insert(temp); 31 | } 32 | } 33 | } 34 | } 35 | return 0; 36 | } 37 | }; -------------------------------------------------------------------------------- /Hard/closestKvalues.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode() {} 8 | * TreeNode(int val) { this.val = val; } 9 | * TreeNode(int val, TreeNode left, TreeNode right) { 10 | * this.val = val; 11 | * this.left = left; 12 | * this.right = right; 13 | * } 14 | * } 15 | */ 16 | class Solution { 17 | public List closestKValues(TreeNode root, double target, int k) { 18 | 19 | Stack s1 = new Stack<>(); 20 | Stack s2 = new Stack<>(); 21 | 22 | inorder(root, false, target, s1); 23 | inorder(root, true, target, s2); 24 | 25 | List result = new ArrayList<>(); 26 | 27 | int count =0; 28 | 29 | while( count < k) 30 | { 31 | if(s1.isEmpty()) 32 | result.add(s2.pop()); 33 | else if (s2.isEmpty()) 34 | result.add(s1.pop()); 35 | 36 | else if(Math.abs(s1.peek() - target) < Math.abs(s2.peek() - target)) 37 | result.add(s1.pop()); 38 | else 39 | result.add(s2.pop()); 40 | 41 | count++; 42 | } 43 | 44 | return result; 45 | } 46 | 47 | public void inorder(TreeNode root, boolean reverse, double target, Stack stack) 48 | { 49 | if(root == null) 50 | return; 51 | 52 | inorder( reverse ? root.right: root.left, reverse ,target, stack ); 53 | if((!reverse && root.val > target) ||(reverse && root.val <= target)) 54 | return; 55 | stack.push(root.val); 56 | inorder( reverse ? root.left: root.right, reverse ,target, stack ); 57 | 58 | 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Hard/countSmaller.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public class TreeNode 3 | { 4 | int val; 5 | int count = 1; 6 | TreeNode left; 7 | TreeNode right; 8 | 9 | TreeNode(int val) 10 | { 11 | this.val = val; 12 | } 13 | } 14 | 15 | public int insert_BST(TreeNode root, int val) 16 | { 17 | int sum = 0; 18 | while(true) 19 | { 20 | if(val <= root.val) 21 | { 22 | root.count++; 23 | if(root.left != null) 24 | root = root.left; 25 | 26 | else 27 | { 28 | root.left = new TreeNode(val); 29 | break; 30 | } 31 | } 32 | else 33 | { 34 | sum+= root.count; 35 | 36 | if(root.right != null) 37 | root = root.right; 38 | 39 | else 40 | { 41 | root.right = new TreeNode(val); 42 | break; 43 | } 44 | } 45 | } 46 | return sum; 47 | } 48 | public List countSmaller(int[] nums) { 49 | List ans = new ArrayList<>(); 50 | if(nums == null || nums.length ==0) 51 | return ans; 52 | TreeNode root = new TreeNode(nums[nums.length-1]); 53 | ans.add(0); 54 | for(int i = nums.length-2; i >=0; i--) 55 | { 56 | int count = insert_BST(root, nums[i]); 57 | ans.add(count); 58 | } 59 | Collections.reverse(ans); 60 | return ans; 61 | 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Hard/findMin.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findMin(int[] nums) { 3 | int left = 0; 4 | int right = nums.length -1; 5 | 6 | while (left < right) 7 | { 8 | 9 | int mid = left +(right - left)/2; 10 | if(nums[mid] > nums[right]) 11 | left = mid+1; 12 | else if(nums[mid] < nums[right]) 13 | right = mid; 14 | else 15 | right--; 16 | 17 | } 18 | 19 | return nums[left]; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Hard/first_missing_positive.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int firstMissingPositive(int[] nums) { 3 | int n = nums.length; 4 | for (int i = 0; i < n; i++) { 5 | while (nums[i] != i + 1) { 6 | if (nums[i] <= 0 || nums[i] >= n) 7 | break; 8 | if(nums[i]==nums[nums[i]-1]) 9 | break; 10 | int temp = nums[i]; 11 | nums[i] = nums[temp - 1]; 12 | nums[temp - 1] = temp; 13 | } 14 | } 15 | for (int i = 0; i < n; i++){ 16 | if (nums[i] != i + 1){ 17 | return i + 1; 18 | } 19 | } 20 | return n + 1; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Hard/ladderLength.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int ladderLength(String beginWord, String endWord, List wordList1) { 3 | Set wordList = new HashSet<>(); 4 | for(int i =0; i< wordList1.size(); i++) 5 | wordList.add(wordList1.get(i)); 6 | if(!wordList.contains(endWord)) 7 | return 0; 8 | Queue q = new LinkedList<>(); 9 | wordList.add(endWord); 10 | 11 | q.offer(beginWord); 12 | int level =0; 13 | 14 | while(!q.isEmpty()) 15 | { 16 | level++; 17 | int size = q.size(); 18 | 19 | for(int i = 0; i < size; i++) 20 | { 21 | 22 | String curr = q.poll(); 23 | 24 | for( int j = 0; j < curr.length(); j++) 25 | { 26 | char c[] = curr.toCharArray(); 27 | for(char x ='a'; x<='z'; x++) 28 | { 29 | c[j] =x; 30 | 31 | String temp = String.valueOf(c); 32 | if(temp.equals(endWord)) 33 | return level+1; 34 | if(curr!= temp && wordList.contains(temp)) 35 | { 36 | q.add(temp); 37 | wordList.remove(temp); 38 | 39 | } 40 | } 41 | 42 | } 43 | 44 | } 45 | 46 | } 47 | 48 | return 0; 49 | 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Hard/largest_Rectangle_in_Histogram.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | vector nextSmallerElement(vector &arr,int n){ 4 | stack s; 5 | s.push(-1); 6 | 7 | vectorans(n); 8 | 9 | for(int i=n-1;i>=0;i--){ 10 | int curr=arr[i]; 11 | while(s.top()!=-1 && arr[s.top()]>=curr){ 12 | s.pop(); 13 | } 14 | ans[i]=s.top(); 15 | s.push(i); 16 | } 17 | return ans; 18 | 19 | } 20 | 21 | vector prevSmallerElement(vector &arr,int n){ 22 | stack s; 23 | s.push(-1); 24 | 25 | vectorans(n); 26 | 27 | for(int i=0;i=curr){ 30 | s.pop(); 31 | } 32 | ans[i]=s.top(); 33 | s.push(i); 34 | } 35 | return ans; 36 | 37 | } 38 | 39 | public: 40 | int largestRectangleArea(vector& heights) { 41 | int n=heights.size(); 42 | 43 | vector next(n); 44 | next=nextSmallerElement(heights, n); 45 | 46 | vector prev(n); 47 | prev=prevSmallerElement(heights,n); 48 | 49 | int area=INT_MIN; 50 | 51 | for(int i=0;i 3 | using namespace std; 4 | #define fast ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0) 5 | #define fn < n; k < n ? i += 1 : i -= 1) 8 | #define ll long long 9 | #define deb(x) cout << #x << "=" << x << endl 10 | #define debg(x) cout << x << endl 11 | #define deb2(x, y) cout << #x << "=" << x << "," << #y << "=" << y << endl 12 | #define pb push_back 13 | #define mp make_pair 14 | #define tr(it, a) for(auto it = a.begin(); it != a.end(); it++) 15 | #define F first 16 | #define S second 17 | #define PI 3.1415926535897932384626 18 | typedef pair pii; 19 | typedef pair pl; 20 | typedef vector vi; 21 | typedef vector vl; 22 | #define a *max_element(v.begin(),v.end()) 23 | #define b *min_element(v.begin(),v.end()) 24 | #define fe(i) for(i=0; i!='\n'; i++) 25 | 26 | 27 | void solve() 28 | { 29 | string str; 30 | cin>>str; 31 | int GG=0; 32 | int RR=0; 33 | for (int i = 0; i < str.size(); i++) 34 | { 35 | if(str[i]==str[i+1]) 36 | { 37 | if(str[i]=='R'){RR++;} 38 | else{GG++;} 39 | } 40 | } 41 | if(str[str.size()-1]==str[0]){ 42 | if(str[0]=='R'){RR++;} 43 | else{GG++;} 44 | } 45 | if((RR==GG)&&RR<=1&&GG<=1){cout<<"yes" fn} 46 | else{cout<<"no" fn} 47 | return; 48 | } 49 | int main() 50 | { 51 | fast; 52 | srand(chrono::high_resolution_clock::now().time_since_epoch().count()); 53 | 54 | int t; 55 | cin >> t; 56 | while (t--) 57 | { 58 | solve(); 59 | } 60 | return 0; 61 | } 62 | -------------------------------------------------------------------------------- /Hard/skyline.java: -------------------------------------------------------------------------------- 1 | public class skyline{ 2 | // 218. The Skyline Problem 3 | // tc O(nlogn) sc O(n) 4 | // As we need the points of the skyline formed by the buldings, analyse what it is 5 | // the points which can be seen from top and its endpoint hasn't come 6 | // So we will use priority queue for storing the max height so far 7 | // We will transform the buildings array according to our need 8 | // for starting index of the building as { building[0],-building[2]} 9 | // and ending index as { building[0],building[2]} 10 | // this is done just to differentiate starting and end indexes with their heights mentioned 11 | // Now, when we will see start index add the height of it in pq and at end index remove that particular end index's height 12 | // if the currmax is changed from the previous max then this is a skyline point and add it in the answer simply. 13 | public List> getSkyline(int[][] buildings) { 14 | int n = buildings.length,idx=0,prevMax=0; 15 | int[][] arrBuild = new int[2*n][2]; 16 | PriorityQueue pq = new PriorityQueue<>((a,b)->{ 17 | return b-a; 18 | }); 19 | 20 | List> ans = new ArrayList<>(); 21 | pq.add(0); 22 | for(int[] building:buildings){ 23 | arrBuild[idx][0] = building[0]; 24 | arrBuild[idx][1] = -building[2]; 25 | idx++; 26 | arrBuild[idx][0] = building[1]; 27 | arrBuild[idx][1] = building[2]; 28 | idx++; 29 | } 30 | Arrays.sort(arrBuild,(a,b)->{ 31 | return a[0]==b[0]?a[1]-b[1]:a[0]-b[0]; 32 | }); 33 | 34 | for(int[] arr:arrBuild){ 35 | if(arr[1]<0){ 36 | pq.add(-arr[1]); 37 | } 38 | else{ 39 | pq.remove(arr[1]); 40 | } 41 | int currMax = pq.peek(); 42 | if(currMax!=prevMax){ 43 | List smallAns= new ArrayList<>(); 44 | smallAns.add(arr[0]); 45 | smallAns.add(currMax); 46 | ans.add(smallAns); 47 | prevMax = pq.peek(); 48 | } 49 | } 50 | return ans; 51 | } 52 | } -------------------------------------------------------------------------------- /Hard/splitArr.java: -------------------------------------------------------------------------------- 1 | public class splitArr { 2 | public static void main(String[] args) { 3 | int[] arr= {7, 2, 5, 8, 10}; 4 | int m= 2; 5 | System.out.println(search(arr, m)); 6 | } 7 | static int search(int[] arr, int m){ 8 | int start =0; 9 | int end= 0; 10 | for (int i = 0; i < arr.length; i++) { 11 | start= Math.max(start, arr[i]); 12 | end+= arr[i]; 13 | } 14 | while (startmid){ 21 | sum= num; 22 | p++; 23 | }else { 24 | sum+= num; 25 | } 26 | } 27 | if(p>m){ 28 | start= mid+1; 29 | }else { 30 | end= mid; 31 | } 32 | } 33 | return end; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Hard/trap1.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int trap(int[] height) { 3 | int l[] = new int [height.length]; 4 | int r[] = new int [height.length]; 5 | if(height.length==0) 6 | return 0; 7 | l[0] = height[0]; 8 | r[height.length-1]= height[height.length-1]; 9 | for(int i=1 ; i< height.length; i++) 10 | { 11 | l[i] = Math.max(height[i], l[i-1]); 12 | 13 | } 14 | 15 | for(int i=height.length-2 ; i>= 0; i--) 16 | { 17 | r[i] = Math.max(r[i+1], height[i]); 18 | 19 | } 20 | 21 | int count =0; 22 | 23 | for(int i=0; i< height.length; i++) 24 | { 25 | count+= Math.min(l[i], r[i]) - height[i]; 26 | } 27 | 28 | return count; 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Hard/trapping_rain_water.cpp: -------------------------------------------------------------------------------- 1 | // Problem: 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 can trap after raining. 5 | 6 | 7 | 8 | // Solution 1 9 | // Time complexity- O(n) Space complexity - O(n) 10 | class Solution { 11 | public: 12 | int trap(vector& height) { 13 | int n=height.size(); 14 | vector leftmax(n),rightmax(n); 15 | leftmax[0]=height[0];rightmax[n-1]=height[n-1]; 16 | for(int i=1;i& height) { 35 | int ans=0; 36 | int leftmax=0,rightmax=0; 37 | int i=0,j=height.size()-1; 38 | while(i<=j){ 39 | if(height[i]&st , string &target,int m, vector&dp) { 6 | 7 | if(i==m) return true ; 8 | 9 | if(dp[i] != -1) return dp[i] ; 10 | 11 | string temp = "" ; 12 | for(int j = i ; j& wordDict) { 24 | 25 | setst ; 26 | for(auto x : wordDict) st.insert(x) ; 27 | int m = s.size() ; 28 | vectordp(m+1,-1) ; 29 | return solve(0,st,s,m,dp) ; 30 | 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Medium/240. Search a 2D Matrix II/Rotate Image/rotate_image_48.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void rotate(int[][] matrix) { 3 | int cols=matrix[0].length-1; 4 | int size=matrix.length-1; 5 | for(int i=0;i<=size;i++){ 6 | for(int j=i;j<=cols;j++){ 7 | int temp=0; 8 | temp=matrix[i][j]; 9 | matrix[i][j]=matrix[j][i]; 10 | matrix[j][i]=temp; 11 | } 12 | } 13 | for(int i=0;i<=size;i++){ 14 | for(int j=0;j<=cols/2;j++){ 15 | int t=0; 16 | t=matrix[i][j]; 17 | matrix[i][j]=matrix[i][cols-j]; 18 | matrix[i][cols-j]=t; 19 | } 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Medium/78 Subsets.py: -------------------------------------------------------------------------------- 1 | 78. Subsets 2 | https://leetcode.com/problems/subsets/ 3 | 4 | 5 | 6 | class Solution: 7 | def subsets(self, nums: List[int]) -> List[List[int]]: 8 | 9 | #recursion apporch 10 | def helper(p , up , ans): 11 | if up == []: 12 | p = p[:-1] 13 | ans.append(p.split(" ")) 14 | return 15 | 16 | 17 | helper(p+str(up[0])+" " , up[1:] , ans) 18 | helper(p , up[1:] , ans) 19 | return ans 20 | 21 | return helper("" , nums , []) 22 | 23 | 24 | #itrative apporch 25 | arr = [[]] 26 | for i in nums: 27 | for j in range(len(arr)): 28 | newItem = arr[j][:] 29 | newItem.append(i) 30 | arr.append(newItem) 31 | return arr 32 | 33 | 34 | -------------------------------------------------------------------------------- /Medium/99-Recovery-Binary-searchTree.py: -------------------------------------------------------------------------------- 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 | void recoverTree(TreeNode* root) { 15 | 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Medium/Add_One_Row_to_Tree.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vanshika2063/Leetcode-Questions/6ac1ef53044340cec9592fb4eab47d80f5440f31/Medium/Add_One_Row_to_Tree.cpp -------------------------------------------------------------------------------- /Medium/Armstrongnumber.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class IsArmstrong { 4 | public static void main(String[] args) { 5 | int my_input, my_temp, my_remainder, my_result; 6 | my_result = 0; 7 | 8 | System.out.println("Required packages have been imported"); 9 | Scanner my_scanner = new Scanner(System.in); 10 | System.out.println("A reader object has been defined "); 11 | System.out.print("Enter the number : "); 12 | my_input = my_scanner.nextInt(); 13 | my_temp = my_input; 14 | while (my_temp != 0){ 15 | my_remainder = my_temp % 10; 16 | my_result += Math.pow(my_remainder, 3); 17 | my_temp /= 10; 18 | } 19 | if(my_result == my_input) 20 | System.out.println(my_input + " is an Armstrong number"); 21 | else 22 | System.out.println(my_input + " is not an Armstrong number"); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Medium/Bitwise XOR of All Pairings.cpp: -------------------------------------------------------------------------------- 1 | 2 | // You are given two 0-indexed arrays, nums1 and nums2, consisting of non-negative integers. There exists another array, nums3, which contains the bitwise XOR of all pairings of integers between nums1 and nums2 (every integer in nums1 is paired with every integer in nums2 exactly once). 3 | 4 | // Return the bitwise XOR of all integers in nums3. 5 | 6 | // Input: nums1 = [2,1,3], nums2 = [10,2,5,0] 7 | // Output: 13 8 | // Explanation: 9 | // A possible nums3 array is [8,0,7,2,11,3,4,1,9,1,6,3]. 10 | // The bitwise XOR of all these numbers is 13, so we return 13. 11 | 12 | // Input: nums1 = [1,2], nums2 = [3,4] 13 | // Output: 0 14 | // Explanation: 15 | // All possible pairs of bitwise XORs are nums1[0] ^ nums2[0], nums1[0] ^ nums2[1], nums1[1] ^ nums2[0], 16 | // and nums1[1] ^ nums2[1]. 17 | // Thus, one possible nums3 array is [2,5,1,6]. 18 | // 2 ^ 5 ^ 1 ^ 6 = 0, so we return 0. 19 | 20 | class Solution { 21 | public: 22 | int xorAllNums(vector& nums1, vector& nums2) { 23 | int size1 = nums1.size(); 24 | int size2 = nums2.size(); 25 | int x1 = 0, x2 = 0; 26 | for(auto i: nums1){ 27 | x1^=i; 28 | } 29 | for(auto i: nums2){ 30 | x2^=i; 31 | } 32 | if(size1 % 2 != 0 && size2 % 2 != 0){ 33 | return x1^x2; 34 | } 35 | if(size1 % 2 == 0 && size2 % 2 != 0){ 36 | return x1; 37 | } 38 | if(size1 % 2 != 0 && size2 % 2 == 0){ 39 | return x2; 40 | } 41 | else 42 | return 0; 43 | 44 | 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /Medium/Combination_Sum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List combinationSum(int[] candidates, int target) 3 | { 4 | List> ans = new ArrayList(); 5 | 6 | findCombinations(candidates, 0, target, ans, new ArrayList<>()); 7 | 8 | return ans; 9 | } 10 | 11 | public void findCombinations(int[] candidates, int index, int target, List> ans, List current) 12 | { 13 | if(target == 0) 14 | { 15 | ans.add(new ArrayList(current)); 16 | return; 17 | } 18 | 19 | for(int i = index; i< candidates.length ; i++) 20 | { 21 | if(candidates[i] <= target ) 22 | { 23 | current.add(candidates[i]); 24 | findCombinations(candidates,i,target-candidates[i],ans,current); 25 | current.remove(new Integer(candidates[i])); 26 | } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Medium/Container With Most Water/Container With Most Water.java: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). 3 | Find two lines that together with the x-axis form a container, such that the container contains the most water. 4 | Return the maximum amount of water a container can store. 5 | Notice that you may not slant the container 6 | */ 7 | 8 | class Solution { 9 | public int maxArea(int[] height) { 10 | 11 | int start=0; 12 | int end=height.length-1; 13 | int max=0; 14 | while(start int: 3 | length=len(height)-1 4 | max_area=0 5 | right=len(height)-1 6 | left=0 7 | while left 2 | using namespace std; 3 | class Solution { 4 | public: 5 | long long countBadPairs(vector& nums) { 6 | unordered_mapm; 7 | long long n=nums.size(); 8 | long long total_pair=n*(n-1)/2; 9 | long long goodpairs=0; 10 | for(int i=0;i hm=new HashMap<>(); 27 | // //find occurrence of all Good Pairs and then substract from total posible pairs to get the count of Bad Pairs.! // 28 | // for(int i=0;inums; 44 | int n; 45 | cin>>n; 46 | for (int i = 0; i < n; i++) 47 | { 48 | int x; 49 | cin>>x; 50 | nums.push_back(x); 51 | } 52 | Solution S1; 53 | cout< hm=new HashMap<>(); 6 | 7 | for(int i=0;i "1" 4 | // 'B' -> "2" 5 | // ... 6 | // 'Z' -> "26" 7 | // To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into: 8 | 9 | // "AAJF" with the grouping (1 1 10 6) 10 | // "KJF" with the grouping (11 10 6) 11 | // Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06". 12 | 13 | // Given a string s containing only digits, return the number of ways to decode it. 14 | 15 | // The test cases are generated so that the answer fits in a 32-bit integer. 16 | 17 | 18 | 19 | // Example 1: 20 | 21 | // Input: s = "12" 22 | // Output: 2 23 | // Explanation: "12" could be decoded as "AB" (1 2) or "L" (12). 24 | // Example 2: 25 | 26 | // Input: s = "226" 27 | // Output: 3 28 | // Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). 29 | // Example 3: 30 | 31 | // Input: s = "06" 32 | // Output: 0 33 | // Explanation: "06" cannot be mapped to "F" because of the leading zero ("6" is different from "06"). 34 | 35 | 36 | // Constraints: 37 | 38 | // 1 <= s.length <= 100 39 | // s contains only digits and may contain leading zero(s). 40 | 41 | 42 | class Solution { 43 | public: 44 | int numDecodings(string s) { 45 | vector dp(s.size()+1); 46 | int way1, way2; 47 | dp[0]=1; 48 | if(s[0]=='0') dp[1]=0; 49 | else dp[1]=1; 50 | for(int i=2; i<=s.size(); i++) 51 | { 52 | if(s[i-1]=='0') way1=0; 53 | else way1=dp[i-1]; 54 | if(stoi(s.substr(i-2,2))<=26 && stoi(s.substr(i-2,2))>0 && s[i-2]!='0') 55 | way2=dp[i-2]; 56 | else way2=0; 57 | dp[i]= way1+way2; 58 | } 59 | return dp[s.size()]; 60 | } 61 | }; -------------------------------------------------------------------------------- /Medium/DecodeWays.java: -------------------------------------------------------------------------------- 1 | public class DecodeWays { 2 | 3 | // 91. Decode Ways 4 | // TC O(n) SC O(n) 5 | // In this we will consider the numbers individually and last two as a group 6 | // when we are considering individually then current ways at i = ways at i-1 7 | // when we are considering in group then current ways at i = ways at i-2 8 | // considering all the edge cases do a dry run on "11106" 9 | public int numDecodings(String s) { 10 | if(s.charAt(0) == '0'){ 11 | return 0; 12 | } 13 | int n = s.length(); 14 | int[] dp = new int[n]; 15 | dp[0] = 1; 16 | for(int i=1;i=10 && num<=26){ 25 | if(i>=2){ 26 | dp[i] += dp[i-2]; 27 | } 28 | else{ 29 | dp[i] += 1; 30 | } 31 | } 32 | 33 | if(num!=10 && num!=20){ 34 | dp[i] += dp[i-1]; 35 | } 36 | } 37 | return dp[n-1]; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /Medium/DeleteNodeLinkedList.java: -------------------------------------------------------------------------------- 1 | public class DeleteNodeLinkedList { 2 | 3 | public static class ListNode { 4 | int val; 5 | ListNode next; 6 | ListNode(int x){ 7 | val = x; 8 | } 9 | } 10 | 11 | public static void deleteNode(ListNode node) { 12 | node.val = node.next.val; 13 | node.next = node.next.next; 14 | } 15 | 16 | private static void printList(ListNode head){ 17 | while(head != null){ 18 | System.out.print(head.val + " "); 19 | head = head.next; 20 | } 21 | System.out.println(""); 22 | } 23 | 24 | public static void main(String[] args) { 25 | 26 | ListNode head = new ListNode(1); 27 | head.next = new ListNode(2); 28 | head.next.next = new ListNode(3); 29 | head.next.next.next = new ListNode(4); 30 | head.next.next.next.next = new ListNode(5); 31 | 32 | System.out.print("Given Linked List: "); 33 | printList(head); 34 | 35 | ListNode node = head; 36 | int n = 2; // n should be smaller than list length 37 | while(n-- > 0){ 38 | node = node.next; 39 | } 40 | 41 | System.out.println("Delete node: " + node.val); 42 | deleteNode(node); 43 | 44 | System.out.print("After delete: "); 45 | printList(head); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Medium/Design Linked List: -------------------------------------------------------------------------------- 1 | class Node { 2 | public: 3 | int val; 4 | Node* next; 5 | Node(int val) { 6 | this->val=val; 7 | next=NULL; 8 | } 9 | }; 10 | 11 | class MyLinkedList { 12 | public: 13 | int size=0; 14 | Node* head=new Node(0); 15 | MyLinkedList() { 16 | 17 | } 18 | 19 | int get(int index) { 20 | if(index>=size) return -1; 21 | Node* temp=head->next; 22 | for(int i=0;inext; 23 | return temp->val; 24 | } 25 | 26 | void addAtHead(int val) { 27 | Node* temp=head->next; 28 | head->next=new Node(val); 29 | head->next->next=temp; 30 | size++; 31 | 32 | } 33 | 34 | void addAtTail(int val) { 35 | Node* temp=head; 36 | while(temp->next!=NULL) temp=temp->next; 37 | temp->next=new Node(val); 38 | size++; 39 | } 40 | 41 | void addAtIndex(int index, int val) { 42 | if(index>size) return; 43 | Node* temp=head; 44 | for(int i=0;inext; 45 | Node* temp1=temp->next; 46 | temp->next=new Node(val); 47 | temp->next->next=temp1; 48 | size++; 49 | } 50 | 51 | void deleteAtIndex(int index) { 52 | if(index>=size) return; 53 | Node* temp=head; 54 | for(int i=0;inext; 55 | Node* temp1=temp->next; 56 | temp->next=temp1->next; 57 | temp1->next=NULL; 58 | size--; 59 | delete temp1; 60 | } 61 | }; 62 | -------------------------------------------------------------------------------- /Medium/Divide_Two_Integers.cpp: -------------------------------------------------------------------------------- 1 | int divide(int dividend, int divisor) { 2 | if(divisor==-1 && dividend == INT_MIN) 3 | return INT_MAX; 4 | bool sign = (dividend>=0) == (divisor>=0) ? true : false; 5 | long int did = abs(dividend); 6 | long int div = abs(divisor); 7 | long int result=0; 8 | // int count=0, temp=divisor; 9 | while(did - div >= 0){ 10 | int count=0; 11 | while((did - (div<<1<=0) 12 | count++; 13 | result += 1< 3 | using namespace std; 4 | #define fast ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0) 5 | #define fn endl; 6 | #define fo(i, n) for (i = 0; i < n; i++) 7 | #define Fo(i, k, n) for (i = k; k < n ? i < n : i > n; k < n ? i += 1 : i -= 1) 8 | #define ll long long 9 | #define deb(x) cout << #x << endl 10 | #define debg(x) cout << x << endl 11 | #define deb2(x, y) cout << #x << "=" << x << "," << #y << "=" << y << endl 12 | #define pb push_back 13 | #define mp make_pair 14 | #define tr(it, a) for (auto it = a.begin(); it != a.end(); it++) 15 | #define F first 16 | #define S second 17 | #define ass(x) sizeof(x) / sizeof(x[0]) 18 | #define PI 3.1415926535897932384626 19 | typedef pair pii; 20 | typedef pair pl; 21 | typedef vector vi; 22 | typedef vector vl; 23 | #define max_l *max_element(v.begin(), v.end()) 24 | #define min_l *min_element(v.begin(), v.end()) 25 | #define fe(i) for (i = 0; i != '\n'; i++) 26 | 27 | 28 | void solve() 29 | { 30 | int a,b,c,d; 31 | cin>>a>>b>>c>>d; 32 | if(max(a,b)>min(c,d) && max(c,d)>min(a,b)){ 33 | deb(YES); 34 | } 35 | else{ 36 | deb(NO); 37 | } 38 | } 39 | int main() 40 | { 41 | fast; 42 | srand(chrono::high_resolution_clock::now().time_since_epoch().count()); 43 | 44 | int t; 45 | cin >> t; 46 | while (t--) 47 | { 48 | solve(); 49 | } 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /Medium/Find All Good Indices/Find-All-Good-Indices.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector goodIndices(vector& nums, int k) { 4 | int n=nums.size(); 5 | vector res; 6 | vector inc(n), dec(n); // inc stores increasing & dec stores decreasing subarray length 7 | 8 | dec[0]=1; // for a single element, subarray length will be 1 9 | for(int i=1;i prev, increase the length 11 | dec[i]=dec[i-1]+1; 12 | else 13 | dec[i]=1; // else, reset the subarray size to 1 14 | } 15 | inc[n-1]=1; 16 | for(int i=n-2;i>=0;i--){ 17 | if(nums[i] <= nums[i+1]) // if cur element <= next, increase the subarray length 18 | inc[i]=inc[i+1]+1; 19 | else 20 | inc[i]=1; // otherwise start a new subarray with single length 21 | } 22 | for(int i=k;i= k and inc[i+1] >= k) 25 | res.push_back(i); 26 | } 27 | return res; 28 | } 29 | }; -------------------------------------------------------------------------------- /Medium/Find First and Last Position of Element in Sorted Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] searchRange(int[] nums, int target) { 3 | 4 | int i = 0,j = nums.length-1,index = -1; 5 | 6 | // find the first occurance of target 7 | while(i <= j){ 8 | int mid = i + (j-i)/2; 9 | 10 | if(nums[mid] == target){ 11 | index = mid; 12 | j = mid-1; // stored result and now traverse in remaining right part 13 | } 14 | 15 | else if(nums[mid] < target) 16 | i = mid+1; // as mid less than target then move in right part of array 17 | 18 | else if(nums[mid] > target) 19 | j = mid-1; // as mid more than target then move in right part of array 20 | } 21 | 22 | if(index == -1) 23 | return new int [] {-1,-1}; 24 | 25 | int res [] = {index, index}; 26 | 27 | // i = 0; their is no need to initialise 'i' again as now will just search in right most part only 28 | // if we want to search only last occurance of target only then use "i = 0" 29 | 30 | j = nums.length-1; 31 | 32 | // find the last occurance of target 33 | 34 | while(i <= j){ 35 | int mid = i + (j-i)/2; 36 | 37 | if(nums[mid] == target){ 38 | index = mid; 39 | i = mid+1; // stored result and now traverse in remaining right part 40 | } 41 | else if (nums[mid] < target) 42 | i = mid+1; // as mid less than target then move in right part of array 43 | 44 | else if (nums[mid] > target) 45 | j = mid-1; // as mid more than target then move in right part of array 46 | } 47 | 48 | res[1] = index; 49 | 50 | return res; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Medium/Find Peak Element.cpp: -------------------------------------------------------------------------------- 1 | //Problem Statement Leetcode 162 2 | /* 3 | A peak element is an element that is strictly greater than its neighbors. 4 | Given a 0-indexed integer array nums, find a peak element, and return its index. 5 | If the array contains multiple peaks, return the index to any of the peaks. 6 | You may imagine that nums[-1] = nums[n] = -∞. 7 | In other words, an element is always considered to be strictly greater than a neighbor that is outside the array. 8 | You must write an algorithm that runs in O(log n) time. 9 | 10 | Example 1: 11 | 12 | Input: nums = [1,2,3,1] 13 | Output: 2 14 | Explanation: 3 is a peak element and your function should return the index number 2. 15 | 16 | Example 2: 17 | 18 | Input: nums = [1,2,1,3,5,6,4] 19 | Output: 5 20 | Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6. 21 | */ 22 | 23 | //Solution.... 24 | class Solution { 25 | public: 26 | int findPeakElement(vector& nums) { 27 | int lo = 0, hi = nums.size()-1, mid; 28 | 29 | while (lo < hi) { 30 | mid = lo + (hi - lo) / 2; 31 | if (nums[mid] < nums[mid + 1]) 32 | lo = mid + 1; 33 | else hi = mid; 34 | } 35 | 36 | return lo; 37 | } 38 | }; -------------------------------------------------------------------------------- /Medium/First_And_Last_Occurence_of_an_Element.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. 3 | If target is not found in the array, return [-1, -1]. 4 | You must write an algorithm with O(log n) runtime complexity. 5 | */ 6 | 7 | /* 8 | Approach: 9 | 1. Find the first occurence of the target element using binary search 10 | Once u find the element then move the high pointer to mid - 1 as we finding the first occurence there might be a chance that there 11 | is another occurence of the element before the current occurence 12 | 13 | 2. Find the last occurence of the target element using binary search 14 | Once u find the element then move the low pointer to mid + 1 as we finding the last occurence there might be a chance that there 15 | is another occurence of the element after the current occurence 16 | */ 17 | 18 | // You can find this question on Leetcode:(34) 19 | 20 | class Solution { 21 | public: 22 | 23 | int binarySearch(vector& nums, int target, bool flag) 24 | { 25 | int low = 0; 26 | int high = nums.size()-1; 27 | 28 | int ansIndex = -1; 29 | while(low <= high) 30 | { 31 | int mid = low + (high-low)/2; 32 | 33 | if(nums[mid] == target) 34 | { 35 | ansIndex = mid; 36 | if(flag == 0) 37 | high = mid - 1; 38 | else 39 | low = mid + 1; 40 | } 41 | else if(nums[mid] > target) 42 | high = mid - 1; 43 | else 44 | low = mid + 1; 45 | } 46 | 47 | return ansIndex; 48 | } 49 | 50 | 51 | 52 | vector searchRange(vector& nums, int target) { 53 | vector ans(2, -1); 54 | ans[0] = binarySearch(nums, target, 0); // flag = 0 for first occurence 55 | ans[1] = binarySearch(nums, target, 1); // flag = 1 for last occurence 56 | return ans; 57 | } 58 | }; 59 | -------------------------------------------------------------------------------- /Medium/Fruit Into Baskets.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def totalFruit(self, fruits: List[int]) -> int: 3 | right=0 4 | left=0 5 | counter={} 6 | max_len=0 7 | while right2: 13 | while len(counter)>2 : 14 | if counter[fruits[left]]==1: 15 | counter.pop(fruits[left]) 16 | else: 17 | counter[fruits[left]]-=1 18 | left+=1 19 | elif len(counter)==2: 20 | max_len=max(max_len,right-left+1) 21 | while len(counter)==2 and right>len(fruits) : 22 | if len(counter)==2: 23 | max_len=max(max_len,right-left+1) 24 | right+=1 25 | if fruits[right] in counter: 26 | counter[fruits[right]]+=1 27 | else: 28 | counter[fruits[right]]=1 29 | if len(counter)<2: 30 | -------------------------------------------------------------------------------- /Medium/House_robber.java: -------------------------------------------------------------------------------- 1 | package com.company; 2 | 3 | public class House_robber { 4 | public static void main(String[] args) { 5 | int[] nums = {1,2,3,1}; 6 | int ans = rob(nums); 7 | System.out.println(ans); 8 | } 9 | 10 | public static int rob(int[] nums) { 11 | int in = nums[0]; 12 | int ex = 0; 13 | int ex_new; 14 | 15 | for(int i=1;i nums2.length){ 11 | return intersection(nums2, nums1); 12 | } 13 | ArrayList list = new ArrayList<>(); 14 | Arrays.sort(nums1); 15 | 16 | for(int num : nums2){ 17 | 18 | if(bS(nums1, num)){ 19 | if(!list.contains(num)){ 20 | list.add(num); 21 | } 22 | } 23 | } 24 | 25 | int[] ans = new int[list.size()]; 26 | 27 | for(int i = 0 ; i < list.size() ; i++){ 28 | ans[i] = list.get(i); 29 | } 30 | return ans; 31 | } 32 | 33 | static boolean bS(int[] arr, int target){ 34 | int s = 0; 35 | int e = arr.length-1; 36 | 37 | while(s <= e){ 38 | int m = s + (e-s)/2; 39 | 40 | if(arr[m] == target){ 41 | return true; 42 | } 43 | if(arr[m] < target){ 44 | s = m+1; 45 | } else{ 46 | e = m-1; 47 | } 48 | } 49 | return false; 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /Medium/Jump_Game.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canJump(int[] nums) { 3 | if(nums[0]==0 && nums.length==1){ 4 | return true; 5 | } 6 | else if(nums[0]==0){ 7 | return false; 8 | } 9 | else if(nums[0]>0&&nums.length==1){ 10 | return true; 11 | } 12 | 13 | int a = nums.length-1; 14 | int aa = a; 15 | 16 | for(int i =0;i findClosestElements(int[] arr, int k, int x) { 11 | int s = 0; 12 | int e = arr.length-k; 13 | 14 | while(s < e){ 15 | int m = s + (e-s)/2; 16 | 17 | int indexJustAfterWindow = m+k; 18 | while(indexJustAfterWindow <= e && arr[m] == arr[indexJustAfterWindow] ){ 19 | indexJustAfterWindow++; 20 | } 21 | 22 | if( Math.abs( arr[m] - x ) > Math.abs( x - arr[indexJustAfterWindow] ) ){ 23 | s = m+1; 24 | } else{ 25 | e = m; 26 | } 27 | } 28 | 29 | List list = new ArrayList<>(); 30 | for(int i = s; i < s +k ; i++){ 31 | list.add( arr[i] ); 32 | } 33 | return list; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Medium/KadaneAlgo.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class KadaneAlgo 3 | { 4 | public static void main(String args[]) 5 | { 6 | Scanner sc = new Scanner(System.in); 7 | 8 | // Input for array size 9 | System.out.println("Enter the size of array : "); 10 | int n=sc.nextInt(); 11 | int arr[]=new int[n]; 12 | 13 | //Input for array elements 14 | System.out.println("Enter array values using spaces : "); 15 | for(int i =0;imaxSum) 35 | { 36 | maxSum=currSum; 37 | } 38 | if(currSum<0) 39 | { 40 | currSum=0; 41 | } 42 | } 43 | return maxSum; 44 | 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Medium/KoKoEatingBanana.java: -------------------------------------------------------------------------------- 1 | public class KoKoEatingBanana { 2 | public static void main(String[] args) { 3 | int[] piles = {3,6,7,11}; 4 | System.out.println(minEatingSpeed(piles, 8)); 5 | } 6 | 7 | static int minEatingSpeed(int[] piles, int h) { 8 | int s = 1; 9 | int e = piles[0]; 10 | for(int pile : piles){ 11 | e = Math.max(e, pile); 12 | } 13 | 14 | while(s < e){ 15 | int m = s + (e-s)/2; 16 | 17 | if( canEatAllWithSpeed(piles, m, h) ){ 18 | e = m; 19 | } else{ 20 | s = m+1; 21 | } 22 | } 23 | return s; 24 | } 25 | 26 | static boolean canEatAllWithSpeed(int[] piles, int allowedBananas, int h) { 27 | int hoursNeeded = 0; 28 | 29 | for(int pile : piles){ 30 | 31 | // dekh agr mne allow kre h 4 banana in 1 hour or is pile main 10 h to 4 + 4 kha paegi or do bchange to 3 ghnte ab ek cheez dekh simple ye nh kr skti 10 /4 to vo seedha mtlb dedega ki 10 main kitne proper 4 ke piece bnenge baat smjh soch thoda thik h or fir ek check lga liyo ki agr modulo krke 0 nhi aaara to mtlb kya h iska ki abhi kuch bche h allowed se km mtlb 4 se km h to bss hour main 1 plus krde bss ab bss shant dimaag se soch aa jaega smjh or agr allowed to 4 h pr piles h 3 to 3 /4 0 aaega or aage bss ek plus ho jaega and that is right!! 32 | hoursNeeded += pile/allowedBananas; 33 | if(pile % allowedBananas != 0){ 34 | hoursNeeded++; 35 | } 36 | } 37 | 38 | return hoursNeeded <= h; 39 | } 40 | 41 | 42 | } 43 | -------------------------------------------------------------------------------- /Medium/LargestnumberofArray.java: -------------------------------------------------------------------------------- 1 | public class LargestInArray{ 2 | public static int getLargest(int[] a, int total){ 3 | int temp; 4 | for (int i = 0; i < total; i++) 5 | { 6 | for (int j = i + 1; j < total; j++) 7 | { 8 | if (a[i] > a[j]) 9 | { 10 | temp = a[i]; 11 | a[i] = a[j]; 12 | a[j] = temp; 13 | } 14 | } 15 | } 16 | return a[total-1]; 17 | } 18 | public static void main(String args[]){ 19 | int a[]={1,2,5,6,3,2}; 20 | int b[]={44,66,99,77,33,22,55}; 21 | System.out.println("Largest: "+getLargest(a,6)); 22 | System.out.println("Largest: "+getLargest(b,7)); 23 | }} 24 | -------------------------------------------------------------------------------- /Medium/Letter_Combinations_of_a_Phone_Number.java: -------------------------------------------------------------------------------- 1 | public static List letterCombinations_4Loops(String digits) { 2 | List ans = new ArrayList<>(); 3 | if (digits == null || digits.length() == 0) { 4 | return ans; 5 | } 6 | 7 | String[] letters = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 8 | int len = digits.length(); 9 | int[] digitsArr = new int[len]; 10 | for (int i = 0; i < len; i++) { 11 | digitsArr[i] = digits.charAt(i) - '0'; 12 | } 13 | 14 | StringBuilder sb = new StringBuilder(); 15 | for (int i = 0; i < len; i++) { 16 | sb.append("a"); 17 | } 18 | 19 | for (int i = 0; i < letters[digitsArr[0] - 2].length(); i++) { 20 | sb.replace(0, 1, letters[digitsArr[0] - 2].charAt(i) + ""); 21 | if (len == 1) { 22 | ans.add(sb.substring(0, 1)); 23 | } 24 | 25 | for (int j = 0; len >= 2 && j < letters[digitsArr[1] - 2].length(); j++) { 26 | sb.replace(1, 2, letters[digitsArr[1] - 2].charAt(j) + ""); 27 | if (len == 2) { 28 | ans.add(sb.toString()); 29 | } 30 | 31 | for (int k = 0; len >= 3 && k < letters[digitsArr[2] - 2].length(); k++) { 32 | sb.replace(2, 3, letters[digitsArr[2] - 2].charAt(k) + ""); 33 | if (len == 3) { 34 | ans.add(sb.toString()); 35 | } 36 | 37 | for (int l = 0; len >= 4 && l < letters[digitsArr[3] - 2].length(); l++) { 38 | sb.replace(3, 4, letters[digitsArr[3] - 2].charAt(l) + ""); 39 | ans.add(sb.toString()); 40 | } 41 | } 42 | } 43 | } 44 | 45 | return ans; 46 | } 47 | -------------------------------------------------------------------------------- /Medium/Letter_Combinations_of_a_Phone_Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def letterCombinations(self, digits: str) -> List[str]: 3 | if len(digits)==0: 4 | return [] 5 | m={} 6 | k=["abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"] 7 | for i in range(2,10): 8 | m[str(i)]=list(k.pop(0)) 9 | 10 | def trv(li,di,digits): 11 | p=m[di] 12 | ans=[] 13 | for i in li: 14 | for j in p: 15 | ans.append(i+j) 16 | li=ans 17 | 18 | if len(digits)>0: 19 | p=digits[0] 20 | digits=digits[1:] 21 | return trv(li,p,digits) 22 | else: 23 | return ans 24 | li=m[digits[0]] 25 | digits=digits[1:] 26 | if len(digits)==0: 27 | return li 28 | p=digits[0] 29 | digits=digits[1:] 30 | 31 | return trv(li,p,digits) 32 | -------------------------------------------------------------------------------- /Medium/LinkedListCycleII.java: -------------------------------------------------------------------------------- 1 | public class LinkedListCycleII { 2 | 3 | public static class ListNode { 4 | int val; 5 | ListNode next; 6 | 7 | ListNode(int x) { 8 | val = x; 9 | next = null; 10 | } 11 | } 12 | public static ListNode detectCycle(ListNode head) { 13 | 14 | ListNode fast = head, slow = head; 15 | 16 | while(fast != null && fast.next != null){ 17 | fast = fast.next.next; 18 | slow = slow.next; 19 | 20 | if(fast == slow){ 21 | fast = head; 22 | 23 | while(fast != slow){ 24 | fast = fast.next; 25 | slow = slow.next; 26 | } 27 | return slow; 28 | } 29 | 30 | } 31 | return null; 32 | } 33 | private static void printList(ListNode head){ 34 | while(head != null){ 35 | System.out.print(head.val + " "); 36 | head = head.next; 37 | } 38 | System.out.println(""); 39 | } 40 | 41 | public static void main(String[] args) { 42 | 43 | ListNode head = new ListNode(1); 44 | head.next = new ListNode(2); 45 | head.next.next = new ListNode(3); 46 | // 1 -> 2 -> 3 47 | 48 | ListNode tmp = new ListNode(4); 49 | tmp.next = new ListNode(5); 50 | // 4 -> 5 51 | 52 | ListNode dummyHead = head; 53 | while(dummyHead.next != null) 54 | dummyHead = dummyHead.next; 55 | 56 | dummyHead.next = tmp; // 1 -> 2 -> 3 (dummyHead) -> 4 -> 5 57 | 58 | tmp = tmp.next; 59 | tmp.next = head.next; // 4 -> 5 (tmp) -> 2 -> 3 -> 4 -> 5 60 | 61 | ListNode node = detectCycle(head); 62 | System.out.println("Cycle node: " + ((node != null) ? node.val : "No Cycle detected")); 63 | 64 | } 65 | } 66 | 67 | -------------------------------------------------------------------------------- /Medium/Longest Subarray With Maximum Bitwise AND/Longest-Subarray-With-Maximum-Bitwise-AND.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestSubarray(vector& nums) { 4 | // Intuition: Maximum AND is only possible when the subarray 5 | // contains only Maximum elements 6 | 7 | // Goal: Find longest subarray containing only maximum element 8 | 9 | int mx = *max_element(nums.begin(), nums.end()); // find the max element first 10 | int res=0, cur=0; // counter variables 11 | 12 | for(const int &num:nums){ 13 | if(num==mx)cur++; // increase counter, if element is = max element 14 | else cur=0; // otherwise reset the counter 15 | res = max(res, cur); // maximize the result 16 | } 17 | return res; 18 | } 19 | }; -------------------------------------------------------------------------------- /Medium/Longest Substring Without Repeating Characters.cpp: -------------------------------------------------------------------------------- 1 | // Given a string s, find the length of the longest substring without repeating characters. 2 | 3 | 4 | 5 | // Example 1: 6 | 7 | // Input: s = "abcabcbb" 8 | // Output: 3 9 | // Explanation: The answer is "abc", with the length of 3. 10 | // Example 2: 11 | 12 | // Input: s = "bbbbb" 13 | // Output: 1 14 | // Explanation: The answer is "b", with the length of 1. 15 | // Example 3: 16 | 17 | // Input: s = "pwwkew" 18 | // Output: 3 19 | // Explanation: The answer is "wke", with the length of 3. 20 | // Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. 21 | 22 | 23 | // Constraints: 24 | 25 | // 0 <= s.length <= 5 * 104 26 | // s consists of English letters, digits, symbols and spaces. 27 | 28 | class Solution { 29 | public: 30 | int lengthOfLongestSubstring(string s) { 31 | map m; 32 | int temp=0, ans=INT_MIN,reset_i=0; 33 | for(int i=0;i1) 38 | { 39 | map :: iterator it; 40 | for(it=m.begin();it!=m.end();it++) 41 | it->second=0; 42 | temp--; 43 | i=reset_i++; 44 | ans = max(ans,temp); 45 | temp=0;} 46 | } 47 | return max(ans,temp); 48 | } 49 | }; -------------------------------------------------------------------------------- /Medium/Longest Substring Without Repeating Characters/solution.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Longest Substring Without Repeating Characters 3 | */ 4 | 5 | let lengthOfLongestSubstrings = (str) => { 6 | let subString = []; 7 | let length = 0; 8 | for (let i = 0; i < str.length; i++) { 9 | if (subString.includes(str[i])) 10 | subString.splice(0, subString.indexOf(str[i]) + 1); 11 | subString.push(str[i]); 12 | length = subString.length > length ? subString.length : length; 13 | } 14 | 15 | return length; 16 | }; 17 | 18 | let s = "abcdeeeeee"; 19 | 20 | let res = lengthOfLongestSubstring(s); 21 | console.log(res); // res: 5 22 | 23 | /** 24 | * Input: s = "abcdeeeeee" 25 | * Output: 5 26 | * Explanation: The answer is "abcde", with the length of 1. 27 | */ 28 | 29 | -------------------------------------------------------------------------------- /Medium/Longest Substring Without Repeating Characters/solution.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLongestSubstring(self, s: str) -> int: 3 | diary = {} 4 | start = 0 5 | res = 0 6 | 7 | for i,c in enumerate(s): 8 | if c in diary: 9 | start = max(start, diary[c]+1) 10 | 11 | diary[c] = i 12 | res = max(res, (i-start) + 1) 13 | 14 | return res 15 | -------------------------------------------------------------------------------- /Medium/Longest Uploaded Prefix/Longest-Uploaded-Prefix.cpp: -------------------------------------------------------------------------------- 1 | class LUPrefix { 2 | set s; 3 | int size; 4 | public: 5 | LUPrefix(int n) { 6 | size=n; 7 | // insert all unprocessed videos, initially all (1 to n) 8 | for(int i=1;i<=n;i++) 9 | s.insert(i); 10 | } 11 | 12 | void upload(int video) { 13 | // delete the uploaded video from set 14 | s.erase(video); 15 | } 16 | 17 | int longest() { 18 | // now, if set is empty, it means all videos are uploaded. hence answer = size 19 | if(s.empty()) 20 | return size; 21 | else{ 22 | // otherwise, ans = the minimum element in set minus 1 23 | // this is because all elements lesser than it are already processed 24 | int f = *s.begin(); 25 | return f-1; 26 | } 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Medium/Longest-Consecutive-sequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestConsecutive(vector& nums) { 4 | int ans = 0; 5 | sort(nums.begin(), nums.end()); 6 | unordered_map m; 7 | for(int i=0; i> &grid, int x, int y) 7 | { 8 | if (x < 0 || x >= m || y < 0 || y >= n || !grid[x][y]) 9 | return; 10 | grid[x][y] = 0; 11 | ++cur; 12 | dfs(grid, x + 1, y); 13 | dfs(grid, x - 1, y); 14 | dfs(grid, x, y + 1); 15 | dfs(grid, x, y - 1); 16 | } 17 | 18 | public: 19 | int maxAreaOfIsland(vector> &grid) 20 | { 21 | m = grid.size(), n = grid[0].size(); 22 | 23 | for (int i = 0; i < m; ++i) 24 | { 25 | for (int j = 0; j < n; ++j) 26 | { 27 | if (grid[i][j] == 1) 28 | { 29 | cur = 0; 30 | dfs(grid, i, j); 31 | mx = max(cur, mx); 32 | } 33 | } 34 | } 35 | 36 | return mx; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /Medium/MaxSubArraySum.java: -------------------------------------------------------------------------------- 1 | public class MaxSubArraySum { 2 | public static void main(String[] args) { 3 | int[] nums = {-2,1,-3,4,-1,2,1,-5,4}; 4 | System.out.println(maxSubArray(nums)); 5 | } 6 | 7 | static int maxSubArray(int[] nums) { 8 | //kadane's algorithm 9 | int max = nums[0]; 10 | int curr = 0; 11 | 12 | for (int num : nums) { 13 | 14 | curr += num; 15 | 16 | if(max < curr){ 17 | max = curr; 18 | } 19 | 20 | if(curr < 0){ 21 | curr = 0; 22 | } 23 | } 24 | 25 | return max; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Medium/Max_Bitwise_And.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 2419. Longest Subarray With Maximum Bitwise AND 3 | 4 | 5 | You are given an integer array nums of size n. 6 | 7 | Consider a non-empty subarray from nums that has the maximum possible bitwise AND. 8 | 9 | In other words, let k be the maximum value of the bitwise AND of any subarray of nums. Then, only subarrays with a bitwise AND equal to k should be considered. 10 | 11 | Return the length of the longest such subarray. 12 | 13 | The bitwise AND of an array is the bitwise AND of all the numbers in it. 14 | 15 | A subarray is a contiguous sequence of elements within an array. 16 | 17 | 18 | 19 | Example 1: 20 | 21 | Input: nums = [1,2,3,3,2,2] 22 | Output: 2 23 | Explanation: 24 | The maximum possible bitwise AND of a subarray is 3. 25 | The longest subarray with that value is [3,3], so we return 2. 26 | 27 | Example 2: 28 | 29 | Input: nums = [1,2,3,4] 30 | Output: 1 31 | Explanation: 32 | The maximum possible bitwise AND of a subarray is 4. 33 | The longest subarray with that value is [4], so we return 1. 34 | 35 | 36 | 37 | Constraints: 38 | 39 | 1 <= nums.length <= 10^5 40 | 1 <= nums[i] <= 10^6 41 | */ 42 | 43 | class Solution { 44 | public: 45 | 46 | int longestSubarray(vector &a) 47 | { 48 | int n = a.size(); 49 | int maxi = *max_element(a.begin(), a.end()); 50 | int cnt = 0; 51 | int ans = -1; 52 | for(int i = 0;i < n;i++){ 53 | if(a[i] == maxi){ 54 | cnt = 0; 55 | while(i < n and a[i] == maxi){ 56 | i++; 57 | cnt++; 58 | } 59 | ans = max(ans, cnt); 60 | } 61 | } 62 | return ans; 63 | } 64 | }; 65 | 66 | -------------------------------------------------------------------------------- /Medium/Maximal-square.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximalSquare(vector>& matrix) { 4 | 5 | int n = matrix.size() ; 6 | int m = matrix[0].size() ; 7 | int ans = 0 ; 8 | 9 | vector< vector >dp(n,vector(m,0)) ; 10 | for(int i=0 ;i>& grid) { 4 | int row = grid.size(); 5 | int col = grid[0].size(); 6 | int sum = 0, ans = INT_MIN; 7 | for(int i = 0; i < row-2; i++){ 8 | for(int j = 0; j < col-2; j++){ 9 | int sum = (grid[i][j]+grid[i][j+1]+grid[i][j+2])+ 10 | (grid[i+1][j+1])+ 11 | (grid[i+2][j]+grid[i+2][j+1]+grid[i+2][j+2]); 12 | ans = max(ans, sum); 13 | } 14 | } 15 | return ans; 16 | } 17 | }; -------------------------------------------------------------------------------- /Medium/Minimize XOR.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 2429. Minimize XOR 3 | 4 | Given two positive integers num1 and num2, find the integer x such that: 5 | 6 | x has the same number of set bits as num2, and 7 | The value x XOR num1 is minimal. 8 | 9 | Note that XOR is the bitwise XOR operation. 10 | 11 | Return the integer x. The test cases are generated such that x is uniquely determined. 12 | 13 | The number of set bits of an integer is the number of 1's in its binary representation. 14 | 15 | 16 | 17 | Example 1: 18 | 19 | Input: num1 = 3, num2 = 5 20 | Output: 3 21 | Explanation: 22 | The binary representations of num1 and num2 are 0011 and 0101, respectively. 23 | The integer 3 has the same number of set bits as num2, and the value 3 XOR 3 = 0 is minimal. 24 | 25 | Example 2: 26 | 27 | Input: num1 = 1, num2 = 12 28 | Output: 3 29 | Explanation: 30 | The binary representations of num1 and num2 are 0001 and 1100, respectively. 31 | The integer 3 has the same number of set bits as num2, and the value 3 XOR 1 = 2 is minimal. 32 | 33 | 34 | 35 | Constraints: 36 | 37 | 1 <= num1, num2 <= 10^9 38 | */ 39 | 40 | class Solution { 41 | public: 42 | int minimizeXor(int n1, int n2) { 43 | int cnt = 0; 44 | for(int i = 0;i < 32;i++){ 45 | if((n2 >> i) & 1){ 46 | cnt++; 47 | } 48 | } 49 | int ans = 0; 50 | for(int i = 31;i >= 0 and cnt > 0;i--){ 51 | if((n1 >> i) & 1){ 52 | cnt--; 53 | ans |= (1 << i); 54 | } 55 | } 56 | int i = 0; 57 | while(cnt > 0 and i < 32){ 58 | if(((n1 >> i) & 1) == 0){ 59 | cnt--; 60 | ans |= (1 << i); 61 | } 62 | i++; 63 | } 64 | return ans; 65 | } 66 | }; -------------------------------------------------------------------------------- /Medium/Minimum time to make Rope Colourful.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minCost(string colors, vector& neededTime) { 4 | int ans=0; 5 | int prev=neededTime[0]; 6 | bool fl=false; 7 | for(int i=1;i 2 | using namespace std; 3 | 4 | int mod=1e9+7; 5 | int minAbsoluteSumDiff(vector& nums1, vector& nums2) 6 | { 7 | int n=nums1.size(); 8 | vector diff(n); 9 | for(int i=0; i>n; 54 | 55 | vector nums1(n), nums2(n); 56 | for(int i=0; i>nums1[i]; 58 | for(int i=0; i>nums2[i]; 60 | 61 | cout<= 0; i--) { 6 | for(int j = n - 1; j >= 0; j--) { 7 | int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); 8 | int p1 = i + j, p2 = i + j + 1; 9 | int sum = mul + pos[p2]; 10 | 11 | pos[p1] += sum / 10; 12 | pos[p2] = (sum) % 10; 13 | } 14 | } 15 | 16 | StringBuilder sb = new StringBuilder(); 17 | for(int p : pos) if(!(sb.length() == 0 && p == 0)) sb.append(p); 18 | return sb.length() == 0 ? "0" : sb.toString(); 19 | } 20 | -------------------------------------------------------------------------------- /Medium/PeakIndexMountainArraySolution.java: -------------------------------------------------------------------------------- 1 | // Leetcode solution to problem #852 2 | // Medium 3 | 4 | // https://leetcode.com/problems/peak-index-in-a-mountain-array 5 | 6 | // code 7 | class PeakIndexMountainArraySolution { 8 | public int peakIndexInMountainArray(int[] arr) { 9 | int start =0; 10 | int end= arr.length -1; 11 | while(start< end){ 12 | int mid = start + (end-start)/2; 13 | if(arr[mid] arr[mid+1]){ 17 | end = mid; 18 | } 19 | } 20 | return start; 21 | } 22 | } -------------------------------------------------------------------------------- /Medium/Peakindex.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int peakIndexInMountainArray(vector& arr) { 4 | int l=0; 5 | int h=arr.size()-1; 6 | int m=l+(h-l)/2; 7 | while(lval]++; 7 | if(root->left){ 8 | dfs(root->left, path); 9 | } 10 | 11 | if(root->right){ 12 | dfs(root->right, path); 13 | } 14 | if(root->left==nullptr && root->right==nullptr){ 15 | int count=0; 16 | for(int i=1;i<=9;i++){ 17 | if(path[i]%2 != 0){ 18 | count++; 19 | } 20 | } 21 | if(count <= 1){ 22 | noOfPP++; 23 | } 24 | } 25 | path[root->val]--; 26 | } 27 | 28 | int pseudoPalindromicPaths (TreeNode* root) { 29 | int path[10] ={0}; 30 | dfs(root, path); 31 | return noOfPP; 32 | } 33 | }; -------------------------------------------------------------------------------- /Medium/Recovery-Binary-searchTree: -------------------------------------------------------------------------------- 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 | void recoverTree(TreeNode* root) { 15 | 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /Medium/Remove Duplicates from Sorted Array/Remove Nth Node From End of List.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | 13 | /* Problem description : 14 | Given the head of a linked list, remove the nth node from the end of the list and return its head. 15 | 16 | 17 | Input: head = [1,2,3,4,5], n = 2 18 | Output: [1,2,3,5] 19 | 20 | Input: head = [1,2], n = 1 21 | Output: [1] 22 | 23 | Constraints: 24 | 25 | The number of nodes in the list is sz. 26 | 1 <= sz <= 30 27 | 0 <= Node.val <= 100 28 | 1 <= n <= sz 29 | 30 | */ 31 | 32 | public ListNode removeNthFromEnd(ListNode head, int n) { 33 | if ((head == null) || (n==1 && head.next == null)) 34 | return null; 35 | int size = 0; 36 | ListNode temp = head; 37 | while(temp != null){ 38 | size++; 39 | temp = temp.next; 40 | } 41 | if(size == n) 42 | return head.next; 43 | int sn = size-n; 44 | int i = 0; 45 | temp = head; 46 | while(i < sn-1){ 47 | temp = temp.next; 48 | i++; 49 | } 50 | temp.next = temp.next.next; 51 | return head; 52 | } 53 | } -------------------------------------------------------------------------------- /Medium/Remove Duplicates from Sorted Array/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeDuplicates(vector& nums) { 4 | int j=0;; 5 | for(int i=1;inext;//Move fast pointer n steps ahead 34 | if (!fast) return head->next;//If fast pointer reaches the end, remove the head 35 | while (fast->next) fast = fast->next, slow = slow->next;//Move both pointers until fast reaches the end 36 | slow->next = slow->next->next;//Remove the nth node from the end 37 | return head;//Return the head 38 | } 39 | }; -------------------------------------------------------------------------------- /Medium/Remove_Duplicates.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void remove_duplicates(int*arr,int*n){ 4 | int i=0; 5 | while(i<(*n)-1){ 6 | if(arr[i]==arr[i+1]){ 7 | for(int j=i+1;j<(*n)-1;j++){ 8 | arr[j]=arr[j+1]; 9 | } 10 | *n=*n-1; 11 | } 12 | else{ 13 | i++; 14 | } 15 | } 16 | } 17 | void display(int*arr,int n){ 18 | for(int i=0;i>n; 25 | int*arr=new int[n]; 26 | for(int i=0;i>arr[i]; 28 | } 29 | 30 | remove_duplicates(arr,&n); 31 | 32 | display(arr,n); 33 | return 0; 34 | } -------------------------------------------------------------------------------- /Medium/RotateArraySolution.java: -------------------------------------------------------------------------------- 1 | // Leetcode solution to problem #189 Rotate Array 2 | // Medium 3 | 4 | // https://leetcode.com/problems/rotate-array/ 5 | 6 | // code 7 | class RotateArraySolution { 8 | public void rotate(int[] nums, int k) { 9 | if(nums.length <= k){ 10 | k = k%nums.length; 11 | } 12 | int i = 0; 13 | int j= nums.length -1; 14 | 15 | while(i Optional[ListNode]: 3 | if head==None: 4 | return None 5 | if head.next==None: 6 | return head 7 | c=0 8 | t=head 9 | while t: 10 | c+=1 11 | t=t.next 12 | k=k%c 13 | while k>0: 14 | p=head 15 | t=head 16 | while head.next.next!=None: 17 | head=head.next 18 | l=head.next 19 | head.next=None 20 | l.next=p 21 | head=l 22 | k-=1 23 | return head 24 | -------------------------------------------------------------------------------- /Medium/RotatedBSDuplicates.java: -------------------------------------------------------------------------------- 1 | public class RotatedBSDuplicates { 2 | public static void main(String[] args) { 3 | int[] nums = {4,5,6,7,0,1,2}; 4 | int target = 0; 5 | System.out.println(search(nums, target)); 6 | } 7 | 8 | static boolean search(int[] nums, int target) { 9 | int s = 0; 10 | int e = nums.length-1; 11 | 12 | while(s <= e){ 13 | 14 | while(s < e && nums[s] == nums[s+1]){ 15 | s++; 16 | } 17 | while (s < e && nums[e] == nums[e-1]){ 18 | e--; 19 | } 20 | //after this the array will not have any duplicates 21 | 22 | int m = s + (e-s)/2; 23 | 24 | if(nums[m] == target){ 25 | return true; 26 | } 27 | 28 | if(nums[m] >= nums[s]){ 29 | if(target < nums[m] && target >= nums[s]){ 30 | e = m-1; 31 | } else{ 32 | s = m+1; 33 | } 34 | } else{ 35 | if(target > nums[m] && target <= nums[e]){ 36 | s = m+1; 37 | } else{ 38 | e = m-1; 39 | } 40 | } 41 | } 42 | return false; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Medium/Search a 2D Matrix II/Search2DMatrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool searchMatrix(vector>& mat, int target) { 4 | 5 | int m = mat.size(); 6 | int n = mat[0].size(); 7 | 8 | int i = m - 1; 9 | int j = 0; 10 | 11 | while (i>=0 && j= arr[0]){ 16 | return binarySearch(arr,0,pivot-1,target); 17 | } 18 | return binarySearch(arr,pivot+1,arr.length -1,target); 19 | } 20 | static int findPivot(int[] arr){ 21 | int start = 0; 22 | int end = arr.length - 1; 23 | while (start <= end) { 24 | int mid = start + (end - start) / 2; 25 | if (mid < end && arr[mid] > arr[mid + 1]) { 26 | return mid; 27 | } 28 | if (mid > start && arr[mid] < arr[mid - 1]) { 29 | return mid-1; 30 | } 31 | if (arr[mid] <= arr[start]) { 32 | end = mid - 1; 33 | } else { 34 | start = mid + 1; 35 | } 36 | } 37 | return -1; 38 | } 39 | static int binarySearch(int[] arr, int start, int end, int target){ 40 | while(start<=end){ 41 | int mid = start + (end-start)/2; 42 | if(arr[mid] < target){ 43 | start = mid + 1; 44 | } 45 | else if(arr[mid] > target){ 46 | end = mid - 1; 47 | } 48 | else{ 49 | return mid; 50 | } 51 | } 52 | return -1; 53 | } 54 | } -------------------------------------------------------------------------------- /Medium/Search_in_rotated_SortedArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int search(vector& nums, int target) { 4 | int n=nums.size(); 5 | int i=0,j=n-1,mid; 6 | while(inums[j]) 10 | { 11 | i=mid+1; 12 | } 13 | else{ 14 | j=mid; 15 | } 16 | } 17 | int peak=i; 18 | if(target>=nums[peak] && target<=nums[n-1]) 19 | { 20 | i=peak,j=n-1; 21 | } 22 | else{ 23 | i=0,j=peak-1; 24 | } 25 | while(i<=j) 26 | { 27 | mid=i+(j-i)/2; 28 | if(nums[mid]==target) 29 | { 30 | return mid; 31 | } 32 | else if(nums[mid]= 0) 16 | matrix[d--][col] = -1; 17 | 18 | // down row 19 | d = row + 1; 20 | while (d < n) 21 | matrix[d++][col] = -1; 22 | 23 | // left col 24 | d = col - 1; 25 | while (d >= 0) 26 | matrix[row][d--] = -1; 27 | 28 | //right col 29 | d = col + 1; 30 | while (d < m) 31 | matrix[row][d++] = -1; 32 | } 33 | } 34 | } 35 | 36 | for (int row = 0; row < n; row++) { 37 | for (int col = 0; col < m; col++) { 38 | if (matrix[row][col] == -1) { 39 | matrix[row][col] = 0; 40 | } 41 | } 42 | } 43 | } 44 | 45 | private static void printMatrix(int[][] matrix){ 46 | 47 | for (int[] mat : matrix) { 48 | for (int m_a : mat) 49 | System.out.print(m_a + " "); 50 | System.out.println(" "); 51 | } 52 | } 53 | 54 | public static void main(String[] args) { 55 | 56 | int[][] matrix = {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}}; 57 | 58 | System.out.println("Before Set Zero"); 59 | printMatrix(matrix); 60 | 61 | setMatrix(matrix); 62 | 63 | System.out.println("====================="); 64 | 65 | System.out.println("After Zero"); 66 | printMatrix(matrix); 67 | } 68 | } -------------------------------------------------------------------------------- /Medium/ShipCapacity.java: -------------------------------------------------------------------------------- 1 | public class ShipCapacity { 2 | public static void main(String[] args) { 3 | int[] weights = {1,2,3,4,5,6,7,8,9,10}; 4 | System.out.println( shipWithinDays(weights, 5)); 5 | } 6 | 7 | static int shipWithinDays(int[] weights, int days) { 8 | int s = weights[0]; 9 | int e = 0; 10 | 11 | for(int weight: weights){ 12 | s = Math.max(s, weight); 13 | e += weight; 14 | } 15 | 16 | while (s < e) { 17 | 18 | int m = s + (e-s)/2; 19 | 20 | if( canShipWithMinWeight(weights, m, days) ){ 21 | e = m; 22 | } else{ 23 | s = m+1; 24 | } 25 | } 26 | return s; 27 | } 28 | 29 | static boolean canShipWithMinWeight(int[] weights, int allowedWeight, int days) { 30 | int daysNeeded = 1; 31 | int sum = 0; 32 | 33 | for(int weight : weights){ 34 | if(sum + weight <= allowedWeight){ 35 | sum += weight; 36 | } else{ 37 | sum = weight; 38 | daysNeeded++; 39 | } 40 | } 41 | return daysNeeded <= days; 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /Medium/Simplify_Path.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String simplifyPath(String path) { 3 | Queue dirs = new LinkedList<>(); 4 | Stack paths = new Stack<>(); 5 | String simplified = ""; 6 | String dir = ""; 7 | for(int i=0; i 0) { 10 | dirs.add(new String(dir)); 11 | } 12 | dir = ""; 13 | continue; 14 | } 15 | 16 | dir = dir + String.valueOf(path.charAt(i)); 17 | } 18 | 19 | if(dir.length() > 0) { 20 | dirs.add(dir); 21 | } 22 | 23 | while(!dirs.isEmpty()) { 24 | dir = dirs.remove(); 25 | if(dir.equals(".")) { 26 | continue; 27 | }else if(dir.equals("..")) { 28 | if(!paths.empty()) { 29 | paths.pop(); 30 | } 31 | }else { 32 | paths.push(dir); 33 | } 34 | } 35 | 36 | while(!paths.empty()) { 37 | dir = paths.pop(); 38 | if(dir.equals(".")) { 39 | continue; 40 | }else if(dir.equals("..")) { 41 | if(!paths.empty()) 42 | paths.pop(); 43 | continue; 44 | } 45 | if(simplified.equals("")) { 46 | simplified = dir; 47 | } 48 | else { 49 | simplified = dir + "/" + simplified; 50 | } 51 | } 52 | 53 | simplified = "/"+simplified; 54 | 55 | return simplified; 56 | 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Medium/SolutionForSpiralMatrix_54_leetcode.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ArrayList spiralOrder(int[][] matrix) { 3 | ArrayList result = new ArrayList(); 4 | 5 | if(matrix == null || matrix.length == 0) return result; 6 | 7 | int m = matrix.length; 8 | int n = matrix[0].length; 9 | 10 | int x=0; 11 | int y=0; 12 | 13 | while(m>0 && n>0){ 14 | 15 | //if one row/column left, no circle can be formed 16 | if(m==1){ 17 | for(int i=0; i spiralOrder(vector>& matrix) { 4 | if (matrix.size() == 0) return {}; 5 | int n = matrix.size(); 6 | int m = matrix[0].size(); 7 | int top = 0, bottom = n - 1, left = 0, right = m - 1; 8 | vector ans; 9 | 10 | while (ans.size() < n*m) { 11 | for (int i = left; i <= right && ans.size() < n*m ; i++) { 12 | ans.push_back(matrix[top][i]); 13 | } 14 | 15 | top++; 16 | 17 | for (int i = top; i <= bottom && ans.size() < n*m; i++) { 18 | ans.push_back(matrix[i][right]); 19 | } 20 | 21 | right--; 22 | 23 | for (int i = right; i >= left && ans.size() < n*m ; i--) { 24 | ans.push_back(matrix[bottom][i]); 25 | } 26 | 27 | bottom--; 28 | 29 | for (int i = bottom; i >= top && ans.size() < n*m; i--) { 30 | ans.push_back(matrix[i][left]); 31 | } 32 | left++; 33 | } 34 | return ans; 35 | } 36 | 37 | }; -------------------------------------------------------------------------------- /Medium/Spiral_Matrix.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | //Problem Statement 5 | //Given an m x n matrix, return all elements of the matrix in spiral order. 6 | // Input: matrix =[ [1,2,3] 7 | // [4,5,6] 8 | // [7,8,9] ] 9 | // Output: [1,2,3,6,9,8,7,4,5] 10 | 11 | //Solution 12 | class Solution { 13 | public List spiralOrder(int[][] matrix) { 14 | 15 | int r = matrix.length; 16 | int c = matrix[0].length; 17 | int startrow = 0; 18 | int startcol = 0; 19 | int endrow = r-1; 20 | int endcol = c-1; 21 | int totallen = r*c; 22 | int count = 0; 23 | 24 | ArrayList al = new ArrayList<>(); 25 | 26 | while(count=startcol; i--) { 41 | al.add(matrix[endrow][i]); 42 | count++; 43 | } 44 | endrow--; 45 | 46 | for(int i=endrow; count=startrow; i--) { 47 | al.add(matrix[i][startcol]); 48 | count++; 49 | } 50 | startcol++; 51 | } 52 | return al; 53 | } 54 | 55 | } -------------------------------------------------------------------------------- /Medium/Subarray Sum Equals K.cpp: -------------------------------------------------------------------------------- 1 | //Subarray Sum Equals K 2 | 3 | // Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. 4 | 5 | // A subarray is a contiguous non-empty sequence of elements within an array. 6 | 7 | 8 | 9 | // Example 1: 10 | 11 | // Input: nums = [1,1,1], k = 2 12 | // Output: 2 13 | // Example 2: 14 | 15 | // Input: nums = [1,2,3], k = 3 16 | // Output: 2 17 | 18 | 19 | // Constraints: 20 | 21 | // 1 <= nums.length <= 2 * 104 22 | // -1000 <= nums[i] <= 1000 23 | // -107 <= k <= 107 24 | 25 | //Solution... 26 | class Solution { 27 | public: 28 | int subarraySum(vector& nums, int k) { 29 | unordered_map mp; 30 | int sum=0,ans=0; 31 | mp[sum] = 1; 32 | for(auto it:nums){ 33 | sum += it; 34 | int find = sum - k; 35 | if(mp.find(find) != mp.end()){ 36 | ans += mp[find]; 37 | } 38 | mp[sum]++; 39 | } 40 | return ans; 41 | } 42 | }; -------------------------------------------------------------------------------- /Medium/Subsets: -------------------------------------------------------------------------------- 1 | 78. Subsets 2 | https://leetcode.com/problems/subsets/ 3 | 4 | 5 | 6 | class Solution: 7 | def subsets(self, nums: List[int]) -> List[List[int]]: 8 | 9 | #recursion apporch 10 | def helper(p , up , ans): 11 | if up == []: 12 | p = p[:-1] 13 | ans.append(p.split(" ")) 14 | return 15 | 16 | 17 | helper(p+str(up[0])+" " , up[1:] , ans) 18 | helper(p , up[1:] , ans) 19 | return ans 20 | 21 | return helper("" , nums , []) 22 | 23 | 24 | #itrative apporch 25 | arr = [[]] 26 | for i in nums: 27 | for j in range(len(arr)): 28 | newItem = arr[j][:] 29 | newItem.append(i) 30 | arr.append(newItem) 31 | return arr 32 | 33 | 34 | -------------------------------------------------------------------------------- /Medium/Subsets II/M#1(Recursion CPP): -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void solve(vectorinput,vectoroutput,set> &ans){ 4 | //base-case 5 | if(input.size()==0){ 6 | ans.insert(output); 7 | return; 8 | } 9 | //recursive call 10 | int x=input[0]; 11 | input.erase(input.begin()+0); 12 | solve(input,output,ans); 13 | output.push_back(x); 14 | solve(input,output,ans); 15 | } 16 | vector> subsetsWithDup(vector& nums) { 17 | vectoroutput;set>ans;sort(nums.begin(),nums.end()); 18 | solve(nums,output,ans); 19 | vector>ans1; 20 | for(auto i:ans){ 21 | ans1.push_back(i); 22 | } 23 | return ans1; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Medium/Sum_Closest.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int threeSumClosest(int[] num, int target) { 3 | int min = Integer.MAX_VALUE; 4 | int result = 0; 5 | Arrays.sort(num); 6 | for (int i = 0; i < num.length; i++) { 7 | int j = i + 1; 8 | int k = num.length - 1; 9 | while (j < k) { 10 | int sum = num[i] + num[j] + num[k]; 11 | int diff = Math.abs(sum - target); 12 | if (diff == 0) 13 | return 0; 14 | if (diff < min) { 15 | min = diff; 16 | result = sum; 17 | } 18 | if (sum <= target) { 19 | j++; 20 | } else { 21 | k--; 22 | } 23 | } 24 | } 25 | return result; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Medium/Sum_of_two_integers.cpp: -------------------------------------------------------------------------------- 1 | //Problem Link - https://leetcode.com/problems/sum-of-two-integers/ 2 | /* 3 | Given two integers a and b, return the sum of the two integers without using the operators + and -. 4 | 5 | Example 1: 6 | Input: a = 1, b = 2 7 | Output: 3 8 | 9 | Example 2: 10 | Input: a = 2, b = 3 11 | Output: 5 12 | 13 | Constraints: 14 | -1000 <= a, b <= 1000 15 | 16 | */ 17 | 18 | // Time-Complexity:- -> O(1) constant as 32 is the number of bits at most we will have to bit shift until carry is zero. 19 | // Space-Complexity:- O(1) 20 | 21 | 22 | class Solution { 23 | public: 24 | int getSum(int a, int b) { 25 | if(a==0 || b==0){ 26 | return a^b; 27 | } 28 | return getSum(a^b , (unsigned(a&b) <<1)); 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /Medium/Swap Nodes In Pairs.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode swapPairs(ListNode head) { 13 | 14 | if(head == null || head.next == null) //If zeo or 1 node in linked list 15 | return head; 16 | 17 | ListNode remaining = head.next.next; //3rd node stored 18 | 19 | ListNode newHead = head.next; //after swapping 2nd head is the head node 20 | 21 | head.next.next = head; //2nd node connected to 1st one 22 | 23 | head.next = swapPairs(remaining); 24 | 25 | return newHead; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Medium/ThreeSum.swift: -------------------------------------------------------------------------------- 1 | class ThreeSum { 2 | func threeSum(_ nums: [Int]) -> [[Int]] { 3 | 4 | var result: [[Int]] = [] 5 | let nums = nums.sorted() 6 | let len = nums.count 7 | 8 | guard len >= 3 else { return result } 9 | 10 | for i in 0.. 0 && nums[i] == nums[i-1] { continue } 12 | 13 | let num = 0 - nums[i] 14 | var a = i + 1, b = len - 1 15 | 16 | while a < b { 17 | let numA = nums[a], numB = nums[b] 18 | let sum = numA + numB 19 | if sum == num { 20 | result.append([nums[i], numA, numB]) 21 | a += 1 22 | b -= 1 23 | while a < b && nums[a] == nums[a-1] { a += 1 } 24 | while a < b && nums[b] == nums[b+1] { b -= 1 } 25 | } else { 26 | sum > num ? b -= 1 : (a += 1) 27 | } 28 | } 29 | } 30 | return result 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Medium/Triangle.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | public class Triangle { 3 | 4 | /** 5 | * Given a triangle array, return the minimum path sum from top to bottom. 6 | * Time Complexity: O(n ^ 2), where n is the number of rows of the triangle. 7 | * Space Complexity: O(1). 8 | * 9 | * @param triangle A list of lists of integers from an triangle array. 10 | * @return An integer of the minimal path sum from top to bottom of the given triangle array. 11 | */ 12 | public int getMinimumTotalWithBottomUpDynamicProgrammingV2(List> triangle) { 13 | for (int i = triangle.size() - 2; i >= 0; i--) { 14 | for (int j = 0; j < triangle.get(i).size(); j++) { 15 | triangle.get(i).set(j, triangle.get(i).get(j) + Math.min( 16 | triangle.get(i + 1).get(j), 17 | triangle.get(i + 1).get(j + 1) 18 | )); 19 | } 20 | } 21 | return triangle.get(0).get(0); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Medium/Ugly_number_2.cpp: -------------------------------------------------------------------------------- 1 | // Leetcode problem 264-Ugly Number II 2 | // DP problem 3 | // Cpp solution 4 | 5 | /* We have an array k of the first n ugly number. We only know, in the beginning, the first one, which is 1. Then 6 | 7 | k[1] = min( k[0]x2, k[0]x3, k[0]x5). The answer is k[0]x2. So we move 2's pointer to 1. Then we test: 8 | 9 | k[2] = min( k[1]x2, k[0]x3, k[0]x5). And so on. Be careful about the cases such as 6, in which we need to forward both pointers of 2 and 3, so no else if, onlyif. 10 | 11 | x here is multiplication.*/ 12 | 13 | class Solution { 14 | public: 15 | int nthUglyNumber(int n) { 16 | vectordp(n); 17 | dp[0]=1; 18 | // three-pointer approach 19 | int p3=0,p2=0,p5=0; 20 | for(int i =1;i0){ 44 | up += dp[r-1][c]; 45 | } 46 | if(c>0){ 47 | down += dp[r][c-1]; 48 | } 49 | dp[r][c] = up + down; 50 | } 51 | } 52 | } 53 | return dp[m-1][n-1]; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Medium/Unique_paths.cpp: -------------------------------------------------------------------------------- 1 | /* Leetcode Problem: 62. Unique Paths 2 | Link: https://leetcode.com/problems/unique-paths/ 3 | */ 4 | 5 | class Solution { 6 | public: 7 | 8 | int helper(int row, int col, vector> &dp) 9 | { 10 | if(row < 0 || col < 0) 11 | return 0; 12 | if(row == 0 && col == 0) 13 | return 1; 14 | 15 | if(dp[row][col] != -1) 16 | return dp[row][col]; 17 | 18 | int l = helper(row, col-1, dp); 19 | int u = helper(row-1, col, dp); 20 | 21 | return dp[row][col] = l + u; 22 | } 23 | 24 | 25 | 26 | int uniquePaths(int m, int n) { 27 | vector> dp(m, vector(n,0)); 28 | 29 | for(int i=0; i left != NULL) { 27 | // Find the inorder predecessor of current 28 | TreeNode* pre = curr -> left; 29 | while(pre -> right != NULL) { 30 | pre = pre -> right; 31 | } 32 | // Link predecessor -> right to curr -> right 33 | pre -> right = curr -> right; 34 | // Link curr -> right to curr -> left 35 | curr-> right = curr -> left; 36 | // Remove link for curr -> left 37 | curr-> left = NULL; 38 | 39 | } 40 | curr = curr -> right; 41 | } 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /Medium/good_pair.cpp: -------------------------------------------------------------------------------- 1 | // Code By Romijul Laskar 2 | #include 3 | #define ll long long 4 | using namespace std; 5 | int main(void) 6 | { 7 | ll t; 8 | cin >> t; 9 | while (t--) 10 | { 11 | ll n;cin >> n;vector vec1(n), vec2(n);ll res = 0; 12 | for (ll &r : vec1){cin >> r;} 13 | for (ll &r : vec2){cin >> r;} 14 | map, ll> cyc; 15 | for (ll i = 0; i < n; i++){res += cyc[{vec1[i], vec2[i]}];cyc[{vec2[i], vec1[i]}]++;} 16 | cout << res << '\n'; 17 | } 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /Medium/min_in_sorted_rotated_sorted_array.py: -------------------------------------------------------------------------------- 1 | #link for question :-https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ 2 | 3 | class Solution: 4 | def findMin(self, nums: List[int]) -> int: 5 | n=len(nums)-1 6 | if(nums[0] 2 | using namespace std; 3 | void nextPermutation(vector& nums) { 4 | int n = nums.size(), k, l; 5 | for (k = n - 2; k >= 0; k--) { 6 | if (nums[k] < nums[k + 1]) { 7 | break; 8 | } 9 | } 10 | if (k < 0) { 11 | reverse(nums.begin(), nums.end()); 12 | } else { 13 | for (l = n - 1; l > k; l--) { 14 | if (nums[l] > nums[k]) { 15 | break; 16 | } 17 | } 18 | swap(nums[k], nums[l]); 19 | reverse(nums.begin() + k + 1, nums.end()); 20 | } 21 | } 22 | 23 | int main() { 24 | vector nums = {1,2,3}; 25 | 26 | nextPermutation(nums);//using in-built function of C++ 27 | 28 | cout< int: 3 | memo = {} 4 | def recursive(n: int, k: int, target: int) -> int: 5 | if (target, n) in memo: 6 | return memo[(target, n)] 7 | if target == 0 and n == 0: 8 | return 1 9 | elif target < 0 or n <= 0: 10 | return 0 11 | else: 12 | result = 0 13 | for face in range(1, k + 1): 14 | result += recursive(n - 1, k, target - face) 15 | memo[(target, n)] = result 16 | return result 17 | return recursive(n, k , target) % (10**9 + 7) 18 | 19 | #https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/ 20 | -------------------------------------------------------------------------------- /Medium/pattern.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool find132pattern(vector& nums) { 4 | int ak = numeric_limits::min(); 5 | stack st; 6 | for (int i = nums.size() - 1; i >= 0; --i) { 7 | if (nums[i] < ak) { 8 | return true; 9 | } else { 10 | while (!st.empty() && nums[i] > st.top()) { 11 | ak = st.top(), st.pop(); 12 | } 13 | } 14 | st.emplace(nums[i]); 15 | } 16 | return false; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Medium/powXN.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public double myPow(double x, int n) { 3 | 4 | if(x==0){ 5 | return 0; 6 | } 7 | if(n==0){ 8 | return 1; 9 | } 10 | if(n<0){ 11 | n = Math.abs(n); 12 | return 1/(x* myPow(x,n-1)); 13 | } 14 | double partialAns = myPow(x, n/2); 15 | double ans = partialAns*partialAns; 16 | if(n%2 != 0) 17 | return ans*x; 18 | 19 | return ans; 20 | } 21 | } -------------------------------------------------------------------------------- /Medium/setMatrixZeroes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void setZeroes(vector < vector < int >> & matrix) { 4 | int col0 = 1, rows = matrix.size(), cols = matrix[0].size(); 5 | for (int i = 0; i < rows; i++) { 6 | 7 | if (matrix[i][0] == 0) col0 = 0; 8 | for (int j = 1; j < cols; j++) { 9 | if (matrix[i][j] == 0) { 10 | matrix[i][0] = 0; 11 | matrix[0][j] = 0; 12 | } 13 | } 14 | } 15 | 16 | for (int i = rows - 1; i >= 0; i--) { 17 | for (int j = cols - 1; j >= 1; j--) { 18 | if (matrix[i][0] == 0 || matrix[0][j] == 0) { 19 | matrix[i][j] = 0; 20 | } 21 | } 22 | if (col0 == 0) { 23 | matrix[i][0] = 0; 24 | } 25 | 26 | } 27 | 28 | } 29 | 30 | int main() { 31 | vector < vector < int >> arr; 32 | arr = {{0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5}}; 33 | setZeroes(arr); 34 | cout<<"The Final Matrix is "<& chars) { 11 | int n = chars.size(); 12 | int ansIndex = 0; 13 | int i = 0; 14 | 15 | while(i < n) { 16 | int j = i+1; 17 | // If adjacent elements are same, increment count of that element 18 | while(j < n && chars[i] == chars[j]) { 19 | j++; 20 | } 21 | 22 | /* 23 | Will reach at this point if traversed whole char vector 24 | or if encounter a new/different character 25 | */ 26 | 27 | // Storing old character in modified chars array 28 | chars[ansIndex++] = chars[i]; 29 | 30 | // Gives count of a particular character 31 | int count = j-i; 32 | 33 | // If count > 1, converting count into single 34 | // digit and saving in modified chars array 35 | if(count > 1) { 36 | string cnt = to_string(count); 37 | for(char ch : cnt) { 38 | chars[ansIndex++] = ch; 39 | } 40 | } 41 | 42 | // Making i = j for counting next new/different character 43 | i = j; 44 | } 45 | 46 | // ansIndex store length of modified chars array 47 | return ansIndex; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /Medium/subsets.CPP: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> res; 4 | 5 | vector> subsets(vector& nums) { 6 | solve(nums, 0, {}); 7 | return res; 8 | } 9 | 10 | void solve(vector& nums, int i, vector cur) { 11 | if (i == nums.size()) { 12 | res.push_back(cur); 13 | return; 14 | } 15 | solve(nums, i+1, cur); 16 | cur.push_back(nums[i]); 17 | solve(nums, i+1, cur); 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Medium/sum.cpp: -------------------------------------------------------------------------------- 1 | define ll long long 2 | class Solution { 3 | public: 4 | vector> threeSum(vector& nums) { 5 | vector>ans; 6 | int n=nums.size(); 7 | sort(nums.begin(),nums.end()); 8 | 9 | int l,r; 10 | for(int i=0;i=1 and nums[i-1]==nums[i]){ 12 | continue; 13 | } 14 | 15 | l=i+1,r=n-1; 16 | while(l> zigzagLevelOrder(TreeNode* root) { 7 | vector> ans; 8 | if(root==NULL) 9 | return ans; 10 | queue q; 11 | q.push(root); 12 | bool lefttoright=true; 13 | while(!q.empty()){ 14 | int size=q.size(); 15 | vector row(size); 16 | for(int i=0;ival; 21 | if(node->left) q.push(node->left); 22 | if(node->right) q.push(node->right); 23 | } 24 | lefttoright=!lefttoright; 25 | ans.push_back(row); 26 | } 27 | return ans; 28 | } 29 | }; -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

LEETCODE

2 |

Description

3 | I have created a repository named "LEETCODE", it has 3 folders, and all these folders contains level wise question 4 | 5 |
6 |
7 | 8 | * Easy 9 | * Medium 10 | * Hard 11 | 12 |
13 |
14 |
15 | 16 | ![Hactoberfest](Hacktoberfest2022.png) 17 | 18 |
19 |
20 |
21 | 22 | # Must read [Contribution](CONTRIBUTING.md) file 23 | 24 |
25 |
26 |
27 | 28 | # Have a look this amazing repository 29 | ### [eBOOKS](https://github.com/Vanshika2063/eBOOKS) 30 | 31 |
32 |
33 |
34 | 35 | # Let's connect with each other 36 | ### Check out Our [Discussion](https://github.com/Vanshika2063/Leetcode-Questions/discussions) 37 | 38 |
39 |
40 |
41 | 42 | # Please share it on social media and tag me on twitter 43 | 44 |

Here is my Twitter Account

45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /twitter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vanshika2063/Leetcode-Questions/6ac1ef53044340cec9592fb4eab47d80f5440f31/twitter.png --------------------------------------------------------------------------------