├── Step 01 - Basics ├── Step 1.3 Basic Maths │ ├── GCD.java │ ├── Count_Digits.java │ ├── Check_prime.java │ ├── Reverse_number.java │ ├── LCM.java │ ├── Check_palindrome.java │ ├── Print_all_divisior.java │ └── Armstrong_number.java ├── Step 1.4 Basic Recursion │ ├── Fibonacci Number.java │ └── Print 1 to N using recursion.java └── Step 1.5 Basic Hashing │ ├── Frequencies of Limited Range Array Elements.java │ └── Frequency of the Most Frequent Element.java ├── Step 03 Arrays ├── Step 3.1 Easy │ ├── GeeksForGeeks │ │ ├── Linear Search.java │ │ ├── Check if array is sorted.java │ │ ├── Largest Element in Array.java │ │ ├── Missing number.java │ │ ├── Remove duplicate elements from sorted Array.java │ │ ├── Maximize Number of 1's.java │ │ ├── Move all zeroes to end of array.java │ │ ├── Row with max 1s.java │ │ ├── Second Largest element.java │ │ ├── Second Smallest Element.java │ │ ├── Longest Sub-Array with Sum K.java │ │ ├── Intersection of two sorted array.java │ │ ├── Search in a matrix.java │ │ ├── Union of two sorted array.java │ │ ├── Find the element that appears once.java │ │ ├── Quick Left Rotation.java │ │ └── Rotating an Array.java │ └── LeetCode │ │ ├── Remove Duplicates from Sorted Array.java │ │ ├── Check if Array Is Sorted and Rotated.java │ │ ├── Missing Number.java │ │ ├── Move Zeroes.java │ │ ├── Max Consecutive Ones.java │ │ ├── Rotate Array.java │ │ ├── Subarray Sum Equals K.java │ │ └── Search a 2D Matrix.java ├── Step 3.2 Medium │ ├── GeeksForGeeks │ │ ├── Max sum in sub-arrays.java │ │ ├── Kadane's Algorithm.java │ │ ├── Leaders in an array.java │ │ ├── Longest consecutive subsequence.java │ │ ├── Majority Element.java │ │ ├── Sort an array of 0s, 1s and 2s.java │ │ ├── Rotate by 90 degree.java │ │ ├── Alternate positive and negative numbers.java │ │ └── Stock buy and sell.java │ └── LeetCode │ │ ├── Maximum Subarray.java │ │ ├── Majority Element.java │ │ ├── Two Sum.java │ │ ├── Rearrange Array Elements by Sign.java │ │ ├── Sort Colors.java │ │ ├── Best Time to Buy and Sell Stock.java │ │ ├── Longest Consecutive Sequence.java │ │ ├── Rotate Image.java │ │ ├── Set Matrix Zeroes.java │ │ ├── Spiral Matrix.java │ │ └── Next Permutation.java └── Step 3.3 Hard │ ├── LeetCode │ ├── Merge Sorted Array.java │ ├── Maximum Product Subarray.java │ ├── Merge Intervals.java │ └── Pascal's Triangle.java │ └── GeeksForGeeks │ ├── Largest subarray with 0 sum.java │ ├── Pascal Triangle.java │ ├── 3 sum closest.java │ ├── Subsets with XOR value.java │ ├── Maximum Product Subarray.java │ ├── Merge Without Extra Space.java │ ├── Find Missing And Repeating.java │ └── Pairwise swap elements of a linked list.java ├── Step 04 Binary Search ├── Step 4.3 Find Answers by BS in Search Space │ ├── GeeksForGeeks │ │ ├── Square root of a number.java │ │ ├── K-th missing element.java │ │ ├── Largest Sum Subarray of Size at least K.java │ │ ├── Median of 2 Sorted Arrays of Different Sizes.java │ │ ├── Find Nth root of M.java │ │ └── Capacity To Ship Packages Within D Days.java │ └── LeetCode │ │ ├── Kth Missing Positive Number.java │ │ ├── Capacity To Ship Packages Within D Days.java │ │ ├── Koko Eating Bananas.java │ │ ├── Find the Smallest Divisor Given a Threshold.java │ │ └── Split Array Largest Sum.java ├── Step 4.1 Learning BS on 1D Array │ ├── LeetCode │ │ ├── Find Peak Element.java │ │ ├── Find Minimum in Rotated Sorted Array.java │ │ ├── Binary Search.java │ │ ├── Search Insert Position.java │ │ ├── Search in Rotated Sorted Array.java │ │ ├── Single Element in a Sorted Array.java │ │ ├── Search in Rotated Sorted Array II.java │ │ └── Find First and Last Position of Element in Sorted Array.java │ └── GeeksForGeeks │ │ ├── Binary Search.java │ │ ├── Peak element.java │ │ ├── Floor in a Sorted Array.java │ │ ├── Ceil The Floor.java │ │ ├── Minimum element in a sorted and rotated array.java │ │ ├── Search insert position of K in a sorted array.java │ │ ├── Find out how many times has an array been rotated.java │ │ ├── Search in a Rotated Array.java │ │ └── First and last occurrences of x.java └── Step 4.2 Applying BS on 2D Array │ ├── GeeksForGeeks │ ├── Search in a matrix.java │ ├── Median in a row-wise sorted Matrix.java │ └── Peak element.java │ └── LeetCode │ ├── Find a Peak Element II.java │ └── Search a 2D Matrix.java ├── Step 08 Bit Manipulation ├── Step 8.1 Learn Bit Manipulation │ ├── GeeksForGeeks │ │ ├── Odd or Even.java │ │ ├── Swap two numbers.java │ │ ├── Power of 2.java │ │ ├── Set the rightmost unset bit.java │ │ ├── Check whether K-th bit is set or not.java │ │ ├── Count total set bits.java │ │ └── Division without using multiplication, division and mod operator.java │ └── Leetcode │ │ ├── Power of Two.java │ │ └── Divide Two Integers.java ├── Step 8.2 Interview Problems │ ├── Leetcode │ │ ├── Single Number.java │ │ ├── Minimum Bit Flips to Convert Number.java │ │ └── Subsets.java │ └── GeeksForGeeks │ │ ├── Exceptionally odd.java │ │ ├── Bit Difference.java │ │ ├── Power Set.java │ │ └── Two numbers with odd occurrences.java └── Step 8.3 Advance Maths │ ├── Leetcode │ ├── Pow(x, n).java │ └── Count Primes.java │ └── GeeksForGeeks │ ├── Power Of Numbers.java │ ├── Prime Factors.java │ └── Sieve of Eratosthenes.java ├── Step 13 Binary Trees ├── Step 13.2 Medium Problems │ ├── LeetCode │ │ ├── Maximum Depth of Binary Tree.java │ │ ├── Same Tree.java │ │ ├── Symmetric Tree.java │ │ ├── Diameter of Binary Tree.java │ │ ├── Binary Tree Maximum Path Sum.java │ │ ├── Balanced Binary Tree.java │ │ ├── Binary Tree Right Side View.java │ │ └── Binary Tree Zigzag Level Order Traversal.java │ └── GeeksForGeeks │ │ ├── Height of Binary Tree.java │ │ ├── Determine if Two Trees are Identical.java │ │ ├── Diameter of a Binary Tree.java │ │ ├── Maximum path sum from any node.java │ │ ├── Check for Balanced Tree.java │ │ ├── Left View of Binary Tree.java │ │ ├── Symmetric Tree.java │ │ └── ZigZag Tree Traversal.java └── Step 13.1 Traversals │ ├── LeetCode │ ├── Binary Tree Preorder Traversal.java │ ├── Binary Tree Inorder Traversal.java │ ├── Binary Tree Postorder Traversal.java │ └── Binary Tree Level Order Traversal.java │ └── GeeksForGeeks │ ├── Preorder Traversal.java │ ├── Inorder Traversal.java │ └── Postorder Traversal.java ├── Step 05 strings ├── Step 5.1 Basic and Easy String Problems │ ├── LeetCode │ │ ├── Rotate String.java │ │ ├── Largest Odd Number in String.java │ │ ├── Longest Common Prefix.java │ │ ├── Reverse Words in a String.java │ │ └── Isomorphic Strings.java │ └── GeeksForGeeks │ │ ├── Check if strings are rotations of each other or not.java │ │ ├── Anagram.java │ │ ├── Longest Common Prefix in an Array.java │ │ ├── Isomorphic Strings.java │ │ └── Reverse words in a given string.java └── Step 5.2 Medium String Problems │ ├── LeetCode │ ├── Maximum Nesting Depth of the Parentheses.java │ ├── Reverse Words in a String.java │ ├── Sum of Beauty of All Substrings.java │ ├── String to Integer (atoi).java │ ├── Roman to Integer.java │ ├── Longest Palindromic Substring.java │ └── Sort Characters By Frequency.java │ └── GeeksForGeeks │ ├── Implement Atoi.java │ ├── Count number of substrings.java │ └── Reverse words in a given string.java ├── Step 06 LinkedList ├── Step 6.2 Doubly Linked List │ └── GeeksForGeeks │ │ ├── Doubly LinkedList Implementatin.java │ │ ├── Reverse a Doubly Linked List.java │ │ ├── Delete node in Doubly Linked List.java │ │ └── Doubly linked list Insertion at given position.java ├── Step 6.1 1D Linked List │ ├── LeetCode │ │ └── Delete Node in a Linked List.java │ └── GeeksForGeeks │ │ ├── Search an element in the LL.java │ │ ├── Count nodes of linked list.java │ │ ├── Delete a Node in Single Linked List.java │ │ ├── LinkedList.java │ │ └── Linked List Insertion.java ├── Step 6.3 Medium Problem of LL │ ├── GeeksForGeeks │ │ ├── Detect Loop in linked list.java │ │ ├── Delete Middle of Linked List.java │ │ ├── Reverse a linked list.java │ │ ├── Check if Linked List is Palindrome.java │ │ ├── Nth node from end of linked list.java │ │ ├── Finding middle element in a linked list.java │ │ ├── Find length of Loop.java │ │ ├── Segregate even and odd nodes in a Link List.java │ │ └── Given a linked list of 0s, 1s and 2s, sort it.java │ └── LeetCode │ │ ├── Middle of the Linked List.java │ │ ├── Reverse Linked List.java │ │ ├── Linked List Cycle.java │ │ ├── Intersection of Two Linked Lists.java │ │ ├── Delete the Middle Node of a Linked List.java │ │ ├── Odd Even Linked List.java │ │ ├── Remove Nth Node From End of List.java │ │ └── Linked List Cycle II.java └── Step 6.5 Hard Problem of LL │ ├── LeetCode │ └── Rotate List.java │ └── GeeksForGeeks │ ├── Clone a linked list with next and random pointer.java │ └── Reverse Nodes in k-Group.java ├── Step 09 Stack and Queues ├── Step 9.3 Monotonic stack ans Queue Problems │ ├── GeeksForGeeks │ │ ├── Immediate Smaller Element.java │ │ ├── Stock span problem.java │ │ ├── Trapping Rain Water.java │ │ ├── Remove K Digits.java │ │ └── Next Greater Element.java │ └── Leetcode │ │ ├── Next Greater Element II.java │ │ ├── Next Greater Element I.java │ │ ├── Sum of Subarray Minimums.java │ │ ├── Online Stock Span.java │ │ ├── Largest Rectangle in Histogram.java │ │ ├── Remove K Digits.java │ │ ├── Asteroid Collision.java │ │ └── Trapping Rain Water.java ├── Step 9.4 Implementation Problems │ ├── LeetCode │ │ ├── Online Stock Span.java │ │ └── Sliding Window Maximum.java │ └── GeeksForGeeks │ │ ├── Maximum of all subarrays of size k.java │ │ ├── The Celebrity Problem.java │ │ └── Stock span problem.java └── Step 9.1 Learning │ ├── GeeksForGeeks │ ├── Implement stack using array.java │ ├── Implement Stack using Linked List.java │ ├── Implement Queue using array.java │ ├── Queue using stack.java │ ├── Stack using two queues.java │ └── Parenthesis Checker.java │ └── Leetcode │ ├── Implement Stack using Queues.java │ └── Valid Parentheses.java ├── Step 10 Sliding Window & Two Pointer Combined Problems ├── Step 10.1 Medium Problems │ ├── GeeksForGeeks │ │ ├── Maximum Consecutive Ones.java │ │ ├── Count Substring.java │ │ ├── Length of the longest substring.java │ │ └── Count Subarray with k odds.java │ └── LeetCode │ │ ├── Number of Substrings Containing All Three Characters.java │ │ ├── Max Consecutive Ones III.java │ │ ├── Maximum Points You Can Obtain from Cards.java │ │ ├── Binary Subarrays With Sum.java │ │ ├── Count Number of Nice Subarrays.java │ │ └── Longest Repeating Character Replacement.java └── Step 10.2 Hard Problems │ ├── GeeksForGeeks │ └── Longest K unique characters substring.java │ └── LeetCode │ └── Subarrays with K Different Integers.java ├── Step 11 Heaps ├── Step 11.2 Medium Problems │ ├── LeetCode │ │ ├── Kth Largest Element in an Array.java │ │ ├── Task Scheduler..java │ │ └── Hand of Straights.java │ └── GeeksForGeeks │ │ ├── Kth smallest element.java │ │ ├── K largest elements.java │ │ ├── Merge k Sorted Arrays.java │ │ └── Merge K sorted linked lists.java ├── Step 11.3 Hard Problems │ ├── GeeksForGeeks │ │ ├── Rod Cutting.java │ │ └── Kth largest element in a stream.java │ └── LeetCode │ │ ├── Kth Largest Element in a Stream.java │ │ ├── Top K Frequent Elements.java │ │ └── Find Median from Data Stream.java └── Step 11.1 Learning │ └── GeeksForGeeks │ └── Does array represent Heap.java ├── Step 12 Greedy Algorithms ├── Step 12.1 Easy Problems │ ├── LeetCode │ │ └── Assign Cookies.java │ └── GeeksForGeeks │ │ ├── Minimum number of Coins.java │ │ ├── Fractional Knapsack.java │ │ └── Parenthesis Checker.java └── Step 12.2 Medium-Hard Problems │ ├── LeetCode │ ├── Jump Game II.java │ ├── Jump Game.java │ ├── Merge Intervals.java │ ├── Non-overlapping Intervals.java │ ├── Insert Interval.java │ └── Candy.java │ └── GeeksForGeeks │ ├── Jump Game.java │ ├── Minimum number of jumps.java │ ├── Page Faults in LRU.java │ └── Minimum Platforms.java ├── Step 07 Recursion ├── Step 7.1 Get a Strong Hold │ ├── GeeksForGeeks │ │ ├── Reverse a Stack.java │ │ ├── Implement Atoi.java │ │ ├── Power Of Numbers.java │ │ └── Sort a stack.java │ └── LeetCode │ │ ├── Count Good Numbers.java │ │ ├── Pow(x, n).java │ │ └── String to Integer (atoi).java ├── Step 7.2 Subsequence Pattern │ ├── LeetCode │ │ ├── Generate Parentheses.java │ │ ├── Subsets.java │ │ ├── Subsets II.java │ │ ├── Combination Sum III.java │ │ ├── Combination Sum.java │ │ └── Combination Sum II.java │ └── GeeksForGeeks │ │ ├── Generate Parentheses.java │ │ ├── Power Set.java │ │ ├── Subset Sums.java │ │ ├── Possible Words From Phone Digits.java │ │ └── Generate_all_binary_strings.java └── Step 7.3 Try Out All Combo │ └── LeetCode │ └── Word Break.java └── Step 02 Learn Important Sorting Techniques ├── Step 2.1 Sorting-I ├── Bubblesort.java ├── Selectionsort.java └── Insertionsort.java └── Step 2.1 Sorting-II └── Quicksort.java /Step 01 - Basics/Step 1.3 Basic Maths/GCD.java: -------------------------------------------------------------------------------- 1 | class Main{ 2 | static Long gcd(Long num1, Long num2){ 3 | if (num2 == 0) return num1; 4 | return gcd(num2, num1 % num2); 5 | } 6 | } -------------------------------------------------------------------------------- /Step 01 - Basics/Step 1.3 Basic Maths/Count_Digits.java: -------------------------------------------------------------------------------- 1 | class Count_Digits{ 2 | 3 | static int countdigit(int N){ 4 | int c=0; 5 | while(N>0){ 6 | c++; 7 | N=N/10; 8 | } 9 | return c; 10 | } 11 | } -------------------------------------------------------------------------------- /Step 01 - Basics/Step 1.4 Basic Recursion/Fibonacci Number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int fib(int n) { 3 | if(n==0) return 0; 4 | if(n==1) return 1; 5 | return fib(n-1)+fib(n-2); 6 | } 7 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.1 Easy/GeeksForGeeks/Linear Search.java: -------------------------------------------------------------------------------- 1 | class Main{ 2 | public static boolean linearsearch(int arr[], int n, int val){ 3 | for(int i=0;iarr[i+1]) return false; 6 | } 7 | return true; 8 | } 9 | } -------------------------------------------------------------------------------- /Step 01 - Basics/Step 1.3 Basic Maths/Reverse_number.java: -------------------------------------------------------------------------------- 1 | class Main{ 2 | public static int reversenumber(int x){ 3 | int num=0, n=Math.abs(x); 4 | while(n>0){ 5 | int rem = n%10; 6 | num = (num*10) + rem; 7 | n=n/10; 8 | } 9 | if(x<0) num=-num; 10 | return num; 11 | } 12 | } -------------------------------------------------------------------------------- /Step 01 - Basics/Step 1.3 Basic Maths/LCM.java: -------------------------------------------------------------------------------- 1 | class Main{ 2 | static Long gcd(Long num1, Long num2){ 3 | if (num2 == 0) return num1; 4 | return gcd(num2, num1 % num2); 5 | } 6 | 7 | static Long lcm(Long num1, Long num2){ 8 | return (num1 / gcd(num1, num2)) * num2; 9 | } 10 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.1 Easy/GeeksForGeeks/Largest Element in Array.java: -------------------------------------------------------------------------------- 1 | class Compute { 2 | 3 | public int largest(int arr[], int n){ 4 | int max = Integer.MIN_VALUE; 5 | for(int i=0;imax) max=arr[i]; 7 | } 8 | return max; 9 | } 10 | } -------------------------------------------------------------------------------- /Step 08 Bit Manipulation/Step 8.1 Learn Bit Manipulation/GeeksForGeeks/Swap two numbers.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | static List get(int a,int b) 3 | { 4 | // code here 5 | List li =new ArrayList<>(); 6 | li.add(b); 7 | li.add(a); 8 | return li; 9 | } 10 | } -------------------------------------------------------------------------------- /Step 08 Bit Manipulation/Step 8.2 Interview Problems/GeeksForGeeks/Exceptionally odd.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int getOddOccurrence(int[] arr, int n) { 3 | // code here 4 | int ans=0; 5 | for(int i=0;i=0){ 5 | if(i>=0 && nums1[i]>nums2[j]){ 6 | nums1[k]=nums1[i]; 7 | i--; 8 | k--; 9 | }else{ 10 | nums1[k]=nums2[j]; 11 | j--; 12 | k--; 13 | } 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Step 08 Bit Manipulation/Step 8.1 Learn Bit Manipulation/Leetcode/Power of Two.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isPowerOfTwo(int n) { 3 | if(n<=0) return false; 4 | while(n>0){ 5 | if((n&1)==1){ 6 | n=n>>1; 7 | if(n>0) return false; 8 | } 9 | else n=n>>1; 10 | } 11 | return true; 12 | } 13 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.1 Easy/GeeksForGeeks/Maximize Number of 1's.java: -------------------------------------------------------------------------------- 1 | class Solve { 2 | // m is maximum of number zeroes allowed to flip 3 | int findZeroes(int arr[], int n, int m) { 4 | // code here 5 | int i = 0 , j; 6 | for(j = 0 ; j < n ; j++){ 7 | if(arr[j] == 0) m--; 8 | if(m < 0 && arr[i++] == 0) m++; 9 | } 10 | return j-i; 11 | } 12 | } -------------------------------------------------------------------------------- /Step 08 Bit Manipulation/Step 8.2 Interview Problems/Leetcode/Minimum Bit Flips to Convert Number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minBitFlips(int start, int goal) { 3 | int c=0; 4 | while(start>0 || goal>0){ 5 | int a = start&1, b = goal&1; 6 | if(a != b) c++; 7 | start=start>>1; 8 | goal=goal>>1; 9 | } 10 | return c; 11 | } 12 | } -------------------------------------------------------------------------------- /Step 04 Binary Search/Step 4.1 Learning BS on 1D Array/LeetCode/Find Peak Element.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findPeakElement(int[] nums) { 3 | int max=Integer.MIN_VALUE; 4 | int index=0; 5 | for(int i=0;i= k) r = mid; 7 | else l = mid + 1; 8 | } 9 | return l + k; 10 | } 11 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.1 Easy/GeeksForGeeks/Move all zeroes to end of array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | void pushZerosToEnd(int[] arr, int n) { 3 | // code here 4 | int i=0; 5 | for(int j=0;j0){ 7 | arr[i]=arr[j]; 8 | i++; 9 | } 10 | } 11 | for(int j=i;jarr[i+1]){ 6 | arr[i]=arr[i+1]; 7 | }else{ 8 | arr[i]=-1; 9 | } 10 | } 11 | arr[n-1]=-1; 12 | } 13 | } -------------------------------------------------------------------------------- /Step 10 Sliding Window & Two Pointer Combined Problems/Step 10.1 Medium Problems/GeeksForGeeks/Maximum Consecutive Ones.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static int longestOnes(int n, int[] nums, int k) { 3 | // code here 4 | int i = 0, j; 5 | for (j = 0; j < n; ++j) { 6 | if (nums[j] == 0) k--; 7 | if (k < 0 && nums[i++] == 0) k++; 8 | } 9 | return j - i; 10 | } 11 | } -------------------------------------------------------------------------------- /Step 04 Binary Search/Step 4.1 Learning BS on 1D Array/GeeksForGeeks/Binary Search.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int binarysearch(int arr[], int n, int k) { 3 | // code here 4 | int l=0, h=n-1; 5 | while(l<=h){ 6 | int mid = l+(h-l)/2; 7 | if(arr[mid]==k) return mid; 8 | else if(arr[mid]>k) h=mid-1; 9 | else l=mid+1; 10 | } 11 | return -1; 12 | } 13 | } -------------------------------------------------------------------------------- /Step 04 Binary Search/Step 4.3 Find Answers by BS in Search Space/GeeksForGeeks/K-th missing element.java: -------------------------------------------------------------------------------- 1 | class Complete{ 2 | int KthMissingElement(int a[], int n, int k) 3 | { 4 | // Complete the function 5 | int i=0, j=n; 6 | while(i<=j){ 7 | int mid = i+(j-i)/2; 8 | if(a[mid]-(mid+1) >= k) i=mid; 9 | else j=mid+1; 10 | } 11 | return i+k; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Step 05 strings/Step 5.2 Medium String Problems/LeetCode/Maximum Nesting Depth of the Parentheses.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxDepth(String s) { 3 | int len = s.length(); 4 | int level = 0; 5 | int max = 0; 6 | for(int i = 0; i < len; ++i){ 7 | final char ch = s.charAt(i); 8 | if(ch == '(') ++level; 9 | if(ch == ')') --level; 10 | if(level > max) max = level; 11 | } 12 | return max; 13 | } 14 | } -------------------------------------------------------------------------------- /Step 08 Bit Manipulation/Step 8.1 Learn Bit Manipulation/GeeksForGeeks/Set the rightmost unset bit.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | static int setBit(int N){ 3 | // code here 4 | int c=0, n=N; 5 | while(n>0){ 6 | if((n&1)==0){ 7 | N+=(int)Math.pow(2,c); 8 | break; 9 | } 10 | c++; 11 | n=n>>1; 12 | } 13 | return N; 14 | } 15 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.1 Easy/LeetCode/Check if Array Is Sorted and Rotated.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean check(int[] nums) { 3 | int count=0; 4 | int n = nums.length; 5 | for(int i=1; i nums[i]){ 7 | count++; 8 | } 9 | } 10 | if(nums[n-1] > nums[0]){ 11 | count++; 12 | } 13 | return count <= 1; 14 | } 15 | } -------------------------------------------------------------------------------- /Step 08 Bit Manipulation/Step 8.1 Learn Bit Manipulation/GeeksForGeeks/Check whether K-th bit is set or not.java: -------------------------------------------------------------------------------- 1 | 2 | class CheckBit 3 | { 4 | // Function to check if Kth bit is set or not. 5 | static boolean checkKthBit(int n, int k) 6 | { 7 | // Your code here 8 | int num=1< pq = new PriorityQueue<>(Collections.reverseOrder()); 4 | for(int i=0;is[j]) j++; 11 | } 12 | return i; 13 | } 14 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.1 Easy/LeetCode/Missing Number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int missingNumber(int[] nums) { 3 | int m=nums.length; 4 | for(int i=0;i=0;i--){ 6 | int no = Integer.parseInt(sb.charAt(i)+""); 7 | if(no%2==1) break; 8 | sb.deleteCharAt(i); 9 | } 10 | return sb.toString(); 11 | } 12 | } -------------------------------------------------------------------------------- /Step 09 Stack and Queues/Step 9.4 Implementation Problems/LeetCode/Online Stock Span.java: -------------------------------------------------------------------------------- 1 | class StockSpanner { 2 | Stack stack; 3 | 4 | public StockSpanner() { 5 | stack=new Stack<>(); 6 | } 7 | 8 | public int next(int price) { 9 | int i=1; 10 | while(!stack.isEmpty()&&stack.peek()[0]<=price) 11 | { 12 | i+=stack.pop()[1]; 13 | } 14 | stack.push(new int[]{price,i}); 15 | return i; 16 | } 17 | } -------------------------------------------------------------------------------- /Step 06 LinkedList/Step 6.1 1D Linked List/LeetCode/Delete Node in a Linked List.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | class Solution { 10 | public void deleteNode(ListNode node) { 11 | if(node==null) 12 | return; 13 | node.val = node.next.val; 14 | node.next = node.next.next; 15 | return; 16 | } 17 | } -------------------------------------------------------------------------------- /Step 11 Heaps/Step 11.2 Medium Problems/GeeksForGeeks/Kth smallest element.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public static int kthSmallest(int[] arr, int l, int r, int k) 3 | { 4 | //Your code here 5 | PriorityQueue pq = new PriorityQueue<>(); 6 | for(int i=0;i= 0; x--) 6 | if ((a >>> x) - b >= 0) { 7 | res += 1 << x; 8 | a -= b << x; 9 | } 10 | return (A > 0) == (B > 0) ? res : -res; 11 | } 12 | } -------------------------------------------------------------------------------- /Step 08 Bit Manipulation/Step 8.2 Interview Problems/GeeksForGeeks/Bit Difference.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | 3 | // Function to find number of bits needed to be flipped to convert A to B 4 | public static int countBitsFlip(int a, int b){ 5 | 6 | // Your code here 7 | int t=a^b; 8 | int c=0; 9 | while(t!=0){ 10 | int r=t & -t; 11 | t-=r; 12 | c++; 13 | } 14 | return c; 15 | } 16 | 17 | 18 | } -------------------------------------------------------------------------------- /Step 13 Binary Trees/Step 13.2 Medium Problems/LeetCode/Symmetric Tree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isSymmetric(TreeNode root) { 3 | return root==null || helper(root.left, root.right); 4 | } 5 | 6 | public static boolean helper(TreeNode left, TreeNode right){ 7 | if(left==null || right==null) return left==right; 8 | if(left.val != right.val) return false; 9 | return helper(left.left,right.right) && helper(left.right,right.left); 10 | } 11 | } -------------------------------------------------------------------------------- /Step 06 LinkedList/Step 6.1 1D Linked List/GeeksForGeeks/Search an element in the LL.java: -------------------------------------------------------------------------------- 1 | public boolean search(Node head, int x){ 2 | if (head == null) return false; 3 | if (head.data == x) return true; 4 | return search(head.next, x); 5 | } 6 | 7 | public boolean search(Node head, int x){ 8 | Node current = head; 9 | while (current != null) 10 | { 11 | if (current.data == x) 12 | return true; 13 | current = current.next; 14 | } 15 | return false; 16 | } -------------------------------------------------------------------------------- /Step 06 LinkedList/Step 6.1 1D Linked List/GeeksForGeeks/Count nodes of linked list.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | //Function to count nodes of a linked list. 4 | public static int getCount(Node head) 5 | { 6 | 7 | //Code here 8 | if(head==null){ 9 | return 0; 10 | } 11 | Node temp=head; 12 | int c=1; 13 | while(temp.next!=null){ 14 | temp=temp.next; 15 | c=c+1; 16 | } 17 | return c; 18 | } 19 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.1 Easy/GeeksForGeeks/Row with max 1s.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int rowWithMax1s(int arr[][], int n, int m) { 3 | // code here 4 | int val=0,r=0; 5 | for(int i=0;i s) 4 | { 5 | // add your code here 6 | for(int i=0;i s, int num, int n){ 10 | if(n==s.size()) s.push(num); 11 | else{ 12 | int val=s.pop(); 13 | helper(s, num, n); 14 | s.push(val); 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /Step 07 Recursion/Step 7.1 Get a Strong Hold/LeetCode/Count Good Numbers.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private static final int MOD = 1000000007; 3 | 4 | public int countGoodNumbers(long n) { 5 | return (int)(count(n / 2, 4 * 5) * (n % 2 == 0 ? 1 : 5) % MOD); 6 | } 7 | 8 | private long count(long power, long x) { 9 | if (power == 0) return 1; 10 | else if (power % 2 == 0) return count(power / 2, x * x % MOD); 11 | return x * count(power - 1, x) % MOD; 12 | } 13 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.2 Medium/LeetCode/Two Sum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] twoSum(int[] nums, int target) { 3 | int[] res = new int[2]; 4 | HashMap map = new HashMap<>(); 5 | for(int i=0;i=0){ 8 | if(mat[i][j]==X){ 9 | return 1; 10 | }else if(mat[i][j] large) 11 | { 12 | second_large = large; 13 | large = arr[i]; 14 | } 15 | 16 | else if (arr[i] > second_large && arr[i] != large) 17 | { 18 | second_large = arr[i]; 19 | } 20 | } 21 | return second_large; 22 | } -------------------------------------------------------------------------------- /Step 01 - Basics/Step 1.3 Basic Maths/Check_palindrome.java: -------------------------------------------------------------------------------- 1 | class Main{ 2 | public static boolean check(int x){ 3 | if(x<0){ 4 | return false; 5 | } 6 | int reverse=0; 7 | int num=x; 8 | while(num != 0) 9 | { 10 | int remainder = num % 10; 11 | reverse = reverse * 10 + remainder; 12 | num = num/10; 13 | } 14 | 15 | if(reverse==x){ 16 | return true; 17 | } 18 | return false; 19 | } 20 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.2 Medium/LeetCode/Rearrange Array Elements by Sign.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] rearrangeArray(int[] nums) { 3 | int n = nums.length; 4 | int[] ans = new int[n]; 5 | int pos=0, neg=1; 6 | for(int i=0;i0){ 8 | ans[pos]=nums[i]; 9 | pos+=2; 10 | }else{ 11 | ans[neg]=nums[i]; 12 | neg+=2; 13 | } 14 | } 15 | return ans; 16 | } 17 | } -------------------------------------------------------------------------------- /Step 08 Bit Manipulation/Step 8.1 Learn Bit Manipulation/GeeksForGeeks/Count total set bits.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | 3 | //Function to return sum of count of set bits in the integers from 1 to n. 4 | public static int countSetBits(int n){ 5 | 6 | // Your code here 7 | if(n==0) return 0; 8 | 9 | int x= (int)(Math.log(n)/ Math.log(2)); 10 | 11 | return ( ((int)Math.pow(2,x-1)*x) + (n- (int)Math.pow(2,x) +1) + countSetBits(n-(int)Math.pow(2,x))); 12 | 13 | } 14 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.1 Easy/LeetCode/Rotate Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private void reverse(int[] nums, int i, int j) { 3 | int t; 4 | while(i < j) { 5 | t = nums[i]; 6 | nums[i++] = nums[j]; 7 | nums[j--] = t; 8 | } 9 | } 10 | public void rotate(int[] nums, int k) { 11 | int n = nums.length; 12 | int finalK = n - (k % n); 13 | reverse(nums, 0, finalK-1); 14 | reverse(nums, finalK, n-1); 15 | reverse(nums, 0, n-1); 16 | } 17 | } -------------------------------------------------------------------------------- /Step 02 Learn Important Sorting Techniques/Step 2.1 Sorting-I/Bubblesort.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | //Function to sort the array using bubble sort algorithm. 4 | public static void bubbleSort(int arr[], int n) 5 | { 6 | //code here 7 | for(int i=0;iarr[j]){ 10 | int temp=arr[i]; 11 | arr[i]=arr[j]; 12 | arr[j]=temp; 13 | } 14 | } 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /Step 05 strings/Step 5.1 Basic and Easy String Problems/GeeksForGeeks/Check if strings are rotations of each other or not.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | //Function to check if two strings are rotations of each other or not. 4 | public static boolean areRotations(String s1, String s2 ) 5 | { 6 | // Your code here 7 | if (s1.length() != s2.length()) { 8 | return false; 9 | } 10 | String st3 = s1 + s1; 11 | if (st3.contains(s2)) return true; 12 | return false; 13 | } 14 | 15 | } -------------------------------------------------------------------------------- /Step 12 Greedy Algorithms/Step 12.2 Medium-Hard Problems/LeetCode/Jump Game II.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int jump(int[] nums) { 3 | int[] dp = new int[nums.length]; 4 | 5 | for(int i = 0; i < nums.length; i++){ 6 | for(int j = i+1; j <= i+nums[i] && j < nums.length; j++){ 7 | if(dp[j] == 0) 8 | dp[j] = dp[i] + 1; 9 | dp[j] = Math.min(dp[j], dp[i] + 1); 10 | } 11 | } 12 | return dp[nums.length-1]; 13 | 14 | } 15 | } -------------------------------------------------------------------------------- /Step 04 Binary Search/Step 4.1 Learning BS on 1D Array/GeeksForGeeks/Peak element.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | // Function to find the peak element 4 | // arr[]: input array 5 | // n: size of array a[] 6 | public int peakElement(int[] arr,int n) 7 | { 8 | //add code here. 9 | int max=Integer.MIN_VALUE; 10 | int index=0; 11 | for(int i=0;i 0) { 7 | if (nn % 2 == 1) { 8 | ans = ans * x; 9 | nn = nn - 1; 10 | } else { 11 | x = x * x; 12 | nn = nn / 2; 13 | } 14 | } 15 | if (n < 0) ans = (double)(1.0) / (double)(ans); 16 | return ans; 17 | } 18 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.1 Easy/GeeksForGeeks/Second Smallest Element.java: -------------------------------------------------------------------------------- 1 | static private int secondSmallest(int[] arr, int n) 2 | { 3 | if (n < 2) 4 | { 5 | return -1; 6 | } 7 | int small = Integer.MAX_VALUE; 8 | int second_small = Integer.MAX_VALUE; 9 | int i; 10 | for (i = 0; i < n; i++) 11 | { 12 | if (arr[i] < small) 13 | { 14 | second_small = small; 15 | small = arr[i]; 16 | } 17 | else if (arr[i] < second_small && arr[i] != small) 18 | { 19 | second_small = arr[i]; 20 | } 21 | } 22 | return second_small; 23 | } -------------------------------------------------------------------------------- /Step 08 Bit Manipulation/Step 8.3 Advance Maths/Leetcode/Pow(x, n).java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public double myPow(double x, int n) { 3 | double ans = 1.0; 4 | long nn = n; 5 | if (nn < 0) nn = -1 * nn; 6 | while (nn > 0) { 7 | if (nn % 2 == 1) { 8 | ans = ans * x; 9 | nn = nn - 1; 10 | } else { 11 | x = x * x; 12 | nn = nn / 2; 13 | } 14 | } 15 | if (n < 0) ans = (double)(1.0) / (double)(ans); 16 | return ans; 17 | } 18 | } -------------------------------------------------------------------------------- /Step 10 Sliding Window & Two Pointer Combined Problems/Step 10.1 Medium Problems/GeeksForGeeks/Count Substring.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static int countSubstring(String s) { 3 | // code here 4 | int count[] = new int[3]; 5 | int res = 0 , i = 0, n = s.length(); 6 | for (int j = 0; j < n; ++j) { 7 | ++count[s.charAt(j) - 'a']; 8 | while (count[0] > 0 && count[1] > 0 && count[2] > 0) --count[s.charAt(i++) - 'a']; 9 | res += i; 10 | } 11 | return res; 12 | } 13 | } -------------------------------------------------------------------------------- /Step 10 Sliding Window & Two Pointer Combined Problems/Step 10.1 Medium Problems/LeetCode/Number of Substrings Containing All Three Characters.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numberOfSubstrings(String s) { 3 | int count[] = new int[3]; 4 | int res = 0 , i = 0, n = s.length(); 5 | for (int j = 0; j < n; ++j) { 6 | ++count[s.charAt(j) - 'a']; 7 | while (count[0] > 0 && count[1] > 0 && count[2] > 0) --count[s.charAt(i++) - 'a']; 8 | res += i; 9 | } 10 | return res; 11 | } 12 | } -------------------------------------------------------------------------------- /Step 07 Recursion/Step 7.2 Subsequence Pattern/LeetCode/Generate Parentheses.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List generateParenthesis(int n) { 3 | List ans = new ArrayList(); 4 | if (n == 0) { 5 | ans.add(""); 6 | } else { 7 | for (int c = 0; c < n; ++c) 8 | for (String left: generateParenthesis(c)) 9 | for (String right: generateParenthesis(n-1-c)) 10 | ans.add("(" + left + ")" + right); 11 | } 12 | return ans; 13 | } 14 | } -------------------------------------------------------------------------------- /Step 11 Heaps/Step 11.3 Hard Problems/GeeksForGeeks/Rod Cutting.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public int cutRod(int price[], int n) { 3 | //code here 4 | int[][] dp = new int[n+1][n+1]; 5 | for(int i=0;i<=n;i++) dp[i][0]=0; 6 | for(int i=0;i<=n;i++) dp[0][i]=0; 7 | for(int i=1;i<=n;i++){ 8 | for(int j=1;j<=n;j++){ 9 | if(i<=j) dp[i][j]=Math.max(price[i-1]+dp[i][j-i], dp[i-1][j]); 10 | else dp[i][j]=dp[i-1][j]; 11 | } 12 | } 13 | return dp[n][n]; 14 | } 15 | } -------------------------------------------------------------------------------- /Step 01 - Basics/Step 1.5 Basic Hashing/Frequencies of Limited Range Array Elements.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | //Function to count the frequency of all elements from 1 to N in the array. 3 | public static void frequencyCount(int arr[], int N, int P) 4 | { 5 | // code here 6 | int[] result = new int[N+1]; 7 | for(int i = 0 ; i< N ; i++){ 8 | if(arr[i] <= N){ 9 | result[arr[i]] += 1; 10 | } 11 | } 12 | for(int i = 0 ;i= 0) ans=Math.min(ans, arr[mid-1]); 12 | if(mid+1 < n) ans=Math.min(ans, arr[mid+1]); 13 | return ans; 14 | } 15 | } -------------------------------------------------------------------------------- /Step 04 Binary Search/Step 4.2 Applying BS on 2D Array/GeeksForGeeks/Median in a row-wise sorted Matrix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int median(int matrix[][], int r, int c) { 3 | // code here 4 | PriorityQueue pq = new PriorityQueue(); 5 | for(int i=0;i= '0' && ch <= '9' || ch=='-'){ 9 | if(ch=='-') flag++; 10 | else n=n*10+(ch-48); 11 | if(flag>1) return -1; 12 | }else{ 13 | return -1; 14 | } 15 | i++; 16 | } 17 | if(flag==1) n=-n; 18 | return n; 19 | } 20 | } -------------------------------------------------------------------------------- /Step 07 Recursion/Step 7.1 Get a Strong Hold/GeeksForGeeks/Implement Atoi.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | int atoi(String str) { 4 | // Your code here 5 | int flag=0,i=0,n=0; 6 | while(i= '0' && ch <= '9' || ch=='-'){ 9 | if(ch=='-') flag++; 10 | else n=n*10+(ch-48); 11 | if(flag>1) return -1; 12 | }else{ 13 | return -1; 14 | } 15 | i++; 16 | } 17 | if(flag==1) n=-n; 18 | return n; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Step 13 Binary Trees/Step 13.2 Medium Problems/LeetCode/Binary Tree Maximum Path Sum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | static int max; 3 | public int maxPathSum(TreeNode root) { 4 | max=Integer.MIN_VALUE; 5 | maxsum(root); 6 | return max; 7 | } 8 | static int maxsum(TreeNode root){ 9 | if(root==null) return 0; 10 | int l=Math.max(maxsum(root.left),0); 11 | int r=Math.max(maxsum(root.right),0); 12 | int sum=root.val+l+r; 13 | max=Math.max(max, sum); 14 | return root.val+Math.max(l,r); 15 | } 16 | } -------------------------------------------------------------------------------- /Step 01 - Basics/Step 1.3 Basic Maths/Print_all_divisior.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | static long sumOfDivisors(int N){ 3 | // code here 4 | long sum=0; 5 | for(int i=1;i<=N;i++){ 6 | sum+=(N/i)*i; 7 | } 8 | return sum; 9 | } 10 | 11 | static void printDivisorsBruteForce(int n){ 12 | System.out.println("The Divisors of "+n+" are:"); 13 | for(int i = 1; i <= n; i++) 14 | if(n % i == 0) 15 | System.out.print(i + " "); 16 | 17 | System.out.println(); 18 | } 19 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.3 Hard/GeeksForGeeks/Largest subarray with 0 sum.java: -------------------------------------------------------------------------------- 1 | class GfG 2 | { 3 | int maxLen(int arr[], int n) 4 | { 5 | // Your code here 6 | int max=0,sum=0; 7 | HashMap map = new HashMap<>(); 8 | map.put(sum,-1); 9 | for(int i=0;i 1) 15 | result = false; 16 | return 1 + Math.max(l, r); 17 | } 18 | 19 | } -------------------------------------------------------------------------------- /Step 08 Bit Manipulation/Step 8.3 Advance Maths/Leetcode/Count Primes.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countPrimes(int n) { 3 | boolean prime[] = new boolean[n+1]; 4 | for(int i=0;i<=n;i++) prime[i]=true; 5 | for(int i=2;i*i<=n;i++){ 6 | if(prime[i]==true){ 7 | for(int j=i*i;j<=n;j+=i){ 8 | prime[j]=false; 9 | } 10 | } 11 | } 12 | int c=0; 13 | for(int i=2;ix) return -1; 9 | int l=0, h=n-1; 10 | while(l<=h){ 11 | int mid=l+(h-l)/2; 12 | if(arr[mid]==x) return mid; 13 | else if(arr[mid]>x) h=mid-1; 14 | else l=mid+1; 15 | } 16 | return l-1; 17 | } 18 | 19 | } -------------------------------------------------------------------------------- /Step 04 Binary Search/Step 4.1 Learning BS on 1D Array/LeetCode/Binary Search.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int search(int[] nums, int target) { 3 | int low = 0, high = nums.length-1; 4 | while(low<=high){ 5 | int mid = (low+high)/2; 6 | if(nums[mid]==target){ 7 | return mid; 8 | } 9 | else if(nums[mid]>target){ 10 | high=mid-1; 11 | } 12 | else if(nums[mid] preorderTraversal(TreeNode root) { 3 | List p = new ArrayList<>(); 4 | if(root==null) return p; 5 | Stack st = new Stack<>(); 6 | st.push(root); 7 | while(!st.isEmpty()){ 8 | root=st.pop(); 9 | p.add(root.val); 10 | if(root.right != null) st.push(root.right); 11 | if(root.left != null) st.push(root.left); 12 | } 13 | return p; 14 | } 15 | } -------------------------------------------------------------------------------- /Step 12 Greedy Algorithms/Step 12.1 Easy Problems/GeeksForGeeks/Minimum number of Coins.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | static List minPartition(int n) 3 | { 4 | // code here 5 | int[] notes={ 1, 2, 5, 10, 20, 50, 100, 200, 500, 2000 }; 6 | List list = new ArrayList<>(); 7 | int i=notes.length-1; 8 | while(n>0){ 9 | if(notes[i]<=n){ 10 | n-=notes[i]; 11 | list.add(notes[i]); 12 | }else{ 13 | i--; 14 | } 15 | } 16 | return list; 17 | } 18 | } -------------------------------------------------------------------------------- /Step 12 Greedy Algorithms/Step 12.2 Medium-Hard Problems/LeetCode/Jump Game.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canJump(int[] nums) { 3 | int n=nums.length; 4 | int lgi=n-1; 5 | for(int i=n-2;i>=0;i--) 6 | if(i+nums[i]>=lgi) 7 | lgi=i; 8 | return lgi==0; 9 | 10 | // int[] dp = new int[nums.length]; 11 | // for(int i=1; i= 0; x--) 9 | if ((a >>> x) - b >= 0) { 10 | res += 1 << x; 11 | a -= b << x; 12 | } 13 | return (A > 0) == (B > 0) ? res : -res; 14 | } 15 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.3 Hard/GeeksForGeeks/Pascal Triangle.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | ArrayList nthRowOfPascalTriangle(int n) { 3 | // code here 4 | Long[][] dp = new Long[n][n]; 5 | for(int i=0;i ans = new ArrayList<>(); 12 | for(int i=0;i preSum = new HashMap<>(); 5 | preSum.put(0, 1); 6 | 7 | for (int i = 0; i < nums.length; i++) { 8 | sum += nums[i]; 9 | if (preSum.containsKey(sum - k)) { 10 | result += preSum.get(sum - k); 11 | } 12 | preSum.put(sum, preSum.getOrDefault(sum, 0) + 1); 13 | } 14 | 15 | return result; 16 | } 17 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.3 Hard/LeetCode/Maximum Product Subarray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxProduct(int[] nums) { 3 | int ans = nums[0]; 4 | int max = nums[0]; 5 | int min = nums[0]; 6 | 7 | for(int i=1;i AllParenthesis(int n) 4 | { 5 | // Write your code here 6 | List l = new ArrayList<>(); 7 | Parenthesis(l,n,"",0,0); 8 | return l; 9 | } 10 | 11 | public void Parenthesis(List l, int max, String s, int open, int close){ 12 | if(s.length() == max*2) l.add(s); 13 | if(max>open) Parenthesis(l,max,s+"(",open+1,close); 14 | if(close rightSideView(TreeNode root) { 3 | List ans = new ArrayList<>(); 4 | if(root==null) return ans; 5 | rightview(root, ans, 0); 6 | return ans; 7 | } 8 | 9 | public static void rightview(TreeNode root, List ans, int level){ 10 | if(root==null) return; 11 | if(ans.size()==level) ans.add(root.val); 12 | rightview(root.right, ans, level+1); 13 | rightview(root.left, ans, level+1); 14 | } 15 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.1 Easy/GeeksForGeeks/Longest Sub-Array with Sum K.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | // Function for finding maximum and value pair 3 | public static int lenOfLongSubarr (int A[], int N, int K) { 4 | //Complete the function 5 | HashMap map = new HashMap<>(); 6 | int ans=0, sum=0; 7 | map.put(0,-1); 8 | for(int i=0;i=x){ 11 | min=Math.min(min,arr[i]); 12 | } 13 | } 14 | if(min==Integer.MAX_VALUE) 15 | min=-1; 16 | Pair p=new Pair(max,min); 17 | return p; 18 | } 19 | } -------------------------------------------------------------------------------- /Step 04 Binary Search/Step 4.1 Learning BS on 1D Array/GeeksForGeeks/Minimum element in a sorted and rotated array.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | int findMin(int arr[], int n) 4 | { 5 | //complete the function here 6 | 7 | int l=0, r=n-1, mid=0, ans=arr[0]; 8 | while(l= 0) ans=Math.min(ans, arr[mid-1]); 15 | if(mid+1 < n) ans=Math.min(ans, arr[mid+1]); 16 | return ans; 17 | } 18 | } -------------------------------------------------------------------------------- /Step 11 Heaps/Step 11.2 Medium Problems/GeeksForGeeks/K largest elements.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | //Function to return k largest elements from an array. 4 | public static ArrayList kLargest(int arr[], int n, int k) 5 | { 6 | // code here 7 | PriorityQueue pq = new PriorityQueue<>(Collections.reverseOrder()); 8 | for(int i=0;i list = new ArrayList<>(); 12 | for(int i=0;i<=k-1;i++){ 13 | list.add(pq.poll()); 14 | } 15 | return list; 16 | } 17 | } -------------------------------------------------------------------------------- /Step 02 Learn Important Sorting Techniques/Step 2.1 Sorting-I/Selectionsort.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | int select(int arr[], int i) 4 | { 5 | // code here such that selectionSort() sorts arr[] 6 | int min = i; 7 | for(int j=i+1;jtarget){ 9 | r=m-1; 10 | }else if(nums[m]= n - 1) return memory[i] = 1; 13 | if (memory[i] != -1) return memory[i]; 14 | for (int j = 1; j <= a[i]; j++) 15 | if (helper(a, n, i + j) == 1) return memory[i] = 1; 16 | return memory[i] = 0; 17 | } 18 | 19 | }; -------------------------------------------------------------------------------- /Step 07 Recursion/Step 7.1 Get a Strong Hold/GeeksForGeeks/Power Of Numbers.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | static long mod=1000000007; 4 | long power(long N,long R) 5 | { 6 | //Your code here 7 | if(N==1) return 1; 8 | if(R==0) return 1; 9 | if(R==1) return N; 10 | long l; 11 | if(R%2==0){ 12 | l=power((N*N)%mod,R/2); 13 | }else{ 14 | l=(N%mod)*power((N*N)%mod,R/2)%mod; 15 | } 16 | return l; 17 | } 18 | long power(int N,int R) 19 | { 20 | //Your code here 21 | return power((long)N, (long)R); 22 | } 23 | 24 | } -------------------------------------------------------------------------------- /Step 07 Recursion/Step 7.2 Subsequence Pattern/LeetCode/Subsets.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> subsets(int[] nums) { 3 | List> output = new ArrayList(); 4 | int n = nums.length; 5 | for (int i = (int)Math.pow(2, n); i < (int)Math.pow(2, n + 1); ++i) { 6 | String bitmask = Integer.toBinaryString(i).substring(1); 7 | List curr = new ArrayList(); 8 | for (int j = 0; j < n; ++j) { 9 | if (bitmask.charAt(j) == '1') curr.add(nums[j]); 10 | } 11 | output.add(curr); 12 | } 13 | return output; 14 | } 15 | } -------------------------------------------------------------------------------- /Step 09 Stack and Queues/Step 9.3 Monotonic stack ans Queue Problems/Leetcode/Next Greater Element II.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] nextGreaterElements(int[] nums) { 3 | int[] res = new int[nums.length]; 4 | Stack stack = new Stack<>(); 5 | for (int i = 2 * nums.length - 1; i >= 0; --i) { 6 | while (!stack.empty() && nums[stack.peek()] <= nums[i % nums.length]) { 7 | stack.pop(); 8 | } 9 | res[i % nums.length] = stack.empty() ? -1 : nums[stack.peek()]; 10 | stack.push(i % nums.length); 11 | } 12 | return res; 13 | } 14 | } -------------------------------------------------------------------------------- /Step 08 Bit Manipulation/Step 8.2 Interview Problems/Leetcode/Subsets.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> subsets(int[] nums) { 3 | List> output = new ArrayList(); 4 | int n = nums.length; 5 | for (int i = (int)Math.pow(2, n); i < (int)Math.pow(2, n + 1); ++i) { 6 | String bitmask = Integer.toBinaryString(i).substring(1); 7 | List curr = new ArrayList(); 8 | for (int j = 0; j < n; ++j) { 9 | if (bitmask.charAt(j) == '1') curr.add(nums[j]); 10 | } 11 | output.add(curr); 12 | } 13 | return output; 14 | } 15 | } -------------------------------------------------------------------------------- /Step 08 Bit Manipulation/Step 8.3 Advance Maths/GeeksForGeeks/Power Of Numbers.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | static long mod=1000000007; 4 | long power(long N,long R) 5 | { 6 | //Your code here 7 | if(N==1) return 1; 8 | if(R==0) return 1; 9 | if(R==1) return N; 10 | long l; 11 | if(R%2==0){ 12 | l=power((N*N)%mod,R/2); 13 | }else{ 14 | l=(N%mod)*power((N*N)%mod,R/2)%mod; 15 | } 16 | return l; 17 | } 18 | long power(int N,int R) 19 | { 20 | //Your code here 21 | return power((long)N, (long)R); 22 | } 23 | 24 | } -------------------------------------------------------------------------------- /Step 09 Stack and Queues/Step 9.1 Learning/GeeksForGeeks/Implement Stack using Linked List.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | class MyStack 4 | { 5 | StackNode top; 6 | 7 | //Function to push an integer into the stack. 8 | void push(int a) 9 | { 10 | // Add your code here 11 | StackNode temp = new StackNode(a); 12 | temp.next=top; 13 | top=temp; 14 | } 15 | 16 | //Function to remove an item from top of the stack. 17 | int pop() 18 | { 19 | // Add your code here 20 | if(top==null) return -1; 21 | int n=top.data; 22 | top=top.next; 23 | return n; 24 | } 25 | } -------------------------------------------------------------------------------- /Step 09 Stack and Queues/Step 9.3 Monotonic stack ans Queue Problems/Leetcode/Next Greater Element I.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] nextGreaterElement(int[] findNums, int[] nums) { 3 | Map map = new HashMap<>(); 4 | Stack stack = new Stack<>(); 5 | for (int num : nums) { 6 | while (!stack.isEmpty() && stack.peek() < num) 7 | map.put(stack.pop(), num); 8 | stack.push(num); 9 | } 10 | for (int i = 0; i < findNums.length; i++) 11 | findNums[i] = map.getOrDefault(findNums[i], -1); 12 | return findNums; 13 | } 14 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.3 Hard/GeeksForGeeks/Subsets with XOR value.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | static int subsetXOR(int arr[], int N, int K) { 3 | // code here 4 | int max = arr[0]; 5 | for(int i=1;imax) max = arr[i]; 7 | } 8 | int m = 10*max; 9 | int[][] dp = new int[N+1][m+1]; 10 | dp[0][0] = 1; 11 | for(int i=1;i<=N;i++){ 12 | for(int j=0;j<=m;j++){ 13 | dp[i][j] += dp[i-1][j]; 14 | if((j^arr[i-1]) <= m) dp[i][j] += dp[i-1][j^arr[i-1]]; 15 | } 16 | } 17 | return dp[N][K]; 18 | } 19 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.3 Hard/LeetCode/Merge Intervals.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[][] merge(int[][] intervals) { 3 | Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0])); 4 | LinkedList merged = new LinkedList<>(); 5 | for (int[] interval : intervals) { 6 | if (merged.isEmpty() || merged.getLast()[1] < interval[0]) { 7 | merged.add(interval); 8 | } 9 | else { 10 | merged.getLast()[1] = Math.max(merged.getLast()[1], interval[1]); 11 | } 12 | } 13 | return merged.toArray(new int[merged.size()][]); 14 | } 15 | } -------------------------------------------------------------------------------- /Step 09 Stack and Queues/Step 9.1 Learning/Leetcode/Implement Stack using Queues.java: -------------------------------------------------------------------------------- 1 | class MyStack { 2 | private Queue queue = new LinkedList<>(); 3 | 4 | public MyStack() { 5 | 6 | } 7 | 8 | public void push(int x) { 9 | queue.add(x); 10 | for(int i = 1;i mergeKArrays(int[][] arr,int K) 5 | { 6 | // Write your code here. 7 | PriorityQueue pq = new PriorityQueue<>(); 8 | for(int i=0;i list = new ArrayList<>(); 14 | while(!pq.isEmpty()){ 15 | list.add(pq.poll()); 16 | } 17 | return list; 18 | } 19 | } -------------------------------------------------------------------------------- /Step 07 Recursion/Step 7.2 Subsequence Pattern/GeeksForGeeks/Power Set.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public List AllPossibleStrings(String s) 4 | { 5 | // Code here 6 | String str = ""; 7 | List list = new ArrayList<>(); 8 | solve(0, s, str, list); 9 | Collections.sort(list); 10 | return list; 11 | } 12 | 13 | static void solve(int i, String s, String str, List list) { 14 | if (i == s.length()) { 15 | if(str!="") list.add(str); 16 | return; 17 | } 18 | solve(i + 1, s, str+s.charAt(i), list); 19 | solve(i + 1, s, str, list); 20 | } 21 | } -------------------------------------------------------------------------------- /Step 02 Learn Important Sorting Techniques/Step 2.1 Sorting-I/Insertionsort.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | static void insert(int arr[],int i) 4 | { 5 | // Your code here 6 | int n=arr.length; 7 | insertionSort(arr, n); 8 | return; 9 | } 10 | //Function to sort the array using insertion sort algorithm. 11 | public static void insertionSort(int arr[], int n) 12 | { 13 | //code here 14 | for(int i=1;i=0 && arr[j]>num){ 17 | arr[j+1]=arr[j]; 18 | j--; 19 | } 20 | arr[j+1]=num; 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /Step 04 Binary Search/Step 4.3 Find Answers by BS in Search Space/GeeksForGeeks/Largest Sum Subarray of Size at least K.java: -------------------------------------------------------------------------------- 1 | class Compute { 2 | public long maxSumWithK(long a[], long n, long k){ 3 | long i=0, j=0, max=Long.MIN_VALUE, sum=0, c=0, b=0; 4 | while(jk){ 10 | c+=a[(int)i]; 11 | i++; 12 | b=Math.min(b,c); 13 | max=Math.max(max,sum-b); 14 | } 15 | j++; 16 | } 17 | return max; 18 | } 19 | } -------------------------------------------------------------------------------- /Step 08 Bit Manipulation/Step 8.2 Interview Problems/GeeksForGeeks/Power Set.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public List AllPossibleStrings(String s) 4 | { 5 | // Code here 6 | String str = ""; 7 | List list = new ArrayList<>(); 8 | solve(0, s, str, list); 9 | Collections.sort(list); 10 | return list; 11 | } 12 | 13 | static void solve(int i, String s, String str, List list) { 14 | if (i == s.length()) { 15 | if(str!="") list.add(str); 16 | return; 17 | } 18 | solve(i + 1, s, str+s.charAt(i), list); 19 | solve(i + 1, s, str, list); 20 | } 21 | } -------------------------------------------------------------------------------- /Step 11 Heaps/Step 11.2 Medium Problems/LeetCode/Task Scheduler..java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int leastInterval(char[] tasks, int n) { 3 | int[] ans = new int[26]; 4 | int max=0, c=0; 5 | for(char task: tasks){ 6 | ans[task-'A']++; 7 | if(max==ans[task-'A']) c++; 8 | else if(max s = new Stack<>(); 4 | int[] dp = new int[arr.length]; 5 | int total = 0; 6 | for (int i = 0; i < arr.length; i++) { 7 | while (!s.isEmpty() && arr[s.peek()] > arr[i]) s.pop(); 8 | if (s.isEmpty()) dp[i] = (i + 1) * arr[i]; 9 | else dp[i] = dp[s.peek()] + (i - s.peek()) * arr[i]; 10 | total = (total + dp[i] ) % 1000000007; 11 | s.push(i); 12 | } 13 | return total; 14 | } 15 | } -------------------------------------------------------------------------------- /Step 11 Heaps/Step 11.1 Learning/GeeksForGeeks/Does array represent Heap.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public boolean countSub(long arr[], long n) 4 | { 5 | // Your code goes here 6 | for(long i=0; i<=n/2; i++){ 7 | long index = i*2 + 1; 8 | if(index < n){ 9 | if(arr[(int)i] < arr[(int)index]){ 10 | return false; 11 | } 12 | } 13 | if(index + 1 < n){ 14 | if(arr[(int)i] < arr[(int)index + 1]){ 15 | return false; 16 | } 17 | } 18 | } 19 | return true; 20 | } 21 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.3 Hard/LeetCode/Pascal's Triangle.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> generate(int numRows) { 3 | List> arr = new ArrayList<>(); 4 | List pre = null; 5 | for(int i=0;i list = new ArrayList<>(); 7 | for(int j=0;j<=i;j++){ 8 | if(j==0 || j==i){ 9 | list.add(1); 10 | }else{ 11 | list.add(pre.get(j-1)+pre.get(j)); 12 | } 13 | } 14 | pre = list; 15 | arr.add(list); 16 | } 17 | return arr; 18 | } 19 | } -------------------------------------------------------------------------------- /Step 06 LinkedList/Step 6.3 Medium Problem of LL/GeeksForGeeks/Delete Middle of Linked List.java: -------------------------------------------------------------------------------- 1 | /* 2 | class Node { 3 | int data; 4 | Node next; 5 | Node(int d) { data = d; next = null; } 6 | } 7 | */ 8 | 9 | class Solution { 10 | Node deleteMid(Node head) { 11 | // This is method only submission. 12 | // You only need to complete the method. 13 | Node f=head; 14 | Node s=head; 15 | Node prev=null; 16 | while(f!=null&&f.next!=null){ 17 | prev=s; 18 | f=f.next.next; 19 | s=s.next; 20 | 21 | } 22 | prev.next=s.next; 23 | return head; 24 | } 25 | } -------------------------------------------------------------------------------- /Step 09 Stack and Queues/Step 9.1 Learning/Leetcode/Valid Parentheses.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isValid(String s) { 3 | Stack st = new Stack(); 4 | for (char it : s.toCharArray()) { 5 | if (it == '(' || it == '[' || it == '{') 6 | st.push(it); 7 | else { 8 | if(st.isEmpty()) return false; 9 | char ch = st.pop(); 10 | if((it == ')' && ch == '(') || (it == ']' && ch == '[') || (it == '}' && ch == '{')) continue; 11 | else return false; 12 | } 13 | } 14 | return st.isEmpty(); 15 | } 16 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.3 Hard/GeeksForGeeks/Maximum Product Subarray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to find maximum product subarray 3 | long maxProduct(int[] arr, int n) { 4 | // code here 5 | long max=arr[0]; 6 | long min=arr[0]; 7 | long ans=arr[0]; 8 | 9 | for(int i=1;i stack; 3 | 4 | public StockSpanner() { 5 | stack=new Stack<>(); 6 | } 7 | 8 | public int next(int price) { 9 | int i=1; 10 | while(!stack.isEmpty()&&stack.peek()[0]<=price) 11 | { 12 | i+=stack.pop()[1]; 13 | } 14 | stack.push(new int[]{price,i}); 15 | return i; 16 | } 17 | } 18 | 19 | /** 20 | * Your StockSpanner object will be instantiated and called as such: 21 | * StockSpanner obj = new StockSpanner(); 22 | * int param_1 = obj.next(price); 23 | */ -------------------------------------------------------------------------------- /Step 12 Greedy Algorithms/Step 12.2 Medium-Hard Problems/LeetCode/Merge Intervals.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[][] merge(int[][] intervals) { 3 | Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0])); 4 | LinkedList merged = new LinkedList<>(); 5 | for (int[] interval : intervals) { 6 | if (merged.isEmpty() || merged.getLast()[1] < interval[0]) { 7 | merged.add(interval); 8 | } 9 | else { 10 | merged.getLast()[1] = Math.max(merged.getLast()[1], interval[1]); 11 | } 12 | } 13 | return merged.toArray(new int[merged.size()][]); 14 | } 15 | } -------------------------------------------------------------------------------- /Step 12 Greedy Algorithms/Step 12.2 Medium-Hard Problems/LeetCode/Non-overlapping Intervals.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int eraseOverlapIntervals(int[][] intervals) { 3 | if(intervals.length == 0 || intervals == null) 4 | return 0; 5 | Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1])); 6 | int removed = 0; 7 | int prevEnd = intervals[0][1]; 8 | for(int i = 1; i < intervals.length; i++){ 9 | if(intervals[i][0] < prevEnd) 10 | removed++; 11 | else{ 12 | prevEnd = intervals[i][1]; 13 | } 14 | } 15 | return removed; 16 | } 17 | } -------------------------------------------------------------------------------- /Step 13 Binary Trees/Step 13.2 Medium Problems/GeeksForGeeks/Maximum path sum from any node.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | static int max; 3 | //Function to return maximum path sum from any node in a tree. 4 | int findMaxSum(Node node){ 5 | //your code goes here 6 | max=Integer.MIN_VALUE; 7 | helper(node); 8 | return max; 9 | } 10 | 11 | static int helper(Node node){ 12 | if(node==null) return 0; 13 | int l=Math.max(helper(node.left),0); 14 | int r=Math.max(helper(node.right),0); 15 | int sum=node.data+l+r; 16 | max=Math.max(max,sum); 17 | return node.data+Math.max(l,r); 18 | } 19 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.3 Hard/GeeksForGeeks/Merge Without Extra Space.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | //Function to merge the arrays. 4 | public static void merge(long arr1[], long arr2[], int m, int n) 5 | { 6 | // code here 7 | int i = 0, j = 0, k = m - 1; 8 | while (i <= k && j < n) { 9 | if (arr1[i] < arr2[j]) 10 | i++; 11 | else { 12 | long temp = arr2[j]; 13 | arr2[j] = arr1[k]; 14 | arr1[k] = temp; 15 | j++; 16 | k--; 17 | } 18 | } 19 | Arrays.sort(arr1); 20 | Arrays.sort(arr2); 21 | } 22 | } -------------------------------------------------------------------------------- /Step 06 LinkedList/Step 6.3 Medium Problem of LL/LeetCode/Middle of the Linked 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 | public ListNode middleNode(ListNode head) { 13 | ListNode slow = head, fast = head; 14 | while(fast != null && fast.next != null){ 15 | slow = slow.next; 16 | fast = fast.next.next; 17 | } 18 | return slow; 19 | } 20 | } -------------------------------------------------------------------------------- /Step 10 Sliding Window & Two Pointer Combined Problems/Step 10.1 Medium Problems/GeeksForGeeks/Length of the longest substring.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | int longestUniqueSubsttr(String S){ 3 | int n = S.length(), ans=0, c=0, i=0, j=0; 4 | int[] count = new int[26]; 5 | while(i k && start <= end) { 13 | if (nums[start] == 0) zerosCount -= 1; 14 | start += 1; 15 | } 16 | length = Math.max(length, end - start + 1); 17 | } 18 | return length; 19 | } 20 | } -------------------------------------------------------------------------------- /Step 10 Sliding Window & Two Pointer Combined Problems/Step 10.1 Medium Problems/LeetCode/Maximum Points You Can Obtain from Cards.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxScore(int[] cardPoints, int k) { 3 | int[] dp = new int[k + 1]; 4 | for (int i = cardPoints.length - 1; i >= cardPoints.length - k; i--) { 5 | dp[0] += cardPoints[i]; 6 | } 7 | int max_points = dp[0]; 8 | 9 | for (int i = 1; i < k + 1; i++) { 10 | dp[i] = dp[i - 1] + cardPoints[i - 1] - cardPoints[cardPoints.length - k + i - 1]; 11 | max_points = Math.max(max_points, dp[i]); 12 | } 13 | 14 | return max_points; 15 | } 16 | } -------------------------------------------------------------------------------- /Step 05 strings/Step 5.1 Basic and Easy String Problems/GeeksForGeeks/Anagram.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | //Function is to check whether two strings are anagram of each other or not. 4 | public static boolean isAnagram(String a,String b) 5 | { 6 | 7 | // Your code here 8 | int n = a.length(), m = b.length(); 9 | if(n!=m) return false; 10 | int count[] = new int[26]; 11 | for(int i=0;i inorderTraversal(TreeNode root) { 3 | List inorder = new ArrayList<>(); 4 | Stack st = new Stack<>(); 5 | TreeNode node = root; 6 | while(true){ 7 | if(node != null){ 8 | st.push(node); 9 | node=node.left; 10 | }else{ 11 | if(st.isEmpty()) break; 12 | node = st.pop(); 13 | inorder.add(node.val); 14 | node = node.right; 15 | } 16 | } 17 | return inorder; 18 | } 19 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.2 Medium/LeetCode/Sort Colors.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void sortColors(int[] nums) { 3 | if(nums.length == 0) return; 4 | int c0 = 0,c1 = 0,c2 = 0; 5 | for(int i=0;i0){ 13 | nums[i]=0; 14 | i++; 15 | } 16 | while(c1-->0){ 17 | nums[i]=1; 18 | i++; 19 | } 20 | while(c2-->0){ 21 | nums[i]=2; 22 | i++; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Step 04 Binary Search/Step 4.1 Learning BS on 1D Array/LeetCode/Search in Rotated Sorted Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int search(int[] nums, int target) { 3 | int low=0; 4 | int high=nums.length-1; 5 | while(low<=high){ 6 | int mid=(low+high)>>1; 7 | if(nums[mid]==target) return mid; 8 | if(nums[low]<=nums[mid]){ 9 | if(nums[low]<=target && nums[mid]>=target) high=mid-1; 10 | else low=mid+1; 11 | }else{ 12 | if(nums[mid]<=target && target<=nums[high]) low=mid+1; 13 | else high=mid-1; 14 | } 15 | } 16 | return -1; 17 | } 18 | } -------------------------------------------------------------------------------- /Step 04 Binary Search/Step 4.1 Learning BS on 1D Array/LeetCode/Single Element in a Sorted Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int singleNonDuplicate(int[] nums) { 3 | int low=0,high=nums.length-1,mid=-1; 4 | while(low<=high){ 5 | mid=low+(high-low)/2; 6 | if(mid<=nums.length-2 && nums[mid]==nums[mid+1]){ 7 | if(mid%2==0) low=mid+1; 8 | else high=mid-1; 9 | } 10 | else if(mid>=1 && nums[mid]==nums[mid-1]){ 11 | if(mid%2==0) high=mid-1; 12 | else low=mid+1; 13 | } 14 | else return nums[mid]; 15 | } 16 | return -1; 17 | } 18 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.2 Medium/GeeksForGeeks/Leaders in an array.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | //Function to find the leaders in the array. 3 | static ArrayList leaders(int arr[], int n){ 4 | // Your code here 5 | ArrayList array = new ArrayList<>(); 6 | int max = arr[n-1]; 7 | array.add(max); 8 | for(int i=n-2;i>=0;i--){ 9 | if(max<=arr[i]){ 10 | max=arr[i]; 11 | array.add(max); 12 | } 13 | } 14 | ArrayList a = new ArrayList<>(); 15 | for(int i=array.size()-1;i>=0;i--){ 16 | a.add(array.get(i)); 17 | } 18 | return a; 19 | } 20 | } -------------------------------------------------------------------------------- /Step 09 Stack and Queues/Step 9.4 Implementation Problems/GeeksForGeeks/Maximum of all subarrays of size k.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | //Function to find maximum of each subarray of size k. 4 | static ArrayList max_of_subarrays(int arr[], int n, int k) 5 | { 6 | // Your code here 7 | ArrayList ar = new ArrayList<>(); 8 | int max = Integer.MIN_VALUE; 9 | for(int i=0;i al = new ArrayList<>(); 7 | boolean[] b = new boolean[N+1]; 8 | Arrays.fill(b,true); 9 | for(int i=2; i*i<=N; i++){ 10 | for(int j = i*2; j<=N; j+=i) b[j] = false; 11 | } 12 | for(int i=2 ; i<=N; i++){ 13 | if(b[i] == true && N%i == 0) al.add(i); 14 | } 15 | int[] arr = new int[al.size()]; 16 | for(int i=0; ik){ 16 | high = mid-1; 17 | //index = mid-1; 18 | } 19 | } 20 | return index; 21 | } 22 | } -------------------------------------------------------------------------------- /Step 05 strings/Step 5.2 Medium String Problems/LeetCode/Reverse Words in a String.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String reverseWords(String s) { 3 | // String[] words = s.trim().split(" +"); 4 | // Collections.reverse(Arrays.asList(words)); 5 | // return String.join(" ", words); 6 | 7 | String [] words = s.split(" "); 8 | StringBuilder sb = new StringBuilder(); 9 | int end = words.length - 1; 10 | for(int i = 0; i<= end; i++){ 11 | if(!words[i].isEmpty()) { 12 | sb.insert(0, words[i]); 13 | if(i < end) sb.insert(0, " "); 14 | } 15 | } 16 | return sb.toString(); 17 | } 18 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.2 Medium/LeetCode/Best Time to Buy and Sell Stock.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxProfit(int[] prices) { 3 | int dayToBuy = 0; 4 | int profit = 0; 5 | int min = Integer.MAX_VALUE; 6 | int ind1=-1, ind2=-1; 7 | for(int i = 0; i < prices.length; i++) { 8 | if(prices[i] < min) { 9 | min = prices[i]; 10 | ind1=i; 11 | } 12 | 13 | if(prices[i] - min > profit) { 14 | profit = prices[i] - min; 15 | ind2=i; 16 | } 17 | } 18 | System.out.println(ind1+" "+ind2); 19 | 20 | return profit; 21 | } 22 | } -------------------------------------------------------------------------------- /Step 06 LinkedList/Step 6.3 Medium Problem of LL/GeeksForGeeks/Reverse a linked list.java: -------------------------------------------------------------------------------- 1 | /* linked list node class: 2 | 3 | class Node { 4 | int value; 5 | Node next; 6 | Node(int value) { 7 | this.value = value; 8 | } 9 | } 10 | 11 | */ 12 | 13 | class Solution 14 | { 15 | //Function to reverse a linked list. 16 | Node reverseList(Node head) 17 | { 18 | // code here 19 | Node prev=null; 20 | Node cur=head; 21 | Node next=null; 22 | while(cur!=null){ 23 | next=cur.next; 24 | cur.next=prev; 25 | prev=cur; 26 | cur=next; 27 | } 28 | head=prev; 29 | return head; 30 | } 31 | } -------------------------------------------------------------------------------- /Step 12 Greedy Algorithms/Step 12.1 Easy Problems/GeeksForGeeks/Fractional Knapsack.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | //Function to get the maximum total value in the knapsack. 4 | double fractionalKnapsack(int W, Item arr[], int n) 5 | { 6 | // Your code here 7 | Arrays.sort(arr, (a, b) -> b.value*a.weight - a.value*b.weight); 8 | double ans = 0.0; 9 | for(int i=0;i=max) return -1; 17 | step=max-i; 18 | } 19 | } 20 | return jump; 21 | } 22 | } -------------------------------------------------------------------------------- /Step 05 strings/Step 5.1 Basic and Easy String Problems/LeetCode/Reverse Words in a String.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String reverseWords(String s) { 3 | // String[] words = s.trim().split(" +"); 4 | // Collections.reverse(Arrays.asList(words)); 5 | // return String.join(" ", words); 6 | 7 | String [] words = s.split(" "); 8 | StringBuilder sb = new StringBuilder(); 9 | int end = words.length - 1; 10 | for(int i = 0; i<= end; i++){ 11 | if(!words[i].isEmpty()) { 12 | sb.insert(0, words[i]); 13 | if(i < end) sb.insert(0, " "); 14 | } 15 | } 16 | return sb.toString(); 17 | } 18 | } -------------------------------------------------------------------------------- /Step 07 Recursion/Step 7.1 Get a Strong Hold/GeeksForGeeks/Sort a stack.java: -------------------------------------------------------------------------------- 1 | class GfG{ 2 | public Stack sort(Stack s) 3 | { 4 | //add code here. 5 | if(s.size()==1){ 6 | return s; 7 | } 8 | int max = Integer.MIN_VALUE; 9 | Stack st = new Stack<>(); 10 | while(!s.empty()){ 11 | if(s.peek()>max){ 12 | if(max==Integer.MIN_VALUE){ 13 | max=s.peek(); 14 | }else{ 15 | st.push(max); 16 | max=s.peek(); 17 | } 18 | s.pop(); 19 | }else { 20 | 21 | st.push(s.pop()); 22 | } 23 | } 24 | Stack ans= sort(st); 25 | ans.push(max); 26 | return ans; 27 | } 28 | } -------------------------------------------------------------------------------- /Step 10 Sliding Window & Two Pointer Combined Problems/Step 10.1 Medium Problems/LeetCode/Binary Subarrays With Sum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numSubarraysWithSum(int[] nums, int goal) { 3 | int low=0, high=0, ans=0, sum=0, s=0; 4 | for(int i=0;igoal){ 7 | sum-=nums[low]; 8 | low++; 9 | } 10 | s+=nums[i]; 11 | while(highgoal || s==goal && nums[high]==0)){ 12 | s-=nums[high]; 13 | high++; 14 | } 15 | if(sum==goal) ans+=(high-low+1); 16 | } 17 | return ans; 18 | } 19 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.1 Easy/GeeksForGeeks/Intersection of two sorted array.java: -------------------------------------------------------------------------------- 1 | public static void main(String args[]) { 2 | int A[]={1,2,3,3,4,5,6,7}; 3 | int B[]= {3,3,4,4,5,8}; 4 | 5 | ArrayList ans=new ArrayList<>(); 6 | 7 | int i = 0, j = 0; // to traverse the arrays 8 | 9 | while (i < A.length && j < B.length) { 10 | if (A[i] < B[j]) { //if current element in i is smaller 11 | i++; 12 | } else if (B[j] < A[i]) { 13 | j++; 14 | } else { 15 | ans.add(A[i]); //both elements are equal 16 | i++; 17 | j++; 18 | } 19 | } 20 | System.out.print("The elements are: "); 21 | for (i = 0; i < ans.size(); i++) { 22 | System.out.print(ans.get(i)+" "); 23 | } 24 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.2 Medium/GeeksForGeeks/Longest consecutive subsequence.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | // arr[] : the input array 4 | // N : size of the array arr[] 5 | 6 | //Function to return length of longest subsequence of consecutive integers. 7 | static int findLongestConseqSubseq(int arr[], int N) 8 | { 9 | // add your code here 10 | int c=0,l=0; 11 | Arrays.sort(arr); 12 | for (int i=0;il) l=c+1; 17 | c=0; 18 | } 19 | } 20 | if(c+1>l) l=c+1; 21 | return l; 22 | } 23 | } -------------------------------------------------------------------------------- /Step 06 LinkedList/Step 6.3 Medium Problem of LL/LeetCode/Reverse Linked 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 | 12 | class Solution { 13 | public ListNode reverseList(ListNode head) { 14 | ListNode newHead = null; 15 | while (head != null) { 16 | ListNode next = head.next; 17 | head.next = newHead; 18 | newHead = head; 19 | head = next; 20 | } 21 | return newHead; 22 | } 23 | } -------------------------------------------------------------------------------- /Step 07 Recursion/Step 7.2 Subsequence Pattern/GeeksForGeeks/Subset Sums.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | static void func(int ind, int sum, ArrayList < Integer > arr, int N, ArrayList < Integer > sumSubset) { 3 | if (ind == N) { 4 | sumSubset.add(sum); 5 | return; 6 | } 7 | func(ind + 1, sum + arr.get(ind), arr, N, sumSubset); 8 | func(ind + 1, sum, arr, N, sumSubset); 9 | } 10 | 11 | ArrayList subsetSums(ArrayList arr, int N){ 12 | // code here 13 | ArrayList < Integer > sumSubset = new ArrayList < > (); 14 | func(0, 0, arr, N, sumSubset); 15 | Collections.sort(sumSubset); 16 | return sumSubset; 17 | } 18 | } -------------------------------------------------------------------------------- /Step 10 Sliding Window & Two Pointer Combined Problems/Step 10.1 Medium Problems/LeetCode/Count Number of Nice Subarrays.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numberOfSubarrays(int[] nums, int k) { 3 | int n=nums.length; 4 | for(int i=0;i count = new HashMap(); 11 | int ans = 0; 12 | for (int x: P) { 13 | ans += count.getOrDefault(x, 0); 14 | count.put(x+k, count.getOrDefault(x+k, 0) + 1); 15 | } 16 | return ans; 17 | } 18 | } -------------------------------------------------------------------------------- /Step 13 Binary Trees/Step 13.1 Traversals/GeeksForGeeks/Preorder Traversal.java: -------------------------------------------------------------------------------- 1 | class BinaryTree 2 | { 3 | //Function to return a list containing the preorder traversal of the tree. 4 | static ArrayList preorder(Node root) 5 | { 6 | // Code here 7 | ArrayList arr = new ArrayList(); 8 | Stack st = new Stack(); 9 | if(root == null) return arr; 10 | st.push(root); 11 | while(!st.isEmpty()){ 12 | root = st.pop(); 13 | arr.add(root.data); 14 | if(root.right != null) st.push(root.right); 15 | if(root.left != null) st.push(root.left); 16 | } 17 | return arr; 18 | } 19 | 20 | } -------------------------------------------------------------------------------- /Step 04 Binary Search/Step 4.1 Learning BS on 1D Array/GeeksForGeeks/Find out how many times has an array been rotated.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int findKRotation(int arr[], int n) { 3 | // code here 4 | int low = 0; 5 | int high = n-1; 6 | 7 | while(low < high) 8 | { 9 | int mid = low + (high - low)/2; 10 | 11 | if(mid>0 && arr[mid] < arr[mid-1]) 12 | { 13 | return mid; 14 | } 15 | 16 | if(arr[high] > arr[mid]) 17 | { 18 | high = mid-1; 19 | } 20 | else 21 | { 22 | low = mid+1; 23 | } 24 | } 25 | 26 | return low; 27 | } 28 | } -------------------------------------------------------------------------------- /Step 10 Sliding Window & Two Pointer Combined Problems/Step 10.1 Medium Problems/GeeksForGeeks/Count Subarray with k odds.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static int countSubarray(int n, int[] nums, int k) { 3 | // code here 4 | for(int i=0;i count = new HashMap(); 11 | int ans = 0; 12 | for (int x: P) { 13 | ans += count.getOrDefault(x, 0); 14 | count.put(x+k, count.getOrDefault(x+k, 0) + 1); 15 | } 16 | return ans; 17 | } 18 | } -------------------------------------------------------------------------------- /Step 10 Sliding Window & Two Pointer Combined Problems/Step 10.1 Medium Problems/LeetCode/Longest Repeating Character Replacement.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int characterReplacement(String s, int k) { 3 | int len = s.length(); 4 | int[] count = new int[26]; 5 | int start = 0, maxCount = 0, maxLength = 0; 6 | for (int end = 0; end < len; end++) { 7 | maxCount = Math.max(maxCount, ++count[s.charAt(end) - 'A']); 8 | while (end - start + 1 - maxCount > k) { 9 | count[s.charAt(start) - 'A']--; 10 | start++; 11 | } 12 | maxLength = Math.max(maxLength, end - start + 1); 13 | } 14 | return maxLength; 15 | } 16 | } -------------------------------------------------------------------------------- /Step 06 LinkedList/Step 6.3 Medium Problem of LL/LeetCode/Linked List Cycle.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public boolean hasCycle(ListNode head) { 14 | if(head == null) return false; 15 | ListNode fast = head; 16 | ListNode slow = head; 17 | 18 | while(fast.next != null && fast.next.next != null) { 19 | fast = fast.next.next; 20 | slow = slow.next; 21 | if(fast == slow) return true; 22 | } 23 | return false; 24 | } 25 | } -------------------------------------------------------------------------------- /Step 09 Stack and Queues/Step 9.4 Implementation Problems/GeeksForGeeks/Stock span problem.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | //Function to calculate the span of stock’s price for all n days. 4 | public static int[] calculateSpan(int price[], int n) 5 | { 6 | // Your code here 7 | ArrayDeque arr = new ArrayDeque<>(); 8 | arr.push(0); 9 | int[] ans = new int[n]; 10 | ans[0]=1; 11 | for(int i=1;i wordDict) { 3 | int n = s.length(); 4 | boolean[] visited = new boolean[n+1]; 5 | return visit(s, 0, wordDict, visited); 6 | } 7 | 8 | private boolean visit(String s, int p, List wordDict, boolean[] visited) { 9 | if (p == s.length()) return true; 10 | visited[p] = true; 11 | for (String word: wordDict) { 12 | if (s.startsWith(word, p) && !visited[p + word.length()] ) { 13 | if (visit(s, p + word.length(), wordDict, visited)) return true; 14 | } 15 | } 16 | return false; 17 | } 18 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.2 Medium/LeetCode/Longest Consecutive Sequence.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int longestConsecutive(int[] nums) { 3 | if(nums.length == 0) return 0; 4 | HashSet hs = new HashSet<>(); 5 | int c=0; 6 | for(int i=0;i sieveOfEratosthenes(int n){ 3 | // code here 4 | boolean prime[] = new boolean[n + 1]; 5 | for (int i = 0; i <= n; i++) 6 | prime[i] = true; 7 | for (int p = 2; p * p <= n; p++) { 8 | if (prime[p] == true) { 9 | for (int i = p * p; i <= n; i += p) 10 | prime[i] = false; 11 | } 12 | } 13 | ArrayList arr = new ArrayList<>(); 14 | for (int i = 2; i <= n; i++) { 15 | if (prime[i] == true) 16 | arr.add(i); 17 | } 18 | return arr; 19 | } 20 | } -------------------------------------------------------------------------------- /Step 09 Stack and Queues/Step 9.3 Monotonic stack ans Queue Problems/GeeksForGeeks/Stock span problem.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | //Function to calculate the span of stock’s price for all n days. 4 | public static int[] calculateSpan(int price[], int n) 5 | { 6 | // Your code here 7 | ArrayDeque arr = new ArrayDeque<>(); 8 | arr.push(0); 9 | int[] ans = new int[n]; 10 | ans[0]=1; 11 | for(int i=1;i pq = new PriorityQueue<>(); 5 | int[] ar = new int[n]; 6 | for(int i=0;ik){ 17 | pq.poll(); 18 | } 19 | j++; 20 | } 21 | ar[n-1]=pq.peek(); 22 | return ar; 23 | } 24 | }; -------------------------------------------------------------------------------- /Step 04 Binary Search/Step 4.3 Find Answers by BS in Search Space/GeeksForGeeks/Median of 2 Sorted Arrays of Different Sizes.java: -------------------------------------------------------------------------------- 1 | class GFG 2 | { 3 | static double medianOfArrays(int n, int m, int a[], int b[]) 4 | { 5 | // Your Code Here 6 | int arr[]=new int[n+m]; 7 | System.arraycopy(a,0,arr,0,n); 8 | System.arraycopy(b,0,arr,n,m); 9 | Arrays.sort(arr); 10 | int size=arr.length; 11 | if(size%2==0){ 12 | int z=size/2; 13 | int e=arr[z]; 14 | int q=arr[z-1]; 15 | double ans=(double)(e+q)/2; 16 | return ans; 17 | }else{ 18 | int z=Math.round(size/2); 19 | return arr[z]; 20 | } 21 | 22 | } 23 | } -------------------------------------------------------------------------------- /Step 13 Binary Trees/Step 13.1 Traversals/GeeksForGeeks/Inorder Traversal.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // Function to return a list containing the inorder traversal of the tree. 3 | ArrayList inOrder(Node root) { 4 | // Code 5 | ArrayList arr = new ArrayList<>(); 6 | Stack st = new Stack(); 7 | Node node = root; 8 | while(true){ 9 | if(node!=null){ 10 | st.push(node); 11 | node=node.left; 12 | }else{ 13 | if(st.isEmpty()) break; 14 | node = st.pop(); 15 | arr.add(node.data); 16 | node=node.right; 17 | } 18 | } 19 | return arr; 20 | } 21 | } -------------------------------------------------------------------------------- /Step 05 strings/Step 5.2 Medium String Problems/GeeksForGeeks/Count number of substrings.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | long substrCount (String S, int K) { 4 | // your code here 5 | return helper(S,K) - helper(S,K-1); 6 | } 7 | 8 | long helper(String S, int K){ 9 | long[] ans = new long[26]; 10 | long s=0, c=0, d=0; 11 | for(int i=0;iK){ 15 | ans[S.charAt((int)s)-'a']--; 16 | if(ans[S.charAt((int)s)-'a']==0) d--; 17 | s++; 18 | } 19 | if(d<=K) c=c+i-s+1; 20 | } 21 | return c; 22 | } 23 | } -------------------------------------------------------------------------------- /Step 06 LinkedList/Step 6.3 Medium Problem of LL/LeetCode/Intersection of Two Linked Lists.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public ListNode getIntersectionNode(ListNode headA, ListNode headB) { 14 | if(headA == null || headB == null) return null; 15 | 16 | ListNode a = headA; 17 | ListNode b = headB; 18 | 19 | while( a != b){ 20 | a = a == null? headB : a.next; 21 | b = b == null? headA : b.next; 22 | } 23 | 24 | return a; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.1 Easy/GeeksForGeeks/Search in a matrix.java: -------------------------------------------------------------------------------- 1 | class Sol 2 | { 3 | public static int matSearch(int mat[][], int N, int M, int X) 4 | { 5 | // your code here 6 | 7 | for(int i=0;iX) 20 | { 21 | high=mid-1; 22 | } 23 | } 24 | } 25 | return 0; 26 | } 27 | } -------------------------------------------------------------------------------- /Step 09 Stack and Queues/Step 9.4 Implementation Problems/LeetCode/Sliding Window Maximum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] maxSlidingWindow(int[] a, int k) { 3 | int n = a.length; 4 | int[] r = new int[n - k + 1]; 5 | int ri = 0; 6 | Deque < Integer > q = new ArrayDeque < > (); 7 | for (int i = 0; i < a.length; i++) { 8 | if (!q.isEmpty() && q.peek() == i - k) { 9 | q.poll(); 10 | } 11 | while (!q.isEmpty() && a[q.peekLast()] < a[i]) { 12 | q.pollLast(); 13 | } 14 | 15 | q.offer(i); 16 | if (i >= k - 1) { 17 | r[ri++] = a[q.peek()]; 18 | } 19 | } 20 | return r; 21 | } 22 | } -------------------------------------------------------------------------------- /Step 11 Heaps/Step 11.2 Medium Problems/LeetCode/Hand of Straights.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isNStraightHand(int[] hand, int groupSize) { 3 | if(hand.length%groupSize != 0) return false; 4 | TreeMap map = new TreeMap<>(); 5 | for(int i=0;i postorderTraversal(TreeNode root) { 3 | Stack st1 = new Stack<>(); 4 | Stack st2 = new Stack<>(); 5 | List postorder = new ArrayList<>(); 6 | if(root == null) return postorder; 7 | st1.push(root); 8 | while(!st1.isEmpty()){ 9 | root = st1.pop(); 10 | st2.add(root); 11 | if(root.left != null) st1.push(root.left); 12 | if(root.right != null) st1.push(root.right); 13 | } 14 | while(!st2.isEmpty()){ 15 | postorder.add(st2.pop().val); 16 | } 17 | return postorder; 18 | } 19 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.2 Medium/GeeksForGeeks/Majority Element.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | static int majorityElement(int a[], int size) 4 | { 5 | // your code here 6 | Map map = new HashMap<>(); 7 | for(int i=0;i entry: map.entrySet()){ 18 | if(entry.getValue()>n){ 19 | num = entry.getKey(); 20 | } 21 | } 22 | return num; 23 | } 24 | } -------------------------------------------------------------------------------- /Step 06 LinkedList/Step 6.2 Doubly Linked List/GeeksForGeeks/Delete node in Doubly Linked List.java: -------------------------------------------------------------------------------- 1 | /* Structure of linkedlist node 2 | class Node 3 | { 4 | int data; 5 | Node next; 6 | Node prev; 7 | Node(int d) 8 | { 9 | data = d; 10 | next = prev = null; 11 | } 12 | } 13 | */ 14 | class Solution 15 | { 16 | // function returns the head of the linkedlist 17 | Node deleteNode(Node head,int x) 18 | { 19 | // Your code here 20 | if(head==null || head.next==null) return null; 21 | if(x==1){ 22 | head=head.next; 23 | head.prev=null; 24 | return head; 25 | } 26 | Node cur=head; 27 | for(int i=0;ic){ 22 | return -1; 23 | } 24 | c=c-n; 25 | if(c<0) return -1; 26 | Node t = head; 27 | while(c!=0){ 28 | t=t.next; 29 | c=c-1; 30 | } 31 | return t.data; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Step 10 Sliding Window & Two Pointer Combined Problems/Step 10.2 Hard Problems/GeeksForGeeks/Longest K unique characters substring.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int longestkSubstr(String s, int k) { 3 | // code here 4 | HashSet hs = new HashSet<>(); 5 | int[] count = new int[26]; 6 | int ans=-1, c=0, n=s.length(), j=0; 7 | for(int i=0;ik){ 11 | count[s.charAt(j)-'a']--; 12 | if(count[s.charAt(j)-'a']==0) hs.remove(s.charAt(j)); 13 | j++; 14 | } 15 | if(hs.size()==k) ans=Math.max(ans, i-j+1); 16 | } 17 | return ans; 18 | } 19 | } -------------------------------------------------------------------------------- /Step 12 Greedy Algorithms/Step 12.2 Medium-Hard Problems/LeetCode/Insert Interval.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[][] insert(int[][] intervals, int[] newInterval) { 3 | List list = new ArrayList<>(); 4 | for (int[] in : intervals) { 5 | if (newInterval[0]>in[1]) { 6 | list.add(in); 7 | } 8 | else if(newInterval[1]> subsetsWithDup(int[] nums) { 3 | Arrays.sort(nums); 4 | List> ansList = new ArrayList<>(); 5 | findSubsets(0, nums, new ArrayList<>(), ansList); 6 | return ansList; 7 | } 8 | 9 | public static void findSubsets(int ind, int[] nums, List ds, List> ansList) { 10 | ansList.add(new ArrayList<>(ds)); 11 | for(int i = ind;i> levelOrder(TreeNode root) { 3 | Queue q = new LinkedList<>(); 4 | List> list = new LinkedList<>(); 5 | if(root == null) return list; 6 | q.offer(root); 7 | while(!q.isEmpty()){ 8 | int l=q.size(); 9 | List sub = new LinkedList<>(); 10 | for(int i=0;i findUnion(int arr1[], int arr2[], int n, int m) 5 | { 6 | // add your code here 7 | HashMap freq=new HashMap<>(); 8 | ArrayList Union=new ArrayList<>(); 9 | for (int i = 0; i < n; i++) 10 | freq.put(arr1[i],freq.getOrDefault(arr1[i],0)+1); 11 | 12 | for (int i = 0; i < m; i++) 13 | freq.put(arr2[i],freq.getOrDefault(arr2[i],0)+1); 14 | 15 | for (int it: freq.keySet()) 16 | Union.add(it); 17 | Collections.sort(Union); 18 | return Union; 19 | } 20 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.2 Medium/GeeksForGeeks/Sort an array of 0s, 1s and 2s.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public static void sort012(int a[], int n) 4 | { 5 | // code here 6 | int arr[] = new int[n]; 7 | int j=0; 8 | for(int i=0;i mid) { 12 | need += 1; 13 | cur = 0; 14 | } 15 | cur += w; 16 | } 17 | if (need > days) left = mid + 1; 18 | else right = mid; 19 | } 20 | return left; 21 | } 22 | } -------------------------------------------------------------------------------- /Step 09 Stack and Queues/Step 9.1 Learning/GeeksForGeeks/Queue using stack.java: -------------------------------------------------------------------------------- 1 | class Queue 2 | { 3 | Stack input = new Stack(); 4 | Stack output = new Stack(); 5 | 6 | /*The method pop which return the element poped out of the stack*/ 7 | int dequeue() 8 | { 9 | // Your code here 10 | if(output.empty()){ 11 | while(input.empty()==false){ 12 | output.push(input.peek()); 13 | input.pop(); 14 | } 15 | } 16 | int x=output.peek(); 17 | output.pop(); 18 | return x; 19 | } 20 | 21 | /* The method push to push element into the stack */ 22 | void enqueue(int x) 23 | { 24 | // Your code here 25 | input.add(x); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Step 13 Binary Trees/Step 13.2 Medium Problems/GeeksForGeeks/Check for Balanced Tree.java: -------------------------------------------------------------------------------- 1 | class Tree 2 | { 3 | 4 | //Function to check whether a binary tree is balanced or not. 5 | public static int height(Node root){ 6 | if(root == null) return 0; 7 | int l = height(root.left); 8 | int r = height(root.right); 9 | return 1+Math.max(l,r); 10 | } 11 | boolean isBalanced(Node root) 12 | { 13 | // Your code here 14 | if(root == null) return true; 15 | int l = height(root.left); 16 | int r = height(root.right); 17 | if(Math.abs(r-l) > 1) return false; 18 | boolean left = isBalanced(root.left); 19 | boolean right = isBalanced(root.right); 20 | if(left==false || right==false) return false; 21 | return true; 22 | } 23 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.2 Medium/GeeksForGeeks/Rotate by 90 degree.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | //Function to rotate matrix anticlockwise by 90 degrees. 4 | static void rotateby90(int matrix[][], int n) 5 | { 6 | // code here 7 | int[][] ans = new int[n][n]; 8 | for(int i=0;imax) max = arr[k]; 15 | if(arr[k]!=0 && arr[k]> combinationSum3(int k, int n) { 3 | List> ans = new ArrayList<>(); 4 | combination(ans, new ArrayList(), k, 1, n); 5 | return ans; 6 | } 7 | 8 | public static void combination(List> ans, List comb, int k, int start, int n) { 9 | if (comb.size() == k && n == 0) { 10 | List li = new ArrayList(comb); 11 | ans.add(li); 12 | return; 13 | } 14 | for (int i = start; i <= 9; i++) { 15 | comb.add(i); 16 | combination(ans, comb, k, i+1, n-i); 17 | comb.remove(comb.size() - 1); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.1 Easy/LeetCode/Search a 2D Matrix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean searchMatrix(int[][] matrix, int target) { 3 | int m = matrix.length; 4 | int n = matrix[0].length; 5 | int index = -1; 6 | for(int i=0;i=target){ 8 | index = i; 9 | break; 10 | } 11 | } 12 | if(index == -1) return false; 13 | int low = 0; 14 | int high = n-1; 15 | while(low<=high){ 16 | int mid=(low+high)/2; 17 | if(matrix[index][mid] == target) return true; 18 | else if(matrix[index][mid] > target) high=mid-1; 19 | else if(matrix[index][mid] < target) low=mid+1; 20 | } 21 | return false; 22 | } 23 | } -------------------------------------------------------------------------------- /Step 04 Binary Search/Step 4.2 Applying BS on 2D Array/LeetCode/Find a Peak Element II.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] findPeakGrid(int[][] mat) { 3 | int start=0; 4 | int end=mat[0].length-1; 5 | while(start<=end){ 6 | int mid=start+(end-start)/2; 7 | int row=0; 8 | for(int i=1; imat[row][mid-1]) && (mid==end||mat[row][mid]>mat[row][mid+1])) 13 | return new int[]{row,mid}; 14 | else if(mat[row][mid] st = new Stack < > (); 4 | int maxA = 0; 5 | int n = histo.length; 6 | for (int i = 0; i <= n; i++) { 7 | while (!st.empty() && (i == n || histo[st.peek()] >= histo[i])) { 8 | int height = histo[st.peek()]; 9 | st.pop(); 10 | int width; 11 | if (st.empty()) 12 | width = i; 13 | else 14 | width = i - st.peek() - 1; 15 | maxA = Math.max(maxA, width * height); 16 | } 17 | st.push(i); 18 | } 19 | return maxA; 20 | } 21 | } -------------------------------------------------------------------------------- /Step 11 Heaps/Step 11.2 Medium Problems/GeeksForGeeks/Merge K sorted linked lists.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | //Function to merge K sorted linked list. 4 | Node mergeKList(Node[]arr,int K) 5 | { 6 | //Add your code here. 7 | Node temp = new Node(-1); 8 | Node cur = temp; 9 | ArrayList list = new ArrayList<>(); 10 | 11 | for(int i=0;i postOrder(Node root) 5 | { 6 | // Your code goes here 7 | ArrayList arr = new ArrayList<>(); 8 | Stack st = new Stack<>(); 9 | Stack st2 = new Stack<>(); 10 | if(root == null) return arr; 11 | st.push(root); 12 | while(!st.isEmpty()){ 13 | root = st.pop(); 14 | st2.add(root); 15 | if(root.left != null) st.push(root.left); 16 | if(root.right != null) st.push(root.right); 17 | } 18 | while(!st2.isEmpty()){ 19 | arr.add(st2.pop().data); 20 | } 21 | return arr; 22 | } 23 | } -------------------------------------------------------------------------------- /Step 04 Binary Search/Step 4.2 Applying BS on 2D Array/LeetCode/Search a 2D Matrix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean searchMatrix(int[][] matrix, int target) { 3 | int m = matrix.length; 4 | int n = matrix[0].length; 5 | int index = -1; 6 | for(int i=0;i=target){ 8 | index = i; 9 | break; 10 | } 11 | } 12 | if(index == -1) return false; 13 | int low = 0; 14 | int high = n-1; 15 | while(low<=high){ 16 | int mid=(low+high)/2; 17 | if(matrix[index][mid] == target) return true; 18 | else if(matrix[index][mid] > target) high=mid-1; 19 | else if(matrix[index][mid] < target) low=mid+1; 20 | } 21 | return false; 22 | } 23 | } -------------------------------------------------------------------------------- /Step 05 strings/Step 5.1 Basic and Easy String Problems/GeeksForGeeks/Longest Common Prefix in an Array.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | String longestCommonPrefix(String arr[], int n){ 3 | // code here 4 | String ans=""; 5 | int l=arr[0].length(); 6 | for(int j=1;jarr[j].length()){ 8 | l=arr[j].length(); 9 | } 10 | } 11 | for(int i=0;i= '0' && s.charAt(i) <= '9') { 16 | if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && s.charAt(i) - '0' > 7)) { 17 | if (sign == -1) { 18 | return Integer.MIN_VALUE; 19 | } 20 | return Integer.MAX_VALUE; 21 | } 22 | res = res * 10 + (s.charAt(i++) - '0'); 23 | } 24 | return sign * res; 25 | 26 | } 27 | } -------------------------------------------------------------------------------- /Step 05 strings/Step 5.2 Medium String Problems/LeetCode/String to Integer (atoi).java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int myAtoi(String s) { 3 | if (s.equals("")) { 4 | return 0; 5 | } 6 | int res = 0, i = 0, sign = 1; 7 | while (i < s.length() && s.charAt(i) == ' ') { 8 | i++; 9 | } 10 | if (i < s.length() && (s.charAt(i) == '+' || s.charAt(i) == '-')) { 11 | if (s.charAt(i++) == '-') { 12 | sign = -1; 13 | } 14 | } 15 | while (i < s.length() && s.charAt(i) >= '0' && s.charAt(i) <= '9') { 16 | if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && s.charAt(i) - '0' > 7)) { 17 | if (sign == -1) { 18 | return Integer.MIN_VALUE; 19 | } 20 | return Integer.MAX_VALUE; 21 | } 22 | res = res * 10 + (s.charAt(i++) - '0'); 23 | } 24 | return sign * res; 25 | 26 | } 27 | } -------------------------------------------------------------------------------- /Step 09 Stack and Queues/Step 9.1 Learning/GeeksForGeeks/Stack using two queues.java: -------------------------------------------------------------------------------- 1 | class Queues 2 | { 3 | Queue q1 = new LinkedList(); 4 | Queue q2 = new LinkedList(); 5 | 6 | //Function to push an element into stack using two queues. 7 | void push(int a) 8 | { 9 | // Your code here 10 | q1.add(a); 11 | } 12 | 13 | //Function to pop an element from stack using two queues. 14 | int pop() 15 | { 16 | // Your code here 17 | int pop=-1; 18 | if(!q1.isEmpty()){ 19 | while(q1.size()!=1){ 20 | q2.add(q1.poll()); 21 | } 22 | pop=q1.poll(); 23 | while(!q2.isEmpty()){ 24 | q1.add(q2.poll()); 25 | } 26 | } 27 | return pop; 28 | } 29 | 30 | } -------------------------------------------------------------------------------- /Step 04 Binary Search/Step 4.3 Find Answers by BS in Search Space/LeetCode/Koko Eating Bananas.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minEatingSpeed(int[] piles, int h) { 3 | int start=1;// because koko will definitely eat one banana. 4 | int end=Integer.MAX_VALUE; 5 | while(start<=end){ 6 | int sph=start+(end-start)/2; 7 | if(hoursTaken(piles,h,sph)) 8 | start=sph+1; 9 | else 10 | end=sph-1; 11 | } 12 | return start; 13 | } 14 | 15 | static boolean hoursTaken(int[] piles,int h,int sph){ 16 | int hours=0; 17 | for(int pile:piles){ 18 | int d=pile/sph ; 19 | hours+=d; 20 | int r=pile%sph; 21 | if(r!=0) hours++; 22 | } 23 | return hours>h; 24 | } 25 | } -------------------------------------------------------------------------------- /Step 10 Sliding Window & Two Pointer Combined Problems/Step 10.2 Hard Problems/LeetCode/Subarrays with K Different Integers.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int subarraysWithKDistinct(int[] nums, int k) { 3 | return help(nums, k) - help(nums, k - 1); 4 | } 5 | 6 | public int help(int[] nums, int k) { 7 | int i = 0, res = 0; 8 | Map map = new HashMap<>(); 9 | for (int j = 0; j < nums.length; ++j) { 10 | if (map.getOrDefault(nums[j], 0) == 0) k--; 11 | map.put(nums[j], map.getOrDefault(nums[j], 0) + 1); 12 | while (k < 0) { 13 | map.put(nums[i], map.get(nums[i]) - 1); 14 | if (map.get(nums[i]) == 0) k++; 15 | i++; 16 | } 17 | res += j - i + 1; 18 | } 19 | return res; 20 | } 21 | } -------------------------------------------------------------------------------- /Step 07 Recursion/Step 7.2 Subsequence Pattern/GeeksForGeeks/Possible Words From Phone Digits.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | static ArrayList list; 4 | static String[] words = {"0", "0", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; 5 | //Function to find list of all words possible by pressing given numbers. 6 | static ArrayList possibleWords(int a[], int N) 7 | { 8 | // your code here 9 | list = new ArrayList<>(); 10 | help(a, 0, ""); 11 | return list; 12 | } 13 | 14 | static void help(int[] a, int c, String str){ 15 | if(c==a.length){ 16 | list.add(str); 17 | return; 18 | } 19 | String key = words[a[c]]; 20 | for(int i=0;im){ 15 | u=mid-1; 16 | } 17 | else{ 18 | l=mid+1; 19 | } 20 | } 21 | return -1; 22 | 23 | 24 | // if(n==0) return m; 25 | // for(int i=1; i<=m; i++){ 26 | // if(Math.pow(i,n) == m) return i; 27 | // else if(Math.pow(i,n) > m) return -1; 28 | // } 29 | // return -1; 30 | } 31 | } -------------------------------------------------------------------------------- /Step 11 Heaps/Step 11.3 Hard Problems/LeetCode/Kth Largest Element in a Stream.java: -------------------------------------------------------------------------------- 1 | class KthLargest { 2 | private static int k; 3 | private PriorityQueue heap; 4 | 5 | public KthLargest(int k, int[] nums) { 6 | this.k = k; 7 | heap = new PriorityQueue<>(); 8 | 9 | for (int num: nums) { 10 | heap.offer(num); 11 | } 12 | 13 | while (heap.size() > k) { 14 | heap.poll(); 15 | } 16 | } 17 | 18 | public int add(int val) { 19 | heap.offer(val); 20 | if (heap.size() > k) { 21 | heap.poll(); 22 | } 23 | 24 | return heap.peek(); 25 | } 26 | } 27 | 28 | /** 29 | * Your KthLargest object will be instantiated and called as such: 30 | * KthLargest obj = new KthLargest(k, nums); 31 | * int param_1 = obj.add(val); 32 | */ -------------------------------------------------------------------------------- /Step 05 strings/Step 5.2 Medium String Problems/LeetCode/Roman to Integer.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int romanToInt(String s) { 3 | HashMap map = new HashMap<>(); 4 | map.put('I',1); 5 | map.put('V',5); 6 | map.put('X',10); 7 | map.put('L',50); 8 | map.put('C',100); 9 | map.put('D',500); 10 | map.put('M',1000); 11 | 12 | int res=0,i; 13 | for(i=0;i freq = new HashMap<>(); 4 | for(int num : nums) { 5 | freq.put(num, freq.getOrDefault(num, 0) + 1); 6 | } 7 | 8 | PriorityQueue> pq = new PriorityQueue<>((a, b) -> Integer.compare(a.getValue(), b.getValue())); 9 | 10 | for(Map.Entry entry : freq.entrySet()) { 11 | pq.add(entry); 12 | while(pq.size() > k) { 13 | pq.poll(); 14 | } 15 | } 16 | 17 | int[] res = new int[k]; 18 | int i = 0; 19 | while(!pq.isEmpty()) { 20 | res[i++] = pq.poll().getKey(); 21 | } 22 | return res; 23 | } 24 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.1 Easy/GeeksForGeeks/Find the element that appears once.java: -------------------------------------------------------------------------------- 1 | class Sol 2 | { 3 | public static int search(int A[], int N) 4 | { 5 | // your code here 6 | // int ans = 0; 7 | // for(int i=0;i row = new HashSet(); 4 | HashSet col = new HashSet<>(); 5 | int m = matrix.length; 6 | int n = matrix[0].length; 7 | for(int i=0;i st = new Stack<>(); 4 | StringBuilder sb = new StringBuilder(); 5 | for(int i=0;i0 && !st.isEmpty() && st.peek()>ch){ 8 | st.pop(); 9 | k--; 10 | } 11 | if(st.isEmpty() && ch=='0') continue; 12 | st.push(ch); 13 | } 14 | while(k>0 && !st.isEmpty()){ 15 | st.pop(); 16 | k--; 17 | } 18 | if(st.isEmpty()) return "0"; 19 | while(!st.isEmpty()){ 20 | sb.append(st.peek()); 21 | st.pop(); 22 | } 23 | return sb.reverse().toString(); 24 | } 25 | } -------------------------------------------------------------------------------- /Step 06 LinkedList/Step 6.3 Medium Problem of LL/GeeksForGeeks/Find length of Loop.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | class Node 4 | { 5 | int data; 6 | Node next; 7 | Node(int d) {data = d; next = null; } 8 | } 9 | 10 | */ 11 | 12 | //Function should return the length of the loop in LL. 13 | 14 | class Solution 15 | { 16 | //Function to find the length of a loop in the linked list. 17 | static int countNodesinLoop(Node head) 18 | { 19 | //Add your code here. 20 | Node slow = head, fast = head.next; 21 | while(fast != slow){ 22 | if(fast == null || fast.next == null) return 0; 23 | fast = fast.next.next; 24 | slow = slow.next; 25 | } 26 | int ans = 1; 27 | fast = fast.next; 28 | while(fast!=slow){ 29 | fast = fast.next; 30 | ans++; 31 | } 32 | return ans; 33 | } 34 | } -------------------------------------------------------------------------------- /Step 11 Heaps/Step 11.3 Hard Problems/LeetCode/Find Median from Data Stream.java: -------------------------------------------------------------------------------- 1 | class MedianFinder { 2 | PriorityQueue maxheap=new PriorityQueue(Collections.reverseOrder()); 3 | PriorityQueue minheap=new PriorityQueue(); 4 | 5 | public MedianFinder() { 6 | 7 | } 8 | 9 | public void addNum(int num) { 10 | if(maxheap.isEmpty()||maxheap.peek()>=num) 11 | maxheap.add(num); 12 | else 13 | minheap.add(num); 14 | 15 | if(maxheap.size()>minheap.size()+1) 16 | minheap.add(maxheap.poll()); 17 | else if(maxheap.size() st = new Stack<>(); 4 | for(int num: asteroids){ 5 | collision: { 6 | while(!st.isEmpty() && num<0 && 0=0;i--){ 21 | ans[i]=st.pop(); 22 | } 23 | return ans; 24 | } 25 | } -------------------------------------------------------------------------------- /Step 04 Binary Search/Step 4.1 Learning BS on 1D Array/GeeksForGeeks/Search in a Rotated Array.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | int search(int A[], int l, int h, int key) 4 | { 5 | // Complete this function 6 | int index=0; 7 | for(int i=0;iA[i+1]){ 9 | index=i; 10 | break; 11 | } 12 | } 13 | int low=l,high=index; 14 | while(low<=high){ 15 | int mid=(low+high)/2; 16 | if(A[mid]==key) return mid; 17 | if(A[mid] st = new Stack<>(); 8 | for(int i=0;i0 && st.peek()=='(') st.pop(); 12 | else return false; 13 | }else if(ch=='}'){ 14 | if(st.size()>0 && st.peek()=='{') st.pop(); 15 | else return false; 16 | }else if(ch==']'){ 17 | if(st.size()>0 && st.peek()=='[') st.pop(); 18 | else return false; 19 | }else st.push(ch); 20 | } 21 | if(st.size()==0) return true; 22 | else return false; 23 | } 24 | } -------------------------------------------------------------------------------- /Step 12 Greedy Algorithms/Step 12.2 Medium-Hard Problems/LeetCode/Candy.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int candy(int[] ratings) { 3 | int sum = 0; 4 | int[] left2right = new int[ratings.length]; 5 | int[] right2left = new int[ratings.length]; 6 | Arrays.fill(left2right, 1); 7 | Arrays.fill(right2left, 1); 8 | for (int i = 1; i < ratings.length; i++) { 9 | if (ratings[i] > ratings[i - 1]) { 10 | left2right[i] = left2right[i - 1] + 1; 11 | } 12 | } 13 | for (int i = ratings.length - 2; i >= 0; i--) { 14 | if (ratings[i] > ratings[i + 1]) { 15 | right2left[i] = right2left[i + 1] + 1; 16 | } 17 | } 18 | for (int i = 0; i < ratings.length; i++) { 19 | sum += Math.max(left2right[i], right2left[i]); 20 | } 21 | return sum; 22 | } 23 | } -------------------------------------------------------------------------------- /Step 12 Greedy Algorithms/Step 12.1 Easy Problems/GeeksForGeeks/Parenthesis Checker.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | //Function to check if brackets are balanced or not. 4 | static boolean ispar(String x) 5 | { 6 | // add your code here 7 | Stack st = new Stack<>(); 8 | for(int i=0;i0 && st.peek()=='(') st.pop(); 12 | else return false; 13 | }else if(ch=='}'){ 14 | if(st.size()>0 && st.peek()=='{') st.pop(); 15 | else return false; 16 | }else if(ch==']'){ 17 | if(st.size()>0 && st.peek()=='[') st.pop(); 18 | else return false; 19 | }else st.push(ch); 20 | } 21 | if(st.size()==0) return true; 22 | else return false; 23 | } 24 | } -------------------------------------------------------------------------------- /Step 04 Binary Search/Step 4.3 Find Answers by BS in Search Space/LeetCode/Find the Smallest Divisor Given a Threshold.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int smallestDivisor(int[] nums, int threshold) { 3 | int low=1, high=Integer.MIN_VALUE; 4 | for(int i=0;i arr1 = new ArrayList<>(); 5 | ArrayList arr2 = new ArrayList<>(); 6 | for(int i=0;i> combinationSum(int[] candidates, int target) { 3 | List < List < Integer >> ans = new ArrayList < > (); 4 | findCombinations(0, candidates, target, ans, new ArrayList < > ()); 5 | return ans; 6 | } 7 | 8 | private void findCombinations(int ind, int[] arr, int target, List < List < Integer >> ans, List < Integer > ds) { 9 | if (ind == arr.length) { 10 | if (target == 0) { 11 | ans.add(new ArrayList < > (ds)); 12 | } 13 | return; 14 | } 15 | 16 | if (arr[ind] <= target) { 17 | ds.add(arr[ind]); 18 | findCombinations(ind, arr, target - arr[ind], ans, ds); 19 | ds.remove(ds.size() - 1); 20 | } 21 | findCombinations(ind + 1, arr, target, ans, ds); 22 | } 23 | } -------------------------------------------------------------------------------- /Step 09 Stack and Queues/Step 9.3 Monotonic stack ans Queue Problems/GeeksForGeeks/Trapping Rain Water.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Solution{ 4 | 5 | // arr: input array 6 | // n: size of array 7 | // Function to find the trapped water between the blocks. 8 | static long trappingWater(int arr[], int n) { 9 | // Your code here 10 | int l=0, r=n-1, lmax=0, rmax=0; 11 | long c=0; 12 | while(l=lmax){ 15 | lmax=arr[l]; 16 | }else{ 17 | c+=lmax-arr[l]; 18 | } 19 | l++; 20 | }else{ 21 | if(arr[r]>=rmax){ 22 | rmax=arr[r]; 23 | }else{ 24 | c+=rmax-arr[r]; 25 | } 26 | r--; 27 | } 28 | } 29 | return c; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Step 06 LinkedList/Step 6.3 Medium Problem of LL/GeeksForGeeks/Segregate even and odd nodes in a Link List.java: -------------------------------------------------------------------------------- 1 | /* 2 | class Node{ 3 | int data; 4 | Node next; 5 | 6 | Node(int x){ 7 | data = x; 8 | next = null; 9 | } 10 | } 11 | */ 12 | 13 | class Solution{ 14 | Node divide(int N, Node head){ 15 | // code here 16 | Node odd = new Node(-1); 17 | Node even = new Node(-1); 18 | Node curr = even; 19 | even.next = head; 20 | Node curr2 = odd; 21 | 22 | while(curr.next!=null){ 23 | if((curr.next.data&1)==1){ 24 | curr2.next = curr.next; 25 | curr.next = curr.next.next; 26 | curr2 = curr2.next; 27 | }else 28 | curr = curr.next; 29 | } 30 | curr2.next = null; 31 | 32 | curr.next = odd.next; 33 | return even.next; 34 | } 35 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.1 Easy/GeeksForGeeks/Rotating an Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | void leftRotate(int[] arr, int n, int k) { 3 | // code here 4 | k=k%n; 5 | int low=0; 6 | int high=k-1; 7 | while(low0;j--) 23 | slow=slow.next; 24 | 25 | fast.next=dummy.next; 26 | dummy.next=slow.next; 27 | slow.next=null; 28 | 29 | return dummy.next; 30 | } 31 | } -------------------------------------------------------------------------------- /Step 13 Binary Trees/Step 13.2 Medium Problems/GeeksForGeeks/Left View of Binary Tree.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | //User function Template for Java 4 | 5 | /* A Binary Tree node 6 | class Node 7 | { 8 | int data; 9 | Node left, right; 10 | 11 | Node(int item) 12 | { 13 | data = item; 14 | left = right = null; 15 | } 16 | }*/ 17 | class Tree 18 | { 19 | //Function to return list containing elements of left view of binary tree. 20 | ArrayList leftView(Node root) 21 | { 22 | // Your code here 23 | ArrayList list = new ArrayList<>(); 24 | View(root, list, 0); 25 | return list; 26 | } 27 | 28 | public static void View(Node curr, ArrayList list, int level){ 29 | if(curr == null) return; 30 | if(list.size() == level) list.add(curr.data); 31 | View(curr.left, list, level+1); 32 | View(curr.right, list, level+1); 33 | } 34 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.3 Hard/GeeksForGeeks/Pairwise swap elements of a linked list.java: -------------------------------------------------------------------------------- 1 | class Node 2 | { 3 | int data; 4 | Node next; 5 | Node(int key) 6 | { 7 | data = key; 8 | next = null; 9 | } 10 | } 11 | 12 | class Solution { 13 | // Function to pairwise swap elements of a linked list. 14 | // It should returns head of the modified list 15 | public Node pairwiseSwap(Node head) 16 | { 17 | // code here 18 | if(head==null || head.next==null) return head; 19 | Node pre = null; 20 | Node cur = head; 21 | Node temp = null; 22 | while(cur!=null && cur.next!=null) 23 | { 24 | temp = cur.next; 25 | cur.next = temp.next; 26 | temp.next = cur; 27 | if(pre==null)head=temp; 28 | else pre.next=temp; 29 | pre = cur; 30 | cur = cur.next; 31 | } 32 | return head; 33 | } 34 | } -------------------------------------------------------------------------------- /Step 09 Stack and Queues/Step 9.3 Monotonic stack ans Queue Problems/Leetcode/Trapping Rain Water.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int trap(int[] height) { 3 | int n = height.length; 4 | int left = 0, right = n - 1; 5 | int res = 0; 6 | int maxLeft = 0, maxRight = 0; 7 | while (left <= right) { 8 | if (height[left] <= height[right]) { 9 | if (height[left] >= maxLeft) { 10 | maxLeft = height[left]; 11 | } else { 12 | res += maxLeft - height[left]; 13 | } 14 | left++; 15 | } else { 16 | if (height[right] >= maxRight) { 17 | maxRight = height[right]; 18 | } else { 19 | res += maxRight - height[right]; 20 | } 21 | right--; 22 | } 23 | } 24 | return res; 25 | } 26 | } -------------------------------------------------------------------------------- /Step 04 Binary Search/Step 4.1 Learning BS on 1D Array/LeetCode/Search in Rotated Sorted Array II.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean search(int[] nums, int target) { 3 | int l=0, r=nums.length-1, mid; 4 | while(l<=r){ 5 | mid = l + (r-l)/2; 6 | if(nums[mid]==target)return true; 7 | else if(nums[mid]=target)l=mid+1; 10 | else r=mid-1; 11 | } 12 | else if(nums[mid]>nums[r])l=mid+1; 13 | else r--; 14 | } 15 | else{ 16 | if(nums[mid]>nums[r]){ 17 | if(nums[l]<=target)r=mid-1; 18 | else l=mid+1; 19 | } 20 | else if(nums[mid] st = new Stack<>(); 5 | StringBuilder sb = new StringBuilder(); 6 | for (int i = 0; i < s.length(); i++) { 7 | char num = s.charAt(i); 8 | while (k > 0 && !st.isEmpty() && st.peek() > num){ 9 | st.pop(); 10 | k--; 11 | } 12 | if(st.isEmpty() && num == '0') 13 | continue; 14 | st.push(num); 15 | } 16 | while(!st.isEmpty() && k > 0){ 17 | st.pop(); 18 | k--; 19 | } 20 | if(st.isEmpty()) return "0"; 21 | while(!st.isEmpty()){ 22 | sb.append(st.peek()); 23 | st.pop(); 24 | } 25 | return sb.reverse().toString(); 26 | } 27 | } -------------------------------------------------------------------------------- /Step 01 - Basics/Step 1.5 Basic Hashing/Frequency of the Most Frequent Element.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxFrequency(int[] nums, int k) { 3 | Arrays.sort(nums); 4 | int len = nums.length; 5 | long[] prefix = new long[len]; 6 | prefix[0] = nums[0]; 7 | for(int i = 1;i0;i--){ 13 | int lo = 0,hi = i; 14 | while(lo<=hi){ 15 | int mid = hi - (hi-lo)/2; 16 | long sum = prefix[i] - (mid>0?prefix[mid-1]:0); 17 | if(sum+k >= nums[i]*1l*(i-mid+1)){ 18 | max = Math.max(max,i-mid+1); 19 | hi = mid-1; 20 | } 21 | else{ 22 | lo = mid+1; 23 | } 24 | } 25 | } 26 | return max; 27 | } 28 | } -------------------------------------------------------------------------------- /Step 05 strings/Step 5.2 Medium String Problems/LeetCode/Longest Palindromic Substring.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String longestPalindrome(String s) { 3 | if (s == null || s.length() < 1) return ""; 4 | int start = 0, end = 0; 5 | for (int i = 0; i < s.length(); i++) { 6 | int len1 = expandAroundCenter(s, i, i); 7 | int len2 = expandAroundCenter(s, i, i + 1); 8 | int len = Math.max(len1, len2); 9 | if (len > end - start) { 10 | start = i - (len - 1) / 2; 11 | end = i + len / 2; 12 | } 13 | } 14 | return s.substring(start, end + 1); 15 | } 16 | 17 | private int expandAroundCenter(String s, int left, int right) { 18 | int L = left, R = right; 19 | while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) { 20 | L--; 21 | R++; 22 | } 23 | return R - L - 1; 24 | } 25 | } -------------------------------------------------------------------------------- /Step 05 strings/Step 5.2 Medium String Problems/LeetCode/Sort Characters By Frequency.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String frequencySort(String s) { 3 | Map map = new HashMap<>(); 4 | for (char c : s.toCharArray()) 5 | map.put(c, map.getOrDefault(c, 0) + 1); 6 | 7 | List [] bucket = new List[s.length() + 1]; 8 | for (char key : map.keySet()) { 9 | int frequency = map.get(key); 10 | if (bucket[frequency] == null) bucket[frequency] = new ArrayList<>(); 11 | bucket[frequency].add(key); 12 | } 13 | 14 | StringBuilder sb = new StringBuilder(); 15 | for (int pos = bucket.length - 1; pos >= 0; pos--) 16 | if (bucket[pos] != null) 17 | for (char c : bucket[pos]) 18 | for (int i = 0; i < pos; i++) 19 | sb.append(c); 20 | 21 | return sb.toString(); 22 | } 23 | } -------------------------------------------------------------------------------- /Step 06 LinkedList/Step 6.3 Medium Problem of LL/LeetCode/Linked List Cycle II.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public ListNode detectCycle(ListNode head) { 14 | if(head == null || head.next == null) return null; 15 | ListNode fast = head; 16 | ListNode slow = head; 17 | ListNode entry = head; 18 | while(fast.next != null && fast.next.next != null){ 19 | slow = slow.next; 20 | fast = fast.next.next; 21 | if(slow == fast){ 22 | while(slow != entry){ 23 | slow=slow.next; 24 | entry=entry.next; 25 | } 26 | return slow; 27 | } 28 | } 29 | return null; 30 | } 31 | } -------------------------------------------------------------------------------- /Step 07 Recursion/Step 7.2 Subsequence Pattern/LeetCode/Combination Sum II.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> combinationSum2(int[] candidates, int target) { 3 | List < List < Integer >> ans = new ArrayList < > (); 4 | Arrays.sort(candidates); 5 | findCombinations(0, candidates, target, ans, new ArrayList < > ()); 6 | return ans; 7 | } 8 | 9 | static void findCombinations(int ind, int[] arr, int target, List < List < Integer >> ans, List < Integer > ds) { 10 | if (target == 0) { 11 | ans.add(new ArrayList < > (ds)); 12 | return; 13 | } 14 | 15 | for (int i = ind; i < arr.length; i++) { 16 | if (i > ind && arr[i] == arr[i - 1]) continue; 17 | if (arr[i] > target) break; 18 | 19 | ds.add(arr[i]); 20 | findCombinations(i + 1, arr, target - arr[i], ans, ds); 21 | ds.remove(ds.size() - 1); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /Step 12 Greedy Algorithms/Step 12.2 Medium-Hard Problems/GeeksForGeeks/Page Faults in LRU.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | static int pageFaults(int N, int C, int pages[]){ 3 | // code here 4 | Deque q = new ArrayDeque<>(); 5 | int ans=0, i=0; 6 | while(i map = new HashMap<>(); 20 | Node node = head; 21 | while(node != null){ 22 | map.put(node, new Node(node.data)); 23 | node = node.next; 24 | } 25 | node = head; 26 | while(node != null){ 27 | map.get(node).next = map.get(node.next); 28 | map.get(node).arb = map.get(node.arb); 29 | node = node.next; 30 | } 31 | return map.get(head); 32 | } 33 | } -------------------------------------------------------------------------------- /Step 04 Binary Search/Step 4.3 Find Answers by BS in Search Space/GeeksForGeeks/Capacity To Ship Packages Within D Days.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | static int leastWeightCapacity(int[] arr, int N, int D) { 3 | // code here 4 | int mini=0,maxi=0,res=0; 5 | for(int i=0;icap){ 15 | days--; 16 | if(days==0) 17 | break; 18 | sum=0; 19 | } 20 | else i++; 21 | } 22 | if(days==0) mini=cap+1; 23 | else{ 24 | res=cap; 25 | maxi=cap-1; 26 | } 27 | } 28 | return res; 29 | } 30 | }; -------------------------------------------------------------------------------- /Step 05 strings/Step 5.1 Basic and Easy String Problems/GeeksForGeeks/Isomorphic Strings.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | //Function to check if two strings are isomorphic. 4 | public static boolean areIsomorphic(String str1,String str2) 5 | { 6 | // Your code here 7 | HashMap map = new HashMap<>(); 8 | int n=str1.length(), m=str2.length(); 9 | if(n != m) return false; 10 | for(int i=0;i=arr[i]) 17 | { 18 | count++; 19 | if(count>max) 20 | { 21 | max=count; 22 | } 23 | i++; 24 | } 25 | else 26 | { 27 | count--; 28 | j++; 29 | } 30 | 31 | } 32 | return max; 33 | } 34 | 35 | } -------------------------------------------------------------------------------- /Step 04 Binary Search/Step 4.1 Learning BS on 1D Array/LeetCode/Find First and Last Position of Element in Sorted Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] searchRange(int[] nums, int target) { 3 | int[] arr = new int[2]; 4 | arr[0]=-1; 5 | arr[1]=-1; 6 | 7 | int low=0, high=nums.length-1; 8 | while(low<=high){ 9 | int mid=(high+low)/2; 10 | if(nums[mid]==target){ 11 | arr[0]=mid; 12 | high=mid-1; 13 | }else if(nums[mid]>target) high=mid-1; 14 | else low=mid+1; 15 | } 16 | 17 | low=0; 18 | high=nums.length-1; 19 | while(low<=high){ 20 | int mid=(high+low)/2; 21 | if(nums[mid]==target){ 22 | arr[1]=mid; 23 | low=mid+1; 24 | }else if(nums[mid]>target) high=mid-1; 25 | else low=mid+1; 26 | } 27 | 28 | return arr; 29 | } 30 | } -------------------------------------------------------------------------------- /Step 09 Stack and Queues/Step 9.3 Monotonic stack ans Queue Problems/GeeksForGeeks/Next Greater Element.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | //Function to find the next greater element for each element of the array. 4 | public static long[] nextLargerElement(long[] arr, int n) 5 | { 6 | // Your code here 7 | long[] ans = new long[n]; 8 | Stack st = new Stack<>(); 9 | for(int i=n-1;i>=0;i--){ 10 | if(st.isEmpty()){ 11 | ans[i]=-1; 12 | st.push(arr[i]); 13 | }else{ 14 | while(!st.isEmpty() && st.peek()<=arr[i]){ 15 | st.pop(); 16 | } 17 | if(st.isEmpty()){ 18 | ans[i]=-1; 19 | st.push(arr[i]); 20 | }else{ 21 | ans[i]=st.peek(); 22 | st.push(arr[i]); 23 | } 24 | } 25 | } 26 | return ans; 27 | } 28 | } -------------------------------------------------------------------------------- /Step 06 LinkedList/Step 6.5 Hard Problem of LL/GeeksForGeeks/Reverse Nodes in k-Group.java: -------------------------------------------------------------------------------- 1 | class Node { 2 | int num; 3 | Node next; 4 | Node(int a) { 5 | num = a; 6 | next = null; 7 | } 8 | } 9 | 10 | class Solution{ 11 | static Node reverseKNodes(Node head,int k) { 12 | if(head == null||head.next == null) return head; 13 | 14 | int length = lengthOfLinkedList(head); 15 | 16 | Node dummyHead = new Node(0); 17 | dummyHead.next = head; 18 | 19 | Node pre = dummyHead; 20 | Node cur; 21 | Node nex; 22 | 23 | while(length >= k) { 24 | cur = pre.next; 25 | nex = cur.next; 26 | for(int i=1;i zigZagTraversal(Node root) 5 | { 6 | //Add your code here. 7 | ArrayList res = new ArrayList(); 8 | Queue queue = new ArrayDeque<>(); 9 | queue.offer(root); 10 | int count = 1; 11 | while(!queue.isEmpty()){ 12 | ArrayList list = new ArrayList(); 13 | int size = queue.size(); 14 | for(int i = 0 ; i < size ; i++){ 15 | if(queue.peek().left!=null)queue.offer(queue.peek().left); 16 | if(queue.peek().right!=null)queue.offer(queue.peek().right); 17 | list.add(queue.remove().data); 18 | } 19 | if(count%2==0) Collections.reverse(list); 20 | count++; 21 | res.addAll(list); 22 | } 23 | return res; 24 | } 25 | } -------------------------------------------------------------------------------- /Step 07 Recursion/Step 7.2 Subsequence Pattern/GeeksForGeeks/Generate_all_binary_strings.java: -------------------------------------------------------------------------------- 1 | public class Generate_all_binary_strings { 2 | public static void main(String[] args) { 3 | int n = 3; 4 | if (n <= 0) return; 5 | char[] ch = new char[n]; 6 | ch[0] = '0'; 7 | generate(n, ch, 1); 8 | ch[0] = '1'; 9 | generate(n, ch, 1); 10 | } 11 | 12 | public static String toString(char[] a) { 13 | String string = new String(a); 14 | return string; 15 | } 16 | 17 | static void generate(int k, char[] ch, int n) { 18 | if (n == k) { 19 | System.out.print(toString(ch)+" "); 20 | return; 21 | } 22 | if (ch[n - 1] == '0') { 23 | ch[n] = '0'; 24 | generate(k, ch, n + 1); 25 | ch[n] = '1'; 26 | generate(k, ch, n + 1); 27 | } 28 | if (ch[n - 1] == '1') { 29 | ch[n] = '0'; 30 | generate(k, ch, n + 1); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.2 Medium/LeetCode/Spiral Matrix.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List spiralOrder(int[][] matrix) { 3 | ArrayList a = new ArrayList<>(); 4 | int m= matrix.length; 5 | int n=matrix[0].length; 6 | int r1=0; 7 | int c1=0; 8 | int r2=m-1; 9 | int c2=n-1; 10 | while(r1<=r2&&c1<=c2){ 11 | for(int i=c1;i<=c2;i++){ 12 | a.add(matrix[r1][i]); 13 | } 14 | r1++; 15 | for(int i=r1;i<=r2;i++){ 16 | a.add(matrix[i][c2]); 17 | } 18 | c2--; 19 | if(r1<=r2){ 20 | for(int i=c2;i>=c1;i--){ 21 | a.add(matrix[r2][i]); 22 | } 23 | } 24 | r2--; 25 | if(c1<=c2){ 26 | for(int i=r2;i>=r1;i--){ 27 | a.add(matrix[i][c1]); 28 | } 29 | } 30 | c1++; 31 | } 32 | return a; 33 | } 34 | } -------------------------------------------------------------------------------- /Step 05 strings/Step 5.2 Medium String Problems/GeeksForGeeks/Reverse words in a given string.java: -------------------------------------------------------------------------------- 1 | //{ Driver Code Starts 2 | import java.util.*; 3 | import java.lang.*; 4 | import java.io.*; 5 | class GFG { 6 | public static void main(String[] args) { 7 | 8 | Scanner sc = new Scanner(System.in); 9 | int t = sc.nextInt(); 10 | while (t > 0) { 11 | String s = sc.next(); 12 | Solution obj = new Solution(); 13 | System.out.println(obj.reverseWords(s)); 14 | t--; 15 | } 16 | } 17 | } 18 | 19 | // } Driver Code Ends 20 | 21 | 22 | 23 | 24 | class Solution 25 | { 26 | //Function to reverse words in a given string. 27 | String reverseWords(String S) 28 | { 29 | // code here 30 | String[] str = S.split("\\."); 31 | String ans=""; 32 | for(int i=str.length-1;i>=0;i--){ 33 | ans+=str[i]; 34 | // System.out.println(str[i]); 35 | if(i!=0) ans+='.'; 36 | } 37 | return ans; 38 | } 39 | } -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.2 Medium/LeetCode/Next Permutation.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static void swap(int a,int b,int[] nums){ 3 | int t=nums[a]; 4 | nums[a]=nums[b]; 5 | nums[b]=t; 6 | } 7 | public void nextPermutation(int[] nums) { 8 | int index=0,c=0; 9 | for(int i=nums.length-2;i>=0;i--){ 10 | if(nums[i]=index;j--){ 24 | if(nums[j]>t){ 25 | break; 26 | } 27 | } 28 | swap(j,index-1,nums); 29 | for(int i=index;i<=(index+nums.length-1)/2;i++){ 30 | swap(i,index+nums.length-1-i,nums); 31 | } 32 | 33 | 34 | } 35 | } -------------------------------------------------------------------------------- /Step 04 Binary Search/Step 4.3 Find Answers by BS in Search Space/LeetCode/Split Array Largest Sum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int[] nums; 3 | public int splitArray(int[] nums, int m) { 4 | this.nums = nums; 5 | int low = 0, high = 0, min = Integer.MAX_VALUE; 6 | for(int i=0;i 0) { 11 | String s = sc.next(); 12 | Solution obj = new Solution(); 13 | System.out.println(obj.reverseWords(s)); 14 | t--; 15 | } 16 | } 17 | } 18 | 19 | // } Driver Code Ends 20 | 21 | 22 | 23 | 24 | class Solution 25 | { 26 | //Function to reverse words in a given string. 27 | String reverseWords(String S) 28 | { 29 | // code here 30 | String[] str = S.split("\\."); 31 | String ans=""; 32 | for(int i=str.length-1;i>=0;i--){ 33 | ans+=str[i]; 34 | // System.out.println(str[i]); 35 | if(i!=0) ans+='.'; 36 | } 37 | return ans; 38 | } 39 | } -------------------------------------------------------------------------------- /Step 04 Binary Search/Step 4.1 Learning BS on 1D Array/GeeksForGeeks/First and last occurrences of x.java: -------------------------------------------------------------------------------- 1 | class GFG 2 | { 3 | ArrayList find(long arr[], int n, int x) 4 | { 5 | // code here 6 | ArrayList a = new ArrayList(); 7 | long f=-1,l=-1; 8 | int low=0,high=n-1; 9 | while(low<=high){ 10 | int mid=(low+high)/2; 11 | if(arr[mid]==x){ 12 | f=mid; 13 | high=mid-1; 14 | }else if(arr[mid]>x){ 15 | high=mid-1; 16 | }else{ 17 | low=mid+1; 18 | } 19 | } 20 | low=0;high=n-1; 21 | while(low<=high){ 22 | int mid=(low+high)/2; 23 | if(arr[mid]==x){ 24 | l=mid; 25 | low=mid+1; 26 | }else if(arr[mid]>x){ 27 | high=mid-1; 28 | }else{ 29 | low=mid+1; 30 | } 31 | } 32 | a.add(f); 33 | a.add(l); 34 | return a; 35 | } 36 | } -------------------------------------------------------------------------------- /Step 13 Binary Trees/Step 13.2 Medium Problems/LeetCode/Binary Tree Zigzag Level Order Traversal.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List> zigzagLevelOrder(TreeNode root) { 3 | List> ans = new ArrayList<>(); 4 | ArrayDeque q = new ArrayDeque<>(); 5 | int flag=0; 6 | if(root == null) return ans; 7 | q.offer(root); 8 | while(!q.isEmpty()){ 9 | int level=q.size(); 10 | List list = new ArrayList<>(); 11 | for(int i=0;i= arr[mid-1]) && (mid == n-1 || arr[mid]>=arr[mid+1])) return mid; 15 | else if(arr[mid]<=arr[mid+1]) low = mid+1; 16 | else high = mid-1; 17 | } 18 | return -1; 19 | 20 | // if(n==1) return 0; 21 | // for(int i=0;iarr[i+1]) return i; 24 | // }else if(i==n-1){ 25 | // if(arr[i]>arr[i-1]) return i; 26 | // }else{ 27 | // if(arr[i]>arr[i+1] && arr[i]>arr[i-1]) return i; 28 | // } 29 | // } 30 | // return 0; 31 | } 32 | } -------------------------------------------------------------------------------- /Step 06 LinkedList/Step 6.3 Medium Problem of LL/GeeksForGeeks/Given a linked list of 0s, 1s and 2s, sort it.java: -------------------------------------------------------------------------------- 1 | /* 2 | class Node 3 | { 4 | int data; 5 | Node next; 6 | Node(int data) 7 | { 8 | this.data = data; 9 | next = null; 10 | } 11 | } 12 | */ 13 | class Solution 14 | { 15 | //Function to sort a linked list of 0s, 1s and 2s. 16 | static Node segregate(Node head) 17 | { 18 | // add your code here 19 | int c0=0, c1=0, c2=0; 20 | Node cur=head; 21 | while(cur != null){ 22 | if(cur.data==0) c0++; 23 | if(cur.data==1) c1++; 24 | if(cur.data==2) c2++; 25 | cur=cur.next; 26 | } 27 | Node prev=head; 28 | while(c0-->0){ 29 | prev.data=0; 30 | prev=prev.next; 31 | } 32 | while(c1-->0){ 33 | prev.data=1; 34 | prev=prev.next; 35 | } 36 | while(c2-->0){ 37 | prev.data=2; 38 | prev=prev.next; 39 | } 40 | return head; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Step 03 Arrays/Step 3.2 Medium/GeeksForGeeks/Stock buy and sell.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void stockBuySell(int[] price, int n) { 3 | // code here 4 | int l = 0; 5 | while(l price[l+1]){ 6 | l++; 7 | } 8 | if(l==n-1){ 9 | System.out.println("No Profit"); 10 | return; 11 | } 12 | int bi = 0; 13 | int si = 0; 14 | for(int i=1; i price[i-1]){ 16 | si = si + 1; 17 | } 18 | else{ 19 | if(price[si]-price[bi] > 0){ 20 | System.out.print("(" + bi + " " + si + ") "); 21 | } 22 | bi = i; 23 | si = i; 24 | } 25 | } 26 | if(bi < n-2 && price[n-1] < price[n-2]) 27 | System.out.print("(" + bi + " " + si + ") "); 28 | else if(price[n-1] > price[n-2] && bi