├── Strings ├── snagrams.java ├── Substring.java ├── StringIsPalindrome.java ├── compareString.java ├── PrintLargestString.java ├── LowercaseVowelsOccurred.java ├── compressionString.java ├── StringCompression.java ├── convertFirstLetterOfUppercase.java ├── FindShortestPath.java ├── anagrams.java ├── DirectionsShortestPath.java └── StringsConvertLettersToUppercase.java ├── Stacks ├── StackSpanProblem.java ├── StackUsingCollectionsFramework.java ├── PushAtBottomOfStack.java ├── ReverseStringUsingStack.java ├── ReverseStack.java ├── StackUsingArrayList.java ├── NextGreaterElementCode.java ├── ImplementStackUsingDeque.java ├── StockSpanProblem.java ├── StackUsingLinkedList.java ├── ValidParenthesesCode.java └── DuplicateParenthesesCode.java ├── .gitignore ├── Lab_Program_List_sem_v_BCA ├── Eg1_Applet.java ├── Eg2_MyApplet.java ├── myFavouriteSong.txt ├── mydata.txt ├── mydata2.txt ├── FileHandling │ ├── My_BufferWriter.java │ ├── MyFileOutputStream.java │ └── My_FileInputStream.java ├── Q13_print_pattern.java ├── Q1_Swap_two_numbers.java ├── Q5_Fibonacci_series.java ├── Q8_ReverseNumber.java ├── Q27_runtime_polymorphism.java ├── Q12_Factors_of_a_number.java ├── Q10_isPrime.java ├── Q2_Command_line_arguments_multiple_these.java ├── Q4_Factorial_of_a_number.java ├── Q16_Factorial_of_a_number_using_recursion.java ├── Q30_create_custom_exception.java ├── Q14_Pascal_triangle.java ├── Q6_Find_GCD_of_two_numbers.java ├── Q25_illustrate_the_multilevel_inheritance.java ├── Q29_try_and_catch_and_finally_block.java ├── Q23_reverses_String.java ├── Q9_palindromeNumber.java ├── Q31_create_BCA_package.java ├── Q3_largest_among.java ├── Q20_Bubble_sort_algorithm.java ├── Q17_Binary_to_decimal.java ├── Q7_Find_LCM_of_two_numbers.java ├── Q11_ArmstrongNumberBetweenTwoIntervals.java ├── Q18_add_two_matrix.java ├── Q21_BinarySearch_algorithm.java ├── Q24_Sorting_given_List_names.java ├── Q35_connection_bw_JDBC.java ├── Q22_displays_area_of_different_figures_using_the_method_overloading.java ├── Q19_multiply_two_matrix.java ├── Q32_file_copy_it_on_another_file.java ├── Q28_multiple_threads.java ├── Q26_uses_of_super_keyword.java └── Student.java ├── Hashing ├── TreeMap3.java ├── CountDistinctElements.java ├── TreeSet1.java ├── LinkedHashSet1.java ├── HashSet1.java ├── LinkedHashMap2.java ├── IterationOnHashSet.java ├── subarraySumEqualToK.java ├── LargestSubarrayWith_0_sum.java ├── IterationOnHashMaps.java ├── MajorityElement.java ├── Union_IntersectionOfTwoArrays.java ├── HashMapOperations.java ├── Find_ItineraryForTickets.java └── ValidAnagram.java ├── Bits-Mantipulation ├── clearLastIbit.java ├── clearIthBit.java ├── setIthBit.java ├── clearRangeBits.java ├── countSetBits.java ├── getIthBit.java ├── checkNumberTwoPower.java ├── fastExponentiation.java └── updateIthBit.java ├── Basic ├── raj.java ├── areaOfTheSquare.java ├── table.java ├── averageOfThreeNo.java └── costOfThreeItems.java ├── OOps ├── OOPS.java ├── AccessModifiers.java ├── GettersSetters.java ├── InterFaces.java ├── AbstractClass.java ├── Inheritance.java └── CopyConstructors.java ├── Queues ├── QueueUsingJCF.java ├── DequeB.java ├── QueueReversal.java ├── FirstNonRepeatingLetter.java ├── ImplementQueueUsingDeque.java ├── InterleaveTwoHalvesOfQueue.java ├── QueueUsingTwoStacks.java └── QueuesUsingArrays.java ├── Arrays ├── LargestNumber.java ├── ReverseArray.java ├── KadaneS_Algorithm_MaxSubarraySum.java ├── BinarySearch.java ├── FindLargestAndSmallestNumber.java ├── PairsInArray.java ├── Array.java ├── MaxSubarraySum.java ├── LinearSearch.java ├── TrappingRainwaterVVI.java └── PrintSubarrays.java ├── Heaps ├── PriorityQueue_PQ.java ├── Connect_N_Ropes.java ├── NearByCass.java ├── PQ_for_Objects.java ├── HeapSort.java └── SlidingWindowMaximum.java ├── LinkedList ├── LLCollectionsFramework.java └── LinkedList.java ├── ConditionalStatements └── incomeTexCalculator.java ├── Patterns ├── invertedHalfPyramidWithNumbersPattern.java ├── floydTrianglePattern.java ├── RotatedHalfPyramid.java ├── numberPyramidPattern.java ├── solidRhombusPattern.java ├── binaryTrianglePattern.java ├── patternHollowRectangle.java ├── HOLLOW_RECTANGLE_pattern.java ├── hollowRhombusPattern.java ├── palindromicPatternWithNumbers.java ├── butterflyPattern.java └── diamondPattern.java ├── BackTracking ├── GridWays.java ├── FindPermutationsString.java ├── FindSubsetsString.java └── BackTracking.java ├── ArrayLists ├── PrintReverseOfAnArrayList.java ├── FindMaximumInAnArrayList.java ├── SortingAnArrayList.java ├── SwapTwoNumber.java ├── ContainerWithMostWaterVVI.java ├── PairSum_1.java ├── ContainerWithMostWater_Using_Two_Pointer_VVI.java └── PairSum_Target_2_PointerApproach.java ├── 2D-Arrays ├── MaxSubarraySumKadaneAlgorithm.java ├── InsertionSort.java ├── BubbleSort.java ├── SelectionSort.java ├── CountingSort.java ├── BestTimeToBuyAndSellStock.java └── SpiralMatrixPrint.java ├── GreedyAlgorithms ├── MinimumSumAbsoluteDifferencePairs.java ├── MaximumLengthChainOfPairs.java ├── IndianCoins.java ├── ActivitySelection.java └── FractionalKnapsack.java ├── SortingAlgorithms ├── InsertionSort.java ├── BubbleSort.java ├── SelectionSort.java ├── CountingSort.java ├── QuickSort.java ├── InbuiltSort.java └── MergeSort.java ├── LICENSE ├── BinaryTrees ├── KthLevelPrint.java ├── BuildBinaryTree.java ├── LowestCommonAncestor_Approach2.java ├── HeightOfTree.java ├── CountOfNodes.java ├── SumOfNodes.java ├── KthAncestorOfNode.java ├── TransformToSumTree.java ├── InorderTraversal.java ├── PostorderTraversal.java ├── PreorderTraversal.java ├── DiameterOfTree_Approach1.java └── DiameterOfTree_Approach2.java ├── Recursion ├── QuickSort.java ├── SearchInRotatedSortedArray.java └── MergeSort.java ├── BinarySearchTree ├── sortedArrayToBalancedBST.java ├── Build_a_BST.java └── MirrorBST.java ├── Graphs └── CreateGraph_adjacencyList.java └── Tries └── implement_Trie.java /Strings/snagrams.java: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Stacks/StackSpanProblem.java: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | .gitignore 3 | raj.kt 4 | raj.java 5 | *.exe 6 | *.c 7 | *.cpp 8 | *.kt -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Eg1_Applet.java: -------------------------------------------------------------------------------- 1 | import java.awt.*; 2 | public class Eg1_Applet { 3 | public static void main(String[] args) { 4 | Frame f = new Frame(); 5 | f.setSize(600,500); 6 | f.setVisible(true); 7 | Button b = new Button("Submit"); 8 | b.setSize(30,30); 9 | f.add(b); 10 | } 11 | } -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Eg2_MyApplet.java: -------------------------------------------------------------------------------- 1 | import java.applet.Applet; 2 | import java.awt.Graphics; 3 | 4 | public class Eg2_MyApplet extends Applet { 5 | @Override 6 | public void paint(Graphics g) { 7 | g.drawString("My name is Raj Kishor", 100, 100); 8 | Integer 9 | } 10 | } 11 | 12 | /* 13 | 14 | 15 | 16 | 17 | */ -------------------------------------------------------------------------------- /Hashing/TreeMap3.java: -------------------------------------------------------------------------------- 1 | import java.util.TreeMap; 2 | 3 | public class TreeMap3 { 4 | public static void main(String[] args) { 5 | TreeMap tm = new TreeMap<>(); 6 | tm.put("India", 100); 7 | tm.put("China", 80); 8 | tm.put("US", 50); 9 | 10 | System.out.println(tm); // sorted order 11 | } 12 | } 13 | 14 | /* 15 | * Output: 16 | * {China=80, India=100, US=50} 17 | */ -------------------------------------------------------------------------------- /Stacks/StackUsingCollectionsFramework.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | public class StackUsingCollectionsFramework { 4 | 5 | public static void main(String[] args) { 6 | Stack s = new Stack<>(); 7 | s.push(1); 8 | s.push(2); 9 | s.push(3); 10 | 11 | while (!s.isEmpty()) { 12 | System.out.println(s.peek()); 13 | s.pop(); 14 | } 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /Bits-Mantipulation/clearLastIbit.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Clear Last i bits 3 | * n=15 = 00001111 -[i=2]> 00001100 =(12) 4 | */ 5 | 6 | public class clearLastIbit { 7 | 8 | public static void main(String[] args) { 9 | System.out.println(clearLastBit(15,2)); 10 | } 11 | 12 | public static int clearLastBit(int n, int i){ 13 | int bitMask= -1<er || sc>ec) { 5 | return 19898239; 6 | } 7 | if (sr==er && sc==ec) { 8 | return 73274339; 9 | } 10 | countWay(sr+1, sc, er, ec, str+"D"); 11 | countWay(sr, sc+1, er, ec, str+"R"); 12 | return 9757495; 13 | } 14 | 15 | public static void main(String[] args) { 16 | countWay(1, 1, 3, 3, ""); 17 | } 18 | } -------------------------------------------------------------------------------- /Hashing/CountDistinctElements.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * unique number 4 | */ 5 | import java.util.HashSet; 6 | 7 | public class CountDistinctElements { 8 | public static void main(String[] args) { 9 | int num[] = { 4, 3, 2, 5, 6, 7, 3, 4, 2, 1 }; 10 | 11 | HashSet hs = new HashSet<>(); 12 | for (int i = 0; i < num.length; i++) { 13 | hs.add(num[i]); 14 | } 15 | System.out.println(hs.size()); 16 | } 17 | } 18 | 19 | /* 20 | * Output: 21 | * 7 22 | */ 23 | -------------------------------------------------------------------------------- /Bits-Mantipulation/clearRangeBits.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Clear Range of bits 3 | * n= 100111010011, - [i=2,j=7]> 100100000011 = (2307) 4 | */ 5 | 6 | public class clearRangeBits { 7 | 8 | public static int isClearRangeBits(int n, int i, int j){ 9 | int a=-1< ts = new TreeSet<>(); 6 | ts.add("Delhi"); 7 | ts.add("Mumbai"); 8 | ts.add("Noida"); 9 | ts.add("Bengaluru"); 10 | 11 | System.out.println(ts); 12 | ts.remove("Delhi"); 13 | System.out.println(ts); 14 | } 15 | } 16 | 17 | /* 18 | * Output: 19 | * [Bengaluru, Delhi, Mumbai, Noida] 20 | * [Bengaluru, Mumbai, Noida] 21 | */ -------------------------------------------------------------------------------- /Bits-Mantipulation/countSetBits.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Count Set Bit in a Number 3 | * 10 = 1010 -> setBit=2 4 | */ 5 | 6 | public class countSetBits { 7 | public static int countSetBit(int n){ 8 | int Count=0; 9 | while(n>0){ 10 | if((n&1)==1){ 11 | Count++; 12 | } 13 | n=n>>1; 14 | } 15 | return Count; 16 | } 17 | 18 | public static void main(String[] args) { 19 | System.out.println(countSetBit(10)); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /Bits-Mantipulation/getIthBit.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Get ith bit 3 | * n = 00001111 -> i=3 4 | * o/p = 1 ; 5 | */ 6 | 7 | public class getIthBit { 8 | 9 | public static int getBit(int n, int i){ 10 | int bitMaxk = 1< (2^2)true 4 | * 3 = 011 -> false 5 | */ 6 | 7 | 8 | public class checkNumberTwoPower { 9 | public static boolean checkPower(int n){ 10 | return (n &(n-1))==0 ; 11 | } 12 | 13 | public static void main(String[] args) { 14 | System.out.println(checkPower(4)); 15 | System.out.println(checkPower(3)); 16 | 17 | } 18 | } 19 | 20 | 21 | 22 | /* 23 | 24 | Output: 25 | 26 | true 27 | false 28 | 29 | */ -------------------------------------------------------------------------------- /OOps/OOPS.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * Object Oriented Programming 4 | */ 5 | 6 | public class OOPS { 7 | public static void main(String[] args) { 8 | Pen p1 = new Pen(); 9 | p1.setColor("Blur"); 10 | p1.setTip(5); 11 | System.out.println(p1.color); 12 | System.out.println(p1.tip); 13 | } 14 | 15 | } 16 | 17 | class Pen { 18 | String color; 19 | int tip; 20 | 21 | void setColor(String newColor) { 22 | this.color = newColor; 23 | } 24 | 25 | void setTip(int tip) { 26 | this.tip = tip; 27 | } 28 | } -------------------------------------------------------------------------------- /Strings/Substring.java: -------------------------------------------------------------------------------- 1 | public class Substring { 2 | 3 | public static String subString(String str, int st, int ei){ 4 | String subString = ""; 5 | for (int i = st; i < ei; i++) { 6 | subString+=str.charAt(i); 7 | } 8 | return subString; 9 | } 10 | public static void main(String[] args) { 11 | String str = "Hello Rajkishor"; 12 | 13 | System.out.println(subString(str, 3, 9)); 14 | System.out.println(str.substring(3,9)); 15 | } 16 | } 17 | 18 | /* 19 | * Output: 20 | * lo Raj 21 | * lo Raj 22 | */ -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/FileHandling/My_BufferWriter.java: -------------------------------------------------------------------------------- 1 | 2 | import java.io.BufferedWriter; 3 | import java.io.FileWriter; 4 | import java.io.IOException; 5 | 6 | public class My_BufferWriter { 7 | public static void main(String[] args) throws IOException{ 8 | FileWriter fw = new FileWriter("D:/My Database/myBuffrtWriter.txt"); 9 | BufferedWriter bw = new BufferedWriter(fw); 10 | for (int i = 0; i < 50; i++) { 11 | bw.write("this is my first program to write string to directaly file"); 12 | bw.newLine(); 13 | } 14 | bw.close(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/FileHandling/MyFileOutputStream.java: -------------------------------------------------------------------------------- 1 | import java.io.FileOutputStream; 2 | import java.io.IOException; 3 | 4 | public class MyFileOutputStream { 5 | 6 | public static void main(String[] args) { 7 | try (FileOutputStream fout = new FileOutputStream("D:\\My Database\\FileOutputStream.txt")) { 8 | String str = "My name is Rajkishor"; 9 | byte b[] = str.getBytes(); 10 | fout.write(b); 11 | System.out.println("Data is successfully written."); 12 | } catch (IOException e) { 13 | e.printStackTrace(); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Hashing/LinkedHashSet1.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Ordered using DLL 3 | */ 4 | 5 | import java.util.LinkedHashSet; 6 | 7 | public class LinkedHashSet1 { 8 | public static void main(String[] args) { 9 | 10 | LinkedHashSet lhs = new LinkedHashSet<>(); 11 | lhs.add("Delhi"); 12 | lhs.add("Mumbai"); 13 | lhs.add("Noida"); 14 | lhs.add("Bengaluru"); 15 | System.out.println(lhs); 16 | lhs.remove("Delhi"); 17 | System.out.println(lhs); 18 | } 19 | } 20 | 21 | /* 22 | * Output: 23 | * [Delhi, Mumbai, Noida, Bengaluru] 24 | * [Mumbai, Noida, Bengaluru] 25 | */ 26 | -------------------------------------------------------------------------------- /Strings/StringIsPalindrome.java: -------------------------------------------------------------------------------- 1 | /* 2 | * check if a String is a palindrome. 3 | */ 4 | 5 | public class StringIsPalindrome { 6 | public static Boolean isPalindrome(String str){ 7 | int n = str.length(); 8 | for (int i = 0; i < n/2; i++) { 9 | if (str.charAt(i)!=str.charAt(n-1-i)) { 10 | return false; 11 | } 12 | } 13 | return true; 14 | } 15 | public static void main(String[] args) { 16 | String str = "racecar"; 17 | System.out.println(isPalindrome(str)); 18 | } 19 | } 20 | 21 | /* 22 | * Output: 23 | * true 24 | */ -------------------------------------------------------------------------------- /Strings/compareString.java: -------------------------------------------------------------------------------- 1 | /* 2 | * For a given set of Strings, print the largest string. 3 | * "apple" , "mango" , "banana" 4 | */ 5 | 6 | public class compareString { 7 | public static void main(String[] args) { 8 | 9 | String fruit[]={ "apple" , "mango" , "banana" }; 10 | String largest= fruit[0]; 11 | for(int i=1; i0){ // n= [00000101] = 5 10 | if((n & 1)==1){ 11 | ans=ans*a; // ans = 5 12 | } 13 | a=a*a; // a=25 14 | n=n>>1; // n= [00000010] 15 | }return ans; // ans=3125 16 | } 17 | 18 | public static void main(String[] args) { 19 | System.out.println(power(5,5)); 20 | } 21 | } -------------------------------------------------------------------------------- /Hashing/HashSet1.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | 3 | public class HashSet1 { 4 | public static void main(String[] args) { 5 | HashSet hs = new HashSet<>(); 6 | hs.add(1); 7 | hs.add(2); 8 | hs.add(3); 9 | hs.add(2); 10 | hs.add(3); 11 | System.out.println(hs); 12 | hs.remove(3); 13 | System.out.println(hs); 14 | System.out.println(hs.contains(3)); 15 | System.out.println(hs.size()); 16 | System.out.println(hs.isEmpty()); 17 | } 18 | } 19 | 20 | /* 21 | * Output: 22 | * [1, 2, 3] 23 | * [1, 2] 24 | * false 25 | * 2 26 | * false 27 | */ 28 | -------------------------------------------------------------------------------- /Queues/QueueUsingJCF.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Create queue using JCF 3 | */ 4 | 5 | import java.util.ArrayDeque; 6 | import java.util.LinkedList; 7 | import java.util.Queue; 8 | 9 | public class QueueUsingJCF { 10 | public static void main(String[] args) { 11 | // Queue q = new LinkedList<>(); 12 | Queue q = new ArrayDeque<>(); 13 | q.add(1); 14 | q.add(2); 15 | q.add(3); 16 | q.add(4); 17 | q.add(5); 18 | while (!q.isEmpty()) { 19 | System.out.println(q.remove()); 20 | } 21 | } 22 | } 23 | 24 | /* 25 | * Output: 26 | * 1 27 | * 2 28 | * 3 29 | * 4 30 | * 5 31 | */ -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q13_print_pattern.java: -------------------------------------------------------------------------------- 1 | /* 2 | @Program: 13 3 | Write a java program to print the following pattern: 4 | 5 | 1 6 | 22 7 | 333 8 | 4444 9 | 55555 10 | 11 | */ 12 | 13 | public class Q13_print_pattern { 14 | public static void main(String[] args) { 15 | int n=5; 16 | for (int i = 1; i <= n; i++) { 17 | for (int j = 1; j <= i; j++) { 18 | System.out.print(i); 19 | } 20 | System.out.println(); 21 | } 22 | } 23 | } 24 | 25 | /* 26 | Output: 27 | 1 28 | 22 29 | 333 30 | 4444 31 | 55555 32 | */ 33 | -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q1_Swap_two_numbers.java: -------------------------------------------------------------------------------- 1 | /* @Program: 1 2 | * Write a java program to swap two numbers. 3 | */ 4 | 5 | public class Q1_Swap_two_numbers { 6 | public static void main(String[] args) { 7 | int a=10; 8 | int b=20; 9 | int c; 10 | System.out.println("Before swap the value\n\ta="+a+"\n\tb="+b); 11 | c=a; 12 | a=b; 13 | b=c; 14 | System.out.println("After swap the value\n\ta="+a+"\n\tb="+b); 15 | } 16 | } 17 | 18 | /* 19 | Output: 20 | Before swap the value 21 | a=10 22 | b=20 23 | After swap the value 24 | a=20 25 | b=10 26 | */ -------------------------------------------------------------------------------- /Strings/PrintLargestString.java: -------------------------------------------------------------------------------- 1 | /* 2 | * For a given set of Strings, Print the largest String. 3 | * array => "apple", "mango", "banana". 4 | */ 5 | 6 | public class PrintLargestString { 7 | public static void main(String[] args) { 8 | String strs[] = {"apple", "mango", "banana"}; 9 | String largeString = strs[0]; 10 | for (int i = 1; i < strs.length; i++) { 11 | if (largeString.compareTo(strs[i]) < 0) { 12 | largeString = strs[i]; 13 | } 14 | } 15 | System.out.println("Largest String : "+ largeString); 16 | } 17 | } 18 | 19 | /* 20 | * Output: 21 | * Largest String : mango 22 | */ -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q5_Fibonacci_series.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @Program: 5 3 | * Write a java program to print Fibonacci series up to given term. 4 | */ 5 | 6 | public class Q5_Fibonacci_series { 7 | public static void main(String[] args) { 8 | int n=15; 9 | int a=0; 10 | int b=1; 11 | int sum =0; 12 | 13 | System.out.println("Fibonacci Series...!"); 14 | for (int i = 0; i < n; i++) { 15 | System.out.print(sum+" "); 16 | sum = a+b; 17 | b=a; 18 | a=sum; 19 | } 20 | } 21 | } 22 | 23 | /* 24 | Output: 25 | Fibonacci Series...! 26 | 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 27 | */ -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q8_ReverseNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @Program: 8 3 | * Write a java program to reverse the number. 4 | */ 5 | 6 | public class Q8_ReverseNumber { 7 | public static int reverseNum(int num){ 8 | int rev=0; 9 | while(num!=0){ 10 | int r = num % 10; 11 | rev= rev*10 + r; 12 | num = num/10; 13 | } 14 | return rev; 15 | } 16 | public static void main(String[] args) { 17 | int num =12345; 18 | int reverse = reverseNum(num); 19 | System.out.println("Reverse number is: "+reverse); 20 | } 21 | } 22 | 23 | /* 24 | * Output: 25 | * Reverse number is: 54321 26 | */ -------------------------------------------------------------------------------- /Arrays/LargestNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Find the largest number in a given array. 3 | * array[] = {1, 2, 6, 3, 5, 4} 4 | */ 5 | 6 | public class LargestNumber { 7 | public static int largestNumber(int arr[]){ 8 | int largest = Integer.MIN_VALUE; 9 | for (int i = 0; i < arr.length; i++) { 10 | if(largest lhm = new LinkedHashMap<>(); 7 | lhm.put("india", 100); 8 | lhm.put("china", 200); 9 | lhm.put("US", 80); 10 | 11 | HashMap hm = new HashMap<>(); 12 | hm.put("india", 100); 13 | hm.put("china", 200); 14 | hm.put("US", 80); 15 | 16 | System.out.println(lhm); 17 | System.out.println(hm); 18 | } 19 | } 20 | 21 | /* 22 | * Output: 23 | * {india=100, china=200, US=80} 24 | * {china=200, india=100, US=80} 25 | */ 26 | -------------------------------------------------------------------------------- /Heaps/PriorityQueue_PQ.java: -------------------------------------------------------------------------------- 1 | import java.util.Comparator; 2 | import java.util.PriorityQueue; 3 | 4 | public class PriorityQueue_PQ { 5 | public static void main(String[] args) { 6 | // PriorityQueue pq = new PriorityQueue<>(); // 1 3 4 5 9 7 | 8 | PriorityQueue pq = new PriorityQueue<>(Comparator.reverseOrder()); 9 | 10 | pq.add(1); // 0(log n) 11 | pq.add(5); 12 | pq.add(3); 13 | pq.add(9); 14 | pq.add(4); 15 | 16 | while (!pq.isEmpty()) { 17 | System.out.print(pq.peek() + " "); // 0(1) //9 5 4 3 1s 18 | pq.remove(); // 0(log n) 19 | } 20 | } 21 | } 22 | 23 | /* 24 | * Output: 25 | * 9 5 4 3 1 26 | */ -------------------------------------------------------------------------------- /Hashing/IterationOnHashSet.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class IterationOnHashSet { 4 | public static void main(String[] args) { 5 | HashSet hs = new HashSet<>(); 6 | hs.add(9); 7 | hs.add(2); 8 | hs.add(2); 9 | hs.add(3); 10 | hs.add(4); 11 | Iterator it = hs.iterator(); 12 | while (it.hasNext()) { 13 | System.out.print(it.next() + " "); 14 | } 15 | System.out.println(); 16 | for (Integer i : hs) { 17 | System.out.print(i + " "); 18 | } 19 | System.out.println("\n" + hs); 20 | 21 | } 22 | } 23 | 24 | /* 25 | * Output: 26 | * 2 3 4 9 27 | * 2 3 4 9 28 | * [2, 3, 4, 9] 29 | */ -------------------------------------------------------------------------------- /Strings/LowercaseVowelsOccurred.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Count how many times lowercase vowels occurred in a String entered by the user. 3 | */ 4 | 5 | public class LowercaseVowelsOccurred { 6 | 7 | public static int countVowels(String str){ 8 | int count=0; 9 | for (int i = 0; i < str.length(); i++) { 10 | char ch = str.charAt(i); 11 | if (ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u') { 12 | count++; 13 | } 14 | } 15 | return count; 16 | } 17 | public static void main(String[] args) { 18 | String str = "rajkishor"; 19 | System.out.println(countVowels(str)); 20 | } 21 | } 22 | 23 | /* 24 | * Output: 25 | * 3 26 | */ -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q27_runtime_polymorphism.java: -------------------------------------------------------------------------------- 1 | /* 2 | @Program: 27 3 | Write a java program to demonstrate the runtime polymorphism. 4 | */ 5 | 6 | public class Q27_runtime_polymorphism { 7 | public static void main(String[] args) { 8 | Child son = new Child(); 9 | son.property(); 10 | Father father = new Father(); 11 | father.property(); 12 | } 13 | } 14 | class Father{ 15 | public void property(){ 16 | System.out.println("Window"); 17 | } 18 | } 19 | class Child extends Father{ 20 | public void property(){ 21 | System.out.println("Table"); 22 | } 23 | } 24 | 25 | /* 26 | 27 | Output: 28 | Table 29 | Window 30 | 31 | */ -------------------------------------------------------------------------------- /Arrays/ReverseArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Reverse an Array 3 | */ 4 | 5 | public class ReverseArray { 6 | 7 | public static void reverse(int array[]) { 8 | int start=0 , end=array.length-1; 9 | for(int i=0; i ll = new LinkedList<>(); 13 | 14 | //add 15 | ll.addLast(1); 16 | ll.addLast(2); 17 | ll.addLast(3); 18 | ll.addLast(4); 19 | ll.addFirst(10); 20 | // 10->1->2->3->4 21 | System.out.println(ll); // [10, 1, 2, 3, 4] 22 | 23 | // remove 24 | ll.removeLast(); 25 | ll.removeFirst(); 26 | System.out.println(ll); // [1, 2, 3] 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /ConditionalStatements/incomeTexCalculator.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class incomeTexCalculator { 4 | public static void main(String[] args) { 5 | Scanner sc = new Scanner(System.in); 6 | 7 | System.out.print("Enter your income: "); 8 | int income = sc.nextInt(); 9 | int tax; 10 | if (income < 500000) { 11 | tax = 0; 12 | } else if (income >= 500000 && income < 1000000) { 13 | tax = (int) (income * 0.2); // 20% 14 | } else { 15 | tax = (int) (income * 0.3); // 30% 16 | } 17 | 18 | System.out.println("your tax is : " + tax); 19 | } 20 | } 21 | /* 22 | * Output: 23 | * Enter your income: 3500000 24 | * your tax is : 1050000 25 | */ -------------------------------------------------------------------------------- /Patterns/invertedHalfPyramidWithNumbersPattern.java: -------------------------------------------------------------------------------- 1 | /* 2 | * INVARTED HALF-PYRAMID with Number pattern 3 | * 4 | * 1 2 3 4 5 5 | * 1 2 3 4 6 | * 1 2 3 7 | * 1 2 8 | * 1 9 | */ 10 | 11 | public class invertedHalfPyramidWithNumbersPattern { 12 | public static void main(String[] args) { 13 | 14 | short rc = 5; 15 | 16 | for (short i = 1; i <= rc; i++) { 17 | for (short j = 1; j <= rc - i + 1; j++) { 18 | System.out.print(j + " "); 19 | } 20 | System.out.println(); 21 | } 22 | } 23 | } 24 | 25 | /* 26 | Output: 27 | 28 | 1 2 3 4 5 29 | 1 2 3 4 30 | 1 2 3 31 | 1 2 32 | 1 33 | 34 | */ -------------------------------------------------------------------------------- /Hashing/subarraySumEqualToK.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class subarraySumEqualToK { 4 | public static void main(String[] args) { 5 | int arr[] = { 10, 2, -2, -20, 10 }; 6 | int k = -10; 7 | 8 | HashMap map = new HashMap<>(); 9 | // (sum,count) 10 | map.put(0, 1); 11 | 12 | int sum = 0; 13 | int ans = 0; 14 | 15 | for (int j = 0; j < arr.length; j++) { // O(n) 16 | sum += arr[j]; // sum(j) 17 | if (map.containsKey(sum - k)) { 18 | ans += map.get(sum - k); 19 | } 20 | map.put(sum, map.getOrDefault(sum, 0) + 1); 21 | } 22 | System.out.println(ans); 23 | } 24 | } 25 | /* 26 | * Output: 27 | * 3 28 | */ -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q12_Factors_of_a_number.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @Program: 12 3 | * Write a java program to display factors of a number. 4 | */ 5 | 6 | 7 | public class Q12_Factors_of_a_number { 8 | 9 | public static void printFactors(int num){ 10 | int i=num; 11 | while (i>0) { 12 | if (num%i == 0) { 13 | System.out.print(i+" "); 14 | } 15 | i--; 16 | } 17 | } 18 | 19 | public static void main(String[] args) { 20 | int num = 100; 21 | System.out.println("factors of a number.!"); 22 | printFactors(num); 23 | } 24 | 25 | } 26 | 27 | /* 28 | * Output: 29 | * factors of a number.! 30 | * 100 50 25 20 10 5 4 2 1 31 | */ -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q10_isPrime.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @Program: 10 3 | * Write a java program to check whether a number is prime or not. 4 | */ 5 | 6 | 7 | public class Q10_isPrime { 8 | public static Boolean isPrime(int num){ 9 | for (int i = 2; i < num/2; i++) { 10 | if (num % i==0) { 11 | return false; 12 | } 13 | } 14 | return true; 15 | } 16 | 17 | public static void main(String[] args) { 18 | int num = 23; 19 | if (isPrime(num)) { 20 | System.out.println("Number is prime.!"); 21 | }else{ 22 | System.out.println("Number is not prime.!"); 23 | } 24 | } 25 | } 26 | 27 | /* 28 | * Output: 29 | * Number is prime.! 30 | */ -------------------------------------------------------------------------------- /Hashing/LargestSubarrayWith_0_sum.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class LargestSubarrayWith_0_sum { 4 | public static void main(String[] args) { 5 | int arr[] = { 15, -2, 2, -8, 1, 7, 10, 23 }; 6 | HashMap map = new HashMap<>(); 7 | // (sum, idx) 8 | 9 | int sum = 0; 10 | int len = 0; 11 | 12 | for (int i = 0; i < arr.length; i++) { 13 | sum += arr[i]; 14 | if (map.containsKey(sum)) { 15 | len = Math.max(len, i - map.get(sum)); 16 | } else { 17 | map.put(sum, i); 18 | } 19 | } 20 | System.out.println("largest subarray with sum as 0 => " + len); 21 | } 22 | } 23 | 24 | /* 25 | * Output: 26 | * largest subarray with sum as 0 => 5 27 | */ -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q2_Command_line_arguments_multiple_these.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @Program: 2 3 | * Write a java program that accepts two doubles as its command line arguments, 4 | * multiple these together and display the product. 5 | */ 6 | public class Q2_Command_line_arguments_multiple_these { 7 | public static void main(String[] args) { 8 | Double a = Double.parseDouble(args[0]); 9 | Double b = Double.parseDouble(args[1]); 10 | Double product = a*b; 11 | System.out.println("Product: "+product); 12 | } 13 | } 14 | 15 | /* 16 | * Output: 17 | * D:\Lab_Program>javac public class Q2_Command_line_arguments_multiple_these.java 18 | * D:\Lab_Program>javac public class Q2_Command_line_arguments_multiple_these 50 5 19 | * Product: 250.0 20 | */ -------------------------------------------------------------------------------- /Queues/DequeB.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Deque [ Double ended queue ] 3 | */ 4 | 5 | import java.util.*; 6 | 7 | public class DequeB { 8 | public static void main(String[] args) { 9 | Deque deque = new LinkedList<>(); 10 | deque.addFirst(1); 11 | deque.addFirst(2); 12 | deque.addFirst(3); 13 | deque.addLast(5); 14 | System.out.println(deque); // [3, 2, 1, 5] 15 | deque.removeFirst(); 16 | deque.removeLast(); 17 | System.out.println(deque); // [2, 1] 18 | System.out.println("get first : " + deque.getFirst()); // get first : 2 19 | System.out.println("get last : " + deque.getLast()); // get last : 1 20 | } 21 | } 22 | 23 | /* 24 | * Output: 25 | * [3, 2, 1, 5] 26 | * [2, 1] 27 | * get first : 2 28 | * get last : 1 29 | * 30 | */ -------------------------------------------------------------------------------- /BackTracking/GridWays.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Grid ways 3 | * Find number of ways to reach from (0,0) to (N-1,M-1) in NxM Grid. 4 | * Allowed moves - right or down. 5 | */ 6 | 7 | public class GridWays { 8 | 9 | public static int gridWays( int i, int j , int n, int m) { 10 | //base case 11 | if(i==n-1 && j==m-1){ //condition for last cell 12 | return 1; 13 | }else if(i==n || j==n){ // bound 14 | return 0; 15 | } 16 | int w1 = gridWays(i+1, j, n, m); 17 | int w2 = gridWays(i, j+1, n, m); 18 | return w1+w2; 19 | } 20 | 21 | public static void main(String[] args) { 22 | int n=3, m=3; 23 | System.out.println(gridWays(0, 0, n, m)); 24 | 25 | } 26 | 27 | } 28 | 29 | /* 30 | * Output: 31 | * 6 32 | */ -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q4_Factorial_of_a_number.java: -------------------------------------------------------------------------------- 1 | /* @Program: 4 2 | * Write a java program to find factorial of a number. 3 | */ 4 | import java.util.Scanner; 5 | 6 | public class Q4_Factorial_of_a_number { 7 | 8 | public static int factorial(int num){ 9 | int fact=num; 10 | while(num>1){ 11 | num=num-1; 12 | fact*=num; 13 | } 14 | return fact; 15 | } 16 | public static void main(String[] args) { 17 | Scanner sc = new Scanner(System.in); 18 | System.out.print("Enter the number: "); 19 | int num = sc.nextInt(); 20 | int fact = factorial(num); 21 | System.out.println("Factorial: "+fact); 22 | } 23 | } 24 | 25 | /* 26 | Output: 27 | Enter the number: 6 28 | Factorial: 720 29 | */ -------------------------------------------------------------------------------- /Patterns/floydTrianglePattern.java: -------------------------------------------------------------------------------- 1 | /* 2 | * FLOYD'S Triangle pattern 3 | * 1 4 | * 2 3 5 | * 4 5 6 6 | * 7 8 9 10 7 | * 11 12 13 14 15 8 | */ 9 | 10 | public class floydTrianglePattern { 11 | public static void main(String[] args) { 12 | short rc = 5; 13 | short num = 1; 14 | for (short i = 1; i <= rc; i++) { 15 | for (short j = 1; j <= i; j++) { 16 | System.out.print(num + " "); 17 | num++; 18 | } 19 | System.out.println(); 20 | } 21 | } 22 | } 23 | 24 | /* 25 | 26 | Output: 27 | 28 | 1 29 | 2 3 30 | 4 5 6 31 | 7 8 9 10 32 | 11 12 13 14 15 33 | 34 | */ -------------------------------------------------------------------------------- /Basic/table.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Write a program to print the multiplication table of a number N,entered by the user. 3 | */ 4 | 5 | import java.util.Scanner; 6 | 7 | public class table { 8 | public static void main(String[] args) { 9 | try (Scanner sc = new Scanner(System.in)) { 10 | System.out.print("Enter the table numbere: "); 11 | int table = sc.nextInt(); 12 | for (int i = 1; i <= 10; i++){ 13 | System.out.println(table + "*" + i + " = " + (table * i)); 14 | } 15 | } 16 | } 17 | } 18 | 19 | /* 20 | * Output: 21 | * Enter the table numbere: 5 22 | * 5*1 = 5 23 | * 5*2 = 10 24 | * 5*3 = 15 25 | * 5*4 = 20 26 | * 5*5 = 25 27 | * 5*6 = 30 28 | * 5*7 = 35 29 | * 5*8 = 40 30 | * 5*9 = 45 31 | * 5*10 = 50 32 | */ -------------------------------------------------------------------------------- /ArrayLists/PrintReverseOfAnArrayList.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Print Reverse of an ArrayList 3 | * list = 1,2,3,4,5 4 | */ 5 | 6 | import java.util.ArrayList; 7 | 8 | public class PrintReverseOfAnArrayList { 9 | 10 | public static void main(String[] args) { 11 | 12 | ArrayList list = new ArrayList<>(); 13 | 14 | list.add(1); 15 | list.add(2); 16 | list.add(3); 17 | list.add(4); 18 | list.add(5); 19 | System.out.println(list); // [1, 2, 3, 4, 5] 20 | System.out.println("Reverse arrayList"); 21 | for(int i=list.size()-1; i>=0; i--){ 22 | System.out.print(list.get(i)+ " "); // 5 4 3 2 1 23 | } 24 | } 25 | } 26 | 27 | /* 28 | * Output: 29 | * [1, 2, 3, 4, 5] 30 | * Reverse arrayList 31 | * 5 4 3 2 1 32 | */ 33 | -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q16_Factorial_of_a_number_using_recursion.java: -------------------------------------------------------------------------------- 1 | /* @Program: 16 2 | * Write a java program to find factorial of a number using recursion. 3 | */ 4 | import java.util.Scanner; 5 | 6 | public class Q16_Factorial_of_a_number_using_recursion { 7 | 8 | public static int factorial(int num){ 9 | if(num<=1){ 10 | return 1; 11 | } 12 | return num * factorial(num-1); 13 | } 14 | public static void main(String[] args) { 15 | Scanner sc = new Scanner(System.in); 16 | System.out.print("Enter the number: "); 17 | int num = sc.nextInt(); 18 | int fact = factorial(num); 19 | System.out.println("Factorial: "+fact); 20 | } 21 | } 22 | 23 | /* 24 | Output: 25 | Enter the number: 6 26 | Factorial: 720 27 | */ -------------------------------------------------------------------------------- /Patterns/RotatedHalfPyramid.java: -------------------------------------------------------------------------------- 1 | /* 2 | INVERTED & ROTATED HALF-PYRAMID pattern 3 | * 4 | ** 5 | *** 6 | **** 7 | */ 8 | 9 | 10 | public class RotatedHalfPyramid { 11 | 12 | public static void pattern(int num){ 13 | for(int i=0; i list = new ArrayList<>(); 12 | list.add(2); 13 | list.add(5); 14 | list.add(9); 15 | list.add(3); 16 | list.add(6); 17 | int max = Integer.MIN_VALUE; 18 | for(int i=0; i {1,-2,6,-1,3} 5 | * 6 | * using kadane`s Algorithm 7 | */ 8 | 9 | 10 | public class MaxSubarraySumKadaneAlgorithm { 11 | 12 | public static void maxSubarraySum(int array[]) { 13 | int currentSum=0 , max=Integer.MIN_VALUE; 14 | for(int i=0; i s, int data) { 11 | if (s.isEmpty()) { 12 | s.push(data); 13 | return; 14 | } 15 | int pop = s.pop(); 16 | pushBottom(s, data); 17 | s.push(pop); 18 | } 19 | 20 | public static void main(String[] args) { 21 | Stack s = new Stack<>(); 22 | s.push(1); 23 | s.push(2); 24 | s.push(3); 25 | pushBottom(s, 4); 26 | 27 | while (!s.isEmpty()) { 28 | System.out.println(s.peek()); 29 | s.pop(); 30 | } 31 | } 32 | } 33 | 34 | /* 35 | * Output: 36 | * 3 37 | * 2 38 | * 1 39 | * 4 40 | * 41 | */ -------------------------------------------------------------------------------- /Hashing/IterationOnHashMaps.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Set; 3 | 4 | public class IterationOnHashMaps { 5 | public static void main(String[] args) { 6 | HashMap hm = new HashMap<>(); 7 | hm.put("India", 100); 8 | hm.put("China", 150); 9 | hm.put("US", 200); 10 | hm.put("Indonesia", 180); 11 | hm.put("Nepal", 50); 12 | 13 | // Iterate 14 | Set keys = hm.keySet(); 15 | System.out.println(keys); 16 | 17 | for (String k : keys) { 18 | System.out.println("key=" + k + ",value=" + hm.get(k)); 19 | } 20 | } 21 | } 22 | 23 | /* 24 | * Output: 25 | * [China, US, Nepal, India, Indonesia] 26 | * key=China,value=150 27 | * key=US,value=200 28 | * key=Nepal,value=50 29 | * key=India,value=100 30 | * key=Indonesia,value=180 31 | */ -------------------------------------------------------------------------------- /Stacks/ReverseStringUsingStack.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Reverse a String using a stack 3 | */ 4 | 5 | import java.util.*; 6 | 7 | public class ReverseStringUsingStack { 8 | 9 | public static String reverseString(String str) { 10 | Stack s = new Stack<>(); 11 | int idx = 0; 12 | while (idx < str.length()) { 13 | s.push(str.charAt(idx)); 14 | idx++; 15 | } 16 | 17 | StringBuilder result = new StringBuilder(""); 18 | while (!s.isEmpty()) { 19 | char curr = s.pop(); 20 | result.append(curr); 21 | } 22 | return result.toString(); 23 | } 24 | 25 | public static void main(String[] args) { 26 | String str = "RajKishor"; 27 | System.out.println(reverseString(str)); 28 | 29 | } 30 | } 31 | 32 | /* 33 | * Output: 34 | * rohsiKjaR 35 | */ -------------------------------------------------------------------------------- /Arrays/KadaneS_Algorithm_MaxSubarraySum.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Max Subarray Sum(Kadane's Algorithm) 3 | * array[]={-2, -3, 4 , -1, 5, -3} 4 | */ 5 | 6 | public class KadaneS_Algorithm_MaxSubarraySum { 7 | public static int kadaneAlgorithm(int array[]){ 8 | int currSum=0; 9 | int maxSum = Integer.MIN_VALUE; 10 | for (int i = 0; i < array.length; i++) { 11 | currSum+=array[i]; 12 | if (currSum<0) { 13 | currSum=0; 14 | } 15 | maxSum = Math.max(maxSum, currSum); 16 | } 17 | return maxSum; 18 | } 19 | public static void main(String[] args) { 20 | int array[] ={-2, -3, 4, -1, -2, 1, 5, -3}; 21 | System.out.println("Max Subarray Sum: "+ kadaneAlgorithm(array)); 22 | } 23 | } 24 | 25 | /* 26 | * Output: 27 | * Max Subarray Sum: 7 28 | */ -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q30_create_custom_exception.java: -------------------------------------------------------------------------------- 1 | /* 2 | @Program: 30 3 | Write a java program to create custom exception. 4 | 5 | */ 6 | 7 | public class Q30_create_custom_exception { 8 | public static void main(String[] args) { 9 | int age = 15; 10 | try { 11 | if (age < 18) { 12 | throw new CustomException("Age is less than 18, not eligible for voting"); 13 | } 14 | } catch (CustomException e) { 15 | System.out.println("Custom Exception caught: " + e.getMessage()); 16 | } 17 | } 18 | } 19 | 20 | class CustomException extends Exception { 21 | public CustomException(String message) { 22 | super(message); 23 | } 24 | } 25 | 26 | /* 27 | * output: 28 | * Custom Exception caught: Age is less than 18, not eligible for voting 29 | */ -------------------------------------------------------------------------------- /Patterns/numberPyramidPattern.java: -------------------------------------------------------------------------------- 1 | /* 2 | * NUMBER PYRAMID pattern 3 | * 1 4 | * 2 2 5 | * 3 3 3 6 | * 4 4 4 4 7 | * 5 5 5 5 5 8 | */ 9 | 10 | public class numberPyramidPattern { 11 | public static void main(String[] args) { 12 | short n = 5; 13 | for (short i = 1; i <= n; i++) { 14 | for (short j = 1; j <= n - i; j++) { 15 | System.out.print(" "); 16 | } 17 | for (short j = 1; j <= i; j++) { 18 | System.out.print(i + " "); 19 | } 20 | System.out.println(); 21 | } 22 | } 23 | } 24 | 25 | /* 26 | Output: 27 | 28 | 1 29 | 2 2 30 | 3 3 3 31 | 4 4 4 4 32 | 5 5 5 5 5 33 | 34 | */ -------------------------------------------------------------------------------- /Patterns/solidRhombusPattern.java: -------------------------------------------------------------------------------- 1 | /* 2 | * SOLID RHOMBUS pattern 3 | * 4 | * ***** 5 | * ***** 6 | * ***** 7 | * ***** 8 | * ***** 9 | */ 10 | 11 | 12 | public class solidRhombusPattern { 13 | public static void main(String[] args) { 14 | short n = 5; 15 | for (short i = 1; i <= n; i++) { 16 | for (short j = 1; j <= n-i; j++){ 17 | System.out.print(" "); 18 | } 19 | for (short j = 1; j <= n; j++) { 20 | System.out.print("*"); 21 | } 22 | System.out.println(); 23 | } 24 | } 25 | } 26 | 27 | 28 | /* 29 | Output: 30 | 31 | ***** 32 | ***** 33 | ***** 34 | ***** 35 | ***** 36 | 37 | */ -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q14_Pascal_triangle.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @Program: 14 3 | * Write a java program to print Pascal triangle. 4 | */ 5 | 6 | public class Q14_Pascal_triangle { 7 | public static void main(String[] args) { 8 | int n=5; 9 | int c=0; 10 | for (int i=0; i pick an element (from unsorted part) & place in the right par in sorted part 4 | */ 5 | 6 | public class InsertionSort { 7 | 8 | public static void sortArray(int array[]) { 9 | for(int i=1; i=0 && array[prev]>curr){ 13 | array[prev+1]=array[prev]; 14 | prev--; 15 | } 16 | // insertion 17 | array[prev+1]=curr; 18 | } 19 | 20 | } 21 | public static void main(String[] args) { 22 | int array[]={5,4,1,3,2}; 23 | sortArray(array); 24 | for(int i=0; i "a3b2c3d2" 6 | * "aaaaabbbcccccc" - > "a5b3c6" 7 | */ 8 | 9 | public class compressionString { 10 | public static String compress(String str){ 11 | StringBuilder sb=new StringBuilder(""); 12 | for(int i=0; i1) { 20 | sb.append(count); 21 | } 22 | } 23 | return sb.toString(); 24 | } 25 | 26 | public static void main(String[] args) { 27 | System.out.println(compress("aaabbcccdd")); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /GreedyAlgorithms/MinimumSumAbsoluteDifferencePairs.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @Min Absolute Difference Pairs 3 | * Given two arrays A and B of equal length n. pair each element of array A to an element in array B, 4 | * such that sum S of absolute differences of all the pairs is minimum. 5 | * A= [1, 2, 3] 6 | * B= [2, 1, 3] 7 | * 8 | * ans = 0 9 | */ 10 | 11 | import java.util.*; 12 | 13 | public class MinimumSumAbsoluteDifferencePairs { 14 | public static void main(String[] args) { 15 | int a[] = { 1, 4, 7, 8 }; 16 | int b[] = { 2, 3, 6, 5 }; 17 | Arrays.sort(a); 18 | Arrays.sort(b); 19 | int minDiff = 0; 20 | for (int i = 0; i < a.length; i++) { 21 | minDiff += Math.abs(a[i] - b[i]); 22 | } 23 | System.out.println("Min absolute diff of pairs= " + minDiff); 24 | } 25 | } 26 | 27 | /* 28 | * Output: 29 | * Min absolute diff of pairs= 6 30 | */ -------------------------------------------------------------------------------- /OOps/AccessModifiers.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Access Modifiers/specifier 3 | */ 4 | 5 | public class AccessModifiers { 6 | public static void main(String[] args) { 7 | 8 | BankAccount myAcc = new BankAccount(); 9 | myAcc.username = "rajkishorbgp"; 10 | myAcc.setPassword("raj@1234"); 11 | ; 12 | 13 | System.out.println(myAcc.username); // rajkishorbgp 14 | System.out.println(myAcc.getPassword()); // raj@1234 15 | } 16 | } 17 | 18 | /** 19 | * BankAccount 20 | */ 21 | class BankAccount { 22 | 23 | public String username; // Public username 24 | private String password; // private password 25 | 26 | public void setPassword(String password) { 27 | this.password = password; 28 | } 29 | 30 | public String getPassword() { 31 | return password; 32 | } 33 | 34 | } 35 | 36 | /* 37 | * Output: 38 | * rajkishorbgp 39 | * raj@1234 40 | */ -------------------------------------------------------------------------------- /SortingAlgorithms/InsertionSort.java: -------------------------------------------------------------------------------- 1 | public class InsertionSort { 2 | 3 | public static void insertionSort(int arr[]) { 4 | for (int i = 1; i < arr.length; i++) { 5 | int curr = arr[i]; 6 | int prev = i - 1; 7 | while (prev >= 0 && arr[prev] > curr) { 8 | arr[prev + 1] = arr[prev]; 9 | prev--; 10 | } 11 | arr[prev + 1] = curr; 12 | } 13 | } 14 | 15 | public static void printArray(int arr[]) { 16 | for (int i = 0; i < arr.length; i++) { 17 | System.out.print(arr[i] + " "); 18 | } 19 | System.out.println(); 20 | } 21 | 22 | public static void main(String[] args) { 23 | int array[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1 }; 24 | insertionSort(array); 25 | 26 | printArray(array); 27 | 28 | } 29 | } 30 | 31 | /* 32 | * Output: 33 | * 1 2 3 4 5 6 7 8 9 34 | */ -------------------------------------------------------------------------------- /BackTracking/FindPermutationsString.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Find permutations 3 | * 4 | * Find & print all parmutations of a string. 5 | */ 6 | 7 | public class FindPermutationsString { 8 | 9 | public static void findPermutation(String str , String ans){ 10 | if(str.length()==0){ 11 | System.out.println(ans); 12 | return; 13 | } 14 | 15 | for(int i=0; i a+b =ab 19 | String newStr =str.substring(0,i)+str.substring(i+1); 20 | findPermutation(newStr,ans+curr); 21 | } 22 | } 23 | public static void main(String[] args) { 24 | String str="abc"; 25 | findPermutation(str,""); 26 | } 27 | } 28 | 29 | /* 30 | * Output: 31 | * abc 32 | * acb 33 | * bac 34 | * bca 35 | * cab 36 | * cba 37 | */ -------------------------------------------------------------------------------- /BackTracking/FindSubsetsString.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Find Subsets 3 | * Find & print all subsets of a given string "abc" 4 | */ 5 | 6 | public class FindSubsetsString { 7 | 8 | public static void printSubset(String str,String ans, int i){ 9 | // Base case 10 | if(i==str.length()){ 11 | if(ans.length()==0){ 12 | System.out.println("null"); 13 | } 14 | else{ 15 | System.out.println(ans); 16 | } 17 | return; 18 | } 19 | printSubset(str,ans+str.charAt(i),i+1); // yes choice 20 | printSubset(str,ans,i+1); // No choice 21 | } 22 | 23 | public static void main(String[] args) { 24 | String str="abc"; 25 | printSubset(str,"",0); 26 | } 27 | } 28 | 29 | /* 30 | * Output: 31 | * abc 32 | * ab 33 | * ac 34 | * a 35 | * bc 36 | * b 37 | * c 38 | * null 39 | */ -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q25_illustrate_the_multilevel_inheritance.java: -------------------------------------------------------------------------------- 1 | /* 2 | @Program: 25 3 | Write a java program to illustrate the multilevel inheritance. 4 | 5 | */ 6 | 7 | public class Q25_illustrate_the_multilevel_inheritance { 8 | public static void main(String[] args) { 9 | Child son = new Child(); 10 | son.grandFatherProperty(); 11 | son.fatherProperty(); 12 | son.childProperty(); 13 | } 14 | } 15 | class GrandFather{ 16 | public void grandFatherProperty(){ 17 | System.out.println("Plants"); 18 | } 19 | } 20 | class Father extends GrandFather{ 21 | public void fatherProperty(){ 22 | System.out.println("Window"); 23 | } 24 | } 25 | class Child extends Father{ 26 | public void childProperty(){ 27 | System.out.println("Table"); 28 | } 29 | } 30 | 31 | /* 32 | 33 | Output: 34 | Plants 35 | Window 36 | Table 37 | 38 | */ -------------------------------------------------------------------------------- /Patterns/binaryTrianglePattern.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 0-1 Triangle pattern 3 | * 4 | * 1 5 | * 0 1 6 | * 1 0 1 7 | * 0 1 0 1 8 | * 1 0 1 0 1 9 | */ 10 | 11 | 12 | public class binaryTrianglePattern { 13 | public static void main(String[] args) { 14 | short rc = 5; 15 | for (short i = 1; i <= rc; i++) { 16 | for (short j = 1; j <= i; j++) { 17 | if ((i + j) % 2 == 0) { 18 | System.out.print("1 "); 19 | } else { 20 | System.out.print("0 "); 21 | } 22 | } 23 | System.out.println(); 24 | } 25 | } 26 | } 27 | 28 | /* 29 | Output: 30 | 31 | 1 32 | 0 1 33 | 1 0 1 34 | 0 1 0 1 35 | 1 0 1 0 1 36 | 37 | */ -------------------------------------------------------------------------------- /Patterns/patternHollowRectangle.java: -------------------------------------------------------------------------------- 1 | /* HOLLOW RECTANGLE pattern 2 | * 3 | * ***** 4 | * * * 5 | * * * 6 | * ***** 7 | */ 8 | 9 | public class patternHollowRectangle { 10 | public static void main(String[] args) { 11 | short r = 4; 12 | short c = 5; 13 | for (short i = 1; i <= r; i++) { 14 | for (short j = 1; j <= c; j++) { 15 | if (i == 1 || j == 1 || j == c || i == 4) { 16 | System.out.print("*"); 17 | } else { 18 | System.out.print(" "); 19 | } 20 | } 21 | System.out.println(); 22 | } 23 | 24 | } 25 | } 26 | 27 | /* 28 | Output: 29 | 30 | ***** 31 | * * 32 | * * 33 | ***** 34 | 35 | */ -------------------------------------------------------------------------------- /OOps/GettersSetters.java: -------------------------------------------------------------------------------- 1 | /* 2 | Getters & Setters 3 | 4 | * --> Get: to return the value 5 | * --> Set: to modify the value 6 | * 7 | * * this: this keyword is used to refer to the current object. 8 | */ 9 | 10 | public class GettersSetters { 11 | public static void main(String[] args) { 12 | Pen p1 = new Pen(); 13 | p1.setColor("Blue"); 14 | p1.setTip(5); 15 | System.out.println(p1.getColor()); 16 | System.out.println(p1.getTip()); 17 | } 18 | } 19 | 20 | class Pen { 21 | private String color; 22 | private int tip; 23 | 24 | String getColor() { 25 | return this.color; 26 | } 27 | 28 | int getTip() { 29 | return this.tip; 30 | } 31 | 32 | void setColor(String color) { 33 | this.color = color; 34 | } 35 | 36 | void setTip(int tip) { 37 | this.tip = tip; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q29_try_and_catch_and_finally_block.java: -------------------------------------------------------------------------------- 1 | /* 2 | @Program: 29 3 | Write a Java program to use the try and catch and finally block. 4 | */ 5 | 6 | public class Q29_try_and_catch_and_finally_block { 7 | private static int divide(int numerator, int denominator) { 8 | return numerator / denominator; 9 | } 10 | public static void main(String[] args) { 11 | try { 12 | int result = divide(10, 0); 13 | System.out.println("Result: " + result); 14 | } catch (ArithmeticException e) { 15 | System.out.println("Error: " + e.getMessage()); 16 | } finally { 17 | System.out.println("Finally block executed."); 18 | } 19 | System.out.println("Program continues..."); 20 | } 21 | } 22 | 23 | /* 24 | * Output: 25 | * Error: / by zero 26 | * Finally block executed. 27 | * Program continues... 28 | */ -------------------------------------------------------------------------------- /Strings/StringCompression.java: -------------------------------------------------------------------------------- 1 | /* 2 | * String Compression 3 | * "aaabbcccdd" -> "a3b2c3d2" 4 | */ 5 | 6 | public class StringCompression { 7 | public static StringBuilder compression(StringBuilder str){ 8 | StringBuilder newStr = new StringBuilder(""); 9 | for (int i = 0; i < str.length(); i++) { 10 | int count =1; 11 | while (i1) { 17 | newStr.append(count); 18 | } 19 | } 20 | return newStr; 21 | } 22 | public static void main(String[] args) { 23 | StringBuilder str = new StringBuilder("aaabbcccdd"); 24 | System.out.println(compression(str)); 25 | } 26 | } 27 | 28 | 29 | /* 30 | * Output: 31 | * a3b2c3d2 32 | */ -------------------------------------------------------------------------------- /2D-Arrays/BubbleSort.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Bubble Sort 3 | * 4 | * Idea - Large elements come to the end of array by Swapping With adjacent elements 5 | */ 6 | 7 | 8 | public class BubbleSort { 9 | 10 | public static void sortArray(int array[]) { 11 | for(int i=0; iarray[j+1]) { 14 | int tmp=array[j]; 15 | array[j]=array[j+1]; 16 | array[j+1]=tmp; 17 | } 18 | } 19 | } 20 | } 21 | 22 | public static void main(String args[]) { 23 | int array[]={8,7,6,5,4,3,2,1,0}; 24 | sortArray(array); 25 | 26 | for(int i=0; i pick the smallest(from unsorted), put it at the beginning. 4 | */ 5 | 6 | 7 | public class SelectionSort { 8 | 9 | public static void sortArray(int array[]) { 10 | for(int i=0; iarray[j]){ 14 | minPos=j; 15 | } 16 | } 17 | 18 | // swap 19 | int tmp=array[i]; 20 | array[i]=array[minPos]; 21 | array[minPos]=tmp; 22 | } 23 | } 24 | public static void main(String[] args) { 25 | int array[]={5,4,1,3,2}; 26 | sortArray(array); 27 | for(int i=0; i pq = new PriorityQueue<>(); 13 | int ropes[] = { 4, 3, 2, 6 }; 14 | for (int i = 0; i < ropes.length; i++) { 15 | pq.add(ropes[i]); 16 | } 17 | int cost = 0; 18 | while (pq.size() > 1) { 19 | int num1 = pq.remove(); 20 | int num2 = pq.remove(); 21 | cost += num1 + num2; 22 | pq.add(num1 + num2); 23 | } 24 | System.out.println("Minimum cost: " + cost); 25 | } 26 | } 27 | 28 | /* 29 | * Output: 30 | * Minimum cost: 29 31 | */ 32 | -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q23_reverses_String.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @Program: 23 3 | * Write a java program that reverses a given String. 4 | */ 5 | import java.util.Scanner;; 6 | public class Q23_reverses_String { 7 | public static String reString(String str){ 8 | StringBuilder revStr = new StringBuilder(""); 9 | for (int i = str.length()-1; i >= 0; i--) { 10 | revStr.append(str.charAt(i)); 11 | } 12 | return revStr.toString(); 13 | } 14 | public static void main(String[] args) { 15 | Scanner sc = new Scanner(System.in); 16 | System.out.print("Enter the any String: "); 17 | String str = sc.nextLine(); 18 | sc.close(); 19 | String revStr = reString(str); 20 | System.out.println("Reverses String: "+ revStr); 21 | } 22 | } 23 | 24 | /* 25 | * Output: 26 | * Enter the any String: Raj kishor 27 | * Reverses String: rohsik jaR 28 | */ -------------------------------------------------------------------------------- /Patterns/HOLLOW_RECTANGLE_pattern.java: -------------------------------------------------------------------------------- 1 | /* 2 | HOLLOW RECTANGLE pattern 3 | ***** 4 | * * 5 | * * 6 | ***** 7 | 8 | */ 9 | 10 | public class HOLLOW_RECTANGLE_pattern { 11 | public static void pattern(int r, int c) { 12 | for (int i = 1; i <= r; i++) { 13 | for (int j = 1; j <= c; j++) { 14 | if (i == 1 || j == 1 || j == c || i == r) { 15 | System.out.print("*"); 16 | } else { 17 | System.out.print(" "); 18 | } 19 | } 20 | System.out.println(); 21 | } 22 | 23 | } 24 | 25 | public static void main(String[] args) { 26 | int R = 4; 27 | int C = 5; 28 | pattern(R, C); 29 | } 30 | } 31 | 32 | 33 | /* 34 | Output: 35 | 36 | ***** 37 | * * 38 | * * 39 | ***** 40 | 41 | */ -------------------------------------------------------------------------------- /Queues/QueueReversal.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Queue Reversal 3 | * {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} 4 | * rv -> {10, 9, 8, 7, 6, 5, 4, 3, 2, 1} 5 | */ 6 | 7 | import java.util.*; 8 | 9 | public class QueueReversal { 10 | 11 | public static void reverse(Queue q) { 12 | Stack s = new Stack<>(); 13 | while (!q.isEmpty()) { 14 | s.push(q.remove()); 15 | } 16 | while (!s.isEmpty()) { 17 | q.add(s.pop()); 18 | } 19 | } 20 | 21 | public static void main(String[] args) { 22 | Queue q = new LinkedList<>(); 23 | q.add(1); 24 | q.add(2); 25 | q.add(3); 26 | q.add(4); 27 | q.add(5); 28 | q.add(6); 29 | q.add(7); 30 | q.add(8); 31 | q.add(9); 32 | q.add(10); 33 | reverse(q); 34 | System.out.println(q); 35 | } 36 | } 37 | 38 | /* 39 | * Output: 40 | * 10 9 8 7 6 5 4 3 2 1 41 | */ -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q9_palindromeNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | @Program: 9 3 | * Write a java program to check whether a number is palindrome or not. 4 | */ 5 | 6 | public class Q9_palindromeNumber { 7 | public static Boolean isPalindrome(int num){ 8 | int demo = num; 9 | int rev=0; 10 | while (demo!=0) { 11 | int r = demo%10; 12 | rev = rev*10+r; 13 | demo/=10; 14 | } 15 | if (rev == num) { 16 | return true; 17 | }else{ 18 | return false; 19 | } 20 | } 21 | 22 | public static void main(String[] args) { 23 | int num = 2112; 24 | if(isPalindrome(num)){ 25 | System.out.println("Number is palindrome.!"); 26 | }else{ 27 | System.out.println("Number is not palindrome.!"); 28 | } 29 | } 30 | } 31 | 32 | /* 33 | * Output: 34 | * Number is palindrome.! 35 | */ -------------------------------------------------------------------------------- /Bits-Mantipulation/updateIthBit.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Update ith bit 3 | * n=10 = 00001010 -[i=2]> 00001110 = (14) 4 | */ 5 | 6 | public class updateIthBit { 7 | 8 | 9 | public static int updateBit(int n,int i,int newBit){ 10 | if(newBit==0){ 11 | return clearBit(n, i); 12 | }else{ 13 | return setBit(n, i); 14 | } 15 | } 16 | 17 | public static int isUpdateBit(int n,int i, int newBit){ 18 | n=clearBit(n, i); 19 | return n | (newBit<); 4 | */ 5 | 6 | import java.util.ArrayList; 7 | import java.util.Collections; 8 | 9 | /** 10 | * SortingAnArrayList 11 | */ 12 | public class SortingAnArrayList { 13 | public static void main(String[] args) { 14 | ArrayList list = new ArrayList<>(); 15 | list.add(5); 16 | list.add(1); 17 | list.add(3); 18 | list.add(6); 19 | list.add(0); 20 | list.add(4); 21 | System.out.println(list + " \nSort ArrayList"); 22 | Collections.sort(list); // ascending 23 | System.out.println(list); 24 | 25 | // descending 26 | Collections.sort(list, Collections.reverseOrder()); 27 | System.out.println(list); // [6, 5, 4, 3, 1, 0] 28 | } 29 | } 30 | 31 | /* 32 | * Output 33 | * [5, 1, 3, 6, 0, 4] 34 | * Sort ArrayList 35 | * [0, 1, 3, 4, 5, 6] 36 | * [6, 5, 4, 3, 1, 0] 37 | */ -------------------------------------------------------------------------------- /SortingAlgorithms/BubbleSort.java: -------------------------------------------------------------------------------- 1 | /** 2 | * BubbleSort 3 | */ 4 | public class BubbleSort { 5 | 6 | public static void bubbleSort(int arr[]) { 7 | for (int i = 0; i < arr.length - 1; i++) { 8 | for (int j = 0; j < arr.length - 1 - i; j++) { 9 | if (arr[j] > arr[j + 1]) { 10 | int temp = arr[j]; 11 | arr[j] = arr[j + 1]; 12 | arr[j + 1] = temp; 13 | } 14 | } 15 | } 16 | } 17 | 18 | public static void printArray(int arr[]) { 19 | for (int i = 0; i < arr.length; i++) { 20 | System.out.print(arr[i] + " "); 21 | } 22 | System.out.println(); 23 | } 24 | 25 | public static void main(String[] args) { 26 | int arr[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1 }; 27 | 28 | bubbleSort(arr); 29 | printArray(arr); 30 | 31 | } 32 | } 33 | 34 | /* 35 | * Output: 36 | * 1 2 3 4 5 6 7 8 9 37 | */ -------------------------------------------------------------------------------- /Basic/averageOfThreeNo.java: -------------------------------------------------------------------------------- 1 | /* 2 | In a program, input 3 numbers : compute the average of three numbers... 3 | */ 4 | 5 | import java.util.Scanner; 6 | 7 | public class averageOfThreeNo { 8 | 9 | public static void average(float a, float b, float c) { 10 | float avg = (a + b + c) / 3; 11 | System.out.println("Average of three numbers: " + avg); 12 | } 13 | 14 | public static void main(String[] args) { 15 | Scanner sc = new Scanner(System.in); 16 | System.out.print("Enter the three number: "); 17 | float a = sc.nextFloat(); 18 | float b = sc.nextFloat(); 19 | float c = sc.nextFloat(); 20 | // float sum = (a + b + c) / 3; 21 | // System.out.println("Average of three no: " + sum); 22 | 23 | average(a,b,c); 24 | 25 | } 26 | } 27 | 28 | /* 29 | * Output: 30 | * Enter the three number: 78.5 75.5 86.9 31 | * Average of three no: 80.299995 32 | */ -------------------------------------------------------------------------------- /Strings/convertFirstLetterOfUppercase.java: -------------------------------------------------------------------------------- 1 | /* 2 | * For a given String convert each the first letter of each word to uppercase. 3 | * 4 | * "hi, i am raj kishor" -> "Hi, I Am Raj Kishor" 5 | */ 6 | 7 | 8 | public class convertFirstLetterOfUppercase { 9 | 10 | public static String conFirstUppercase(String str){ 11 | StringBuilder sb = new StringBuilder(""); 12 | sb.append(Character.toUpperCase(str.charAt(0))); 13 | for(int i=1; i s, int data) { 10 | if (s.isEmpty()) { 11 | s.push(data); 12 | return; 13 | } 14 | int pop = s.pop(); 15 | pushBottom(s, data); 16 | s.push(pop); 17 | } 18 | 19 | public static void isReverse(Stack s) { 20 | if (s.isEmpty()) { 21 | return; 22 | } 23 | int data = s.pop(); 24 | isReverse(s); 25 | pushBottom(s, data); 26 | } 27 | 28 | public static void main(String[] args) { 29 | Stack s = new Stack<>(); 30 | s.push(1); 31 | s.push(2); 32 | s.push(3); 33 | isReverse(s); 34 | while (!s.empty()) { 35 | System.out.println(s.peek()); 36 | s.pop(); 37 | } 38 | } 39 | } 40 | 41 | /* 42 | * output: 43 | * 1 44 | * 2 45 | * 3 46 | */ -------------------------------------------------------------------------------- /Stacks/StackUsingArrayList.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class StackUsingArrayList { 4 | 5 | static class Stack { 6 | 7 | static ArrayList list = new ArrayList<>(); 8 | 9 | public boolean isEmpty() { 10 | return list.size() == 0; 11 | } 12 | 13 | // push 14 | public void push(int data) { 15 | list.add(data); 16 | } 17 | 18 | // pop 19 | public int pop() { 20 | int top = list.get(list.size() - 1); 21 | list.remove(list.size() - 1); 22 | return top; 23 | } 24 | 25 | // peek 26 | public int peek() { 27 | return list.get(list.size() - 1); 28 | } 29 | } 30 | 31 | public static void main(String[] args) { 32 | Stack s = new Stack(); 33 | s.push(1); 34 | s.push(2); 35 | s.push(3); 36 | while (!s.isEmpty()) { 37 | System.out.println(s.peek()); 38 | s.pop(); 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q31_create_BCA_package.java: -------------------------------------------------------------------------------- 1 | /* 2 | @Program: 31 3 | Write a package BCA which has one class Student. Accept student detail through parameterized constructor. 4 | Write display() method to display details. Create a main class which will use package and calculate total marks and percentage. 5 | */ 6 | import BCA.Student; 7 | 8 | public class Q31_create_BCA_package { 9 | public static void main(String[] args) { 10 | Student student = new Student("Raj Kishor", 6095, 80, 75, 90,79); 11 | 12 | student.display(); 13 | 14 | System.out.println("Total Marks: " + student.getTotalMarks()); 15 | System.out.println("Percentage: " + student.getPercentage() + "%"); 16 | } 17 | } 18 | 19 | /* 20 | * Output: 21 | * Student Details: 22 | * Name: Raj Kishor 23 | * Roll Number: 6095 24 | * DBMS: 80 25 | * java: 75 26 | * computerNetworks: 90 27 | * numericalMethod: 79 28 | * Total Marks: 324 29 | * Percentage: 81.0% 30 | */ -------------------------------------------------------------------------------- /Patterns/hollowRhombusPattern.java: -------------------------------------------------------------------------------- 1 | /* 2 | * HOLLOW RHOMBUS pattern 3 | * 4 | * ***** 5 | * * * 6 | * * * 7 | * * * 8 | * ***** 9 | */ 10 | 11 | public class hollowRhombusPattern { 12 | public static void main(String[] args) { 13 | short n = 5; 14 | for (short i = 1; i <= n; i++) { 15 | for (short j = 1; j <= n - i; j++) { 16 | System.out.print(" "); 17 | } 18 | for (short j = 1; j <= n; j++) { 19 | if (i == 1 || j == 1 || j == n || i == n) { 20 | System.out.print("*"); 21 | } else { 22 | System.out.print(" "); 23 | } 24 | } 25 | System.out.println(); 26 | } 27 | } 28 | } 29 | 30 | /* 31 | Output: 32 | 33 | ***** 34 | * * 35 | * * 36 | * * 37 | ***** 38 | 39 | 40 | */ 41 | -------------------------------------------------------------------------------- /2D-Arrays/CountingSort.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Counting Sort 3 | */ 4 | 5 | public class CountingSort { 6 | 7 | public static void sortArray(int array[]) { 8 | int largest=Integer.MIN_VALUE; 9 | for(int i=0; i0){ 20 | array[j]=i; 21 | j++; 22 | count[i]--; 23 | } 24 | } 25 | 26 | } 27 | 28 | public static void main(String[] args) { 29 | int array[]={1,4,1,3,2,4,3,7}; 30 | sortArray(array); 31 | 32 | for(int i=0; inum2) { 17 | if (num1>num3) { 18 | max = num1; 19 | }else{ 20 | max = num3; 21 | } 22 | }else if(num2>num3){ 23 | max =num2; 24 | }else{ 25 | max =num3; 26 | } 27 | System.out.println("Largest among of three numbers is "+max); 28 | } 29 | } 30 | 31 | /* 32 | Output: 33 | Enter any Three number: 34 | 10 20 30 35 | Largest among of three numbers is 30 36 | */ -------------------------------------------------------------------------------- /ArrayLists/SwapTwoNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Swap 2 Numbers 3 | * list = 2, 5, 9, 3, 6 4 | * index : inx1=1, inx2=3; 5 | * list = 2, 3, 9, 5, 6 6 | */ 7 | 8 | import java.util.ArrayList; 9 | 10 | public class SwapTwoNumber { 11 | 12 | public static void swap(ArrayList list , int idx1 , int idx2) { 13 | int temp = list.get(idx1); 14 | list.set(idx1, list.get(idx2)); 15 | list.set(idx2, temp); 16 | } 17 | 18 | public static void main(String[] args) { 19 | ArrayList list = new ArrayList<>(); 20 | list.add(2); 21 | list.add(5); 22 | list.add(9); 23 | list.add(3); 24 | list.add(6); 25 | int idx1 = 1 , idx2 = 3; 26 | System.out.println(list); // [2, 5, 9, 3, 6] 27 | System.out.println("After swap Numbers.."); 28 | swap(list,idx1,idx2); 29 | System.out.println(list); // [2, 3, 9, 5, 6] 30 | } 31 | } 32 | 33 | /* 34 | * Output: 35 | * [2, 5, 9, 3, 6] 36 | * After swap Numbers.. 37 | * [2, 3, 9, 5, 6] 38 | */ -------------------------------------------------------------------------------- /Strings/FindShortestPath.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a route containing 4 directions(E, W, N, S), 3 | * find the shortest path to reach destination. 4 | * path -> (WNEENESENNN) 5 | */ 6 | public class FindShortestPath { 7 | public static void main(String[] args) { 8 | String path = "WNEENESENNN"; 9 | Double dest = getShortPath(path); 10 | System.out.println(dest); 11 | } 12 | 13 | private static Double getShortPath(String path) { 14 | int x=0; 15 | int y=0; 16 | for (int i = 0; i < path.length(); i++) { 17 | char ch = path.charAt(i); 18 | if (ch=='E') { 19 | x++; 20 | } 21 | if (ch=='W') { 22 | x--; 23 | } 24 | if (ch=='N') { 25 | y++; 26 | } 27 | if (ch=='S') { 28 | y--; 29 | } 30 | } 31 | int X = x*x; 32 | int Y = y*y; 33 | return Math.sqrt(X+Y); 34 | } 35 | } 36 | 37 | /* 38 | * Output: 39 | * 5.0 40 | */ -------------------------------------------------------------------------------- /Queues/FirstNonRepeatingLetter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * First non-repeating letter in a stream of characters. 3 | */ 4 | 5 | import java.util.LinkedList; 6 | import java.util.Queue; 7 | import javax.management.Query; 8 | 9 | public class FirstNonRepeatingLetter { 10 | 11 | public static void printNonRepeating(String str) { 12 | int freq[] = new int[26]; // 'a' - 'z' 13 | Queue q = new LinkedList<>(); 14 | for (int i = 0; i < str.length(); i++) { 15 | char ch = str.charAt(i); 16 | q.add(ch); 17 | freq[ch - 'a']++; 18 | 19 | while (!q.isEmpty() && freq[q.peek() - 'a'] > 1) { 20 | q.remove(); 21 | } 22 | } 23 | if (q.isEmpty()) { 24 | System.out.println(-1); 25 | } else { 26 | System.out.println(q.peek()); 27 | } 28 | } 29 | 30 | public static void main(String[] args) { 31 | String str = "aabccxb"; 32 | printNonRepeating(str); 33 | } 34 | } 35 | 36 | /* 37 | * Output: 38 | * x 39 | */ 40 | -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q20_Bubble_sort_algorithm.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @Program: 20 3 | * Write a java program to implement bubble sort algorithm. 4 | */ 5 | 6 | public class Q20_Bubble_sort_algorithm { 7 | 8 | public static void bubbleSort(int arr[]){ 9 | for (int i = 0; i < arr.length-1; i++) { 10 | int count=0; 11 | for (int j = 0; j < arr.length-i-1; j++) { 12 | if (arr[j]>arr[j+1]) { 13 | int temp = arr[j]; 14 | arr[j]=arr[j+1]; 15 | arr[j+1]= temp; 16 | count++; 17 | } 18 | } 19 | if (count==0) { 20 | break; 21 | } 22 | } 23 | } 24 | 25 | public static void main(String[] args) { 26 | int arr[]={9,8,7,6,5,4,3,4,5}; 27 | bubbleSort(arr); 28 | for(int i=0; i deque = new LinkedList<>(); 11 | 12 | public void add(int data) { 13 | deque.addLast(data); 14 | } 15 | 16 | public boolean isEmpty() { 17 | return deque.isEmpty(); 18 | } 19 | 20 | public int peek() { 21 | return deque.getFirst(); 22 | } 23 | 24 | public int remove() { 25 | return deque.removeFirst(); 26 | } 27 | } 28 | 29 | public static void main(String[] args) { 30 | Queue q = new Queue(); 31 | q.add(1); 32 | q.add(2); 33 | q.add(3); 34 | q.add(4); 35 | q.add(5); 36 | 37 | while (!q.isEmpty()) { 38 | System.out.println(q.peek()); 39 | q.remove(); 40 | } 41 | } 42 | } 43 | 44 | /* 45 | * Output: 46 | * 1 47 | * 2 48 | * 3 49 | * 4 50 | * 5 51 | */ -------------------------------------------------------------------------------- /SortingAlgorithms/SelectionSort.java: -------------------------------------------------------------------------------- 1 | /** 2 | * SelectionSort 3 | */ 4 | public class SelectionSort { 5 | 6 | public static void selectionSort(int array[]) { 7 | for (int i = 0; i < array.length; i++) { 8 | int min = i; 9 | int j = array.length - 1; 10 | while (j > i) { 11 | if (array[min] > array[j]) { 12 | min = j; 13 | } 14 | j--; 15 | } 16 | int temp = array[min]; 17 | array[min] = array[i]; 18 | array[i] = temp; 19 | } 20 | } 21 | 22 | public static void printArray(int arr[]) { 23 | for (int i = 0; i < arr.length; i++) { 24 | System.out.print(arr[i] + " "); 25 | } 26 | System.out.println(); 27 | } 28 | 29 | public static void main(String[] args) { 30 | 31 | int arr[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1 }; 32 | 33 | selectionSort(arr); 34 | printArray(arr); 35 | 36 | } 37 | } 38 | 39 | /* 40 | * Output: 41 | * 1 2 3 4 5 6 7 8 9 42 | */ -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q17_Binary_to_decimal.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @Program: 17 3 | * Write a java program to convert binary number into decimal number. 4 | */ 5 | 6 | import java.util.Scanner; 7 | 8 | public class Q17_Binary_to_decimal { 9 | public static int binaryToDecimal(int binary) { 10 | int decimal = 0; 11 | int pow =0; 12 | 13 | while (binary!=0) { 14 | int r =binary%10; 15 | decimal += Math.pow(2, pow)*r; 16 | binary/=10; 17 | pow++; 18 | } 19 | return decimal; 20 | } 21 | public static void main(String[] args) { 22 | Scanner sc = new Scanner(System.in); 23 | 24 | System.out.print("Enter a binary number: "); 25 | int binary = sc.nextInt(); 26 | int decimal =binaryToDecimal(binary); 27 | System.out.println("Decimal number is: "+decimal); 28 | } 29 | } 30 | 31 | /* 32 | 33 | Output: 34 | Enter a binary number: 1010 35 | Decimal number is: 10 36 | 37 | Enter a binary number: 1000 38 | Decimal number is: 8 39 | 40 | */ -------------------------------------------------------------------------------- /Strings/anagrams.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Determine if 2 Strings are anagrams of each other. 3 | */ 4 | 5 | import java.util.Arrays; 6 | 7 | public class anagrams { 8 | public static void main(String[] args) { 9 | String str1 = "rajkishorbgp"; 10 | String str2 = "kishorbgpraj"; 11 | if (anagrams(str1, str2)) { 12 | System.out.println("Strings are anagrams."); 13 | } else { 14 | System.out.println("Strings are not anagrams."); 15 | } 16 | } 17 | 18 | public static Boolean anagrams(String str1, String str2) { 19 | if (str1.length() != str2.length()) { 20 | return false; 21 | } 22 | char str3[] = str1.toCharArray(); 23 | char str4[] = str2.toCharArray(); 24 | Arrays.sort(str3); 25 | Arrays.sort(str4); 26 | for (int i = 0; i < str3.length; i++) { 27 | if (str3[i] != str4[i]) { 28 | return false; 29 | } 30 | } 31 | return true; 32 | } 33 | } 34 | 35 | /* 36 | * Output: 37 | * Strings are anagrams. 38 | */ -------------------------------------------------------------------------------- /BackTracking/BackTracking.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Back tracking 3 | * 4 | * Types of Back tracking 5 | * (1) Decision 6 | * (2) Optimization 7 | * (3) Enumeration 8 | */ 9 | 10 | public class BackTracking { 11 | 12 | public static void changeArray(int arr[], int i , int val){ 13 | 14 | // base case 15 | if(i==arr.length){ 16 | printArray(arr); 17 | return; 18 | } 19 | 20 | // Recursion(kaam) 21 | arr[i]=val; 22 | changeArray( arr , i+1 , val+1 ); //fnx call stap 23 | arr[i]-=2; //back tracking stap 24 | 25 | } 26 | 27 | public static void printArray(int arr[]){ 28 | 29 | for(int i=0; i= 1; j--) { 20 | System.out.print(j + " "); 21 | } 22 | for (short j = 2; j <= i; j++) { 23 | System.out.print(j + " "); 24 | } 25 | System.out.println(); 26 | } 27 | } 28 | } 29 | 30 | /* 31 | Output: 32 | 33 | 1 34 | 2 1 2 35 | 3 2 1 2 3 36 | 4 3 2 1 2 3 4 37 | 5 4 3 2 1 2 3 4 5 38 | 39 | */ -------------------------------------------------------------------------------- /Arrays/BinarySearch.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Binary Search 3 | * Prerequisite - sorted arrays 4 | */ 5 | 6 | 7 | public class BinarySearch { 8 | public static int binarySearch(int arr[], int key) { 9 | int start=0 , end=arr.length-1; 10 | while(start<=end){ 11 | int mid = (start + end)/2; 12 | // comparisons 13 | if(arr[mid]==key){ 14 | return mid; 15 | } 16 | if(arr[mid]arr[i]){ 21 | Smallest=arr[i]; 22 | } 23 | } 24 | return Smallest; 25 | } 26 | public static void main(String[] args) { 27 | int array[]={2,4,6,8,5,12,34,1,23,0,32,3}; 28 | System.out.println("Largest Number: " + largestNumber(array)); 29 | System.out.println("Smallest Number: " + SmallestNumber(array)); 30 | } 31 | } 32 | 33 | /* 34 | * Output: 35 | * Largest Number: 34 36 | * Smallest Number: 0 37 | */ -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q7_Find_LCM_of_two_numbers.java: -------------------------------------------------------------------------------- 1 | /* @Progrme: 7 2 | * Write a java program to find LCM of two numbers. 3 | */ 4 | 5 | import java.util.Scanner; 6 | 7 | public class Q7_Find_LCM_of_two_numbers { 8 | public static int gcd(int num1, int num2) { 9 | if (num2 == 0) { 10 | return num1; 11 | } 12 | return gcd(num2, num1 % num2); 13 | } 14 | 15 | public static int lcm(int num1, int num2) { 16 | int gcdResult = gcd(num1, num2); 17 | return (num1 * num2) / gcdResult; 18 | } 19 | 20 | public static void main(String[] args) { 21 | Scanner sc = new Scanner(System.in); 22 | System.out.print("Enter the first number: "); 23 | int num1 = sc.nextInt(); 24 | System.out.print("Enter the second number: "); 25 | int num2 = sc.nextInt(); 26 | 27 | int result = lcm(num1, num2); 28 | System.out.println("LCM of two numbers: " + result); 29 | } 30 | } 31 | 32 | /* 33 | Output: 34 | Enter the first number: 10 35 | Enter the second number: 40 36 | LCM of two numbers: 10 37 | */ -------------------------------------------------------------------------------- /Arrays/PairsInArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Pairs in an Array 3 | * 4 | * Ex- array = {2,4,6,8,10}; 5 | * 6 | * O/P --> (2,4) (2,6) (2,8) (2,10) 7 | * (4,6) (4,8) (4,10) 8 | * (6,8) (6,10) 9 | * (8,10) 10 | */ 11 | 12 | public class PairsInArray { 13 | 14 | public static int pairsInArray(int array[]) { 15 | int tp=0; 16 | for(int i=0; i The next greater element of same element X in an array is the first greater 4 | * element that is to the right of x in the same array. 5 | */ 6 | 7 | import java.util.Stack; 8 | 9 | public class NextGreaterElementCode { 10 | 11 | public static void main(String[] args) { 12 | 13 | int arr[] = { 6, 8, 0, 1, 3 }; 14 | int n = arr.length; 15 | int nextGreater[] = new int[n]; 16 | Stack s = new Stack<>(); 17 | 18 | for (int i = n - 1; i >= 0; i--) { 19 | while (!s.empty() && arr[s.peek()] <= arr[i]) { 20 | s.pop(); 21 | } 22 | if (s.isEmpty()) { 23 | nextGreater[i] = -1; 24 | } else { 25 | nextGreater[i] = arr[s.peek()]; 26 | } 27 | s.push(i); 28 | } 29 | 30 | for (int i = 0; i < n; i++) { 31 | System.out.print(nextGreater[i] + " "); 32 | } 33 | System.out.println(); 34 | } 35 | } 36 | 37 | /* 38 | * Output: 39 | * 8 -1 1 3 -1 40 | */ 41 | -------------------------------------------------------------------------------- /Arrays/Array.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Arrays 3 | * -> Array is a list of element of the same type placed in a contiguous memory location. 4 | */ 5 | 6 | import java.util.*; 7 | 8 | public class Array { 9 | 10 | public static void main(String[] args) { 11 | 12 | Scanner sc = new Scanner(System.in); 13 | // Creating an Array 14 | 15 | // dataType arratName[] = new dataType[size]; 16 | 17 | int marks[] = new int[50]; 18 | 19 | int number[] = { 1, 2, 3, 4, 5 }; 20 | 21 | String fruits[] = { "Apple", "Mango", "Orange" }; 22 | 23 | // Input in arrays 24 | System.out.print("Enter the 5 subject marks: "); 25 | marks[0] = sc.nextInt(); 26 | marks[1] = sc.nextInt(); 27 | marks[2] = sc.nextInt(); 28 | marks[3] = sc.nextInt(); 29 | marks[4] = sc.nextInt(); 30 | 31 | // Output in Array 32 | System.out.println(marks[0] + " " + marks[1] + " " + marks[2] + " " + marks[3] + " " + marks[4]); 33 | } 34 | 35 | } 36 | 37 | /* 38 | * Output: 39 | * Enter the 5 subject marks: 70 80 79 87 98 40 | * 70 80 79 87 98 41 | */ -------------------------------------------------------------------------------- /Strings/StringsConvertLettersToUppercase.java: -------------------------------------------------------------------------------- 1 | /** 2 | * For a given String convert each the first letter of each 3 | * word to uppercase. 4 | * 5 | * "hi, i am rajkishor" 6 | */ 7 | 8 | public class StringsConvertLettersToUppercase { 9 | public static StringBuilder convertFirstLetterOfUppercase(StringBuilder str){ 10 | StringBuilder sb = new StringBuilder(""); 11 | 12 | char ch = Character.toUpperCase(str.charAt(0)); 13 | sb.append(ch); 14 | 15 | for (int i = 1; i < str.length(); i++) { 16 | if (str.charAt(i) == ' ') { 17 | sb.append(str.charAt(i)); 18 | i++; 19 | sb.append(Character.toUpperCase(str.charAt(i))); 20 | }else{ 21 | sb.append(str.charAt(i)); 22 | } 23 | } 24 | return sb; 25 | } 26 | public static void main(String[] args) { 27 | StringBuilder str = new StringBuilder("hi, i am rajkishor"); 28 | str = convertFirstLetterOfUppercase(str); 29 | System.out.println(str); 30 | } 31 | } 32 | 33 | /* 34 | * Output: 35 | * Hi, I Am Rajkishor 36 | */ -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/FileHandling/My_FileInputStream.java: -------------------------------------------------------------------------------- 1 | import java.io.FileInputStream; 2 | import java.io.IOException; 3 | import java.io.*; 4 | 5 | public class My_FileInputStream { 6 | public static void main(String[] args)throws IOException { 7 | int i; 8 | FileInputStream fout = new FileInputStream("D:/My Database/FileOutputStream.txt"); 9 | do { 10 | i=fout.read(); 11 | if (i!=-1) { 12 | System.out.print((char)i); 13 | } 14 | } while (i!=-1); 15 | } 16 | } 17 | 18 | 19 | // import java.io.FileInputStream; 20 | // import java.io.IOException; 21 | 22 | // public class My_FileInputStream { 23 | // public static void main(String[] args) { 24 | // try (FileInputStream fin = new FileInputStream("D:\\My Database\\FileOutputStream.txt")) { 25 | // int i; 26 | // while ((i = fin.read()) != -1) { 27 | // System.out.print((char) i); 28 | // } 29 | // } catch (IOException e) { 30 | // e.printStackTrace(); 31 | // } 32 | // } 33 | // } 34 | -------------------------------------------------------------------------------- /SortingAlgorithms/CountingSort.java: -------------------------------------------------------------------------------- 1 | public class CountingSort { 2 | 3 | public static void countingSort(int arr[]) { 4 | int max = Integer.MIN_VALUE; 5 | for (int i = 0; i < arr.length; i++) { 6 | max = Math.max(max, arr[i]); 7 | } 8 | 9 | int count[] = new int[max + 1]; 10 | for (int i = 0; i < arr.length; i++) { 11 | count[arr[i]]++; 12 | } 13 | 14 | // sort 15 | int j = 0; 16 | for (int i = 0; i < count.length; i++) { 17 | while (count[i] > 0) { 18 | arr[j] = i; 19 | j++; 20 | count[i]--; 21 | } 22 | } 23 | } 24 | 25 | public static void printArray(int arr[]) { 26 | for (int i = 0; i < arr.length; i++) { 27 | System.out.print(arr[i] + " "); 28 | } 29 | System.out.println(); 30 | } 31 | 32 | public static void main(String[] args) { 33 | int array[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1 }; 34 | countingSort(array); 35 | printArray(array); 36 | } 37 | } 38 | 39 | /* 40 | * Output: 41 | * 1 2 3 4 5 6 7 8 9 42 | */ -------------------------------------------------------------------------------- /Hashing/MajorityElement.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given an integer array of size n, find all elements that appear more than[n/3] times. 3 | */ 4 | 5 | import java.util.HashMap; 6 | 7 | public class MajorityElement { 8 | 9 | public static void main(String[] args) { 10 | // int arr[] = { 1, 3, 2, 5, 1, 3, 1, 5, 1 }; [output: 1] 11 | int arr[] = { 1, 2 }; 12 | HashMap hm = new HashMap<>(); 13 | 14 | // for (int i = 0; i < arr.length; i++) { 15 | // if (hm.containsKey(arr[i])) { 16 | // hm.put(arr[i], hm.get(arr[i]) + 1); 17 | // } else { 18 | // hm.put(arr[i], 1); 19 | // } 20 | // } 21 | 22 | // Sortcut 23 | for (int i = 0; i < arr.length; i++) { 24 | hm.put(arr[i], hm.getOrDefault(arr[i], 0) + 1); 25 | } 26 | 27 | // Set keys = hm.keySet(); 28 | 29 | // sortcut 30 | for (int key : hm.keySet()) { 31 | if (hm.get(key) > arr.length / 3) { 32 | System.out.println(key); 33 | } 34 | } 35 | } 36 | } 37 | 38 | /* 39 | * Output: 40 | * 1 41 | * 2 42 | */ 43 | -------------------------------------------------------------------------------- /Basic/costOfThreeItems.java: -------------------------------------------------------------------------------- 1 | /* 2 | Enter cost of 3 items from the user (using float data type) - a pencil, a pen and 3 | an eraser. You have to output the total cost of the items back to the user as their bill. */ 4 | 5 | import java.util.Scanner; 6 | 7 | public class costOfThreeItems { 8 | public static void main(String[] args) { 9 | Scanner sc = new Scanner(System.in); 10 | System.out.print("Enter the cost of pencil: "); 11 | float a = sc.nextFloat(); 12 | System.out.print("Enter the cost of pen: "); 13 | float b = sc.nextFloat(); 14 | System.out.print("Enter the cost of eraser: "); 15 | float c = sc.nextFloat(); 16 | float total = (a + b + c); 17 | System.out.println("Bill is : " + total); 18 | // Add on - with 18% tax 19 | float newTotal = total + (0.18f * total); 20 | System.out.println("Bill with 18% tax : " + newTotal); 21 | 22 | } 23 | } 24 | 25 | /* 26 | * Output: 27 | * Enter the cost of pencil: 5 28 | * Enter the cost of pen: 8 29 | * Enter the cost of eraser: 5 30 | * Bill is : 18.0 31 | * Bill with 18% tax : 21.24 32 | */ -------------------------------------------------------------------------------- /Stacks/ImplementStackUsingDeque.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Stack using Deque 3 | * (i) push() 4 | * (ii) pop() 5 | * (iii) peek() 6 | */ 7 | 8 | import java.util.*; 9 | import java.util.LinkedList; 10 | 11 | public class ImplementStackUsingDeque { 12 | 13 | static class Stack { 14 | Deque deque = new LinkedList<>(); 15 | 16 | public void push(int data) { 17 | deque.addLast(data); 18 | } 19 | 20 | public boolean isEmpty() { 21 | return deque.isEmpty(); 22 | } 23 | 24 | public int pop() { 25 | return deque.removeLast(); 26 | } 27 | 28 | public int peek() { 29 | return deque.getLast(); 30 | } 31 | 32 | } 33 | 34 | public static void main(String[] args) { 35 | Stack s = new Stack(); 36 | s.push(1); 37 | s.push(2); 38 | s.push(3); 39 | s.push(4); 40 | s.push(5); 41 | while (!s.isEmpty()) { 42 | System.out.println(s.peek()); 43 | s.pop(); 44 | } 45 | } 46 | } 47 | 48 | /* 49 | * Output: 50 | * 5 51 | * 4 52 | * 3 53 | * 2 54 | * 1 55 | */ -------------------------------------------------------------------------------- /Arrays/MaxSubarraySum.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Prifix Array 3 | * {1,-2,6,-1,3} 4 | * 5 | * prefix Array={1,-1,5,4,7} 6 | * 7 | */ 8 | 9 | public class MaxSubarraySum { 10 | 11 | public static void maxSubarraySum(int array[]) { 12 | int max=Integer.MIN_VALUE; 13 | int prefix[]=new int[array.length]; 14 | prefix[0]=array[0]; 15 | 16 | // Calculate prifixArray 17 | for(int i=1; i You are given n pairs of numbers. In every pair, the first number is always smaller than 5 | * the second number.A pair {c, d)}an come after pair(a, b) if b o[1])); 21 | 22 | int ans = 1; 23 | int pairEnd = pairs[0][1]; 24 | for (int i = 1; i < pairs.length; i++) { 25 | if (pairEnd < pairs[i][0]) { 26 | ans++; 27 | pairEnd = pairs[i][1]; 28 | } 29 | } 30 | System.out.println("Max Length Chain of Pairs: " + ans); 31 | } 32 | } 33 | 34 | /* 35 | * Output: 36 | * Max Length Chain of Pairs: 3 37 | */ 38 | -------------------------------------------------------------------------------- /Queues/InterleaveTwoHalvesOfQueue.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @Interleave 2 Halves of a Queue(even length) 3 | * 4 | * {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} 5 | * {1, 6, 2, 7, 3, 8, 4, 9, 5, 10} 6 | */ 7 | 8 | import java.util.LinkedList; 9 | import java.util.Queue; 10 | 11 | public class InterleaveTwoHalvesOfQueue { 12 | 13 | public static void interleaveTwoHalves(Queue q1) { 14 | int size = q1.size(); 15 | Queue q2 = new LinkedList<>(); 16 | for (int i = 0; i < size / 2; i++) { 17 | q2.add(q1.remove()); 18 | } 19 | while (!q2.isEmpty()) { 20 | q1.add(q2.remove()); 21 | q1.add(q1.remove()); 22 | } 23 | } 24 | 25 | public static void main(String[] args) { 26 | Queue q = new LinkedList<>(); 27 | q.add(1); 28 | q.add(2); 29 | q.add(3); 30 | q.add(4); 31 | q.add(5); 32 | q.add(6); 33 | q.add(7); 34 | q.add(8); 35 | q.add(9); 36 | q.add(10); 37 | System.out.println(q); 38 | interleaveTwoHalves(q); 39 | System.out.println(q); 40 | } 41 | } 42 | 43 | /* 44 | * Output: 45 | * 1 6 2 7 3 8 4 9 5 10 46 | */ 47 | -------------------------------------------------------------------------------- /SortingAlgorithms/QuickSort.java: -------------------------------------------------------------------------------- 1 | 2 | public class QuickSort { 3 | 4 | public static void quickSort(int arr[], int si, int ei) { 5 | if (si >= ei) { 6 | return; 7 | } 8 | int pidx = partition(arr, si, ei); 9 | quickSort(arr, si, pidx - 1); 10 | quickSort(arr, pidx + 1, ei); 11 | } 12 | 13 | public static int partition(int arr[], int si, int ei) { 14 | int pivot = arr[ei]; 15 | int j = si - 1; 16 | for (int i = si; i < ei; i++) { 17 | if (arr[i] < pivot) { 18 | int temp = arr[++j]; 19 | arr[j] = arr[i]; 20 | arr[i] = temp; 21 | } 22 | } 23 | arr[ei] = arr[++j]; 24 | arr[j] = pivot; 25 | return j; 26 | } 27 | 28 | public static void main(String[] args) { 29 | 30 | int arr[] = { 8, 7, 6, 5, 4, 3, 5, 6, 3, 2, 1, 23, 4, 5, 6, 7, 8 }; 31 | quickSort(arr, 0, arr.length - 1); 32 | 33 | for (int i = 0; i < arr.length; i++) { 34 | System.out.print(arr[i] + " "); 35 | } 36 | System.out.println(); 37 | } 38 | } 39 | 40 | /* 41 | * Output: 42 | * 1 2 3 3 4 4 5 5 5 6 6 6 7 7 8 8 23 43 | */ -------------------------------------------------------------------------------- /BinaryTrees/KthLevelPrint.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Kth Level of a Tree 3 | */ 4 | 5 | public class KthLevelPrint { 6 | 7 | public static void KLevel(Node root, int level, int k) { 8 | 9 | if (root == null) { 10 | return; 11 | } 12 | 13 | if (level == k) { 14 | System.out.print(root.data + " "); 15 | return; 16 | } 17 | KLevel(root.left, level + 1, k); 18 | KLevel(root.right, level + 1, k); 19 | } 20 | 21 | static class Node { 22 | int data; 23 | Node left; 24 | Node right; 25 | 26 | Node(int data) { 27 | this.data = data; 28 | this.left = null; 29 | this.right = null; 30 | } 31 | } 32 | 33 | public static void main(String[] args) { 34 | Node root = new Node(1); 35 | root.left = new Node(2); 36 | root.right = new Node(3); 37 | root.left.left = new Node(4); 38 | root.left.right = new Node(5); 39 | root.right.left = new Node(6); 40 | root.right.right = new Node(7); 41 | 42 | int k = 3; 43 | KLevel(root, 1, k); 44 | } 45 | } 46 | 47 | /* 48 | * Output: 49 | * 4 5 6 7 50 | * 51 | */ -------------------------------------------------------------------------------- /Hashing/Union_IntersectionOfTwoArrays.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | 3 | public class Union_IntersectionOfTwoArrays { 4 | 5 | public static int union(int arr1[], int arr2[]) { 6 | HashSet hs = new HashSet<>(); 7 | for (int i = 0; i < arr1.length; i++) { 8 | hs.add(arr1[i]); 9 | } 10 | for (int i = 0; i < arr2.length; i++) { 11 | hs.add(arr2[i]); 12 | } 13 | return hs.size(); 14 | } 15 | 16 | public static int intersection(int[] arr1, int[] arr2) { 17 | int count = 0; 18 | HashSet hs = new HashSet<>(); 19 | for (int i = 0; i < arr1.length; i++) { 20 | hs.add(arr1[i]); 21 | } 22 | for (int i = 0; i < arr2.length; i++) { 23 | if (hs.remove(arr2[i])) { 24 | count++; 25 | } 26 | } 27 | return count; 28 | } 29 | 30 | public static void main(String[] args) { 31 | int arr1[] = { 7, 3, 9 }; 32 | int arr2[] = { 6, 3, 9, 2, 9, 4 }; 33 | 34 | System.out.println(union(arr1, arr2)); 35 | System.out.println(intersection(arr1, arr2)); 36 | } 37 | } 38 | 39 | /* 40 | * Output: 41 | * 6 42 | * 2 43 | */ -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q18_add_two_matrix.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @Program: 18 3 | * Write a java program to add two matrix using multi-dimensional arrays. 4 | */ 5 | public class Q18_add_two_matrix { 6 | public static int[][] addMatrix(int matrix1[][], int matrix2[][]){ 7 | int result[][] = new int[3][3]; 8 | for (int i = 0; i < matrix1.length; i++) { 9 | for (int j = 0; j < matrix2.length; j++) { 10 | result[i][j]=matrix1[i][j]+matrix2[i][j]; 11 | } 12 | } 13 | return result; 14 | } 15 | public static void main(String[] args) { 16 | int matrix1[][]={{2,2,2},{3,3,3},{4,4,4}}; 17 | int matrix2[][]={{2,2,2},{3,3,3},{4,4,4}}; 18 | int result[][]=addMatrix(matrix1, matrix2); 19 | System.out.println("Add two matrix...!"); 20 | for (int i = 0; i < matrix1.length; i++) { 21 | for (int j = 0; j < matrix2.length; j++) { 22 | System.out.print(result[i][j]+"\t"); 23 | } 24 | System.out.println(); 25 | } 26 | } 27 | } 28 | 29 | /* 30 | 31 | Output: 32 | Add two matrix...! 33 | 4 4 4 34 | 6 6 6 35 | 8 8 8 36 | 37 | */ -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q21_BinarySearch_algorithm.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @Program: 21 3 | * Write a java program to implement binary search algorithm. 4 | * 5 | */ 6 | 7 | public class Q21_BinarySearch_algorithm { 8 | public static int binarySearch(int arr[], int key, int st, int ed){ 9 | if (st > ed) { 10 | return -1; 11 | } 12 | 13 | int mid = st + (ed - st) / 2; 14 | 15 | if (arr[mid] == key) { 16 | return mid; 17 | } 18 | 19 | if (arr[mid] > key) { 20 | return binarySearch(arr, key, st, mid - 1); 21 | } else { 22 | return binarySearch(arr, key, mid + 1, ed); 23 | } 24 | } 25 | 26 | public static void main(String[] args) { 27 | int array[] ={2,4,5,6,7,8,9,10}; 28 | int key = 9; 29 | int index = binarySearch(array, key, 0, array.length - 1); 30 | 31 | if(index != -1){ 32 | System.out.println("Element "+ key + " is at " + index + " position"); 33 | } else { 34 | System.out.println("Element "+ key + " is not found!"); 35 | } 36 | } 37 | } 38 | /* 39 | * Output: 40 | * Element 9 is at 6 position 41 | */ -------------------------------------------------------------------------------- /OOps/InterFaces.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Interfaces 3 | * -> All methods are public, abstract & without implementation 4 | * -> Used to achieve total abstraction 5 | * -> Variables in the interface are final, public and static 6 | * 7 | */ 8 | 9 | public class InterFaces { 10 | public static void main(String[] args) { 11 | Queen q = new Queen(); 12 | q.moves(); 13 | } 14 | } 15 | 16 | interface ChessPlayer{ 17 | void moves(); 18 | } 19 | 20 | class Queen implements ChessPlayer { 21 | public void moves () { 22 | System.out.println("up , down , left , right , diagonal ( in all 4 dirns )"); 23 | } 24 | } 25 | 26 | 27 | class Rook implements ChessPlayer { 28 | public void moves () { 29 | System.out.println("up , down , left , right"); 30 | } 31 | } 32 | 33 | 34 | class King implements ChessPlayer { 35 | public void moves () { 36 | System.out.println("up , down , left , right , diagonal -( by 1 step )"); 37 | } 38 | } 39 | interface Herbivore{ 40 | 41 | } 42 | 43 | interface Carnivore { 44 | 45 | } 46 | 47 | class Bear implements Herbivore, Carnivore{ 48 | 49 | } 50 | 51 | /* 52 | * Output 53 | * up , down , left , right , diagonal ( in all 4 dirns ) 54 | */ -------------------------------------------------------------------------------- /OOps/AbstractClass.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Abstract class 3 | * -> Cannot create create an instance of abstract class 4 | * -> Can have abstract/non-abstract methods 5 | * -> Can have constructors 6 | */ 7 | 8 | public class AbstractClass { 9 | public static void main(String[] args) { 10 | Horse h1 = new Horse(); 11 | h1.eat(); 12 | h1.walk(); 13 | Chicken c1 = new Chicken(); 14 | c1.eat(); 15 | c1.walk(); 16 | System.out.println(h1.color); 17 | } 18 | } 19 | 20 | abstract class IsAnimal { 21 | String color; 22 | IsAnimal(){ 23 | color = "brown"; 24 | } 25 | void eat(){ 26 | System.out.println("animal eats"); 27 | } 28 | abstract void walk(); 29 | } 30 | 31 | class Horse extends IsAnimal{ 32 | void changeColor(){ 33 | color="dark brown"; 34 | } 35 | void walk (){ 36 | System.out.println("Walks on 4 legs"); 37 | } 38 | } 39 | 40 | class Chicken extends IsAnimal { 41 | void walk(){ 42 | System.out.println("Walks on 2 legs"); 43 | } 44 | } 45 | 46 | /* 47 | * Output 48 | * animal eats 49 | * Walks on 4 legs 50 | * animal eats 51 | * Walks on 2 legs 52 | * brown 53 | */ -------------------------------------------------------------------------------- /BinaryTrees/BuildBinaryTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Build Binary Tree 3 | */ 4 | 5 | public class BuildBinaryTree { 6 | static class Node { 7 | int data; 8 | Node left; 9 | Node right; 10 | 11 | Node(int data) { 12 | this.data = data; 13 | this.left = null; 14 | this.right = null; 15 | } 16 | } 17 | 18 | static class BinaryTree { 19 | static int idx = -1; 20 | 21 | public Node buildTree(int nodes[]) { 22 | idx++; 23 | if (nodes[idx] == -1) { 24 | return null; 25 | } 26 | Node newNode = new Node(nodes[idx]); 27 | newNode.left = buildTree(nodes); 28 | newNode.right = buildTree(nodes); 29 | return newNode; 30 | } 31 | } 32 | 33 | public static void main(String[] args) { 34 | int nodes[] = { 1, 2, 4, -1, -1, 5, -1, -1, 3, -1, 6, -1, -1 }; 35 | BinaryTree tree = new BinaryTree(); 36 | Node root = tree.buildTree(nodes); 37 | System.out.println(root.data); // 1 38 | System.out.println(root.left.data); // 2 39 | System.out.println(root.right.data); // 3 40 | 41 | } 42 | } 43 | 44 | /* 45 | * Output: 46 | * 1 47 | * 2 48 | * 3 49 | */ -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q24_Sorting_given_List_names.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @Program: 24 3 | * Write a java program for sorting a given list of names in ascending order. 4 | */ 5 | 6 | public class Q24_Sorting_given_List_names { 7 | public static void sort(String[] list){ 8 | for (int i = 0; i < list.length; i++) { 9 | int min = i; 10 | int j = list.length - 1; 11 | while (j > i) { 12 | if (list[min].compareTo(list[j])>0) { 13 | min = j; 14 | } 15 | j--; 16 | } 17 | String temp = list[min]; 18 | list[min] = list[i]; 19 | list[i] = temp; 20 | } 21 | } 22 | 23 | public static void main(String[] args) { 24 | String[] nameList = {"Raj kishor", "Manmeet", "Ram", "Palak", "Sonali", "Kajal", 25 | "Amaresh", "Yovraj", "Annu Priya"}; 26 | sort(nameList); 27 | for (int i = 0; i < nameList.length; i++) { 28 | System.out.println(nameList[i]); 29 | } 30 | } 31 | } 32 | 33 | /* 34 | 35 | Output: 36 | Amaresh 37 | Annu Priya 38 | Kajal 39 | Manmeet 40 | Palak 41 | Raj kishor 42 | Ram 43 | Sonali 44 | Yovraj 45 | 46 | */ -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q35_connection_bw_JDBC.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Program: 35 3 | * Write a program to establish the connection between Java program to database. 4 | */ 5 | 6 | import java.sql.Connection; 7 | import java.sql.DriverManager; 8 | import java.sql.SQLException; 9 | 10 | public class Q35_connection_bw_JDBC { 11 | 12 | public static void main(String[] args) { 13 | String url = "jdbc:mysql://localhost:3306/rajdb"; 14 | String user = "root"; 15 | String usPassword = "raj@2002"; 16 | try { 17 | Class.forName("com.mysql.cj.jdbc.Driver"); 18 | Connection connection = DriverManager.getConnection(url, user, usPassword); 19 | if (connection != null) { 20 | System.out.println("Connected to the database!"); 21 | connection.close(); 22 | } 23 | } catch (ClassNotFoundException e) { 24 | System.err.println("MySQL JDBC Driver not found!"); 25 | e.printStackTrace(); 26 | } catch (SQLException e) { 27 | System.err.println("Error connecting to the database!"); 28 | e.printStackTrace(); 29 | } 30 | } 31 | } 32 | 33 | /* 34 | * Output: 35 | * Connected to the database! 36 | */ -------------------------------------------------------------------------------- /ArrayLists/ContainerWithMostWaterVVI.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Container with Most Water 3 | * -> For given n lines on x-axis, use 2 lines to form a container such that it holds 4 | * maximum water. 5 | * height= [1,8,6,2,5,4,8,3,7] 6 | */ 7 | 8 | import java.util.ArrayList; 9 | 10 | public class ContainerWithMostWaterVVI { 11 | public static int storeWater(ArrayList height) { 12 | int maxWater = 0; 13 | for(int i=0; i height= new ArrayList<>(); 27 | height.add(1); 28 | height.add(8); 29 | height.add(6); 30 | height.add(2); 31 | height.add(5); 32 | height.add(4); 33 | height.add(8); 34 | height.add(3); 35 | height.add(7); 36 | System.out.println(storeWater(height)); 37 | } 38 | } 39 | 40 | /* 41 | * Output 42 | * 49 43 | */ -------------------------------------------------------------------------------- /Stacks/StockSpanProblem.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Stock Span problem 3 | * (Span => max no of consecutive days for which ) 4 | * [price <= today's psice] 5 | * 6 | */ 7 | 8 | import java.util.Stack; 9 | 10 | public class StockSpanProblem { 11 | 12 | public static void stockSpan(int stocks[], int span[]) { 13 | Stack s = new Stack<>(); 14 | span[0] = 1; 15 | s.push(0); 16 | for (int i = 1; i < stocks.length; i++) { 17 | int currPrice = stocks[i]; 18 | while (!s.isEmpty() && currPrice >= stocks[s.peek()]) { 19 | s.pop(); 20 | } 21 | if (s.isEmpty()) { 22 | span[i] = i + 1; 23 | } else { 24 | int prevHigh = s.peek(); 25 | span[i] = i - prevHigh; 26 | } 27 | s.push(i); 28 | } 29 | } 30 | 31 | public static void main(String[] args) { 32 | int stock[] = { 100, 80, 60, 70, 60, 85, 100 }; 33 | int span[] = new int[stock.length]; 34 | stockSpan(stock, span); 35 | for (int i = 0; i < span.length; i++) { 36 | System.out.print(span[i] + " "); 37 | } 38 | System.out.println(); 39 | } 40 | 41 | } 42 | 43 | /* 44 | * Output: 45 | * 1 1 1 2 1 5 7 46 | */ -------------------------------------------------------------------------------- /BinaryTrees/LowestCommonAncestor_Approach2.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Lowest Common Ancestor 3 | */ 4 | 5 | public class LowestCommonAncestor_Approach2 { 6 | 7 | static class Node { 8 | int data; 9 | Node left; 10 | Node right; 11 | 12 | Node(int data) { 13 | this.data = data; 14 | this.left = null; 15 | this.right = null; 16 | } 17 | } 18 | 19 | public static Node lca(Node root, int n1, int n2) { 20 | if (root == null || root.data == n1 || root.data == n2) { 21 | return root; 22 | } 23 | Node laftLca = lca(root.left, n1, n2); 24 | Node rightLca = lca(root.right, n1, n2); 25 | if (laftLca == null) { 26 | return rightLca; 27 | } 28 | if (rightLca == null) { 29 | return laftLca; 30 | } 31 | return root; 32 | } 33 | 34 | public static void main(String[] args) { 35 | Node root = new Node(1); 36 | root.left = new Node(2); 37 | root.right = new Node(3); 38 | root.left.left = new Node(4); 39 | root.left.right = new Node(5); 40 | root.right.right = new Node(6); 41 | 42 | int n1 = 4, n2 = 5; 43 | 44 | System.out.println(lca(root, n1, n2).data); // 2 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Recursion/QuickSort.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Quick Sort 3 | */ 4 | 5 | public class QuickSort { 6 | 7 | public static void quickSort(int arr[], int si , int ei) { 8 | if(si>=ei){ 9 | return; 10 | } 11 | // last element 12 | int pIdx = partition(arr,si,ei); 13 | quickSort(arr, si, pIdx-1); // left 14 | quickSort(arr, pIdx+1, ei); // right 15 | } 16 | 17 | public static int partition(int arr[], int si , int ei){ 18 | int pivot = arr[ei]; 19 | int i= si-1; // to make place for els smaller than pivot 20 | 21 | for(int j=si; j ei) { 20 | return null; 21 | } 22 | int mid = si + (ei - si) / 2; 23 | Node root = new Node(arr[mid]); 24 | root.left = buildBalancedBST(arr, si, mid - 1); 25 | root.right = buildBalancedBST(arr, mid + 1, ei); 26 | return root; 27 | } 28 | 29 | public static void inOrder(Node root) { 30 | if (root == null) { 31 | return; 32 | } 33 | inOrder(root.left); 34 | System.out.print(root.data + " "); 35 | inOrder(root.right); 36 | } 37 | 38 | public static void main(String[] args) { 39 | int arr[] = { 3, 5, 6, 8, 10, 11, 12 }; 40 | Node root = buildBalancedBST(arr, 0, arr.length - 1); 41 | inOrder(root); 42 | } 43 | } 44 | 45 | /* 46 | * Output: 47 | * 3 5 6 8 10 11 12 48 | */ -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q22_displays_area_of_different_figures_using_the_method_overloading.java: -------------------------------------------------------------------------------- 1 | /* 2 | @Program: 22 3 | Write a java program that displays area of different figures 4 | (Square,Rectangle,Circle) using the method overloading. 5 | */ 6 | 7 | public class Q22_displays_area_of_different_figures_using_the_method_overloading { 8 | //area of square (width)^2 9 | public static Double area(Double width){ 10 | return Math.pow(width, 2); 11 | } 12 | //area of rectangle = length * width; 13 | public static Double area(Double length, Double width){ 14 | return length*width; 15 | } 16 | //area of circle = pi*r^2 17 | public static Double area(Double radius, float pi){ 18 | return pi*Math.pow(radius, 2); 19 | } 20 | 21 | public static void main(String[] args) { 22 | final Double pi=3.14159265; 23 | Double width = 10.5; 24 | Double length = 5.5; 25 | System.out.println("Area of square: "+ area(width)); 26 | System.out.println("Area of rectangle: "+ area(length,width)); 27 | System.out.println("Area of circle: "+ area(width,pi)); 28 | } 29 | } 30 | 31 | /* 32 | 33 | Output: 34 | Area of square: 110.25 35 | Area of rectangle: 57.75 36 | Area of circle: 32.986722825 37 | 38 | */ -------------------------------------------------------------------------------- /ArrayLists/PairSum_1.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Pair Sum -1 3 | * Find if any pair in a Sorted ArrayList has a target sum. 4 | * list = [1, 2, 3, 4, 5, 6], target =5 5 | * 6 | * --> BRUTE FORCE --[O(n^2)]> all possible pairs 7 | */ 8 | 9 | import java.util.ArrayList; 10 | 11 | public class PairSum_1 { 12 | 13 | public static boolean pairSum(ArrayList list , int target){ 14 | for(int i=0; i list = new ArrayList<>(); 26 | list.add(1); 27 | list.add(2); 28 | list.add(3); 29 | list.add(4); 30 | list.add(5); 31 | list.add(6); 32 | int target = 5; 33 | if(pairSum(list,target)){ 34 | System.out.println("Yes, target pair sum present in Array list"); 35 | }else{ 36 | System.out.println("No!, target pair sum not present in array list"); 37 | } 38 | } 39 | 40 | } 41 | 42 | /* 43 | * Output: 44 | * Yes, target pair sum present in Array list 45 | */ -------------------------------------------------------------------------------- /LinkedList/LinkedList.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Linked List 3 | * 4 | * [1] --> [2] --> [3] --> [4] 5 | * 6 | * `/> _Node _ _Node _ _Node _ _Node _ 7 | * | data | | data | | data | | data | 8 | * |-------| |-------| |-------| |-------| 9 | * |_next _| -----> |_next _|---> |_next _| ----> |_next _| -----> NULL 10 | * 1 2 3 4 11 | */ 12 | 13 | 14 | public class LinkedList { 15 | 16 | public static class Node { 17 | int data; 18 | Node next; 19 | 20 | Node(int data){ 21 | this.data = data; 22 | this.next = null; 23 | } 24 | } 25 | public static Node head; 26 | public static Node tail; 27 | 28 | // add -> first, last 29 | public void addFist(int data) { 30 | 31 | // step1: create new node 32 | Node newNode = new Node(data); 33 | 34 | if (head == null) { 35 | head = tail = newNode; 36 | return; 37 | } 38 | 39 | // step2: newNode next = head 40 | newNode.next = head; //link 41 | 42 | } 43 | 44 | 45 | public static void main(String[] args) { 46 | LinkedList list = new LinkedList(); 47 | list.addFist(1); 48 | list.addFist(2); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /BinaryTrees/HeightOfTree.java: -------------------------------------------------------------------------------- 1 | public class HeightOfTree { 2 | static class Node { 3 | int data; 4 | Node left; 5 | Node right; 6 | 7 | Node(int data) { 8 | this.data = data; 9 | this.left = null; 10 | this.right = null; 11 | } 12 | } 13 | 14 | public static int height(Node root) { 15 | if (root == null) { 16 | return 0; 17 | } 18 | int lh = height(root.left); 19 | int rh = height(root.right); 20 | return Math.max(lh, rh) + 1; 21 | } 22 | 23 | public static void main(String[] args) { 24 | 25 | // 1 26 | // / \ 27 | // 2 3 28 | // / \ / \ 29 | // 4 5 6 7 30 | 31 | Node root = new Node(1); 32 | root.left = new Node(2); 33 | root.right = new Node(3); 34 | root.left.left = new Node(4); 35 | root.left.right = new Node(5); 36 | root.right = new Node(3); 37 | root.right.left = new Node(6); 38 | root.right.right = new Node(7); 39 | 40 | System.out.println("Height of tree : " + height(root)); // Height of tree : 3 41 | 42 | root.right.right.right = new Node(10); 43 | root.right.right.right.right = new Node(10); 44 | 45 | System.out.println("Height of tree : " + height(root)); // Height of tree : 5 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /GreedyAlgorithms/IndianCoins.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @Indian Coins 3 | * -> We are given an infinite supply of denominations [1, 2, 5, 10, 20, 50, 100, 500, 2000]. 4 | * Find min no. of coins/notes to make change for a value V. 5 | * 6 | * V = 121 7 | * ans = 3 (100+20+1) 8 | * 9 | * V= 590 10 | * ans = 4 (500 + 50 + 20 + 20) 11 | */ 12 | 13 | import java.util.*; 14 | 15 | public class IndianCoins { 16 | 17 | public static void main(String[] args) { 18 | Integer coins[] = { 1, 2, 5, 10, 20, 50, 100, 500, 2000 }; 19 | int amount = 590; 20 | Arrays.sort(coins, Comparator.reverseOrder()); 21 | ArrayList ans = new ArrayList<>(); 22 | int countOfCoins = 0; 23 | for (int i = 0; i < coins.length; i++) { 24 | if (coins[i] <= amount) { 25 | while (coins[i] <= amount) { 26 | countOfCoins++; 27 | ans.add(coins[i]); 28 | amount -= coins[i]; 29 | } 30 | } 31 | } 32 | System.out.print("total (min) coins using: " + countOfCoins + " ( "); 33 | for (int i = 0; i < ans.size(); i++) { 34 | System.out.print(ans.get(i) + " "); 35 | } 36 | System.out.println(")"); 37 | } 38 | } 39 | /* 40 | * Output: 41 | * total (min) coins using: 4 ( 500 50 20 20 ) 42 | */ 43 | -------------------------------------------------------------------------------- /BinaryTrees/CountOfNodes.java: -------------------------------------------------------------------------------- 1 | public class CountOfNodes { 2 | static class Node { 3 | int data; 4 | Node left; 5 | Node right; 6 | 7 | Node(int data) { 8 | this.data = data; 9 | this.left = null; 10 | this.right = null; 11 | } 12 | } 13 | 14 | public static int countNodes(Node root) { 15 | if (root == null) { 16 | return 0; 17 | } 18 | int ln = countNodes(root.left); 19 | int rn = countNodes(root.right); 20 | return (ln + rn) + 1; 21 | } 22 | 23 | public static void main(String[] args) { 24 | 25 | // 1 26 | // / \ 27 | // 2 3 28 | // / \ / \ 29 | // 4 5 6 7 30 | 31 | Node root = new Node(1); 32 | root.left = new Node(2); 33 | root.right = new Node(3); 34 | root.left.left = new Node(4); 35 | root.left.right = new Node(5); 36 | root.right.left = new Node(6); 37 | root.right.right = new Node(7); 38 | 39 | System.out.println("total Nodes of tree : " + countNodes(root)); // total Nodes of tree : 7 40 | 41 | root.right.right.right = new Node(9); 42 | root.right.right.right.right = new Node(10); 43 | 44 | System.out.println("total Nodes of tree : " + countNodes(root)); // total Nodes of tree : 9 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Hashing/HashMapOperations.java: -------------------------------------------------------------------------------- 1 | /* 2 | * HashMap Operation 3 | */ 4 | 5 | import java.util.HashMap; 6 | 7 | public class HashMapOperations { 8 | public static void main(String[] args) { 9 | // create 10 | HashMap hm = new HashMap<>(); 11 | 12 | // Insert - 0(1) 13 | hm.put("India", 100); 14 | hm.put("Chaina", 150); 15 | hm.put("US", 95); 16 | 17 | System.out.println(hm); 18 | hm.put("India", 120); 19 | System.out.println(hm); 20 | 21 | // Get - O(1) 22 | int population = hm.get("India"); 23 | System.out.println(population); 24 | System.out.println(hm.get("Indonesia")); 25 | 26 | // ContainsKey -O(1) 27 | System.out.println(hm.containsKey("India")); 28 | System.out.println(hm.containsKey("Indonesia")); 29 | 30 | // remove -O(1) 31 | hm.remove("Chaina"); 32 | System.out.println(hm); 33 | 34 | // size 35 | System.out.println(hm.size()); 36 | 37 | // clear 38 | hm.clear(); 39 | 40 | // is Empty 41 | System.out.println(hm.isEmpty()); 42 | } 43 | } 44 | 45 | /* 46 | * Output: 47 | * {Chaina=150, US=95, India=100} 48 | * {Chaina=150, US=95, India=120} 49 | * 120 50 | * null 51 | * true 52 | * false 53 | * {US=95, India=120} 54 | * 2 55 | * true 56 | */ -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q19_multiply_two_matrix.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Program: 19 3 | * Write a java program to multiply two matrix using multi-dimensional arrays. 4 | */ 5 | public class Q19_multiply_two_matrix { 6 | public static int[][] multiply(int matrix1[][],int matrix2[][]){ 7 | int result[][] = new int[matrix1.length][matrix2[0].length]; 8 | for (int i = 0; i using 2 pointer approach 4 | * height = [1, 8, 6, 2, 5, 4, 8, 3, 7] 5 | */ 6 | 7 | import java.util.ArrayList; 8 | 9 | public class ContainerWithMostWater_Using_Two_Pointer_VVI { 10 | 11 | public static int storeWater(ArrayList height) { 12 | int maxWater = 0; 13 | int lp = 0, rp = height.size() - 1; 14 | while (lp < rp) { 15 | // calculate water area 16 | int ht = Math.min(height.get(lp), height.get(rp)); 17 | int width = rp - lp; 18 | maxWater = Math.max(maxWater, ht * width); 19 | 20 | // update ptr 21 | if (lp < rp) { 22 | lp++; 23 | } else { 24 | rp--; 25 | } 26 | } 27 | return maxWater; 28 | } 29 | 30 | public static void main(String[] args) { 31 | ArrayList height = new ArrayList<>(); 32 | height.add(1); 33 | height.add(8); 34 | height.add(6); 35 | height.add(2); 36 | height.add(5); 37 | height.add(4); 38 | height.add(8); 39 | height.add(3); 40 | height.add(7); 41 | System.out.println("Most water: " + storeWater(height)); 42 | } 43 | } 44 | 45 | /* 46 | * Output: 47 | * Most water: 49 48 | */ -------------------------------------------------------------------------------- /SortingAlgorithms/InbuiltSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Collections;; 3 | 4 | public class InbuiltSort { 5 | 6 | public static void printArray(int array[]) { 7 | for (int i = 0; i < array.length; i++) { 8 | System.out.print(array[i] + " "); 9 | } 10 | System.out.println(); 11 | } 12 | 13 | public static void main(String[] args) { 14 | int array[] = { 1, 9, 8, 7, 5, 4, 3, 2, 0 }; 15 | 16 | /* 17 | * [ import java.util.Arrays; ] 18 | * Arrays.sort(array); // 0(n logn) < 0(n^2) 19 | * printArray(array); // 0 1 2 3 4 5 7 8 9 20 | */ 21 | 22 | Arrays.sort(array, 0, 5); 23 | printArray(array); // 1 5 7 8 9 4 3 2 0 24 | 25 | /* 26 | * Integer arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 27 | * Arrays.sort(arr, Collections.reverseOrder()); 28 | * for (int i = 0; i < arr.length; i++) { 29 | * System.out.print(arr[i] + " // 9 8 7 6 5 4 3 2 1 30 | * } 31 | */ 32 | 33 | Integer arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; 34 | Arrays.sort(arr, 0, 5, Collections.reverseOrder()); 35 | for (int i = 0; i < arr.length; i++) { 36 | System.out.print(arr[i] + " "); // 5 4 3 2 1 6 7 8 37 | } 38 | } 39 | } 40 | 41 | /* 42 | * Output: 43 | * 1 5 7 8 9 4 3 2 0 44 | * 5 4 3 2 1 6 7 8 45 | */ -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q32_file_copy_it_on_another_file.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Program: 32 3 | * Write a java program to read the data from the file and copy it on another file. 4 | */ 5 | 6 | import java.io.*; 7 | public class Q32_file_copy_it_on_another_file { 8 | public static void main(String[] args)throws IOException { 9 | FileReader fr = new FileReader("./myFavouriteSong.txt"); 10 | FileWriter fw = new FileWriter("./mydata.txt"); 11 | BufferedReader bf = new BufferedReader(fr); 12 | BufferedWriter bw = new BufferedWriter(fw); 13 | String str; 14 | while ((str = bf.readLine()) != null) { 15 | System.out.println(str); 16 | bw.write(str); 17 | bw.newLine(); 18 | } 19 | bf.close(); 20 | bw.close(); 21 | System.out.println("\nData successfully copied."); 22 | 23 | } 24 | } 25 | 26 | /* 27 | Output: 28 | Jaagi Hoon Na Soyi Hoon 29 | Khayalon Mein Tere Khoyi Hoon 30 | Jaagi Hoon Na Soyi Hoon 31 | Khayalon Mein Tere Khoyi Hoon 32 | 33 | Izhaar Hua Humein Bhi Pyar Hua 34 | Mulakaat Ki Hai Ghadi Ab 35 | Aayi Aayi Aayi Aayi 36 | 37 | Neend Mein Bhi 38 | Labon Pe Naam Tera 39 | Banke Main Rahun 40 | Teri Parchhai Aayi Aayi Aayi 41 | 42 | Tujhe Mere Liye 43 | Mujhe Tere Liye 44 | Hai Banaya Gaya 45 | Oh Harjai Aayi Aayi Aayi 46 | 47 | Data successfully copied. 48 | 49 | */ -------------------------------------------------------------------------------- /2D-Arrays/BestTimeToBuyAndSellStock.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Best Time to Buy & Sell Stock 3 | * 4 | * you are given an array price where prices[i] is the price of a given stock on the ith day. 5 | * you want to maximize your profit by choosing a single day to buy one stock and choosing a different 6 | * day in the future to sell that stock . return the maximum profit you can achieve from this transaction. 7 | * if you cannot achive any profit , return 0. 8 | * Prices = [7,1,5,3,6,4] 9 | * 10 | */ 11 | 12 | public class BestTimeToBuyAndSellStock { 13 | 14 | public static int profit(int price[]) { 15 | int buyPrice=Integer.MAX_VALUE; 16 | // int sellPrice=Integer.MIN_VALUE; 17 | int maxProfit=0; 18 | for(int i=0; i { 11 | int x; 12 | int y; 13 | int distSq; 14 | int index; 15 | 16 | public Point(int x, int y, int distSq, int index) { 17 | this.x = x; 18 | this.y = y; 19 | this.distSq = distSq; 20 | this.index = index; 21 | } 22 | 23 | @Override 24 | public int compareTo(Point p2) { 25 | return this.distSq - p2.distSq; 26 | } 27 | } 28 | 29 | public static void main(String[] args) { 30 | int pts[][] = { { 3, 3 }, { 5, -1 }, { -2, 4 } }; 31 | int k = 2; 32 | 33 | PriorityQueue pq = new PriorityQueue<>(); 34 | for (int i = 0; i < pts.length; i++) { 35 | int distSq = pts[i][0] * pts[i][0] + pts[i][1] * pts[i][1]; 36 | pq.add(new Point(pts[i][0], pts[i][1], distSq, i)); 37 | } 38 | 39 | for (int i = 0; i < pts.length; i++) { 40 | System.out.println("C" + pq.remove().index); 41 | } 42 | } 43 | } 44 | 45 | /* 46 | * Output: 47 | * C0 48 | * C2 49 | * C1 50 | */ -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q28_multiple_threads.java: -------------------------------------------------------------------------------- 1 | /* 2 | @Program: 28 3 | Write a java program to generate multiple threads using runnable interface. 4 | */ 5 | 6 | public class Q28_multiple_threads { 7 | 8 | public static void main(String[] args) { 9 | PlayVideo v = new PlayVideo(); 10 | Thread video = new Thread(v); 11 | video.start(); 12 | PlayMusic m = new PlayMusic(); 13 | Thread music = new Thread(m); 14 | music.start(); 15 | ProgressBar p = new ProgressBar(); 16 | Thread progressBar = new Thread(p); 17 | progressBar.start(); 18 | Timer t = new Timer(); 19 | Thread timer = new Thread(t); 20 | timer.start(); 21 | } 22 | } 23 | class PlayVideo implements Runnable{ 24 | public void run(){ 25 | System.out.println("Playing Video"); 26 | } 27 | } 28 | class PlayMusic implements Runnable{ 29 | public void run(){ 30 | System.out.println("Playing Music"); 31 | } 32 | } 33 | class ProgressBar implements Runnable{ 34 | public void run(){ 35 | System.out.println("Progress bar is executing"); 36 | } 37 | } 38 | class Timer implements Runnable{ 39 | public void run(){ 40 | System.out.println("timer is executing"); 41 | } 42 | } 43 | 44 | /* 45 | * Output: 46 | * Playing Video 47 | * Playing Music 48 | * Progress bar is executing 49 | * timer is executing 50 | */ -------------------------------------------------------------------------------- /Heaps/PQ_for_Objects.java: -------------------------------------------------------------------------------- 1 | import java.util.Comparator; 2 | import java.util.PriorityQueue; 3 | 4 | public class PQ_for_Objects { 5 | 6 | static class Student implements Comparable { 7 | String name; 8 | int rank; 9 | 10 | Student(String name, int rank) { 11 | this.name = name; 12 | this.rank = rank; 13 | } 14 | 15 | @Override 16 | public int compareTo(Student s2) { 17 | return this.rank - s2.rank; 18 | } 19 | } 20 | 21 | public static void main(String[] args) { 22 | // PriorityQueue pq = new PriorityQueue<>(); 23 | PriorityQueue pq = new PriorityQueue<>(Comparator.reverseOrder()); 24 | 25 | pq.add(new Student("raj", 20)); 26 | pq.add(new Student("Amarjeet", 30)); 27 | pq.add(new Student("amress", 15)); 28 | pq.add(new Student("RajKishoe", 5)); 29 | pq.add(new Student("rohan", 6)); 30 | pq.add(new Student("Aman", 10)); 31 | 32 | while (!pq.isEmpty()) { 33 | System.out.println(pq.peek().name + ": " + pq.peek().rank); 34 | pq.remove(); 35 | } 36 | } 37 | } 38 | 39 | /* 40 | * Output: 41 | * 42 | * // * RajKishoe: 5 43 | * // * rohan: 6 44 | * // * Aman: 10 45 | * // * amress: 15 46 | * // * raj: 20 47 | * // * Amarjeet: 30 48 | * 49 | * Amarjeet: 30 50 | * raj: 20 51 | * amress: 15 52 | * Aman: 10 53 | * rohan: 6 54 | * RajKishoe: 5 55 | */ -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Q26_uses_of_super_keyword.java: -------------------------------------------------------------------------------- 1 | /* 2 | @Program: 26 3 | Write a java program to illustrate all uses of super keyword. 4 | 5 | */ 6 | 7 | public class Q26_uses_of_super_keyword { 8 | public static void main(String[] args) { 9 | Child son = new Child("Table","Window","Plants"); 10 | son.childProperty(); 11 | son.fatherProperty(); 12 | son.grandFatherProperty(); 13 | } 14 | } 15 | 16 | class GrandFather{ 17 | protected String property; 18 | 19 | GrandFather(String grFatProperty){ 20 | this.property = grFatProperty; 21 | } 22 | } 23 | 24 | class Father extends GrandFather{ 25 | protected String property; 26 | 27 | Father(String fatProperty, String grFatProperty){ 28 | super(grFatProperty); 29 | this.property = fatProperty; 30 | } 31 | 32 | public void grandFatherProperty(){ 33 | System.out.println(super.property); 34 | } 35 | } 36 | 37 | class Child extends Father{ 38 | private String property; 39 | Child(String childProperty, String fatProperty, String grFatProperty ){ 40 | super(fatProperty,grFatProperty); 41 | this.property = childProperty; 42 | } 43 | public void childProperty(){ 44 | System.out.println(this.property); 45 | } 46 | public void fatherProperty(){ 47 | System.out.println(super.property); 48 | } 49 | } 50 | 51 | /* 52 | 53 | Output: 54 | Table 55 | Window 56 | Plants 57 | */ -------------------------------------------------------------------------------- /Lab_Program_List_sem_v_BCA/Student.java: -------------------------------------------------------------------------------- 1 | // BCA package 2 | package BCA; 3 | 4 | // Student class in the BCA package 5 | public class Student { 6 | private String name; 7 | private int rollNumber; 8 | private int DBMS; 9 | private int java; 10 | private int computerNetworks; 11 | private int numericalMethod; 12 | 13 | // Parameterized constructor to accept student details 14 | public Student(String name, int rollNumber, int DBMS, int java, int computerNetworks, int numericalMethod) { 15 | this.name = name; 16 | this.rollNumber = rollNumber; 17 | this.DBMS = DBMS; 18 | this.java = java; 19 | this.computerNetworks = computerNetworks; 20 | this.numericalMethod = numericalMethod; 21 | } 22 | 23 | // Display method to display student details 24 | public void display() { 25 | System.out.println("Student Details:"); 26 | System.out.println("Name: " + name); 27 | System.out.println("Roll Number: " + rollNumber); 28 | System.out.println("DBMS: " + DBMS); 29 | System.out.println("java: " + java); 30 | System.out.println("computerNetworks: " + computerNetworks); 31 | System.out.println("numericalMethod: "+ numericalMethod); 32 | } 33 | 34 | public int getTotalMarks() { 35 | return DBMS + java + computerNetworks + numericalMethod; 36 | } 37 | 38 | public double getPercentage() { 39 | return (getTotalMarks() / 4.0); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /BinaryTrees/KthAncestorOfNode.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Kth Ancestor Of Node 3 | */ 4 | public class KthAncestorOfNode { 5 | 6 | static class Node { 7 | int data; 8 | Node left; 9 | Node right; 10 | 11 | Node(int data) { 12 | this.data = data; 13 | this.left = null; 14 | this.right = null; 15 | } 16 | } 17 | 18 | public static int kAncestor(Node root, int data, int k) { 19 | if (root == null) { 20 | return -1; 21 | } 22 | if (root.data == data) { 23 | return 0; 24 | } 25 | int leftDist = kAncestor(root.left, data, k); 26 | int rightDist = kAncestor(root.right, data, k); 27 | 28 | if (leftDist == -1 && rightDist == -1) { 29 | return -1; 30 | } 31 | int max = Math.max(leftDist, rightDist); 32 | if (max + 1 == k) { 33 | System.out.println(root.data); 34 | } 35 | return max + 1; 36 | } 37 | 38 | public static void main(String[] args) { 39 | 40 | Node root = new Node(1); 41 | root.left = new Node(2); 42 | root.right = new Node(3); 43 | root.left.left = new Node(4); 44 | root.left.right = new Node(5); 45 | root.right.left = new Node(6); 46 | root.right.right = new Node(7); 47 | 48 | int data = 4; 49 | int k = 2; 50 | kAncestor(root, data, k); 51 | } 52 | } 53 | 54 | /* 55 | * Output: 56 | * 1 57 | */ -------------------------------------------------------------------------------- /OOps/Inheritance.java: -------------------------------------------------------------------------------- 1 | /* 2 | * * Tnheritance 3 | * -> Inheritance is when properties & methods of base class are passed on to a derived class. 4 | * 5 | * Types of Inheritance 6 | * -> Single Level Inheritance [Base Class] --> [Derived Class] 7 | * -> Multi Level Inheritance [Base Class] --> [Derived Class] --> [Derived Class] 8 | * -> Hierarchial Inheritance [Base class] --> [Derived class] 1 9 | * `--> [Derived class] 2... 10 | * 11 | */ 12 | 13 | public class Inheritance { 14 | public static void main(String[] args) { 15 | // Fish shark = new Fish(); 16 | // shark.eat(); 17 | Dog dobby = new Dog(); 18 | dobby.eat(); 19 | dobby.legs=4; 20 | System.out.println(dobby.legs); 21 | } 22 | } 23 | 24 | //Base class 25 | class Animal { 26 | String color; 27 | void eat() { 28 | System.out.println("eats"); 29 | } 30 | 31 | void breathe(){ 32 | System.out.println("breathes"); 33 | } 34 | } 35 | 36 | //Derived Class 37 | class Fish extends Animal { 38 | int fins; 39 | void swim(){ 40 | System.out.println("swims in water"); 41 | } 42 | } 43 | 44 | //Derived Class 45 | class Mammal extends Animal { 46 | int legs; 47 | } 48 | 49 | //Derived Class 50 | class Dog extends Mammal { 51 | String breed; 52 | } 53 | 54 | /* 55 | * Output: 56 | * eats 57 | * 4 58 | */ -------------------------------------------------------------------------------- /BinaryTrees/TransformToSumTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Transform to Sum tree 3 | */ 4 | public class TransformToSumTree { 5 | 6 | static class Node { 7 | int data; 8 | Node left; 9 | Node right; 10 | 11 | Node(int data) { 12 | this.data = data; 13 | this.left = null; 14 | this.right = null; 15 | } 16 | 17 | } 18 | 19 | public static int transFormSumTree(Node root) { 20 | 21 | if (root == null) { 22 | return 0; 23 | } 24 | int leftSum = transFormSumTree(root.left); 25 | int rightSum = transFormSumTree(root.right); 26 | int rootData = root.data; 27 | root.data = leftSum + rightSum; 28 | return rootData + leftSum + rightSum; 29 | } 30 | 31 | public static void printTree(Node root) { 32 | if (root == null) { 33 | return; 34 | } else { 35 | System.out.print(root.data + " "); 36 | } 37 | printTree(root.left); 38 | printTree(root.right); 39 | } 40 | 41 | public static void main(String[] args) { 42 | Node root = new Node(1); 43 | root.left = new Node(2); 44 | root.right = new Node(3); 45 | root.left.left = new Node(4); 46 | root.left.right = new Node(5); 47 | root.right.left = new Node(6); 48 | root.right.right = new Node(7); 49 | 50 | transFormSumTree(root); 51 | printTree(root); 52 | } 53 | } 54 | 55 | /* 56 | * 27 9 0 0 13 0 0 57 | */ -------------------------------------------------------------------------------- /Patterns/butterflyPattern.java: -------------------------------------------------------------------------------- 1 | /* 2 | * BUTTERFLY pattern 3 | * 4 | * * * 5 | * ** ** 6 | * *** *** 7 | * ******** 8 | * ******** 9 | * *** *** 10 | * ** ** 11 | * * * 12 | */ 13 | 14 | 15 | public class butterflyPattern { 16 | public static void main(String[] args) { 17 | short n = 4; 18 | for (short i = 1; i <= n; i++) { 19 | for (short j = 1; j <= i; j++) { 20 | System.out.print("*"); 21 | } 22 | for (short j = 1; j <= 2 * (n - i); j++) { 23 | System.out.print(" "); 24 | } 25 | for (short j = 1; j <= i; j++) { 26 | System.out.print("*"); 27 | } 28 | System.out.println(); 29 | } 30 | for (short i = n; i >= 1; i--) { 31 | for (short j = 1; j <= i; j++) { 32 | System.out.print("*"); 33 | } 34 | for (short j = 1; j <= 2 * (n - i); j++) { 35 | System.out.print(" "); 36 | } 37 | for (short j = 1; j <= i; j++) { 38 | System.out.print("*"); 39 | } 40 | System.out.println(); 41 | } 42 | } 43 | } 44 | 45 | 46 | /* 47 | Output: 48 | 49 | * * 50 | ** ** 51 | *** *** 52 | ******** 53 | ******** 54 | *** *** 55 | ** ** 56 | * * 57 | 58 | */ -------------------------------------------------------------------------------- /ArrayLists/PairSum_Target_2_PointerApproach.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Pair Sum -1 3 | * Find if any pair in a Sorted ArrayList has a target sum. 4 | * list = [1, 2, 3, 4, 5, 6], target =5 5 | * 6 | * --> BRUTE FORCE --[O(n^2)]> all possible pairs 7 | */ 8 | 9 | import java.util.ArrayList; 10 | 11 | public class PairSum_Target_2_PointerApproach { 12 | 13 | public static boolean pairSum(ArrayList list , int target){ 14 | int lp=0, rp=list.size()-1; 15 | while(lp target){ 23 | rp--; 24 | } 25 | } 26 | return false; 27 | } 28 | 29 | public static void main(String[] args) { 30 | ArrayList list = new ArrayList<>(); 31 | list.add(1); 32 | list.add(2); 33 | list.add(3); 34 | list.add(4); 35 | list.add(5); 36 | list.add(6); 37 | int target = 5; 38 | if(pairSum(list,target)){ 39 | System.out.println("Yes, target pair sum present in Array list"); 40 | }else{ 41 | System.out.println("No!, target pair sum not present in array list"); 42 | } 43 | } 44 | 45 | } 46 | 47 | 48 | /* 49 | * Output: 50 | * Yes, target pair sum present in Array list 51 | */ -------------------------------------------------------------------------------- /Hashing/Find_ItineraryForTickets.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Find Itinerary from Tickets 3 | * 4 | * "Chennai" -> "Bengaluru" 5 | * "Mumbai" -> "Delhi" 6 | * "Goa" -> "Chennai" 7 | * "Delhi" -> "Goa" 8 | * 9 | * "Mumbai" -> "Delhi" -> "Goa" -> "Chennai" -> "Benagluru" 10 | */ 11 | 12 | import java.util.HashMap; 13 | 14 | public class Find_ItineraryForTickets { 15 | 16 | public static String getStart(HashMap tickets) { 17 | HashMap revMap = new HashMap<>(); 18 | 19 | for (String key : tickets.keySet()) { 20 | revMap.put(tickets.get(key), key); 21 | } 22 | 23 | for (String key : tickets.keySet()) { 24 | if (!revMap.containsKey(key)) { 25 | return key; 26 | } 27 | } 28 | return null; 29 | } 30 | 31 | public static void main(String[] args) { 32 | HashMap tickets = new HashMap<>(); 33 | tickets.put("Chennai", "Bengaluru"); 34 | tickets.put("Mumbai", "Delhi"); 35 | tickets.put("Goa", "Chennai"); 36 | tickets.put("Delhi", "Goa"); 37 | 38 | String start = getStart(tickets); 39 | System.out.print(start); 40 | for (String key : tickets.keySet()) { 41 | System.out.print(" -> " + tickets.get(start)); 42 | start = tickets.get(start); 43 | } 44 | System.out.println(); 45 | } 46 | } 47 | 48 | /* 49 | * Output: 50 | * Mumbai -> Delhi -> Goa -> Chennai -> Bengaluru 51 | */ -------------------------------------------------------------------------------- /OOps/CopyConstructors.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Create Copy Constructors 3 | */ 4 | 5 | public class CopyConstructors { 6 | public static void main(String[] args) { 7 | Student s1 = new Student(); 8 | s1.name="RajKishor"; 9 | s1.roll= 1302; 10 | s1.marks[0]=80; 11 | s1.marks[1]=90; 12 | s1.marks[2]=70; 13 | s1.college="MIT"; 14 | Student s2 = new Student(s1); 15 | s1.marks[1]=100; 16 | for (int i = 0; i < 3; i++) { 17 | System.out.println(s2.marks[i]); 18 | } 19 | s1.name="raja"; 20 | s1.roll=6095; 21 | 22 | System.out.println(s1.name); 23 | System.out.println(s2.roll); 24 | 25 | } 26 | } 27 | 28 | 29 | /** 30 | * Student 31 | */ 32 | 33 | class Student { 34 | int roll; 35 | String name; 36 | String college; 37 | int marks[] = new int[3]; 38 | Student(){} 39 | /* 40 | // Shallow Copy constructor 41 | Student(Student s1){ 42 | this.marks= s1.marks; 43 | this.roll = s1.roll; 44 | this.name = s1.name; 45 | this.college= s1.college; 46 | } 47 | */ 48 | // deep cpoy constructor 49 | Student(Student s1){ 50 | this.roll = s1.roll; 51 | this.name = s1.name; 52 | this.college= s1.college; 53 | for (int i = 0; i < 3; i++) { 54 | this.marks[i]= s1.marks[i]; 55 | } 56 | } 57 | } 58 | 59 | /* 60 | * Output 61 | * 80 62 | * 90 63 | * 70 64 | * raja 65 | * 1302 66 | * 67 | */ -------------------------------------------------------------------------------- /BinarySearchTree/Build_a_BST.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Build a Binary Search Tree 3 | * [to Remember: BST makes search efficient] 4 | */ 5 | 6 | public class Build_a_BST { 7 | static class Node { 8 | int data; 9 | Node left; 10 | Node right; 11 | 12 | Node(int data) { 13 | this.data = data; 14 | this.left = null; 15 | this.right = null; 16 | } 17 | } 18 | 19 | public static Node buildBST(Node root, int value) { 20 | if (root == null) { 21 | root = new Node(value); 22 | return root; 23 | } 24 | if (root.data > value) { 25 | // left Subtree Search 26 | root.left = buildBST(root.left, value); 27 | } else { 28 | // right Subtree Search 29 | root.right = buildBST(root.right, value); 30 | } 31 | return root; 32 | } 33 | 34 | // inorder treversing 35 | public static void printTree(Node root) { 36 | if (root == null) { 37 | return; 38 | } 39 | printTree(root.left); 40 | System.out.print(root.data + " "); 41 | printTree(root.right); 42 | } 43 | 44 | public static void main(String[] args) { 45 | int value[] = { 5, 1, 3, 4, 2, 7 }; 46 | Node root = null; 47 | 48 | for (int i = 0; i < value.length; i++) { 49 | root = buildBST(root, value[i]); 50 | } 51 | 52 | printTree(root); 53 | } 54 | } 55 | 56 | /* 57 | * 1 2 3 4 5 7 58 | */ 59 | -------------------------------------------------------------------------------- /BinaryTrees/InorderTraversal.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @ Inorder Traversal 3 | * (i) Left Subtree 4 | * (ii) Root 5 | * (iii) Right Subtree 6 | */ 7 | 8 | public class InorderTraversal { 9 | 10 | static class Node { 11 | int data; 12 | Node left; 13 | Node right; 14 | 15 | Node(int data) { 16 | this.data = data; 17 | this.left = null; 18 | this.right = null; 19 | } 20 | } 21 | 22 | static class BinaryTree { 23 | static int idx = -1; 24 | 25 | public Node buildBinaryTree(int nodes[]) { 26 | idx++; 27 | if (nodes[idx] == -1) { 28 | return null; 29 | } 30 | Node newNode = new Node(nodes[idx]); 31 | newNode.left = buildBinaryTree(nodes); 32 | newNode.right = buildBinaryTree(nodes); 33 | return newNode; 34 | } 35 | 36 | public void inorderTraversal(Node root) { 37 | if (root == null) { 38 | return; 39 | } 40 | inorderTraversal(root.left); 41 | System.out.print(root.data + " "); 42 | inorderTraversal(root.right); 43 | } 44 | } 45 | 46 | public static void main(String[] args) { 47 | int nodes[] = { 1, 2, 4, -1, -1, 5, -1, -1, 3, -1, 6, -1, -1 }; 48 | BinaryTree tree = new BinaryTree(); 49 | Node root = tree.buildBinaryTree(nodes); 50 | tree.inorderTraversal(root); 51 | } 52 | } 53 | /* 54 | * Output: 55 | * 4 2 5 1 3 6 56 | */ -------------------------------------------------------------------------------- /Stacks/StackUsingLinkedList.java: -------------------------------------------------------------------------------- 1 | 2 | public class StackUsingLinkedList { 3 | 4 | static class Node { 5 | int data; 6 | Node next; 7 | 8 | Node(int data) { 9 | this.data = data; 10 | this.next = null; 11 | } 12 | } 13 | 14 | public static class Stack { 15 | static Node head = null; 16 | 17 | public boolean isEmpty() { 18 | return head == null; 19 | } 20 | 21 | // push 22 | public void push(int data) { 23 | Node nextNode = new Node(data); 24 | if (isEmpty()) { 25 | head = nextNode; 26 | return; 27 | } 28 | nextNode.next = head; 29 | head = nextNode; 30 | } 31 | 32 | // pop 33 | public int pop() { 34 | if (isEmpty()) { 35 | return -1; 36 | } 37 | int top = head.data; 38 | head = head.next; 39 | return top; 40 | } 41 | 42 | // peek 43 | public int peek() { 44 | if (isEmpty()) { 45 | return -1; 46 | } 47 | return head.data; 48 | } 49 | } 50 | 51 | public static void main(String[] args) { 52 | Stack s = new Stack(); 53 | s.push(1); 54 | s.push(2); 55 | s.push(3); 56 | s.push(4); 57 | while (!s.isEmpty()) { 58 | System.out.println(s.peek()); 59 | s.pop(); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Graphs/CreateGraph_adjacencyList.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Create a graph (Adjacency List) 3 | */ 4 | 5 | import java.util.ArrayList; 6 | 7 | public class CreateGraph_adjacencyList { 8 | static class Edge { 9 | int src; 10 | int dest; 11 | int wt; 12 | 13 | public Edge(int s, int d, int w) { 14 | this.src = s; 15 | this.dest = d; 16 | this.wt = w; 17 | } 18 | } 19 | 20 | public static void main(String[] args) { 21 | int v = 5; 22 | ArrayList[] graph = new ArrayList[v]; 23 | 24 | for (int i = 0; i < v; i++) { 25 | graph[i] = new ArrayList<>(); 26 | } 27 | 28 | // 0 vertex 29 | graph[0].add(new Edge(0, 1, 5)); 30 | 31 | // 1 vertex 32 | graph[1].add(new Edge(1, 0, 5)); 33 | graph[1].add(new Edge(1, 2, 1)); 34 | graph[1].add(new Edge(1, 3, 3)); 35 | 36 | // 2 vertex 37 | graph[2].add(new Edge(2, 1, 1)); 38 | graph[2].add(new Edge(2, 3, 1)); 39 | graph[2].add(new Edge(2, 4, 2)); 40 | 41 | // 3 vertex 42 | graph[3].add(new Edge(3, 2, 1)); 43 | graph[3].add(new Edge(3, 1, 3)); 44 | 45 | // 4 vertex 46 | graph[4].add(new Edge(4, 2, 2)); 47 | 48 | // 2's neighbors 49 | for (int i = 0; i < graph[2].size(); i++) { 50 | Edge e = graph[2].get(i); 51 | System.out.println(e.dest); // O(k) 52 | } 53 | } 54 | } 55 | 56 | /* 57 | * Output: 58 | * 1 59 | * 3 60 | * 4 61 | */ -------------------------------------------------------------------------------- /GreedyAlgorithms/ActivitySelection.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @Activity Selection 3 | * 4 | * You are given n activities with their start and end times. Select the maximum 5 | * number of activities that can be performed by a single person, assuming that 6 | * a 7 | * person can only work on a single activity at a time. Activities are sorted 8 | * according to end time. 9 | * 10 | * start = {10, 12, 20} 11 | * end = {20, 25, 30} 12 | * 13 | * ans = 2 (A0 & A2) 14 | */ 15 | 16 | import java.util.*; 17 | 18 | public class ActivitySelection { 19 | public static void main(String[] args) { 20 | int start[] = { 1, 3, 0, 5, 8, 5 }; 21 | int end[] = { 2, 4, 6, 7, 9, 9 }; 22 | 23 | // end time basis sorted 24 | int maxAct = 0; 25 | ArrayList ans = new ArrayList<>(); 26 | 27 | // 1st activity 28 | maxAct = 1; 29 | ans.add(0); 30 | int lastEnd = end[0]; 31 | for (int i = 1; i < end.length; i++) { 32 | if (start[i] >= lastEnd) { 33 | // activity select 34 | maxAct++; 35 | ans.add(i); 36 | lastEnd = end[i]; 37 | } 38 | } 39 | System.out.println("max activities = " + maxAct); 40 | for (int i = 0; i < ans.size(); i++) { 41 | System.out.println(start[ans.get(i)] + "-" + end[ans.get(i)]); 42 | } 43 | System.out.println(); 44 | } 45 | 46 | } 47 | 48 | /* 49 | * Output: 50 | * max activities = 4 51 | * 1-2 52 | * 3-4 53 | * 5-7 54 | * 8-9 55 | */ -------------------------------------------------------------------------------- /BinaryTrees/PostorderTraversal.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @ Postorder Traversal 3 | * (i) Left Subtree 4 | * (ii) Right Subtree 5 | * (iii) Root 6 | */ 7 | 8 | public class PostorderTraversal { 9 | 10 | static class Node { 11 | int data; 12 | Node left; 13 | Node right; 14 | 15 | Node(int data) { 16 | this.data = data; 17 | this.left = null; 18 | this.right = null; 19 | } 20 | } 21 | 22 | static class BinaryTree { 23 | static int idx = -1; 24 | 25 | public Node buildBinaryTree(int nodes[]) { 26 | idx++; 27 | if (nodes[idx] == -1) { 28 | return null; 29 | } 30 | Node newNode = new Node(nodes[idx]); 31 | newNode.left = buildBinaryTree(nodes); 32 | newNode.right = buildBinaryTree(nodes); 33 | return newNode; 34 | } 35 | 36 | public void postorderTraversal(Node root) { 37 | if (root == null) { 38 | return; 39 | } 40 | postorderTraversal(root.left); 41 | postorderTraversal(root.right); 42 | System.out.print(root.data + " "); 43 | } 44 | } 45 | 46 | public static void main(String[] args) { 47 | int nodes[] = { 1, 2, 4, -1, -1, 5, -1, -1, 3, -1, 6, -1, -1 }; 48 | BinaryTree tree = new BinaryTree(); 49 | Node root = tree.buildBinaryTree(nodes); 50 | tree.postorderTraversal(root); 51 | } 52 | } 53 | /* 54 | * Output: 55 | * 4 5 2 6 3 1 56 | */ -------------------------------------------------------------------------------- /Heaps/HeapSort.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Heap Sort 3 | */ 4 | 5 | public class HeapSort { 6 | 7 | public static void heapSort(int arr[]) { 8 | // step1: build maxHeap 9 | int n = arr.length; 10 | for (int i = n / 2; i >= 0; i--) { 11 | heapify(arr, i, n); 12 | } 13 | 14 | // step2: push largest at end 15 | for (int i = n - 1; i > 0; i--) { 16 | // swap (largest-first with last) 17 | int temp = arr[0]; 18 | arr[0] = arr[i]; 19 | arr[i] = temp; 20 | heapify(arr, 0, i); 21 | } 22 | } 23 | 24 | public static void heapify(int arr[], int i, int size) { 25 | int left = 2 * i + 1; 26 | int right = 2 * i + 2; 27 | int maxIdx = i; 28 | 29 | if (left < size && arr[left] > arr[maxIdx]) { 30 | maxIdx = left; 31 | } 32 | 33 | if (right < size && arr[right] > arr[maxIdx]) { 34 | maxIdx = right; 35 | } 36 | 37 | if (maxIdx != i) { 38 | // swap 39 | int temp = arr[i]; 40 | arr[i] = arr[maxIdx]; 41 | arr[maxIdx] = temp; 42 | heapify(arr, maxIdx, size); 43 | } 44 | } 45 | 46 | public static void main(String[] args) { 47 | int arr[] = { 8, 7, 65, 5, 4, 3, 2 }; 48 | heapSort(arr); 49 | 50 | for (int i = 0; i < arr.length; i++) { 51 | System.out.print(arr[i] + " "); 52 | } 53 | } 54 | } 55 | 56 | /* 57 | * Output: 58 | * 2 3 4 5 7 8 65 59 | */ -------------------------------------------------------------------------------- /Arrays/LinearSearch.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Linear Search 3 | * -> Find the index of element in a given array. 4 | */ 5 | 6 | import java.util.*; 7 | 8 | import javax.lang.model.element.Element; 9 | 10 | public class LinearSearch { 11 | 12 | public static int arraySearch(int array[], int key) { 13 | for (int i = 0; i < array.length; i++) { 14 | if (array[i] == key) { 15 | return i; 16 | } 17 | } 18 | return -1; 19 | } 20 | 21 | public static void main(String[] args) { 22 | 23 | Scanner sc = new Scanner(System.in); 24 | 25 | System.out.print("How many elements do you want to enter in the array: "); 26 | int n = sc.nextInt(); 27 | int arr[] = new int[n]; 28 | System.out.print("Enter the " + n + "th elements: "); 29 | for (int i = 0; i < n; i++) { 30 | arr[i] = sc.nextInt(); 31 | } 32 | System.out.print("Enter the element you want to search: "); 33 | int key = sc.nextInt(); 34 | int index = arraySearch(arr, key); 35 | 36 | if (index == -1) { 37 | System.out.println("Element " + key + " is not found!"); 38 | } else { 39 | System.out.println("Element " + key + " is index " + index); 40 | } 41 | } 42 | } 43 | 44 | /* 45 | * Output: 46 | * How many elements do you want to enter in the array: 15 47 | * Enter the 15th elements: 2 7 4 2 7 9 12 1 514 21 16 8 9 15 6 48 | * Enter the element you want to search: 8 49 | * Element 8 is index 11 50 | */ -------------------------------------------------------------------------------- /Patterns/diamondPattern.java: -------------------------------------------------------------------------------- 1 | /* 2 | * DIAMOND pattern 3 | * 4 | * * 5 | * *** 6 | * ***** 7 | * ******* 8 | * ******* 9 | * ***** 10 | * *** 11 | * * 12 | */ 13 | 14 | 15 | public class diamondPattern { 16 | public static void main(String[] args) { 17 | short n = 4; 18 | for (short i = 1; i <= n; i++) { 19 | for (short j = 1; j <= n - i; j++) { 20 | System.out.print(" "); 21 | } 22 | for (short j = 1; j <= i; j++) { 23 | System.out.print("*"); 24 | } 25 | for (short j = 1; j <= i - 1; j++) { 26 | System.out.print("*"); 27 | } 28 | System.out.println(); 29 | } 30 | for (short i = n; i >= 1; i--) { 31 | 32 | for (short j = 1; j <= n - i; j++) { 33 | System.out.print(" "); 34 | } 35 | for (short j = 1; j <= i; j++) { 36 | System.out.print("*"); 37 | } 38 | for (short j = 1; j <= i - 1; j++) { 39 | System.out.print("*"); 40 | } 41 | System.out.println(); 42 | } 43 | } 44 | } 45 | 46 | 47 | /* 48 | Output: 49 | 50 | * 51 | *** 52 | ***** 53 | ******* 54 | ******* 55 | ***** 56 | *** 57 | * 58 | 59 | */ -------------------------------------------------------------------------------- /GreedyAlgorithms/FractionalKnapsack.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @Fractional Knapsack 3 | * -> Given the weights and value of N items, put these irems in a 4 | * knapsack of capacity W to get the maximum total value in the 5 | * knapsack. 6 | * value = {60, 100, 120} 7 | * weight = {10, 20, 30} 8 | * ans = 240; 9 | * W = 50 10 | */ 11 | 12 | import java.util.*; 13 | 14 | public class FractionalKnapsack { 15 | public static void main(String[] args) { 16 | int val[] = { 60, 100, 120 }; 17 | int weight[] = { 10, 20, 30 }; 18 | int W = 50; 19 | 20 | double ratio[][] = new double[val.length][2]; 21 | // 0th -> idx; 1st col -> ratio 22 | 23 | for (int i = 0; i < val.length; i++) { 24 | ratio[i][0] = i; 25 | ratio[i][1] = val[i] / (double) weight[i]; 26 | } 27 | 28 | // ascending order 29 | Arrays.sort(ratio, Comparator.comparingDouble(o -> o[1])); 30 | 31 | int capacity = W; 32 | int finalVal = 0; 33 | for (int i = val.length - 1; i >= 0; i--) { 34 | int idx = (int) ratio[i][0]; 35 | if (capacity >= weight[idx]) { 36 | finalVal += val[idx]; 37 | capacity -= weight[idx]; 38 | } else { 39 | // include fractional item 40 | finalVal += (ratio[i][1] * capacity); 41 | capacity = 0; 42 | break; 43 | } 44 | } 45 | System.out.println("Final Value: " + finalVal); 46 | } 47 | } 48 | /* 49 | * Output: 50 | * Final Value: 240 51 | */ 52 | -------------------------------------------------------------------------------- /2D-Arrays/SpiralMatrixPrint.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @ Spiral Matrix 3 | * array[][] = { {1,2,3,4}, 4 | * {5,6,7,8}, 5 | * {9,10,11,12}, 6 | * {13,14,15,16} }; 7 | * 8 | * Output: -> 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 9 | */ 10 | 11 | public class SpiralMatrixPrint { 12 | public static void spiralMatrixPrint(int matrix[][]){ 13 | int startRow =0; 14 | int startCol =0; 15 | int endRow = matrix.length-1; 16 | int endCol = matrix[0].length-1; 17 | 18 | while (startRow=startCol ; i--) { 29 | System.out.print(matrix[i][endRow]+ " "); 30 | } 31 | //left 32 | for (int i = startCol; i >=startRow ; i--) { 33 | System.out.print(matrix[i][startCol]+" "); 34 | } 35 | 36 | startRow++; 37 | startCol++; 38 | endRow--; 39 | endCol--; 40 | } 41 | } 42 | public static void main(String[] args){ 43 | int matrix[][]= { {1,2,3,4}, 44 | {5,6,7,8},{9,10,11,12},{13,14,15,16} }; 45 | spiralMatrixPrint(matrix); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /Tries/implement_Trie.java: -------------------------------------------------------------------------------- 1 | 2 | public class implement_Trie { 3 | 4 | public static class Node { 5 | Node children[] = new Node[26]; 6 | boolean eow; 7 | 8 | Node() { 9 | for (int i = 0; i < 26; i++) { 10 | this.children[i] = null; 11 | } 12 | this.eow = false; 13 | } 14 | } 15 | 16 | public static Node root = new Node(); 17 | 18 | public static void insert(String word) { 19 | Node curr = root; 20 | for (int level = 0; level < word.length(); level++) { 21 | int indx = word.charAt(level) - 'a'; 22 | if (curr.children[indx] == null) { 23 | curr.children[indx] = new Node(); 24 | } 25 | curr = curr.children[indx]; 26 | } 27 | curr.eow = true; 28 | } 29 | 30 | public static boolean search(String words) { 31 | Node curr = root; 32 | for (int i = 0; i < words.length(); i++) { 33 | int indx = words.charAt(i) - 'a'; 34 | if (curr.children[indx] == null) { 35 | return false; 36 | } else { 37 | curr = curr.children[indx]; 38 | } 39 | } 40 | return curr.eow == true; 41 | } 42 | 43 | public static void main(String[] args) { 44 | String words[] = { "the", "a", "there", "their", "any", "thee" }; 45 | 46 | for (int i = 0; i < words.length; i++) { 47 | insert(words[i]); 48 | } 49 | System.out.println(search("the")); 50 | System.out.println(search("an")); 51 | } 52 | } -------------------------------------------------------------------------------- /SortingAlgorithms/MergeSort.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Divide & Conquer 3 | */ 4 | 5 | public class MergeSort { 6 | 7 | public static void mergeSort(int array[], int si, int ei) { 8 | 9 | if (si >= ei) { // end me true 10 | return; 11 | } 12 | 13 | int mid = si + (ei - si) / 2; 14 | 15 | mergeSort(array, si, mid); 16 | mergeSort(array, mid + 1, ei); 17 | 18 | merge(array, si, mid, ei); 19 | } 20 | 21 | public static void merge(int array[], int si, int mid, int ei) { 22 | int temp[] = new int[ei - si + 1]; 23 | int i = si; 24 | int j = mid + 1; 25 | int k = 0; 26 | while (i <= mid && j <= ei) { 27 | if (array[i] > array[j]) { 28 | temp[k] = array[j++]; 29 | } else { 30 | temp[k] = array[i++]; 31 | } 32 | k++; 33 | } 34 | 35 | while (i <= mid) { 36 | temp[k++] = array[i++]; 37 | } 38 | 39 | while (j <= ei) { 40 | temp[k++] = array[j++]; 41 | } 42 | 43 | for (i = 0, j = si; i < temp.length; i++, j++) { 44 | array[j] = temp[i]; 45 | } 46 | } 47 | 48 | public static void main(String[] args) { 49 | int array[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1 }; 50 | 51 | mergeSort(array, 0, array.length - 1); 52 | 53 | for (int i = 0; i < array.length; i++) { 54 | System.out.print(array[i] + " "); 55 | } 56 | System.out.println(); 57 | } 58 | } 59 | 60 | /* 61 | * Output: 62 | * 1 2 3 4 5 6 7 8 9 63 | */ -------------------------------------------------------------------------------- /BinaryTrees/PreorderTraversal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Preorder Traversal 3 | * -> (i) Root 4 | * -> (ii) Left Subtree 5 | * -> (iii) Right Subtree 6 | */ 7 | public class PreorderTraversal { 8 | 9 | static class Node { 10 | int data; 11 | Node left; 12 | Node right; 13 | 14 | Node(int data) { 15 | this.data = data; 16 | this.left = null; 17 | this.right = null; 18 | } 19 | } 20 | 21 | static class BinaryTree { 22 | static int idx = -1; 23 | 24 | public Node buildBinaryTree(int nodes[]) { 25 | idx++; 26 | if (nodes[idx] == -1) { 27 | return null; 28 | } 29 | Node newNode = new Node(nodes[idx]); 30 | newNode.left = buildBinaryTree(nodes); 31 | newNode.right = buildBinaryTree(nodes); 32 | return newNode; 33 | } 34 | 35 | public void preorderTraversal(Node root) { 36 | if (root == null) { 37 | System.out.print("-1" + " "); 38 | return; 39 | } 40 | System.out.print(root.data + " "); 41 | preorderTraversal(root.left); 42 | preorderTraversal(root.right); 43 | } 44 | } 45 | 46 | public static void main(String[] args) { 47 | int nodes[] = { 1, 2, 4, -1, -1, 5, -1, -1, 3, -1, 6, -1, -1 }; 48 | BinaryTree tree = new BinaryTree(); 49 | Node root = tree.buildBinaryTree(nodes); 50 | tree.preorderTraversal(root); 51 | } 52 | } 53 | /* 54 | * Output: 55 | * 1 2 4 -1 -1 5 -1 -1 3 -1 6 -1 -1 56 | */ -------------------------------------------------------------------------------- /Queues/QueueUsingTwoStacks.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Create queue using two stacks 3 | */ 4 | 5 | import java.util.Stack; 6 | 7 | import javax.xml.crypto.Data; 8 | 9 | public class QueueUsingTwoStacks { 10 | 11 | static class Queue { 12 | Stack s1 = new Stack<>(); 13 | Stack s2 = new Stack<>(); 14 | 15 | public boolean isEmpty() { 16 | return s1.isEmpty(); 17 | } 18 | 19 | // add 20 | public void add(int data) { 21 | while (!s1.isEmpty()) { 22 | s2.push(s1.pop()); 23 | } 24 | 25 | s1.push(data); 26 | 27 | while (!s2.isEmpty()) { 28 | s1.push(s2.pop()); 29 | } 30 | } 31 | 32 | // remove 33 | public int remove() { 34 | if (isEmpty()) { 35 | System.out.println("Queue is Empty"); 36 | return -1; 37 | } 38 | return s1.pop(); 39 | } 40 | 41 | // peek 42 | public int peek() { 43 | if (isEmpty()) { 44 | System.out.println("Queue is Empty"); 45 | return -1; 46 | } 47 | return s1.peek(); 48 | } 49 | 50 | } 51 | 52 | public static void main(String[] args) { 53 | Queue q = new Queue(); 54 | q.add(1); 55 | q.add(2); 56 | q.add(3); 57 | q.add(4); 58 | while (!q.isEmpty()) { 59 | System.out.println(q.peek()); 60 | q.remove(); 61 | } 62 | } 63 | } 64 | 65 | /* 66 | * Output: 67 | * 1 68 | * 2 69 | * 3 70 | * 4 71 | */ -------------------------------------------------------------------------------- /Stacks/ValidParenthesesCode.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', 3 | * determine if the input string is valid. 4 | * @An input string is valid if: 5 | * (i) -> Open brackets must be closed by the same type of brackets. 6 | * (ii) -> Open brackets must be closed in the corrent order. 7 | * (iii) -> Every close bracket has a corresponding open bracket of the same type. 8 | * 9 | * Ex => (i). ({[]}()) -> true 10 | * (ii). {([]}{} -> false 11 | */ 12 | 13 | import java.util.Stack; 14 | 15 | public class ValidParenthesesCode { 16 | 17 | public static boolean isValid(String str) { 18 | Stack s = new Stack<>(); 19 | for (int i = 0; i < str.length(); i++) { 20 | char c = str.charAt(i); 21 | if (c == '(' || c == '{' || c == '[') { 22 | s.push(c); 23 | } else { 24 | if (s.isEmpty()) { 25 | return false; 26 | } 27 | if (s.peek() == '(' && c == ')' || 28 | s.peek() == '{' && c == '}' || 29 | s.peek() == '[' && c == ']') { 30 | s.pop(); 31 | } else { 32 | return false; 33 | } 34 | } 35 | } 36 | if (s.isEmpty()) { 37 | return true; 38 | } else { 39 | return false; 40 | } 41 | } 42 | 43 | public static void main(String[] args) { 44 | String str = "({[]}())"; // true 45 | System.out.println(isValid(str)); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Hashing/ValidAnagram.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Given two strings s and t, return true if t is an anagram of s, and 3 | * false otherwise. An Anagram is a word or phrase formed by rearranging 4 | * the letters of a different word or phrase, typically using all the 5 | * original letters exactly once. 6 | * 7 | * s="race" t="care" -> True 8 | * s="heart" t="earth" -> True 9 | * s="tulip" t="lipid" -> False 10 | */ 11 | 12 | import java.util.*; 13 | 14 | public class ValidAnagram { 15 | 16 | public static boolean isAnagram(String s, String t) { 17 | HashMap hm = new HashMap<>(); 18 | for (int i = 0; i < s.length(); i++) { 19 | char ch = s.charAt(i); 20 | hm.put(ch, hm.getOrDefault(ch, 0) + 1); 21 | } 22 | 23 | for (int i = 0; i < t.length(); i++) { 24 | char ch = t.charAt(i); 25 | if (hm.get(ch) != null) { 26 | if (hm.get(ch) == 1) { 27 | hm.remove(ch); 28 | } else { 29 | hm.put(ch, hm.get(ch) - 1); 30 | } 31 | } else { 32 | return false; 33 | } 34 | } 35 | return hm.isEmpty(); 36 | } 37 | 38 | public static void main(String[] args) { 39 | String s = "knee"; 40 | String t = "keen"; 41 | 42 | System.out.println(isAnagram(s, t)); 43 | System.out.println(isAnagram("race", "care")); 44 | System.out.println(isAnagram("heart", "earth")); 45 | System.out.println(isAnagram("tulip", "lipid")); 46 | 47 | } 48 | } 49 | 50 | /* 51 | * Output: 52 | * true 53 | * true 54 | * true 55 | * false 56 | */ -------------------------------------------------------------------------------- /Arrays/TrappingRainwaterVVI.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Trapping Rainwater 3 | * 4 | * [Problem] -> Given n non-negative integers representing an elevation map where 5 | * the width of each bar is 1, compute how much water it can trap after raining. 6 | * height=[4,2,0,6,3,2,5] 7 | * 8 | */ 9 | 10 | 11 | public class TrappingRainwaterVVI { 12 | 13 | public static int trappedRainwater(int height[]) { 14 | 15 | int n=height.length; 16 | // calculate left max boundary - array 17 | int leftMax[]=new int[n]; 18 | leftMax[0]=height[0]; 19 | for(int i=1; i=0; i--){ 27 | rightMax[i]=Math.max(height[i], rightMax[i+1]); 28 | } 29 | 30 | // loop 31 | int trappedWater=0; 32 | for(int i=0; i maximum of all subarrays of size k 5 | * 1,2,3,4,5,6,7,8,9,10 6 | * k=3 7 | */ 8 | import java.util.Comparator; 9 | import java.util.PriorityQueue; 10 | import java.util.ArrayList; 11 | 12 | public class SlidingWindowMaximum { 13 | 14 | static class pair implements Comparable { 15 | int value; 16 | int indx; 17 | 18 | pair(int value, int indx) { 19 | this.value = value; 20 | this.indx = indx; 21 | } 22 | 23 | @Override 24 | public int compareTo(pair win) { 25 | return this.value - win.value; 26 | } 27 | } 28 | 29 | public static void main(String[] args) { 30 | 31 | PriorityQueue pq = new PriorityQueue<>(Comparator.reverseOrder()); 32 | ArrayList ll = new ArrayList<>(); 33 | 34 | int arr[] = { 1, 3, -1, -3, 5, 3, 6, 7 }; 35 | int k = 3; 36 | int result[] = new int[arr.length - k + 1]; 37 | 38 | // first window 39 | for (int i = 0; i < k; i++) { 40 | pq.add(new pair(arr[i], i)); 41 | } 42 | result[0] = pq.peek().value; 43 | for (int i = k; i < arr.length; i++) { 44 | while (pq.size() > 0 && pq.peek().indx <= (i - k)) { 45 | pq.remove(); 46 | } 47 | pq.add(new pair(arr[i], i)); 48 | result[i - k + 1] = pq.remove().value; 49 | } 50 | 51 | // Print result 52 | for (int i = 0; i < result.length; i++) { 53 | System.out.print(result[i] + " "); 54 | } 55 | } 56 | 57 | } 58 | 59 | /* 60 | * Output: 61 | * 3 3 5 3 6 7 62 | */ -------------------------------------------------------------------------------- /Stacks/DuplicateParenthesesCode.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @Duplicate Parentheses 3 | * Givee a balanced expression, find if contains duplicate parentheses or not. A set of 4 | * parentheses are duplicate if the same subexpression is surrounded by multiple parentheses. 5 | * 6 | * -> Return a true if it contains duplicates else return false. 7 | * 8 | * example: 9 | * (i) -> (((a+(b)))+(c+d)) => true 10 | * (ii) -> ((((a)+(b))+c+d)) => true 11 | * (iii)-> ((a+b)+(c+d)) => false 12 | * (iv) -> (((a+b))+c) => true 13 | */ 14 | 15 | import java.util.Stack;; 16 | 17 | public class DuplicateParenthesesCode { 18 | 19 | public static boolean isDuplicate(String str) { 20 | Stack s = new Stack<>(); 21 | for (int i = 0; i < str.length(); i++) { 22 | char ch = str.charAt(i); 23 | 24 | // closing 25 | if (ch == ')') { 26 | int count = 0; 27 | while (s.peek() != '(') { 28 | s.pop(); 29 | count++; 30 | } 31 | if (count < 1) { 32 | return true; // duplicate 33 | } else { 34 | s.pop(); // opening pair 35 | } 36 | } else { 37 | // opening 38 | s.push(ch); 39 | } 40 | } 41 | return false; 42 | } 43 | 44 | public static void main(String[] args) { 45 | String str1 = "(((a+(b)))+(c+d))"; 46 | System.out.println(isDuplicate(str1)); // false 47 | String str2 = "((a+b)+(c+d))"; 48 | System.out.println(isDuplicate(str2)); // true 49 | 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /BinaryTrees/DiameterOfTree_Approach1.java: -------------------------------------------------------------------------------- 1 | public class DiameterOfTree_Approach1 { 2 | static class Node { 3 | int data; 4 | Node left; 5 | Node right; 6 | 7 | Node(int data) { 8 | this.data = data; 9 | this.left = null; 10 | this.right = null; 11 | } 12 | } 13 | 14 | public static int height(Node root) { 15 | if (root == null) { 16 | return 0; 17 | } 18 | int lh = height(root.left); 19 | int rh = height(root.right); 20 | return Math.max(lh, rh) + 1; 21 | } 22 | 23 | public static int diameter(Node root) { // O(n^2) 24 | if (root == null) { 25 | return 0; 26 | } 27 | 28 | int leftDiam = diameter(root.left); 29 | int leftHt = height(root.left); 30 | int rightDiam = diameter(root.right); 31 | int rightHt = height(root.right); 32 | int selfDiam = leftHt + rightHt + 1; 33 | return Math.max(selfDiam, Math.max(leftDiam, rightDiam)) + 1; 34 | } 35 | 36 | public static void main(String[] args) { 37 | 38 | Node root = new Node(1); 39 | root.left = new Node(2); 40 | root.right = new Node(3); 41 | root.left.left = new Node(4); 42 | root.left.right = new Node(5); 43 | root.right.left = new Node(6); 44 | root.right.right = new Node(7); 45 | 46 | System.out.println("Max diameter of tree : " + diameter(root)); // Max diameter of tree :5 47 | 48 | root.right.right.right = new Node(9); 49 | root.right.right.right.right = new Node(10); 50 | 51 | System.out.println("Max diameter of tree : " + diameter(root)); // Max diameter of tree : 7 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Recursion/SearchInRotatedSortedArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Search in Rotated Sorted Array 3 | * 4 | * input-> sorted, rotated array with distinct number (in ascending order) it is rotated at a pivot point. 5 | * Find the index of given element. 6 | */ 7 | 8 | public class SearchInRotatedSortedArray { 9 | 10 | public static int searchArray(int arr[] , int tar , int si , int ei) { 11 | if (si>ei) { 12 | return -1; 13 | } 14 | // kaam 15 | int mid = si+(ei-si)/2; 16 | // case found 17 | if (arr[mid]==tar) { 18 | return mid; 19 | } 20 | // mid on L1 21 | if(arr[si]<=arr[mid]){ 22 | //case a: L1 left 23 | if(arr[si]<=tar&&tar<=arr[mid]){ 24 | return searchArray(arr,tar,si,mid-1); 25 | }else{ 26 | // case b: right 27 | return searchArray(arr,tar,mid+1,ei); 28 | } 29 | } 30 | // mid on L2 31 | else{ 32 | // case c: right 33 | if(arr[mid]<=tar&&tar<=arr[ei]){ 34 | return searchArray(arr,tar,mid+1,ei); 35 | } 36 | //case d: left 37 | else{ 38 | return searchArray(arr,tar,si,mid-1); 39 | } 40 | } 41 | } 42 | 43 | public static void main(String[] args) { 44 | int arr[]={4,5,6,7,0,1,2}; 45 | int tar=1; 46 | int index=searchArray(arr,tar,0,arr.length-1); 47 | if (index==-1) { 48 | System.out.println("index is not found!"); 49 | }else{ 50 | System.out.println("index no: " + index); 51 | } 52 | } 53 | } 54 | 55 | /* 56 | * Output: 57 | * index no: 5 58 | */ -------------------------------------------------------------------------------- /Queues/QueuesUsingArrays.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Queues Using Arrays 3 | */ 4 | 5 | public class QueuesUsingArrays { 6 | 7 | static class Queue { 8 | static int arr[]; 9 | static int size; 10 | static int rear; 11 | 12 | Queue(int n) { 13 | arr = new int[n]; 14 | size = n; 15 | rear = -1; 16 | } 17 | 18 | public boolean isEmpty() { 19 | return rear == -1; 20 | } 21 | 22 | // add 23 | public void add(int data) { 24 | if (rear == size - 1) { 25 | System.out.println("queue is full"); 26 | return; 27 | } 28 | rear = rear + 1; 29 | arr[rear] = data; 30 | } 31 | 32 | // remove 33 | public int remove() { 34 | if (isEmpty()) { 35 | System.out.println("empty queue"); 36 | return -1; 37 | } 38 | 39 | int front = arr[0]; 40 | for (int i = 0; i < rear; i++) { 41 | arr[i] = arr[i + 1]; 42 | } 43 | rear = rear - 1; 44 | return front; 45 | } 46 | 47 | // peek 48 | public int peek() { 49 | if (isEmpty()) { 50 | System.out.println("empty queue"); 51 | return -1; 52 | } 53 | return arr[0]; 54 | } 55 | 56 | } 57 | 58 | public static void main(String[] args) { 59 | Queue q = new Queue(5); 60 | 61 | q.add(1); 62 | q.add(2); 63 | q.add(3); 64 | q.add(4); 65 | while (!q.isEmpty()) { 66 | System.out.println(q.peek()); 67 | q.remove(); 68 | } 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /Recursion/MergeSort.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Merge Sort 3 | * 4 | * idea(?)-> Divide & Conquer(Ha.. Ha..haaa)! 5 | */ 6 | 7 | public class MergeSort { 8 | 9 | public static void mergeSort(int arr[] , int si, int ei) { 10 | if (si >= ei) { 11 | return; 12 | } 13 | // kaam 14 | int mid = si + (ei - si)/2; // (si+ei)/2 15 | mergeSort(arr, si, mid); // left part 16 | mergeSort(arr, mid+1, ei); // right part 17 | 18 | merge( arr, si, mid, ei); 19 | } 20 | 21 | public static void merge(int arr[], int si , int mid , int ei) { 22 | int temp[]=new int[ei-si+1]; 23 | int i=si; // iterator for left part 24 | int j=mid+1; // iterator for right part 25 | int k=0; // iterator for temp arr 26 | 27 | while(i<=mid && j<= ei){ 28 | if (arr[i] a continuous part of array 6 | * 7 | * Ex-> Array= {2,4,6,8,10}; 8 | * 9 | * --> { 2 } { 2 4 } { 2 4 6 } { 2 4 6 8 } { 2 4 6 8 10 } 10 | * { 4 } { 4 6 } { 4 6 8 } { 4 6 8 10 } 11 | * { 6 } { 6 8 } { 6 8 10 } 12 | * { 8 } { 8 10 } 13 | * { 10 } 14 | * 15 | */ 16 | 17 | public class PrintSubarrays { 18 | 19 | public static void printSubarrays(int array[]) { 20 | int smallest =Integer.MAX_VALUE , largest=Integer.MIN_VALUE; 21 | for (int i = 0; i < array.length; i++) { 22 | for (int j = i; j < array.length; j++) { 23 | int sum=0; 24 | System.out.print("{ "); 25 | for (int k = i; k <= j; k++) { 26 | System.out.print(array[k] + " "); 27 | sum+=array[k]; 28 | } 29 | largest=Math.max(sum,largest); 30 | smallest=Math.min(sum,smallest); 31 | System.out.print("} "); 32 | } 33 | System.out.println(); 34 | } 35 | System.out.println("Smallest sum of Subarray: " + smallest); 36 | System.out.println("Largest sum of Subarray: " + largest); 37 | } 38 | 39 | public static void main(String[] args) { 40 | int array[] = { 2, 4, 6, 8, 10 }; 41 | printSubarrays(array); 42 | } 43 | } 44 | 45 | 46 | /* 47 | * 48 | * Output: 49 | * { 2 } { 2 4 } { 2 4 6 } { 2 4 6 8 } { 2 4 6 8 10 } 50 | * { 4 } { 4 6 } { 4 6 8 } { 4 6 8 10 } 51 | * { 6 } { 6 8 } { 6 8 10 } 52 | * { 8 } { 8 10 } 53 | * { 10 } 54 | * Smallest sum of Subarray: 2 55 | * Largest sum of Subarray: 30 56 | * 57 | */ -------------------------------------------------------------------------------- /BinarySearchTree/MirrorBST.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Mirror BST 3 | */ 4 | 5 | public class MirrorBST { 6 | 7 | public static class Node { 8 | int data; 9 | Node left; 10 | Node right; 11 | 12 | Node(int data) { 13 | this.data = data; 14 | this.left = null; 15 | this.right = null; 16 | } 17 | } 18 | 19 | public static Node buildBST(Node root, int data) { 20 | if (root == null) { 21 | root = new Node(data); 22 | return root; 23 | } 24 | if (root.data > data) { 25 | root.left = buildBST(root.left, data); 26 | } else if (root.data < data) { 27 | root.right = buildBST(root.right, data); 28 | } 29 | return root; 30 | } 31 | 32 | public static void inOrder(Node root) { 33 | if (root == null) { 34 | return; 35 | } 36 | inOrder(root.left); 37 | System.out.print(root.data + " "); 38 | inOrder(root.right); 39 | } 40 | 41 | public static Node mirrorBST(Node root) { 42 | if (root == null) { 43 | return root; 44 | } 45 | Node lefts = mirrorBST(root.left); 46 | Node rights = mirrorBST(root.right); 47 | root.left = rights; 48 | root.right = lefts; 49 | return root; 50 | } 51 | 52 | public static void main(String[] args) { 53 | int arr[] = { 8, 5, 10, 3, 6, 11 }; 54 | Node root = null; 55 | for (int i = 0; i < arr.length; i++) { 56 | root = buildBST(root, arr[i]); 57 | } 58 | inOrder(root); 59 | root = mirrorBST(root); 60 | System.out.println(); 61 | inOrder(root); 62 | } 63 | } 64 | 65 | /* 66 | * Output: 67 | * 3 5 6 8 10 11 68 | * 11 10 8 6 5 3 69 | */ -------------------------------------------------------------------------------- /BinaryTrees/DiameterOfTree_Approach2.java: -------------------------------------------------------------------------------- 1 | public class DiameterOfTree_Approach2 { 2 | static class Node { 3 | int data; 4 | Node left; 5 | Node right; 6 | 7 | Node(int data) { 8 | this.data = data; 9 | this.left = null; 10 | this.right = null; 11 | } 12 | } 13 | 14 | static class Info { 15 | int diam; 16 | int ht; 17 | 18 | Info(int dimt, int ht) { 19 | this.diam = dimt; 20 | this.ht = ht; 21 | } 22 | } 23 | 24 | public static Info diameter(Node root) { 25 | if (root == null) { 26 | return new Info(0, 0); 27 | } 28 | Info leftInfo = diameter(root.left); 29 | Info rightInfo = diameter(root.right); 30 | 31 | int diam = Math.max(Math.max(leftInfo.diam, rightInfo.diam), leftInfo.ht + rightInfo.ht + 1); 32 | int ht = Math.max(leftInfo.ht, rightInfo.ht) + 1; 33 | return new Info(diam, ht); 34 | } 35 | 36 | public static void main(String[] args) { 37 | 38 | Node root = new Node(1); 39 | root.left = new Node(2); 40 | root.right = new Node(3); 41 | root.left.left = new Node(4); 42 | root.left.right = new Node(5); 43 | root.right.left = new Node(6); 44 | root.right.right = new Node(7); 45 | 46 | System.out.println("Max diameter of tree : " + diameter(root).diam); // Max diameter of tree :5 47 | // 48 | 49 | root.right.right.right = new Node(9); 50 | root.right.right.right.right = new Node(10); 51 | 52 | System.out.println("Max diameter of tree : " + diameter(root).diam); // Max diameter of tree : 7 53 | System.out.println("Max height of tree : " + diameter(root).ht); // Max height of tree : 5 54 | } 55 | } 56 | --------------------------------------------------------------------------------