├── Array ├── BirthdayCakeCandles.java ├── Intersection.java ├── IsUnique.java ├── LeftRotateArray ├── LemonadeChange.java ├── MO's Algorithm (Query Square Root Decomposition).java ├── MatrixMultiplication.java ├── Max_sum_circular_array.java ├── MinimumDiff.java ├── MonotonicArray.java ├── Multiply.java ├── ProductOfArrayExceptSelf.java ├── Rotate_an_array_to_the_left_by_3_position.java ├── SpiralMatrix.java ├── StringCompression.java ├── ThreeSum.java ├── Transpose.java ├── TrapRainWater.java ├── TwoSum.java ├── ValidSubsequence.java ├── WordsFormedByCharacters.java ├── add.txt ├── chocolateDistribution.java ├── maxConsecutiveOnes.java ├── requirements.txt ├── right_rotate.java ├── runningSum.java └── sparsematrix │ ├── requirements.txt │ ├── runner.java │ ├── sparseMatrix.txt │ └── sparseTriplet.txt ├── Bit Manipulation ├── Bitwiser Operators ├── ComputeXORfrom1ton.java ├── PowerOfTwo.java ├── SetBitOff.java ├── operationsOfBitManipulation.java └── readme.md ├── DP Problems ├── 0-1Knapsack.txt ├── BirthdayCakeCandles.java ├── Longest_common_subsequence.txt ├── Unique-Paths-II.txt ├── minimum_cost-path.txt └── number_of_ balanced_Binary_Trees.txt ├── GoogleKickstart ├── TrashBinsSolution.java ├── Wigglewalk.java └── readme.md ├── Images └── readme.md ├── Interview_Questions ├── Anagram.java ├── BalanceParentheses.java ├── Choose.java ├── ChooseNumber.class ├── ChooseNumber.java ├── CoinChange.class ├── CoinChange.java ├── ConvertToRoman.java ├── FindLongestSubsequence.java ├── Largest Sum Subarray ├── MaxOccuringChar.java ├── Move zeros.java ├── NumberOfDuplicates.java ├── ParenthesisChecker.java ├── SearchInRotatedArray.java ├── SymmetricTree.java ├── checkPrime.java ├── rainWaterProblem.java ├── readme.md └── solutions ├── LICENSE ├── Linked Lists ├── CircularLInkedlist.java ├── ClockwiseRotation.java ├── Deleting_a_linked_list.java ├── DetectLoop.java ├── FindMiddle.java ├── MergeSortSLL.java ├── RemoveDuplicates.java ├── RemoveDuplikates.java ├── RemoveLinkedListElements.java ├── ReverseK.java ├── SinglyLinkedList.java └── getDecimalValue.java ├── Maths ├── AddDigits.java ├── BookingConcertTicketsinGroups.java ├── DecimalToOctal.java ├── Divisor.java ├── Fibonacci.java ├── HCF.java ├── HCFofNnumbers.java ├── HappyNumber.java ├── OptimizedPalindrome.java ├── PowerOfThree.java ├── QuadraticEQ.java ├── ReverseDigits.java ├── SequenceAndSeries.java ├── SetBitOff.java ├── Tribinacci.java ├── ValidPerfectSquare.java ├── add └── lcm.java ├── Matrix ├── Find row with maximum no. of 1's.java.java ├── Median in a row-wise sorted Matrix.java.java ├── README.md ├── Sort all elements of the matrix.java.java └── Spirally traversing a matrix.java.java ├── NumOfFactors └── NumOfFactors.java ├── NumberTheory ├── FindDivisor.java └── findpermutation_nCr.java ├── Patterns ├── AdapterPattern.java ├── BridgePattern.java ├── DiamondPattern.java ├── Fibonacci.java ├── FishPattern.java ├── FlyodsTriangle.java ├── HourGlassPattern.java ├── PascalsTriangle.java ├── PrototypePattern.java ├── PyramidPattern.java ├── RightTriangleStarPattern.java ├── Singleton.java ├── TrianglePattern.java ├── TrianglePattern123.java ├── add └── pascaltri.java ├── PrimeFactors └── PrimeFactors.java ├── README.md ├── Recursion&Backtracking ├── FibonacciSequence ├── NKnightProblem.java ├── NQueenProblem.java ├── RatInAMaze.java ├── StringSubset.java ├── SudokuSolver.java ├── SumSoup.java ├── add ├── n to 1.java └── toh.java ├── Searching & Sorting ├── BinarySearch.java ├── Bogosort.java ├── BubbleSort.java ├── BucketSort.java ├── CountingSort.java ├── HeapSort.java ├── InsertionSort.java ├── InterpolationSearch.java ├── JumpSearch.java ├── LinearSearch.java ├── MatrixSearch.java ├── MergeSort.java ├── QuickSort.java ├── RadixSort.java ├── SelectionSort.java └── partition.java ├── Stack ├── StackDynamic.java └── StackStatic.java ├── Strings ├── Anagram.java ├── Anagrams.java ├── IsPalindrome ├── Palindrome.java ├── Remove permutation from a given string ├── RemoveDuplicates.java ├── ReverseString.java ├── SnakeToCamel.java ├── StringCompression.java ├── StringReverse.java ├── SyntaxCheck ├── ThousandSeparator.java ├── Tokenizer.java ├── add ├── balancedStringSplit.java ├── lengthOfLongestSubstring.java ├── string_rotation.java ├── stringcompression.java ├── stringremoveduplicate.java └── swap.java ├── Trees & Graphs ├── LevelOrderTraversalofBTree.java ├── Path.java ├── Prim.java ├── SerializeDeserialize.java ├── Tree.java ├── UndirectedGraph.java ├── WORD-LADDER-BFS │ └── abc.java └── graph.java └── requirements.txt /Array/BirthdayCakeCandles.java: -------------------------------------------------------------------------------- 1 | package p1; 2 | 3 | import java.io.*; 4 | import java.math.*; 5 | import java.security.*; 6 | import java.text.*; 7 | import java.util.*; 8 | import java.util.concurrent.*; 9 | import java.util.regex.*; 10 | 11 | public class BirthdayCakeCandles{ 12 | static int birthdayCakeCandles(int[] ar) { 13 | 14 | int m =0; 15 | int count =0; 16 | for(int i=0;i map = new HashMap<>(); 10 | List arr = new ArrayList<>(); 11 | 12 | for(int i:nums1) { 13 | map.put(i,map.getOrDefault(i,0)+1); 14 | } 15 | 16 | for(int i:nums2) { 17 | if(map.containsKey(i) && map.get(i)>0) { 18 | arr.add(i); 19 | map.put(i,map.get(i)-1); 20 | } 21 | } 22 | 23 | int [] ret = new int[arr.size()]; 24 | for(int i = 0;i charOccurence = new HashMap<>(); 15 | // Iterate every Character of the String 16 | for(char w:example.toCharArray()) { 17 | // If Hashmap doesn't contain character put it inside 18 | if(!charOccurence.containsKey(w)) { 19 | charOccurence.put(w,0); 20 | } else { 21 | // If it already contains the character print and return 22 | System.out.println("Contains more than one same char."); 23 | return; 24 | } 25 | } 26 | // Print the result 27 | System.out.println("Unique characters only"); 28 | } 29 | } 30 | 31 | 32 | -------------------------------------------------------------------------------- /Array/LeftRotateArray: -------------------------------------------------------------------------------- 1 | public static LeftRotateArray{ 2 | public static int[] rotateLeftArr(int[] data, int d){ 3 | int[] result = new int[data.length]; 4 | for(int i = 0; i < data.length; i++){ 5 | result[(i+(data.length-d)) % data.length ] = data[i]; 6 | } 7 | return result; 8 | } 9 | } -------------------------------------------------------------------------------- /Array/LemonadeChange.java: -------------------------------------------------------------------------------- 1 | class LemonadeChange { 2 | 3 | /** 4 | * You have a lemonade stand where each lemonade costs 5 dollars, customers come with 5,10,20 dollars bills 5 | * Return true if and only if you can provide every customer with correct change. 6 | * Ex : [5,5,5,10,20] should return true 7 | **/ 8 | 9 | public boolean lemonadeChange(int[] bills) { 10 | int fiveBills = 0; 11 | int tenBills = 0; 12 | 13 | int lemonadePrice = 5; 14 | 15 | for(int i:bills) { 16 | 17 | if(i==lemonadePrice) { 18 | fiveBills++; 19 | } else if (i-lemonadePrice==5 && fiveBills>0) { 20 | fiveBills--; 21 | tenBills++; 22 | } else if (i-lemonadePrice==15 && fiveBills>0 && tenBills>0) { 23 | fiveBills--; 24 | tenBills--; 25 | } else if (i-lemonadePrice==15 && fiveBills>=3){ 26 | fiveBills-=3; 27 | } else { 28 | return false; 29 | } 30 | } 31 | return true; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Array/MO's Algorithm (Query Square Root Decomposition).java: -------------------------------------------------------------------------------- 1 | // Java Program to compute sum of ranges for different range 2 | // queries. 3 | import java.util.*; 4 | 5 | // Class to represent a query range 6 | class Query{ 7 | int L; 8 | int R; 9 | Query(int L, int R){ 10 | this.L = L; 11 | this.R = R; 12 | } 13 | } 14 | 15 | class GFG 16 | { 17 | // Prints sum of all query ranges. m is number of queries 18 | // n is the size of the array. 19 | static void printQuerySums(int a[], int n, ArrayList q, int m) 20 | { 21 | // One by one compute sum of all queries 22 | for (int i=0; i q = new ArrayList(); 45 | q.add(new Query(0,4)); 46 | q.add(new Query(1,3)); 47 | q.add(new Query(2,4)); 48 | 49 | int m = q.size(); 50 | printQuerySums(a, n, q, m); 51 | } 52 | } -------------------------------------------------------------------------------- /Array/MatrixMultiplication.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Scanner; 3 | //Other imports go here, Do NOT change the class name 4 | class MatrixMultiplication 5 | { 6 | public static void main(String[] args) 7 | { 8 | Scanner sc=new Scanner(System.in); 9 | int x=sc.nextInt(); 10 | while(x>0) 11 | { 12 | int r1,c1,r2,c2,i,j; 13 | r1=sc.nextInt(); 14 | c1=sc.nextInt(); 15 | int arr[][]=new int[r1][c1]; 16 | 17 | for(i=0;iA[i]){ 11 | isIncreasing = false; 12 | } 13 | 14 | if(A[i-1]=0;i--){ 38 | product *= input[i+1]; 39 | prod[i] *= product; 40 | } 41 | return prod; 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /Array/Rotate_an_array_to_the_left_by_3_position.java: -------------------------------------------------------------------------------- 1 | package Array; 2 | 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | 6 | public class Rotate_an_array_to_the_left_by_3_position { 7 | 8 | public static void main(String[] args) { 9 | Scanner sc = new Scanner(System.in); 10 | System.out.println("Enter number of element to be in array"); 11 | int n = 0; 12 | do { 13 | n = sc.nextInt(); 14 | if(n < 3) { 15 | System.out.println("Please enter number of element to be greater than 3"); 16 | 17 | } 18 | }while(n<3); 19 | 20 | int[] arr = new int[n]; 21 | System.out.println("Enter elements to the array"); 22 | for (int i = 0; i < n; i++) { 23 | arr[i] = sc.nextInt(); 24 | } 25 | 26 | rotateby3(arr,3); 27 | System.out.println(Arrays.toString(arr)); 28 | } 29 | 30 | public static void rotateby3(int[] arr, int k) { 31 | int n = arr.length; 32 | rotate(arr,0,k-1); 33 | rotate(arr,k,n-1); 34 | rotate(arr,0,n-1); 35 | 36 | } 37 | 38 | public static void rotate(int[] arr, int start, int end) { 39 | while(start <= end) { 40 | int temp = arr[start]; 41 | arr[start] = arr[end]; 42 | arr[end] = temp; 43 | start++; 44 | end--; 45 | } 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /Array/SpiralMatrix.java: -------------------------------------------------------------------------------- 1 | 2 | /*Spirally traversing a matrix 3 | Traversing an array is an elementary operation on an array, in which each element will be processed 4 | for some operation. Printing elements is one example operation. 5 | 6 | So, complete the below function, which given a two dimensional array, print the array 7 | in spiral form rotating clockwise. 8 | 9 | 10 | 11 | Input Format 12 | 13 | Each test-case will begin with two number m and n where m = no. of rows and 14 | n = no. of columns. m rows will follow with n integers in each row separated 15 | by a space. Constraint : 1<=m<=50 and 1<=n<=50. 16 | 17 | Output Format 18 | 19 | For each test case, print the elements of 2-d array in spiral form starting 20 | from index (0,0) or upper-left corner in clockwise direction.*/ 21 | import java.util.*; 22 | public class SpiralMatrix 23 | { 24 | public static void main(String[] args) 25 | { 26 | Scanner sc=new Scanner(System.in); 27 | int r=sc.nextInt(); 28 | int c=sc.nextInt(); 29 | int arr[][]=new int[r][c]; 30 | for(int i=0;i=c1;i--) 53 | { 54 | System.out.println(arr[r-1][i]); 55 | } 56 | r--; 57 | } 58 | if(c1=r1;i--) 61 | { 62 | System.out.println(arr[i][c1]); 63 | } 64 | c1++; 65 | } 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Array/StringCompression.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | public class StringCompression{ 4 | 5 | private static String example = "aaaaabbbbbeeeeeeee"; 6 | 7 | public static void main(String args[]) { 8 | System.out.println(encoding()); 9 | } 10 | 11 | private static String encoding() { 12 | 13 | HashMap map = new HashMap<>(); 14 | 15 | for(char c: example.toCharArray()) { 16 | if(!map.containsKey(c)) 17 | map.put(c,0); 18 | map.put(c, map.get(c) + 1); 19 | } 20 | 21 | StringBuilder encodedString = new StringBuilder(); 22 | for(char c: map.keySet()) { 23 | encodedString.append(c + Integer.toString(map.get(c))); 24 | } 25 | 26 | if(encodedString.length() > example.length()) 27 | return example; 28 | return encodedString.toString(); 29 | 30 | } 31 | } 32 | 33 | -------------------------------------------------------------------------------- /Array/ThreeSum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * The ThreeSum program implements an application that - 3 | * Given an array of integers nums and an integer target, return indices of the three numbers such that they add up to target. 4 | * 5 | * @author Tirtharaj Ghosh 6 | * @version 1.0 7 | * @since 2020-10-23 8 | */ 9 | 10 | import java.util.*; 11 | 12 | class ThreeSum { 13 | 14 | public static List> findThreeSum(int[] nums, int target){ 15 | List > res = new ArrayList >(); 16 | for(int i = 0; i s = new HashSet(); 19 | int curr_sum = target - nums[i]; 20 | for (int j = i + 1; j < nums.length; j++) { 21 | if (s.contains(curr_sum - nums[j])) { 22 | List temp = new ArrayList(); 23 | temp.add(nums[i]); 24 | temp.add(nums[j]); 25 | temp.add(curr_sum - nums[j]); 26 | res.add(temp); 27 | } 28 | s.add(nums[j]); 29 | } 30 | } 31 | return res; 32 | } 33 | 34 | public static void main(String[] args) { 35 | int[] nums = { -1,0,1,2,-1,-4 }; 36 | int target = 0; 37 | System.out.println(findThreeSum(nums, target)); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Array/Transpose.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Transpose{ 3 | public static void main(String[] args) { 4 | Scanner name= new Scanner(System.in); 5 | int a[][]=new int[100][100]; 6 | int b[][]=new int[100][100]; 7 | 8 | int m,n; 9 | System.out.println("Enter the number of rows of the matrix A "); 10 | m=name.nextInt(); 11 | System.out.println("Enter the number of columns of the matrix A"); 12 | n=name.nextInt(); 13 | System.out.println("Enter the elements of matrix A one by one"); 14 | for(int i=0;i= 0; i--) { 59 | rightMax[i] = Math.max(height[i], rightMax[i + 1]); 60 | } 61 | 62 | // At any given point, what limits rain water trapped is the smallest of the left wall and right wall, 63 | // hence we compute the min and subtract the current height. 64 | // n.b. Think about edge cases here - what happens if we have a peak at a given point? 65 | for (int i = 1; i < n - 1; i++) { 66 | result += Math.min(leftMax[i], rightMax[i]) - height[i]; 67 | } 68 | 69 | return result; 70 | } 71 | 72 | /** 73 | * Stack Approach to Solving Problem 74 | * Time Complexity: O(2n) = O(n) 75 | * Space Complexity = O(n) 76 | */ 77 | private static int trapStack(int[] height) { 78 | int result = 0; 79 | int i = 0; 80 | Stack boundingWalls = new Stack<>(); 81 | 82 | // Iterate through array 83 | while (i < height.length) { 84 | // Find bounding wall 85 | while (!boundingWalls.isEmpty() && height[i] > height[boundingWalls.peek()]) { 86 | int top = boundingWalls.pop(); 87 | if (boundingWalls.empty()) 88 | break; 89 | 90 | // Compute distance and height to bounded wall and thus rain water trapped. 91 | int distance = i - boundingWalls.peek() - 1; 92 | int boundedHeight = Math.min(height[i], height[boundingWalls.peek()]) - height[top]; 93 | result += distance * boundedHeight; 94 | } 95 | boundingWalls.push(i++); 96 | } 97 | return result; 98 | } 99 | 100 | /** 101 | * Two Pointer approach to Solving Problem 102 | * Time Complexity: O(n) 103 | * Space Complexity: O(1) 104 | */ 105 | private static int trapTwoPointer(int[] height) { 106 | int left = 0; 107 | int right = height.length - 1; 108 | 109 | int ans = 0; 110 | int leftMax = 0, rightMax = 0; 111 | 112 | // Shrink pointers together 113 | while (left < right) { 114 | if (height[left] < height[right]) { 115 | if (height[left] >= leftMax) { 116 | leftMax = height[left]; 117 | } else { 118 | ans += leftMax - height[left]; 119 | } 120 | ++left; 121 | } 122 | else { 123 | if (height[right] >= rightMax) { 124 | rightMax = height[right]; 125 | } else { 126 | ans += rightMax - height[right]; 127 | } 128 | --right; 129 | } 130 | } 131 | return ans; 132 | } 133 | 134 | 135 | } 136 | 137 | -------------------------------------------------------------------------------- /Array/TwoSum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * The TwoSum program implements an application that - 3 | * Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 4 | * 5 | * @author Tirtharaj Ghosh 6 | * @version 1.0 7 | * @since 2020-10-22 8 | */ 9 | 10 | import java.util.HashMap; 11 | import java.util.Scanner; 12 | import java.util.Map; 13 | 14 | class TwoSum { 15 | 16 | /** 17 | * findTwoSum method - using One-pass Hash Table. 18 | * @see https://leetcode.com/problems/two-sum/
19 | * Time complexity: O(n)
20 | * Space complexity: O(n) 21 | * @param nums The nums array. 22 | * @param target The target value 23 | * @return int[] This returns indices of the two numbers 24 | */ 25 | private static int[] findTwoSum(int[] nums, int target) { 26 | Map numMap = new HashMap<>(); 27 | for (int i = 0; i < nums.length; i++) { 28 | int complement = target - nums[i]; 29 | if (numMap.containsKey(complement)) { 30 | return new int[] { numMap.get(complement), i }; 31 | } else { 32 | numMap.put(nums[i], i); 33 | } 34 | } 35 | return new int[] {}; 36 | } 37 | 38 | /** 39 | * This is the main method which drives the program. 40 | * @param args Unused. 41 | * @return void. 42 | */ 43 | public static void main(String[] args) { 44 | Scanner sc = new Scanner(System.in); 45 | 46 | int n = sc.nextInt(); 47 | int[] nums = new int[n]; 48 | 49 | for(int i = 0; i < n; i++) { 50 | nums[i] = sc.nextInt(); 51 | } 52 | int target = sc.nextInt(); 53 | 54 | sc.close(); 55 | 56 | int[] indices = findTwoSum(nums, target); 57 | 58 | if (indices.length == 2) { 59 | System.out.println(indices[0] + " , " + indices[1]); 60 | } else { 61 | System.out.println("No solution found!"); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /Array/ValidSubsequence.java: -------------------------------------------------------------------------------- 1 | /** 2 | * The ValidSubsequence program implements an application that - 3 | * Given two strings ( s and t ), return boolean result of if s is subsequence of t. 4 | * 5 | * @author Tirtharaj Ghosh 6 | * @version 1.0 7 | * @since 2020-10-23 8 | */ 9 | 10 | class ValidSubsequence { 11 | 12 | /** 13 | * isSubsequence method - Brute-force method 14 | * Time complexity: O(n) 15 | * Space complexity: O(1) 16 | * @param s 17 | * @param t 18 | * @return 19 | */ 20 | public static boolean isSubsequence(String s, String t) { 21 | int pos = -1; 22 | for(int i=0; i0) { 24 | arr1[word.charAt(i)-'a']--; 25 | } else { 26 | canMake = false; 27 | } 28 | } 29 | 30 | if(canMake) 31 | ret += word.length(); 32 | 33 | } 34 | return ret; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Array/add.txt: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Array/chocolateDistribution.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | /** 6 | * 7 | * This is from a array based problem in GeeksForGeeks. 8 | * 9 | * Given an array A of positive integers of size N, where each value represents number of chocolates in a packet. 10 | * Each packet can have variable number of chocolates. There are M students, the task is to distribute chocolate packets such that : 11 | * 1. Each student gets one packet. 12 | * 2. The difference between the number of chocolates given to the students having packet with maximum chocolates and student having packet with minimum chocolates is minimum. 13 | * 14 | * @author Jetty53 15 | */ 16 | 17 | class chocolateDistribution { 18 | public static void main(String[] args) { 19 | Scanner sc = new Scanner(System.in); 20 | int n = sc.nextInt(); 21 | int[] arr = new int[n]; 22 | for (int i = 0; i < n; i++) { 23 | arr[i] = sc.nextInt(); 24 | } 25 | Arrays.sort(arr); 26 | int m = sc.nextInt(); 27 | int res = minDiff(arr, m); 28 | System.out.println(res); 29 | 30 | } 31 | 32 | static int minDiff(int[] arr, int m) { 33 | int min = arr[m - 1] - arr[0]; 34 | int i = 1, j = m; 35 | while (j <= arr.length - 1) { 36 | 37 | if ((arr[j] - arr[i]) < min) { 38 | min = arr[j] - arr[i]; 39 | } 40 | i++; 41 | j++; 42 | } 43 | return min; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Array/maxConsecutiveOnes.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class maxConsecutiveOnes { 4 | 5 | public static int findMaxConsecutiveOnes(int[] nums) { 6 | int n = nums.length, si = 0, ei = 0, len = 0, count = 0; 7 | while (ei < n) { 8 | if (nums[ei++] == 0) 9 | count++; 10 | 11 | while (count == 1) { 12 | if (nums[si++] == 0) 13 | count--; 14 | } 15 | 16 | len = Math.max(len, ei - si); 17 | } 18 | return len; 19 | } 20 | 21 | public static void main(String[] args){ 22 | Scanner scn=new Scanner(System.in); 23 | int n=scn.nextInt(); 24 | int[] arr=new int[n]; 25 | for(int i=0;i>>>End of Input>>>>"); 39 | System.out.print("\nDo you want to rotate the array to the right by 3 positions ? \npress 1 to confirm, press 0 to decline : "); 40 | int c=Integer.parseInt(b.readLine()); 41 | if(c==1) 42 | { 43 | k = 3; 44 | rightRotate(a, n, k-1); 45 | } 46 | else if(c==0) 47 | { 48 | System.out.print("\nEnter the number of positions by which you want to right rotate the array: "); 49 | k=Integer.parseInt(b.readLine()); 50 | rightRotate(a, n, k-1); 51 | } 52 | else 53 | System.out.println(">>>>Invalid Input>>>>"); 54 | } 55 | } -------------------------------------------------------------------------------- /Array/runningSum.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static int[] runningSum(int[] nums) { 3 | int[] sum=new int[nums.length]; 4 | if(nums.length==0) 5 | return sum; 6 | sum[0]=nums[0]; 7 | for(int i=1;i= weight[i]; j--) 9 | dp[j] = Math.max(dp[j] , value[i] + dp[j - weight[i]]); 10 | return dp[maxWeight]; 11 | } 12 | 13 | public static void main(String[] args) { 14 | int weights[]= {6,1,2,4,5}; 15 | int values[]= {10,5,4,8,6}; 16 | int maxWeight=5; 17 | System.out.println(knapsackDP(weights, values, maxWeight)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /DP Problems/BirthdayCakeCandles.java: -------------------------------------------------------------------------------- 1 | package p1; 2 | 3 | import java.io.*; 4 | import java.math.*; 5 | import java.security.*; 6 | import java.text.*; 7 | import java.util.*; 8 | import java.util.concurrent.*; 9 | import java.util.regex.*; 10 | 11 | public class BirthdayCakeCandles{ 12 | static int birthdayCakeCandles(int[] ar) { 13 | 14 | int m =0; 15 | int count =0; 16 | for(int i=0;i=0;j--) { //last row 10 | storage[m-1][j]=storage[m-1][j+1]+arr[m-1][j]; 11 | } 12 | for(int i=m-2;i>=0;i--) { //last column 13 | storage[i][n-1]=storage[i+1][n-1]+arr[i][n-1]; 14 | } 15 | 16 | for(int i=m-2;i>=0;i--) { 17 | for(int j=n-2;j>=0;j--) { 18 | storage[i][j]=arr[i][j]+Math.min(storage[i][j+1],Math.min(storage[i+1][j+1], storage[i+1][j])); 19 | 20 | } 21 | } 22 | return storage[0][0]; 23 | } 24 | 25 | public static void main(String[] args) { 26 | int arr[][]= {{1,1,1},{4,5,2},{7,8,9}}; 27 | System.out.println(minCostPathDP(arr)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /DP Problems/number_of_ balanced_Binary_Trees.txt: -------------------------------------------------------------------------------- 1 | public class Balanced_BTs { 2 | public static int balancedTreesOfHeightH(int height){ 3 | int MOD = 1000000007; 4 | int[] dp = new int[height + 1]; 5 | 6 | // base cases 7 | dp[0] = 1; 8 | dp[1] = 1; 9 | 10 | for(int i = 2; i <= height; i++){ 11 | long x = (long)dp[i-1]*dp[i-1]; 12 | long y = (long)dp[i-1]*dp[i-2]*2; 13 | x = x%MOD; 14 | y = y%MOD; 15 | dp[i] = (int)(x+y)%MOD; 16 | } 17 | 18 | return dp[height]; 19 | 20 | } 21 | 22 | public static void main(String[] args) { 23 | int h=3; 24 | int ans= balancedTreesOfHeightH(h); 25 | System.out.println(ans); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /GoogleKickstart/TrashBinsSolution.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class TrashBinsSolution { 3 | public static void main(String[] args){ 4 | Scanner s = new Scanner(System.in); 5 | 6 | int t = s.nextInt(); 7 | int case_count=1; 8 | 9 | while(t>0){ 10 | 11 | int N = s.nextInt(); 12 | String str = s.next(); 13 | int res=0; 14 | for(int i=0; i=0 ){ 36 | if(str.charAt(left)=='1'){ 37 | pos_l= left; 38 | break; 39 | } 40 | left--; 41 | } 42 | 43 | while(right> lists = new ArrayList<>(); 9 | r=sr;c=sc; 10 | lists.add(List.of(r, c)); 11 | String tot_command=scan.nextLine(); 12 | for(int k=0;k balanceList = new ArrayList(); 40 | 41 | for (int i = 0; i <= lastIndexOf(brackets.length()); i++) { 42 | 43 | char c = brackets.charAt(i); 44 | if (isOpen(c)) { // if c is an open character, add it to the balanceList 45 | balanceList.add(String.valueOf(c)); 46 | } else { // if c is a closed character and a match for the last character in balanceList, remove it 47 | if (isBalanced(balanceList, c)) { 48 | int last = lastIndexOf(balanceList.size()); 49 | balanceList.remove(last); 50 | } else { // irrevocably unbalanced, c is a close character without a preceding open character 51 | balanceList.add(String.valueOf(c)); 52 | } 53 | } 54 | } 55 | 56 | if (balanceList.isEmpty()) { 57 | result = yes(); 58 | } else { 59 | result = no(); 60 | } 61 | 62 | System.out.println("result: " + result); 63 | } 64 | 65 | public static Boolean isOpen(char c) { 66 | if (c == curlyOpen || c == bracketOpen || c == parenthesesOpen) { 67 | return true; 68 | } 69 | else { 70 | return false; 71 | } 72 | } 73 | 74 | public static Boolean isBalanced(ArrayList balanceList, char c) { 75 | 76 | int last = lastIndexOf(balanceList.size()); 77 | if (last >= 0) { 78 | String endOfBalanceList = balanceList.get(last); 79 | 80 | String match = String.valueOf(matchOf(c)); 81 | 82 | if (endOfBalanceList.compareTo(match) == 0) { 83 | return true; 84 | } 85 | } 86 | 87 | return false; 88 | 89 | } 90 | 91 | public static char matchOf(char c) { 92 | switch(c) { 93 | case curlyClose: 94 | return curlyOpen; 95 | case bracketClose: 96 | return bracketOpen; 97 | case parenthesesClose: 98 | return parenthesesOpen; 99 | default: 100 | return c; 101 | } 102 | } 103 | 104 | public static int lastIndexOf(int size) { 105 | return size-1; 106 | } 107 | 108 | public static String yes() { 109 | return "Yes"; 110 | } 111 | 112 | public static String no() { 113 | return "No"; 114 | } 115 | 116 | public static void main(String[] args) { 117 | balanceParentheses("(())"); // Yes 118 | balanceParentheses("(())"); // Yes 119 | balanceParentheses("(())()"); // Yes 120 | balanceParentheses("())("); // No 121 | balanceParentheses("(()))"); // No 122 | balanceParentheses("[()]{}{[()()]()}"); // Yes 123 | balanceParentheses("{[(])"); // No 124 | 125 | } 126 | 127 | } -------------------------------------------------------------------------------- /Interview_Questions/Choose.java: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an array of integers A. 3 | You need to tell whether you can choose three numbers such that a+b>=c. 4 | 5 | Input Format 6 | First line consists of number of integers N. next line consists of N space separated integers. 7 | 8 | Constraints 9 | 1 <= N <= 10^5 10 | 11 | Output Format 12 | YES or NO 13 | 14 | Sample Input 15 | 5 16 | 1 2 3 4 9 17 | Sample Output 18 | YES 19 | Explanation 20 | you can choose 1+3 >= 4 21 | */ 22 | 23 | 24 | 25 | 26 | import java.io.*; 27 | 28 | public class Choose 29 | { 30 | public static void main(String args[])throws Exception 31 | { 32 | BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); 33 | StringBuilder sb=new StringBuilder(); 34 | int n=Integer.parseInt(bu.readLine()); 35 | int a[]=new int[n],i; 36 | String s[]=bu.readLine().split(" "); 37 | for(i=0;ia[1]) 44 | { 45 | max=a[0]; 46 | max2=a[1]; 47 | maxp=0; 48 | max2p=1; 49 | } 50 | else 51 | { 52 | max=a[1]; 53 | max2=a[0]; 54 | maxp=1; 55 | max2p=0; 56 | } 57 | 58 | for(i=2;imax) 60 | { 61 | max2=max; 62 | max2p=maxp; 63 | max=a[i]; 64 | maxp=i; 65 | } 66 | else if(a[i]>max2) 67 | { 68 | max2=a[i]; 69 | max2p=i; 70 | } 71 | 72 | int min=Integer.MAX_VALUE; 73 | for(i=0;i=min) System.out.print("YES"); //simplest possible triplet of a,b,c 78 | else System.out.print("NO"); 79 | } 80 | } 81 | 82 | 83 | 84 | /* 85 | eg cases- 86 | 4 87 | 2 2 4 4 88 | YES 89 | 3 90 | 3 1 3 91 | YES 92 | 5 93 | 1 2 3 4 5 94 | YES 95 | 2 96 | 2 1 97 | NO 98 | */ 99 | -------------------------------------------------------------------------------- /Interview_Questions/ChooseNumber.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akshitagit/JAVA/5398fe315c9cc98c5aa761d0906872b0f31cc778/Interview_Questions/ChooseNumber.class -------------------------------------------------------------------------------- /Interview_Questions/ChooseNumber.java: -------------------------------------------------------------------------------- 1 | 2 | public class ChooseNumber { 3 | 4 | public static void main(String[] args) { 5 | int [] A = {1, 3, 4, 5, 6, 9}; 6 | 7 | System.out.println("result: " + chooseNumbers(A)); 8 | } 9 | 10 | public static String chooseNumbers(int [] A) { 11 | if (A.length < 3) return "NO"; 12 | 13 | int index = getMinIndex(A); 14 | int minVal = A[index]; 15 | 16 | index = getMaxIndex(A); 17 | int maxVal1 = A[index]; 18 | A[index] = Integer.MIN_VALUE; 19 | 20 | index = getMaxIndex(A); 21 | int maxVal2 = A[index]; 22 | return ((maxVal1 + maxVal2) >= minVal)? "YES" : "NO"; 23 | } 24 | 25 | private static int getMinIndex(int[] a) { 26 | int minIndex = 0; 27 | for (int i = 0; i < a.length; i++) { 28 | if (a[minIndex] > a[i]) { 29 | minIndex = i; 30 | } 31 | } 32 | return minIndex; 33 | } 34 | 35 | private static int getMaxIndex(int[] a) { 36 | int maxIndex = 0; 37 | for (int i = 0; i < a.length; i++) { 38 | if (a[maxIndex] < a[i]) { 39 | maxIndex = i; 40 | } 41 | } 42 | return maxIndex; 43 | } 44 | } 45 | 46 | 47 | -------------------------------------------------------------------------------- /Interview_Questions/CoinChange.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akshitagit/JAVA/5398fe315c9cc98c5aa761d0906872b0f31cc778/Interview_Questions/CoinChange.class -------------------------------------------------------------------------------- /Interview_Questions/CoinChange.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | class CoinChange { 4 | 5 | static int minCoins(int[] coins, int m, int V) { 6 | int table[] = new int[V+1]; 7 | // base case 8 | table[0] = 0; 9 | 10 | // initialize value: 11 | for(int i=1;i0){ 11 | int N = sc.nextInt(); 12 | ToRoman toRoman = new ToRoman(); 13 | System.out.println(toRoman.convertToRoman(N)); 14 | 15 | } 16 | } 17 | } 18 | 19 | class ToRoman{ 20 | 21 | private Numeral[] numerals = { 22 | new Numeral("M", 1000), 23 | new Numeral("CM", 900), 24 | new Numeral("D", 500), 25 | new Numeral("CD", 400), 26 | new Numeral("C", 100), 27 | new Numeral("XC", 90), 28 | new Numeral("L", 50), 29 | new Numeral("XL", 40), 30 | new Numeral("X", 10), 31 | new Numeral("IX", 9), 32 | new Numeral("V", 5), 33 | new Numeral("IV", 4), 34 | new Numeral("I", 1) 35 | }; 36 | 37 | public String convertToRoman(int num){ 38 | String result = ""; 39 | 40 | for (Numeral numeral : numerals){ 41 | int numberOfSymbol = num/numeral.value; 42 | if (numberOfSymbol != 0) result += numeral.symbol.repeat(numberOfSymbol); 43 | num %= numeral.value; 44 | } 45 | return result; 46 | } 47 | 48 | public class Numeral{ 49 | public String symbol; 50 | public int value; 51 | 52 | public Numeral(String symbol, int value){ 53 | this.symbol = symbol; 54 | this.value = value; 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Interview_Questions/FindLongestSubsequence.java: -------------------------------------------------------------------------------- 1 | /* 2 | Find the length of the longest subsequence in a given array A of integers such that all elements of the subsequence are sorted in strictly ascending order. 3 | Input Format 4 | 5 | The first line contains a single integer n. 6 | Next line contains n space separated numbers denoting the elements of the array. 7 | Constraints 8 | 9 | 0 < n< 105 10 | 0 < Ai < 105 11 | Output Format 12 | 13 | Print a single line containing a single integer denoting the length of the longest increasing subsequence. 14 | Sample Input 15 | 16 | 6 17 | 50 3 10 7 40 80 18 | 19 | Sample Output 20 | 4 21 | */ 22 | import java.util.Scanner; 23 | class FindLongestSubsequence{ 24 | public static int FLS(int[] seq){ 25 | int min = seq[0]; 26 | int count =0; 27 | int last=0; 28 | for(int i=0;ipointer){ 31 | min=pointer; 32 | last=pointer; 33 | count=1; 34 | continue; 35 | } 36 | if(pointer>last){ 37 | count++; 38 | last = pointer; 39 | } 40 | } 41 | return count; 42 | } 43 | public static void main(String args[]){ 44 | Scanner sc= new Scanner(System.in); 45 | int length = sc.nextInt(); 46 | int sequence[] = new int[length]; 47 | for(int i =0;imax){ 17 | max=currsum; 18 | } 19 | if(currsum<0){ 20 | currsum=0; 21 | } 22 | } 23 | System.out.println(max); 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Interview_Questions/MaxOccuringChar.java: -------------------------------------------------------------------------------- 1 | package String; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | 7 | public class MaxOccuringChar { 8 | 9 | public static void main(String[] args) throws IOException { 10 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 11 | int tc = Integer.parseInt(br.readLine().trim()); 12 | 13 | while (tc-- > 0){ 14 | String line = br.readLine().trim(); 15 | MaxOccurance mo = new MaxOccurance(); 16 | System.out.println(mo.getMaxOccurance(line)); 17 | } 18 | } 19 | } 20 | 21 | class MaxOccurance{ 22 | 23 | 24 | public static char getMaxOccurance(String line){ 25 | int[] arr = new int[256]; 26 | 27 | for (int i=0; i<=line.length()-1; i++){ 28 | arr[line.charAt(i)] += 1; 29 | } 30 | 31 | int max = -1; 32 | char c = ' '; 33 | 34 | for (int i=0; i li = new ArrayList(); 22 | System.out.println("Number of elements in ArrayList"); 23 | int size=sc.nextInt(); 24 | for (int i = 0; i < size; i++) { 25 | li.add(sc.nextInt()); 26 | } 27 | System.out.println(duplicates(li,size)); 28 | 29 | } 30 | 31 | private static int duplicates(List li, int size) { 32 | int count=0; 33 | Map map = new HashMap(); 34 | for (int i = 0; i < size; i++) { 35 | if(map.containsKey(li.get(i))) { 36 | map.put(li.get(i), map.get(li.get(i))+1); 37 | }else 38 | map.put(li.get(i), 1); 39 | } 40 | for(Map.Entry entry: map.entrySet()) { 41 | if(entry.getValue()>count) 42 | count++; 43 | } 44 | return count; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /Interview_Questions/ParenthesisChecker.java: -------------------------------------------------------------------------------- 1 | 2 | /*Given an expression string exp. Examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp. 3 | For example, the program should print 'balanced' for exp = “[()]{}{[()()]()}” and 'not balanced' for exp = “[(])” 4 | 5 | Input: 6 | The first line of input contains an integer T denoting the number of test cases. Each test case consists of a string of expression, in a separate line. 7 | 8 | Output: 9 | Print 'balanced' without quotes if the pair of parenthesis is balanced else print 'not balanced' in a separate line. 10 | 11 | Constraints: 12 | 1 ≤ T ≤ 100 13 | 1 ≤ |s| ≤ 105 14 | 15 | Example: 16 | Input: 17 | 3 18 | {([])} 19 | () 20 | ([] 21 | 22 | Output: 23 | balanced 24 | balanced 25 | not balanced*/ 26 | 27 | import java.util.*; 28 | import java.io.*; 29 | 30 | class ParenthesisChecker { 31 | public static void main (String[] args) { 32 | Scanner sc=new Scanner(System.in); 33 | int n=sc.nextInt(); 34 | sc.nextLine(); 35 | while(n-->0) 36 | { 37 | boolean flag=true; 38 | String str=sc.nextLine(); 39 | Stack stk=new Stack<>(); 40 | for(int i=0;i h) 48 | return -1; 49 | 50 | int mid = (l + h) / 2; 51 | if (arr[mid] == key) 52 | return mid; 53 | 54 | // Check if first subarray arr[l...mid] is sorted 55 | if (arr[l] <= arr[mid]) { 56 | 57 | //Key present in first subarray 58 | if (key >= arr[l] && key <= arr[mid]) 59 | return search(arr, l, mid - 1, key); 60 | 61 | //Key present in second subarray 62 | return search(arr, mid + 1, h, key); 63 | } 64 | 65 | // If first subarray is not sorted, then the second subarray arr[mid... h] must be sorted 66 | 67 | //Key present in second subarray 68 | if (key >= arr[mid] && key <= arr[h]) 69 | return search(arr, mid + 1, h, key); 70 | 71 | return search(arr, l, mid - 1, key); 72 | } 73 | 74 | public static void main(String args[]) { 75 | Scanner sc= new Scanner(System.in); 76 | int n = sc.nextInt(); 77 | 78 | int[] arr = new int[n]; 79 | for (int i=0; i 1_000_000){ 10 | System.err.println("You must select a number between 1 and 1,000,000.Please try again."); 11 | roofLength = sc.nextInt(); 12 | } 13 | System.out.println("Please enter the height the height of each block seperated by a space."); 14 | sc.nextLine(); 15 | String roofHeights = sc.nextLine(); 16 | //while control statement needed 17 | //converts string to Array 18 | String [] arr = roofHeights.split(" ", roofLength); 19 | //converts string Array to integer Array 20 | int [] roofHeightsArray = new int[roofLength]; 21 | for (int index = 0; index < roofHeightsArray.length; index++){ 22 | roofHeightsArray[index] = Integer.parseInt(arr[index]); 23 | } 24 | //determines max Height 25 | int maxHeight = 0; 26 | for (int index = 0; index < roofHeightsArray.length; index++){ 27 | if (roofHeightsArray[index] > maxHeight){ 28 | maxHeight = roofHeightsArray[index]; 29 | } 30 | } 31 | //finds frequency of max height 32 | int startIndex = 0; 33 | int endIndex = 0; 34 | for (int index = 0; index < roofHeightsArray.length; index++){ 35 | if (roofHeightsArray[index] == maxHeight){ 36 | startIndex = index; 37 | break; 38 | } 39 | } 40 | for (int revIndex = roofHeightsArray.length - 1; revIndex >= 0; revIndex--){ 41 | if (roofHeightsArray[revIndex] == maxHeight){ 42 | endIndex = revIndex; 43 | break; 44 | } 45 | } 46 | System.out.println("Max Height:" + maxHeight + ", Indexes: " + startIndex + " " + endIndex); 47 | //determines number of blocks of water from left to right up to max height 48 | int blocksWaterSaved = 0; 49 | int currentHeight = 0; 50 | for (int index = 0; index < roofHeightsArray.length; index++){ 51 | if (roofHeightsArray[index] > currentHeight){ 52 | currentHeight = roofHeightsArray[index]; 53 | } 54 | if (currentHeight == maxHeight){ 55 | break; 56 | } 57 | blocksWaterSaved += (currentHeight - roofHeightsArray[index]); 58 | System.out.println(blocksWaterSaved); 59 | } 60 | System.out.println("new block"); 61 | //reset current height and run in reverse 62 | currentHeight = 0; 63 | for (int revIndex = (roofLength-1); revIndex >= 0; revIndex--){ 64 | if (roofHeightsArray[revIndex] > currentHeight){ 65 | currentHeight = roofHeightsArray[revIndex]; 66 | } 67 | if(currentHeight == maxHeight){ 68 | break; 69 | } 70 | blocksWaterSaved += (currentHeight - roofHeightsArray[revIndex]); 71 | System.out.println(blocksWaterSaved); 72 | } 73 | currentHeight = maxHeight; 74 | for (int index = startIndex; startIndex < endIndex; startIndex++){ 75 | blocksWaterSaved += (currentHeight - roofHeightsArray[startIndex]); 76 | System.out.println(blocksWaterSaved); 77 | } 78 | 79 | //Declare blocks of water saved 80 | System.out.printf("%nThe blocks of water saved = %d.", blocksWaterSaved); 81 | } 82 | } -------------------------------------------------------------------------------- /Interview_Questions/readme.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Interview_Questions/solutions: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 OpenSourceDSA 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Linked Lists/CircularLInkedlist.java: -------------------------------------------------------------------------------- 1 | Circular LInkedlist #2 2 | 3 | class CircularLInkedlist { 4 | 5 | // node 6 | static class Node { 7 | int data; 8 | Node next; 9 | } 10 | 11 | // Function to insert a node at the beginning of a Circular linked list 12 | static Node push(Node head_ref, int data) { 13 | Node ptr1 = new Node(); 14 | Node temp = head_ref; 15 | ptr1.data = data; 16 | ptr1.next = head_ref; 17 | 18 | //If linked list is not null then set the next of last node 19 | if (head_ref != null) { 20 | while (temp.next != head_ref) 21 | temp = temp.next; 22 | temp.next = ptr1; 23 | } else 24 | ptr1.next = ptr1; 25 | 26 | head_ref = ptr1; 27 | 28 | return head_ref; 29 | } 30 | 31 | //Function to print nodes in a given Circular linked list 32 | static void printList(Node head) { 33 | Node temp = head; 34 | if (head != null) { 35 | do { 36 | System.out.print(temp.data + " "); 37 | temp = temp.next; 38 | } 39 | while (temp != head); 40 | } 41 | } 42 | 43 | // Driver Code 44 | public static void main(String args[]) { 45 | Node head = null; 46 | 47 | //Created linked list will be 11.2.56.12 48 | head = push(head, 12); 49 | head = push(head, 56); 50 | head = push(head, 2); 51 | head = push(head, 11); 52 | 53 | System.out.println("Contents of Circular Linked List:"); 54 | printList(head); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Linked Lists/ClockwiseRotation.java: -------------------------------------------------------------------------------- 1 | 2 | class ClockwiseRotation 3 | { 4 | //node of linked_list 5 | static class Node 6 | { 7 | int data; 8 | Node next; 9 | } 10 | 11 | //insert data into list 12 | static Node push(Node head_ref, int new_data) 13 | { 14 | Node new_node = new Node(); 15 | new_node.data = new_data; 16 | new_node.next = (head_ref); 17 | (head_ref) = new_node; 18 | return head_ref; 19 | } 20 | 21 | //print the linked_list 22 | static void printList(Node node) 23 | { 24 | while (node != null) 25 | { 26 | System.out.print(node.data + " -> "); 27 | node = node.next; 28 | } 29 | System.out.println( "null"); 30 | } 31 | 32 | 33 | static Node clockwise_rotate(Node head, int k) 34 | { 35 | if (head == null) 36 | return head; 37 | 38 | Node tmp = head; 39 | int len = 1; 40 | while (tmp.next != null) 41 | { 42 | tmp = tmp.next; 43 | len++; 44 | } 45 | 46 | if (k > len) 47 | k = k % len; 48 | 49 | k = len - k; 50 | if (k == 0 || k == len) 51 | return head; 52 | 53 | Node current = head; 54 | int cnt = 1; 55 | while (cnt < k && current != null) 56 | { 57 | current = current.next; 58 | cnt++; 59 | } 60 | 61 | if (current == null) 62 | return head; 63 | Node kthnode = current; 64 | tmp.next = head; 65 | head = kthnode.next; 66 | kthnode.next = null; 67 | return head; 68 | 69 | } 70 | 71 | public static void main(String args[]) 72 | { 73 | Node head = null; 74 | head = push(head, 5); 75 | head = push(head, 4); 76 | head = push(head, 3); 77 | head = push(head, 2); 78 | head = push(head, 1); 79 | printList(head); 80 | int k = 2; 81 | System.out.println("k="+k); 82 | Node updated_head = clockwise_rotate(head, k); 83 | System.out.println("rotated list"); 84 | printList(updated_head); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /Linked Lists/Deleting_a_linked_list.java: -------------------------------------------------------------------------------- 1 | class LinkedList 2 | { 3 | Node head; // head of the list 4 | 5 | /* Linked List node */ 6 | class Node 7 | { 8 | int data; 9 | Node next; 10 | Node(int d) { data = d; next = null; } 11 | } 12 | 13 | /* Function deletes the entire linked list */ 14 | void deleteList() 15 | { 16 | head = null; 17 | } 18 | 19 | /* Inserts a new Node at front of the list. */ 20 | public void push(int new_data) 21 | { 22 | /* 1 & 2: Allocate the Node & 23 | Put in the data*/ 24 | Node new_node = new Node(new_data); 25 | 26 | /* 3. Make next of new Node as head */ 27 | new_node.next = head; 28 | 29 | /* 4. Move the head to point to new Node */ 30 | head = new_node; 31 | } 32 | 33 | public static void main(String [] args) 34 | { 35 | LinkedList llist = new LinkedList(); 36 | /* Use push() to construct below list 37 | 1->12->1->4->1 */ 38 | 39 | llist.push(1); 40 | llist.push(4); 41 | llist.push(1); 42 | llist.push(12); 43 | llist.push(1); 44 | 45 | System.out.println("Deleting the list"); 46 | llist.deleteList(); 47 | 48 | System.out.println("Linked list deleted"); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Linked Lists/DetectLoop.java: -------------------------------------------------------------------------------- 1 | /*Java program to create, detect and find loop in SLL. 2 | Pre-requiste: Check Floyd Cycle Detection Algorithm :)*/ 3 | 4 | import java.util.*; 5 | 6 | class DetectLoop{ 7 | class Node{ 8 | int data; 9 | Node next; 10 | 11 | public Node(int data){ 12 | this.data = data; 13 | this.next = null; 14 | } 15 | } 16 | public Node add(Node head, int data){ 17 | Node newNode = new Node(data); 18 | if(head == null){ 19 | head = newNode; 20 | return head; 21 | } 22 | else{ 23 | Node current = head; 24 | while(current.next != null){ 25 | current = current.next; 26 | } 27 | current.next = newNode; 28 | return head; 29 | } 30 | } 31 | public void display(Node head){ 32 | Node current = head; 33 | 34 | if(head == null){ 35 | System.out.println("List is empty"); 36 | } 37 | else{ 38 | while(current != null ){ 39 | System.out.print("->"+current.data); 40 | current = current.next; 41 | } 42 | } 43 | } 44 | public Node createLoop(Node head){ 45 | Node end = head; 46 | Node loopPosition = head; 47 | 48 | int count = 3; //Creating the loop from 3 node; 49 | while(end.next != null){ 50 | end = end.next; 51 | } 52 | while(--count != 0){ 53 | loopPosition = loopPosition.next; 54 | } 55 | end.next = loopPosition; 56 | return head; 57 | } 58 | public Node detect(Node head){ // Check whether loop is there or not. 59 | Node hare = head; // hare which always move ahead of tortoise. 60 | Node tortoise = head; 61 | while(hare != null && tortoise != null && tortoise.next != null){ 62 | hare = hare.next.next; 63 | tortoise = tortoise.next; 64 | if(hare == tortoise){ // if loop is there, they will surely meet at one place. 65 | System.out.println("There is a loop"); 66 | return hare; 67 | } 68 | 69 | } 70 | return null; 71 | } 72 | public int startLoopPlace(Node loop, Node head){ //According to Floyd Cycle detection algo, Distance between start and loop position is equal to meet and loop position. 73 | Node current = head; 74 | while(current != loop){ 75 | current = current.next; 76 | loop = loop.next; 77 | } 78 | return loop.data; 79 | } 80 | public static Node head = null; 81 | public static void main(String[] args) { 82 | DetectLoop l1 = new DetectLoop(); 83 | 84 | head = l1.add(head,1); 85 | head = l1.add(head,2); 86 | head = l1.add(head,3); 87 | head = l1.add(head,4); 88 | head = l1.add(head,5); 89 | head = l1.add(head,6); 90 | 91 | l1.display(head); 92 | 93 | head = l1.createLoop(head); 94 | //l1.display(head); //Uncomment the code to get the loop :> 95 | 96 | Node loop = l1.detect(head); 97 | int loopData = l1.startLoopPlace(loop,head); 98 | System.out.println("Loop starts from node data:" + loopData); 99 | } 100 | } -------------------------------------------------------------------------------- /Linked Lists/FindMiddle.java: -------------------------------------------------------------------------------- 1 | /*Find middle element of the linked list.*/ 2 | /* TC: O(N) && SC: O(1) */ 3 | 4 | import java.util.*; 5 | 6 | class FindMiddle{ 7 | class Node{ 8 | int data; 9 | Node next; 10 | 11 | public Node(int data){ 12 | this.data = data; 13 | this.next = null; 14 | } 15 | } 16 | public Node add(Node head, int data){ 17 | Node newNode = new Node(data); 18 | if(head == null){ 19 | head = newNode; 20 | return head; 21 | } 22 | else{ 23 | Node current = head; 24 | while(current.next != null){ 25 | current = current.next; 26 | } 27 | current.next = newNode; 28 | return head; 29 | } 30 | } 31 | public void display(Node head){ 32 | if(head == null){ 33 | System.out.println("List is empty"); 34 | } 35 | else{ 36 | Node current = head; 37 | while(current != null){ 38 | System.out.print("->" + current.data); 39 | current = current.next; 40 | } 41 | } 42 | } 43 | public int find(Node head){ //Tortoise and hare approach or Two pointer approach. 44 | Node forward = head; 45 | Node backward = head; 46 | if(head == null){ 47 | System.out.println("List is empty"); 48 | } 49 | else{ 50 | while(forward != null && forward.next != null){ 51 | forward = forward.next.next; 52 | backward = backward.next; 53 | } 54 | } 55 | return backward.data; 56 | } 57 | public static Node head = null; 58 | public static void main(String[] args) { 59 | FindMiddle l1 = new FindMiddle(); 60 | 61 | head = l1.add(head,1); 62 | head = l1.add(head,2); 63 | head = l1.add(head,3); 64 | head = l1.add(head,4); 65 | head = l1.add(head,5); 66 | head = l1.add(head,6); 67 | head = l1.add(head,7); 68 | head = l1.add(head,8); 69 | head = l1.add(head,9); 70 | 71 | l1.display(head); 72 | 73 | System.out.println(""); 74 | int middle = l1.find(head); 75 | System.out.println("Middle element of the Linked List is: "+middle); 76 | 77 | } 78 | } -------------------------------------------------------------------------------- /Linked Lists/MergeSortSLL.java: -------------------------------------------------------------------------------- 1 | /*Merge Sort Linked List.*/ 2 | 3 | import java.util.*; 4 | 5 | class MergeSortSLL{ 6 | class Node{ 7 | int data; 8 | Node next; 9 | 10 | public Node(int data){ 11 | this.data = data; 12 | this.next = null; 13 | } 14 | } 15 | public Node add(Node head, int data){ 16 | Node newNode = new Node(data); 17 | if(head == null){ 18 | head = newNode; 19 | return head; 20 | } 21 | else{ 22 | Node current = head; 23 | while(current.next != null){ 24 | current = current.next; 25 | } 26 | current.next = newNode; 27 | return head; 28 | } 29 | } 30 | public void display(Node head){ 31 | if(head == null){ 32 | System.out.println("List is empty"); 33 | } 34 | else{ 35 | Node current = head; 36 | while(current != null){ 37 | System.out.print("->" + current.data); 38 | current = current.next; 39 | } 40 | } 41 | } 42 | public Node sort(Node left, Node right){ 43 | if(left == null){ 44 | return right; 45 | } 46 | if(right == null){ 47 | return left; 48 | } 49 | Node result = null; 50 | if(left.data <= right.data){ 51 | result = left; 52 | left.next = sort(left.next,right); 53 | } 54 | else{ 55 | result = right; 56 | right.next = sort(left,right.next); 57 | } 58 | 59 | return result; 60 | } 61 | public Node mergeSort(Node head){ //Divide into sub list 62 | if(head == null || head.next == null){ 63 | return head; 64 | } 65 | Node fast = head; //end 66 | Node slow = head; //middle 67 | Node temp = null; //before middle 68 | while(fast != null && fast.next != null){ 69 | temp = slow; 70 | fast = fast.next.next; 71 | slow = slow.next; 72 | } 73 | 74 | temp.next = null; 75 | 76 | Node left = mergeSort(head); 77 | Node right = mergeSort(slow); 78 | 79 | Node sortedList = sort(left,right); 80 | return sortedList; 81 | } 82 | public static Node head = null; 83 | public static void main(String[] args) { 84 | MergeSortSLL l1 = new MergeSortSLL(); 85 | 86 | head = l1.add(head,5); 87 | head = l1.add(head,1); 88 | head = l1.add(head,6); 89 | head = l1.add(head,4); 90 | head = l1.add(head,3); 91 | head = l1.add(head,2); 92 | 93 | l1.display(head); 94 | 95 | head = l1.mergeSort(head); 96 | System.out.println(""); 97 | l1.display(head); 98 | } 99 | } -------------------------------------------------------------------------------- /Linked Lists/RemoveDuplicates.java: -------------------------------------------------------------------------------- 1 | /* Remove Duplicates from a singly LinkedList 2 | Tc-->O(N^2) Sc-->O(1) 3 | */ 4 | 5 | class RemoveDuplicates{ 6 | 7 | class innernode 8 | { 9 | int data; 10 | innernode next; 11 | } 12 | static innernode head; 13 | 14 | public void insert(int data) 15 | { 16 | innernode node =new innernode(); 17 | node.data=data; 18 | node.next=null; 19 | if(head==null) 20 | { 21 | head=node; 22 | } 23 | else 24 | { 25 | innernode n=head; 26 | while(n.next!=null) 27 | { 28 | n=n.next; 29 | } 30 | n.next=node; 31 | } 32 | 33 | } 34 | public void display(innernode head) 35 | { 36 | innernode run=head; 37 | while(run.next!=null) 38 | { 39 | System.out.print(run.data+" "); 40 | run=run.next; 41 | } 42 | System.out.println(run.data); 43 | } 44 | void removeDuplicates() { 45 | innernode h1 = null, h2 = null, duplicate = null; 46 | h1 = head; 47 | 48 | while (h1 != null && h1.next != null) { 49 | h2 = h1; 50 | 51 | 52 | while (h2.next != null) { 53 | 54 | 55 | if (h1.data == h2.next.data) { 56 | 57 | 58 | duplicate = h2.next; 59 | h2.next = h2.next.next; 60 | 61 | } else { 62 | h2 = h2.next; 63 | } 64 | } 65 | h1 = h1.next; 66 | } 67 | } 68 | 69 | 70 | public static void main(String[] args){ 71 | RemoveDuplicates rd=new RemoveDuplicates(); 72 | rd.insert(1); 73 | rd.insert(1); 74 | rd.insert(2); 75 | rd.insert(9); 76 | rd.insert(10); 77 | rd.insert(3); 78 | rd.insert(5); 79 | rd.insert(5); 80 | rd.display(head); 81 | rd.removeDuplicates(); 82 | rd.display(head); 83 | } 84 | 85 | } 86 | 87 | 88 | -------------------------------------------------------------------------------- /Linked Lists/RemoveDuplikates.java: -------------------------------------------------------------------------------- 1 | /* 2 | 'removeDuplikates' method is removing values that are repated 'i' times. 3 | For instance: 4 | removeDuplicates(4, 1, 2, 2, 2, 5, 6, 4, 6), 2); 5 | it should return only 4 and 6. But not 2 which is repeated 3 times. 6 | In map as a key there are elements from a list, and as a values there are how many times this value is repeated. 7 | */ 8 | 9 | import java.util.*; 10 | 11 | class RemoveDuplikates{ 12 | 13 | public static List removeDuplikates(List arr, int i){ 14 | Map map = new HashMap(); 15 | 16 | for(Integer el : arr){ 17 | if(!map.containsKey(el)){ 18 | map.put(el,1); 19 | } else{ 20 | map.put(el, map.get(el) + 1); 21 | } 22 | } 23 | 24 | for(Integer el : map.keySet()){ 25 | if(map.get(el) == i){ 26 | arr.remove(el); 27 | } 28 | } 29 | return arr; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Linked Lists/RemoveLinkedListElements.java: -------------------------------------------------------------------------------- 1 | class RemoveLinkedListElements { 2 | public ListNode removeElements(ListNode head, int val) { 3 | 4 | while(head!=null && head.val==val) 5 | head = head.next; 6 | 7 | if(head==null) 8 | return head; 9 | 10 | ListNode traversalNode = new ListNode(head.val); 11 | ListNode retHead = traversalNode; 12 | 13 | head=head.next; 14 | while(head!=null) { 15 | if(head.val!=val) { 16 | traversalNode.next = new ListNode(head.val); 17 | traversalNode = traversalNode.next; 18 | } 19 | head = head.next; 20 | } 21 | return retHead; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Linked Lists/ReverseK.java: -------------------------------------------------------------------------------- 1 | /*Reverse SLL of given size k using recursion. 2 | TC:O(N) && SC:O(1). if not considering stack memory*/ 3 | 4 | import java.util.*; 5 | 6 | class ReverseK{ 7 | class Node{ 8 | int data; 9 | Node next; 10 | 11 | public Node(int data){ 12 | this.data = data; 13 | this.next = null; 14 | } 15 | } 16 | public static Node head = null; 17 | public Node add(Node head, int data){ 18 | Node newNode = new Node(data); 19 | if(head == null){ 20 | head = newNode; 21 | return head; 22 | } 23 | else{ 24 | Node current = head; 25 | while(current.next != null){ 26 | current = current.next; 27 | } 28 | current.next = newNode; 29 | return head; 30 | } 31 | } 32 | public void display(Node head){ 33 | Node current = head; 34 | 35 | if(head == null){ 36 | System.out.println("List is empty"); 37 | } 38 | else{ 39 | while(current != null ){ 40 | System.out.print("->"+current.data); 41 | current = current.next; 42 | } 43 | } 44 | } 45 | public Node reverse(Node head, int k){ 46 | Node current = head; 47 | Node prev = null; 48 | Node next = null; 49 | int count = 0; 50 | while(count != k && current != null){ 51 | next = current.next; 52 | current.next = prev; 53 | prev = current; 54 | current = next; 55 | count++; 56 | } 57 | if(next != null){ 58 | head.next = reverse(next,k); //At each recursive call head of group points to reverse of next group 59 | } 60 | return prev; 61 | } 62 | public static void main(String[] args) { 63 | ReverseK l1 = new ReverseK(); 64 | 65 | head = l1.add(head,1); 66 | head = l1.add(head,2); 67 | head = l1.add(head,3); 68 | head = l1.add(head,4); 69 | head = l1.add(head,5); 70 | head = l1.add(head,6); 71 | 72 | l1.display(head); 73 | 74 | head = l1.reverse(head,2); //2 is my k size 75 | System.out.println(""); 76 | System.out.println("After reversing by k size"); 77 | l1.display(head); 78 | } 79 | } -------------------------------------------------------------------------------- /Linked Lists/getDecimalValue.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.LinkedList; 3 | 4 | /** 5 | * Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. 6 | * The linked list holds the binary representation of a number. Return the decimal value of the number in the linked list. 7 | * Ex: [1,0,1] the program should return 5 8 | * Solution: We first iterate the list to get the number and the size, and the iteratively we find the number 9 | */ 10 | public class getDecimalValue { 11 | 12 | public int getListValue(LinkedList head) { 13 | 14 | ArrayList l = new ArrayList<>(); 15 | 16 | while(head!=null) { 17 | l.add(head.value); 18 | head=head.next; 19 | } 20 | 21 | int power = l.size()-1; 22 | 23 | int count = 0; 24 | 25 | for(int i=0;i=k){ 15 | seatsLeft[row] -= k; 16 | return new int[]{row, m- seatsLeft[row]-k}; 17 | } 18 | } 19 | return new int[]{}; 20 | 21 | } 22 | 23 | public boolean scatter(int k, int maxRow) { 24 | int start = seatStartsFrom; 25 | while(start<=maxRow && k > seatsLeft[start]) 26 | k = k - seatsLeft[start++]; 27 | if(start>maxRow && k>0) return false; 28 | 29 | seatsLeft[start] -= k; 30 | seatStartsFrom = start; 31 | return true; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Maths/DecimalToOctal.java: -------------------------------------------------------------------------------- 1 | public class DecimalToOctal { 2 | 3 | public static void main(String[] args) { 4 | 5 | int number = Integer.parseInt(args[0]); 6 | 7 | final int decimalNumber = number; 8 | 9 | int octalNumber = 0; 10 | 11 | int multiplier = 1; 12 | 13 | while (number != 0) { 14 | octalNumber += (number % 8) * multiplier; 15 | number /= 8; 16 | multiplier *= 10; 17 | } 18 | 19 | System.out.println("Converted decimal number '" + decimalNumber 20 | + "' to octal number '" + octalNumber + "'"); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Maths/Divisor.java: -------------------------------------------------------------------------------- 1 | public class Divisor { 2 | public static void main(String args[]) { 3 | Scanner scanner = new Scanner(System.in); 4 | System.out.print("Enter the number : "); 5 | long num = scanner.nextInt(), i; 6 | System.out.print("Divisors of " + num + " = 1 , "); 7 | for (i = 2; i <= num / 2; i++) { 8 | if (num % i == 0) { 9 | System.out.print(i + " , "); 10 | } 11 | } 12 | System.out.println(num); 13 | scanner.close(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Maths/Fibonacci.java: -------------------------------------------------------------------------------- 1 | 2 | // Print the Fibonacci series for n=20 3 | import java.util.Scanner; 4 | public class Fibonacci { 5 | 6 | public static void main(String[] args) { 7 | Scanner sc=new Scanner(System.in); 8 | System.out.println("enter any positive number:"); 9 | int n=sc.nextInt(); 10 | 11 | int t1 = 0, t2 = 1; 12 | 13 | while (t1 <= n) { 14 | System.out.print(t1 + " "); 15 | 16 | int sum = t1 + t2; 17 | t1 = t2; 18 | t2 = sum; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Maths/HCF.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class HCF { 3 | int hcf(int a,int b){ 4 | if(a == 0){ 5 | return b; 6 | } 7 | return hcf(b%a, a); 8 | } 9 | 10 | int findHCF(int arr[], int n){ 11 | int result = 0; 12 | for(int i = 0; i < arr.length; i++){ 13 | result = hcf(result, arr[i]); 14 | if (result == 1){ 15 | return 1; 16 | } 17 | } 18 | return result; 19 | 20 | } 21 | 22 | public static void main(String[] args) { 23 | Scanner inp = new Scanner(System.in); 24 | HCF hcf = new HCF(); 25 | int n = inp.nextInt(); 26 | int[] arr = new int[n]; 27 | int value ; 28 | for(int i = 0;i< n;i++){ 29 | arr[i] = inp.nextInt(); 30 | } 31 | 32 | System.out.print(hcf.findHCF(arr, n)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Maths/HCFofNnumbers.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.Scanner; 3 | 4 | class Hcf 5 | { 6 | public static void main(String arg[]) 7 | { 8 | { 9 | Scanner sc=new Scanner(System.in); 10 | System.out.println("HCF of how many numbers? (numbers<=10) - "); 11 | int N=sc.nextInt(); 12 | long input[]=new long[N]; 13 | System.out.println("Enter "+ N+" numbers"); 14 | for(int i=0;i=0) 14 | { 15 | r1=(-b+Math.sqrt(d))/(2*a); 16 | r2=(-b-Math.sqrt(d))/(2*a); 17 | System.out.print("The roots are "+String.format("%.1f",r1)+","+String.format("%.1f",r2)); 18 | } 19 | else 20 | { 21 | r1=(-b)/(2*a); 22 | d=Math.sqrt(-d)/(2*a); 23 | System.out.print("The roots are "+String.format("%.1f",r1)+"+"+String.format("%.1f",d)+"i,"+String.format("%.1f",r1)+"-"+String.format("%.1f",d)+"i"); 24 | } 25 | } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /Maths/ReverseDigits.java: -------------------------------------------------------------------------------- 1 | class ReverseDigits 2 | { 3 | public static void main(String args[]) 4 | { 5 | int num=0; 6 | int reverse =0; 7 | System.out.println("Input Number: "); 8 | Scanner in = new Scanner(System.in); 9 | num = in.nextInt(); 10 | while( num != 0 ) 11 | { 12 | reverse = reverse * 10; 13 | reverse = reverse + num%10; 14 | num = num/10; 15 | } 16 | 17 | System.out.println("Reverse of input number is: "+reverse); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Maths/SetBitOff.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | /* Bit toggiling/ Setting bit ON or OFF is a way of changing a digit's Binary for 0 3 | to 1 or vice-versa. 4 | * */ 5 | public class SetBitOff{ 6 | public static void main(String[] args) { ; 7 | Scanner sc = new Scanner(System.in); 8 | //Take input from the user for toggling the Bit 9 | System.out.println("Enter the no to be turned off"); 10 | int num = sc.nextInt(); 11 | //Take input of the position of the Bit to be turned off from the user 12 | System.out.println("Enter the position to be off"); 13 | int pos = sc.nextInt(); 14 | int mask = 1 << pos; 15 | mask = ~mask; 16 | System.out.println("Digit before turnign off " + Integer.toBinaryString(num)); 17 | num = num & mask; 18 | System.out.println(Integer.toBinaryString(num)); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Maths/Tribinacci.java: -------------------------------------------------------------------------------- 1 | // first n Tribinacci numbers. 2 | import java.io.*; 3 | 4 | class Tribinacci { 5 | 6 | // Recursion Function 7 | static int printTribRec(int n) 8 | { 9 | 10 | if (n == 0 || n == 1 || n == 2) 11 | return 0; 12 | 13 | if (n == 3) 14 | return 1; 15 | else 16 | return printTribRec(n - 1) + 17 | printTribRec(n - 2) + 18 | printTribRec(n - 3); 19 | } 20 | 21 | static void printTrib(int n) 22 | { 23 | for (int i = 1; i < n; i++) 24 | System.out.print(printTribRec(i) 25 | +" "); 26 | } 27 | 28 | // Driver code 29 | public static void main(String args[]) 30 | { 31 | int n = 20; 32 | 33 | printTrib(n); 34 | } 35 | } 36 | 37 | -------------------------------------------------------------------------------- /Maths/ValidPerfectSquare.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a positive integer num, write a function which returns True if num is a perfect 3 | * square else False. 4 | **/ 5 | class ValidPerfectSquare { 6 | public boolean isPerfectSquare(int num) { 7 | 8 | long start = 1; 9 | long end = num; 10 | long mid = 0; 11 | 12 | while(start<=end) { 13 | mid = start + (end-start)/2; 14 | if((int)mid*mid == num) 15 | return true; 16 | if(mid*midnum) 19 | end = mid -1; 20 | } 21 | return false; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Maths/add: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Maths/lcm.java: -------------------------------------------------------------------------------- 1 | //LCM of two numbers 2 | import java.util.*; 3 | public class Main{ 4 | public static void main(String[] args) { 5 | Scanner sc=new Scanner(System.in); 6 | int num1=sc.nextInt(); 7 | int num2=sc.nextInt(); 8 | int max=Math.max(num1,num2); 9 | while(true){ 10 | if(max%num1==0 && max%num2==0){ 11 | System.out.println("LCM is: "+ max); 12 | break; 13 | } 14 | max++; 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Matrix/Find row with maximum no. of 1's.java.java: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | //Initial Template for Java 3 | 4 | import java.util.*; 5 | import java.io.*; 6 | 7 | public class Main { 8 | 9 | public static void main(String[] args) throws Exception { 10 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 11 | int tc = Integer.parseInt(br.readLine().trim()); 12 | while (tc-- > 0) { 13 | String[] inputLine; 14 | inputLine = br.readLine().trim().split(" "); 15 | int n = Integer.parseInt(inputLine[0]); 16 | int m = Integer.parseInt(inputLine[1]); 17 | int[][] arr = new int[n][m]; 18 | inputLine = br.readLine().trim().split(" "); 19 | 20 | for (int i = 0; i < n; i++) { 21 | for (int j = 0; j < m; j++) { 22 | arr[i][j] = Integer.parseInt(inputLine[i * m + j]); 23 | } 24 | } 25 | int ans = new Solution().rowWithMax1s(arr, n, m); 26 | System.out.println(ans); 27 | } 28 | } 29 | } 30 | // } Driver Code Ends 31 | 32 | 33 | //User function Template for Java 34 | 35 | class Solution { 36 | int rowWithMax1s(int arr[][], int n, int m) { 37 | // code here 38 | int k =0; 39 | while(k 0) 15 | { 16 | String S[] = read.readLine().split(" "); 17 | int R = Integer.parseInt(S[0]); 18 | int C = Integer.parseInt(S[1]); 19 | String line[] = read.readLine().trim().split("\\s+"); 20 | int matrix[][] = new int[R][C]; 21 | int c = 0; 22 | for(int i = 0; i < R; i++){ 23 | for(int j = 0; j < C; j++){ 24 | matrix[i][j] = Integer.parseInt(line[c++]); 25 | } 26 | } 27 | Solution ob = new Solution(); 28 | int ans = ob.median(matrix, R, C); 29 | System.out.println(ans); 30 | } 31 | } 32 | } 33 | // } Driver Code Ends 34 | 35 | 36 | //User function Template for Java 37 | 38 | class Solution { 39 | int median(int matrix[][], int r, int c) { 40 | // code here 41 | int[] ans =new int [r*c]; 42 | int k=0; 43 | for(int i = 0 ; i < r ; i ++){ 44 | for(int j = 0 ; j < c ; j ++) 45 | ans[k++]=matrix[i][j]; 46 | 47 | } 48 | Arrays.sort(ans); 49 | return ans[((r*c)-1)/2]; 50 | } 51 | } -------------------------------------------------------------------------------- /Matrix/README.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Matrix/Sort all elements of the matrix.java.java: -------------------------------------------------------------------------------- 1 | // { Driver Code Starts 2 | // Initial Template for Java 3 | 4 | import java.io.*; 5 | import java.util.*; 6 | 7 | class GFG { 8 | public static void main(String args[]) throws IOException { 9 | BufferedReader read = 10 | new BufferedReader(new InputStreamReader(System.in)); 11 | int t = Integer.parseInt(read.readLine()); 12 | while (t-- > 0) { 13 | int N = Integer.parseInt(read.readLine()); 14 | int v[][] = new int[N][N]; 15 | for (int i = 0; i < N; i++) { 16 | String s[] = read.readLine().split(" "); 17 | for (int j = 0; j < N; j++) v[i][j] = Integer.parseInt(s[j]); 18 | } 19 | Solution ob = new Solution(); 20 | int ans[][] = ob.sortedMatrix(N, v); 21 | for (int i = 0; i < N; i++) { 22 | for (int j = 0; j < N; j++) System.out.print(ans[i][j] + " "); 23 | System.out.println(); 24 | } 25 | } 26 | } 27 | }// } Driver Code Ends 28 | 29 | 30 | // User function Template for Java 31 | 32 | class Solution { 33 | int[][] sortedMatrix(int n, int matrix[][]) { 34 | // code here 35 | int[] temp=new int[n*n]; 36 | int k=0; 37 | for(int i=0;i 0) 12 | { 13 | int r = sc.nextInt(); 14 | int c = sc.nextInt(); 15 | 16 | int matrix[][] = new int[r][c]; 17 | 18 | for(int i = 0; i < r; i++) 19 | { 20 | for(int j = 0; j < c; j++) 21 | matrix[i][j] = sc.nextInt(); 22 | } 23 | Solution ob = new Solution(); 24 | ArrayList ans = ob.spirallyTraverse(matrix, r, c); 25 | for (Integer val: ans) 26 | System.out.print(val+" "); 27 | System.out.println(); 28 | } 29 | } 30 | }// } Driver Code Ends 31 | 32 | 33 | class Solution 34 | { 35 | //Function to return a list of integers denoting spiral traversal of matrix. 36 | static ArrayList spirallyTraverse(int matrix[][], int r, int c) 37 | { 38 | // code here 39 | ArrayList al = new ArrayList<>(); 40 | int t =0 ; 41 | int R=c; 42 | int b=r; 43 | int l=0; 44 | while(t<=b&&l<=r){ 45 | for(int i=l;i=l;i--){ 56 | al.add(matrix[b-1][i]); 57 | } 58 | b--; 59 | } 60 | if(l <= R){ 61 | for(int i=b-1;i>=t;i--){ 62 | al.add(matrix[i][l]); 63 | } 64 | l++; 65 | } 66 | } 67 | return al; 68 | 69 | } 70 | 71 | } -------------------------------------------------------------------------------- /NumOfFactors/NumOfFactors.java: -------------------------------------------------------------------------------- 1 | 2 | public class NumOfFactors { 3 | 4 | 5 | public static void main(String[] args) { 6 | 7 | long number=10; 8 | int factors=getNumOfFactors(number); 9 | 10 | System.out.println(String.format("Total factors of %d are: %d",number,factors)); 11 | } 12 | 13 | private static int getNumOfFactors(long num) { 14 | 15 | int totalFactors=1;//accounts for the number itself 16 | int increment=1; 17 | if(num%2==1) {//if number is odd, it can never have an even factor 18 | increment=2; 19 | } 20 | 21 | for(long numFac=1; numFac System.out.println("info: " + message); 8 | } 9 | static Logger warning() { 10 | return message -> System.out.println("warning: " + message); 11 | } 12 | } 13 | 14 | abstract class AbstractAccount { 15 | private Logger logger = Logger.info(); 16 | 17 | public void setLogger(Logger logger) { 18 | this.logger = logger; 19 | } 20 | 21 | // the logging part is delegated to the Logger implementation 22 | protected void operate(String message, boolean result) { 23 | logger.log(message + " result " + result); 24 | } 25 | } 26 | 27 | class SimpleAccount extends AbstractAccount { 28 | private int balance; 29 | 30 | public SimpleAccount(int balance) { 31 | this.balance = balance; 32 | } 33 | 34 | public boolean isBalanceLow() { 35 | return balance < 50; 36 | } 37 | 38 | public void withdraw(int amount) { 39 | boolean shouldPerform = balance >= amount; 40 | if (shouldPerform) { 41 | balance -= amount; 42 | } 43 | operate("withdraw " + amount, shouldPerform); 44 | } 45 | } 46 | 47 | public class BridgePattern { 48 | public static void main(String[] args) { 49 | SimpleAccount account = new SimpleAccount(100); 50 | account.withdraw(75); 51 | 52 | if (account.isBalanceLow()) { 53 | // you can also change the Logger implementation at runtime 54 | account.setLogger(Logger.warning()); 55 | } 56 | 57 | account.withdraw(10); 58 | account.withdraw(100); 59 | } 60 | } -------------------------------------------------------------------------------- /Patterns/DiamondPattern.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class DiamondPattern { 4 | public static void main(String[] args) { 5 | Scanner sc = new Scanner(System.in); 6 | System.out.print("Enter a number for printing Diamond Pattern:"); 7 | int size = sc.nextInt(); 8 | 9 | for (int i = 1; i <= size; i++) { 10 | for (int j = 1; j <= 2*(size - i); j++) { 11 | System.out.print(" "); 12 | } 13 | for (int j = 1; j <= 2*i - 1; j++) { 14 | System.out.print("*"+" "); 15 | } 16 | System.out.println(); 17 | } 18 | for (int i = 1; i <= size - 1; i++) { 19 | for (int j = 1; j <= 2*i; j++) { 20 | System.out.print(" "); 21 | } 22 | for (int j = 1; j <= 2*(size - i) - 1; j++) { 23 | System.out.print("*"+" "); 24 | } 25 | System.out.println(); 26 | } 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Patterns/Fibonacci.java: -------------------------------------------------------------------------------- 1 | public class Fibonacci 2 | { 3 | static void printSeries() 4 | { 5 | int a = 0,b = 1,c = 1; 6 | System.out.print(a+" "); 7 | for (int i = 1; i < 20; i++) 8 | { 9 | System.out.print(c+" "); 10 | c = a + b; 11 | a = b; 12 | b = c; 13 | } 14 | } 15 | 16 | public static void main(String a[]) 17 | { 18 | printSeries(); 19 | } 20 | } -------------------------------------------------------------------------------- /Patterns/FishPattern.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | This code prints the Fish Pattern, 4 | 5 | Enter any number to generate Fish Pattern. 6 | 7 | 8 | */ 9 | import java.util.Scanner; 10 | 11 | public class FishPattern { 12 | 13 | public static void main(String[] args) { 14 | Scanner sc = new Scanner(System.in); 15 | System.out.print("Enter a number for printing Fish Pattern:"); 16 | int size = sc.nextInt(); 17 | 18 | for (int i = 1; i <= size; i++) { 19 | if (i == size) 20 | break; 21 | for (int j = 1; j <= i - 1; j++) { 22 | System.out.print("*"); 23 | } 24 | for (int j = 1; j <= size - i; j++) { 25 | System.out.print(" "); 26 | } 27 | for (int j = 1; j <= 2 * i - 1; j++) { 28 | System.out.print("* "); 29 | } 30 | System.out.println(); 31 | } 32 | for (int i = 1; i <= size; i++) { 33 | for (int j = 1; j <= size - i; j++) { 34 | System.out.print("*"); 35 | } 36 | for (int j = 1; j <= i - 1; j++) { 37 | System.out.print(" "); 38 | } 39 | for (int j = 1; j <= 2 * (size - i) + 1; j++) { 40 | System.out.print("* "); 41 | } 42 | System.out.println(); 43 | } 44 | sc.close(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Patterns/FlyodsTriangle.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class FlyodsTriangle { 4 | public static void main(String[] args) { 5 | Scanner sc = new Scanner(System.in); 6 | System.out.print("Enter a number for printing Flyods Triangle:"); 7 | int size = sc.nextInt(); 8 | int num = 1; 9 | 10 | for (int i = 1; i <= size; i++) { 11 | for (int j = 1; j <= i; j++) { 12 | System.out.print(num+++" "); 13 | } 14 | System.out.println(); 15 | } 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Patterns/HourGlassPattern.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class HourGlassPattern { 4 | public static void main(String args[]){ 5 | Scanner scan = new Scanner(System.in); 6 | System.out.println(); 7 | int n, i, j; 8 | System.out.print("Enter a number: "); 9 | n = scan.nextInt(); 10 | 11 | for(i=0; i<=n; i++){ 12 | for(j=0; j=1) 15 | System.out.print(" "); 16 | } 17 | for(j=n-i;j>=0;j--){ 18 | System.out.print(j+" "); 19 | } 20 | for(j=1;j<=n-i;j++){ 21 | System.out.print(j+" "); 22 | } 23 | System.out.print("\n"); 24 | } 25 | for(i=n-1; i>=0; i--){ 26 | for(j=0; j=1) 29 | System.out.print(" "); 30 | } 31 | for(j=n-i;j>=0;j--){ 32 | System.out.print(j+" "); 33 | } 34 | for(j=1;j<=n-i;j++){ 35 | System.out.print(j+" "); 36 | } 37 | System.out.print("\n"); 38 | } 39 | 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Patterns/PascalsTriangle.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class PascalsTriangle{ 4 | public static void main (String args[]){ 5 | System.out.println("Please! Enter a Number"); 6 | Scanner numberInput = new Scanner(System.in); 7 | int number = numberInput.nextInt(); 8 | int spaces = number; 9 | int numberNew = 1; 10 | 11 | if (number <= 10){ 12 | for(int i=0; i < number; i++){ 13 | for(int s=1 ; s<=spaces; s++){ 14 | System.out.print(" "); 15 | } 16 | 17 | numberNew = 1; 18 | for(int j=0 ; j <= i ; j++){ 19 | System.out.print(numberNew + " "); 20 | numberNew = numberNew * (i-j)/(j+1); 21 | } 22 | spaces--; 23 | System.out.println(); 24 | } 25 | } 26 | else{ 27 | System.out.println("Please, Enter a Valid No., Less than or Equal to 10"); 28 | } 29 | } 30 | 31 | } -------------------------------------------------------------------------------- /Patterns/PrototypePattern.java: -------------------------------------------------------------------------------- 1 | // Prototype pattern 2 | abstract class Prototype implements Cloneable { 3 | public Prototype clone() throws CloneNotSupportedException{ 4 | return (Prototype) super.clone(); 5 | } 6 | } 7 | 8 | class ConcretePrototype1 extends Prototype { 9 | @Override 10 | public Prototype clone() throws CloneNotSupportedException { 11 | return (ConcretePrototype1)super.clone(); 12 | } 13 | } 14 | 15 | class ConcretePrototype2 extends Prototype { 16 | @Override 17 | public Prototype clone() throws CloneNotSupportedException { 18 | return (ConcretePrototype2)super.clone(); 19 | } 20 | } 21 | 22 | public class PrototypePattern { 23 | 24 | public static void main (String [] args) throws CloneNotSupportedException { 25 | Prototype car1 = new ConcretePrototype1(); 26 | Prototype car2 = new ConcretePrototype2(); 27 | 28 | Prototype anotherCar1 = car1.clone(); 29 | Prototype anotherCar2 = car2.clone(); 30 | } 31 | } -------------------------------------------------------------------------------- /Patterns/PyramidPattern.java: -------------------------------------------------------------------------------- 1 | /* 2 | This code prints Pyramid Pattern, 3 | 4 | Enter any number to generate Pattern. 5 | 6 | 7 | */ 8 | 9 | import java.util.*; 10 | 11 | public class PyramidPattern { 12 | public static void main(String args[]) { 13 | Scanner sc = new Scanner(System.in); 14 | System.out.print("Enter a number for printing Pyramid Pattern:"); 15 | int size = sc.nextInt(); 16 | for (int i = 1; i <= size - 1; i++) { 17 | for (int j = 1; j <= size - i; j++) { 18 | System.out.print(" "); 19 | } 20 | for (int j = 1; j <= 2 * i - 1; j++) { 21 | System.out.print("* "); 22 | } 23 | 24 | System.out.println(); 25 | } 26 | sc.close(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Patterns/RightTriangleStarPattern.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /* 4 | Enter the number of rows: 10 5 | 6 | * 7 | * * 8 | * * * 9 | * * * * 10 | * * * * * 11 | * * * * * * 12 | * * * * * * * 13 | * * * * * * * * 14 | * * * * * * * * * 15 | * * * * * * * * * * 16 | */ 17 | 18 | public class RightTriangleStarPattern { 19 | public static void main(String args[]) { 20 | Scanner sc = new Scanner(System.in); 21 | System.out.print("Enter the number of rows: "); 22 | int n = sc.nextInt(); 23 | 24 | System.out.println(); 25 | for(int i=1; i<=n; i++){ 26 | for(int j=1; j<=i; j++){ 27 | System.out.print("* "); 28 | } 29 | System.out.println(); 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /Patterns/Singleton.java: -------------------------------------------------------------------------------- 1 | class Coin { 2 | 3 | private static final int ADD_MORE_COIN = 10; 4 | private int coin; 5 | private static Coin instance = new Coin(); // eagerly loads the singleton 6 | 7 | private Coin() { 8 | // private to prevent anyone else from instantiating 9 | } 10 | 11 | public static Coin getInstance() { 12 | return instance; 13 | } 14 | 15 | public int getCoin() { 16 | return coin; 17 | } 18 | 19 | public void addMoreCoin() { 20 | coin += ADD_MORE_COIN; 21 | } 22 | 23 | public void deductCoin() { 24 | coin--; 25 | } 26 | } 27 | 28 | public class Singleton { 29 | 30 | public static void main(String [] args) { 31 | Coin coin = Coin.getInstance(); 32 | coin.addMoreCoin(); 33 | } 34 | 35 | } -------------------------------------------------------------------------------- /Patterns/TrianglePattern.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class TrianglePattern { 4 | 5 | static void Printpattern(int n) 6 | { 7 | int i,j,k; 8 | 9 | for(i = 1; i <= n; i++) 10 | { 11 | for(j = 0; j <= n-i; j++) 12 | System.out.print(" "); 13 | 14 | for(j = i,k = 0;k <= (2*i-1)/2; j++, k++) 15 | System.out.print(j+" "); 16 | 17 | j-=2; 18 | 19 | while(j >= i) 20 | { 21 | 22 | System.out.print(j+" "); 23 | j--; 24 | } 25 | 26 | System.out.println(); 27 | } 28 | 29 | } 30 | 31 | public static void main(String args[]) { 32 | 33 | System.out.println("Enter number of rows for printing triangle pattern"); 34 | Scanner sc=new Scanner(System.in); 35 | int rows=sc.nextInt(); 36 | 37 | Printpattern(rows); 38 | } 39 | } -------------------------------------------------------------------------------- /Patterns/TrianglePattern123.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Pattern28 { 4 | 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | Scanner sc = new Scanner(System.in); 8 | int n=0; 9 | if(sc.hasNext()) { 10 | n = sc.nextInt(); 11 | } 12 | 13 | int nsp=n-1; 14 | int nst=1; 15 | int val; 16 | 17 | int row=1; 18 | while(row<=n) { 19 | // spaces 20 | for(int csp=1;csp<=nsp;csp++) { 21 | System.out.print("\t"); 22 | } 23 | 24 | // stars 25 | val=row; 26 | for(int cst = 1;cst<=nst;cst++) { 27 | System.out.print(val +"\t"); 28 | // work 29 | if(cst<=nst/2) { 30 | val++; 31 | }else { 32 | val--; 33 | } 34 | } 35 | 36 | // prep 37 | System.out.println(); 38 | nsp--; 39 | nst+=2; 40 | row++; 41 | } 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /Patterns/add: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Patterns/pascaltri.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class pascaltri 3 | { 4 | static int factorial(int n) 5 | { 6 | int f=1; 7 | for(int i=1; i<=n; i++) 8 | f=f*i; 9 | return(f); 10 | } 11 | static int ncr(int x, int y) 12 | { 13 | return(factorial(x)/(factorial(x-y)*factorial(y))); 14 | } 15 | public static void main(String[] args) 16 | { 17 | int i,j,rows; 18 | Scanner sc=new Scanner(System.in); 19 | rows=sc.nextInt(); 20 | for(i=0; i multiples=new ArrayList();//List representation 17 | int primeFactor=2; 18 | 19 | while(num!=1) { 20 | if(num%primeFactor==0) { 21 | 22 | if(splitNum.length()==0) 23 | splitNum=String.valueOf(primeFactor); 24 | else 25 | splitNum+="*"+String.valueOf(primeFactor); 26 | 27 | multiples.add(primeFactor); 28 | num/=primeFactor; 29 | }else { 30 | primeFactor=getNextPrime(primeFactor); 31 | } 32 | } 33 | 34 | return splitNum; 35 | } 36 | 37 | private static int getNextPrime(int factor) { 38 | int temp=factor+1; 39 | while(!isPrime(temp)) { 40 | temp+=1; 41 | } 42 | return temp; 43 | } 44 | 45 | private static boolean isPrime(int num) { 46 | 47 | if(num==2||num==3) { 48 | return true; 49 | } 50 | 51 | int increment=1; 52 | if(num%2==1) {//if number is odd, it can never have an even factor 53 | increment=2; 54 | } 55 | double srt=Math.sqrt(num); 56 | 57 | for(int i=2;i> Fork it 22 | 23 | Clone it to your local system 24 | 25 | Make a new branch 26 | 27 | Make your changes 28 | 29 | Push it back to your repo 30 | 31 | Click the Compare & pull request button 32 | 33 | Click Create pull request to open a new pull request 34 | 35 | If the reviewers ask for changes, repeat steps 5 and 6 to add more commits to your pull request. 36 | 37 | The implementations/codes which are added/merged in JAVA-: 38 | 39 | ### Contributors :pray: :dizzy: 40 | ![10](https://contributors-img.web.app/image?repo=akshitagit/JAVA) 41 | 42 | 43 | Happy coding! 44 | -------------------------------------------------------------------------------- /Recursion&Backtracking/FibonacciSequence: -------------------------------------------------------------------------------- 1 | public class FibonacciSequence{ 2 | public int fib(int n){ 3 | if (n == 1 || n == 2) 4 | return 1; 5 | else 6 | return fib(n-1) + fib(n-2); 7 | } 8 | } -------------------------------------------------------------------------------- /Recursion&Backtracking/NKnightProblem.java: -------------------------------------------------------------------------------- 1 | /* Knight's tour is a problem in which we are provided with a NxN chessboard and a knight.Similar to the N-Queens problem, we start by moving the knight and if the knight reaches to a cell from where there is no further cell available to move and we have not reached to the solution yet (not all cells are covered), then we backtrack and change our decision and choose a different path. 2 | 3 | So from a cell, we choose a move of the knight from all the moves available, 4 | and then recursively check if this will lead us to the solution or not. 5 | If not, then we choose a different path.*/ 6 | 7 | import java.util.Scanner; 8 | 9 | public class NKnightProblem { 10 | 11 | private static Scanner sc; 12 | 13 | public static void main(String[] args) { 14 | sc = new Scanner(System.in); 15 | int n = sc.nextInt(); 16 | 17 | boolean board[][] = new boolean[3][4]; 18 | 19 | int c = allc(0, 0, 0, board); 20 | System.out.println(c); 21 | all(0,0,0, "", board); 22 | 23 | } 24 | 25 | public static int allc(int row, int col, int kpsf,boolean v[][]) { 26 | if (kpsf == v.length) { //knight placed so far 27 | //System.out.print(ans + " "); 28 | return 1; 29 | } 30 | 31 | int count = 0; 32 | 33 | for (int c = col; c < v[0].length; c++) { 34 | if (issafe(row, c, v)) { 35 | 36 | v[row][c] = true; 37 | 38 | count = count + allc(row, c + 1, kpsf + 1, v); 39 | v[row][c] = false; 40 | } 41 | 42 | } 43 | 44 | for (int r = row + 1; r < v.length; r++) { 45 | for (int c = 0; c < v[0].length; c++) { 46 | if (issafe(r, c, v)) { 47 | 48 | v[r][c] = true; 49 | count = count + allc(r, c + 1, kpsf + 1,v); 50 | v[r][c] = false; 51 | } 52 | 53 | } 54 | } 55 | return count; 56 | 57 | } 58 | //kpsf->knight placed so far 59 | 60 | public static void all(int row, int col, int kpsf,String ans, boolean v[][]) { 61 | if (kpsf == v.length) { 62 | 63 | System.out.println(ans + " "); 64 | return ; 65 | } 66 | 67 | 68 | 69 | for (int c = col; c < v[0].length; c++) { 70 | if (issafe(row, c, v)) { 71 | 72 | v[row][c] = true; 73 | 74 | all(row, c + 1, kpsf + 1, ans + "{" + row + "-" + c + "}" + " ", v); 75 | v[row][c] = false; 76 | } 77 | 78 | } 79 | 80 | for (int r = row + 1; r < v.length; r++) { 81 | for (int c = 0; c < v[0].length; c++) { 82 | if (issafe(r, c, v)) { 83 | 84 | v[r][c] = true; 85 | all(r, c + 1, kpsf + 1, ans + "{" + r + "-" + c + "}" + " ",v); 86 | v[r][c] = false; 87 | } 88 | 89 | } 90 | } 91 | 92 | 93 | } 94 | //if it is safe to place the knight at row and col return true else false 95 | 96 | public static boolean issafe(int row, int col, boolean v[][]) { 97 | 98 | if (v[row][col]) 99 | return false; 100 | 101 | int c = col; 102 | int r = row - 2; 103 | if (r >= 0 && c + 1 < v.length) { 104 | if (v[r][c + 1]) 105 | return false; 106 | } 107 | if (r >= 0 && c - 1 >= 0) { 108 | if (v[r][c - 1]) 109 | return false; 110 | } 111 | r = row - 1; 112 | c = col; 113 | if (r >= 0 && c - 2 >= 0) { 114 | if (v[r][c - 2]) 115 | return false; 116 | } 117 | if (r >= 0 && c + 2 < v.length) { 118 | if (v[r][c + 2]) 119 | return false; 120 | } 121 | 122 | 123 | 124 | return true; 125 | } 126 | 127 | } 128 | -------------------------------------------------------------------------------- /Recursion&Backtracking/NQueenProblem.java: -------------------------------------------------------------------------------- 1 | // N-Queen Problem using Backtracking 2 | /* 3 | The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. 4 | The solution uses Backtracking to solve the problem. 5 | The expected output will contain all possible positions to place the queens. 6 | 7 | */ 8 | 9 | import java.util.Scanner; 10 | 11 | class Solution 12 | { 13 | public static boolean isItSafeToPlaceQueen(boolean[][] board, int row, int col) { 14 | 15 | 16 | int r = row - 1; 17 | int c = col; 18 | while (r >= 0) { 19 | if (board[r][c]) { 20 | return false; 21 | } 22 | r--; 23 | } 24 | 25 | r = row; 26 | c = col - 1; 27 | while (c >= 0) { 28 | if (board[r][c]) { 29 | return false; 30 | } 31 | c--; 32 | } 33 | 34 | r = row - 1; 35 | c = col - 1; 36 | while (r >= 0 && c >= 0) { 37 | if (board[r][c]) { 38 | return false; 39 | } 40 | r--; 41 | c--; 42 | } 43 | 44 | r = row - 1; 45 | c = col + 1; 46 | while (r >= 0 && c < board[0].length) { 47 | if (board[r][c]) { 48 | return false; 49 | } 50 | r--; 51 | c++; 52 | ; 53 | } 54 | return true; 55 | } 56 | 57 | public static void NQueen(boolean[][] board, int row, int col, int queensPlaced, int totalQueens, String ans) { 58 | 59 | if (queensPlaced == totalQueens) { 60 | System.out.println(ans); 61 | return; 62 | } 63 | 64 | if (col == board[0].length) { 65 | col = 0; 66 | row++; 67 | } 68 | 69 | if (row == board.length) { 70 | return; 71 | } 72 | 73 | if (isItSafeToPlaceQueen(board, row, col)) { 74 | board[row][col] = true; 75 | NQueen(board, row, col + 1, queensPlaced + 1, totalQueens, ans + "[" + row + "-" + col + "]"); 76 | board[row][col] = false; 77 | } 78 | NQueen(board, row, col + 1, queensPlaced, totalQueens, ans); 79 | 80 | } 81 | 82 | 83 | public static void main(String [] args){ 84 | 85 | Scanner s=new Scanner(System.in); 86 | int N=s.nextInt(); 87 | boolean[][] board=new boolean[N][N]; 88 | NQueen(board, 0, 0,0, N ,""); 89 | 90 | } 91 | 92 | } 93 | 94 | 95 | /* Input : 96 | 4 97 | 98 | Output : 99 | [0-1][1-3][2-0][3-2] 100 | [0-2][1-0][2-3][3-1] 101 | 102 | */ 103 | -------------------------------------------------------------------------------- /Recursion&Backtracking/RatInAMaze.java: -------------------------------------------------------------------------------- 1 | /* Java program to solve Rat in 2 | a Maze problem using backtracking */ 3 | 4 | class RatMaze { 5 | 6 | // Size of the maze 7 | static int N; 8 | 9 | /* A utility function to print 10 | solution matrix sol[N][N] */ 11 | void printSolution(int sol[][]) 12 | { 13 | for (int i = 0; i < N; i++) { 14 | for (int j = 0; j < N; j++) 15 | System.out.print( 16 | " " + sol[i][j] + " "); 17 | System.out.println(); 18 | } 19 | } 20 | 21 | /* A utility function to check 22 | if x, y is valid index for N*N maze */ 23 | boolean isSafe( 24 | int maze[][], int x, int y) 25 | { 26 | // if (x, y outside maze) return false 27 | return (x >= 0 && x < N && y >= 0 28 | && y < N && maze[x][y] == 1); 29 | } 30 | 31 | /* This function solves the Maze problem using 32 | Backtracking. It mainly uses solveMazeUtil() 33 | to solve the problem. It returns false if no 34 | path is possible, otherwise return true and 35 | prints the path in the form of 1s. Please note 36 | that there may be more than one solutions, this 37 | function prints one of the feasible solutions.*/ 38 | boolean solveMaze(int maze[][]) 39 | { 40 | int sol[][] = new int[N][N]; 41 | 42 | if (solveMazeUtil(maze, 0, 0, sol) == false) { 43 | System.out.print("Solution doesn't exist"); 44 | return false; 45 | } 46 | 47 | printSolution(sol); 48 | return true; 49 | } 50 | 51 | /* A recursive utility function to solve Maze 52 | problem */ 53 | boolean solveMazeUtil(int maze[][], int x, int y, 54 | int sol[][]) 55 | { 56 | // if (x, y is goal) return true 57 | if (x == N - 1 && y == N - 1 58 | && maze[x][y] == 1) { 59 | sol[x][y] = 1; 60 | return true; 61 | } 62 | 63 | // Check if maze[x][y] is valid 64 | if (isSafe(maze, x, y) == true) { 65 | // mark x, y as part of solution path 66 | sol[x][y] = 1; 67 | 68 | /* Move forward in x direction */ 69 | if (solveMazeUtil(maze, x + 1, y, sol)) 70 | return true; 71 | 72 | /* If moving in x direction doesn't give 73 | solution then Move down in y direction */ 74 | if (solveMazeUtil(maze, x, y + 1, sol)) 75 | return true; 76 | 77 | /* If none of the above movements works then 78 | BACKTRACK: unmark x, y as part of solution 79 | path */ 80 | sol[x][y] = 0; 81 | return false; 82 | } 83 | 84 | return false; 85 | } 86 | 87 | public static void main(String args[]) 88 | { 89 | RatMaze rat = new RatMaze(); 90 | int maze[][] = { { 1, 0, 0, 0 }, 91 | { 1, 1, 0, 1 }, 92 | { 0, 1, 0, 0 }, 93 | { 1, 1, 1, 1 } }; 94 | 95 | N = maze.length; 96 | rat.solveMaze(maze); 97 | } 98 | } -------------------------------------------------------------------------------- /Recursion&Backtracking/StringSubset.java: -------------------------------------------------------------------------------- 1 | /* Generate subtes of a given string 2 | */ 3 | import java.util.Scanner; 4 | public class StringSubset { 5 | static void SubSets(String str, String current, int index){ 6 | if(index==str.length()) { 7 | System.out.println(current + " "); 8 | return; 9 | } 10 | /* Two cases for every character 11 | (i) We consider the character as part of current subset 12 | (ii) We do not consider current character as part of current subset */ 13 | SubSets(str,current+str.charAt(index), index+1); 14 | SubSets(str,current, index+1); 15 | 16 | } 17 | //Driver code 18 | public static void main(String[] args) { 19 | Scanner scan = new Scanner(System.in); 20 | System.out.println("Enter the string you want to generate substrings of"); 21 | String str = scan.nextLine(); 22 | int index =0; 23 | String current = ""; 24 | SubSets(str,current ,index); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Recursion&Backtracking/SudokuSolver.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | class SudokuSolver { 4 | static class FastReader{ 5 | BufferedReader br; 6 | StringTokenizer st; 7 | FastReader(){ 8 | br = new BufferedReader(new InputStreamReader(System.in)); 9 | } 10 | String next(){ 11 | while(st==null || !st.hasMoreElements()){ 12 | try{ 13 | st =new StringTokenizer(br.readLine()); 14 | } 15 | catch(IOException e) { 16 | e.printStackTrace(); 17 | } 18 | } 19 | return st.nextToken(); 20 | } 21 | int nextInt(){ 22 | return Integer.parseInt(next()); 23 | } 24 | } 25 | public static void main(String[] args) { 26 | FastReader fr = new FastReader(); 27 | int n = fr.nextInt(); 28 | int[][] board = new int[n][n]; 29 | for(int i=0;i0) 23 | { 24 | String s[]=bu.readLine().split(" "); 25 | int p=Integer.parseInt(s[0]),q=Integer.parseInt(s[1]); 26 | int ans=soup(p,q); 27 | sb.append(ans+"\n"); 28 | } 29 | System.out.print(sb); 30 | } 31 | 32 | static int soup(int p,int q) 33 | { 34 | if(p==1) return q*(q+1)/2; 35 | return soup(p-1,q*(q+1)/2); 36 | } 37 | } 38 | 39 | /* 40 | i/p- 41 | 3 42 | 2 3 43 | 1 5 44 | 2 4 45 | 46 | o/p- 47 | 27 48 | 15 49 | 65 50 | */ 51 | -------------------------------------------------------------------------------- /Recursion&Backtracking/add: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Recursion&Backtracking/n to 1.java: -------------------------------------------------------------------------------- 1 | /*package whatever //do not write package name here */ 2 | 3 | import java.io.*; 4 | import java.util.*; 5 | 6 | class GFG { 7 | 8 | 9 | static void printToN(int n) 10 | { 11 | if(n == 0) 12 | return; 13 | 14 | System.out.print(n+" "); 15 | 16 | printToN(n - 1); 17 | 18 | } 19 | public static void main(String [] args) 20 | { 21 | int n = 4; 22 | 23 | printToN(n); 24 | 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /Recursion&Backtracking/toh.java: -------------------------------------------------------------------------------- 1 | 2 | public class toh { 3 | 4 | static void ToH(int n, char A, char B, char C) 5 | { 6 | if (n == 1) 7 | { 8 | System.out.println("Move 1 from " + A + " to " + C); 9 | return; 10 | } 11 | ToH(n-1, A, C, B); 12 | System.out.println("Move " + n + " from " + A + " to " + C); 13 | ToH(n-1, B, A, C); 14 | } 15 | 16 | 17 | public static void main(String args[]) 18 | { 19 | int n = 2; 20 | ToH(n, 'A', 'B', 'C'); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Searching & Sorting/BinarySearch.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | class BinarySearch { 4 | 5 | int binarySearch(int arr[], int start, int end, int x){ 6 | if(end >= start){ 7 | int mid = start + (end - start)/2; 8 | if(arr[mid] == x) 9 | return mid; 10 | 11 | if (arr[mid] > x) 12 | return binarySearch(arr, start, mid - 1, x); 13 | 14 | 15 | return binarySearch(arr, mid + 1, end, x); 16 | } 17 | return -1; 18 | } 19 | public static void main(String[] args) { 20 | BinarySearch bs = new BinarySearch(); 21 | int arr[] = { 1, 3, 5, 10, 35 }; 22 | int n = arr.length; 23 | int x = 10; 24 | int result = bs.binarySearch(arr, 0, n - 1, x); 25 | if (result == -1) 26 | System.out.println("Element is not present in the given array"); 27 | else 28 | System.out.println(result); // prints index of the element; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Searching & Sorting/Bogosort.java: -------------------------------------------------------------------------------- 1 | // Java Program to implement BogoSort. 2 | //WORST SORTING ALGORITHM that uses concept of permutation. 3 | //also known as stupid sort, slow sort or monkey sort. 4 | public class BogoSort { 5 | void bogoSort(int[] arr) 6 | { 7 | // if array is not sorted then shuffle the 8 | // array again 9 | while (isSorted(arr) == false) 10 | shuffle(arr); 11 | } 12 | 13 | // generating permuatation of the array 14 | void shuffle(int[] arr) 15 | { 16 | // Math.random() returns a positive number with double data type 17 | // value greater than or equal to 0.0 and less than 1.0. 18 | for (int i = 0; i < arr.length; i++) { 19 | int j = (int)(Math.random()*i); 20 | //swapping two elements 21 | int temp = arr[i]; 22 | arr[i] = arr[j]; 23 | arr[j] = temp; 24 | } 25 | } 26 | // To check if array is sorted or not 27 | boolean isSorted(int[] arr) 28 | { 29 | for (int i = 1; i < arr.length; i++) 30 | if (arr[i] < arr[i - 1]) 31 | return false; 32 | return true; 33 | } 34 | 35 | // Prints the array 36 | void printArray(int[] arr) 37 | { 38 | for (int i = 0; i < arr.length; i++) 39 | System.out.print(arr[i] + " "); 40 | System.out.println(); 41 | } 42 | 43 | public static void main(String[] args) 44 | { 45 | // Enter array to be sorted here 46 | int[] arr = { 3, 2, 5, 1, 0, 4 }; 47 | BogoSort ob = new BogoSort(); 48 | ob.bogoSort(arr); 49 | System.out.print("Sorted array: "); 50 | ob.printArray(arr); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Searching & Sorting/BubbleSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class BubbleSort 4 | { 5 | void bubbleSort(int array[]) 6 | { 7 | int n = array.length; 8 | for (int i = 0; i < n-1; i++) 9 | for (int j = 0; j < n-i-1; j++) 10 | if (array[j] > array[j+1]) 11 | { 12 | array[j+1] = array[j] + array[j+1] - (array[j] = array[j+1]); // Optimized Swapping 13 | } 14 | } 15 | 16 | public static void main(String args[]) 17 | { 18 | BubbleSort bs = new BubbleSort(); 19 | int array[] = {64, 34, 25, 12, 22, 11, 90}; 20 | System.out.println("Before Bubble Sort:"+Arrays.toString(array)); 21 | bs.bubbleSort(array); 22 | System.out.println("After Bubble Sort:"+Arrays.toString(array)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Searching & Sorting/BucketSort.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.util.Collections; 3 | 4 | public class BucketSort { 5 | 6 | // Function to sort arr[] of size n 7 | // using bucket sort 8 | public static void bucketSort(float arr[], int n) 9 | { 10 | if (n <= 0) 11 | return; 12 | 13 | // 1) Create n empty buckets 14 | @SuppressWarnings("unchecked") 15 | Vector[] buckets = new Vector[n]; 16 | 17 | for (int i = 0; i < n; i++) { 18 | buckets[i] = new Vector(); 19 | } 20 | 21 | // 2) Put array elements in different buckets 22 | for (int i = 0; i < n; i++) { 23 | float idx = arr[i] * n; 24 | buckets[(int)idx].add(arr[i]); 25 | } 26 | 27 | // 3) Sort individual buckets 28 | for (int i = 0; i < n; i++) { 29 | Collections.sort(buckets[i]); 30 | } 31 | 32 | // 4) Concatenate all buckets into arr[] 33 | int index = 0; 34 | for (int i = 0; i < n; i++) { 35 | for (int j = 0; j < buckets[i].size(); j++) { 36 | arr[index++] = buckets[i].get(j); 37 | } 38 | } 39 | } 40 | 41 | // Driver code 42 | public static void main(String args[]) 43 | { 44 | float arr[] = { (float)0.897, (float)0.565, 45 | (float)0.656, (float)0.1234, 46 | (float)0.665, (float)0.3434 }; 47 | 48 | int n = arr.length; 49 | bucketSort(arr, n); 50 | 51 | System.out.println("Sorted array is "); 52 | for (float el : arr) { 53 | System.out.print(el + " "); 54 | } 55 | } 56 | } 57 | 58 | /*Output: 59 | * Sorted array is 60 | 0.1234 0.3434 0.565 0.656 0.665 0.897 */ 61 | -------------------------------------------------------------------------------- /Searching & Sorting/CountingSort.java: -------------------------------------------------------------------------------- 1 | class CountingSort { 2 | 3 | void sort(char arr[]) 4 | { 5 | int n = arr.length; 6 | char output[] = new char[n]; 7 | int count[] = new int[256]; 8 | 9 | for (int i = 0; i < 256; ++i) 10 | count[i] = 0; 11 | 12 | for (int i = 0; i < n; ++i) 13 | ++count[arr[i]]; 14 | 15 | for (int i = 1; i <= 255; ++i) 16 | count[i] += count[i - 1]; 17 | 18 | for (int i = n - 1; i >= 0; i--) { 19 | output[count[arr[i]] - 1] = arr[i]; 20 | --count[arr[i]]; 21 | } 22 | 23 | for (int i = 0; i < n; ++i) 24 | arr[i] = output[i]; 25 | } 26 | 27 | 28 | public static void main(String args[]) 29 | { 30 | CountingSort cs = new CountingSort(); 31 | char arr[] = { 'a', 'e', 'e', 'b', 's', 'd', 'z', 32 | 'r', 'g', 'e', 'e', 'k', 's' }; 33 | 34 | cs.sort(arr); 35 | 36 | System.out.print("Sorted character array is "); 37 | for (int i = 0; i < arr.length; ++i) 38 | System.out.print(arr[i]); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Searching & Sorting/HeapSort.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | class HeapSort { 4 | 5 | static void sort(int[] a) { 6 | ArrayList heap = new ArrayList(); 7 | for (int i : a) { 8 | // add i at the end and swap it into the right position 9 | trickleUp(heap, i); 10 | } 11 | for (int i = 0; i < a.length; i++) { 12 | a[i] = heap.get(0); 13 | if (heap.size() > 1) { 14 | heap.set(0, heap.remove(heap.size() - 1)); 15 | trickleDown(heap); 16 | } 17 | } 18 | 19 | } 20 | 21 | static void trickleDown(ArrayList heap) { 22 | int i = heap.get(0); 23 | int index = 0; 24 | while (heap.size() >= (index + 1) * 2) { 25 | int l = heap.get((index + 1) * 2 - 1); 26 | // swap i with bigger child 27 | if (i < l) { 28 | if (heap.size() > (index + 1) * 2) { 29 | int r = heap.get((index + 1) * 2); 30 | if (r > l) { 31 | heap.set(index, r); 32 | index = (index + 1) * 2; 33 | heap.set(index, i); 34 | } else { 35 | heap.set(index, l); 36 | index = (index + 1) * 2 - 1; 37 | heap.set(index, i); 38 | 39 | } 40 | } else 41 | break; 42 | } else { 43 | if (heap.size() > (index + 1) * 2) { 44 | int r = heap.get((index + 1) * 2); 45 | if (r > i) { 46 | heap.set(index, r); 47 | index = (index + 1) * 2; 48 | heap.set(index, i); 49 | } else 50 | break; 51 | } else 52 | break; 53 | } 54 | } 55 | } 56 | 57 | static void trickleUp(ArrayList heap, int i) { 58 | heap.add(i); 59 | int index = heap.size() - 1; 60 | while (index > 0 && i > heap.get((index - 1) / 2)) { 61 | // swap i and its parent if i is bigger than the parent 62 | heap.set(index, heap.get((index - 1) / 2)); 63 | index = (index - 1) / 2; 64 | heap.set(index, i); 65 | 66 | } 67 | } 68 | 69 | public static void main(String[] args) { 70 | int[] a = new int[] { 17, 3, 2, 6, 5, 9, 6, 14, 0, 4, 7, 3, 9, 4, 1 }; 71 | System.out.println("Unsorted Array: "); 72 | for (int i : a) { 73 | System.out.print(i + " "); 74 | } 75 | sort(a); 76 | System.out.println("\n\nSorted Array: "); 77 | for (int i : a) { 78 | System.out.print(i + " "); 79 | } 80 | } 81 | 82 | } 83 | -------------------------------------------------------------------------------- /Searching & Sorting/InsertionSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | class InsertionSort { 4 | void sort(int arr[]) 5 | { 6 | int n = arr.length; 7 | for (int i = 1; i < n; ++i) { 8 | int key = arr[i]; 9 | int j = i - 1; 10 | 11 | while (j >= 0 && arr[j] > key) { 12 | arr[j + 1] = arr[j]; 13 | j = j - 1; 14 | } 15 | arr[j + 1] = key; 16 | } 17 | } 18 | 19 | static void printArray(int arr[]) 20 | { 21 | int n = arr.length; 22 | for (int i = 0; i < n; ++i) 23 | System.out.print(arr[i] + " "); 24 | 25 | System.out.println(); 26 | } 27 | 28 | public static void main(String args[]) 29 | { 30 | Scanner sc = new Scanner(System.in); 31 | int n =sc.nextInt(); 32 | int[] arr = new int[n]; 33 | for(int i=0;i end) 24 | return Integer.MAX_VALUE; 25 | int middleValue = sorted[middle]; 26 | if (value == middleValue) 27 | return middle; 28 | if (value > middleValue) 29 | return recursiveFind(value, middle + 1, end); 30 | return recursiveFind(value, start, middle -1); 31 | } 32 | 33 | public static void main(String[] args) { 34 | int[] integers = {10,20,30,40,50,60,70,80,90,100}; 35 | int key = 100; 36 | 37 | int atIndex = InterpolationSearch.find(key, integers); 38 | 39 | System.out.println("The array indes starts from 0"); 40 | System.out.println("The size of the array is : " + integers.length); 41 | System.out.println("The element found at index : " + atIndex); 42 | } 43 | } -------------------------------------------------------------------------------- /Searching & Sorting/JumpSearch.java: -------------------------------------------------------------------------------- 1 | public class JumpSearch { 2 | public static int jumpSearch(int[] sortedArray, int key) { 3 | 4 | int n = sortedArray.length; 5 | int step = (int)Math.floor(Math.sqrt(n)); 6 | int prev = 0; 7 | 8 | while (sortedArray[Math.min(step, n)-1] < key) { 9 | prev = step; 10 | step += (int)Math.floor(Math.sqrt(n)); 11 | if (prev >= n) 12 | return -1; 13 | } 14 | 15 | while (sortedArray[prev] < key) { 16 | prev++; 17 | if (prev == Math.min(step, n)) 18 | return -1; 19 | } 20 | 21 | if (sortedArray[prev] == key) 22 | return prev; 23 | 24 | return -1; 25 | } 26 | public static void main(String [ ] args) { 27 | int sortedArray[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 43, 48, 55, 89, 144, 233, 377, 610}; 28 | int key = 55; 29 | int index = jumpSearch(sortedArray, key); 30 | System.out.println("Number " + key + " is at index " + index); 31 | } 32 | } -------------------------------------------------------------------------------- /Searching & Sorting/LinearSearch.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akshitagit/JAVA/5398fe315c9cc98c5aa761d0906872b0f31cc778/Searching & Sorting/LinearSearch.java -------------------------------------------------------------------------------- /Searching & Sorting/MatrixSearch.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /* 4 | Problem Statement: 5 | Given an N x M matrix, where every row and column is sorted in increasing order, and a number x . 6 | Find if element x is present in the matrix or not. 7 | 8 | Input Format: 9 | 10 | First line consists of two space separated integers N and M, denoting the number of element in a 11 | row and column respectively. Second line of each test case consists of N*M space separated integers 12 | denoting the elements in the matrix in row major order. Third line of each test case contains a 13 | single integer x, the element to be searched. 14 | 15 | Constraints : 1 <= N,M <= 30 0 <= A[i] <= 100000 16 | 17 | Output Format 18 | 19 | Print 1 if the element is present in the matrix, else 0. 20 | 21 | Sample Input 1 22 | 23 | 3 3 24 | 3 30 38 25 | 44 52 54 26 | 57 60 69 27 | 62 28 | 29 | Sample Output 1 30 | 31 | 0 32 | 33 | Sample Input 2 34 | 35 | 4 4 36 | 10 20 30 40 37 | 15 25 35 45 38 | 27 29 37 48 39 | 32 33 39 50 40 | 39 41 | 42 | Sample Output 2 43 | 44 | 1 45 | */ 46 | 47 | public class MatrixSearch { 48 | private static void search(int[][] mat, int n, int m, int x) { 49 | int i = 0, j = m-1; // set indexes for top right element 50 | 51 | while (i < n && j >= 0) { 52 | if (mat[i][j] == x) { 53 | System.out.print("1"); 54 | return; 55 | } 56 | if (mat[i][j] > x) 57 | j--; 58 | else 59 | i++; 60 | } 61 | 62 | System.out.print("0"); 63 | } 64 | 65 | 66 | public static void main(String[] args) { 67 | Scanner sc= new Scanner(System.in); 68 | int n = sc.nextInt(); 69 | int m = sc.nextInt(); 70 | 71 | int[][] arr = new int[n][m]; 72 | for (int i=0; i mx) 12 | mx = arr[i]; 13 | return mx; 14 | } 15 | 16 | // A function to do counting sort of arr[] according to 17 | // the digit represented by exp. 18 | static void countSort(int arr[], int n, int exp) { 19 | int output[] = new int[n]; // output array 20 | int i; 21 | int count[] = new int[10]; 22 | Arrays.fill(count,0); 23 | 24 | // Store count of occurrences in count[] 25 | for (i = 0; i < n; i++) 26 | count[ (arr[i]/exp)%10 ]++; 27 | 28 | // Change count[i] so that count[i] now contains 29 | // actual position of this digit in output[] 30 | for (i = 1; i < 10; i++) 31 | count[i] += count[i - 1]; 32 | 33 | // Build the output array 34 | for (i = n - 1; i >= 0; i--) 35 | { 36 | output[count[ (arr[i]/exp)%10 ] - 1] = arr[i]; 37 | count[ (arr[i]/exp)%10 ]--; 38 | } 39 | 40 | // Copy the output array to arr[], so that arr[] now 41 | // contains sorted numbers according to curent digit 42 | for (i = 0; i < n; i++) 43 | arr[i] = output[i]; 44 | } 45 | 46 | // The main function to that sorts arr[] of size n using 47 | // Radix Sort 48 | static void radixsort(int arr[], int n) { 49 | // Find the maximum number to know number of digits 50 | int m = getMax(arr, n); 51 | 52 | // Do counting sort for every digit. Note that instead 53 | // of passing digit number, exp is passed. exp is 10^i 54 | // where i is current digit number 55 | for (int exp = 1; m/exp > 0; exp *= 10) 56 | countSort(arr, n, exp); 57 | } 58 | 59 | // A utility function to print an array 60 | static void print(int arr[], int n) { 61 | for (int i=0; ijava PartitionApp 4 | //////////////////////////////////////////////////////////////// 5 | class ArrayPar 6 | { 7 | private long[] theArray; // ref to array theArray 8 | private int nElems; // number of data items 9 | //-------------------------------------------------------------- 10 | public ArrayPar(int max) // constructor 11 | { 12 | theArray = new long[max]; // create the array 13 | nElems = 0; // no items yet 14 | } 15 | //-------------------------------------------------------------- 16 | public void insert(long value) // put element into array 17 | { 18 | theArray[nElems] = value; // insert it 19 | nElems++; // increment size 20 | } 21 | //-------------------------------------------------------------- 22 | public int size() // return number of items 23 | { return nElems; } 24 | //-------------------------------------------------------------- 25 | public void display() // displays array contents 26 | { 27 | System.out.print("A="); 28 | for(int j=0; j left && // find smaller item 44 | theArray[--rightPtr] > pivot) 45 | ; // (nop) 46 | if(leftPtr >= rightPtr) // if pointers cross, 47 | break; // partition done 48 | else // not crossed, so 49 | swap(leftPtr, rightPtr); // swap elements 50 | } // end while(true) 51 | return leftPtr; // return partition 52 | } // end partitionIt() 53 | //-------------------------------------------------------------- 54 | public void swap(int dex1, int dex2) // swap two elements 55 | { 56 | long temp; 57 | temp = theArray[dex1]; // A into temp 58 | theArray[dex1] = theArray[dex2]; // B into A 59 | theArray[dex2] = temp; // temp into B 60 | } // end swap() 61 | //-------------------------------------------------------------- 62 | } // end class ArrayPar 63 | //////////////////////////////////////////////////////////////// 64 | class PartitionApp 65 | { 66 | public static void main(String[] args) 67 | { 68 | int maxSize = 16; // array size 69 | ArrayPar arr; // reference to array 70 | arr = new ArrayPar(maxSize); // create the array 71 | 72 | for(int j=0; j lhs = new LinkedHashSet(); 7 | for(int i = 0;i < s.length(); i++){ 8 | lhs.add(s.charAt(i)); 9 | } 10 | 11 | for(Character ch: lhs){ 12 | System.out.print(ch); 13 | } 14 | } 15 | public static void main(String[] args) { 16 | String s = "hhhaackkktobbbeerr"; 17 | RemoveDuplicates rd = new RemoveDuplicates(); 18 | rd.removeDuplicates(s); 19 | } 20 | } 21 | 22 | -------------------------------------------------------------------------------- /Strings/ReverseString.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | public class reversestring { 4 | public static void main(String args[]) { 5 | Scanner sc=new Scanner(System.in); 6 | System.out.print("Enter the string:"); 7 | String s=sc.nextLine(); 8 | 9 | String s1=""; 10 | for(int i=s.length()-1;i>=0;i--) 11 | { 12 | char ch=s.charAt(i); 13 | while(i>=0&&s.charAt(i)==' ') 14 | i--; 15 | int j=i; 16 | if(i<0) 17 | break; 18 | while(i>=0&&s.charAt(i)!=' ') 19 | i--; 20 | if(s1.isEmpty()) { 21 | s1=s1.concat(s.substring(i+1,j+1)); 22 | } 23 | else 24 | s1=s1.concat(" "+s.substring(i+1,j+1)); 25 | } 26 | System.out.print("The reversed string is:"); 27 | System.out.print(s1); 28 | 29 | }} 30 | -------------------------------------------------------------------------------- /Strings/SnakeToCamel.java: -------------------------------------------------------------------------------- 1 | //Converting Snake Case string to Camel Case. 2 | //Input: str = "snake_case_to_camel_case" 3 | //Output: "SnakeCaseToCamelCase" 4 | 5 | import java.io.*; 6 | class SnakeTOCamel { 7 | 8 | // Function to convert snake case to camel case 9 | public static String 10 | snakeToCamel(String str) 11 | { 12 | // Capitalizing first letter of string 13 | str = str.substring(0, 1).toUpperCase() + str.substring(1); 14 | StringBuilder builder = new StringBuilder(str); 15 | // Traversing the string character by 16 | // character and remove underscore 17 | // and capitalize next letter 18 | for (int i = 0; i < builder.length(); i++) { 19 | 20 | // Checking char is underscore 21 | if (builder.charAt(i) == '_') { 22 | 23 | builder.deleteCharAt(i); 24 | builder.replace(i, i + 1,String.valueOf(Character.toUpperCase(builder.charAt(i)))); 25 | } 26 | } 27 | // Returning in String type 28 | return builder.toString(); 29 | } 30 | public static void main(String[] args){ 31 | 32 | // Given String 33 | String str = "snake_to_camel"; 34 | // Function Call 35 | str = snakeToCamel(str); 36 | // Modified String 37 | System.out.println(str); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Strings/StringCompression.java: -------------------------------------------------------------------------------- 1 | public class StringCompression { 2 | 3 | void printCompressedString(String input) { 4 | String compressedWord = ""; 5 | boolean areTheySame = false; 6 | int counter = 1; 7 | 8 | for (int index = 0; index < input.length(); index++) { 9 | final char letter = input.charAt(index); 10 | if (index < input.length() - 1) { 11 | final char nextLetter = input.charAt(index + 1); 12 | if (letter == nextLetter) { 13 | counter++; 14 | areTheySame = true; 15 | } else if (areTheySame) { 16 | compressedWord += String.valueOf(letter) + counter; 17 | counter = 1; 18 | areTheySame = false; 19 | } else { 20 | compressedWord += String.valueOf(letter) + counter; 21 | } 22 | } else { 23 | compressedWord += String.valueOf(letter) + counter; 24 | } 25 | } 26 | System.out.println(compressedWord); 27 | } 28 | 29 | 30 | public static void main(String[] args) { 31 | StringCompression compression = new StringCompression(); 32 | String input = "hhhaaaccckkktttooobbbeeerrr"; 33 | compression.printCompressedString(input); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Strings/StringReverse.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Scanner; 3 | public class StringReverse { 4 | 5 | public static void main(String[] args) 6 | { 7 | Scanner sc=new Scanner(System.in); 8 | String str=sc.next(); 9 | String temp=new String(); 10 | char s[]=str.toCharArray(); 11 | for(int i=0;i 0) { 11 | String pattern = scan.nextLine(); 12 | try { 13 | Pattern.compile(pattern); 14 | System.out.println("Valid"); 15 | } catch (PatternSyntaxException exception) { 16 | System.out.println("Invalid"); 17 | } 18 | } 19 | scan.close(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Strings/ThousandSeparator.java: -------------------------------------------------------------------------------- 1 | // Given an integer n, add a dot (".") as the thousands separator 2 | // and return it in string format. 3 | class ThousandSeparator { 4 | public String thousandSeparator(int n) { 5 | 6 | StringBuilder s = new StringBuilder(); 7 | String ret = Integer.toString(n); 8 | 9 | int end = ret.length()-1; 10 | 11 | if((end+1)<=3) 12 | return ret; 13 | 14 | for(int i = 0;i<=end;i++) { 15 | 16 | 17 | if((end-i)%3==0 && i!=end) { 18 | s.append(ret.charAt(i)); 19 | s.append("."); 20 | } else { 21 | s.append(ret.charAt(i)); 22 | } 23 | } 24 | 25 | return s.toString(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Strings/Tokenizer.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.StringTokenizer; 3 | 4 | /** 5 | * 6 | * @author Maduranga 7 | */ 8 | public class Tokenizer { 9 | 10 | public static void main(String []args){ 11 | String url="http:/Exercise/java.sun.com/j2se/1.4/docs/api"; 12 | 13 | StringTokenizer tokenUrl=new StringTokenizer(url,"/"); 14 | 15 | System.out.println("No of tokens = "+tokenUrl.countTokens()); 16 | 17 | while(tokenUrl.hasMoreTokens()){ 18 | 19 | System.out.println(tokenUrl.nextToken()); 20 | 21 | 22 | 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Strings/add: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Strings/balancedStringSplit.java: -------------------------------------------------------------------------------- 1 | public class balancedStringSplit { 2 | 3 | /** 4 | * Given a balanced string s return the maximum amount of splitted balanced strings. 5 | * Ex : s = "RLRRLLRLRL" 6 | * s can be split into "RL", "RRLL", "RL", "RL" so we return 4 7 | * To solve this we just count the number of R and L and when they are the same we increase the counter 8 | */ 9 | 10 | public static int split(String s) { 11 | 12 | int countofL = 0; 13 | int countofR = 0; 14 | 15 | int count = 0; 16 | 17 | for(int i=0;i freq(128,0); 8 | 9 | while (ei < n) { 10 | if (freq[s.charAt(ei)] == 1) 11 | count++; 12 | freq[s.charAt(ei)]++; 13 | ei++; 14 | 15 | while (count > 0) { 16 | if (freq[s.charAt(si)] == 2) 17 | count--; 18 | freq[s.charAt(si)]--; 19 | si++; 20 | } 21 | 22 | len = Math.max(len, ei - si); 23 | } 24 | 25 | return len; 26 | } 27 | 28 | public static void main(String[] args){ 29 | Scanner scn=new Scanner(System.in); 30 | String str=scn.nextLine(); 31 | System.out.println(lengthOflongestSubstring(str)); 32 | } 33 | 34 | 35 | } 36 | -------------------------------------------------------------------------------- /Strings/string_rotation.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | class string_rotation 5 | { 6 | 7 | // method that rotates s towards left by d 8 | static String leftrotate(String str, int d) 9 | { 10 | String ans = str.substring(d) + str.substring(0, d); 11 | return ans; 12 | } 13 | 14 | // method that rotates s towards right by d 15 | static String rightrotate(String str, int d) 16 | { 17 | return leftrotate(str, str.length() - d); 18 | } 19 | 20 | 21 | public static void main(String args[]) 22 | { 23 | String str1 = "HelloWorld"; 24 | System.out.println(leftrotate(str1, 1)); 25 | 26 | String str2 = "JavaIsLob"; 27 | System.out.println(rightrotate(str2, 1)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Strings/stringcompression.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class stringcompression 3 | { 4 | public static void main(String args[]) 5 | { 6 | Scanner sc=new Scanner(System.in); 7 | String str=sc.nextLine(); 8 | char ch;int c=0; 9 | for(ch='a';ch<='z';ch++) 10 | { 11 | c=0; 12 | for(int i=0;i path= new ArrayList<>(); 7 | 8 | public Path(int n){ 9 | for(int i=0;i "); 21 | r=0; 22 | weight_sum=0; 23 | path= new Path(n); //reset for next iterations 24 | path.setpath(i,1); 25 | edge_vertices[1]=i; 26 | edge_vertices[0]=i; 27 | while (path.check()==0){ 28 | min= undirectedGraph.find_max(); 29 | for(int k=0;k<2;k++){ 30 | for(int j=0;j "); 45 | } 46 | System.out.println(weight_sum); 47 | } 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /Trees & Graphs/SerializeDeserialize.java: -------------------------------------------------------------------------------- 1 | class Tree 2 | { 3 | class Passing{ 4 | int index; 5 | } 6 | 7 | //Function to serialize a tree and return a list containing nodes of tree. 8 | public void serialize(Node root, ArrayList A) 9 | { 10 | //base case if node is null. 11 | if(root==null){ 12 | A.add(-1); 13 | return; 14 | } 15 | 16 | //storing the data at node in list. 17 | A.add(root.data); 18 | 19 | //calling function recursively for left and right subtrees. 20 | serialize(root.left, A); 21 | serialize(root.right, A); 22 | } 23 | 24 | //Function to construct the tree. 25 | public Node kewl(ArrayList A, Passing ps) 26 | { 27 | //base case if there are no more elements in list. 28 | if (ps.index == A.size() || A.get(ps.index) == -1) 29 | { 30 | ps.index += 1; 31 | return null; 32 | } 33 | //creating new node for storing current element. 34 | Node root = new Node(A.get(ps.index)); 35 | ps.index += 1; 36 | 37 | //calling function recursively for left and right subtrees. 38 | root.left = kewl(A, ps); 39 | root.right = kewl(A, ps); 40 | return root; 41 | } 42 | 43 | //Function to deserialize a list and construct the tree. 44 | public Node deSerialize(ArrayList A) 45 | { 46 | Passing ps=new Passing(); 47 | ps.index=0; 48 | //returning the tree. 49 | return kewl(A, ps); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Trees & Graphs/Tree.java: -------------------------------------------------------------------------------- 1 | final class Node { 2 | T data; 3 | Node left=null; 4 | Node right=null; 5 | 6 | public Node(T param){ 7 | this.data = param; 8 | } 9 | 10 | public void preorder() { 11 | System.out.print(this.data+" "); 12 | if(this.left!=null) 13 | this.left.preorder(); 14 | if(this.right!=null) 15 | this.right.preorder(); 16 | } 17 | 18 | public void inorder(){ 19 | if(this.left!=null) 20 | this.left.inorder(); 21 | System.out.print(this.data+" "); 22 | if(this.right!=null) 23 | this.right.inorder(); 24 | } 25 | 26 | public void postorder(){ 27 | if(this.left!=null) 28 | this.left.postorder(); 29 | if(this.right!=null) 30 | this.right.postorder(); 31 | System.out.print(this.data+" "); 32 | } 33 | 34 | public boolean dfs(T content){ 35 | boolean lres = false; 36 | boolean rres = false; 37 | if(this.data == content) 38 | return true; 39 | if(this.left!=null) 40 | lres = this.left.dfs(content); 41 | if(this.right!=null) 42 | rres = this.right.dfs(content); 43 | return lres||rres; 44 | } 45 | } 46 | 47 | class Tree { 48 | public static void main(String[] args) { 49 | Node a = new Node(5); 50 | a.left= new Node(3); 51 | a.right= new Node(7); 52 | a.left.left= new Node(2); 53 | a.left.right= new Node(4); 54 | a.right.left= new Node(6); 55 | a.right.right= new Node(8); 56 | a.preorder(); 57 | System.out.println(); 58 | a.inorder(); 59 | System.out.println(); 60 | a.postorder(); 61 | System.out.println(); 62 | System.out.println(a.dfs(5)); 63 | System.out.println(a.dfs(8)); 64 | System.out.println(a.dfs(1)); 65 | } 66 | } -------------------------------------------------------------------------------- /Trees & Graphs/UndirectedGraph.java: -------------------------------------------------------------------------------- 1 | package com.company; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Scanner; 5 | 6 | // Undirected Graph 7 | public class UndirectedGraph { 8 | private ArrayList> arlist= new ArrayList<>(); 9 | 10 | public UndirectedGraph(int n){ 11 | Scanner sc= new Scanner(System.in); 12 | for(int i=0;i temp= new ArrayList<>(); 14 | for(int j=0;jmax) 45 | max=get_vertice(i,j); 46 | } 47 | } 48 | return max; 49 | } 50 | 51 | public int get_vertice(int x,int y){ 52 | return arlist.get(x).get(y); 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /Trees & Graphs/WORD-LADDER-BFS/abc.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class abc 3 | { 4 | static int wordladder(String start,String target,ArrayList al) 5 | { 6 | HashSet hs=new HashSet<>(al); 7 | if(!hs.contains(target)) return 0; 8 | Queue q=new LinkedList<>(); 9 | q.add(start); 10 | int level=1; 11 | while(!q.isEmpty()) 12 | { 13 | int count=q.size(); 14 | for(int i=0;i al=new ArrayList<>(); 47 | for(int i=0;i>adj) 8 | { 9 | adj.get(s).add(d); 10 | adj.get(d).add(s); 11 | } 12 | public static void main (String[] args) 13 | { 14 | Scanner sc = new Scanner(System.in); 15 | //accept the number of test cases 16 | int tc = sc.nextInt(); 17 | for(int k=0;k> list = new ArrayList<>(); 23 | for(int i=0;i()); 26 | } 27 | for(int i=0;i>adj,int V) 37 | { 38 | for(int i =0;i temp = adj.get(i); 40 | System.out.print(i); 41 | for(int j = 0; j "+temp.get(j)); 43 | } 44 | System.out.println(); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | 2 | --------------------------------------------------------------------------------